def __init__(self, kind, parent=None):
        super(AuxiliaryRecordModule, self).__init__(parent)
        self.setupUi(self)
        if kind == 0:
            index = '12'
        elif kind == 1:
            index = '25'
        elif kind == 2:
            index = '32'
        else:
            index = '-1'
        if index not in user.powers:
            self.close()
        if user.powers[index] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers[index])

        if self.power[1] == '0':
            self.pushButton_accept.setEnabled(False)
            self.pushButton_cancel.setEnabled(False)
        self.kind = kind
        self.year = user.NIAN
        self.month = user.YUE
        self.docid = 0
        self.current_content = QWidget()
        self.AC = AuxiliaryRecordController()
        self.SC = SelfdefinedformatController()
        self.treeWidget_itemlist.hideColumn(0)
        self.treeWidget_itemlist.hideColumn(4)
        self.get_year_list()
示例#2
0
    def __init__(self, autoid=None, parent=None):
        super(EditSelfDefineFormatDetailModule, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlag(Qt.WindowMinMaxButtonsHint)
        if '3' not in user.powers:
            self.close()
        if user.powers['3'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['3'])
        if self.power[1] == '0':
            self.pushButton_accept.setEnabled(False)
            self.pushButton_close.setEnabled(False)

        self.autoid = autoid
        self.detail = QWidget()
        self.dom = QDomDocument()
        self.current_widget = QWidget()
        self.nodelist = None
        self.SC = SelfdefinedformatController()
        self.ori_detail = {}
        self.new_detail = {}
        self.format_content = '<?xml version="1.0"?><GMPPaper />'
        self.current_content = XMLReadWrite()
        self.current_elemnt = None
        res = self.get_detail()
        self.set_kind()
        self.set_subkind()
        if res:
            self.set_formtype()
        self.set_widgetlist()
        self.set_format()
        for i in range(0, 17):
            getattr(self, 'checkBox_' + str(2**i)).toggled.connect(
                self.on_formattype_toggled)
 def __init__(self, autoid=None, vdpid=0, parent=None):
     super(VerificationDetailModule, self).__init__(parent)
     self.setupUi(self)
     self.autoid = autoid
     self.vdpid = vdpid
     self.filename = None
     self.doc = None
     self.reportid = 0
     self.current_content = QWidget()
     self.current_img = object
     self.current_page = object
     self.label_image.setScaledContents(True)
     self.status = 0
     self.current_docid = 0
     self.ori_detail = {}
     self.new_detail = {}
     self.VC = VerificationController()
     self.SC = SelfdefinedformatController()
     self.lineEdit_product.setup(DB_TABLE_TUPLE[0], RETURN_ROW[0],
                                 CONDITION_KEY[0], TREEHEADER_NAME, None,
                                 330, 200)
     self.treeWidget_report.hideColumn(0)
     self.treeWidget_labreport.hideColumn(0)
     self.treeWidget_labreport.hideColumn(1)
     self.treeWidget_pp_record.hideColumn(0)
     self.treeWidget_pp_record.hideColumn(1)
     self.label_other.setVisible(False)
     self.lineEdit_other.setVisible(False)
     self.get_plan()
     self.show_plandoc()
     self.get_report()
     self.get_producingplan_records()
     self.get_lab_records()
 def __init__(self, parent=None):
     super(SelectGeneralRecordsModule, self).__init__(parent)
     self.detail = []
     self.SC = SelfdefinedformatController()
     self.setupUi(self)
     self.treeWidget_filelist.hideColumn(1)
     # 或取设备一般记录
     self.get_generalrecords()
示例#5
0
 def __init__(self, parent=None):
     super(SelfDefineFormatListModule, self).__init__(parent)
     self.setupUi(self)
     if '4' not in user.powers:
         self.close()
     if user.powers['4'] == 0:
         self.close()
     self.power = '{:03b}'.format(user.powers['4'])
     self.SC = SelfdefinedformatController()
     self.treeWidget_formatlist.hideColumn(1)
     self.get_format_list()
示例#6
0
class SelectSelfDefineFormatModule(QDialog, Ui_Dialog):
    selected = pyqtSignal(list)

    def __init__(self, kind, parent=None):
        super(SelectSelfDefineFormatModule, self).__init__(parent)
        self.kind = kind
        self.detail = []
        self.SC = SelfdefinedformatController()
        self.setupUi(self)
        self.treeWidget_filelist.hideColumn(1)
        # 或取记录
        self.get_generalrecords()

    def get_generalrecords(self):
        res = self.SC.get_selfdefinedformat(
            False,
            *VALUES_TUPLE_SD).extra(where=['formtype&' + str(self.kind)])
        for item in res:
            if item['subkind'] == '':
                qtreeitem = QTreeWidgetItem(self.treeWidget_filelist)
            else:
                itemlist = self.treeWidget_filelist.findItems(
                    item['subkind'], Qt.MatchContains, 0)
                if not len(itemlist):
                    qtreeitem_parent = QTreeWidgetItem(
                        self.treeWidget_filelist)
                    qtreeitem_parent.setText(0, item['subkind'])
                    qtreeitem_parent.setText(1, '0')
                    qtreeitem = QTreeWidgetItem(qtreeitem_parent)
                else:
                    qtreeitem = QTreeWidgetItem(itemlist[0])
            qtreeitem.setText(0, item['formatname'])
            qtreeitem.setText(1, str(item['autoid']))

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_filelist_itemDoubleClicked(self, qitem, p_int):
        if qitem.text(1) != '0':
            self.selected.emit([
                int(qitem.text(1)),
            ])
            self.accept()

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        items = self.treeWidget_filelist.selectedItems()
        select_list = []
        for item in items:
            if item.text(1) != '0':
                select_list.append(int(item.text(1)))
        if len(select_list):
            self.selected.emit(select_list)
        self.accept()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.close()
示例#7
0
    def __init__(self, parent=None):
        super(EqGeneralRecorsListModule, self).__init__(parent)
        self.setupUi(self)
        if '50' not in user.powers:
            self.close()
        if user.powers['50'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['50'])

        self.EC = EquipmentController()
        self.SC = SelfdefinedformatController()
        self.deptid = ''
        self.eqtype = -1
        self.eqno = ''

        self.treeWidget_equuiplist.hideColumn(0)
        self.treeWidget_deptlist.hideColumn(1)
        self.treeWidget_recordslist.hideColumn(0)
        self.get_dept_detail()
        self.get_eq_detail()
示例#8
0
 def __init__(self, autoid=None, parent=None):
     super(EditSupplyerDetailModule, self).__init__(parent)
     self.setupUi(self)
     if '3' not in user.powers:
         self.close()
     if user.powers['3'] == 0:
         self.close()
     self.power = '{:03b}'.format(user.powers['3'])
     if self.power[1] == '0':
         self.pushButton_accept.setVisible(False)
         self.pushButton_cancel.setVisible(False)
     self.autoid = autoid
     self.docid = 0
     self.current_content = QWidget()
     self.ori_detail = dict()
     self.new_detail = dict()
     self.current_img = object
     self.current_page = object
     self.SC = SupplyerController()
     self.SDC = SelfdefinedformatController()
     self.IC = ImageController()
     self.treeWidget_stuff.hideColumn(0)
     self.treeWidget_revalution.hideColumn(0)
     self.treeWidget_imagenamelist.hideColumn(0)
     self.treeWidget_imagenamelist.hideColumn(1)
     # 自动缩放
     self.label_image.setScaledContents(True)
     return_row = ('parentid', 'autoid', 'kindname')
     condition_key = {'autoid', 'kindname', 'inputcode'}
     treeheader_name = ['parentid', '编号', '名称']
     condition = {'kind': 0}
     self.lineEdit_kind.setup('Treestructure',
                              return_row,
                              condition_key,
                              treeheader_name,
                              condition,
                              treewidth=300)
     self.get_detail()
    def __init__(self, parent=None):
        super(ProductLineListModule, self).__init__(parent)
        self.setupUi(self)

        if '5' not in user.powers:
            self.close()
        if user.powers['5'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['5'])
        self.treeWidget_productline.hideColumn(1)
        self.treeWidget_productline.hideColumn(2)
        self.treeWidget_productline.hideColumn(3)
        self.treeWidget_format.hideColumn(1)
        self.treeWidget_equipment.hideColumn(2)
        self.treeWidget_document.hideColumn(1)
        self.PC = ProductLineConroller()
        self.SC = SelfdefinedformatController()
        self.EC = EquipmentController()
        self.DC = DocumentController()
        self.get_selfdefineformat()
        self.get_equipment_list()
        self.get_document_list()
        self.get_product_line_list()
class VerificationDetailModule(QDialog, Ui_Dialog):
    updated = pyqtSignal()

    def __init__(self, autoid=None, vdpid=0, parent=None):
        super(VerificationDetailModule, self).__init__(parent)
        self.setupUi(self)
        self.autoid = autoid
        self.vdpid = vdpid
        self.filename = None
        self.doc = None
        self.reportid = 0
        self.current_content = QWidget()
        self.current_img = object
        self.current_page = object
        self.label_image.setScaledContents(True)
        self.status = 0
        self.current_docid = 0
        self.ori_detail = {}
        self.new_detail = {}
        self.VC = VerificationController()
        self.SC = SelfdefinedformatController()
        self.lineEdit_product.setup(DB_TABLE_TUPLE[0], RETURN_ROW[0],
                                    CONDITION_KEY[0], TREEHEADER_NAME, None,
                                    330, 200)
        self.treeWidget_report.hideColumn(0)
        self.treeWidget_labreport.hideColumn(0)
        self.treeWidget_labreport.hideColumn(1)
        self.treeWidget_pp_record.hideColumn(0)
        self.treeWidget_pp_record.hideColumn(1)
        self.label_other.setVisible(False)
        self.lineEdit_other.setVisible(False)
        self.get_plan()
        self.show_plandoc()
        self.get_report()
        self.get_producingplan_records()
        self.get_lab_records()

    def get_plan(self):
        if self.autoid is None:
            self.tabWidget.setTabVisible(1, False)
            self.tabWidget.setTabVisible(2, False)
            self.tabWidget.setTabVisible(3, False)
            self.tabWidget.setTabVisible(4, False)
            self.tabWidget.setTabVisible(5, False)
            self.dateEdit_valstartdate.setDate(user.now_date)
            self.dateEdit_valenddate.setDate(user.now_date)
            self.dateEdit_createdate.setDate(user.now_date)
            self.pushButton_examine.setVisible(False)
            self.pushButton_approval.setVisible(False)
            self.pushButton_finish.setVisible(False)
            return
        condition = {'autoid': self.autoid}
        res = self.VC.get_data(1, False, *VALUES_TUPLE_PLAN, **condition)
        if not len(res):
            return
        self.ori_detail = res[0]
        self.comboBox_valtype.setCurrentIndex(self.ori_detail['valtype'])
        self.comboBox_kind.setCurrentIndex(self.ori_detail['kind'])
        if self.ori_detail['kind'] < 2:
            self.lineEdit_product.setText(self.ori_detail['prodid'] + ' ' +
                                          self.ori_detail['prodname'])
        else:
            self.lineEdit_other.setText(self.ori_detail['prodnamether'])
        self.dateEdit_valstartdate.setDate(self.ori_detail['valstartdate'])
        self.dateEdit_valenddate.setDate(self.ori_detail['valenddate'])
        self.lineEdit_doctitle.setText(self.ori_detail['doctitle'])
        self.label_creator.setText(self.ori_detail['creatorid'] + ' ' +
                                   self.ori_detail['creatorname'])
        self.dateEdit_createdate.setDate(self.ori_detail['createdate'] if type(
            self.ori_detail['createdate']) is datetime.date else user.now_date)
        self.label_examiner.setText(self.ori_detail['auditorid'] + ' ' +
                                    self.ori_detail['auditorname'])
        self.dateEdit_auditdate.setDate(self.ori_detail['auditdate'] if type(
            self.ori_detail['auditdate']) is datetime.date else user.now_date)
        self.label_approver.setText(self.ori_detail['approverid'] + ' ' +
                                    self.ori_detail['approvername'])

        self.dateEdit_approvedate.setDate(self.ori_detail['approvedate'] if
                                          type(self.ori_detail['approvedate'])
                                          is datetime.date else user.now_date)

        if self.ori_detail['status'] == 1:
            self.pushButton_upload.setVisible(False)
            self.pushButton_apply.setVisible(False)
            self.pushButton_examine.setVisible(False)
            self.pushButton_approval.setVisible(False)
            self.pushButton_finish.setVisible(False)

    def show_plandoc(self):
        if not len(self.ori_detail):
            return
        ext = self.ori_detail['ext']
        title = self.ori_detail['doctitle']
        self.doc = self.ori_detail['doc']

        if ext in ("doc", "docx"):
            self.groupBox_pdf.setVisible(False)
            self.axWidget.setVisible(True)
            self.axWidget.clear()
            if not (self.axWidget.setControl("Word.Application")
                    or self.axWidget.setControl("Kwps.Application")):
                msg = MessageBox(self, text="没有安装Word/WPS文字!")
                msg.show()
                return
            self.open_office(title + '.' + ext)
        elif ext == "pdf":
            self.axWidget.setVisible(False)
            self.axWidget.clear()
            self.groupBox_pdf.setVisible(True)
            self.open_pdf(title + '.' + ext)
        elif ext in ("xls", "xlsx"):
            self.groupBox_pdf.setVisible(False)
            self.axWidget.setVisible(True)
            self.axWidget.clear()
            if not (self.axWidget.setControl("Excel.Application")
                    or self.axWidget.setControl("Ket.Application")):
                msg = MessageBox(self, text="没有安装Excel/WPS表格!")
                msg.show()
                return
            self.open_office(title + '.' + ext)

    def get_report(self):
        self.treeWidget_report.clear()
        if self.autoid is None:
            return
        condition = {'vdrid_id': self.autoid}
        res = self.VC.get_data(2, False, *VALUES_TUPLE_REPORT, *condition)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_report)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['formname'])
            qtreeitem.setText(2, item['creatorid'] + ' ' + item['creatorname'])
            qtreeitem.setText(3, str(item['createdate']))
        for i in range(1, 4):
            self.treeWidget_report.resizeColumnToContents(i)

    def get_producingplan_records(self):
        self.treeWidget_pp_record.clear()
        condition = {'kind': 0, 'vdrid_id': self.autoid}
        res = self.VC.get_data(3, False, **condition).extra(
            select={
                'prodid': 'prodid',
                'prodname': 'prodname',
                'spec': 'spec',
                'package': 'package',
                'batchno': 'batchno',
                'status': 'status',
                'makedate': 'makedate'
            },
            tables=['Producingplan'],
            where=['Producingplan.autoid=Validaterelationrecords.ppid'
                   ]).values(*VALUES_TUPLE_PP)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_pp_record)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, str(item['ppid']))
            qtreeitem.setText(2, STATUS_PP[item['status']])
            qtreeitem.setText(3, item['prodid'])
            qtreeitem.setText(4, item['prodname'])
            qtreeitem.setText(5, item['batchno'])
            qtreeitem.setText(6, item['spec'])
            qtreeitem.setText(7, item['package'])
            qtreeitem.setText(8, str(item['makedate']))
        for i in range(1, 9):
            self.treeWidget_pp_record.resizeColumnToContents(i)

    def get_lab_records(self):
        self.treeWidget_labreport.clear()
        condition = {'kind': 1, 'vdrid_id': self.autoid}
        res = self.VC.get_data(3, False, **condition).extra(
            select={
                'chkid': 'chkid',
                'chkname': 'chkname',
                'spec': 'spec',
                'package': 'package',
                'batchno': 'batchno',
                'status': 'status',
                'paperno': 'paperno'
            },
            tables=['Labrecords'],
            where=['Labrecords.autoid=Validaterelationrecords.ppid'
                   ]).values(*VALUES_TUPLE_LR)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_labreport)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, str(item['ppid']))
            qtreeitem.setText(2, STATUS_LR[item['status']])
            qtreeitem.setText(3, item['chkid'])
            qtreeitem.setText(4, item['chkname'])
            qtreeitem.setText(5, item['batchno'])
            qtreeitem.setText(6, item['spec'])
            qtreeitem.setText(7, item['package'])
        for i in range(1, 8):
            self.treeWidget_labreport.resizeColumnToContents(i)

    @pyqtSlot(QPoint)
    def on_treeWidget_pp_record_customContextMenuRequested(self, pos):
        current_item = self.treeWidget_pp_record.currentItem()
        global_pos = self.treeWidget_pp_record.mapToGlobal(pos)
        menu = QMenu()
        action_1 = menu.addAction("新建生产记录")
        action_2 = menu.addAction("关联生产记录")
        action_3 = menu.addAction("删除记录")
        action = menu.exec(global_pos)
        if action == action_1:
            detail = EditProducingplan(parent=self)
            detail.created.connect(self.created_producingplan)
            detail.created.connect(self.get_producingplan_records)
            detail.show()

        elif action == action_2:
            detail = SelectRecordsModule(0, self)
            detail.selected.connect(self.add_pp_or_lr_records)
            detail.selected.connect(self.get_producingplan_records)
            detail.show()

        elif action == action_3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.VC.delete_data(3, condition)
            self.get_producingplan_records()

    def created_producingplan(self, ppid):
        self.add_pp_or_lr_records(0, [
            ppid,
        ])

    @pyqtSlot(QPoint)
    def on_treeWidget_labreport_customContextMenuRequested(self, pos):
        current_item = self.treeWidget_labreport.currentItem()
        global_pos = self.treeWidget_labreport.mapToGlobal(pos)
        menu = QMenu()
        action_1 = menu.addAction("新建请验单")
        action_2 = menu.addAction("关联检验记录")
        action_3 = menu.addAction("删除记录")
        action = menu.exec(global_pos)
        if action == action_1:
            pass
        elif action == action_2:
            detail = SelectRecordsModule(1, self)
            detail.selected.connect(self.add_pp_or_lr_records)
            detail.selected.connect(self.get_lab_records)
            detail.show()

        elif action == action_3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.VC.delete_data(3, condition)
            self.get_lab_records()

    def add_pp_or_lr_records(self, p_int, id_list):
        for item in id_list:
            detail = {'vdrid_id': self.autoid, 'kind': p_int, 'ppid': item}
            self.VC.update_data(3, **detail)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_pp_record_itemDoubleClicked(self, qtreeitem, p_int):
        id = int(qtreeitem.text(1))
        try:
            detail = ProducingModule(autoid=id, parent=self)
            detail.show()
        except ValueError:
            pass

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_labreport_itemDoubleClicked(self, qtreeitem, p_int):
        id = int(qtreeitem.text(1))
        detail = CheckreportModule(autoid=id, is_view=True, parent=self)
        detail.show()

    @pyqtSlot(QPoint)
    def on_treeWidget_report_customContextMenuRequested(self, pos):
        current_item = self.treeWidget_report.currentItem()
        global_pos = self.treeWidget_report.mapToGlobal(pos)
        menu = QMenu()
        action_1 = menu.addAction("增加")
        action_2 = menu.addAction("修改")
        action_3 = menu.addAction("删除")
        action = menu.exec(global_pos)
        if action == action_1:
            detail = SelectSelfDefineFormatModule("512", self)
            detail.selected.connect(self.add_oricheckpaper)
            detail.selected.connect(self.get_report)
            detail.show()
        elif action == action_2:
            if current_item is None:
                return
            if hasattr(self.current_content, 'flat'):
                if self.current_content.flat:
                    dialog = MessageBox(self,
                                        title="提醒",
                                        text="文档尚未保存",
                                        informative="是否要保存文档",
                                        yes_text="保存",
                                        no_text="放弃保存")
                    result = dialog.exec()
                    if result == QMessageBox.Yes:
                        # 调用保存的槽函数
                        self.on_pushButton_accept_clicked()
            self.reportid = int(current_item.text(0))
            condition = {'autoid': self.reportid}
            res = self.VC.get_data(2, True, *VALUES_TUPLE_RP_DETAIL,
                                   **condition)
            if not len(res):
                return
            content = str(res[0])
            if not self.gridLayout_11.isEmpty():
                self.gridLayout_11.removeWidget(self.current_content)
                self.current_content.close()
            self.current_content = XMLReadWrite(self)
            self.current_content.openxml(content)
            self.gridLayout_11.addWidget(self.current_content)
            self.current_content.__setattr__('autoid', self.reportid)
        elif action == action_3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.VC.delete_data(2, condition)
            self.get_report()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_report_itemDoubleClicked(self, qtreeitem, p_int):
        if hasattr(self.current_content, 'flat'):
            if self.current_content.flat:
                dialog = MessageBox(self,
                                    title="提醒",
                                    text="文档尚未保存",
                                    informative="是否要保存文档",
                                    yes_text="保存",
                                    no_text="放弃保存")
                result = dialog.exec()
                if result == QMessageBox.Yes:
                    # 调用保存的槽函数
                    self.on_pushButton_accept_clicked()
        self.reportid = int(qtreeitem.text(0))
        condition = {'autoid': self.reportid}
        res = self.VC.get_data(2, True, *VALUES_TUPLE_RP_DETAIL, **condition)
        if not len(res):
            return
        content = str(res[0])
        if not self.gridLayout_11.isEmpty():
            self.gridLayout_11.removeWidget(self.current_content)
            self.current_content.close()
        self.current_content = XMLReadWrite(self)
        self.current_content.openxml(content)
        self.gridLayout_11.addWidget(self.current_content)
        self.current_content.__setattr__('autoid', self.reportid)

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if self.reportid == 0:
            return
        if not hasattr(self.current_content, 'flat'):
            return
        newcontent = self.current_content.get_content()
        condition = {'autoid': self.reportid}
        kwargs = {'formcontent': newcontent}
        self.VC.update_data(2, condition, **kwargs)
        self.current_content.flat = 0

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        if hasattr(self.current_content, 'flat'):
            self.current_content.flat = 0

    def add_oricheckpaper(self, sdfid_list):
        condition = {'autoid__in': sdfid_list}
        res = self.SC.get_data(0, False, *VALUES_TUPLE_SD, **condition)
        for item in res:
            condition = {
                'vdrid_id': self.autoid,
                'formname': item['formatname'],
                'formcontent': item['format'],
                'creatorid': user.user_id,
                'creatorname': user.user_name,
                'createdate': user.now_date
            }
            self.VC.update_data(2, **condition)
        self.get_report()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_records_itemDoubleClicked(self, qtreeitem, p_int):
        id = int(qtreeitem.text(0))
        detail = VerificationDetailModule(autoid=id, parent=self)
        detail.updated.connect(self.get_reports)
        detail.show()

    def open_office(self, filename):

        if not os.path.exists(os.getcwd() + '\\temp'):
            os.makedirs(os.getcwd() + '\\temp')
        self.filename = os.getcwd() + '\\temp\\' + filename
        with open(self.filename, 'wb') as fp:
            fp.write(self.doc)
            fp.close()
            fp = None
        self.axWidget.setControl(self.filename)

    def open_pdf(self, filename):
        self.current_img = fitz.Document(stream=self.doc, filetype='pdf')
        page_count = self.current_img.pageCount
        page_list = []
        self.comboBox_jumpto.clear()
        for i in range(1, page_count + 1):
            page_list.append('第' + str(i) + '页')
        self.comboBox_jumpto.addItems(page_list)
        self.current_page = self.current_img.loadPage(0)
        self.horizontalSlider_zoom.setValue(20)

    @pyqtSlot(int)
    def on_horizontalSlider_zoom_valueChanged(self, p_int):

        try:
            self.label_zoom.setText(str(p_int * 10) + '%')
            # 把当前页面转为QPixmap,并缩放为p_int/10
            cover = render_pdf_page(self.current_page, p_int / 10, p_int / 10)
            self.label_image.setPixmap(cover)
        except (AttributeError, ValueError):
            size = self.current_img.size()
            new_pixmap = self.current_img.scaled(size.width() * p_int / 10,
                                                 size.height() * p_int / 10)
            self.label_image.setPixmap(new_pixmap)

    @pyqtSlot(int)
    def on_comboBox_jumpto_currentIndexChanged(self, p_int):
        try:
            self.current_page = self.current_img.loadPage(p_int)
            self.on_horizontalSlider_zoom_valueChanged(
                self.horizontalSlider_zoom.value())
        except (AttributeError, ValueError):
            pass

    @pyqtSlot()
    def on_pushButton_prepage_clicked(self):
        index = self.comboBox_jumpto.currentIndex()
        if index - 1 >= 0:
            try:
                self.current_page = self.current_img.loadPage(index - 1)
                self.comboBox_jumpto.setCurrentIndex(index - 1)
            except (AttributeError, ValueError):
                pass

    @pyqtSlot()
    def on_pushButton_nextpage_clicked(self):
        index = self.comboBox_jumpto.currentIndex()
        if index + 1 < self.comboBox_jumpto.count():
            try:
                self.current_page = self.current_img.loadPage(index + 1)
                self.comboBox_jumpto.setCurrentIndex(index + 1)
            except (AttributeError, ValueError):
                pass

    @pyqtSlot(int)
    def on_comboBox_valtype_currentIndexChanged(self, p_int):
        try:
            if p_int != self.ori_detail['valtype']:
                self.new_detail['valtype'] = p_int
            else:
                try:
                    del self.new_detail['valtype']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['valtype'] = p_int

    @pyqtSlot(int)
    def on_comboBox_kind_currentIndexChanged(self, p_int):
        try:
            if p_int != self.ori_detail['kind']:
                self.new_detail['kind'] = p_int
            else:
                try:
                    del self.new_detail['kind']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['kind'] = p_int
        # if 'prodid' in self.new_detail:
        #     del self.new_detail['prodid']
        # if 'prodname' in self.new_detail:
        #     del self.new_detail['prodname']

        if p_int < 2:
            self.label_prodname.setVisible(True)
            self.lineEdit_product.setVisible(True)
            self.label_other.setVisible(False)
            self.lineEdit_other.setVisible(False)
            self.lineEdit_product.setText('')
            self.lineEdit_product.setup(DB_TABLE_TUPLE[p_int],
                                        RETURN_ROW[p_int],
                                        CONDITION_KEY[p_int], TREEHEADER_NAME,
                                        None, 300, 200)
        else:
            self.label_prodname.setVisible(False)
            self.lineEdit_product.setVisible(False)
            self.label_other.setVisible(True)
            self.lineEdit_other.setVisible(True)
            self.lineEdit_other.setText('')

    @pyqtSlot()
    def on_pushButton_upload_clicked(self):
        fileurl, type = QFileDialog.getOpenFileName(
            self, "打开文件",
            os.path.expanduser("~") + "\Desktop",
            "选择文件(*.docx *.doc *.pdf);;All File(*.*)")
        if not fileurl:
            return
        filename = fileurl.split("/")[-1]
        name_no_ext = filename.split(".")[0]
        ext = fileurl.split(".")[1]
        if ext.lower() not in ('doc', 'docx', 'xls', 'xlsx', 'pdf'):
            return
        fp = open(fileurl, 'rb')
        with fp:
            file_byte = fp.read()
            fp.close()
        fp = None
        self.lineEdit_doctitle.setText(name_no_ext)
        self.new_detail['doc'] = file_byte
        self.doc = file_byte
        self.new_detail['ext'] = ext.lower()
        self.new_detail['doctitle'] = name_no_ext
        if ext in ("doc", "docx"):
            self.groupBox_pdf.setVisible(False)
            self.axWidget.setVisible(True)
            self.axWidget.clear()
            if not (self.axWidget.setControl("Word.Application")
                    or self.axWidget.setControl("Kwps.Application")):
                msg = MessageBox(self, text="没有安装Word/WPS文字!")
                msg.show()
                return
            self.open_office(name_no_ext + '.' + ext)
        elif ext == "pdf":
            self.axWidget.setVisible(False)
            self.axWidget.clear()
            self.groupBox_pdf.setVisible(True)
            self.open_pdf(name_no_ext + '.' + ext)
        elif ext in ("xls", "xlsx"):
            self.groupBox_pdf.setVisible(False)
            self.axWidget.setVisible(True)
            self.axWidget.clear()
            if not (self.axWidget.setControl("Excel.Application")
                    or self.axWidget.setControl("Ket.Application")):
                msg = MessageBox(self, text="没有安装Excel/WPS表格!")
                msg.show()
                return
            self.open_office(name_no_ext + '.' + ext)

    @pyqtSlot(object)
    def on_lineEdit_product_getItem(self, qtreeitem):
        if qtreeitem is None:
            self.new_detail['prodid'] = ''
            self.new_detail['prodname'] = ''
            return
        id, name = qtreeitem.text(1), qtreeitem.text(2)
        try:
            if id != self.ori_detail['prodid'] and name != self.ori_detail[
                    'prodname']:
                self.new_detail['prodid'] = id
                self.new_detail['prodname'] = name
            else:
                try:
                    del self.new_detail['prodid']
                    del self.new_detail['prodname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['prodid'] = id
            self.new_detail['prodname'] = name

    @pyqtSlot(str)
    def on_lineEdit_other_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['prodname']:
                self.new_detail['prodid'] = ''
                self.new_detail['prodname'] = p_str
            else:
                try:
                    del self.new_detail['prodid']
                    del self.new_detail['prodname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['prodid'] = ''
            self.new_detail['prodname'] = p_str

    @pyqtSlot(QDate)
    def on_dateEdit_valstartdate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['valstartdate']) is str:
                self.new_detail['valstartdate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['valstartdate']):
                self.new_detail['valstartdate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['valstartdate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['valstartdate'] = q_date.toPyDate()

    @pyqtSlot(QDate)
    def on_dateEdit_valenddate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['valenddate']) is str:
                self.new_detail['valenddate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['valenddate']):
                self.new_detail['valenddate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['valenddate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['valenddate'] = q_date.toPyDate()

    @pyqtSlot(QDate)
    def on_dateEdit_createdate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['createdate']) is str:
                self.new_detail['createdate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['createdate']):
                self.new_detail['createdate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['createdate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['createdate'] = q_date.toPyDate()

    @pyqtSlot(QDate)
    def on_dateEdit_auditdate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['auditdate']) is str:
                self.new_detail['auditdate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['auditdate']):
                self.new_detail['auditdate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['auditdate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['auditdate'] = q_date.toPyDate()

    @pyqtSlot(QDate)
    def on_dateEdit_approvedate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['approvedate']) is str:
                self.new_detail['approvedate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['approvedate']):
                self.new_detail['approvedate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['approvedate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['approvedate'] = q_date.toPyDate()

    @pyqtSlot()
    def on_pushButton_apply_clicked(self):
        self.new_detail['creatorid'] = user.user_id
        self.new_detail['creatorname'] = user.user_name
        self.label_creator.setText(user.user_id + ' ' + user.user_name)

        if self.autoid is None:
            self.new_detail['vdpid_id'] = self.vdpid
            res = self.VC.update_data(1, **self.new_detail)
            self.autoid = res.autoid
            self.tabWidget.setTabVisible(1, True)
            self.tabWidget.setTabVisible(2, True)
            self.tabWidget.setTabVisible(3, True)
            self.tabWidget.setTabVisible(4, True)
            self.tabWidget.setTabVisible(5, True)
            self.pushButton_examine.setVisible(True)
            self.pushButton_approval.setVisible(True)
        else:
            condition = {'autoid': self.autoid}
            self.VC.update_data(1, condition, **self.new_detail)
        self.updated.emit()

    @pyqtSlot()
    def on_pushButton_examine_clicked(self):
        self.new_detail['examineid'] = user.user_id
        self.new_detail['examinename'] = user.user_name
        condition = {'autoid': self.autoid}
        self.VC.update_data(1, condition, **self.new_detail)
        self.updated.emit()

    @pyqtSlot()
    def on_pushButton_approval_clicked(self):
        self.new_detail['approvalid'] = user.user_id
        self.new_detail['approvalname'] = user.user_name
        condition = {'autoid': self.autoid}
        self.VC.update_data(1, condition, **self.new_detail)
        self.updated.emit()

    @pyqtSlot()
    def on_pushButton_finish_clicked(self):
        self.new_detail['status'] = 1
        condition = {'autoid': self.autoid}
        self.VC.update_data(1, condition, **self.new_detail)
        self.updated.emit()

    def closeEvent(self, event):
        self.axWidget.clear()
        if self.filename is not None and os.path.exists(self.filename):
            os.remove(self.filename)
        super(VerificationDetailModule, self).closeEvent(event)
示例#11
0
class EditSupplyerDetailModule(QDialog, Ui_Dialog):
    def __init__(self, autoid=None, parent=None):
        super(EditSupplyerDetailModule, self).__init__(parent)
        self.setupUi(self)
        if '3' not in user.powers:
            self.close()
        if user.powers['3'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['3'])
        if self.power[1] == '0':
            self.pushButton_accept.setVisible(False)
            self.pushButton_cancel.setVisible(False)
        self.autoid = autoid
        self.docid = 0
        self.current_content = QWidget()
        self.ori_detail = dict()
        self.new_detail = dict()
        self.current_img = object
        self.current_page = object
        self.SC = SupplyerController()
        self.SDC = SelfdefinedformatController()
        self.IC = ImageController()
        self.treeWidget_stuff.hideColumn(0)
        self.treeWidget_revalution.hideColumn(0)
        self.treeWidget_imagenamelist.hideColumn(0)
        self.treeWidget_imagenamelist.hideColumn(1)
        # 自动缩放
        self.label_image.setScaledContents(True)
        return_row = ('parentid', 'autoid', 'kindname')
        condition_key = {'autoid', 'kindname', 'inputcode'}
        treeheader_name = ['parentid', '编号', '名称']
        condition = {'kind': 0}
        self.lineEdit_kind.setup('Treestructure',
                                 return_row,
                                 condition_key,
                                 treeheader_name,
                                 condition,
                                 treewidth=300)
        self.get_detail()

    def get_detail(self):
        if self.autoid is None:
            self.dateEdit_validdate.setDate(user.now_date)
            return
        key_dict = {'autoid': self.autoid}
        res = self.SC.get_data(0, False, *VALUE_TUPLE_SUP, **key_dict)
        if not len(res):
            return
        self.ori_detail = res[0]
        self.lineEdit_supid.setText(self.ori_detail['supid'])
        self.lineEdit_supname.setText(self.ori_detail['supname'])
        self.lineEdit_inputcode.setText(self.ori_detail['inputcode'])
        self.lineEdit_kind.setText(
            str(self.ori_detail['tstkind']) + ' ' + self.ori_detail['tstname'])
        self.lineEdit_address.setText(self.ori_detail['address'])
        self.lineEdit_postzip.setText(self.ori_detail['postzip'])
        self.lineEdit_charger.setText(self.ori_detail['charger'])
        self.lineEdit_telno.setText(self.ori_detail['telno'])
        self.lineEdit_chargertitle.setText(self.ori_detail['chargertitle'])
        self.lineEdit_email.setText(self.ori_detail['email'])
        self.lineEdit_bankname.setText(self.ori_detail['bankname'])
        self.lineEdit_bankaccount.setText(self.ori_detail['bankaccount'])
        self.lineEdit_taxno.setText(self.ori_detail['taxno'])
        self.dateEdit_validdate.setDate(self.ori_detail['validdate'])
        self.plainTextEdit_remark.setPlainText(self.ori_detail['remark'])

    def get_image(self):
        self.treeWidget_imagenamelist.clear()
        if self.autoid is None:
            return
        key_dict = {'scid': self.autoid, 'kind': 0}
        res = self.IC.get_data(0, False, *VALUE_TUPLE_IMRELA, **key_dict)
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_imagenamelist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, str(item['imageid']))
            qtreeitem.setText(2, item['title'])
            qtreeitem.setText(3, item['creatorid'] + item['creatorname'])
            qtreeitem.setText(4, str(item['createdate']))

    def get_format(self):
        if self.autoid is None:
            return
        self.treeWidget_revalution.clear()
        key_dict = {'spid': self.autoid}
        res = self.SC.get_data(4, False, *VALUE_TUPLE_SR, **key_dict)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_revalution)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['title'])
            qtreeitem.setText(2, str(item['createdate']))
            qtreeitem.setText(3, item['creatorid'] + ' ' + item['creatorname'])
        for i in range(1, 4):
            self.treeWidget_revalution.resizeColumnToContents(i)

    def get_stuff(self):
        if self.autoid is None:
            return
        self.treeWidget_stuff.clear()
        key_dict = {'spid': self.autoid}
        res = self.SC.get_data(1, False, **key_dict).extra(
            select={
                'autoid': 'stuffdictionary.autoid',
                'stuffid': 'stuffdictionary.stuffid',
                'stuffname': 'stuffdictionary.stuffname',
                'stufftype': 'stuffdictionary.stufftype',
                'spec': 'stuffdictionary.spec',
                'package': 'stuffdictionary.package'
            },
            tables=['stuffdictionary'],
            where=['stuffdictionary.autoid=stuffsupplyers.sdid'
                   ]).values(*VALUE_TUPLE_STUFF)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_stuff)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, STUFFTYPE[item['stufftype']])
            qtreeitem.setText(2, item['stuffid'])
            qtreeitem.setText(3, item['stuffname'])
            qtreeitem.setText(4, item['spec'])
            qtreeitem.setText(5, item['package'])
        for i in range(1, 6):
            self.treeWidget_stuff.resizeColumnToContents(i)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_imagenamelist_itemDoubleClicked(self, qtreeitem, p_int):

        img_id = int(qtreeitem.text(1))
        key_dict = {'autoid': img_id}
        res = self.IC.get_data(1, False, *VALUE_TUPLE_IM, **key_dict)
        if not len(res):
            return
        ext = res[0]['ext']
        image = res[0]['img']

        if ext.lower() == 'pdf':
            self.comboBox_jumpto.setVisible(True)
            self.pushButton_prepage.setVisible(True)
            self.pushButton_nextpage.setVisible(True)
            self.current_img = fitz.Document(stream=image, filetype='pdf')
            page_count = self.current_img.pageCount
            page_list = []
            self.comboBox_jumpto.clear()
            for i in range(1, page_count + 1):
                page_list.append('第' + str(i) + '页')
            self.comboBox_jumpto.addItems(page_list)
            self.current_page = self.current_img.loadPage(0)

        else:
            self.comboBox_jumpto.setVisible(False)
            self.pushButton_prepage.setVisible(False)
            self.pushButton_nextpage.setVisible(False)
            img = QImage.fromData(image)
            self.current_img = QPixmap.fromImage(img)
            self.label_image.setPixmap(self.current_img)

        # 默认放大为3被,同时自动调用on_horizontalSlider_zoom_valueChanged
        self.horizontalSlider_zoom.setValue(30)

    @pyqtSlot(int)
    def on_horizontalSlider_zoom_valueChanged(self, p_int):

        try:
            self.label_zoom.setText(str(p_int * 10) + '%')
            # 把当前页面转为QPixmap,并缩放为p_int/10
            cover = render_pdf_page(self.current_page, p_int / 10, p_int / 10)
            self.label_image.setPixmap(cover)
        except (ValueError, AttributeError):
            size = self.current_img.size()
            new_pixmap = self.current_img.scaled(size.width() * p_int / 10,
                                                 size.height() * p_int / 10)
            self.label_image.setPixmap(new_pixmap)

    @pyqtSlot(int)
    def on_comboBox_jumpto_currentIndexChanged(self, p_int):
        try:
            self.current_page = self.current_img.loadPage(p_int)
            self.on_horizontalSlider_zoom_valueChanged(
                self.horizontalSlider_zoom.value())
        except (AttributeError, ValueError):
            pass

    @pyqtSlot()
    def on_pushButton_prepage_clicked(self):
        index = self.comboBox_jumpto.currentIndex()
        if index - 1 >= 0:
            try:
                self.current_page = self.current_img.loadPage(index - 1)
                self.comboBox_jumpto.setCurrentIndex(index - 1)
            except (AttributeError, ValueError):
                pass

    @pyqtSlot()
    def on_pushButton_nextpage_clicked(self):
        index = self.comboBox_jumpto.currentIndex()
        if index + 1 < self.comboBox_jumpto.count():
            try:
                self.current_page = self.current_img.loadPage(index + 1)
                self.comboBox_jumpto.setCurrentIndex(index + 1)
            except (AttributeError, ValueError):
                pass

    @pyqtSlot(QPoint)
    def on_treeWidget_imagenamelist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        # 返回调用者的对象
        sender_widget = self.sender()
        menu = QMenu()
        button1 = menu.addAction("新增图片")
        button2 = menu.addAction("修改图片")
        button3 = menu.addAction("删除图片")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        res = "rollback"
        # 增加
        if action == button1:
            img_names, img_type = QFileDialog.getOpenFileNames(
                self, "打开图片",
                os.path.expanduser("~") + "\Desktop",
                "*.jpg;;*.png;;*.bmp;;*.gif;;*.pdf;;All Files(*)")
            for item in img_names:
                imagename_no_ext = item.split("/")[-1]
                image_ext = item.split(".")[1]
                if image_ext.lower() not in ("jpg", "png", "bmp", "gif",
                                             "pdf"):
                    continue
                fp = open(item, 'rb')
                with fp:
                    image_byte = fp.read()
                    fp.close()
                imagedetail = {'img': image_byte, 'ext': image_ext}
                reladetail = {
                    'kind': 0,
                    'scid': self.autoid,
                    'title': imagename_no_ext,
                    'creatorid': user.user_id,
                    'creatorname': user.user_name,
                    'createdate': user.now_date
                }

                res = self.IC.update_images(reladetail, imagedetail)

        # 修改
        elif action == button2:
            rela_id = self.treeWidget_imagenamelist.currentItem().text(0)
            img_id = self.treeWidget_imagenamelist.currentItem().text(1)
            img_name, img_type = QFileDialog.getOpenFileName(
                self, "打开图片",
                os.path.expanduser("~") + "\Desktop",
                "*.jpg;;*.png;;*.bmp;;*.gif;;*.pdf;;All Files(*)")
            imagename_no_ext = img_name.split("/")[-1]
            image_ext = img_name.split(".")[1]
            if image_ext.lower() in ("jpg", "png", "bmp", "gif", "pdf"):
                fp = open(img_name, 'rb')
                with fp:
                    image_byte = fp.read()
                    fp.close()
                imagedetail = {'img': image_byte, 'ext': image_ext}
                reladetail = {
                    'title': imagename_no_ext,
                    'creatorid': user.user_id,
                    'creatorname': user.user_name,
                    'createdate': user.now_date
                }

                res = self.IC.update_images(reladetail, imagedetail, rela_id,
                                            img_id)

        # 删除
        elif action == button3:
            select_item = sender_widget.selectedItems()
            rela_id = []
            img_id = []
            for item in select_item:
                rela_id.append(item.text(0))
                img_id.append(item.text(1))
            res = self.IC.delete_images(rela_id, img_id)

        if res == "accept":
            self.get_image()

    @pyqtSlot(str)
    def on_lineEdit_supid_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['supid']:
                self.new_detail['supid'] = p_str
            else:
                try:
                    del self.new_detail['supid']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['supid'] = p_str

        @pyqtSlot(bool, str)
        def on_pushButton_warrantor_signChanged(self, p_bool, p_str):
            id, name = p_str.split(' ') if p_bool else ('', '')
            try:
                if id != self.ori_detail['warrantorid'] or name != \
                        self.ori_detail[
                            'warrantorname']:
                    self.new_detail['warrantorid'] = id
                    self.new_detail['warrantorname'] = name
                else:
                    try:
                        del self.new_detail['warrantorid']
                        del self.new_detail['warrantorname']
                    except KeyError:
                        pass
            except KeyError:
                self.new_detail['warrantorid'] = id
                self.new_detail['warrantorname'] = name

    @pyqtSlot(str)
    def on_lineEdit_supname_textChanged(self, p_str):
        self.lineEdit_inputcode.setText(Inputcode.make_inputcode(p_str))
        try:
            if p_str != self.ori_detail['supname']:
                self.new_detail['supname'] = p_str
            else:
                try:
                    del self.new_detail['supname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['supname'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_kind_textChanged(self, p_str):
        if len(p_str.split(' ')) != 2 and p_str != '':
            return
        id, name = p_str.split(' ') if p_str != '' else ('', '')
        try:
            if id != self.ori_detail['tstkind'] or name != \
                    self.ori_detail['tstname']:
                self.new_detail['tstkind'] = id
                self.new_detail['tstname'] = name
            else:
                try:
                    del self.new_detail['tstkind']
                    del self.new_detail['tstname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['tstkind'] = id
            self.new_detail['tstname'] = name

    @pyqtSlot(str)
    def on_lineEdit_inputcode_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['inputcode']:
                self.new_detail['inputcode'] = p_str
            else:
                try:
                    del self.new_detail['inputcode']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['inputcode'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_address_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['address']:
                self.new_detail['address'] = p_str
            else:
                try:
                    del self.new_detail['address']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['address'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_postzip_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['postzip']:
                self.new_detail['postzip'] = p_str
            else:
                try:
                    del self.new_detail['postzip']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['postzip'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_charger_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['charger']:
                self.new_detail['charger'] = p_str
            else:
                try:
                    del self.new_detail['charger']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['charger'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_telno_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['telno']:
                self.new_detail['telno'] = p_str
            else:
                try:
                    del self.new_detail['telno']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['telno'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_chargertitle_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['chargertitle']:
                self.new_detail['chargertitle'] = p_str
            else:
                try:
                    del self.new_detail['chargertitle']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['chargertitle'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_email_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['email']:
                self.new_detail['email'] = p_str
            else:
                try:
                    del self.new_detail['email']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['email'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_bankname_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['bankname']:
                self.new_detail['bankname'] = p_str
            else:
                try:
                    del self.new_detail['bankname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['bankname'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_bankaccount_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['bankaccount']:
                self.new_detail['bankaccount'] = p_str
            else:
                try:
                    del self.new_detail['bankaccount']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['bankaccount'] = p_str

    @pyqtSlot(str)
    def on_lineEdit_taxno_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['taxno']:
                self.new_detail['taxno'] = p_str
            else:
                try:
                    del self.new_detail['taxno']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['taxno'] = p_str

    @pyqtSlot(QDate)
    def on_dateEdit_validdate_dateChanged(self, q_date):
        try:
            if type(self.ori_detail['validdate']) is str:
                self.new_detail['validdate'] = q_date.toPyDate()
                return
            if q_date != QDate(self.ori_detail['validdate']):
                self.new_detail['validdate'] = q_date.toPyDate()
            else:
                try:
                    del self.new_detail['validdate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['validdate'] = q_date.toPyDate()

    @pyqtSlot()
    def on_plainTextEdit_remark_textChanged(self):
        p_str = self.plainTextEdit_remark.toPlainText()
        try:
            if p_str != self.ori_detail['remark']:
                self.new_detail['remark'] = p_str
            else:
                try:
                    del self.new_detail['remark']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['remark'] = p_str

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if not len(self.new_detail):
            return
        condition = dict()
        if self.autoid is not None:
            condition['autoid'] = self.autoid
        self.SC.update_data(0, condition, **self.new_detail)
        self.accept()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.close()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_revalution_itemDoubleClicked(self, qtreeitem, p_int):
        if hasattr(self.current_content, 'flat'):
            if self.current_content.flat:
                dialog = MessageBox(self,
                                    title="提醒",
                                    text="文档尚未保存",
                                    informative="是否要保存文档",
                                    yes_text="保存",
                                    no_text="放弃保存")
                result = dialog.exec()
                if result == QMessageBox.Yes:
                    # 调用保存的槽函数
                    self.on_pushButton_save_clicked()
        self.docid = int(qtreeitem.text(0))
        key_dict = {'autoid': self.docid}
        res = self.SC.get_data(4, True, *VALUE_TUPLE_SD, **key_dict)
        if not len(res):
            return
        content = str(res[0])
        if not self.gridLayout_7.isEmpty():
            self.gridLayout_7.removeWidget(self.current_content)
            self.current_content.close()
        self.current_content = XMLReadWrite(self)
        self.current_content.openxml(content)
        self.gridLayout_7.addWidget(self.current_content)
        self.current_content.__setattr__('autoid', self.docid)

    @pyqtSlot()
    def on_pushButton_save_clicked(self):
        if self.docid == 0:
            return
        if not hasattr(self.current_content, 'flat'):
            return
        newcontent = self.current_content.get_content()
        condition = {'autoid': self.docid}
        kwargs = {'conclusion': newcontent}
        self.SC.update_data(4, condition, **kwargs)
        self.current_content.flat = 0

    @pyqtSlot()
    def on_pushButton_undo_clicked(self):
        if hasattr(self.current_content, 'flat'):
            self.current_content.flat = 0

    @pyqtSlot(QPoint)
    def on_treeWidget_revalution_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        if self.autoid is None:
            return
        sender_widget = self.sender()
        current_item = sender_widget.currentItem()
        menu = QMenu()
        button1 = menu.addAction("增加记录")
        button2 = menu.addAction("修改记录")
        button3 = menu.addAction("删除记录")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if action == button1:
            detail = SelectSelfDefineFormatModule('4', self)
            detail.selected.connect(self.new_records)
            detail.accepted.connect(self.get_format)
            detail.show()
        elif action == button2:
            if current_item is None:
                return
            if hasattr(self.current_content, 'flat'):
                if self.current_content.flat:
                    dialog = MessageBox(self,
                                        title="提醒",
                                        text="文档尚未保存",
                                        informative="是否要保存文档",
                                        yes_text="保存",
                                        no_text="放弃保存")
                    result = dialog.exec()
                    if result == QMessageBox.Yes:
                        # 调用保存的槽函数
                        self.on_pushButton_accept_clicked()
            self.docid = int(current_item.text(0))
            key_dict = {'autoid': self.docid}
            res = self.SC.get_data(4, True, *VALUE_TUPLE_SD, **key_dict)
            if not len(res):
                return
            content = str(res[0])
            if not self.gridLayout_7.isEmpty():
                self.gridLayout_7.removeWidget(self.current_content)
                self.current_content.close()
            self.current_content = XMLReadWrite(self)
            self.current_content.openxml(content)
            self.gridLayout_7.addWidget(self.current_content)
            self.current_content.__setattr__('autoid', self.docid)
        elif action == button3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.SC.delete_data(4, condition)
            self.get_format()

    def new_records(self, q_list):
        detail = {
            'creatorid': user.user_id,
            'creatorname': user.user_name,
            'createdate': user.now_date,
            'spid': self.autoid
        }
        key_dict = {'autoid__in': q_list}
        sd_list = self.SDC.get_data(0, **key_dict)
        for item in q_list:
            for sd in sd_list:
                if item == sd.autoid:
                    detail['title'] = sd.formatname
                    detail['conclusion'] = sd.format
                    self.SC.update_data(4, **detail)
                    break

    @pyqtSlot(int)
    def on_tabWidget_currentChanged(self, p_int):
        if p_int == 0:
            self.get_detail()
        elif p_int == 1:
            self.get_image()
        elif p_int == 2:
            self.get_format()
        elif p_int == 3:
            self.get_stuff()
        else:
            pass
示例#12
0
class SelfDefineFormatListModule(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(SelfDefineFormatListModule, self).__init__(parent)
        self.setupUi(self)
        if '4' not in user.powers:
            self.close()
        if user.powers['4'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['4'])
        self.SC = SelfdefinedformatController()
        self.treeWidget_formatlist.hideColumn(1)
        self.get_format_list()

    def get_format_list(self):
        self.treeWidget_formatlist.clear()
        res = self.SC.get_data(0, False, *VALUES_TUPLE_SD)
        for item in res:
            parent_item = self.treeWidget_formatlist
            kind = item['kind']
            subkind = item['subkind']
            # 存在kind
            if kind != '':
                items = self.treeWidget_formatlist.findItems(
                    kind, Qt.MatchExactly, 0)
                if len(items):
                    # 存在subkind
                    if subkind != '':
                        # 遍历所有的祖父节点,找到subkind
                        found = False
                        for i in range(items[0].childCount()):
                            if items[0].child(i).text(0) == subkind:
                                parent_item = items[0].child(i)
                                found = True
                                break
                        if not found:
                            parent_item = QTreeWidgetItem(items[0])
                            parent_item.setText(0, subkind)

                    # 不存在,则把第一个祖父节点设置为父节点
                    else:
                        parent_item = items[0]
                else:
                    parent_item = QTreeWidgetItem(self.treeWidget_formatlist)
                    parent_item.setText(0, kind)
            else:
                if subkind != '':
                    items = self.treeWidget_formatlist.findItems(
                        kind, Qt.MatchExactly, 0)
                    if len(items):
                        parent_item = items[0]
                    else:
                        parent_item = QTreeWidgetItem(
                            self.treeWidget_formatlist)
                        parent_item.setText(0, subkind)
            qtreeitem = QTreeWidgetItem(parent_item)
            qtreeitem.setText(0, item['formatname'])
            qtreeitem.setText(1, str(item['autoid']))
        self.treeWidget_formatlist.resizeColumnToContents(0)

    @pyqtSlot(QPoint)
    def on_treeWidget_formatlist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        menu = QMenu()
        current_item = self.treeWidget_formatlist.currentItem()
        action1 = menu.addAction("新增记录")
        action2 = menu.addAction("修改记录")
        action3 = menu.addAction("删除记录")
        global_pos = self.treeWidget_formatlist.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if action == action1:
            detail = EditSelfDefineFormatDetailModule(parent=self)
            detail.accepted.connect(self.get_format_list)
            detail.show()
        elif action == action2:
            if current_item is None:
                return
            id = current_item.text(1)
            if id == '':
                return
            detail = EditSelfDefineFormatDetailModule(autoid=int(id),
                                                      parent=self)
            detail.accepted.connect(self.get_format_list)
            detail.show()
        elif action3 == action3:
            if current_item is None:
                return
            id = current_item.text(1)
            if id == '':
                return
            condition = {'autoid': int(id)}
            self.SC.delete_data(0, condition)
            self.get_format_list()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_formatlist_itemDoubleClicked(self, qtreeitem, p_int):
        id = qtreeitem.text(1)
        if id == '':
            return
        detail = EditSelfDefineFormatDetailModule(autoid=int(id), parent=self)
        detail.accepted.connect(self.get_format_list)
        detail.show()
示例#13
0
class EqGeneralRecorsListModule(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(EqGeneralRecorsListModule, self).__init__(parent)
        self.setupUi(self)
        if '50' not in user.powers:
            self.close()
        if user.powers['50'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['50'])

        self.EC = EquipmentController()
        self.SC = SelfdefinedformatController()
        self.deptid = ''
        self.eqtype = -1
        self.eqno = ''

        self.treeWidget_equuiplist.hideColumn(0)
        self.treeWidget_deptlist.hideColumn(1)
        self.treeWidget_recordslist.hideColumn(0)
        self.get_dept_detail()
        self.get_eq_detail()

    def get_eq_detail(self):
        self.treeWidget_equuiplist.clear()
        key_dict = dict()
        if self.deptid != '':
            key_dict['deptid'] = self.deptid
        if self.eqtype != -1:
            key_dict['eqtype'] = self.eqtype

        res = self.EC.get_data(0, False, *VALUES_TUPLE_EQ, **key_dict)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_equuiplist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['eqno'])
            qtreeitem.setText(2, item['eqname'])
            qtreeitem.setText(3, item['instposition'])
        for i in range(1, 4):
            self.treeWidget_equuiplist.resizeColumnToContents(i)

    def get_dept_detail(self):
        self.treeWidget_deptlist.clear()
        all_dept = QTreeWidgetItem(self.treeWidget_deptlist)
        all_dept.setText(0, "全部部门")
        all_dept.setText(1, "")
        self.treeWidget_deptlist.expandAll()
        res = self.EC.get_data(0, False, *VALUES_TUPLE_DP).distinct()
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(all_dept)
            qtreeitem.setText(0, item['deptname'])
            qtreeitem.setText(1, item['deptid'])
        self.treeWidget_deptlist.resizeColumnToContents(0)

    def get_generalrecors_note(self):
        self.treeWidget_recordslist.clear()
        index = self.tabWidget.currentIndex()
        key_dict = {
            'eqno': self.eqno,
            'status': index,
        }
        res = self.EC.get_data(5, False, *VALUES_TUPLE_RECORDS, **key_dict)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_recordslist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['formname'])
            qtreeitem.setText(
                2, item['createtime'].strftime('%Y-%m-%d %H:%M')
                if type(item['createtime']) is datetime.datetime else '')
            qtreeitem.setText(3, item['creatorid'] + ' ' + item['creatorname'])
        for i in range(1, 4):
            self.treeWidget_recordslist.resizeColumnToContents(i)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_equuiplist_itemDoubleClicked(self, qtreeitem, p_int):
        self.eqno = qtreeitem.text(1)
        self.get_generalrecors_note()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_deptlist_itemDoubleClicked(self, qtreeitem, p_int):
        self.deptid = qtreeitem.text(1)
        self.get_eq_detail()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_equiplist_itemDoubleClicked(self, qtreeitem, p_int):
        self.eqid = qtreeitem.text(0)
        self.get_generalrecors_note()

    @pyqtSlot(int)
    def on_toolBox_currentChanged(self, p_int):
        current_tool = getattr(self, 'page_' + str(p_int))
        current_tool.setLayout(self.gridLayout_3)
        self.eqtype = p_int - 1
        self.get_eq_detail()

    @pyqtSlot(int)
    def on_tabWidget_currentChanged(self, p_int):
        current_tool = getattr(self, 'tab_' + str(p_int))
        current_tool.setLayout(self.gridLayout_2)
        self.get_generalrecors_note()

    @pyqtSlot(QPoint)
    def on_treeWidget_recordslist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        sender_widget = self.sender()
        current_item = sender_widget.currentItem()
        index = self.tabWidget.currentIndex()
        menu = QMenu()
        button1 = menu.addAction("增加一般记录")
        button2 = menu.addAction("修改一般记录")
        button3 = menu.addAction("删除一般记录")
        menu.addSeparator()
        button4 = menu.addAction("提交完成")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if action == button1:
            if self.eqno != '':
                detail = SelectGeneralRecordsModule(self)
                detail.accepted.connect(self.get_generalrecors_note)
                detail.selected.connect(self.new_general_records)
                detail.show()
        elif action == button2:
            if current_item is not None and index == 0:
                id = int(current_item.text(0))
                detail = GeneralRecordModule(id, self)
                detail.accepted.connect(self.get_generalrecors_note)
                detail.show()
        elif action == button3:
            if current_item is not None:
                id = int(current_item.text(0))
                condition = {'autoid': id}
                self.EC.delete_data(5, condition)
                self.get_generalrecors_note()
        elif action == button4:
            if current_item is not None and index == 0:
                id = int(current_item.text(0))
                condition = {'autoid': id}
                kwargs = {'status': 1}
                self.EC.update_data(5, condition, **kwargs)
                self.get_generalrecors_note()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_recordslist_itemDoubleClicked(self, qtreeitem, p_int):
        id = int(qtreeitem.text(0))
        detail = GeneralRecordModule(id, self)
        detail.accepted.connect(self.get_generalrecors_note)
        detail.show()

    def new_general_records(self, id_tuple):
        if len(id_tuple) == 0:
            return
        else:
            key_dict = dict()
            key_dict['autoid__in'] = id_tuple
            res = self.SC.get_selfdefinedformat(False, *VALUES_TUPLE_SD,
                                                **key_dict)
            for item in res:
                kwargs = {
                    'eqno': self.eqno,
                    'creatorid': user.user_id,
                    'creatorname': user.user_name,
                    'formname': item['formatname'],
                    'kind': item['kind'],
                    'subkind': item['subkind'],
                    'format': item['format'],
                    'createtime': user.now_time
                }
                self.EC.update_data(5, **kwargs)
class AuxiliaryRecordModule(QWidget, Ui_Form):
    def __init__(self, kind, parent=None):
        super(AuxiliaryRecordModule, self).__init__(parent)
        self.setupUi(self)
        if kind == 0:
            index = '12'
        elif kind == 1:
            index = '25'
        elif kind == 2:
            index = '32'
        else:
            index = '-1'
        if index not in user.powers:
            self.close()
        if user.powers[index] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers[index])

        if self.power[1] == '0':
            self.pushButton_accept.setEnabled(False)
            self.pushButton_cancel.setEnabled(False)
        self.kind = kind
        self.year = user.NIAN
        self.month = user.YUE
        self.docid = 0
        self.current_content = QWidget()
        self.AC = AuxiliaryRecordController()
        self.SC = SelfdefinedformatController()
        self.treeWidget_itemlist.hideColumn(0)
        self.treeWidget_itemlist.hideColumn(4)
        self.get_year_list()

    def get_year_list(self):
        key_dict = {'deptid': user.dept_id}
        res = self.AC.get_data(0, True, *VALUES_TUPLE_YEAR, **key_dict).\
            annotate(Min('createdate'))
        if len(res):
            self.comboBox_year.addItems(map(str, res))
        else:
            self.comboBox_year.addItem(user.NIAN)
        if self.comboBox_year.findText(user.NIAN, Qt.MatchExactly) == -1:
            self.comboBox_year.addItem(user.NIAN)
        self.comboBox_year.setCurrentText(user.NIAN)
        self.tabWidget_itemlist.setCurrentIndex(int(user.YUE) - 1)

    def get_item_list(self):
        self.treeWidget_itemlist.clear()
        key_dict = {
            'deptid': user.dept_id,
            'kind': self.kind,
            'createdate__year': self.year,
            'createdate__month': self.month
        }
        res = self.AC.get_data(0, False, *VALUES_TUPLE_ITEM, **key_dict)

        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_itemlist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['title'])
            qtreeitem.setText(
                2,
                str(item['createdate'])
                if type(item['createdate']) is datetime.date else '')
            qtreeitem.setText(3, item['creatorid'] + ' ' + item['creatorname'])
            qtreeitem.setText(4, str(item['sdid']))
        for i in range(1, 4):
            self.treeWidget_itemlist.resizeColumnToContents(i)

    @pyqtSlot(int)
    def on_tabWidget_itemlist_currentChanged(self, p_int):
        self.month = p_int + 1
        tab = getattr(self, 'tab_' + str(p_int))
        tab.setLayout(self.gridLayout_2)
        self.get_item_list()

    @pyqtSlot(str)
    def on_comboBox_year_currentTextChanged(self, p_str):
        if p_str in ('', ' '):
            return
        self.year = int(p_str)
        self.get_item_list()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_itemlist_itemDoubleClicked(self, qtreeitem, p_int):
        if hasattr(self.current_content, 'flat'):
            if self.current_content.flat:
                dialog = MessageBox(self,
                                    title="提醒",
                                    text="文档尚未保存",
                                    informative="是否要保存文档",
                                    yes_text="保存",
                                    no_text="放弃保存")
                result = dialog.exec()
                if result == QMessageBox.Yes:
                    # 调用保存的槽函数
                    self.on_pushButton_accept_clicked()
        self.docid = int(qtreeitem.text(0))
        key_dict = {'autoid': self.docid}
        res = self.AC.get_data(0, True, *VALUES_TUPLE_CONTENT, **key_dict)
        if not len(res):
            return
        content = str(res[0])
        if not self.gridLayout_3.isEmpty():
            self.gridLayout_3.removeWidget(self.current_content)
            self.current_content.close()
        self.current_content = XMLReadWrite(self)
        self.current_content.openxml(content)
        self.gridLayout_3.addWidget(self.current_content)
        self.current_content.__setattr__('autoid', self.docid)

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if self.docid == 0:
            return
        if not hasattr(self.current_content, 'flat'):
            return
        newcontent = self.current_content.get_content()
        condition = {'autoid': self.docid}
        kwargs = {'ar': newcontent}
        self.AC.update_data(0, condition, **kwargs)
        self.current_content.flat = 0

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        if hasattr(self.current_content, 'flat'):
            self.current_content.flat = 0

    @pyqtSlot(QPoint)
    def on_treeWidget_itemlist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        sender_widget = self.sender()
        current_item = sender_widget.currentItem()
        menu = QMenu()
        button1 = menu.addAction("增加记录")
        button2 = menu.addAction("修改记录")
        button3 = menu.addAction("删除记录")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if action == button1:
            detail = SelectSelfDefineFormatModule(SD_TYPE[self.kind], self)
            detail.selected.connect(self.new_records)
            detail.accepted.connect(self.get_item_list)
            detail.show()
        elif action == button2:
            if current_item is None:
                return
            if hasattr(self.current_content, 'flat'):
                if self.current_content.flat:
                    dialog = MessageBox(self,
                                        title="提醒",
                                        text="文档尚未保存",
                                        informative="是否要保存文档",
                                        yes_text="保存",
                                        no_text="放弃保存")
                    result = dialog.exec()
                    if result == QMessageBox.Yes:
                        # 调用保存的槽函数
                        self.on_pushButton_accept_clicked()
            self.docid = int(current_item.text(0))
            key_dict = {'autoid': self.docid}
            res = self.AC.get_data(0, True, *VALUES_TUPLE_CONTENT, **key_dict)
            if not len(res):
                return
            content = str(res[0])
            if not self.gridLayout_3.isEmpty():
                self.gridLayout_3.removeWidget(self.current_content)
                self.current_content.close()
            self.current_content = XMLReadWrite(self)
            self.current_content.openxml(content)
            self.gridLayout_3.addWidget(self.current_content)
            self.current_content.__setattr__('autoid', self.docid)
        elif action == button3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.AC.delete_data(0, condition)
            self.get_item_list()

    def new_records(self, q_list):
        detail = {
            'kind': self.kind,
            'creatorid': user.user_id,
            'creatorname': user.user_name,
            'deptid': user.dept_id,
            'deptname': user.dept_name,
            'createdate': user.now_date
        }
        key_dict = {'autoid__in': q_list}
        sd_list = self.SC.get_data(0, **key_dict)
        for item in q_list:
            for sd in sd_list:
                if item == sd.autoid:
                    detail['sdid'] = item
                    detail['title'] = sd.formatname
                    detail['ar'] = sd.format
                    self.AC.update_data(0, **detail)
                    break
示例#15
0
class EditSelfDefineFormatDetailModule(QDialog, Ui_Dialog):
    def __init__(self, autoid=None, parent=None):
        super(EditSelfDefineFormatDetailModule, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlag(Qt.WindowMinMaxButtonsHint)
        if '3' not in user.powers:
            self.close()
        if user.powers['3'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['3'])
        if self.power[1] == '0':
            self.pushButton_accept.setEnabled(False)
            self.pushButton_close.setEnabled(False)

        self.autoid = autoid
        self.detail = QWidget()
        self.dom = QDomDocument()
        self.current_widget = QWidget()
        self.nodelist = None
        self.SC = SelfdefinedformatController()
        self.ori_detail = {}
        self.new_detail = {}
        self.format_content = '<?xml version="1.0"?><GMPPaper />'
        self.current_content = XMLReadWrite()
        self.current_elemnt = None
        res = self.get_detail()
        self.set_kind()
        self.set_subkind()
        if res:
            self.set_formtype()
        self.set_widgetlist()
        self.set_format()
        for i in range(0, 17):
            getattr(self, 'checkBox_' + str(2**i)).toggled.connect(
                self.on_formattype_toggled)

    def get_detail(self):
        if self.autoid is None:
            return False
        condition = {'autoid': self.autoid}
        res = self.SC.get_data(0, False, *VALUES_TUPLE_SD, **condition)
        if not len(res):
            return
        self.ori_detail = res[0]
        self.lineEdit_formatname.setText(self.ori_detail['formatname'])
        self.comboBox_orientation.setCurrentIndex(
            self.ori_detail['orientation'])
        self.checkBox_flag.setChecked(self.ori_detail['flag'])
        self.format_content = self.ori_detail['format']
        return True

    def set_kind(self):
        items = self.SC.get_data(0, True, *VALUES_TUPLE_KIND).distinct()
        if len(items):
            self.comboBox_kind.addItems(items)
        if len(self.ori_detail):
            self.comboBox_kind.setCurrentText(self.ori_detail['kind'])
        else:
            self.comboBox_kind.setCurrentText('')

    def set_subkind(self):
        items = self.SC.get_data(0, True, *VALUES_TUPLE_SUBKIND).distinct()
        if len(items):
            self.comboBox_subkind.addItems(items)
        if len(self.ori_detail):
            self.comboBox_subkind.setCurrentText(self.ori_detail['subkind'])
        else:
            self.comboBox_subkind.setCurrentText('')

    def set_formtype(self):
        if self.ori_detail['formtype'] == 0:
            return
        formtype = '{:017b}'.format(self.ori_detail['formtype'])
        for i in range(0, 17):
            getattr(self, 'checkBox_' + str(2**i)).setChecked(int(formtype[i]))

    def set_format(self):
        if not self.gridLayout_5.isEmpty():
            # self.gridLayout_5.removeWidget(self.current_content)
            self.format_content = self.dom.toString(-1)
            self.current_content.clear()
            self.current_content.scrollArea.setHidden(True)
        else:
            self.gridLayout_5.addWidget(self.current_content)

        self.current_content.openxml(self.format_content, True)
        self.current_content.scrollArea.setHidden(False)

    def set_widgetlist(self):
        self.treeWidget_widgetlist.clear()
        file = self.format_content
        qfile = QFile(file)
        self.dom = QDomDocument()
        # 找到文件,则设置引擎,否则向xml文件直接添加数据
        if qfile.open(QFile.ReadWrite | QFile.Text):
            self.dom.setContent(QFile)
            # self.file = QFile
        else:
            self.dom.setContent(file)
            # self.file = file
        if self.dom.isNull():
            return False
        # 获得根目录的元素,返回QDomElement    <GMPPaper>
        element = self.dom.documentElement()
        # 获得第一个子元素,返回QDomNode
        n = element.firstChild()
        # 如果没有读到文档结尾,而且没有出现错误
        self.nodelist = element.childNodes()
        line_number = 1
        for i in range(len(self.nodelist)):
            tag_name = self.nodelist.item(i).toElement().tagName()
            qtreeitem = QTreeWidgetItem(self.treeWidget_widgetlist)
            qtreeitem.setText(0, str(i))
            qtreeitem.setText(1, str(line_number))
            qtreeitem.setText(2, TAG_NAME_DICT[tag_name])
            if tag_name == "br":
                line_number += 1
        if qfile.isOpen():
            qfile.close()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_widgetlist_itemClicked(self, qtreeitem, p_int):
        index = int(qtreeitem.text(0))
        childrens = self.current_content.scrollAreaWidgetContents.children()
        item = childrens[index]
        item.setFocus()
        self.showsetting(item)

    @pyqtSlot(QMouseEvent)
    def mouseDoubleClickEvent(self, event):
        pos = event.pos()
        widget = self.childAt(pos)

        super(EditSelfDefineFormatDetailModule,
              self).mouseDoubleClickEvent(event)

    def mousePressEvent(self, event):
        pos = event.pos()
        widget = self.childAt(pos)
        self.showsetting(widget)

    def showsetting(self, widget):
        if not hasattr(widget, 'index') or self.current_widget == widget:
            self.current_elemnt = None
            return
        try:
            self.current_widget.leave()
        except AttributeError:
            if hasattr(self.current_widget.parent(), 'leave'):
                self.current_widget.parent().leave()
        except RuntimeError:
            pass
        self.current_widget = widget
        index = widget.index
        item = self.treeWidget_widgetlist.topLevelItem(index)
        if not self.gridLayout_6.isEmpty():
            self.gridLayout_6.removeWidget(self.detail)
            self.detail.close()
        self.treeWidget_widgetlist.setCurrentItem(item)
        self.current_elemnt = self.nodelist.item(index).toElement()
        if self.current_elemnt.tagName() not in WIDGET_TYPE:
            self.detail.close()
            return
        self.detail = WIDGET_TYPE[self.current_elemnt.tagName()](
            self.current_elemnt, self)
        self.detail.edited.connect(self.set_format)
        self.gridLayout_6.addWidget(self.detail)

    @pyqtSlot()
    def on_pushButton_1_clicked(self):
        new_element = self.dom.createElement("Title")
        new_element.setAttribute("width", 18)
        text = self.dom.createTextNode("新标题")
        new_element.appendChild(text)
        if self.current_elemnt is None or not hasattr(self.current_elemnt,
                                                      'tagName'):
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_2_clicked(self):
        new_element = self.dom.createElement("TextBox")
        new_element.setAttribute("width", 30)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_3_clicked(self):
        new_element = self.dom.createElement("Signature")
        new_element.setAttribute("width", 30)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_4_clicked(self):
        new_element = self.dom.createElement("Memo")
        new_element.setAttribute("width", 50)
        new_element.setAttribute("height", 3)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_5_clicked(self):
        new_element = self.dom.createElement("ComboBox")
        new_element.setAttribute("width", 30)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_6_clicked(self):
        new_element = self.dom.createElement("CheckBox")
        new_element.setAttribute("width", 30)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_7_clicked(self):
        new_element = self.dom.createElement("Box")
        new_element.setAttribute("width", 50)
        new_element.setAttribute("height", 3)
        new_element.setAttribute("PenWidth", 2)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_8_clicked(self):
        new_element = self.dom.createElement("Expr")
        new_element.setAttribute("width", 30)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_9_clicked(self):
        new_element = self.dom.createElement("br")
        # new_element.setAttribute("width", 20)
        if self.current_elemnt is None:
            self.dom.documentElement().appendChild(new_element)
        else:
            self.dom.documentElement().insertBefore(new_element,
                                                    self.current_elemnt)
        self.flush()

    @pyqtSlot()
    def on_pushButton_10_clicked(self):
        if self.current_widget is None or not hasattr(self.current_widget,
                                                      'index'):
            return
        index = self.current_widget.index
        self.nodelist.item(index)
        try:
            self.dom.documentElement().removeChild(self.current_elemnt)
        except TypeError:
            pass
        self.flush()

    def flush(self):
        # index = self.treeWidget_widgetlist.currentIndex().data(Qt.DisplayRole)
        current_item = self.treeWidget_widgetlist.currentItem()
        if current_item is None:
            index = None
        else:
            index = current_item.text(0)
        self.set_format()
        self.set_widgetlist()

        if index is not None:
            self.current_elemnt = self.nodelist.item(int(index))
            newindex = self.treeWidget_widgetlist.model().index(int(index), 0)
            try:
                self.current_content.scrollAreaWidgetContents.children()[int(
                    index)].setFocus()
            except IndexError:
                pass
        else:
            count = self.treeWidget_widgetlist.topLevelItemCount()
            self.current_elemnt = self.nodelist.item(count - 1)
            newindex = self.treeWidget_widgetlist.model().index(count - 1, 0)
            try:
                self.current_content.scrollAreaWidgetContents.children()[
                    count - 1].setFocus()
            except IndexError:
                pass
        self.treeWidget_widgetlist.setCurrentIndex(newindex)

    @pyqtSlot(str)
    def on_lineEdit_formatname_textChanged(self, p_str):
        try:
            if p_str != self.ori_detail['formatname']:
                self.new_detail['formatname'] = p_str
            else:
                try:
                    del self.new_detail['formatname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['formatname'] = p_str

    @pyqtSlot(str)
    def on_comboBox_kind_currentTextChanged(self, p_str):
        try:
            if p_str != self.ori_detail['kind']:
                self.new_detail['kind'] = p_str
            else:
                try:
                    del self.new_detail['kind']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['kind'] = p_str

    @pyqtSlot(str)
    def on_comboBox_subkind_currentTextChanged(self, p_str):
        try:
            if p_str != self.ori_detail['subkind']:
                self.new_detail['subkind'] = p_str
            else:
                try:
                    del self.new_detail['subkind']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['subkind'] = p_str

    @pyqtSlot(int)
    def on_comboBox_orientation_currentIndexChanged(self, p_int):
        try:
            if p_int != self.ori_detail['orientation']:
                self.new_detail['orientation'] = p_int
            else:
                try:
                    del self.new_detail['orientation']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['orientation'] = p_int

    @pyqtSlot(bool)
    def on_checkBox_flag_toggled(self, p_bool):
        p_int = 1 if p_bool else 0
        try:
            if p_int != self.ori_detail['flag']:
                self.new_detail['flag'] = p_int
            else:
                try:
                    del self.new_detail['flag']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['flag'] = p_int

    @pyqtSlot(bool)
    def on_formattype_toggled(self, p_bool):
        combobox = self.sender()
        try:
            num = int(
                combobox.objectName().split("_")[1]) * (1 if p_bool else -1)
        except (IndexError, ValueError):
            return
        if 'formtype' in self.new_detail:
            self.new_detail['formtype'] += num
        elif len(self.ori_detail):
            self.new_detail['formtype'] = self.ori_detail['formtype'] + num
        else:
            self.new_detail['formtype'] = num

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        xml = self.dom.toString(-1)
        self.new_detail['format'] = xml
        if self.autoid is not None:
            condition = {'autoid': self.autoid}
            self.SC.update_data(0, condition=condition, **self.new_detail)
        else:
            self.SC.update_data(0, **self.new_detail)
        self.accept()

    @pyqtSlot()
    def on_pushButton_view_clicked(self):
        detail = ViewFormat(self.dom, self)
        detail.show()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.close()
class LabrecordsController(object):
    def __init__(self):
        self.SFC = SelfdefinedformatController()
        self.EC = EquipmentController()
        self.SC = StuffController()
        self.PC = ProductController()

    def get_labrecord(self, flag=False, *args, **kwargs):
        return LabModel.get_labrecord(flag, *args, **kwargs)

    def get_labitem(self, flag=False, *args, **kwargs):
        return LabModel.get_labitem(flag, *args, **kwargs)

    def get_labimages(self, flag=False, kind=2, scid=0):
        values_list_rela = [
            'autoid', 'title', 'imageid', 'creatorid', 'creatorname',
            'createdate'
        ]
        key_dict_rela = {'kind': kind, 'scid': scid}
        res = ImagesModel.get_rela(flag, *values_list_rela, **key_dict_rela)
        if not len(res):
            return []
        img_list = []
        for item in res:
            img_list.append(item['imageid'])
        values_list_img = ['autoid', 'img', 'ext']
        key_dict_img = {'autoid__in': img_list}
        image_list = ImagesModel.get_img(flag, *values_list_img,
                                         **key_dict_img)
        for it in res:
            for value in image_list:
                if it['imageid'] == value['autoid']:
                    it.update({'image': value['img'], 'ext': value['ext']})
                    break
        return res

    def select_oricheckpaper(self, dictid, itemtype=0):
        if not dictid:
            return []
        if itemtype in (0, 1, 2):
            condition = {'stuffid': dictid}
            res = self.SC.get_data(0, True, *VALUES_TUPLE_ID, **condition)
            if not len(res):
                return []
            id = res[0]
        elif itemtype in (3, 4, 5, 6):
            condition = {'prodid': dictid}
            res = self.PC.get_data(1, True, *VALUES_TUPLE_ID, **condition)
            if not len(res):
                return []
            id = res[0]
        else:
            id = int(dictid)
        key_dict = {'dictid': id, 'itemtype': itemtype}
        sdfid_list = LabModel.get_oricheckpapersetting(True, *VALUES_TUPLE_SD,
                                                       **key_dict)
        if len(sdfid_list):
            values_list_sdf = ['autoid', 'kind', 'formatname']
            key_dict_sdf = {'autoid__in': sdfid_list}
            return self.SFC.get_selfdefinedformat(False, *values_list_sdf,
                                                  **key_dict_sdf)
        else:
            return []

    def get_selfdefineformat(self, flag=False, *args, **kwargs):
        return self.SFC.get_selfdefinedformat(False, *args, **kwargs)

    def get_oricheckpaper(self, flag=False, *args, **kwargs):
        return LabModel.get_oricheckpaper(flag, *args, **kwargs)

    def get_paperno(self, lrid):
        return LabModel.get_paperno(lrid)

    def update_labrecord(self, autoid=0, *args, **kwargs):
        return LabModel.update_labrecord(autoid, *args, **kwargs)

    def delete_labrecord(self, autoid=0, *args, **kwargs):
        return LabModel.delete_labrecord(autoid, *args, **kwargs)

    def update_labitem(self, autoid=0, *args, **kwargs):
        return LabModel.update_labitem(autoid, *args, **kwargs)

    def delete_labitem(self, autoid=0, *args, **kwargs):
        return LabModel.delete_labitem(autoid, *args, **kwargs)

    def update_labimages(self, relakwargs, imgkwargs, relaid=0, imgid=0):
        return ImagesModel.update_img(relakwargs, imgkwargs, relaid, imgid)

    def create_oricheckpaper(self, opid, op_detail, sdfid, sdf_detail):
        with transaction.atomic():
            p1 = transaction.savepoint()
            condition = {'autoid': sdfid}
            res = self.SFC.get_data(0, False, *VALUES_TUPLE_SDF, **condition)
            if not len(res):
                transaction.savepoint_rollback(p1)
                return False
            sdf_data = {
                'formname': res[0]['formatname'],
                'formcontent': res[0]['format']
            }
            sdf_data.update(sdf_detail)
            oripaper = self.update_data(2, **sdf_data)
            condition_2 = {'opid_id': opid}
            res_2 = self.get_data(8, False, **condition_2)
            for item in res_2:
                eqrun_data = {
                    'eqno': item.eqid.eqno,
                    'rtype': 1,
                    'pid': oripaper.autoid
                }
                eqrun_data.update(op_detail)
                self.EC.update_data(1, **eqrun_data)
            return oripaper

    def delete_labimages(self, relaid, imgid):
        return ImagesModel.delete_img(relaid, imgid)

    def delete_oricheckpaper(self, id):
        with transaction.atomic():
            p1 = transaction.savepoint()
            condition = {'autoid': id}
            self.delete_data(2, **condition)
            condition_eqrun = {'pid': id, 'rtype': 1}
            self.EC.delete_data(1, **condition_eqrun)
            return True

    def get_data(self, table_num: int, display_flag=False, *args, **kwargs):
        table_str = TABLE_SET[table_num][0]
        err_msg = "查询" + TABLE_SET[table_num][1]
        return LabModel.get_data(table_str, err_msg, display_flag, *args,
                                 **kwargs)

    def update_data(self, table_num: int, condition={}, *args, **kwargs):
        table_str = TABLE_SET[table_num][0]
        err_msg = "更新" + TABLE_SET[table_num][1]
        return LabModel.update_data(table_str, err_msg, condition, *args,
                                    **kwargs)

    def delete_data(self, table_num: int, condition={}, *args, **kwargs):
        table_str = TABLE_SET[table_num][0]
        err_msg = "删除" + TABLE_SET[table_num][1]
        return LabModel.delete_data(table_str, err_msg, condition, *args,
                                    **kwargs)

    def create_labrecord(self, checkitem_id, itemtype, date, *args, **kwargs):
        with transaction.atomic():
            p1 = transaction.savepoint()

            new_labrecor = self.update_data(0, **kwargs)
            lrid = new_labrecor.autoid
            key_dict_checkitem = {
                'stuffid': checkitem_id,
                'itemtype': itemtype
            }
            checkitems = self.get_data(4, False, *VALUES_TUPLE_CHECKITEM,
                                       **key_dict_checkitem)
            for item in checkitems:
                kwargs_checkitem = {
                    'lrid': lrid,
                    'seqid': item['seqid'],
                    'itemname': item['itemname'],
                    'kind': item['kind'],
                    'referencevalue': item['referencevalue'],
                    'labvalue': item['referencevalue'],
                    'putintype': item['putintype'],
                    'startdate': date,
                    'enddate': date,
                    'checked': 2
                }
                self.update_data(1, **kwargs_checkitem)
            return lrid

    def delete_labrecord_and_detail(self, lrid=0, *args, **kwargs):
        with transaction.atomic():
            p1 = transaction.savepoint()
            if lrid != 0:
                condition_lr = {'autoid': lrid}
                condition_detail = {'autoid': lrid}
            else:
                condition_lr = {'autoid__in': args}
                condition_detail = {'autoid__in': args}
            self.delete_data(0, condition_lr)
            self.delete_data(1, condition_detail)
            self.delete_data(2, condition_detail)

    def delete_sample_record(self, srid):
        with transaction.atomic():
            p1 = transaction.savepoint()
            condition = {'srid_id': srid}
            lrid_list = self.get_data(7, False, **condition).extra(
                select={
                    'lrid': 'Labrecords.autoid'
                },
                tables=['Labrecords'],
                where=[
                    'Labrecords.ciid=Observationrecords.autoid',
                    'Labrecords.labtype=6'
                ]).values_list(*VALUES_TUPLE_OB, flat=True)
            if len(lrid_list):
                self.delete_labrecord_and_detail(*lrid_list)
            condition = {'autoid': srid}
            self.delete_data(6, condition)
class ProductLineListModule(QWidget, Ui_Form):

    def __init__(self, parent=None):
        super(ProductLineListModule, self).__init__(parent)
        self.setupUi(self)

        if '5' not in user.powers:
            self.close()
        if user.powers['5'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['5'])
        self.treeWidget_productline.hideColumn(1)
        self.treeWidget_productline.hideColumn(2)
        self.treeWidget_productline.hideColumn(3)
        self.treeWidget_format.hideColumn(1)
        self.treeWidget_equipment.hideColumn(2)
        self.treeWidget_document.hideColumn(1)
        self.PC = ProductLineConroller()
        self.SC = SelfdefinedformatController()
        self.EC = EquipmentController()
        self.DC = DocumentController()
        self.get_selfdefineformat()
        self.get_equipment_list()
        self.get_document_list()
        self.get_product_line_list()

    def get_selfdefineformat(self):
        # self.treeWidget_format.clear()
        res = self.SC.get_data(0, False, *VALUES_TUPLE_SD).extra(
            where=['formtype&2']
        )
        if not len(res):
            return
        for item in res:
            kind = item['subkind']
            if kind != '':
                match_list = self.treeWidget_format.findItems(
                    kind, Qt.MatchExactly, 0
                )
                if len(match_list):
                    parent = match_list[0]
                else:
                    parent = QTreeWidgetItem(self.treeWidget_format)
                    parent.setText(0, kind)
                    parent.setText(1, '0')
            else:
                parent = self.treeWidget_format
            qtreeitem = QTreeWidgetItem(parent)
            qtreeitem.setText(0, item['formatname'])
            qtreeitem.setText(1, str(item['autoid']))

    def get_equipment_list(self):
        self.treeWidget_equipment.clear()
        res = self.EC.get_data(0, False, *VALUES_TUPLE_EQ)
        if not len(res):
            return
        for item in res:
            kind = item['deptname']
            if kind != '':
                match_list = self.treeWidget_equipment.findItems(
                    kind, Qt.MatchExactly, 0
                )
                if len(match_list):
                    parent = match_list[0]
                else:
                    parent = QTreeWidgetItem(self.treeWidget_equipment)
                    parent.setText(0, kind)
                    parent.setText(2, '0')
            else:
                parent = self.treeWidget_equipment
            qtreeitem = QTreeWidgetItem(parent)
            qtreeitem.setText(0, item['eqno'] + ' ' + item['eqname'])
            qtreeitem.setText(1, item['instposition'])
            qtreeitem.setText(2, str(item['autoid']))
        self.treeWidget_equipment.resizeColumnToContents(0)

    def get_document_list(self):
        self.treeWidget_document.clear()
        res = self.DC.get_data(0, False, *VALUES_TUPLE_DC)
        if not len(res):
            return
        for item in res:
            kind = item['kind']
            if kind != '':
                match_list = self.treeWidget_document.findItems(
                    kind, Qt.MatchExactly, 0
                )
                if len(match_list):
                    parent = match_list[0]
                else:
                    parent = QTreeWidgetItem(self.treeWidget_document)
                    parent.setText(0, kind)
                    parent.setText(1, '0')
            else:
                parent = self.treeWidget_document
            qtreeitem = QTreeWidgetItem(parent)
            qtreeitem.setText(0, item['docno'] + ' ' + item['title'])
            qtreeitem.setText(1, str(item['autoid']))

    def get_product_line_list(self):
        # 第三列位当前行的类型
        # -1:种类
        # 0:生产线名
        # 1:岗位名
        # 2:生产文档;3:岗位设备;4:操作文档
        self.treeWidget_productline.clear()
        res = self.PC.get_data(0, False, *VALUES_TUPLE_PL)
        if not len(res):
            return
        for item in res:
            kind = item['kind']
            if kind != '':
                match_list = self.treeWidget_productline.findItems(
                    kind, Qt.MatchExactly, 0
                )
                if len(match_list):
                    parent = match_list[0]
                else:
                    parent = QTreeWidgetItem(self.treeWidget_productline)
                    parent.setText(0, kind)
                    parent.setText(1, '-1')
                    parent.setText(2, '-1')
            else:
                parent = self.treeWidget_productline
            qtreeitem = QTreeWidgetItem(parent)
            qtreeitem.setText(0, item['linename'])
            qtreeitem.setText(1, str(item['autoid']))
            qtreeitem.setText(2, '0')
            self.add_postname(item['autoid'], qtreeitem)

    @pyqtSlot(QPoint)
    def on_treeWidget_productline_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        current_item = self.treeWidget_productline.currentItem()
        menu = QMenu()
        button1 = menu.addAction("新增生产线")
        button2 = menu.addAction("修改生产线")
        button3 = menu.addAction("删除生产线")
        menu.addSeparator()
        button4 = menu.addAction("新增岗位")
        button5 = menu.addAction("修改岗位")
        button6 = menu.addAction("删除岗位")
        menu.addSeparator()
        button7 = menu.addAction("删除记录/设备/文档")
        global_pos = self.treeWidget_productline.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if action == button1:
            detail = EditProductLineDetailModule(parent=self)
            detail.accepted.connect(self.get_product_line_list)
            detail.show()
        elif action == button2:
            if current_item is None:
                return
            if current_item.text(2) != '0':
                return
            id = int(current_item.text(1))
            detail = EditProductLineDetailModule(id, self)
            detail.accepted.connect(self.get_product_line_list)
            detail.show()
        elif action == button3:
            if current_item is None or current_item.text(2) != '0':
                return
            id = int(current_item.text(1))
            condition = {'autoid': id}
            self.PC.delete_data(0, condition)
            self.get_product_line_list()
        elif action == button4:
            if current_item is None:
                return
            type = int(current_item.text(2))
            if type == 0:
                parent_item = current_item
                seqid = current_item.childCount()  + 1
                plid = int(current_item.text(1))
            elif type == 1:
                parent_item = current_item.parent()
                seqid = int(parent_item.text(3)) if parent_item.text(3) != '' \
                    else parent_item.childCount()  + 1
                plid = int(parent_item.text(1))
            else:
                return
            detail = EditWorkFlowDetailModule(
                plid=plid, seqid=seqid, parent=self
            )
            detail.accepted.connect(lambda :self.add_postname(plid, parent_item))
            detail.show()
        elif action == button5:
            if current_item is None:
                return
            if current_item.text(2) != '1':
                return
            parent_item = current_item.parent()
            plid = int(parent_item.text(1))
            id = int(current_item.text(1))
            detail = EditWorkFlowDetailModule(autoid=id, plid=plid, parent=self)
            detail.accepted.connect(lambda :self.add_postname(plid, parent_item))
            detail.show()
        elif action == button6:
            if current_item is None or current_item.text(2) != '1':
                return
            wfid = int(current_item.text(1))
            seqid = int(current_item.text(3))
            parent_item = current_item.parent()
            plid = int(parent_item.text(1))
            self.PC.delet_post(wfid, seqid)
            self.add_postname(plid, parent_item)
        elif action == button7:
            if current_item is None:
                return
            id = int(current_item.text(1))
            type = int(current_item.text(2))
            seqid = int(current_item.text(3))
            parent_item = current_item.parent()
            if parent_item is None:
                return
            wfid = int(parent_item.parent().text(1))
            if type not in (2, 3, 4) or id == 0:
                return
            condition = {'autoid': id}
            self.PC.delete_data(type+1, condition)
            condition_update = {'seqid__gt': seqid}
            detail = {'seqid': F('seqid')-1}
            self.PC.update_data(type+1, condition_update, **detail)
            getattr(self, FUN_LIST[type-1])(wfid, parent_item)

    @pyqtSlot(QDropEvent, QPoint)
    def on_treeWidget_productline_droped(self, event, pos):
        if self.power[1] == '0':
            return
        data = event.mimeData().data('application/x-qabstractitemmodeldatalist')
        data_items = decode_data(data)
        parent_item = self.treeWidget_productline.itemAt(pos)
        if parent_item.text(2) in ('-1', '0'):
            return

        from_tree = event.source()

        if from_tree == self.treeWidget_format:
            self.on_treeWidget_format_draged(data_items, parent_item)
        elif from_tree == self.treeWidget_equipment:
            self.on_treeWidget_equipment_draged(data_items, parent_item)
        elif from_tree == self.treeWidget_document:
            self.on_treeWidget_document_draged(data_items, parent_item)
        # 生产线自己内部调整位置
        elif from_tree == self.treeWidget_productline:
            self.on_treeWidget_productline_draged(data_items, parent_item)
        else:
            pass

    def add_postname(self, plid, parent_item):
        parent_item.takeChildren()
        condition = {'plid': plid}
        res = self.PC.get_data(1, False, *VALUES_TUPLE_WF, **condition)
        for item in res.order_by('seqid'):
            new_qtreeitem = QTreeWidgetItem(parent_item)
            new_qtreeitem.setText(0, item['postname'])
            new_qtreeitem.setText(1, str(item['autoid']))
            new_qtreeitem.setText(2, '1')
            new_qtreeitem.setText(3, str(item['seqid']))
            format_tree = QTreeWidgetItem(new_qtreeitem)
            format_tree.setText(0, "生产文档")
            format_tree.setText(1, "0")
            format_tree.setText(2, "2")
            format_tree.setText(3, "0")
            self.add_post_formats(item['autoid'], format_tree)
            eq_tree = QTreeWidgetItem(new_qtreeitem)
            eq_tree.setText(0, "岗位设备")
            eq_tree.setText(1, "0")
            eq_tree.setText(2, "3")
            eq_tree.setText(3, "0")
            self.add_post_equipments(item['autoid'], eq_tree)
            dc_tree = QTreeWidgetItem(new_qtreeitem)
            dc_tree.setText(0, "操作文档")
            dc_tree.setText(1, "0")
            dc_tree.setText(2, "4")
            dc_tree.setText(3, "0")
            self.add_post_documnets(item['autoid'], dc_tree)

    def add_post_formats(self, wfid, parent_item):
        parent_item.takeChildren()
        condition_fm = {'wfid_id': wfid}
        res = self.PC.get_data(3, False, **condition_fm)
        for item in res.order_by('seqid'):
            new_qtreeitem = QTreeWidgetItem(parent_item)
            try:
                if item.docid_id >=0:
                    new_qtreeitem.setText(0, item.docid.formatname)
                else:
                    new_qtreeitem.setText(0, GENERAL_DOC[item.docid_id])
            except ObjectDoesNotExist:
                new_qtreeitem.setText(0, "")
            new_qtreeitem.setText(1, str(item.autoid))
            new_qtreeitem.setText(2, "2")
            new_qtreeitem.setText(3, str(item.seqid))

    def add_post_equipments(self, wfid, parent_item):
        parent_item.takeChildren()
        condition_eq = {'wfid_id': wfid}
        res = self.PC.get_data(4, False, **condition_eq)
        for item in res.order_by('seqid'):
            new_qtreeitem = QTreeWidgetItem(parent_item)
            try:
                new_qtreeitem.setText(0,
                                      item.eqid.eqno + ' ' + item.eqid.eqname)
            except ObjectDoesNotExist:
                new_qtreeitem.setText(0, '')
            new_qtreeitem.setText(1, str(item.autoid))
            new_qtreeitem.setText(2, "3")
            new_qtreeitem.setText(3, str(item.seqid))

    def add_post_documnets(self, wfid, parent_item):
        parent_item.takeChildren()
        condition_dc = {'wfid_id': wfid}
        res = self.PC.get_data(5, False, **condition_dc)
        for item in res.order_by('seqid'):
            new_qtreeitem = QTreeWidgetItem(parent_item)
            try:
                new_qtreeitem.setText(
                    0, item.docid.docno + ' ' + item.docid.title
                )
            except ObjectDoesNotExist:
                new_qtreeitem.setText(0, '')
            new_qtreeitem.setText(1, str(item.autoid))
            new_qtreeitem.setText(2, "4")
            new_qtreeitem.setText(3, str(item.seqid))

    def on_treeWidget_format_draged(self, data, receive_item):
        if self.power[1] == '0':
            return
        # drop_autoid = int(data[1][0])
        qtreeitem = self.treeWidget_format.currentItem()
        drop_autoid = int(qtreeitem.text(1))
        if receive_item.text(2) != '2' or drop_autoid == 0:
            return
        if receive_item.text(1) == '0':
            # 文档直接拖到了"生产文档"上,则新记录放在最后的位置上
            wfid = int(receive_item.parent().text(1))
            seqid = int(receive_item.childCount() + 1)
            parent_item = receive_item
        else:
            # 文档直接拖到了具体的文档上,则新记录占用这个位置,且后面的记录seqid+1
            wfid = int(receive_item.parent().parent().text(1))
            seqid = int(receive_item.text(3))
            condition = {'wfid_id': wfid, 'seqid__gte': seqid}
            detail = {'seqid': F('seqid') + 1}
            parent_item = receive_item.parent()
            self.PC.update_data(3, condition, **detail)
        kwargs = {
            'wfid_id': wfid,
            'seqid': seqid,
            'docid_id': drop_autoid
        }
        self.PC.update_data(3, **kwargs)
        self.add_post_formats(wfid, parent_item)

    def on_treeWidget_equipment_draged(self, data, receive_item):
        if self.power[1] == '0':
            return
        # drop_autoid = int(data[2][0])
        qtreeitem = self.treeWidget_equipment.currentItem()
        drop_autoid = int(qtreeitem.text(2))
        if receive_item.text(2) != '3' or drop_autoid == 0:
            return
        if receive_item.text(1) == '0':
            # 文档直接拖到了"生产文档"上,则新记录放在最后的位置上
            wfid = int(receive_item.parent().text(1))
            seqid = int(receive_item.childCount() + 1)
            parent_item = receive_item
        else:
            # 文档直接拖到了具体的文档上,则新记录占用这个位置,且后面的记录seqid+1
            wfid = int(receive_item.parent().parent().text(1))
            seqid = int(receive_item.text(3))
            condition = {'wfid_id': wfid, 'seqid__gte': seqid}
            detail = {'seqid': F('seqid') + 1}
            parent_item = receive_item.parent()
            self.PC.update_data(5, condition, **detail)
        kwargs = {
            'wfid_id': wfid,
            'seqid': seqid,
            'eqid_id': drop_autoid
        }
        self.PC.update_data(4, **kwargs)
        self.add_post_equipments(wfid, parent_item)

    def on_treeWidget_document_draged(self, data, receive_item):
        if self.power[1] == '0':
            return
        # drop_autoid = int(data[1][0])
        qtreeitem = self.treeWidget_document.currentItem()
        drop_autoid = int(qtreeitem.text(1))
        if receive_item.text(2) != '4' or drop_autoid == 0:
            return
        if receive_item.text(1) == '0':
            # 文档直接拖到了"生产文档"上,则新记录放在最后的位置上
            wfid = int(receive_item.parent().text(1))
            seqid = int(receive_item.childCount() + 1)
            parent_item = receive_item
        else:
            # 文档直接拖到了具体的文档上,则新记录占用这个位置,且后面的记录seqid+1
            wfid = int(receive_item.parent().parent().text(1))
            seqid = int(receive_item.text(3))
            condition = {'wfid_id': wfid, 'seqid__gte': seqid}
            detail = {'seqid': F('seqid') + 1}
            parent_item = receive_item.parent()
            self.PC.update_data(5, condition, **detail)
        kwargs = {
            'wfid_id': wfid,
            'seqid': seqid,
            'docid_id': drop_autoid
        }
        self.PC.update_data(5, **kwargs)
        self.add_post_documnets(wfid, parent_item)

    def on_treeWidget_productline_draged(self, data, receive_item):
        if self.power[1] == '0':
            return
        # drop_autoid = int(data[1][0])
        # drop_type = int(data[2][0])
        # drop_seqid = int(data[3][0])
        # receive_id = receive_item.text(1)
        qtreeitem = self.treeWidget_productline.currentItem()
        drop_autoid = int(qtreeitem.text(1))
        drop_type = int(qtreeitem.text(2))
        drop_seqid = int(qtreeitem.text(3))
        receive_id = receive_item.text(1)
        if drop_type in (2, 3, 4):
            # 拖拽的项目类型不一致
            if drop_type != int(receive_item.text(2)):
                return
            # 拖拽的是生产文档
            if receive_id == '0':
                # 接收的是"生产文档"
                parent_item = receive_item
                wfid = int(receive_item.parent().text(1))
                condition_other = {'wfid_id': wfid, 'seqid__gt': drop_seqid}
                detail_other = {'seqid': F('seqid') - 1}
                new_seqid = receive_item.childCount()
                condition_this = {'autoid': drop_autoid}
                detail_this = {'seqid': new_seqid}
            else:
                # 接收的是生产记录
                parent_item = receive_item.parent()
                wfid = int(receive_item.parent().parent().text(1))
                receive_seqid = int(receive_item.text(3))
                condition_other = {
                    'wfid_id': wfid,
                    'seqid__gte': receive_seqid,
                    'seqid__lt': drop_seqid
                }
                detail_other = {'seqid': F('seqid') + 1}
                condition_this = {'autoid': drop_autoid}
                detail_this = {'seqid': receive_seqid}
            self.PC.update_data(drop_type+1, condition_other, **detail_other)
            self.PC.update_data(drop_type+1, condition_this, **detail_this)
            getattr(self, FUN_LIST[drop_type-1])(wfid, parent_item)
        # 拖拽的是岗位
        elif drop_type == 1:
            receive_type = receive_item.text(2)
            # 接收的是"生产线名称"
            if receive_type == '0':
                parent_item = receive_item
                plid = int(parent_item.text(1))
                condition_other = {'plid': plid, 'seqid__gt': drop_seqid}
                detail_other = {'seqid': F('seqid') - 1}
                new_seqid = receive_item.childCount()
                condition_this = {'autoid': drop_autoid}
                detail_this = {'seqid': new_seqid}
            # 接收的是岗位名
            elif receive_type == '1':

                parent_item = receive_item.parent()
                plid = int(parent_item.text(1))
                receive_seqid = int(receive_item.text(3))
                condition_other = {
                    'plid': plid,
                    'seqid__gte': receive_seqid,
                    'seqid__lt': drop_seqid
                }
                detail_other = {'seqid': F('seqid') + 1}
                condition_this = {'autoid': drop_autoid}
                detail_this = {'seqid': receive_seqid}
            else:
                return
            self.PC.update_data(1, condition_other, **detail_other)
            self.PC.update_data(1, condition_this, **detail_this)
            getattr(self, FUN_LIST[drop_type - 1])(plid, parent_item)
        else:
            pass
 def __init__(self):
     self.SFC = SelfdefinedformatController()
     self.EC = EquipmentController()
     self.SC = StuffController()
     self.PC = ProductController()