Beispiel #1
0
 def __init__(self):
     self.SC = StuffController()
     self.SLC = SaleController()
     self.SP = SupplyerController()
     self.WM = WarehouseModel()
     self.WC = WorkshopController()
     self.PC = ProductController()
Beispiel #2
0
    def __init__(self, ppid, parent=None):
        super(QrcodelistModule, self).__init__(parent)
        self.setupUi(self)

        self.ppid = ppid
        self.WC = WorkshopController()

        # 获取现有的二维码列表
        self.get_qrcode_list()
    def __init__(self, ppid, parent=None):
        # b,m,s分别对应大、中、小包装
        # num 为已经扫描的个数
        # amount 为包装比例
        super(ScanqrcodeModule, self).__init__(parent)
        self.setupUi(self)
        self.PC = ProductController()
        self.WC = WorkshopController()
        self.tts = Tts()
        self.tts.start()
        self.ppid = ppid

        self.batchno = ''
        self.commonname = ''
        self.allowno = ''
        # 上级码的对象
        self.lpid = None
        self.bpid = None
        self.mpid = None
        # 扫了多少个码
        self.scan_num = [0, 0, 0, 0]
        # 一箱对应的码数量
        self.lv_amount = [0, 0, 0, 0]
        # 各级码的出现次数
        self.lpsum = 0
        self.bpsum = 0
        self.mpsum = 0
        self.widget_list = [
            self.lineEdit_lpqrcode, self.lineEdit_bpqrcode,
            self.lineEdit_mpqrcode, self.lineEdit_spqrcode
        ]
        self.use_lv_qrcode = []

        qrtype = self.get_prod_packagelv()
        self.qrcode = AboxQrcode(
            qrtype, self.lv_amount[1], self.lv_amount[2],
            self.lv_amount[3]
        )

        q_list = ('lp', 'bp', 'mp', 'sp')
        qrtype = '{: 04b}'.format(qrtype)

        self.mpsum = self.lv_amount[3] if qrtype[3] == '1' else 1
        self.bpsum = self.mpsum * (self.lv_amount[2] if qrtype[2] == '1' else 1)
        self.lpsum = self.bpsum * (self.lv_amount[1] if qrtype[1] == '1' else 1)

        for i in (3, 2, 1, 0):
            if qrtype[i] == '1':
                self.use_lv_qrcode.append(q_list[i])
            else:
                self.widget_list[i].setEnabled(False)
                self.widget_list.pop(i)
                self.scan_num.pop(i)
                self.lv_amount.pop(i)
        self.use_lv_qrcode.reverse()
        self.widget_list[0].setFocus()
    def __init__(self, parent=None):
        super(PreProdputinlistModule, self).__init__(parent)
        self.setupUi(self)
        if '36' not in user.powers:
            self.close()
        if user.powers['36'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['36'])

        self.PC = ProductController()
        self.WC = WorkshopController()
        self.LC = LabrecordsController()
        # 获取当前状态的批生产记录
        self.get_proddetail()
Beispiel #5
0
 def __init__(self, autoid, parent=None):
     super(HomePageModule, self).__init__(parent)
     self.setupUi(self)
     self.autoid=autoid
     self.current_img = object
     self.current_page = object
     self.PC = ProductController()
     self.WC = WorkshopController()
     self.IC = ImageController()
     # 自动缩放
     self.label_image.setScaledContents(True)
     self.get_detail()
     self.get_images()
     self.scrollArea.setVisible(False)
     self.groupBox.setVisible(False)
Beispiel #6
0
    def __init__(self, parent=None):
        super(QrcodeinputModule, self).__init__(parent)
        self.setupUi(self)
        if '58' not in user.powers:
            self.close()
        if user.powers['58'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['58'])

        self.WC = WorkshopController()
        self.PC = ProductController()
        self.SC = SystemController()
        self.prodlist = dict()
        # 获取二维码信息
        self.get_product_list()
 def end_linepost(self, condition, ppid, detail):
     with transaction.atomic():
         p1 = transaction.savepoint()
         self.update_data(0, condition, detail)
         res = self.get_data(0, False, ppid=ppid)
         flag = 1
         for item in res:
             if item.status != 2:
                 flag = 0
                 break
         if flag == 1:
             PC = WorkshopController()
             condition = {'autoid': ppid}
             detail = {'status': 3}
             PC.update_data(2, condition, **detail)
         return True
Beispiel #8
0
 def __init__(self, autoid, parent=None):
     super(SaleOrderModule, self).__init__(parent)
     self.setupUi(self)
     self.SC = SaleController()
     self.WC = WarehouseController()
     self.WSC = WorkshopController()
     self.autoid = autoid
     self.get_order_list()
     self.get_product_list()
    def __init__(self, autoid: int = 0, ppid: int = 0, parent=None):
        super(PreProdPutInModule, self).__init__(parent)
        self.setupUi(self)
        self.ppid = ppid
        self.autoid = autoid
        self.content = decimal.Decimal('-1')
        self.water = decimal.Decimal('-1')
        self.rdensity = decimal.Decimal('-1')
        self.impurity = decimal.Decimal('-1')
        self.lrid = 0
        self.checkdate = user.now_date
        # self.units = set()
        self.unit = ''
        self.cunit = '%'
        self.expireddays = 730
        self.countercheckdays = 365
        self.WC = WorkshopController()
        self.LC = LabrecordsController()
        self.PC = ProductController()
        self.SC = StuffController()
        self.product_detail = dict()
        self.ori_detail = dict()
        self.new_detail = dict()

        # 把autoid和ppid补全
        self.get_autoid_or_ppid()
        # 获取入库位置的下拉选项
        self.get_postiton()

        # 整箱数量的校验器
        self.set_valitor(self.lineEdit_amount, 0)
        # 获取产品信息
        self.get_productdetail()
        # 设置含量单位、复检日期、有效期等参数
        self.basicdetail()

        # 获取报告书的状态和编号
        self.get_labdetail()
        # 获取入库信息
        self.get_putinnote()
 def __init__(self, autoid:int=0, ppid: int=0, parent=None):
     super(ProductputinModule, self).__init__(parent)
     self.setupUi(self)
     self.ppid = ppid
     self.autoid = autoid
     self.bpamount = decimal.Decimal('0')
     self.mpamount = decimal.Decimal('0')
     self.spamount = decimal.Decimal('0')
     self.a_box_samount = decimal.Decimal('0')
     self.oddments_list = []
     self.units = set()
     self.WC = WorkshopController()
     self.LC = LabrecordsController()
     self.PC = ProductController()
     self.product_detail = dict()
     self.ori_detail = dict()
     self.new_detail = dict()
     if not self.ppid and not self.autoid:
         return
     # 把autoid和ppid补全
     self.get_autoid_or_ppid()
     # 获取产品信息
     self.get_productdetail()
     # 设置比例、一箱数量等参数
     self.basicdetail()
     # 获取寄库和入库位置的下拉选项
     self.get_postiton()
     # 获取报告书的状态和编号
     self.get_labdetail()
     # 获取入库信息
     self.get_putinnote()
     # 获取零头领取信息
     self.get_oddment()
     # 整箱数量的校验器
     self.set_valitor(self.lineEdit_amount, 0)
     # 零头数量的校验器
     self.set_valitor(self.lineEdit_oddment, 0, self.a_box_samount)
     self.set_total_amount()
Beispiel #11
0
 def __init__(self, parent=None):
     super(SaleOrderListModule, self).__init__(parent)
     self.setupUi(self)
     if '53' not in user.powers:
         self.close()
     if user.powers['53'] == 0:
         self.close()
     self.power = '{:03b}'.format(user.powers['53'])
     self.SC = SaleController()
     self.WC = WarehouseController()
     self.WSC = WorkshopController()
     self.groupBox.setVisible(False)
     self.snid = 0
     self.get_order_list()
class PreProdPutInModule(QWidget, Ui_Form):
    accepted = pyqtSignal()

    def __init__(self, autoid: int = 0, ppid: int = 0, parent=None):
        super(PreProdPutInModule, self).__init__(parent)
        self.setupUi(self)
        self.ppid = ppid
        self.autoid = autoid
        self.content = decimal.Decimal('-1')
        self.water = decimal.Decimal('-1')
        self.rdensity = decimal.Decimal('-1')
        self.impurity = decimal.Decimal('-1')
        self.lrid = 0
        self.checkdate = user.now_date
        # self.units = set()
        self.unit = ''
        self.cunit = '%'
        self.expireddays = 730
        self.countercheckdays = 365
        self.WC = WorkshopController()
        self.LC = LabrecordsController()
        self.PC = ProductController()
        self.SC = StuffController()
        self.product_detail = dict()
        self.ori_detail = dict()
        self.new_detail = dict()

        # 把autoid和ppid补全
        self.get_autoid_or_ppid()
        # 获取入库位置的下拉选项
        self.get_postiton()

        # 整箱数量的校验器
        self.set_valitor(self.lineEdit_amount, 0)
        # 获取产品信息
        self.get_productdetail()
        # 设置含量单位、复检日期、有效期等参数
        self.basicdetail()

        # 获取报告书的状态和编号
        self.get_labdetail()
        # 获取入库信息
        self.get_putinnote()

    def get_autoid_or_ppid(self):
        values_list = ('autoid', 'ppid')
        if self.autoid:
            key_dict = {'autoid': self.autoid}
        else:
            key_dict = {'ppid': self.ppid}
        res = self.WC.get_productputinnote(False, *values_list, **key_dict)
        if not len(res):
            return
        if self.autoid:
            self.ppidid = res[0]['ppid']
        else:
            self.autoid = res[0]['autoid']

    def set_valitor(self, widget, bottom=0, top=0):
        intvalitor = QIntValidator()
        intvalitor.setBottom(bottom)
        if top != 0:
            intvalitor.setTop(top)
        widget.setValidator(intvalitor)

    def get_postiton(self):

        key_dict_ws = {'ppid': self.ppid}
        ws_list = self.WC.get_productputinnote(True, *VALUES_LIST_WS,
                                               **key_dict_ws)
        if not len(ws_list):
            return
        warehouseid = ws_list[0]

        values_list_positon = ('position', )
        key_dict_position = {'warehouseid': warehouseid}
        pos_list = self.WC.get_productputinnote(True, *values_list_positon,
                                                **key_dict_position)
        if len(pos_list):
            self.comboBox_piposition.addItems(pos_list.distinct())

    def get_productdetail(self):

        key_dict = {'autoid': self.ppid}
        res = self.PC.get_producingplan(False, *VALUES_LIST_PROD, **key_dict)
        if len(res) != 1:
            return
        self.product_detail = res[0]
        self.label_product.setText(
            self.product_detail['prodid'] + ' ' + \
            self.product_detail['prodname']
        )
        self.label_spec.setText(self.product_detail['spec'])
        self.label_package.setText(self.product_detail['package'])
        self.label_unit.setText(self.product_detail['basicunit'])

    def basicdetail(self):
        if not len(self.product_detail):
            return
        stuffid = self.product_detail['prodid']
        stuffname = self.product_detail['prodname']
        key_dict = {'stuffid': stuffid, 'stuffname': stuffname}
        res = self.SC.get_stuffdict(False, *VALUES_TUPLE_STUFF, **key_dict)
        if not len(res):
            return
        self.cunit = res[0]['cunit']
        self.expireddays = res[0]['expireddays']
        self.countercheckdays = res[0]['countercheckdays']
        self.label_contentunit.setText(self.cunit)

    def get_labdetail(self):
        values_list = ('autoid', 'paperno', 'status', 'reportdate')
        key_dict = {'labtype': 2, 'ciid': self.ppid}
        res = self.LC.get_labrecord(False, *values_list, **key_dict)
        if not len(res):
            return
        # 选择最后一条符合条件的成品报告
        detail = res.order_by('-autoid')[0]
        self.lrid = detail['autoid']
        self.checkdate = detail['reportdate']
        self.label_reportpaperno.setText(detail['paperno'])
        self.label_checkstatus.setText(CHECK_STATUS[detail['status']])

    def get_putinnote(self):

        key_dict = {'autoid': self.autoid}
        res = self.WC.get_productputinnote(False, *VALUES_TUPLE_PUTIN,
                                           **key_dict)
        if not len(res):
            return
        # 选择第一条
        self.ori_detail = res[0]

        self.label_warehouse.setText(self.ori_detail['warehouseid'] + ' ' +
                                     self.ori_detail['warehousename'])
        self.comboBox_piposition.setCurrentText(self.ori_detail['position'])
        self.pushButton_applyer.setText(self.ori_detail['piapplyerid'] + ' ' +
                                        self.ori_detail['piapplyername'])
        self.pushButton_qa.setSign(
            True,
            self.ori_detail['piqaid'] + ' ' + self.ori_detail['piqaname'])
        self.pushButton_piwsman.setSign(
            True, self.ori_detail['warehousemanid'] + ' ' +
            self.ori_detail['warehousemanname'])
        self.lineEdit_amount.setText(to_str(self.ori_detail['piamount']))

        if self.ori_detail['pistatus'] == 0:
            self.pushButton_accept.setVisible(True)
            self.pushButton_save.setVisible(True)
            self.pushButton_cancel.setVisible(False)
            self.pushButton_pi.setVisible(False)
        elif self.ori_detail['pistatus'] == 1:
            self.pushButton_accept.setVisible(False)
            self.pushButton_save.setVisible(False)
            self.pushButton_cancel.setVisible(True)
            self.pushButton_pi.setVisible(True)
        elif self.ori_detail['pistatus'] == 3:
            self.pushButton_accept.setVisible(False)
            self.pushButton_save.setVisible(False)
            self.pushButton_cancel.setVisible(False)
            self.pushButton_pi.setVisible(False)

    @pyqtSlot(str)
    def on_lineEdit_amount_textEdited(self, p_str):
        if p_str == '':
            amount = decimal.Decimal('0')
        else:
            amount = decimal.Decimal(p_str)
        try:
            if amount != self.ori_detail['piamount']:
                self.new_detail['piamount'] = amount
            else:
                try:
                    del self.new_detail['piamount']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piamount'] = amount

    @pyqtSlot(bool, str)
    def on_pushButton_qa_signChanged(self, p_bool, p_str):
        if p_bool:
            self.pushButton_accept.setEnabled(True)
            piqaid, piqaname = p_str.split(' ')
        else:
            self.pushButton_accept.setEnabled(False)
            piqaid, piqaname = ('', '')
        try:
            if piqaid != self.ori_detail['piqaid']:
                self.new_detail['piqaid'] = piqaid
                self.new_detail['piqaname'] = piqaname
            else:
                try:
                    del self.new_detail['piqaid']
                    del self.new_detail['piqaname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piqaid'] = piqaid
            self.new_detail['piqaname'] = piqaname

    @pyqtSlot(bool, str)
    def on_pushButton_applyer_signChanged(self, p_bool, p_str):
        if p_bool:
            piapplyerid, piapplyername = p_str.split(' ')
        else:
            piapplyerid, piapplyername = ('', '')
        try:
            if piapplyerid != self.ori_detail['piapplyerid']:
                self.new_detail['piapplyerid'] = piapplyerid
                self.new_detail['piapplyername'] = piapplyername
            else:
                try:
                    del self.new_detail['piapplyerid']
                    del self.new_detail['piapplyername']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piapplyerid'] = piapplyerid
            self.new_detail['piapplyername'] = piapplyername

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

    @pyqtSlot()
    def on_pushButton_save_clicked(self):
        if self.has_changed():
            self.WC.update_productputinnote(self.autoid, **self.new_detail)

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if self.lineEdit_amount.text() in ('', '0'):
            msg = MessageBox(self, text="入库数量不能未空")
            msg.show()
            return
        if self.pushButton_applyer.text() in ('', ' '):
            self.pushButton_applyer.setSign(
                True, user.user_id + ' ' + user.user_name)
            self.new_detail['piapplyerid'] = user.user_id
            self.new_detail['piapplyername'] = user.user_name
            self.new_detail['pidate'] = user.now_date
        self.new_detail['pistatus'] = 1

        self.WC.update_productputinnote(self.autoid, **self.new_detail)
        realamount = decimal.Decimal(self.lineEdit_amount.text())
        detail = {'realamount': realamount}
        self.PC.update_producingplan(self.ppid, **detail)

        self.pushButton_save.setVisible(False)
        self.pushButton_accept.setVisible(False)
        self.pushButton_cancel.setVisible(True)
        self.pushButton_pi.setVisible(True)
        self.accepted.emit()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.new_detail['piapplyerid'] = ''
        self.new_detail['piapplyername'] = ''
        self.new_detail['pistatus'] = 0

        self.WC.update_productputinnote(self.autoid, **self.new_detail)

        self.pushButton_save.setVisible(True)
        self.pushButton_accept.setVisible(True)
        self.pushButton_cancel.setVisible(False)
        self.pushButton_pi.setVisible(False)
        self.accepted.emit()

    @pyqtSlot()
    def on_pushButton_pi_clicked(self):
        if self.label_checkstatus.text() != '检验合格':
            mesgbox = MessageBox(parent=self,
                                 title="提示",
                                 text="当前产品尚未检验合格无法入库")
            mesgbox.exec()
            return

        self.new_detail['warehousemanid'] = user.user_id
        self.new_detail['warehousemanname'] = user.user_name
        self.new_detail['pidate'] = user.now_date
        self.new_detail['pistatus'] = 3

        # 计算要入库的产品信息
        putin_msg = self.get_putin_msg()
        res = self.WC.update_preproductputinnote(self.autoid, putin_msg,
                                                 **self.new_detail)
        if not res:
            return
        self.pushButton_piwsman.setSign(True,
                                        user.user_id + ' ' + user.user_name)
        self.pushButton_save.setVisible(False)
        self.pushButton_accept.setVisible(False)
        self.pushButton_cancel.setVisible(False)
        self.pushButton_pi.setVisible(False)
        self.accepted.emit()

    def get_putin_msg(self):

        return_dict = self.product_detail
        return_dict['stuffid'] = return_dict.pop('prodid')
        return_dict['stuffname'] = return_dict.pop('prodname')
        return_dict['stuffkind'] = return_dict.pop('commonname')
        return_dict['ciid'] = self.autoid
        return_dict['pltype'] = 1
        return_dict['stufftype'] = 1
        return_dict['expireddate'] = self.product_detail['makedate'] + \
            datetime.timedelta(days=self.expireddays)
        return_dict['amount'] = decimal.Decimal(self.lineEdit_amount.text())
        return_dict['piamount'] = decimal.Decimal(self.lineEdit_amount.text())
        return_dict['position'] = self.comboBox_piposition.currentText()
        return_dict['checkindate'] = user.now_date
        return_dict['putindate'] = user.now_date
        return_dict['warehousemanid'] = user.user_id
        return_dict['warehousemanname'] = user.user_name
        return_dict['content'] = self.content
        return_dict['cunit'] = self.cunit
        return_dict['water'] = self.water
        return_dict['rdensity'] = self.rdensity
        return_dict['impurity'] = self.impurity
        return_dict['lrid'] = self.lrid
        return_dict['checkdate'] = self.checkdate
        return_dict['nextcheckdate'] = self.checkdate + \
            datetime.timedelta(days=self.countercheckdays)
        return_dict['deptid'] = self.ori_detail['warehouseid']
        return_dict['deptname'] = self.ori_detail['warehousename']
        return return_dict

    def has_changed(self):
        if not len(self.new_detail):
            return False
        if self.pushButton_applyer.text() in ('', ' '):
            self.pushButton_applyer.setSign(
                True, user.user_id + ' ' + user.user_name)
            self.new_detail['piapplyerid'] = user.user_id
            self.new_detail['piapplyername'] = user.user_name
        return True
class ProductputinModule(QWidget, Ui_Form):
    accepted = pyqtSignal()

    def __init__(self, autoid:int=0, ppid: int=0, parent=None):
        super(ProductputinModule, self).__init__(parent)
        self.setupUi(self)
        self.ppid = ppid
        self.autoid = autoid
        self.bpamount = decimal.Decimal('0')
        self.mpamount = decimal.Decimal('0')
        self.spamount = decimal.Decimal('0')
        self.a_box_samount = decimal.Decimal('0')
        self.oddments_list = []
        self.units = set()
        self.WC = WorkshopController()
        self.LC = LabrecordsController()
        self.PC = ProductController()
        self.product_detail = dict()
        self.ori_detail = dict()
        self.new_detail = dict()
        if not self.ppid and not self.autoid:
            return
        # 把autoid和ppid补全
        self.get_autoid_or_ppid()
        # 获取产品信息
        self.get_productdetail()
        # 设置比例、一箱数量等参数
        self.basicdetail()
        # 获取寄库和入库位置的下拉选项
        self.get_postiton()
        # 获取报告书的状态和编号
        self.get_labdetail()
        # 获取入库信息
        self.get_putinnote()
        # 获取零头领取信息
        self.get_oddment()
        # 整箱数量的校验器
        self.set_valitor(self.lineEdit_amount, 0)
        # 零头数量的校验器
        self.set_valitor(self.lineEdit_oddment, 0, self.a_box_samount)
        self.set_total_amount()

    def get_autoid_or_ppid(self):
        values_list = ('autoid', 'ppid')
        if self.autoid:
            key_dict = {'autoid': self.autoid}
        else:
            key_dict = {'ppid': self.ppid}
        res = self.WC.get_productputinnote(False, *values_list, **key_dict)
        if not len(res):
            return
        self.autoid = res[0]['autoid']
        self.ppid = res[0]['ppid']

    def set_valitor(self, widget, bottom=0, top=0):
        intvalitor = QIntValidator()
        intvalitor.setBottom(bottom)
        if top != 0:
            intvalitor.setTop(top)
        widget.setValidator(intvalitor)

    def get_postiton(self):
        values_list_ws = ("warehouseid",)
        key_dict_ws = {
            'ppid': self.ppid
        }
        ws_list = self.WC.get_productputinnote(
            True, *values_list_ws, **key_dict_ws
        )
        if not len(ws_list):
            return
        warehouseid = ws_list[0]

        values_list_dppositon = ('dpposition',)
        values_list_positon = ('position',)
        key_dict_position = {
            'warehouseid': warehouseid
        }
        dppos_list = self.WC.get_productputinnote(
            True, *values_list_dppositon, **key_dict_position)
        pos_list = self.WC.get_productputinnote(
            True, *values_list_positon, **key_dict_position)
        if len(dppos_list):
            self.comboBox_dpposition.addItems(dppos_list.distinct())
        if len(pos_list):
            self.comboBox_piposition.addItems(pos_list.distinct())

    def get_productdetail(self):
        VALUES_LIST = (
            "prodid", "prodname", "spec", "package", "bpamount", "bpunit",
            "mpamount", "mpunit", "spamount", "spunit", "lpunit"
        )
        key_dict = {
            'autoid': self.ppid
        }
        res = self.PC.get_producingplan(
            False, *VALUES_LIST, **key_dict
        )
        if len(res) != 1:
            return
        self.product_detail = res[0]
        self.label_product.setText(
            self.product_detail['prodid'] + ' ' + \
            self.product_detail['prodname']
        )
        self.label_spec.setText(self.product_detail['spec'])
        self.label_package.setText(self.product_detail['package'])
        self.label_piunit.setText(self.product_detail['spunit'])
        self.label_dpunit.setText(self.product_detail['spunit'])

    def basicdetail(self):
        if self.product_detail['bpamount'] != decimal.Decimal('0'):
            self.bpamount = self.product_detail['bpamount']
        else:
            self.bpamount = decimal.Decimal('1')
        if self.product_detail['mpamount'] != decimal.Decimal('0'):
            self.mpamount = self.product_detail['mpamount']
        else:
            self.mpamount = decimal.Decimal('1')
        if self.product_detail['spamount'] != decimal.Decimal('0'):
            self.spamount = self.product_detail['spamount']
        else:
            self.spamount = decimal.Decimal('1')
        self.a_box_samount = self.bpamount * self.mpamount * self.spamount
        self.units = [
            self.product_detail['lpunit'], self.product_detail['bpunit'],
            self.product_detail['mpunit'], self.product_detail['spunit']
        ]

    def get_labdetail(self):
        values_list = ("paperno", "status")
        key_dict = {
            'labtype': 4,
            'ciid': self.ppid
        }
        res = self.LC.get_labrecord(
            False, *values_list, **key_dict
        )
        if not len(res):
            return
        # 选择最后一条符合条件的成品报告
        detail = res.order_by('-autoid')[0]
        self.label_reportpaperno.setText(detail['paperno'])
        self.label_checkstatus.setText(CHECK_STATUS[detail['status']])

    def get_putinnote(self):
        values_list = (
            "dpamount", "piamount", "packamount", "unittype",
            "pidate", "piapplyerid", "piapplyername", "piqaid", "piqaname",
            "warehousemanid", "warehousemanname", "pistatus", "position",
            "dpposition", "dpwarehousemanid", "dpwarehousemanname",
            "warehouseid", "warehousename", "oddment", "dpdate", "oddment"
        )
        key_dict = {
            'autoid': self.autoid
        }
        res = self.WC.get_productputinnote(
            False, *values_list, **key_dict
        )
        if not len(res):
            return
        # 选择第一条
        self.ori_detail = res[0]

        self.label_dpdate.setText(
            str(self.ori_detail['dpdate']) if type(self.ori_detail['dpdate'])
                                              is datetime.date else ''
        )
        self.label_pidate.setText(
            str(self.ori_detail['pidate']) if type(self.ori_detail['pidate'])
                                              is datetime.date else ''
        )
        self.comboBox_unittype.setCurrentIndex(self.ori_detail['unittype'])
        self.label_warehouse.setText(
            self.ori_detail['warehouseid'] + ' ' +
            self.ori_detail['warehousename']
        )
        self.comboBox_dpposition.setCurrentText(self.ori_detail['dpposition'])
        self.comboBox_piposition.setCurrentText(self.ori_detail['position'])
        self.pushButton_applyer.setText(
            self.ori_detail['piapplyerid'] + ' ' +
            self.ori_detail['piapplyername']
        )
        self.pushButton_qa.setSign(
            True, self.ori_detail['piqaid'] + ' ' + self.ori_detail['piqaname']
        )
        self.pushButton_dpwsman.setText(
            self.ori_detail['dpwarehousemanid'] + ' ' +
            self.ori_detail['dpwarehousemanname']
        )
        self.pushButton_piwsman.setSign(
            True, self.ori_detail['warehousemanid'] + ' ' +
            self.ori_detail['warehousemanname']
        )

        self.lineEdit_amount.setText(str(self.ori_detail['dpamount']))
        self.lineEdit_oddment.setText(str(self.ori_detail['oddment']))
        self.label_unit.setText(self.units[self.ori_detail['unittype']])
        self.label_oddmentunit.setText(self.units[3])

        self.label_dpamount.setText(str(self.ori_detail['piamount']))
        self.label_piamount.setText(str(self.ori_detail['piamount']))

        if self.ori_detail['pistatus'] == 0:
            self.pushButton_accept.setVisible(True)
            self.pushButton_save.setVisible(True)
            self.pushButton_cancel.setVisible(False)
            self.pushButton_dp.setVisible(False)
            self.pushButton_pi.setVisible(False)
        elif self.ori_detail['pistatus'] == 1:
            self.pushButton_accept.setVisible(False)
            self.pushButton_save.setVisible(False)
            self.pushButton_cancel.setVisible(True)
            self.pushButton_dp.setVisible(True)
            self.pushButton_pi.setVisible(False)
        elif self.ori_detail['pistatus'] == 2:
            self.pushButton_accept.setVisible(False)
            self.pushButton_save.setVisible(False)
            self.pushButton_cancel.setVisible(False)
            self.pushButton_dp.setVisible(False)
            self.pushButton_pi.setVisible(True)
        elif self.ori_detail['pistatus'] == 3:
            self.pushButton_accept.setVisible(False)
            self.pushButton_save.setVisible(False)
            self.pushButton_cancel.setVisible(False)
            self.pushButton_dp.setVisible(False)
            self.pushButton_pi.setVisible(False)

    def get_oddment(self):
        self.treeWidget_oddments.clear()
        self.treeWidget_oddments.hideColumn(0)
        values_list = (
            "autoid", "batchno", "amount", "unit", "makedate", "ppid"
        )
        key_dict = {
            'dppid': self.ppid
        }
        res = self.PC.get_oddmentdrawnotes(False, *values_list, **key_dict)
        if not len(res):
            return

        for item in res:
            if item['unit'] not in self.units:
                continue
            qtreeitem = QTreeWidgetItem(self.treeWidget_oddments)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['batchno'])
            qtreeitem.setText(2, str(item['amount']))
            qtreeitem.setText(3, item['unit'])
            qtreeitem.setText(4, str(self.a_box_samount - item['amount']))
            qtreeitem.setText(5, str(item['makedate']))
            self.oddments_list.append(
                (2, self.ppid, self.a_box_samount,
                 item['ppid'], item['amount'])
            )
        for i in range(1, 6):
            self.treeWidget_oddments.resizeColumnToContents(i)
        if self.treeWidget_oddments.topLevelItemCount() > 0:
            self.checkBox_has_draw_oddments.setCheckState(2)

    @pyqtSlot(int)
    def on_comboBox_unittype_currentIndexChanged(self, p_int):
        self.label_unit.setText(self.units[p_int])
        try:
            if p_int != self.ori_detail['unittype']:
                self.new_detail['unittype'] = p_int
            else:
                try:
                    del self.new_detail['unittype']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['unittype'] = p_int
        self.set_total_amount()

    @pyqtSlot(str)
    def on_lineEdit_amount_textEdited(self, p_str):
        if p_str == '':
            amount = decimal.Decimal('0')
        else:
            amount = decimal.Decimal(p_str)
        try:
            if amount != self.ori_detail['dpamount']:
                self.new_detail['dpamount'] = amount
            else:
                try:
                    del self.new_detail['dpamount']
                except KeyError:
                    pass

            self.set_total_amount()

        except KeyError:
            self.new_detail['dpamount'] = amount
        except decimal.InvalidOperation:
            pass

    def set_total_amount(self):
        if self.lineEdit_amount.text() != '':
            amount = decimal.Decimal(self.lineEdit_amount.text())
        else:
            amount = decimal.Decimal('0')
        if self.lineEdit_oddment.text() != '':
            oddment = decimal.Decimal(self.lineEdit_oddment.text())
        else:
            oddment = decimal.Decimal('0')
        unit_index = self.comboBox_unittype.currentIndex()
        this_batchno_amount = 0
        if unit_index == 0:
            this_batchno_amount = amount * self.a_box_samount + oddment
        elif unit_index == 1:
            this_batchno_amount = amount * self.mpamount * self.spamount + oddment
        elif unit_index == 2:
            this_batchno_amount = amount * self.spamount + oddment
        elif unit_index == 3:
            this_batchno_amount = amount + oddment
        merge_amount = self.treeWidget_oddments.topLevelItemCount() * \
                       self.a_box_samount
        piamount = this_batchno_amount + merge_amount
        self.label_dpamount.setText(str(piamount))
        self.label_piamount.setText(str(piamount))
        try:
            if piamount != self.ori_detail['piamount']:
                self.new_detail['piamount'] = piamount
            else:
                try:
                    del self.new_detail['piamount']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piamount'] = piamount

    @pyqtSlot(str)
    def on_lineEdit_oddment_textEdited(self, p_str):
        if p_str == '':
            amount = decimal.Decimal('0')
        else:
            amount = decimal.Decimal(p_str)
        try:
            if amount != self.ori_detail['oddment']:
                self.new_detail['oddment'] = amount
            else:
                try:
                    del self.new_detail['oddment']
                except KeyError:
                    pass
            self.set_total_amount()
        except KeyError:
            self.new_detail['oddment'] = amount
        except decimal.InvalidOperation:
            pass

    @pyqtSlot(bool, str)
    def on_pushButton_qa_signChanged(self, p_bool, p_str):
        if p_bool:
            self.pushButton_accept.setEnabled(True)
            piqaid, piqaname = p_str.split(' ')
        else:
            self.pushButton_accept.setEnabled(False)
            piqaid, piqaname = ('', '')
        try:
            if piqaid != self.ori_detail['piqaid']:
                self.new_detail['piqaid'] = piqaid
                self.new_detail['piqaname'] = piqaname
            else:
                try:
                    del self.new_detail['piqaid']
                    del self.new_detail['piqaname']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piqaid'] = piqaid
            self.new_detail['piqaname'] = piqaname

    @pyqtSlot(bool, str)
    def on_pushButton_applyer_signChanged(self, p_bool, p_str):
        if p_bool:
            piapplyerid, piapplyername = p_str.split(' ')
        else:
            piapplyerid, piapplyername = ('', '')
        try:
            if piapplyerid != self.ori_detail['piapplyerid']:
                self.new_detail['piapplyerid'] = piapplyerid
                self.new_detail['piapplyername'] = piapplyername
            else:
                try:
                    del self.new_detail['piapplyerid']
                    del self.new_detail['piapplyername']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['piapplyerid'] = piapplyerid
            self.new_detail['piapplyername'] = piapplyername

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

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

    @pyqtSlot()
    def on_pushButton_save_clicked(self):
        if self.has_changed():
            self.WC.update_productputinnote(self.autoid, **self.new_detail)

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if self.pushButton_applyer.text() in ('', ' '):
            self.pushButton_applyer.setSign(
                True, user.user_id + ' ' +user.user_name
            )
            self.new_detail['piapplyerid'] = user.user_id
            self.new_detail['piapplyername'] = user.user_name
            self.new_detail['dpdate'] = user.now_date
        self.new_detail['pistatus'] = 1

        self.WC.update_productputinnote(self.autoid, **self.new_detail)
        realamount = decimal.Decimal(self.label_piamount.text())
        detail = {'realamount': realamount}
        self.PC.update_producingplan(self.ppid, **detail)

        self.pushButton_save.setVisible(False)
        self.pushButton_accept.setVisible(False)
        self.pushButton_cancel.setVisible(True)
        self.pushButton_dp.setVisible(False)
        self.pushButton_pi.setVisible(False)
        self.accepted.emit()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.new_detail['piapplyerid'] = ''
        self.new_detail['piapplyername'] = ''
        self.new_detail['pistatus'] = 0

        self.WC.update_productputinnote(self.autoid, **self.new_detail)

        self.pushButton_save.setVisible(True)
        self.pushButton_accept.setVisible(True)
        self.pushButton_cancel.setVisible(False)
        self.pushButton_dp.setVisible(False)
        self.pushButton_pi.setVisible(False)
        self.accepted.emit()

    @pyqtSlot()
    def on_pushButton_dp_clicked(self):
        self.new_detail['dpwarehousemanid'] = user.user_id
        self.new_detail['dpwarehousemanname'] = user.user_name
        self.new_detail['pistatus'] = 2

        self.WC.update_productputinnote(self.autoid, **self.new_detail)

        self.pushButton_save.setVisible(False)
        self.pushButton_accept.setVisible(False)
        self.pushButton_cancel.setVisible(False)
        self.pushButton_dp.setVisible(False)
        self.pushButton_pi.setVisible(True)
        self.accepted.emit()

    @pyqtSlot()
    def on_pushButton_pi_clicked(self):
        if self.label_checkstatus.text() != '检验合格':
            mesgbox = MessageBox(
                parent=self, title="提示", text="当前产品尚未检验合格无法入库"
            )
            mesgbox.exec()
            return
        self.new_detail['warehousemanid'] = user.user_id
        self.new_detail['warehousemanname'] = user.user_name
        self.new_detail['pidate'] = user.now_date
        self.new_detail['pistatus'] = 3
        # 计算要入库的产品信息
        putin_msg = self.get_putin_msg()
        self.WC.update_productputinnote(self.autoid, True, putin_msg, **self.new_detail)

        self.pushButton_save.setVisible(False)
        self.pushButton_accept.setVisible(False)
        self.pushButton_cancel.setVisible(False)
        self.pushButton_dp.setVisible(False)
        self.pushButton_pi.setVisible(False)
        self.accepted.emit()

    def get_putin_msg(self):
        return_detail = []
        return_detail += self.oddments_list
        # 全部的入库数量
        all_amount = decimal.Decimal(self.label_piamount.text())
        # 本批零头数量
        if self.lineEdit_oddment.text() not in ('', '0'):
            oddment_amount = decimal.Decimal(self.lineEdit_oddment.text())
            return_detail.append((1, self.ppid, oddment_amount, 0, 0))
        else:
            oddment_amount = 0
        # 合箱数量
        merge_amount = decimal.Decimal(self.treeWidget_oddments.topLevelItemCount()) * self.a_box_samount

        # 本批整箱数量
        spamount_of_total_box = all_amount - oddment_amount - merge_amount
        return_detail.append((0, self.ppid, spamount_of_total_box,0 ,0))
        return return_detail

    def has_changed(self):
        if not len(self.new_detail):
            return False
        if self.pushButton_applyer.text() in ('', ' '):
            self.pushButton_applyer.setSign(
                True, user.user_id + ' ' +user.user_name
            )
            self.new_detail['piapplyerid'] = user.user_id
            self.new_detail['piapplyername'] = user.user_name
        return True
Beispiel #14
0
class QrcodeinputModule(QWidget, Ui_Form):
    """ 二维码入库文件模块,可以查看到所有产品批次的二维码记录。
    提供了右键下载二维码和导入二维码的功能。

    导入二维码和覆盖二维码功能尚未实现。
    导入二维码只把文件里的数据导入,不会覆盖旧有的数据
    覆盖二维码会先把旧的二维码删除了,同时需要把二维码库中的使用状态used改未0
    导入和覆盖进行的同时还需要把新二维码在二维码库中的状态改为used=1
    """
    def __init__(self, parent=None):
        super(QrcodeinputModule, self).__init__(parent)
        self.setupUi(self)
        if '58' not in user.powers:
            self.close()
        if user.powers['58'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['58'])

        self.WC = WorkshopController()
        self.PC = ProductController()
        self.SC = SystemController()
        self.prodlist = dict()
        # 获取二维码信息
        self.get_product_list()

    def get_product_list(self):
        self.treeWidget_prodlist.clear()
        self.treeWidget_prodlist.hideColumn(0)
        key_dict = {'pltype': 0}
        index = self.tabWidget.currentIndex()
        if index in (0, 1):
            key_dict['qrflag'] = index

        self.prodlist = self.PC.get_producingplan(False, *VALUES_LIST,
                                                  **key_dict)
        if not len(self.prodlist):
            return
        for item in self.prodlist:
            qtreeitem = QTreeWidgetItem(self.treeWidget_prodlist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['prodid'] + item['prodname'])
            qtreeitem.setText(2, item['batchno'])
            qtreeitem.setText(3, item['spec'])
            qtreeitem.setText(4, item['package'])
            qtreeitem.setText(5, str(item['makedate']))
        for i in range(1, 6):
            self.treeWidget_prodlist.resizeColumnToContents(i)

    @pyqtSlot(QPoint)
    def on_treeWidget_prodlist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        qtreeitem = self.treeWidget_prodlist.selectedItems()
        if not len(qtreeitem):
            return
        select_ppid = int(qtreeitem[0].text(0))

        menu = QMenu()
        button1 = menu.addAction("生成入库数据文件")
        # button2 = menu.addAction("导入入库二维码数据")
        # button3 = menu.addAction("覆盖入库二维码数据")
        g_pos = self.treeWidget_prodlist.mapToGlobal(pos)
        action = menu.exec(g_pos)
        if action == button1:
            clipboard = QApplication.clipboard()
            dir = clipboard.property("qrcodeinputurl")
            filename = "入库数据" + str(user.now_date).replace("-", "") + ".xml"
            if not dir:
                dir = "C:\\"
            file_route, ext = QFileDialog.getSaveFileName(
                self, "请选择入库文件输出路径", dir + filename, "*.xml;;All Files(*)")

            if not file_route:
                return
            selected_dir = re.findall(r'^(.+/|.+\\)', file_route)[0]
            clipboard.setProperty("qrcodeinputurl", selected_dir)

            self.makeqrcodeinputfile(select_ppid, file_route)
            self.PC.update_producingplan(select_ppid, qrflag=1)
            self.get_product_list()

    @pyqtSlot(int)
    def on_tabWidget_currentChanged(self, index):
        getattr(self, 'tab_' + str(index)).setLayout(self.gridLayout_2)
        self.get_product_list()

    def makeqrcodeinputfile(self, ppid, file_route):
        for item in self.prodlist:
            if item['autoid'] == ppid:
                proddetail = item
                break
        key_dict = {'ppid': ppid}
        res = self.WC.get_qrcoderep(False, *VALUES_LIST_QRCODE, **key_dict)
        if not len(res):
            return
        # 把二维码按比例分组
        q_list, proportion_list = self.sort_qrcode(res)
        # 把比例相同的合并成一个同一个项目
        q_list_merge, proportion_list_merge = self.merge_qrcode(
            q_list, proportion_list)
        xml = QXmlStreamWriter()
        qfile = QFile(file_route)
        if qfile.open(QIODevice.WriteOnly):
            xml.setDevice(qfile)
        else:
            return

        xml.setAutoFormatting(True)
        xml.writeStartDocument()
        # 添加头文件信息
        self.addxmlheader(xml)
        self.addxmlproddetail(xml, proddetail)
        for i in range(0, len(proportion_list_merge)):
            spnum = proportion_list[i][0]
            mpnum = proportion_list[i][1]
            bpnum = proportion_list[i][2]
            lpnum = proportion_list[i][3]
            xml.writeStartElement("Batch")
            xml.writeAttribute('batchNo', proddetail['batchno'])
            xml.writeAttribute('specification', proddetail['spec'])
            xml.writeAttribute('minPackUnit', proddetail['spunit'])
            if spnum != 0:
                minTagUnit = proddetail['spunit']
            elif mpnum != 0:
                minTagUnit = proddetail['mpunit']
            else:
                minTagUnit = proddetail['bpunit']
            tagPackRatio = ''
            for num in (lpnum, bpnum, mpnum, spnum):
                if num != 0:
                    if tagPackRatio == '':
                        tagPackRatio = str(num)
                    else:
                        tagPackRatio += ':' + str(num)
            xml.writeAttribute('minTagUnit', minTagUnit)
            xml.writeAttribute('tagPackRatio', tagPackRatio)
            xml.writeAttribute('produceDate', str(proddetail['makedate']))
            xml.writeAttribute('operator', user.user_name)
            xml.writeAttribute('oprDate', str(user.now_date))
            xml.writeAttribute('count', str(len(q_list_merge[i])))
            xml.writeAttribute('countUnit',
                               '1' if minTagUnit == tagPackRatio else '2')
            qrcode = q_list_merge[i]
            for code in qrcode:
                xml.writeStartElement("Data")
                xml.writeAttribute('code', code)
                xml.writeEndElement()

            xml.writeEndElement()
        xml.writeEndElement()
        xml.writeEndElement()
        xml.writeEndDocument()

    def sort_qrcode(self, qrcode_list):
        q_list = []
        temp_q_list = []
        next_box = False
        # 比例
        proportion_list = []
        temp_proportion_list = []
        spnum = 0
        mpnum = 0
        bpnum = 0
        lpnum = 0

        # qrcode_s = ''
        qrcode_m = ''
        qrcode_b = ''
        qrcode_l = ''
        max_lv = 'lp'
        first_qrcode = qrcode_list[0]
        # qrcode0 = first_qrcode['qrcode0']
        # qrcode1 = first_qrcode['qrcode1']
        qrcode2 = first_qrcode['qrcode2']
        qrcode3 = first_qrcode['qrcode3']
        if qrcode3 == '' and qrcode2 == '':
            max_lv = 'mp'
        elif qrcode3 == '' and qrcode2 != '':
            max_lv = 'bp'

        for item in qrcode_list:

            if qrcode_m == '' and item['qrcode1'] != '':
                qrcode_m = item['qrcode1']
            elif qrcode_m != item['qrcode1']:
                temp_q_list.append(qrcode_m)
                qrcode_m = item['qrcode1']
                mpnum += 1
                if max_lv == 'mp':
                    next_box = True

            if qrcode_b == '' and item['qrcode2'] != '':
                qrcode_b = item['qrcode2']
            elif qrcode_b != item['qrcode2']:
                temp_q_list.append(qrcode_b)
                qrcode_b = item['qrcode2']
                bpnum += 1
                if max_lv == 'bp':
                    next_box = True
            if qrcode_l == '' and item['qrcode3'] != '':
                qrcode_l = item['qrcode3']
            elif qrcode_l != item['qrcode3']:
                temp_q_list.append(qrcode_l)
                qrcode_l = item['qrcode3']
                lpnum += 1
                if max_lv == 'lp':
                    next_box = True

            if next_box:
                q_list.append(temp_q_list)
                temp_q_list = []
                for num in (spnum, mpnum, bpnum, lpnum):
                    temp_proportion_list.append(num)
                spnum = 0
                mpnum = 0
                bpnum = 0
                lpnum = 0
                proportion_list.append(temp_proportion_list)
                temp_proportion_list = []
                next_box = False

            if item['qrcode0'] != '':
                temp_q_list.append(item['qrcode0'])
                spnum += 1
        if len(temp_q_list):
            if qrcode_m != '':
                temp_q_list.append(qrcode_m)
                mpnum += 1
            if qrcode_b != '':
                temp_q_list.append(qrcode_b)
                bpnum += 1
            if qrcode_l != '':
                temp_q_list.append(qrcode_l)
                lpnum += 1

            q_list.append(temp_q_list)
            for item in (spnum, mpnum, bpnum, lpnum):
                temp_proportion_list.append(item)
            proportion_list.append(temp_proportion_list)
        return q_list, proportion_list

    def merge_qrcode(self, q_list, proportion_list):
        q_list_merge = []
        proportion_list_merge = []
        for i in range(0, len(proportion_list)):
            proprotion = proportion_list[i]
            if proprotion in proportion_list_merge:
                index = proportion_list_merge.index(proprotion)
                q_list_merge[index] += q_list[i]
            else:
                proportion_list_merge.append(proprotion)
                q_list_merge.append(q_list[i])
        return q_list_merge, proportion_list_merge

    def addxmlheader(self, xml):
        company = "智普飞扬"
        mancode = "19060310"
        key_dict_sys = {'varname__in': ("company", "mancode")}
        res = self.SC.get_syssetting(False, *VALUES_LIST_SYS, **key_dict_sys)
        if len(res):
            for item in res:
                if item['varname'] == "company":
                    company = item['varvalue']
                elif item['varname'] == "mancode":
                    mancode = item['varvalue']
        xml.writeStartElement("DataList")
        xml.writeAttribute("corpName", company)
        xml.writeAttribute("manCode", mancode)
        xml.writeAttribute("dataType", "wareHouseIn")
        xml.writeAttribute("version", "1.0")
        xml.writeAttribute("xmlns: xsi",
                           "http://www.w3.org/2001/XMLSchema-instance")
        xml.writeAttribute("xsi: noNamespaceSchemaLocation",
                           "兽药产品入库数据_生产企业.xsd")

    def addxmlproddetail(self, xml, proddetail):
        xml.writeStartElement("Product")
        xml.writeAttribute("productName", proddetail['commonname'])
        xml.writeAttribute("pzwh", proddetail['allowno'])
        xml.writeAttribute(
            "packing",
            str(proddetail['basicamount']) + proddetail['basicunit'])
class ScanqrcodeModule(QDialog, Ui_Dialog):
    applyed = pyqtSignal(list, str)

    def __init__(self, ppid, parent=None):
        # b,m,s分别对应大、中、小包装
        # num 为已经扫描的个数
        # amount 为包装比例
        super(ScanqrcodeModule, self).__init__(parent)
        self.setupUi(self)
        self.PC = ProductController()
        self.WC = WorkshopController()
        self.tts = Tts()
        self.tts.start()
        self.ppid = ppid

        self.batchno = ''
        self.commonname = ''
        self.allowno = ''
        # 上级码的对象
        self.lpid = None
        self.bpid = None
        self.mpid = None
        # 扫了多少个码
        self.scan_num = [0, 0, 0, 0]
        # 一箱对应的码数量
        self.lv_amount = [0, 0, 0, 0]
        # 各级码的出现次数
        self.lpsum = 0
        self.bpsum = 0
        self.mpsum = 0
        self.widget_list = [
            self.lineEdit_lpqrcode, self.lineEdit_bpqrcode,
            self.lineEdit_mpqrcode, self.lineEdit_spqrcode
        ]
        self.use_lv_qrcode = []

        qrtype = self.get_prod_packagelv()
        self.qrcode = AboxQrcode(
            qrtype, self.lv_amount[1], self.lv_amount[2],
            self.lv_amount[3]
        )

        q_list = ('lp', 'bp', 'mp', 'sp')
        qrtype = '{: 04b}'.format(qrtype)

        self.mpsum = self.lv_amount[3] if qrtype[3] == '1' else 1
        self.bpsum = self.mpsum * (self.lv_amount[2] if qrtype[2] == '1' else 1)
        self.lpsum = self.bpsum * (self.lv_amount[1] if qrtype[1] == '1' else 1)

        for i in (3, 2, 1, 0):
            if qrtype[i] == '1':
                self.use_lv_qrcode.append(q_list[i])
            else:
                self.widget_list[i].setEnabled(False)
                self.widget_list.pop(i)
                self.scan_num.pop(i)
                self.lv_amount.pop(i)
        self.use_lv_qrcode.reverse()
        self.widget_list[0].setFocus()

    def get_prod_packagelv(self):
        key_dict_prod = {
            'autoid': self.ppid
        }
        res = self.PC.get_producingplan(
            False, *VALUE_LIST_PROD, **key_dict_prod
        )
        if len(res) != 1:
            return
        self.batchno = res[0]['batchno']
        self.commonname = res[0]['commonname']
        self.allowno = res[0]['allowno']
        self.lv_amount[1] = res[0]['bpamount']
        self.lv_amount[2] = res[0]['mpamount']
        self.lv_amount[3] = res[0]['spamount']
        return res[0]['qrtype']

    @pyqtSlot()
    def on_lineEdit_spqrcode_focused(self):
        self.tts.say("请扫描小包装二维码")

    @pyqtSlot()
    def on_lineEdit_mpqrcode_focused(self):
        self.tts.say("请扫描中包装二维码")

    @pyqtSlot()
    def on_lineEdit_bpqrcode_focused(self):
        self.tts.say("请扫描大包装二维码")

    @pyqtSlot()
    def on_lineEdit_lpqrcode_focused(self):
        self.tts.say("请扫描巨包装二维码")

    @pyqtSlot()
    def on_lineEdit_spqrcode_returnPressed(self):
        p_str = self.lineEdit_spqrcode.text()
        self.plainTextEdit_spqrcode.appendPlainText(p_str)
        data = p_str.replace(',', ',')
        qrcode = data.split(',')[0]
        self.lineEdit_spqrcode.clear()
        if not self.check_qrcode(qrcode, 'spqrcoce', 1):
            return
        self.qrcode.set_qrcode(0, self.mpid, qrcode)
        self.next_qrcode_lv(self.lineEdit_spqrcode)

    @pyqtSlot()
    def on_lineEdit_mpqrcode_returnPressed(self):
        p_str = self.lineEdit_mpqrcode.text()
        self.plainTextEdit_mpqrcode.appendPlainText(p_str)
        data = p_str.replace(',', ',')
        qrcode = data.split(',')[0]
        self.lineEdit_mpqrcode.clear()
        if not self.check_qrcode(qrcode, 'mpqrcoce', self.mpsum):
            return
        self.mpid = self.qrcode.set_qrcode(1, self.bpid, qrcode)
        self.next_qrcode_lv(self.lineEdit_mpqrcode)

    @pyqtSlot()
    def on_lineEdit_bpqrcode_returnPressed(self):
        p_str = self.lineEdit_bpqrcode.text()
        self.plainTextEdit_bpqrcode.appendPlainText(p_str)
        data = p_str.replace(',', ',')
        qrcode = data.split(',')[0]
        self.lineEdit_bpqrcode.clear()
        if not self.check_qrcode(qrcode, 'bpqrcoce', self.bpsum):
            return

        self.bpid = self.qrcode.set_qrcode(2, self.lpid, qrcode)
        self.next_qrcode_lv(self.lineEdit_bpqrcode)

    @pyqtSlot()
    def on_lineEdit_lpqrcode_returnPressed(self):
        p_str = self.lineEdit_mpqrcode.text()
        self.plainTextEdit_mpqrcode.appendPlainText(p_str)
        data = p_str.replace(',', ',')
        qrcode = data.split(',')[0]
        self.lineEdit_lpqrcode.clear()
        if not self.check_qrcode(qrcode, 'lpqrcoce', self.lpsum):
            return

        self.lpid = self.qrcode.set_qrcode(3, None, qrcode)
        self.next_qrcode_lv(self.lineEdit_lpqrcode)

    @pyqtSlot()
    def on_pushButton_nextbox_clicked(self):
        self.qrcode.reset()
        qrcode_list = self.qrcode.qrcode_list
        self.applyed.emit(qrcode_list, self.batchno)
        self.qrcode.reset()

    def check_qrcode(self, qrcode, kind, amount):
        if len(qrcode) != 24:
            # 二维码长度不对
            text = qrcode + ":二维码格式错误\n"
            self.textEdit_errorlist.insertPlainText(text)
            self.tts.say("错码")
            return False
        key_dict_qrcode_rep['qrcode'] = qrcode
        res = self.WC.get_data(
            0, False, *VALUE_LIST_QRCODE_REP, **key_dict_qrcode_rep
        )
        if len(res) == 0:
            # 二维码库中无此二维码
            text = qrcode + ":二维码库中无此二维码\n"
            self.textEdit_errorlist.insertPlainText(text)
            self.tts.say("错码")
            return False
        elif res[0]['prodname'] != self.commonname or res[0][
            'allowno'] != self.allowno:
            # 二维码不是这个产品
            text = qrcode + ":二维码库中此二维码的通用名/批准文号不正确\n"
            self.textEdit_errorlist.insertPlainText(text)
            self.tts.say("错码")
            return False
        elif res[0]['used'] == 1:
            if kind == 'spqrcode':
                # 此二维码已经被使用
                text = qrcode + ":此二维码已被使用\n"
                self.textEdit_errorlist.insertPlainText(text)
                self.tts.say("虫码")
                return False
            else:
                condition = {kind: qrcode}
                used_list = self.WC.get_data(
                    1, False, *value_list_prodqr, **condition
                )
                if len(used_list) >= amount or len(used_list) == 0:
                    text = qrcode + ":此二维码使用次数超过" + amount + "次\n"
                    self.textEdit_errorlist.insertPlainText(text)
                    self.tts.say("虫码")
                    return False
                for item in used_list:
                    if item['ppid'] != self.ppid:
                        # 此二维码已经被使用
                        text = qrcode + ":此二维码已在其他批次中使用\n"
                        self.textEdit_errorlist.insertPlainText(text)
                        self.tts.say("虫码")
                        return False
                amount = len(used_list)
        else:
            # 二维码是否出现本这箱中
            flag, that_kind = self.qrcode.has_qrcode(qrcode)
            if flag:
                if kind != that_kind:
                    text = qrcode + ":此二维码已在本箱中使用\n"
                    self.textEdit_errorlist.insertPlainText(text)
                    self.tts.say("虫码")
                    return False
                elif kind == 'spqrcode':
                    text = qrcode + ":此二维码已在本箱中使用\n"
                    self.textEdit_errorlist.insertPlainText(text)
                    self.tts.say("虫码")
                    return False

        return True

    def next_qrcode_lv(self, widget):
        index = self.widget_list.index(widget)
        self.scan_num[index] += 1
        num = self.scan_num[index]

        flat = False
        # now_sum = len(getattr(self.qrcode, widget.objectName()[9: 11] + 'qrcode'))
        # sum = getattr(self.qrcode, widget.objectName()[9: 11] + 'count')
        self.tts.say(str(num) + "个")
        count = self.lv_amount[index]

        if self.qrcode.is_enough_qrcode():
            self.applyed.emit(self.qrcode.qrcode_list, self.batchno)
            # 扫够一箱,进行下一箱
            self.qrcode.reset()
            for i in range(len(self.scan_num)):
                self.scan_num[i] = 0
            self.widget_list[0].setFocus()

        # 不够一箱
        # self.scan_num[index] = 0
        elif index == 0:
            while index < len(self.widget_list) - 1:
                index += 1
                if self.scan_num[index] < self.lv_amount[index]:
                    self.widget_list[index].setFocus()
                    flat = True
                    break
        elif index == len(self.widget_list) - 1:
            if num < count:
                # 最小级别码没有扫够,则继续扫本级二维码
                return
            else:
                # 扫够则寻找上一级没有扫够的级别
                self.scan_num[index] = 0
                while index > 0:
                    index -= 1
                    if self.scan_num[index] < self.lv_amount[index]:
                        self.widget_list[index].setFocus()
                        flat = True
                        break
        else:
            # 不是最上一级和最下一级,则先往下级再往上级判断是否已经足够数量
            # 如果数量不够,则或取焦点
            flag = False
            j = index
            while j < len(self.widget_list) - 1:
                j += 1
                if self.scan_num[j] < self.lv_amount[j]:
                    self.widget_list[j].setFocus()
                    flag = True
                    flat = True
                    break
            if not flag:
                while index > 0:
                    index -= 1
                    if self.scan_num[index] < self.lv_amount[index]:
                        self.widget_list[index].setFocus()
                        flat = True
                        break
        if not flat:
            self.widget_list[0].setFocus()

    def closeEvent(self, e):
        qrcode_list = self.qrcode.qrcode_list
        self.applyed.emit(qrcode_list, self.batchno)
        self.qrcode.reset()
Beispiel #16
0
class WarehouseController(object):
    def __init__(self):
        self.SC = StuffController()
        self.SLC = SaleController()
        self.SP = SupplyerController()
        self.WM = WarehouseModel()
        self.WC = WorkshopController()
        self.PC = ProductController()

    def get_stuffdrawpaper(self, *args, **kwargs):
        return self.SC.get_stuffdrawpaper(*args, **kwargs)
        """if len(res):
            ppid_list = list()
            for item in res:
                ppid_list.append(item.ppid)
            value_tuple = (
                'autoid', 'prodid', 'prodname', 'spec', 'package', 'batchno')
            prod_info_tuple = self.WM.get_producingplan(*value_tuple,
                                                        autoid__in=set(
                                                            ppid_list))
            for item in res:
                for it in prod_info_tuple:
                    if item.ppid == it[0]:
                        item.prod = it[1] + ' ' + it[2]
                        item.spec = it[3]
                        item.package = it[4]
                        item.batchno = it[5]
            return res
        else:
            return []"""

    def get_stuffrepository(self, display_flag=False, *args, **kwargs):
        return self.WM.get_stuffrepository(display_flag, *args, **kwargs)
        """res = self.WM.get_stuffrepository(flag, *args, **kwargs)
        supid_list = []
        if len(res):
            for item in res:
                supid_list.append(item['supid'])
            supplyers = self.SP.get_supply(('supid', 'supname'), supid__in=set(supid_list))
            for item in res:
                item['supname'] = ''
                for supplyer in supplyers:
                    if item['supid'] == supplyer[0]:
                        item['supname'] = supplyer[1]
                        break
        return res
        """

    def update_stuffrepository(self, autoid=None, *args, **kwargs):
        return WarehouseModel.update_stuffrepository(autoid, *args, **kwargs)

    def update_stuffrepository_amount(self, ppid, *args, **kwargs):
        return WarehouseModel.update_stuffrepository_amount(
            ppid, *args, **kwargs)

    def get_productputoutpaper(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_productputoutpaper(display_flag, *args,
                                                     **kwargs)

    def update_productputoutpaper(self, autoid=None, *args, **kwargs):
        return WarehouseModel.update_productputoutpaper(
            autoid, *args, **kwargs)

    def delete_productputoutpaper(self, autoid=None, *args, **kwargs):
        return WarehouseModel.delete_productputoutpaper(
            autoid, *args, **kwargs)

    def get_prodwithdrawnote(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_prodwithdrawnote(display_flag, *args,
                                                   **kwargs)

    def update_prodwithdrawnote(self, autoid, *args, **kwargs):
        return WarehouseModel.update_prodwithdrawnote(autoid, *args, **kwargs)

    def delete_prodwithdrawnote(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_prodwithdrawnote(autoid, *args, **kwargs)

    def get_ppopqrcode(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_ppopqrcode(display_flag, *args, **kwargs)

    def update_ppopqrcode(self, autoid, *args, **kwargs):
        return WarehouseModel.update_ppopqrcode(autoid, *args, **kwargs)

    def delete_ppopqrcode(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_ppopqrcode(autoid, *args, **kwargs)

    def get_pwqrcode(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_pwqrcode(display_flag, *args, **kwargs)

    def update_pwqrcode(self, autoid, *args, **kwargs):
        return WarehouseModel.update_pwqrcode(autoid, *args, **kwargs)

    def delete_pwqrcode(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_pwqrcode(autoid, *args, **kwargs)

    def get_stuffcheckin(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_stuffcheckin(display_flag, *args, **kwargs)

    def update_stuffcheckin(self, autoid, *args, **kwargs):
        return WarehouseModel.update_stuffcheckin(autoid, *args, **kwargs)

    def new_stuffcheckin(self, ppid, *args, **kwargs):
        detail = dict()
        key_dict = {'ppid': ppid}
        stuff_query = self.SP.get_purchstuff(False, *VALUES_TUPLE_PPLIST,
                                             **key_dict)
        if not len(stuff_query):
            return
        stuff_list = list(stuff_query)

        with transaction.atomic():
            p1 = transaction.savepoint()
            res = WarehouseModel.update_stuffcheckin(None, *args, **kwargs)

            for item in stuff_list:
                if item['amount'] - item['arrivedamount'] <= 0:
                    continue
                detail['paperno'] = res.paperno
                detail['papertype'] = 0
                detail['makedate'] = user.now_date
                detail['expireddate'] = user.now_date + datetime.timedelta(
                    days=item['expireddays'])
                detail['checkindate'] = user.now_date
                detail['amount'] = item['amount'] - item['arrivedamount']
                detail['piamount'] = item['amount'] - item['arrivedamount']
                detail['supid'] = kwargs['supid']
                detail['supname'] = kwargs['supname']
                del item['amount']
                del item['arrivedamount']
                del item['expireddays']
                detail.update(item)
                WarehouseModel.update_stuffcheckinlist(None, **detail)

    def delete_stuffcheckin(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_stuffcheckin(autoid, *args, **kwargs)

    def get_stuffcheckinlist(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_stuffcheckinlist(display_flag, *args,
                                                   **kwargs)

    def update_stuffcheckinlist(self, autoid, *args, **kwargs):
        return WarehouseModel.update_stuffcheckinlist(autoid, *args, **kwargs)

    def delete_stuffcheckinlist(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_stuffcheckinlist(autoid, *args, **kwargs)

    def get_productrepository(self, display_flag=False, *args, **kwargs):
        return WarehouseModel.get_productrepository(display_flag, *args,
                                                    **kwargs)

    def update_productrepository(self, autoid, *args, **kwargs):
        return WarehouseModel.update_productrepository(autoid, *args, **kwargs)

    def delete_productrepository(self, autoid, *args, **kwargs):
        return WarehouseModel.delete_productrepository(autoid, *args, **kwargs)

    def find_prodqrcode(self, qrcode):
        """ 产品二维码中是否找到输入的二维码(qrcode)
        返回4个参数
        第一个参数
            0: 找到二维码且(全部)未使用
            1: 找到二维码但(全部)已被使用
            2: 找到二维码但(部分)已被使用
            3: 找不到二维码
        第二个参数
            二维码级别
        第三个参数
            二维码对应的数量
        第四个参数
            二维码所在的ppid,选择结果集中的第一个ppid
        第五个二维码
            二维码所在的batchno,选择结果集的第一个batchno
        """
        key_dict_0 = {'qrcode0': qrcode}
        key_dict_1 = {'qrcode1': qrcode}
        key_dict_2 = {'qrcode2': qrcode}
        key_dict_3 = {'qrcode3': qrcode}
        res = None
        i = 0
        for i in range(0, 4):
            res = self.WC.get_prodqrcode(False, *VALUES_TUPLE_PRODQRCODE,
                                         **locals()['key_dict_' + str(i)])
            if len(res):
                break
        if not len(res):
            return 3, i, 0, 0, ''
        res_dist = res.distinct()
        sum = len(res)
        amount = self.sum_to_amount(sum, i, res_dist[0]['ppid'])

        if len(res_dist) == 2:

            return 2, i, amount, res_dist[0]['ppid'], res_dist[0]['batchno']
        elif len(res_dist) == 1:
            item = res_dist[0]
            if item['used'] == 0:
                return 0, i, amount, item['ppid'], item['batchno']
            else:
                return 1, i, amount, item['ppid'], item['batchno']
        else:
            return False

    def sum_to_amount(self, sum, i, ppid):
        """把二维码次数转位数量
        :parameter
            sum:二维码的数量
            i:第几级二维码
            ppid: 对应的批生产记录
        :return
            amount: 转换后的数量
        首先要获取ppid对应记录的扫码比例
        如果是0则 则amount=sum,否则amount=sum*没有扫码的级别数量
        """
        key_dict_pp = {'autoid': ppid}
        res = self.PC.get_producingplan(False, *VALUES_TUPLE_PP, **key_dict_pp)
        if not len(res):
            return 1
        qrtype = res[0]['qrtype']
        amount_list = (res[0]['bpamount'], res[0]['mpamount'],
                       res[0]['spamount'])
        if qrtype == 1:
            return sum
        for key, value in enumerate('{:04b}'.format(qrtype)[::-1]):
            if value == '1':
                break
            elif value == '0':
                sum *= amount_list[2 - key]
        return sum

    def add_ppopqrocde(self, flag, qrcode, detail):
        with transaction.atomic():
            p1 = transaction.savepoint()

            WarehouseModel.update_ppopqrcode(**detail)
            key_dict = {globals()['QRCODE_KIND'][flag]: qrcode}
            values = {'used': 1}
            self.WC.update_prodqrcode(key_dict, **values)

    def drop_ppopqrocde(self, flag, qrcode, autoid=None, **kwargs):
        with transaction.atomic():
            p1 = transaction.savepoint()

            WarehouseModel.delete_ppopqrcode(autoid, **kwargs)
            key_dict = {globals()['QRCODE_KIND'][flag]: qrcode}
            values = {'used': 0}
            self.WC.update_prodqrcode(key_dict, **values)

    def apply_productputoutpaper(self, autoid, snid=None, *args, **kwargs):
        with transaction.atomic():
            p1 = transaction.savepoint()
            WarehouseModel.update_productputoutpaper(autoid, *args, **kwargs)
            if snid is not None:
                key_dict_sn = {
                    'status': 3,
                    'deliverid': user.user_id,
                    'delivername': user.user_name
                }
                self.SLC.update_salenotes(snid, **key_dict_sn)
            key_dict = {'ppopid': autoid}
            qrcode_list = WarehouseModel.get_ppopqrcode(
                False, *VALUES_TUPLE_PPOPRCODE, **key_dict).order_by('ppid')
            no_enough_list = []
            # 大中小包装得数量
            for item in qrcode_list:
                kind = item['kind']
                amount = item['amount']
                ppid = item['ppid']

                if kind == 0:
                    key_dict_rep = {'pisource': 0, 'ppid': ppid}
                    rep_list = WarehouseModel.get_productrepository(
                        **key_dict_rep)
                    for rep_item in rep_list:
                        if rep_item.stockamount - amount >= 0:
                            rep_item.stockamount -= amount
                            amount = 0
                            rep_item.save()
                            break
                        else:
                            amount -= rep_item.stockamount
                            rep_item.stockamount = 0
                            rep_item.save()
                    if amount > 0:
                        no_enough_list.append((0, ppid))

                elif kind == 1:
                    key_dict_rep = {'pisource': 1, 'ppid': ppid}
                    # 优先比较零头的数量
                    rep_list = WarehouseModel.get_productrepository(
                        **key_dict_rep)
                    for rep_item in rep_list:
                        if rep_item.stockamount - amount >= 0:
                            rep_item.stockamount -= amount
                            amount = 0
                            rep_item.save()
                            break
                        else:
                            amount -= rep_item.stockamount
                            rep_item.stockamount = 0
                            rep_item.save()
                    if amount > 0:
                        key_dict_rep = {'pisource': 2, 'hxid': ppid}
                        # 优先比较零头的数量
                        rep_list = WarehouseModel.get_productrepository(
                            **key_dict_rep)
                        for rep_item in rep_list:
                            # 剩余数量和合箱剩余数量都是足够
                            if rep_item.stockamount - amount >= 0 and \
                                    rep_item.hxstockamount - amount >= 0:

                                rep_item.stockamount -= amount
                                rep_item.hxstockamount -= amount
                                amount = 0
                                rep_item.save()
                                break
                            else:
                                amount -= rep_item.hxstockamount
                                rep_item.hxstockamount = 0
                                rep_item.save()
                        if amount > 0:
                            no_enough_list.append((1, ppid))
                elif kind == 2:
                    key_dict_rep = {'pisource': 2, 'ppid': ppid}
                    rep_list = WarehouseModel.get_productrepository(
                        **key_dict_rep)
                    for rep_item in rep_list:
                        # 剩余总数-合箱数量=本批的数量
                        if rep_item.stockamount - rep_item.hxstockamount - \
                                amount >= 0:
                            rep_item.stockamount -= amount
                            amount = 0
                            rep_item.save()
                            break
                        else:
                            amount -= (rep_item.stockamount - \
                                      rep_item.hxstockamount)
                            rep_item.stockamount = rep_item.hxstockamount
                            rep_item.save()
                    if amount > 0:
                        no_enough_list.append((2, ppid))

            if len(no_enough_list):
                transaction.savepoint_rollback(p1)
                return "no enough", no_enough_list
            else:
                return 'OK'

    def stuffreturn(self, autoid=0, backamount_list=[], *args, **kwargs):
        key_dict = {'autoid': 0}
        with transaction.atomic():
            p1 = transaction.savepoint()
            self.SC.update_stuffdrawpaper(autoid, *args, **kwargs)
            for item in backamount_list:
                id = item[0]
                backamount = item[1]
                key_dict['autoid'] = id
                sr_list = WarehouseModel.get_stuffrepository(False, **key_dict)
                if not len(sr_list):
                    continue
                sr_item = sr_list[0]
                sr_item.amount += backamount
                sr_item.save()

    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 WarehouseModel.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 WarehouseModel.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 WarehouseModel.delete_data(table_str, err_msg, condition, *args,
                                          **kwargs)
Beispiel #17
0
class HomePageModule(QWidget, Ui_Form):

    def __init__(self, autoid, parent=None):
        super(HomePageModule, self).__init__(parent)
        self.setupUi(self)
        self.autoid=autoid
        self.current_img = object
        self.current_page = object
        self.PC = ProductController()
        self.WC = WorkshopController()
        self.IC = ImageController()
        # 自动缩放
        self.label_image.setScaledContents(True)
        self.get_detail()
        self.get_images()
        self.scrollArea.setVisible(False)
        self.groupBox.setVisible(False)

    def get_detail(self):
        key_dict = {'autoid': self.autoid}
        res = self.PC.get_producingplan(False, *VALUES_TUPLE_PP, **key_dict)
        if not len(res):
            return
        pp_detail = res[0]
        self.label_product.setText(pp_detail['prodid'] + pp_detail['prodname'])
        self.label_commonname.setText(pp_detail['commonname'])
        self.label_spec.setText(pp_detail['spec'])
        self.label_package.setText(pp_detail['package'])
        self.label_batchno.setText(pp_detail['batchno'])
        self.label_realamout.setText(
            to_str(pp_detail['realamount']) + pp_detail['spunit']
        )
        self.label_makedate.setText(str(pp_detail['makedate']))

    def get_images(self):
        self.treeWidget_imagenamelist.clear()
        self.treeWidget_imagenamelist.hideColumn(0)
        key_dict = {'ppid': self.autoid}
        imgid_list = self.WC.get_plids(True,*VALUES_TUPLE_PLIB, **key_dict)
        if not len(imgid_list):
            return

        for item in imgid_list:
            qtreeitem = QTreeWidgetItem(self.treeWidget_imagenamelist)
            qtreeitem.setText(0, str(item['imgid']))
            qtreeitem.setText(1, str(item['title']))
            qtreeitem.setText(2, str(item['ext']))
        self.treeWidget_imagenamelist.resizeColumnToContents(1)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_imagenamelist_itemDoubleClicked(self, qtreeitem, p_int):
        self.scrollArea.setVisible(True)
        self.groupBox.setVisible(True)
        img_id = int(qtreeitem.text(0))
        ext = qtreeitem.text(2).lower()
        key_dict = {
            'autoid': img_id
        }
        img_list = self.IC.get_image(False, *VALUES_TUPLE_IMG, **key_dict)
        if not len(img_list):
            return
        image = img_list[0]
        if ext == 'pdf':
            self.comboBox_jumpto.setVisible(True)
            self.pushButton_prepage.setVisible(True)
            self.pushButton_nextpage.setVisible(True)
            self.current_img = fitz.Document(stream=image['img'],
                                             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['img'])
            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 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
Beispiel #18
0
class QrcodelistModule(QWidget, Ui_Form):
    def __init__(self, ppid, parent=None):
        super(QrcodelistModule, self).__init__(parent)
        self.setupUi(self)

        self.ppid = ppid
        self.WC = WorkshopController()

        # 获取现有的二维码列表
        self.get_qrcode_list()

    def get_qrcode_list(self):
        self.treeWidget_qrcode.clear()
        self.treeWidget_qrcode.hideColumn(1)
        self.treeWidget_qrcode.hideColumn(2)
        value_list = ('autoid', 'qrcode0', 'qrcode1', 'qrcode2', 'qrcode3')
        key_dict = {'ppid': self.ppid}
        res = self.WC.get_prodqrcode(False, *value_list, **key_dict)
        if not len(res):
            return
        for item in res:
            self.add_qrcode_to_treewidget(item)
        self.treeWidget_qrcode.resizeColumnToContents(0)

    def add_qrcode_to_treewidget(self, item, i=0):
        # i:二维码级别,默认为0,巨包装二维码,3为小包装二维码

        if i == 3:
            qtreeitem = QTreeWidgetItem(self.treeWidget_qrcode)
            qtreeitem.setText(0, item['qrcode3'])
            qtreeitem.setText(1, str(item['autoid']))
            qtreeitem.setText(2, '3')
            return qtreeitem

        qrcode = item['qrcode' + str(i)]
        qrcode_parent = item['qrcode' + str(i + 1)]
        # 上一级包装码不为空
        if qrcode_parent != '':
            # 检查是否已经存上级二维码
            match_list_qr = self.treeWidget_qrcode.findItems(
                qrcode_parent, Qt.MatchFixedString | Qt.MatchRecursive, 0)
            # 如果不存在且上一级包装码
            if not len(match_list_qr):
                new_parent = self.add_qrcode_to_treewidget(item, i=i + 1)
                qtreeitem = QTreeWidgetItem(new_parent)
            else:
                qtreeitem = QTreeWidgetItem(match_list_qr[0])
        else:
            qtreeitem = QTreeWidgetItem(self.treeWidget_qrcode)
        qtreeitem.setText(0, qrcode)
        qtreeitem.setText(1, str(item['autoid']))
        qtreeitem.setText(2, str(i))
        return qtreeitem

    @pyqtSlot()
    def on_pushButton_scanqrcode_clicked(self):
        detail = ScanqrcodeModule(self.ppid, self)
        detail.applyed.connect(self.addqrcode)
        detail.show()

    @pyqtSlot()
    def on_pushButton_deleteqrcode_clicked(self):
        pass

    @pyqtSlot()
    def on_pushButtonchangeqrcode_clicked(self):
        pass

    def addqrcode(self, q_list, batchno):
        for item in q_list:
            detail = {
                'ppid': self.ppid,
                'qrcode0': item[0],
                'qrcode1': item[1],
                'qrcode2': item[2],
                'qrcode3': item[3],
                'batchno': batchno
            }
            self.WC.update_prodqrcode(**detail)
            self.get_qrcode_list()
class PreProdputinlistModule(QWidget, Ui_Form):
    """ 前处理入库列表记录记录
    分2个标签,0:0:未入库,1:已入库
    点击其中一条生产记录时显示对应的记录内容
    """
    def __init__(self, parent=None):
        super(PreProdputinlistModule, self).__init__(parent)
        self.setupUi(self)
        if '36' not in user.powers:
            self.close()
        if user.powers['36'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['36'])

        self.PC = ProductController()
        self.WC = WorkshopController()
        self.LC = LabrecordsController()
        # 获取当前状态的批生产记录
        self.get_proddetail()

    def get_proddetail(self):
        self.treeWidget_prodlist.clear()
        self.treeWidget_prodlist.hideColumn(0)
        values_tuple_prod = ("autoid", "prodid", "prodname", "commonname",
                             "spec", "package", "realamount", "basicunit")
        key_dict_prod = dict()

        values_list_putin = ('ppid', )
        index = self.tabWidget.currentIndex()
        key_dict_putin = {'pistatus': 1 if index == 0 else 3}

        id_list = self.WC.get_productputinnote(True, *values_list_putin,
                                               **key_dict_putin)
        if not len(id_list):
            return
        key_dict_prod['autoid__in'] = id_list.distinct()
        key_dict_prod['pltype'] = 1

        values_tuple_lab = ('status', 'ciid')
        key_dict_lab = {'ciid__in': id_list.distinct(), 'labtype': 2}
        res_lab = self.LC.get_labrecord(False, *values_tuple_lab,
                                        **key_dict_lab)
        res_prod = self.PC.get_producingplan(False, *values_tuple_prod,
                                             **key_dict_prod)
        for item in res_prod:
            qtreeitem = QTreeWidgetItem(self.treeWidget_prodlist)
            qtreeitem.setText(0, str(item['autoid']))
            for lab_item in res_lab:
                if lab_item['ciid'] == item['autoid']:
                    qtreeitem.setText(1, CHECK_STATUS[lab_item['status']])
                    break
            qtreeitem.setText(2, item['prodid'] + ' ' + item['prodname'])
            qtreeitem.setText(3, item['commonname'])
            qtreeitem.setText(4, item['spec'])
            qtreeitem.setText(5, item['package'])
            qtreeitem.setText(6, str(item['realamount']) + item['basicunit'])

        for i in range(1, 7):
            self.treeWidget_prodlist.resizeColumnToContents(i)

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

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_prodlist_itemDoubleClicked(self, qtreeitem, p_int):
        if self.power[1] == '0':
            return
        ppid = int(qtreeitem.text(0))
        dialog = QDialog(self)
        layout = QGridLayout(dialog)
        dialog.setLayout(layout)
        detail = PreProdPutInModule(ppid=ppid, parent=dialog)
        layout.addWidget(detail)
        detail.accepted.connect(self.get_proddetail)
        detail.accepted.connect(dialog.accept)
        dialog.show()

    @pyqtSlot(QPoint)
    def on_treeWidget_oddmentlist_customContextMenuRequested(self, pos):
        index = self.tabWidget.currentIndex()
        if index != 1 or self.power[1] == '0':
            return
            # 返回调用者的对象
        sender_widget = self.sender()
        select_items = sender_widget.selectedItems()
        if not len(select_items):
            return
        id_list = []
        for item in select_items:
            id_list.append(int(item.text(0)))

        menu = QMenu()
        if index in (1, 5):
            button1 = menu.addAction("提交寄库")
        elif index == 3:
            button2 = menu.addAction("取消寄库")

        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)

        if index in (1, 5):
            if action == button1:
                detail = {
                    'flag': 2,
                    'qaid': user.user_id,
                    'qaname': user.user_name,
                    'qadate': user.now_date
                }
                self.PC.update_oddmentdrawnotes(id_list, **detail)

                self.get_proddetail()
                self.get_oddmentdetail()

        elif index == 3:
            if action == button2:
                detail = {'flag': 0, 'qaid': '', 'qaname': '', 'qadate': None}
                self.PC.update_oddmentdrawnotes(id_list, **detail)

                self.get_proddetail()
                self.get_oddmentdetail()