Esempio n. 1
0
 def get_sys_vars(self, kind=0):
     if self.autoid != 0:
         try:
             if kind == 0:
                 pm = ProductController()
                 vlist = ('prodid', 'prodname', 'commonname', 'batchno',
                          'spec', 'package', 'medkind', 'planamount',
                          'mpunit', 'plantime', 'realamount', 'makedate',
                          'linename', 'workshopid', 'workshopname')
                 self.proddetail = pm.get_producingplan(
                     *vlist, autoid=self.autoid)[0]
             elif kind == 1:
                 sm = StuffController()
                 self.stuffdetail = sm.get_prodstuff(ppid=self.autoid)
                 for item in self.stuffdetail:
                     stufftype = item.stufftype
                     if stufftype == 0:
                         self.stuffdetailZC.append(item)
                         self.stuffdetailZF.append(item)
                     elif stufftype == 1:
                         self.stuffdetailFC.append(item)
                         self.stuffdetailZF.append(item)
                     elif stufftype == 2:
                         self.stuffdetailNB.append(item)
                         self.stuffdetailBC.append(item)
                     elif stufftype == 3:
                         self.stuffdetailWB.append(item)
                         self.stuffdetailBC.append(item)
                     elif stufftype == 4:
                         self.stuffdetailQC.append(item)
             elif kind == 2:
                 sm = StuffController()
                 self.mstuffdetail = sm.get_Mprodstuff(self.autoid)
                 for item in self.mstuffdetail:
                     stufftype = item.stufftype
                     if stufftype == 0:
                         self.stuffdetailMZC.append(item)
                         self.stuffdetailMZF.append(item)
                     elif stufftype == 1:
                         self.stuffdetailMFC.append(item)
                         self.stuffdetailMZF.append(item)
                     elif stufftype == 2:
                         self.stuffdetailMNB.append(item)
                         self.stuffdetailMBC.append(item)
                     elif stufftype == 3:
                         self.stuffdetailMWB.append(item)
                         self.stuffdetailMBC.append(item)
                     elif stufftype == 4:
                         self.stuffdetailMQC.append(item)
             elif kind == 3:
                 lm = LabrecordsController()
                 self.labdetail = lm.get_labrecord(self.autoid)[0]
         except:
             # traceback.print_exc()
             SaveExcept("获取系统变量出错", self.get_content(), kind)
Esempio n. 2
0
 def get_sys_vars(self, kind=0):
     if self.autoid != 0:
         try:
             if kind == 0:
                 pm = ProductController()
                 self.proddetail = pm.get_producingplan(
                     autoid=self.autoid)[0]
             elif kind == 1:
                 sm = StuffController()
                 self.stuffdetail = sm.get_prodstuff(self.autoid)
                 for item in self.stuffdetail:
                     stufftype = item.stufftype
                     if stufftype == 0:
                         self.stuffdetailZC.append(item)
                         self.stuffdetailZF.append(item)
                     elif stufftype == 1:
                         self.stuffdetailFC.append(item)
                         self.stuffdetailZF.append(item)
                     elif stufftype == 2:
                         self.stuffdetailNB.append(item)
                         self.stuffdetailBC.append(item)
                     elif stufftype == 3:
                         self.stuffdetailWB.append(item)
                         self.stuffdetailBC.append(item)
                     elif stufftype == 4:
                         self.stuffdetailQC.append(item)
             elif kind == 2:
                 sm = StuffController()
                 self.mstuffdetail = sm.get_Mprodstuff(self.autoid)
                 for item in self.mstuffdetail:
                     stufftype = item.stufftype
                     if stufftype == 0:
                         self.stuffdetailMZC.append(item)
                         self.stuffdetailMZF.append(item)
                     elif stufftype == 1:
                         self.stuffdetailMFC.append(item)
                         self.stuffdetailMZF.append(item)
                     elif stufftype == 2:
                         self.stuffdetailMNB.append(item)
                         self.stuffdetailMBC.append(item)
                     elif stufftype == 3:
                         self.stuffdetailMWB.append(item)
                         self.stuffdetailMBC.append(item)
                     elif stufftype == 4:
                         self.stuffdetailMQC.append(item)
             elif kind == 3:
                 lm = LabrecordsController()
                 self.labdetail = lm.get_labrecord(1, autoid=self.autoid)[0]
         except:
             # traceback.print_exc()
             pass
class EditProducingplan(QDialog, Ui_Dialog):
    created = pyqtSignal(int)

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

        # if '20' not in user.powers:
        #     self.close()
        #     self.accept_button.setVisible(False)
        #     self.cancel_button.setVisible(False)
        #     self.pushButton_audit.setVisible(False)
        # if user.powers['20'] == 0:
        #     self.close()
        # self.power = '{:03b}'.format(user.powers['20'])
        # if self.power[1] == '0':
        #     self.accept_button.setVisible(False)
        #     self.cancel_button.setVisible(False)
        #     self.pushButton_audit.setVisible(False)

        self.PC = ProductController()
        self.WC = WarehouseController()

        self.autoid = autoid
        self.prod_id = 0
        self.ori_detail = {}
        self.new_detail = {}
        self.detail = {}
        self.stuff_list = []
        self.stuff_repository = []
        self.no_enough_stuff_list = []
        self.treewidget_meterial.hideColumn(1)
        self.treeWidget_package.hideColumn(1)
        # 公式错误信息
        self.errormsg = []

        self.prodname.setup(DB_TABLE[0], PRODUCT_VALUE_TUPLE, PRODUCT_KEY,
                            VALUE_NAME, None, 650, 250)

        self.prodname.getItem.connect(self.setproduct)
        self.set_validator()
        if autoid is not None:
            self.get_detail()
            self.set_treewidget_formula((0, 1, 2), self.treewidget_meterial)
            self.set_treewidget_formula((3, 4), self.treeWidget_package)
        else:
            self.makedate.setDate(QDate.currentDate())

    def set_validator(self):

        doubleValitor = QDoubleValidator()
        doubleValitor.setBottom(0)
        doubleValitor.setDecimals(2)
        doubleValitor.setNotation(QDoubleValidator.StandardNotation)
        self.planamount.setValidator(doubleValitor)

    def setproduct(self, qtreeitem: QTreeWidgetItem):
        self.prod_id = qtreeitem.text(0)
        self.commonname.setText(qtreeitem.text(3))
        self.spec.setText(qtreeitem.text(4))
        self.package_2.setText(qtreeitem.text(5))
        if self.prod_id:
            # flag:产品的类型,0成品,1半成品,2退货, 3验证
            flag = self.productkind.currentIndex()
            key_dict = {'autoid': self.prod_id}
            res = self.PC.get_product_or_stuff_dictionary(
                flag, False, **key_dict)
            if res:
                self.unit.setText(res[0].spunit)
                if flag in (0, 1):
                    lineid = res[0].plid
                elif flag == 2:
                    lineid = res[0].wplid
                elif flag == 3:
                    lineid = res[0].vplid
                else:
                    lineid = 0
                if lineid:
                    productline = ProductLineConroller()
                    pline = productline.get_productline(lineid, flag)
                    if pline:
                        self.prodline.setText(pline[0].linename)
                        self.productworkshop.setText(pline[0].deptid + ' ' +
                                                     pline[0].deptname)

    def set_autoid(self, autoid: int):
        self.autoid = autoid
        # 查询autoid对应的记录,并关联到表格中
        self.get_detail()
        self.new_detail.clear()

    def get_detail(self):
        res = self.PC.get_producingplan(autoid=self.autoid)
        if res:
            # 把生产指令的内容填入表格中
            self.set_data(res[0])
            self.ori_detail = model_to_dict(res[0])
            self.detail = self.ori_detail
        else:
            errordialig = QErrorMessage(self)
            errordialig.setWindowTitle("错误")

    # 初始化编辑生产指令的内容
    def set_data(self, detail):
        self.productkind.setCurrentIndex(detail.pltype)
        self.prodname.setText(detail.prodid + ' ' + detail.prodname)
        self.commonname.setText(detail.commonname)
        self.spec.setText(detail.spec)
        self.package_2.setText(detail.package)
        self.planamount.setText(str(detail.planamount))
        self.unit.setText(detail.spunit)
        self.batchno.setText(detail.batchno)
        self.makedate.setDate(
            QDate(detail.makedate)
            if type(detail.makedate) is datetime.date else user.now_date)
        self.remarks.setText(detail.remark)
        lineid = detail.lineid

        if lineid:
            productline = ProductLineConroller()
            pline = productline.get_productline(lineid, detail.pltype)
            if pline:
                self.prodline.setText(pline[0].linename)
                self.productworkshop.setText(pline[0].deptid + ' ' +
                                             pline[0].deptname)
                self.new_detail['linename'] = pline[0].linename
                self.new_detail['workshopid'] = pline[0].deptid
                self.new_detail['workshopname'] = pline[0].deptname

    def set_treewidget_formula(self, stufftype=(0, 1, 2), qtree=None):
        prodtype = 1 if self.productkind.currentIndex() == 1 else 0
        qtree.clear()
        condition = {
            'prodid': self.prod_id,
            'stufftype__in': stufftype,
            'prodtype': prodtype
        }
        # 获取配方
        self.formula = self.PC.get_data(6, False, *VALUES_TUPLE_PD,
                                        **condition)
        if not len(self.formula):
            return
        stuffkind_list = self.formula.values_list('stuffkind', flat=True)
        condition_sk = {'stuffkind__in': stuffkind_list, 'amount__gt': 0}
        self.stuff_repository = self.WC.get_data(2, False, *VALUES_TUPLE_SD,
                                                 **condition_sk)
        for it in self.stuff_repository:
            condition_lock = {'srid': it['autoid']}
            drawamount_list = self.PC.get_data(
                7, True, *VALUES_TUPLE_SL,
                **condition_lock).exclude(ppid=self.autoid)
            it['realamount'] = it['amount'] - sum(drawamount_list)
        for item in self.formula:
            parent_treeitem = QTreeWidgetItem(qtree)

            parent_treeitem.setText(0, item['stuffkind'])
            parent_treeitem.setText(2, item['formula'])

            stuffkind = item['stuffkind']
            condition_sf = {'stuffkind': stuffkind, 'amount__gt': 0}

            # 获取库存
            stuffrepository = self.WC.get_data(2, False, *VALUES_TUPLE_SD,
                                               **condition_sf)
            if not len(stuffrepository):
                brush = QBrush(1)
                brush.setColor(QColor(255, 85, 0))
                for i in range(0, 13):
                    parent_treeitem.setBackground(i, brush)
                    # Decimal(rnd(eval(presexpression, evalenv(self)),
                    #             precision))
                parent_treeitem.setText(
                    6,
                    str(self.no_stuffrep_count_presamount(item)) +
                    item['presunit'])
                self.no_enough_stuff_list.append(stuffkind)
                continue

            draw_status = self.draw_stuff(item)
            if not draw_status:
                self.no_enough_stuff_list.append(stuffkind)
                brush = QBrush(1)
                brush.setColor(QColor(255, 255, 127))
                for i in range(1, 13):
                    parent_treeitem.setBackground(i, brush)

            for it in stuffrepository:
                condition_lock = {'srid': it['autoid']}
                drawamount_list = self.PC.get_data(7, True, *VALUES_TUPLE_SL,
                                                   **condition_lock)
                qtreeitem = QTreeWidgetItem(parent_treeitem)
                qtreeitem.setText(1, str(it['autoid']))
                qtreeitem.setText(0, it['stuffname'])
                qtreeitem.setText(3, it['batchno'])
                qtreeitem.setText(4, str(it['amount']))
                qtreeitem.setText(5, str(sum(drawamount_list)))
                for sr in self.stuff_list:
                    if it['autoid'] == sr['autoid']:
                        qtreeitem.setText(
                            7,
                            str(sr['newpracamount']) + item['pracunit'])
                        qtreeitem.setText(
                            8,
                            str(sr['drawamount']) + item['drawunit'])

                        parent_treeitem.setText(
                            6,
                            str(sr['presamount']) + item['presunit'])
                        break
                if stufftype == (0, 1, 2):
                    qtreeitem.setText(9, str(it['content']) + it['cunit'])
                    qtreeitem.setText(10, str(it['water']) + '%')
                    qtreeitem.setText(11, str(it['rdensity']))
                    qtreeitem.setText(12, str(it['impurity']))
        qtree.expandAll()
        qtree.resizeColumnToContents(0)
        for i in range(2, 13 if stufftype == (0, 1, 2) else 9):
            qtree.resizeColumnToContents(i)
        qtree.collapseAll()

    def no_stuffrep_count_presamount(self, item):
        stuffkind = item['stuffkind']
        precision = item['precision']
        loss = item['loss']
        # 处理产品信息的变量,去除系统变量
        presexpression = self.reckon_expression(item['presexpression'], 1)
        # 计划量
        try:
            presamount = Decimal(
                rnd(eval(presexpression, evalenv(self)), precision))
            return presamount
        except SyntaxError:
            if stuffkind + ' 计划量' not in self.errormsg:
                self.errormsg.append(stuffkind + ' 计划量')
            return 0

    # 系统根据配方自动领料
    def draw_stuff(self, item):
        stuffkind = item['stuffkind']
        precision = item['precision']
        loss = item['loss']
        # 处理产品信息的变量,去除系统变量
        presexpression = self.reckon_expression(item['presexpression'], 1)
        # 计划量
        try:
            presamount = Decimal(
                rnd(eval(presexpression, evalenv(self)), precision))
        except SyntaxError:
            if stuffkind + ' 计划量' not in self.errormsg:
                self.errormsg.append(stuffkind + ' 计划量')
            presamount = 0

        # 实际量公式,去除系统变量
        pracexpression = self.reckon_expression(item['pracexpression'], 1)
        # 领取量公式,去除系统变量
        drawexpression = self.reckon_expression(item['drawexpression'], 1)
        # 计算领料量,返回领料情况res, 和标记:是否已经领购料
        res = self.reckon_drawamount(stuffkind, presamount, precision,
                                     pracexpression, drawexpression, loss)
        if len(res):
            self.stuff_list_additem(res)

        return self.is_drawamount_enough(stuffkind, presamount)

    # 判断领取的物料是否足够
    def is_drawamount_enough(self, stuffkind, presamount):
        new_presamount = 0
        for item in self.stuff_list:
            if item['stuffkind'] == stuffkind:
                new_presamount += item['newpresamount']

        return True if new_presamount >= presamount else False

    # 把领取的物料加到领料记录中,如果发现重复的情况则替换旧的记录
    def stuff_list_additem(self, newitems):
        for newitem in newitems:
            flat = 0
            for item in self.stuff_list:
                if newitem['autoid'] == item['autoid']:
                    # item = newitem
                    flat = 1
                    break
            if flat == 0:
                self.stuff_list.append(newitem)

    # 计算系统变量
    def reckon_expression(self, expression, iterdepth):
        # iterdepth:迭代深度,超过50则抛出RuntimeError
        # 产品信息变量,ex: @planamount@, @spec@, @package@
        if iterdepth > 50:
            raise RuntimeError
        pattern = re.findall(r'@[%?!()()::.#\w]*@', expression)
        for item in pattern:
            # 引用其他物料
            if len(item[1:-1].split('.')) == 2:
                var_name, var_item = item[1:-1].split('.')
                value = Decimal('0')
                # 标记是否找到了对应的物料
                find_stuff_flag = 0
                for stuff in self.stuff_list:
                    if stuff['stuffkind'] == var_name:
                        find_stuff_flag = 1
                        if var_item == '计划量':
                            value = stuff[VAR_ITEM[var_item]]
                            expression = expression.replace(item, str(value))
                            break
                        else:
                            value += stuff[VAR_ITEM[var_item]]
                        expression = expression.replace(item, str(value))
                # 没有找到对应的物料则再本领料单中继续寻找
                if find_stuff_flag == 0:
                    for item in self.formula:
                        try:
                            if item['stuffkind'] == var_name:
                                # stuffkind = item.text(2)
                                precision = item['precision']
                                loss = item['loss']
                                # 处理产品信息的变量,去除系统变量
                                presexpression = self.reckon_expression(
                                    item['presexpression'], iterdepth + 1)
                                # 计划量
                                try:
                                    presamount = Decimal(
                                        rnd(
                                            eval(presexpression,
                                                 evalenv(self)), precision))
                                except SyntaxError:
                                    if var_name + ' 计划量' not in self.errormsg:
                                        self.errormsg.append(var_name + ' 计划量')
                                    presamount = 0
                                # 把计划量加到产品信息变量中
                                # self.detail['presamount'] = presamount
                                # 实际量公式,去除系统变量
                                pracexpression = self.reckon_expression(
                                    item['pracexpression'], iterdepth + 1)
                                # 领取量公式,去除系统变量
                                drawexpression = self.reckon_expression(
                                    item['drawexpression'], iterdepth + 1)
                                # 计算领料量,返回领料情况res, 和标记:是否已经领购料
                                res = self.reckon_drawamount(
                                    var_name, presamount, precision,
                                    pracexpression, drawexpression, loss)
                                if len(res):
                                    self.stuff_list_additem(res)
                                    # self.is_drawamount_enough()
                                    expression = self.reckon_expression(
                                        expression, iterdepth + 1)
                        except RuntimeError:
                            break
            # 引用生产指令的参数
            else:
                key = item.replace('@', '')
                if key in self.detail:
                    expression = expression.replace(item,
                                                    str(self.detail[key]))
        # pattern_1 = re.findall(r'@[%?!()()::.#\w]*@', expression)
        return expression

    # 计算实际量
    def reckon_pracamount(self, autoid, presamount, precision, expression):
        # stuffkind: 物料种类
        # presamount: 计划量
        # expression: 实际量的公式
        stuff_detail = []
        # 最终要领取的批次和实际量
        # 分析公式,获取变量
        pattern = re.findall(r'@\w*@', expression)
        # 把变量设置为对应的值
        for item in self.stuff_repository:
            if autoid != item['autoid']:
                continue
            for key in pattern:
                k = key.replace('@', '')
                if k == 'presamount':
                    expression = expression.replace(key, str(presamount))
                elif k in item:
                    expression = expression.replace(key, str(item[k]))
                elif k in self.detail:
                    expression = expression.replace(key, str(self.detail[k]))
            try:
                pracamount = Decimal(
                    rnd(eval(expression, evalenv(self)), precision))
            except SyntaxError:
                if item['stuffkind'] + ' 实际量' not in self.errormsg:
                    self.errormsg.append(item['stuffkind'] + ' 实际量')
                pracamount = 0

            item['pracamount'] = pracamount

    # 计算领取量
    # stuffkindorsrid: 根据flat决定类型, True是物料种类,False是srid
    # presamount: 计划量
    # precision: 计算结果精度
    # prac_expression: 实际量公式
    # draw_expression: 领取公式
    # loss: 损耗限度
    # flat: 是否需要继续领下一批物料,默认为True即继续领下一批物料,
    #       False则不再领取下一批物料
    def reckon_drawamount(self,
                          stuffkindorsrid,
                          presamount,
                          precision,
                          prac_expression,
                          draw_expression,
                          loss=0,
                          flat=True):

        # 要领取的物料批次
        draw_list = []
        # 已经领取了的量
        has_drawamount = 0
        # 分析公式,获取变量
        pattern = re.findall(r'@\w*@', draw_expression)
        # 把变量设置为对应的值
        for item in self.stuff_repository:

            item['presamount'] = presamount
            new_expression = draw_expression
            if has_drawamount != 0:
                presamount -= has_drawamount
                has_drawamount = 0
            if stuffkindorsrid != (item['stuffkind']
                                   if flat else str(item['autoid'])):
                continue
            item['loss'] = loss
            item['newpresamount'] = presamount
            item['precision'] = precision
            # 算出该批次对应的实际量
            self.reckon_pracamount(item['autoid'], presamount, precision,
                                   prac_expression)
            for key in pattern:

                k = key.replace('@', '')
                if k in item:
                    new_expression = new_expression.replace(key, str(item[k]))
                elif k in self.detail:
                    new_expression = new_expression.replace(
                        key, str(self.detail[k]))
            try:
                drawamount = Decimal(
                    rnd(eval(new_expression, evalenv(self)), precision))
            except SyntaxError:
                if stuffkindorsrid + ' 领取量' not in self.errormsg:
                    self.errormsg.append(stuffkindorsrid + ' 领取量')
                drawamount = 0
                continue
            if item['realamount'] >= drawamount:
                item['drawamount'] = drawamount
                item['newpracamount'] = item['pracamount']
                draw_list.append(item)
                break
            else:
                # 转化为计划量 = 领取量 * 计划量 / 实际量
                has_drawamount = Decimal(
                    rnd(item['realamount'] * presamount / item['pracamount'],
                        precision))
                item['newpresamount'] = has_drawamount
                item['newpracamount'] = rnd(item['realamount'], precision)
                item['drawamount'] = rnd(item['realamount'], precision)
                draw_list.append(item)
                if not flat:
                    # 指定库存记录时,默认按领够料处理
                    break
        return draw_list

    # 产品种类改变时
    @pyqtSlot(int)
    def on_productkind_currentIndexChanged(self, p_int):
        if p_int in (0, 2, 3):
            self.prodname.setup(DB_TABLE[0], PRODUCT_VALUE_TUPLE, PRODUCT_KEY,
                                VALUE_NAME, None, 650, 250)
        else:
            self.prodname.setup(DB_TABLE[1], STUFF_VALUE_TUPLE, STUFF_KEY,
                                VALUE_NAME, None, 650, 250)

    # 修改计划量时触发
    @pyqtSlot()
    def on_planamount_editingFinished(self):
        p_str = self.planamount.text()
        planamount = Decimal(p_str) if p_str != '' else 0
        try:
            if planamount != self.ori_detail['planamount']:
                self.new_detail['planamount'] = planamount
                self.detail['planamount'] = planamount
            else:
                try:
                    del self.new_detail['planamount']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['planamount'] = planamount
            self.detail['planamount'] = planamount

        self.stuff_list = []
        self.stuff_repository = []
        self.no_enough_stuff_list = []
        self.set_treewidget_formula((0, 1, 2), self.treewidget_meterial)
        self.set_treewidget_formula((3, 4), self.treeWidget_package)

    # 修改批号时触发
    @pyqtSlot(str)
    def on_batchno_textEdited(self, p_str):
        try:
            if p_str != self.ori_detail['batchno']:
                self.new_detail['batchno'] = p_str
            else:
                try:
                    del self.new_detail['batchno']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['batchno'] = p_str

    # 修改生产日期时触发
    @pyqtSlot(QDate)
    def on_makedate_dateChanged(self, q_date):
        p_date = q_date.toPyDate()
        try:
            if p_date != self.ori_detail['makedate']:
                self.new_detail['makedate'] = p_date
            else:
                try:
                    del self.new_detail['makedate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['makedate'] = p_date

    # 修改备注时触发
    @pyqtSlot(str)
    def on_remarks_textChanged(self, p_str):
        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_accept_button_clicked(self):
        if self.prodname.flat == 0:
            text = "没有找到对应的产品信息,请修改后重试!"
            informative = "选择好产品名称后请不要再修改,否则将导致系统无法找到正确的产品!"
            errordialig = MessageBox(self, text=text, informative=informative)
            errordialig.exec()
            self.prodname.setFocus()
            return
        if len(self.no_enough_stuff_list):
            text = "以下物料不足!"
            informative = ";\n".join(self.no_enough_stuff_list)
            errordialig = MessageBox(self,
                                     text=text,
                                     informative=informative,
                                     yes_text="继续下达指令")
            res = errordialig.exec()
            if res == 65536:
                self.prodname.setFocus()
                return
        # 有修改过数据
        if self.new_detail:
            try:
                # 修改过记录,把当前的人员和日期存入修改记录中
                self.new_detail['instructorid'] = user.user_id
                self.new_detail['instructorname'] = user.user_name
                self.new_detail['plandate'] = user.now_date
                self.new_detail['deptid'] = user.dept_id
                self.new_detail['deptname'] = user.dept_name
                self.new_detail['bpconstitutorid'] = user.user_id
                self.new_detail['bpconstitutorname'] = user.user_name
                self.new_detail['bpconsdate'] = user.now_date

                # autoid不为空,则为修改记录
                # 否则为插入记录
                if self.autoid:
                    self.PC.update_producingplan(autoid=self.autoid,
                                                 **self.new_detail)
                    condition = {'ppid': self.autoid}
                    self.PC.delete_data(7, condition)
                else:
                    prodtype = self.productkind.currentIndex()
                    prod_id = self.prodname.namelist.currentItem().text(0)
                    self.new_detail['id'] = prod_id
                    ppid = self.PC.update_producingplan(prodtype=prodtype,
                                                        **self.new_detail)
                    self.autoid = ppid
                    self.created.emit(self.autoid)
                for item in self.stuff_list:
                    detail = {
                        'ppid': self.autoid,
                        'srid': item['autoid'],
                        'drawamount': item['drawamount'],
                        'stuffkind': item['stuffkind']
                    }
                    self.PC.update_data(7, **detail)
                self.accept()
            except Exception as e:
                SaveExcept(e, "提交生产指令时出错", **self.new_detail)
        else:
            self.close()

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

    @pyqtSlot()
    def on_pushButton_audit_clicked(self):
        if len(self.no_enough_stuff_list):
            text = "以下物料不足!无法执行指令!"
            informative = ";\n".join(self.no_enough_stuff_list)
            errordialig = MessageBox(self, text=text, informative=informative)
            errordialig.exec()
            return
        if self.autoid is None:
            self.new_detail['instructorid'] = user.user_id
            self.new_detail['instructorname'] = user.user_name
            self.new_detail['plandate'] = user.now_date
            self.new_detail['deptid'] = user.dept_id
            self.new_detail['deptname'] = user.dept_name
            self.new_detail['bpconstitutorid'] = user.user_id
            self.new_detail['bpconstitutorname'] = user.user_name
            self.new_detail['bpconsdate'] = user.now_date

        self.new_detail['status'] = 1
        self.new_detail['statustime'] = user.now_time
        self.new_detail['warrantorid'] = user.user_id
        self.new_detail['warrantorname'] = user.user_name
        self.new_detail['warrantdate'] = user.now_date
        self.new_detail['qadate'] = user.now_date
        self.new_detail['bpwarrantorid'] = user.user_id
        self.new_detail['bpwarrantorname'] = user.user_name
        self.new_detail['bpwarrantdate'] = user.now_date
        if self.autoid is None:
            prodtype = self.productkind.currentIndex()
            prod_id = self.prodname.namelist.currentItem().text(0)
            self.new_detail['id'] = prod_id
            ppid = self.PC.update_producingplan(prodtype=prodtype,
                                                **self.new_detail)
            self.autoid = ppid
            self.created.emit(self.autoid)
            # self.PC.update_data(3, **self.new_detail)
        else:
            condition = {'autoid': self.autoid}
            self.PC.update_data(3, condition, **self.new_detail)
        for item in self.stuff_list:
            if item['drawamount'] == 0:
                continue
            detail = {
                'ppid': self.autoid,
                'srid': item['autoid'],
                'drawamount': item['drawamount'],
                'stuffkind': item['stuffkind']
            }
            self.PC.update_data(7, **detail)
        self.accept()
class ProductRepositoryModule(QWidget, Ui_Form):

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

        if '42' not in user.powers:
            self.close()
        if user.powers['42'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['42'])

        self.WC = WarehouseController()
        self.LC = LabrecordsController()
        self.PC = ProductController()
        self.current_button = self.radioButton_batchno
        self.get_product_list()

    def get_product_list(self):
        if self.current_button == self.radioButton_batchno:
            self.treeWidget_productbatchnolist.setVisible(True)
            self.treeWidget_productkindlist.setVisible(False)
            current_tree = self.treeWidget_productbatchnolist
            current_tree.hideColumn(0)
        elif self.current_button == self.radioButton_kind:
            self.treeWidget_productbatchnolist.setVisible(False)
            self.treeWidget_productkindlist.setVisible(True)
            current_tree = self.treeWidget_productkindlist
        else:
            return

        current_tree.clear()
        key_dict = {'stockamount__gt': 0}
        product_list = self.WC.get_productrepository(
            False, **key_dict
        )
        if not len(product_list):
            return

        if current_tree == self.treeWidget_productbatchnolist:
            self.set_batchno_tree(current_tree, product_list)
            for i in range(1, 15):
                current_tree.resizeColumnToContents(i)
        elif current_tree == self.treeWidget_productkindlist:
            self.set_kind_tree(current_tree, product_list)
            for i in range(0, 6):
                current_tree.resizeColumnToContents(i)
        else:
            return

    def set_batchno_tree(self, current_tree, product_list):
        p_list = product_list.values(*VALUES_TUPLE_BATCHNO)
        """
        .extra(
            select={
                'prodid': 'prodid', 'prodname': 'prodname', 'spec': 'spec',
                'commonname': 'commonname', 'batchno': 'batchno',
                'package': 'package', 'spunit': 'spunit',
                'makedate': 'makedate', 'expireddates': 'expireddates'
            },
            tables=['producingplan'],
            where=['producingplan.autoid=ppid']
        )
        """
        for item in p_list:
            qtreeitem = QTreeWidgetItem(current_tree)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, SOURCE[item['pisource']])
            qtreeitem.setText(2, item['prodid'] + ' ' + item['prodname'])
            qtreeitem.setText(3, item['commonname'])
            if item['pisource'] == 2:
                key_dict = {'autoid': item['hxid']}
                hx_batchno_list = self.PC.get_producingplan(
                    True, *VALUES_TUPLE_PRODUCINGPLAN, **key_dict
                )
                hx_batchno = ''
                if len(hx_batchno_list):
                    hx_batchno = hx_batchno_list[0]
                qtreeitem.setText(4, item['batchno'] + ' ' + hx_batchno)

                qtreeitem.setText(
                    7, to_str((item['piamount'] - item[
                        'hxamount'])) + '+' +
                       to_str(item['hxamount'])
                )
                qtreeitem.setText(
                    8, to_str(item['stockamount'] - item[
                        'hxstockamount']) + '+' + to_str(item['hxstockamount'])
                )
            else:
                qtreeitem.setText(4, item['batchno'])
                qtreeitem.setText(7, str(item['piamount']))
                qtreeitem.setText(8, str(item['stockamount']))

            qtreeitem.setText(5, item['spec'])
            qtreeitem.setText(6, item['package'])
            qtreeitem.setText(9, item['spunit'])
            qtreeitem.setText(10, item['position'])

            qtreeitem.setText(11, str(item['indate']))
            if type(item['makedate']) is datetime.date:
                qtreeitem.setText(12, str(item['makedate']))
                qtreeitem.setText(13, str(item['expireddate']))
            qtreeitem.setText(
                14, item['warehousemanid'] + item['warehousemanname']
            )

    def set_kind_tree(self, current_tree, product_list):
        kind_list = product_list.values(*VALUES_TUPLE_KIND).annotate(
            stockamount=Sum('stockamount'), piamount=Sum('piamount')
        )
        """
        .extra(
            select={
                'prodid': 'prodid', 'prodname': 'prodname', 'spec': 'spec',
                'commonname': 'commonname', 'package': 'package',
                'spunit': 'spunit'
            },
            tables=['producingplan'],
            where=['producingplan.autoid=ppid']
        ). \
        """
        for item in kind_list:
            qtreeitem = QTreeWidgetItem(current_tree)
            qtreeitem.setText(0, item['prodid'] + item['prodname'])
            qtreeitem.setText(1, item['commonname'])
            qtreeitem.setText(2, item['spec'])
            qtreeitem.setText(3, item['package'])
            qtreeitem.setText(4, to_str(item['piamount']))
            qtreeitem.setText(5, to_str(item['stockamount']))
            qtreeitem.setText(6, item['spunit'])

    pyqtSlot(bool)

    def on_radioButton_batchno_toggled(self, p_bool):
        if p_bool:
            self.current_button = self.radioButton_batchno
            self.get_product_list()

    pyqtSlot(bool)
    def on_radioButton_kind_toggled(self, p_bool):
        if p_bool:
            self.current_button = self.radioButton_kind
            self.get_product_list()

    @pyqtSlot(QPoint)
    def on_treeWidget_productbatchnolist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        id = 0
        batchno = ''
        sender_widget = self.sender()
        current_item = sender_widget.currentItem()
        if current_item is None:
            return

        id = int(current_item.text(0))
        prodid, stuffname = current_item.text(2).split(' ')
        batchno = current_item.text(4)

        menu = QMenu()
        button1 = menu.addAction("查看检验报告")

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

        if action == button1:
            detail = FindCheckReportModule(prodid, batchno, self)
            detail.show()
Esempio n. 5
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
Esempio n. 6
0
class MidproddrawnoteModule(QWidget, Ui_Form):
    """ 半成品登记/发放记录
    autoid: 登记/发放表的ppid
    kind: 0为登记记录,1为发放记录
    """
    def __init__(self, autoid, kind, parent=None):
        super(MidproddrawnoteModule, self).__init__(parent)
        self.autoid = autoid
        self.kind = kind
        self.setupUi(self)
        self.PC = ProductController()
        self.ori_detail = dict()
        self.new_detail = dict()

        if kind == 0:
            self.treeWidget_midproductlist.headerItem().setText(3, "中间站登记人")
            self.treeWidget_midproductlist.headerItem().setText(5, "登记工人")
        elif kind == 1:
            self.treeWidget_midproductlist.headerItem().setText(3, "中间站发放人")
            self.treeWidget_midproductlist.headerItem().setText(5, "领料工人")
        # 获取半成品信息
        self.get_midprod()
        # 获取半成品的登记/发放状态
        self.get_midstatus()

    def get_midprod(self):
        self.treeWidget_midproductlist.clear()
        values_list = ["autoid", "container", "amount", "unit"]
        if self.kind == 0:
            reg_list = [
                "registrarid", "registrarname", "regtime", "workerid",
                "workername"
            ]
        elif self.kind == 1:
            reg_list = [
                "providerid", "providername", "drawtime", "drawerid",
                "drawername"
            ]
        values_list += reg_list
        key_dict = {'ppid': self.autoid}
        res = self.PC.get_midproddrawnotes(True, *values_list, **key_dict)
        if len(res):
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_midproductlist)
                qtreeitem.setText(0, str(item[0]))  # autoid
                qtreeitem.setText(1, str(item[1]))  # 桶号
                qtreeitem.setText(2, str(item[2]) + item[3])  # 数量
                qtreeitem.setText(3, item[4] + ' ' + item[5])  # 登记人/发放人
                qtreeitem.setText(4, str(item[6]))  # 登记/发放日期
                qtreeitem.setText(5, item[7] + ' ' + item[8])  # 工人

            self.treeWidget_midproductlist.hideColumn(0)
            for i in range(1, 6):
                self.treeWidget_midproductlist.resizeColumnToContents(i)

    def get_midstatus(self):
        values_tuple = ("midstatus", )
        key_dict = {'autoid': self.autoid}
        res = self.PC.get_producingplan(False, *values_tuple, **key_dict)
        if len(res) == 1:
            if res[0]['midstatus'] > 2 and self.kind == 0:
                # 已经完成发放记录,则无法修改登记记录
                self.pushButton_workersign.setVisible(False)
            elif res[0]['midstatus'] == 0 and self.kind == 1:
                # 还没有完成登记,则无法修改发放记录
                self.pushButton_workersign.setVisible(False)

    @pyqtSlot()
    def on_pushButton_workersign_clicked(self):
        it = QTreeWidgetItemIterator(self.treeWidget_midproductlist)

        id_list = []
        while it.value():
            item = it.value()
            id_list.append(int(item.text(0)))
            it += 1
        if not len(id_list):
            return
        detail = dict()
        status: int
        if self.kind == 0:
            detail = {'workerid': user.user_id, 'workername': user.user_name}
            status = 1
        elif self.kind == 1:
            detail = {'drawerid': user.user_id, 'drawername': user.user_name}
            status = 2

        res = self.PC.update_midproddrawnotes(id_list, self.autoid, status,
                                              **detail)
        if res > 0:
            self.get_midprod()
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()
class ProductLineConroller(object):
    def __init__(self):
        self.PC = ProductController()

    def get_productline(self, autoid=None, pltype=None):
        kwarg = dict()
        if autoid:
            kwarg['autoid'] = autoid
        if pltype is not None:
            kwarg['pltype'] = pltype
        if kwarg:
            return ProductLineModel.get_productline(**kwarg)
        else:
            return False

    def get_workflow(self, plid, *args, **kwargs):
        return ProductLineModel.get_workflow(plid, *args, **kwargs)

    def get_formula(self, *args, **kwargs):
        return ProductLineModel.get_formula(*args, **kwargs)

    def get_product_detail(self, flag=0, *args, **kwargs):
        return self.PC.get_producingplan(flag, *args, **kwargs)

    def delet_delet_productline(
        self,
        plid,
    ):
        with transaction.atomic():
            p1 = transaction.savepoint()
            condition = {'wfid': wfid}
            for i in range(3, 6):
                self.delete_data(i, condition)
            condition_wf = {'autoid': wfid}
            self.delete_data(1, condition_wf)
            condition_update = {'seqid__gt': seqid}
            detail_update = {'seqid': F('seqid') - 1}
            self.update_data(1, condition_update, **detail_update)

    def delet_post(self, wfid, seqid):
        with transaction.atomic():
            p1 = transaction.savepoint()
            condition_wf = {'autoid': wfid}
            self.delete_data(1, condition_wf)
            condition_update = {'seqid__gt': seqid}
            detail_update = {'seqid': F('seqid') - 1}
            self.update_data(1, condition_update, **detail_update)

    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 ProductLineModel.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 ProductLineModel.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 ProductLineModel.delete_data(table_str, err_msg, condition,
                                            *args, **kwargs)
class PorductionInstructionModule(QWidget, Ui_Form):

    def __init__(self, autoid, parent=None):
        super(PorductionInstructionModule, self).__init__(parent)
        self.autoid = autoid
        self.setupUi(self)
        self.SC = StuffController()
        self.PC = ProductController()
        self.ori_detail = dict()
        self.new_detail = dict()
        # 获取物料信息
        self.get_stufflist()
        # 获取生产指令信息
        self.get_detail()

    # 获取已经领取了的物料
    def get_stufflist(self):
        values_tupe = (
            "autoid", "lrid", "stuffid", "stuffname", "batchno", "spec",
            "package", "presamount", "content", "cunit", "water",
            "impurity", "rdensity", "presunit"
        )
        key_dict = {
            'ppid': self.autoid,
            'stufftype__in': (0, 1, 2)
        }
        res = self.SC.get_prodstuff(False, *values_tupe, **key_dict)
        if len(res):
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_stufflist)
                qtreeitem.setText(0, str(item['autoid']))  # autoid
                qtreeitem.setText(1, str(item['lrid']))  # lrid
                qtreeitem.setText(2, item['stuffid'] + ' ' + item[
                    'stuffname'])  # 物料
                qtreeitem.setText(3, item['batchno'])  # 进厂批号
                qtreeitem.setText(4, item['spec'])  # 含量规格
                qtreeitem.setText(5, item['package'])  # 包装规格
                qtreeitem.setText(6, str(item['presamount']) + item[
                    'presunit'])  # 计划量
                qtreeitem.setText(7, str(item['content']) + item[
                    'cunit'])  # 含量/效价
                qtreeitem.setText(8, str(item['water']) + '%')  # 水分
                qtreeitem.setText(9, str(item['impurity']))  # 相对密度
                qtreeitem.setText(10, str(item['rdensity']))  # 杂质

            self.treeWidget_stufflist.hideColumn(0)
            self.treeWidget_stufflist.hideColumn(1)
            for i in range(2, 11):
                self.treeWidget_stufflist.resizeColumnToContents(i)



    def get_detail(self):
        values_list = (
            'instructorid', 'instructorname', 'warrantorid', 'warrantorname',
            'executorid', 'executorname', 'plandate', 'warrantdate',
            'executedate'
        )
        key_dict = {
            'autoid': self.autoid
        }
        res = self.PC.get_producingplan(False, *values_list, **key_dict)
        if len(res) == 0:
            return

        self.ori_detail = res[0]
        self.pushButton_instructor.setText(
            self.ori_detail['instructorid'] + ' ' +
            self.ori_detail['instructorname']
        )
        self.pushButton_warrantor.setText(
            self.ori_detail['warrantorid'] + ' ' +
            self.ori_detail['warrantorname']
        )
        self.pushButton_executor.setText(
            self.ori_detail['executorid'] + ' ' +
            self.ori_detail['executorname']
        )
        if type(self.ori_detail['plandate']) is datetime.date:
            self.dateEdit_plandate.setDate(self.ori_detail['plandate'])
        if type(self.ori_detail['warrantdate']) is datetime.date:
            self.dateEdit_warrantdate.setDate(self.ori_detail['warrantdate'])
        if type(self.ori_detail['executedate']) is datetime.date:
            self.dateEdit_executedate.setDate(self.ori_detail['executedate'])
class PackageInstructionModule(QWidget, Ui_Form):

    def __init__(self, autoid, parent=None):
        super(PackageInstructionModule, self).__init__(parent)
        self.autoid = autoid
        self.setupUi(self)
        self.SC = StuffController()
        self.PC = ProductController()
        self.ori_detail = dict()
        self.new_detail = dict()
        # 获取物料信息
        self.get_stufflist()
        # 获取批包装指令信息
        self.get_detail()

    # 获取已经领取了的物料
    def get_stufflist(self):
        values_tupe = (
            "autoid", "lrid", "stuffid", "stuffname", "batchno", "spec",
            "package", "presamount", "content", "cunit", "water",
            "impurity", "rdensity", "presunit"
        )
        key_dict = {
            'ppid': self.autoid,
            'stufftype__in': (3, 4)
        }
        res = self.SC.get_prodstuff(False, *values_tupe, **key_dict)
        if len(res):
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_stufflist)
                qtreeitem.setText(0, str(item['autoid']))  # autoid
                qtreeitem.setText(1, str(item['lrid']))  # lrid
                qtreeitem.setText(2, item['stuffid'] + ' ' + item[
                    'stuffname'])  # 物料
                qtreeitem.setText(3, item['batchno'])  # 进厂批号
                qtreeitem.setText(4, item['spec'])  # 含量规格
                qtreeitem.setText(5, item['package'])  # 包装规格
                qtreeitem.setText(6, str(item['presamount']) + item[
                    'presunit'])  # 计划量
                qtreeitem.setText(7, str(item['content']) + item[
                    'cunit'])  # 含量/效价
                qtreeitem.setText(8, str(item['water']) + '%')  # 水分
                qtreeitem.setText(9, str(item['impurity']))  # 相对密度
                qtreeitem.setText(10, str(item['rdensity']))  # 杂质

            self.treeWidget_stufflist.hideColumn(0)
            self.treeWidget_stufflist.hideColumn(1)
            for i in range(2, 11):
                self.treeWidget_stufflist.resizeColumnToContents(i)



    def get_detail(self):
        values_list = (
            'bpconstitutorid', 'bpconstitutorname', 'bpwarrantorid', 'bpwarrantorname',
            'bpexecutorid', 'bpexecutorname', 'bpconsdate', 'bpwarrantdate',
            'bpexecutedate', 'bpdate'
        )
        key_dict = {
            'autoid': self.autoid
        }
        res = self.PC.get_producingplan(False, *values_list, **key_dict)
        if len(res) == 0:
            return

        self.ori_detail = res[0]
        self.pushButton_bpconstitutor.setText(
            self.ori_detail['bpconstitutorid'] + ' ' +
            self.ori_detail['bpconstitutorname']
        )
        self.pushButton_bpwarrantor.setText(
            self.ori_detail['bpwarrantorid'] + ' ' +
            self.ori_detail['bpwarrantorname']
        )
        self.pushButton_bpexecutor.setText(
            self.ori_detail['bpexecutorid'] + ' ' +
            self.ori_detail['bpexecutorname']
        )
        if type(self.ori_detail['bpconsdate']) is datetime.date:
            self.dateEdit_bpconsdate.setDate(self.ori_detail['bpconsdate'])
        if type(self.ori_detail['bpwarrantdate']) is datetime.date:
            self.dateEdit_bpwarrantdate.setDate(self.ori_detail['bpwarrantdate'])
        if type(self.ori_detail['bpexecutedate']) is datetime.date:
            self.dateEdit_bpexecutedate.setDate(self.ori_detail['bpexecutedate'])
        else:
            self.dateEdit_bpexecutedate.setDate(user.now_date)
        if type(self.ori_detail['bpdate']) is datetime.date:
            self.dateEdit_bpdate.setDate(self.ori_detail['bpdate'])
        else:
            self.dateEdit_bpdate.setDate(user.now_date)

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

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

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

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if len(self.new_detail):
            res = self.PC.update_producingplan(self.autoid, **self.new_detail)
Esempio n. 11
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'])
Esempio n. 12
0
class MidproddetailModule(QWidget, Ui_Form):
    """ 半成品登记/发放列表记录记录
    分3个标签,0:未登记,1:已登记,2:已发放
    点击其中一条生产记录时下方显示对应的记录内容
    在未登记标签里右键可以选择增加新的登记信息,以及工人签名
    在已登记标签里右键可以选中发放签名以及工人签名
    """

    def __init__(self, parent=None):
        super(MidproddetailModule, self).__init__(parent)
        self.setupUi(self)
        self.ppid = 0
        self.sign_id = ''
        self.sign_name = ''
        self.PC = ProductController()
        self.ori_detail = dict()
        self.new_detail = dict()
        self.groupBox.setVisible(False)

        # 获取当前状态的批生产记录
        self.get_prodstatusinmid()

    def get_prodstatusinmid(self):
        self.treeWidget_prodlist.clear()
        values_tuple = (
            "autoid", "prodid", "prodname", "commonname", "spec", "package",
            "planamount", "spunit", 'batchno'
        )
        index = self.tabWidget.currentIndex()
        key_dict = {
            'midstatus': index
        }
        res = self.PC.get_producingplan(False, *values_tuple, **key_dict)
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_prodlist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['prodid'] + ' ' + item['prodname'])
            qtreeitem.setText(2, item['commonname'])
            qtreeitem.setText(3, item['batchno'])
            qtreeitem.setText(4, item['spec'])
            qtreeitem.setText(5, item['package'])
            qtreeitem.setText(6, str(item['planamount']) + item['spunit'])
        self.treeWidget_prodlist.hideColumn(0)
        for i in range(1, 7):
            self.treeWidget_prodlist.resizeColumnToContents(i)

    # 获取半成品信息
    def get_midprod(self):
        self.treeWidget_midprodlist.clear()
        values_list = [
            "autoid", "container", "amount", "unit", "registrarid",
            "registrarname", "regtime", "workerid", "workername", "providerid",
            "providername", "drawtime", "drawerid", "drawername"]

        key_dict = {
            'ppid': self.ppid
        }
        res = self.PC.get_midproddrawnotes(True, *values_list, **key_dict)
        if len(res):
            for item in res.order_by('container'):
                qtreeitem = QTreeWidgetItem(self.treeWidget_midprodlist)
                qtreeitem.setText(0, str(item[0]))  # autoid
                qtreeitem.setText(1, str(item[1]))  # 桶号
                qtreeitem.setText(2, str(item[2]) + item[3])  # 数量
                qtreeitem.setText(3, item[4] + ' ' + item[5])  # 登记人
                qtreeitem.setText(4, str(item[6]))  # 登记日期
                qtreeitem.setText(5, item[7] + ' ' + item[8])  # 登记工人
                qtreeitem.setText(6, item[9] + ' ' + item[10])  # 发放人
                qtreeitem.setText(7, str(item[11]) if type(
                    item[11]) is datetime.datetime else '')  # 发放日期
                qtreeitem.setText(8, item[12] + ' ' + item[13])  # 领取工人

            self.treeWidget_midprodlist.hideColumn(0)
            for i in range(1, 6):
                self.treeWidget_midprodlist.resizeColumnToContents(i)

    # @pyqtSlot()
    # def on_pushButton_workersign_clicked(self):
    #     it = QTreeWidgetItemIterator(self.treeWidget_midproductlist)
    #
    #     id_list = []
    #     while it.value():
    #         item = it.value()
    #         id_list.append(int(item.text(0)))
    #         it += 1
    #     if not len(id_list):
    #         return
    #     detail = dict()
    #     status : int
    #     if self.kind == 0:
    #         detail = {
    #             'workerid': user.user_id,
    #             'workername': user.user_name
    #         }
    #         status = 1
    #     elif self.kind == 1:
    #         detail = {
    #             'drawerid': user.user_id,
    #             'drawername': user.user_name
    #         }
    #         status = 2
    #
    #     res = self.PC.update_midproddrawnotes(id_list, self.autoid, status, **detail)
    #     if res > 0:
    #         self.get_midprod()

    @pyqtSlot(int)
    def on_tabWidget_currentChanged(self, p_int):
        getattr(self, 'tab_' + str(p_int)).setLayout(self.gridLayout_2)
        self.get_prodstatusinmid()
        self.groupBox.setVisible(False)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_prodlist_itemClicked(self, qtreeitem, p_int):
        if not self.groupBox.isVisible():
            self.groupBox.setVisible(True)
        self.ppid = int(qtreeitem.text(0))
        self.get_midprod()

    @pyqtSlot(QPoint)
    def on_treeWidget_midprodlist_customContextMenuRequested(self, pos):
        # 返回调用者的对象
        sender_widget = self.sender()
        menu = QMenu()
        index = self.tabWidget.currentIndex()
        if index == 0:
            button1 = menu.addAction("增加")
            button2 = menu.addAction("修改")
            button3 = menu.addAction("删除")
            button4 = menu.addAction("登记工人签名")

        elif index == 1:
            button5 = menu.addAction("发放人签名")
            button6 = menu.addAction("领取工人签名")
        else:
            return

        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        if index == 0:
            if action == button1:
                ppid = int(self.treeWidget_prodlist.currentItem().text(0))
                detail = Modifymiddetailmodule(ppid=ppid, parent=self)
                detail.itemAdded.connect(self.get_midprod)
                detail.show()
            elif action == button2:
                qtreeitem = sender_widget.currentItem()
                if not qtreeitem:
                    return
                detail = Modifymiddetailmodule(autoid=int(qtreeitem.text(0)),
                                               parent=self)
                detail.accepted.connect(self.get_midprod)
                detail.show()
            elif action == button3:
                items = sender_widget.selectedItems()
                if not items:
                    return
                id_list = []
                for item in items:
                    id_list.append(int(item.text(0)))
                res = self.PC.delete_midproddrawnotes(id_list)
                if res:
                    self.get_midprod()
            elif action == button4:
                signmodule = SignModule()
                signmodule.userchanged.connect(self.set_signuser)
                signmodule.exec()
                id_list = []
                it = QTreeWidgetItemIterator(self.treeWidget_midprodlist)
                while it.value():
                    qtreeitem = it.value()
                    id_list.append(int(qtreeitem.text(0)))
                    it += 1
                detail = {
                    'workerid': self.sign_id,
                    'workername': self.sign_name
                }
                if not len(id_list):
                    return
                res = self.PC.update_midproddrawnotes(
                    autoid=id_list, pid=self.ppid, **detail, status=1
                )
                if res:
                    self.get_midprod()
                    self.get_prodstatusinmid()
        elif index == 1:
            if action == button5:
                signmodule = SignModule()
                signmodule.userchanged.connect(self.set_signuser)
                signmodule.exec()
                id_list = []
                it = QTreeWidgetItemIterator(self.treeWidget_midprodlist)
                while it.value():
                    qtreeitem = it.value()
                    id_list.append(int(qtreeitem.text(0)))
                    it += 1
                detail = {
                    'providerid': self.sign_id,
                    'providername': self.sign_name,
                    'drawtime': user.time
                }
                if not len(id_list):
                    return
                res = self.PC.update_midproddrawnotes(autoid=id_list, **detail)
                if res:
                    self.get_midprod()
                    self.get_prodstatusinmid()
            elif action == button6:
                signmodule = SignModule()
                signmodule.userchanged.connect(self.set_signuser)
                signmodule.exec()
                id_list = []
                it = QTreeWidgetItemIterator(self.treeWidget_midprodlist)
                while it.value():
                    qtreeitem = it.value()
                    if qtreeitem.text(6) not in ('', ' '):
                        id_list.append(int(qtreeitem.text(0)))
                    it += 1
                detail = {
                    'drawerid': self.sign_id,
                    'drawername': self.sign_name
                }
                if not len(id_list):
                    return
                if len(
                        id_list) < self.treeWidget_midprodlist.topLevelItemCount() \
                        or self.sign_id in ('', ' '):
                    status = 1
                else:
                    status = 2
                res = self.PC.update_midproddrawnotes(
                    autoid=id_list, pid=self.ppid, **detail, status=status
                )
                if res:
                    self.get_midprod()
                    self.get_prodstatusinmid()
        # except (AttributeError, UnboundLocalError):
        # pass

    def set_signuser(self, p_bool, p_str):
        if p_str in ('', ' '):
            self.sign_id = ''
            self.sign_name = ''
        else:
            try:
                self.sign_id, self.sign_name = p_str.split(' ')
            except ValueError:
                self.sign_id = ''
                self.sign_name = ''

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_midprodlist_itemDoubleClicked(self, qtreeitem, p_int):
        if not qtreeitem:
            return
        detail = Modifymiddetailmodule(
            autoid=int(qtreeitem.text(0)), parent=self
        )
        detail.accepted.connect(self.get_midprod)
        detail.show()
Esempio n. 13
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)
Esempio n. 14
0
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()
Esempio n. 15
0
class ProducingModule(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, autoid, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.product = ProductController()
        self.autoid = autoid
        # 当前的文档内容
        self.current_docid = 0
        self.current_content = object
        self.wsmodels = WorkshopModels()
        self.detail = self.product.get_producingplan(autoid=autoid)
        if len(self.detail) != 1:
            raise ValueError
        self.linepost = self.wsmodels.get_linepost(autoid)
        linepost_list = []
        if len(self.linepost):
            for item in self.linepost:
                linepost_list.append(item.autoid)
        self.linepostdocuments = self.wsmodels.get_linepostdocuments(
            linepost_list)
        #if len(self.linepostdocuments):
        # 初始化标题和基本信息
        self.setup_title(self.detail[0])
        # 初始化文档目录
        self.setup_filetree(list(self.linepost), list(self.linepostdocuments))

    # 初始化标题和基本信息
    def setup_title(self, detail_list):
        self.label_prodname.setText(detail_list.prodid + ' ' +
                                    detail_list.prodname)
        self.label_batchno.setText(detail_list.batchno)
        self.label_package.setText(detail_list.package)
        self.label_medkind.setText(detail_list.medkind)
        self.label_spec.setText(detail_list.spec)
        self.label_planamount.setText(
            str(detail_list.planamount) + detail_list.spunit)
        self.label_basicamount.setText(
            str(detail_list.planamount * detail_list.basicamount) +
            detail_list.basicunit)

    # 初始化文档目录
    # post_list:岗位列表
    # document_list:文档列表
    # 数节点分3行,第一行为岗位/文档的id,第2行为岗位:0,
    # 文档:负数->内建文档,整数->自定义文档
    def setup_filetree(self, post_list, document_list):
        # 把岗位列表和文档列表合并为一个新的字典
        post_to_doucument = dict()
        for item in post_list:
            post_to_doucument[item] = []
            for it in document_list[:]:
                if item.autoid == it.lpid:
                    post_to_doucument[item].append(it)
                    document_list.remove(it)

        treeitem_root = QtWidgets.QTreeWidgetItem(self.treewidget_filetree)
        treeitem_root.setText(0, "批生产记录封面")
        treeitem_root.setText(1, '0')

        for item in post_to_doucument:
            qtreeitem = QtWidgets.QTreeWidgetItem(treeitem_root)

            qtreeitem.setText(0, item.postname)
            qtreeitem.setText(1, '1')
            qtreeitem.setText(2, str(item.autoid))
            qtreeitem.setText(3, str(item.seqid))
            qtreeitem.setText(4, str(item.expireddays))
            for it in post_to_doucument[item]:
                qtreechilditem = QtWidgets.QTreeWidgetItem(qtreeitem)
                #0:文档名称,1: 类型, 2:autoid, 3: docid, 4: aid
                if it.docid < 0:
                    # 内建文档
                    qtreechilditem.setText(0, GENERAL_DOC[it.docid])
                    qtreechilditem.setText(1, '2')
                    qtreechilditem.setText(2, str(it.autoid))
                    qtreechilditem.setText(3, str(it.docid))
                    qtreechilditem.setText(4, str(it.aid))
                    if it.docid in (-15, -16, -17, -18):
                        qtreechilditem_lr = QtWidgets.QTreeWidgetItem(
                            qtreeitem)
                        qtreechilditem_lr.setText(1, '2')
                        qtreechilditem_lr.setText(2, "-1")
                        qtreechilditem_lr.setText(3, str(it.docid))
                        qtreechilditem_lr.setText(4, str(it.aid))
                        if it.docid == -15:
                            # 半成品请验单
                            qtreechilditem_lr.setText(0, "半成品检验报告")
                        elif it.docid == -16:
                            # 成品请验单
                            qtreechilditem_lr.setText(0, "成品检验报告")
                        elif it.docid == -17:
                            # 中间产品请验单
                            qtreechilditem_lr.setText(0, "中间产品检验报告")
                        elif it.docid == -18:
                            # 验证请验单
                            qtreechilditem_lr.setText(0, "验证检验报告")
                else:
                    qtreechilditem.setText(0, it.formatname)
                    qtreechilditem.setText(1, '3')
                    qtreechilditem.setText(2, str(it.autoid))
                    qtreechilditem.setText(3, str(it.docid))
                    qtreechilditem.setText(4, '0')
        # self.treewidget_filetree.hideColumn(1)
        # self.treewidget_filetree.hideColumn(2)
        # self.treewidget_filetree.hideColumn(3)
        # self.treewidget_filetree.hideColumn(4)
        self.treewidget_filetree.expandAll()

    # 打开一个新文档
    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
    def on_treewidget_filetree_itemClicked(self, qitem, p_int):
        try:
            # 判断之前是否有打开过文档且没有保存
            if self.current_content.flat:
                dialog = MessageBox(self,
                                    title="提醒",
                                    text="文档尚未保存",
                                    informative="是否要保存文档",
                                    yes_text="保存",
                                    no_text="放弃保存")
                result = dialog.exec()
                if result == QtWidgets.QMessageBox.Yes:
                    # 调用保存的槽函数
                    self.on_pushButton_accept_clicked()

        except (AttributeError, TypeError):
            pass
        finally:
            if not self.gridLayout_4.isEmpty():
                self.gridLayout_4.removeWidget(self.current_content)
                self.current_content.close()

        self.label_filename.setText(qitem.text(0))
        self.current_docid = qitem.text(3)

        # 点击的是内建文档
        if qitem.text(1) == '2':
            doctype = int(qitem.text(3))
            # 生产指令
            if doctype == -1:
                self.current_content = PorductionInstructionModule(
                    self.autoid, self)
            # 领料单
            if doctype in (-2, -3, -4):
                self.current_content = StuffdrawpaperModule(
                    qitem.text(4), self)
            # 退料单
            elif doctype in (-5, -6, -7):
                self.current_content = StuffReturnPaperModule(
                    qitem.text(4), self)
            # 批包装指令
            elif doctype == -8:
                self.current_content = PackageInstructionModule(
                    self.autoid, self)
            # 批剩余(残次)标签、包装材料销毁记录
            elif doctype == -9:
                pass
            # 称量配料记录
            elif doctype == -10:
                pass
            # 半成品登记/发放记录
            elif doctype in (-11, -12):
                self.current_content = MidproddrawnoteModule(
                    self.autoid,
                    abs(doctype) - 11)
            # 前处理入库单
            elif doctype == -14:
                self.current_content = PreProdPutInModule(autoid=self.autoid,
                                                          parent=self)
            # 成品寄库单
            elif doctype == -13:
                self.current_content = ProductputinModule(
                    int(qitem.text(4)), self)
            # 请验单
            if doctype in (-15, -16, -17, -18):
                docid = qitem.text(2)
                if docid == "-1":
                    self.current_content = CheckreportModule(autoid=int(
                        qitem.text(4)),
                                                             is_view=True,
                                                             parent=self)
                else:
                    self.current_content = ApplycheckModule(autoid=int(
                        qitem.text(4)),
                                                            parent=self)

            # 清场合格证(副本)
            elif doctype == -19:
                self.current_content = CleanconfirmityCopyModule(
                    int(qitem.text(4)), self)
            # 清场合格证(正本)
            elif doctype == -20:
                self.current_content = CleanconfirmityOriginalModule(
                    qitem.text(4), int(qitem.parent().text(3)), self)
            # 库存零头领取单
            elif doctype == -21:
                pass
            # 尾料销毁记录
            elif doctype == -22:
                pass
            # 产品二维码
            elif doctype == -23:
                self.current_content = QrcodelistModule(self.autoid, self)
            # 小、中包装二维码关联
            elif doctype == -24:
                pass
            # 大、中包装二维码关联
            elif doctype == -25:
                pass
            # 巨、大包装二维码关联
            elif doctype == -26:
                pass
            # 零头登记记录
            elif doctype == -27:
                self.current_content = OddmentregisternoteModule(
                    self.autoid, self)
            # 零头发放记录
            elif doctype == -28:
                self.current_content = OddmentdrawnoteModule(self.autoid, self)
            # 退货产品领料单
            elif doctype == -29:
                pass
            self.gridLayout_4.addWidget(self.current_content)
        # 点击的是自定义文档
        elif qitem.text(1) == '3':
            # 自定义文档在Forms表里的id
            formatid = qitem.text(3)
            document = self.wsmodels.get_form(formatid)
            if document is not None:
                content = document.format
                self.current_content = XMLReadWrite(self)
                self.current_content.openxml(content)
                self.gridLayout_4.addWidget(self.current_content)
                self.current_content.__setattr__('autoid', self.autoid)
        # 点击的是岗位名
        elif qitem.text(1) == '1':
            self.current_content = PostdetailModule(qitem.text(2),
                                                    self.detail[0].lineid,
                                                    qitem.text(3),
                                                    qitem.text(0), self)
            self.gridLayout_4.addWidget(self.current_content)
        # 点击的是封面
        elif qitem.text(1) == '0':
            self.current_content = HomePageModule(self.autoid, self)
            self.gridLayout_4.addWidget(self.current_content)

    @QtCore.pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if int(self.current_docid) > 0:
            res = self.wsmodels.update_form(self.current_docid,
                                            self.current_content.get_content())
            if res:
                self.current_content.flat = 0
        else:
            res = self.current_content.save()

    @QtCore.pyqtSlot()
    def on_pushButton_flush_clicked(self):
        pass

    @QtCore.pyqtSlot()
    def on_pushButton_reset_clicked(self):
        pass
Esempio n. 16
0
class ProducingplanModule(QtWidgets.QDialog, Ui_Form):
    current_kind = 'editButton'

    # flag: 区分是在生产指令还是在生产车间点开
    def __init__(self, flag=0, parent=None):
        super().__init__(parent)
        self.setupUi(self)

        if '21' not in user.powers:
            self.close()
        if user.powers['21'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['21'])

        self.flag = flag
        if self.flag:
            self.addButton.setVisible(False)
            self.deleteButton.setVisible(False)
            self.editButton.setVisible(False)
            self.current_kind = 'produceButton'
            self.produceButton.setEnabled(False)
        # 数据库操作类
        self.sd = ProductModel()
        self.product = ProductController()
        self.detail = ''
        # 未下达/已下达/正在生产/审核/生产结束 五个状态按键的功能
        self.editButton.clicked.connect(self.on_statusButton_clikcked)
        self.releaseButton.clicked.connect(self.on_statusButton_clikcked)
        self.produceButton.clicked.connect(self.on_statusButton_clikcked)
        self.examineButton.clicked.connect(self.on_statusButton_clikcked)
        self.finishedpushButton.clicked.connect(self.on_statusButton_clikcked)
        # 显示产品列表
        self.show_production_list()
        # 添加右键菜单功能
        self.__add_menu()

    # 显示生产记录列表
    def show_production_list(self):
        status = BUTTON_KIND.index(self.current_kind)
        vlst = ('autoid', 'prodid', 'prodname', 'commonname', 'batchno',
                'spec', 'package', 'medkind', 'planamount', 'mpunit',
                'instructorid', 'instructorname', 'plandate', 'realamount',
                'makedate', 'qaauditorid', 'qaauditorname', 'qadate',
                'executorid', 'executorname', 'executedate', 'linename',
                'workshopid', 'workshopname')
        production_records = self.product.get_producingplan(False,
                                                            status=status,
                                                            *vlst)
        production_records.reverse()
        if production_records:
            count = len(production_records)
            self.countlabel.setText("共%s条记录" % count)
            self.productionrecords.clear()
            for item in production_records.order_by('-autoid'):
                tree_item = QtWidgets.QTreeWidgetItem(self.productionrecords)
                tree_item.setText(0, str(item['autoid']))
                tree_item.setText(1, item['prodid'])
                tree_item.setText(2, item['prodname'])
                tree_item.setText(3, item['commonname'])
                tree_item.setText(4, item['batchno'])
                tree_item.setText(5, item['spec'])
                tree_item.setText(6, item['package'])
                tree_item.setText(7, item['medkind'])
                tree_item.setText(8, str(item['planamount']) + item['mpunit'])
                tree_item.setText(
                    9, item['instructorid'] + " " + item['instructorname'])
                tree_item.setText(
                    10,
                    str(item['plandate'])
                    if type(item['plandate']) is datetime.date else '')
                tree_item.setText(
                    11,
                    str(item['makedate'])
                    if type(item['makedate']) is datetime.date else '')
                tree_item.setText(
                    12, item['qaauditorid'] + " " + item['qaauditorname'])
                tree_item.setText(13, str(item['qadate']))
                tree_item.setText(
                    14, item['executorid'] + " " + item['executorname'])
                tree_item.setText(
                    15,
                    str(item['executedate'])
                    if type(item['executedate']) is datetime.date else '')
                tree_item.setText(16, item['linename'])
                tree_item.setText(
                    17, item['workshopid'] + " " + item['workshopname'])
            # 隐藏第一列的id
            self.productionrecords.hideColumn(0)
            for i in range(1, 18):
                self.productionrecords.resizeColumnToContents(i)
                if self.productionrecords.columnWidth(i) > 200:
                    self.productionrecords.setColumnWidth(i, 180)
                elif self.productionrecords.columnWidth(i) < 80:
                    self.productionrecords.setColumnWidth(i, 100)
        else:
            self.productionrecords.clear()
            self.productionrecords.hideColumn(0)
            self.countlabel.setText("共0条记录")

    def __add_menu(self):
        if self.flag == 0:
            self.productionrecords.setContextMenuPolicy(
                QtCore.Qt.CustomContextMenu)
            self.productionrecords.customContextMenuRequested.connect(
                self.generate_menu)
        else:
            pass

    def generate_menu(self, pos):
        if self.power[1] == '0':
            return
        sender_widget = self.sender()
        menu = QtWidgets.QMenu()
        if BUTTON_KIND.index(self.current_kind) == 0:
            button1 = menu.addAction("增加")
            button2 = menu.addAction("修改")
            button3 = menu.addAction("删除")
            # button5 = menu.addAction("审核下达")
        elif BUTTON_KIND.index(self.current_kind) == 1:
            button6 = menu.addAction("取消下达")
            button7 = menu.addAction("开始生产")
        elif BUTTON_KIND.index(self.current_kind) == 2:
            button4 = menu.addAction("显示批生产记录")
            button8 = menu.addAction("删除生产记录")
        else:
            button4 = menu.addAction("显示批生产记录")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        try:
            if BUTTON_KIND.index(self.current_kind) == 0:
                # 增加
                if action == button1:
                    self.on_addButton_clicked()
                # 修改
                elif action == button2:
                    self.on_recordButton_clicked()
                # 删除
                elif action == button3:
                    self.on_deleteButton_clicked()
                # 审核下达
                # elif action == button5:
                #     self.on_status_changed(1)
            elif BUTTON_KIND.index(self.current_kind) == 1:
                # 取消下达
                if action == button6:
                    self.on_status_changed(0)
                # 开始生产生产记录
                elif action == button7:
                    self.on_status_changed(1)
            elif BUTTON_KIND.index(self.current_kind) == 2:
                # 显示批生产记录
                if action == button4:
                    pass
                # 删除生产记录
                elif action == button8:
                    self.on_deleteButton_clicked()
            else:
                # 显示批生产记录
                if action == button4:
                    pass
        # 按键没有定义
        except UnboundLocalError:
            pass

    # 批生产状态更新
    # current_status:int    当前的状态
    # flat:bool 更新的状态方向,0为减少1,1为加1
    def on_status_changed(self, flat: bool):
        current_status = BUTTON_KIND.index(self.current_kind)
        items = self.productionrecords.selectedItems()
        autoid_list = []
        if items is not None:
            for item in items:
                autoid_list.append(item.text(0))
        data = dict()
        data['status'] = current_status + 1 if flat else current_status - 1
        data['statustime'] = user.time if flat else datetime.datetime(
            1000, 1, 1, 0, 0, 0)
        # 未下达
        if current_status == 0:
            data['warrantorid'] = user.user_id if flat else ''
            data['warrantorname'] = user.user_name if flat else ''
            data['warrantdate'] = user.now_date if flat else datetime.date(
                1000, 1, 1)
            data['qadate'] = user.now_date if flat else datetime.date
            data['bpwarrantorid'] = user.user_id if flat else ''
            data['bpwarrantorname'] = user.user_name if flat else ''
            data['bpwarrantdate'] = user.now_date if flat else datetime.date(
                1000, 1, 1)
            res = self.product.update_producingplan_status(autoid_list, **data)
            self.show_production_list()
        # 已下达
        elif current_status == 1:
            data['executorid'] = user.user_id if flat else ''
            data['executorname'] = user.user_name if flat else ''
            data['executedate'] = user.now_date if flat else ''
            data['qadate'] = user.now_date if flat else ''
            data['bpwarrantorid'] = user.user_id if flat else ''
            data['bpwarrantorname'] = user.user_name if flat else ''
            data['bpwarrantdate'] = user.now_date if flat else ''
            res = self.product.update_producingplan_status(autoid_list, **data)
            if res:
                self.show_production_list()

    # 增加按键功能
    @QtCore.pyqtSlot()
    def on_addButton_clicked(self):
        detail = EditProducingplan(parent=self)
        detail.accepted.connect(self.show_production_list)
        detail.show()

    # 打开记录详情
    @QtCore.pyqtSlot()
    def on_recordButton_clicked(self):
        if self.productionrecords.currentItem():
            self.on_productionrecords_itemDoubleClicked(
                self.productionrecords.currentItem(), 0)

    # 刷新生产指令列表
    @QtCore.pyqtSlot()
    def on_refreshButton_clicked(self):
        self.show_production_list()

    # 删除按键功能
    @QtCore.pyqtSlot()
    def on_deleteButton_clicked(self):
        items = self.productionrecords.selectedItems()
        autoid_list = []
        if items is not None:
            current_status = BUTTON_KIND.index(self.current_kind)
            if current_status < 2:
                # 还没有开始生产,只需要删除producingplan里的记录
                flat = 0
            else:
                # 已经生产了,需要删除全部记录
                flat = 1
            for item in items:
                autoid_list.append(item.text(0))

            self.product.delete_producingplan(None, flat, *autoid_list)
            self.show_production_list()

    # 生产指令列表双击功能
    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
    def on_productionrecords_itemDoubleClicked(self, QTreeWidgetItem, p_int):
        autoid = QTreeWidgetItem.text(0)
        if BUTTON_KIND.index(self.current_kind) < 2:
            # 生产指令详细列表
            detail = EditProducingplan(parent=self)
            detail.set_autoid(autoid)
            detail.accepted.connect(self.show_production_list)
            # 修改了物料记录,刷新列表
            detail.show()
        else:
            detail = ProducingModule(autoid, self)
            detail.showMaximized()

    # 状态按键功能,5个按键共用一个方法
    @QtCore.pyqtSlot()
    def on_statusButton_clikcked(self):
        clicked_button = self.sender()
        current_button = getattr(self, self.current_kind)
        clicked_button.setEnabled(False)
        current_button.setEnabled(True)
        self.current_kind = clicked_button.objectName()
        self.show_production_list()
Esempio n. 17
0
class OddmentputinnoteModule(QWidget, Ui_Form):
    """ 零头登记/发放列表记录记录
    分6个标签,0:全部批记录,包括没有零头记录的批次;
            1:登记中;
            2:已发放;
            3:已寄库
            4:已入库
            5:已过期
    点击其中一条生产记录时下方显示对应的记录内容
    除了已过期标签下的零头记录外,其他的都没有功能,只允许查看
    """
    def __init__(self, parent=None):
        super(OddmentputinnoteModule, self).__init__(parent)
        self.setupUi(self)
        if '34' not in user.powers:
            self.close()
        if user.powers['34'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['34'])

        self.ppid = 0
        self.PC = ProductController()
        self.ori_detail = dict()
        self.new_detail = dict()
        self.groupBox.setVisible(False)
        # 获取当前状态的批生产记录
        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", "planamount", "basicunit")
        index = self.tabWidget.currentIndex()
        key_dict_prod = dict()
        key_dict_oddment = {'flag': index + 2}
        values_list_oddment = ['ppid']

        id_list = self.PC.get_oddmentdrawnotes(True, *values_list_oddment,
                                               **key_dict_oddment)
        if not len(id_list):
            return
        key_dict_prod['autoid__in'] = id_list.distinct()

        res = self.PC.get_producingplan(False, *values_tuple_prod,
                                        **key_dict_prod)
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_prodlist)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, item['prodid'] + ' ' + item['prodname'])
            qtreeitem.setText(2, item['commonname'])
            qtreeitem.setText(3, item['spec'])
            qtreeitem.setText(4, item['package'])
            qtreeitem.setText(5, str(item['planamount']) + item['basicunit'])

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

    # 获取零头信息
    def get_oddmentdetail(self):
        self.treeWidget_oddmentlist.clear()
        self.treeWidget_oddmentlist.hideColumn(0)
        values_list = ("autoid", "amount", "unit", "registerid",
                       "registername", "regdate", "invaliddate", "qaid",
                       "qaname", "qadate", "warehousemanid",
                       "warehousemanname", "warehousedate")

        key_dict = {'ppid': self.ppid}
        index = self.tabWidget.currentIndex()
        key_dict['flag'] = index + 2
        res = self.PC.get_oddmentdrawnotes(False, *values_list, **key_dict)
        if len(res):
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_oddmentlist)
                qtreeitem.setText(0, str(item['autoid']))  # autoid
                qtreeitem.setText(1, str(item['amount']))  # 数量
                qtreeitem.setText(2, item['unit'])  # 单位
                qtreeitem.setText(3, item['registerid'] + ' ' +
                                  item['registername'])  # 登记人
                qtreeitem.setText(4, str(item['regdate']))  # 登记日期
                qtreeitem.setText(5, str(item['invaliddate']))  # 过期日期

                qtreeitem.setText(6,
                                  item['qaid'] + ' ' + item['qaname'])  # 寄库人
                qtreeitem.setText(
                    7,
                    str(item['qadate'])
                    if type(item['qadate']) is datetime.date else '')  # 寄库日期
                qtreeitem.setText(8, item['warehousemanid'] + ' ' +
                                  item['warehousemanname'])  # 入库人
                qtreeitem.setText(9,
                                  str(item['warehousedate']) if
                                  type(item['warehousedate']) is datetime.date
                                  else '')  # 入库日期

            for i in range(1, 10):
                self.treeWidget_oddmentlist.resizeColumnToContents(i)

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

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_prodlist_itemClicked(self, qtreeitem, p_int):
        if not self.groupBox.isVisible():
            self.groupBox.setVisible(True)
        self.ppid = int(qtreeitem.text(0))
        self.get_oddmentdetail()

    @pyqtSlot(QPoint)
    def on_treeWidget_oddmentlist_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        index = self.tabWidget.currentIndex()
        if index != 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()
        button1 = menu.addAction("确认寄库")
        button2 = menu.addAction("取消寄库")

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

        if action == button1:
            detail = {
                'flag': 3,
                'warehousemanid': user.user_id,
                'warehousemanname': user.user_name,
                'warehousedate': user.now_date
            }
            self.PC.update_oddmentdrawnotes(id_list, **detail)

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

            self.get_proddetail()
            self.get_oddmentdetail()
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
Esempio n. 19
0
class SelectoddmentdrawModule(QDialog, Ui_Dialog):
    def __init__(self, ppid, parent=None):
        super(SelectoddmentdrawModule, self).__init__(parent)
        self.setupUi(self)
        self.ppid = ppid
        self.prodid = ''
        self.id_list = tuple()
        self.PC = ProductController()
        # 获取ppid对应的prodid
        self.get_prodid()
        # 查找prodid相同的记录,并保存这些记录的id_list
        self.get_id_list()
        # 零头记录中找到没有过有效期且没有被领取(dppid=0)
        self.get_oddments_list()

    def get_prodid(self):
        values_list = ('prodid', )
        key_dict = {'autoid': self.ppid}
        res = self.PC.get_producingplan(True, *values_list, **key_dict)
        if len(res) == 1:
            self.prodid = res[0]

    def get_id_list(self):
        if not self.prodid:
            return
        values_list = ('autoid', )
        key_dict = {'prodid': self.prodid}
        res = self.PC.get_producingplan(True, *values_list, **key_dict)
        # 去除本批ppid
        self.id_list = list(res)
        if self.ppid in self.id_list:
            self.id_list.remove(self.ppid)

    def get_oddments_list(self):
        self.treeWidget_oddmentdrawlist.clear()
        self.treeWidget_oddmentdrawlist.hideColumn(0)

        values_list = ('autoid', 'batchno', 'amount', 'unit', 'registerid',
                       'registername', 'regdate', 'invaliddate')
        # 没有发放,没有寄库,没有过期
        key_dict = {
            'ppid__in': self.id_list,
            'dppid': 0,
            'status': 0,
            'invaliddate__gte': user.now_date,
        }
        res = self.PC.get_oddmentdrawnotes(False, *values_list, **key_dict)
        if not len(res):
            return
        for item in res:
            qtreeitem = QTreeWidgetItem(self.treeWidget_oddmentdrawlist)
            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,
                              item['registerid'] + ' ' + item['registername'])
            qtreeitem.setText(5, str(item['regdate']))
            qtreeitem.setText(6, str(item['invaliddate']))
            qtreeitem.setCheckState(1, 0)
        for i in range(1, 7):
            self.treeWidget_oddmentdrawlist.resizeColumnToContents(i)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_oddmentdrawlist_itemDoubleClicked(
            self, qtreeitem, p_int):
        state = qtreeitem.checkState(1)
        if state == 0:
            qtreeitem.setCheckState(1, 2)
        else:
            qtreeitem.setCheckState(1, 0)

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        it = QTreeWidgetItemIterator(self.treeWidget_oddmentdrawlist)
        select_id_list = []
        while it.value():
            qtreeitem = it.value()
            if qtreeitem.checkState(1) == 2:
                select_id_list.append(int(qtreeitem.text(0)))
            it += 1
        if not len(select_id_list):
            return
        detail = {
            'dppid': self.ppid,
            'drawerid': user.user_id,
            'drawername': user.user_name,
            'drawdate': user.now_date
        }
        res = self.PC.update_oddmentdrawnotes(select_id_list, **detail)
        if res:
            self.accept()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.close()
Esempio n. 20
0
class Modifyoddmentmodule(QDialog, Ui_Dialog):
    """ 修改/增加新的零头登记记录

    """
    def __init__(self, autoid: int = 0, ppid: int = 0, parent=None):
        super(Modifyoddmentmodule, self).__init__(parent)
        self.autoid = autoid
        self.ppid = ppid
        self.batchno = '0'
        self.setupUi(self)
        self.PC = ProductController()
        self.SC = SystemController()
        self.ori_detail = dict()
        self.new_detail = dict()
        self.proddetail = {'spunit': '', 'basicunit': ''}
        self.validdate = 90
        # 获取生产记录里小包装单位和基本单位
        self.get_producingplan_detail()
        # 获取当前零头登记的详情
        self.get_detail()
        # 设置数量的校验器
        self.set_amount_validator()
        # 获取零头有效期天数
        self.get_oddmentvaliddate()

    def get_producingplan_detail(self):
        values_list = ('spunit', 'basicunit', 'makedate')
        key_dict = {'autoid': self.ppid}
        res = self.PC.get_producingplan(True, *values_list, **key_dict)
        if len(res) != 1:
            return

        self.proddetail = res[0]
        self.comboBox_unit.addItems(self.proddetail[0:2])

    def get_detail(self):
        if not self.autoid:
            self.dateEdit_regdate.setDate(user.now_date)
            values_list = ("batchno", )

            key_dict = {'autoid': self.ppid}
            res = self.PC.get_producingplan(False, *values_list, **key_dict)
            if len(res) == 1:
                self.batchno = res[0]['batchno']
            return
        values_list = ("amount", "unit", "regdate")

        key_dict = {'autoid': self.autoid}
        res = self.PC.get_oddmentdrawnotes(False, *values_list, **key_dict)
        if len(res) == 1:
            self.ori_detail = res[0]
            self.lineEdit_amount.setText(str(self.ori_detail['amount']))
            self.comboBox_unit.setCurrentText(self.ori_detail['unit'])
            self.dateEdit_regdate.setDate(
                self.ori_detail['regdate'] if type(self.ori_detail['regdate']) \
                is datetime.datetime else user.now_date
            )

    def set_amount_validator(self):
        doublevalidator = QDoubleValidator()
        doublevalidator.setBottom(0)
        self.lineEdit_amount.setValidator(doublevalidator)

    def get_oddmentvaliddate(self):
        values_list = ('otvalue', )
        key_dict = {'otid': 11}
        res = self.SC.get_systemoption(True, *values_list, **key_dict)
        if len(res):
            self.validdate = res[0]

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

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

    @pyqtSlot(QDate)
    def on_dateEdit_regdate_dateChanged(self, q_date):
        res = self.PC.get_oddment_invaliddate(q_date.toPyDate(),
                                              self.validdate)
        invaliddate = res[0]
        try:
            if type(self.ori_detail['regdate']) is str:
                self.new_detail['regdate'] = q_date.toPyDate()
                self.new_detail['invaliddate'] = invaliddate
                return
            if q_date != QDate(self.ori_detail['regdate']):
                self.new_detail['regdate'] = q_date.toPyDate()
                self.new_detail['invaliddate'] = invaliddate
            else:
                try:
                    del self.new_detail['regdate']
                    del self.new_detail['invaliddate']
                except KeyError:
                    pass
        except KeyError:
            self.new_detail['regdate'] = q_date.toPyDate()
            self.new_detail['invaliddate'] = invaliddate

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        if self.lineEdit_amount.text() == '':
            return
        if not len(self.new_detail):
            return
        self.new_detail['registerid'] = user.user_id
        self.new_detail['registername'] = user.user_name

        if self.autoid:
            res = self.PC.update_oddmentdrawnotes(autoid=self.autoid,
                                                  **self.new_detail)

        else:
            self.new_detail['ppid'] = self.ppid
            self.new_detail['batchno'] = self.batchno
            self.new_detail['makedate'] = self.proddetail[2]
            res = self.PC.update_oddmentdrawnotes(**self.new_detail)
        if res:
            self.accept()

    @pyqtSlot()
    def on_pushButton_cancel_clicked(self):
        self.close()
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
Esempio n. 22
0
class DrawstuffModule(QDialog, Ui_Dialog):
    def __init__(self, ppid, sdpid, kind, parent=None):
        super(DrawstuffModule, self).__init__(parent)
        self.ppid = ppid
        self.sdpid = sdpid
        self.kind = kind
        self.setupUi(self)
        if '37' not in user.powers:
            self.close()
        if user.powers['37'] == 0:
            self.close()
        self.power = '{:03b}'.format(user.powers['37'])
        if self.power[1] == '0':
            self.pushButton_accept.setVisible(False)
            self.pushButton_cancel.setVisible(False)
        self.WC = WarehouseController()
        self.SC = StuffController()
        self.PC = ProductController()
        self.PLC = ProductLineConroller()
        self.detail = dict()
        self.stuff_list = []
        # 当前正在修改的树节点
        self.edittreeitem = None
        self.stuff_repository = []
        # 公式错误信息
        self.errormsg = []
        self.treeWidget_stuffrepository.setDragDropMode(1)
        self.treeWidget_drawstuff.setDragDropMode(2)

    def showMaximized(self):
        try:
            #获取产品信息
            self.get_product_detail()
            self.get_formula()
            self.get_has_drawstuff(self.ppid)
            self.draw_stuff()
            # 配方有错误信息,提示错误内容
            if len(self.errormsg):
                self.pushButton_accept.setEnabled(False)
                self.show_errormsg(self.errormsg)
            super(DrawstuffModule, self).showMaximized()
        except Exception as e:
            self.done(6)

    # 显示错误信息
    def show_errormsg(self, msg):
        text = "以下物料配方设置出错,请检查配方后重新领料"
        informative = ""
        for i, item in enumerate(msg):
            informative += str(i + 1) + '、' + item + '设置出错\n'
        dialog = MessageBox(self, text=text, informative=informative)
        dialog.show()

    # 获取当前领料单的物料配方
    def get_formula(self):
        if self.detail['pltype'] == 0:
            table = ['Productdictionary']
            condition = [
                'Productdictionary.autoid=Productprescription.prodid',
                'Productdictionary.prodid=' + self.detail['prodid']
            ]
        else:
            table = ['Stuffdictionary']
            condition = [
                'Stuffdictionary.autoid=Productprescription.prodid',
                'Stuffdictionary.stuffid=' + self.detail['prodid']
            ]
        # 获得配方
        if self.kind == 0:
            res = self.PLC.get_formula(version=self.detail['version'],
                                       stufftype__in=(0, 1, 2),
                                       prodtype=self.detail['pltype']).extra(
                                           tables=table, where=condition)
        else:
            res = self.PLC.get_formula(version=self.detail['version'],
                                       stufftype=self.kind + 2,
                                       prodtype=self.detail['pltype']).extra(
                                           tables=table, where=condition)
        stuffkind_list = []
        if len(res):
            # 显示配方
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_formula)
                qtreeitem.setText(1, STUFFTYPE[item.stufftype])
                qtreeitem.setText(2, item.stuffkind)
                qtreeitem.setText(3, item.formula)
                qtreeitem.setText(4, item.presexpression)
                qtreeitem.setText(5, item.pracexpression)
                qtreeitem.setText(6, item.drawexpression)
                # 领料精度
                qtreeitem.setText(7, str(item.precision))
                # 损耗限度
                qtreeitem.setText(8, str(item.loss))
                # 标记该物料是否已经发够料
                qtreeitem.setText(9, '0')
                stuffkind_list.append(item.stuffkind)

            self.treeWidget_formula.hideColumns(0, 4, 5, 6, 7, 8, 9)
            self.treeWidget_formula.resizeColumns(300, 1, 2, 3)
        # 如果当前配方不为空,则获取对应的库存
        if len(stuffkind_list):
            self.get_stuffrep_gt_zero(stuffkind_list)

    # 获取本批产品其他领料单已经领取了的物料
    def get_has_drawstuff(self, ppid):
        values_tupe = ("autoid", "stuffid", "stuffname", "stuffkind", "spec",
                       "package", "presamount", "pracamount", "drawamount",
                       "content", "water", "impurity", "rdensity")
        stuffs = self.SC.get_prodstuff(0, ppid=ppid, *values_tupe)
        if len(stuffs):
            self.stuff_list_additem(stuffs)

    # 把领取的物料加到领料记录中,如果发现重复的情况则替换旧的记录
    def stuff_list_additem(self, newitems):
        for newitem in newitems:
            flat = 0
            for item in self.stuff_list:
                if newitem['autoid'] == item['autoid']:
                    item = newitem
                    flat = 1
            if flat == 0:
                self.stuff_list.append(newitem)

    # 获取配方对应的物料
    def get_stuffrep_gt_zero(self, stuffkind_list):
        self.treeWidget_stuffrepository.clear()
        row_tuple = ('autoid', 'stuffkind', 'stuffid', 'stuffname', 'spec',
                     'package', 'batchno', 'mbatchno', 'amount', 'producer',
                     'supid', 'supname', 'content', 'cunit', 'water',
                     'rdensity', 'impurity', 'basicunit', 'lrid', 'stufftype')
        res = self.WC.get_stuffrepository(False,
                                          *row_tuple,
                                          stuffkind__in=stuffkind_list,
                                          amount__gt=0)
        self.stuff_repository = res
        if len(res):
            for item in res:
                qtreeitem = QTreeWidgetItem(self.treeWidget_stuffrepository)
                qtreeitem.setText(0, str(item['autoid']))
                qtreeitem.setText(1, str(item['stuffkind']))
                qtreeitem.setText(2, item['stuffid'] + ' ' + item['stuffname'])
                qtreeitem.setText(3, item['spec'])
                qtreeitem.setText(4, item['package'])
                qtreeitem.setText(5, item['batchno'])
                qtreeitem.setText(6, item['mbatchno'])
                qtreeitem.setText(7, str(item['amount']) + item['basicunit'])
                qtreeitem.setText(9, item['supid'] + ' ' + item['supname'])
                qtreeitem.setText(10, item['producer'])
                qtreeitem.setText(11, str(item['content']) + item['cunit'])
                qtreeitem.setText(12, str(item['water']) + '%')
                qtreeitem.setText(13, str(item['rdensity']))
                qtreeitem.setText(14, str(item['impurity']))
            self.treeWidget_stuffrepository.hideColumns(0, 1, 15)
            column_list = [i for i in range(2, 15)]
            self.treeWidget_stuffrepository.resizeColumns(120, *column_list)

    # 获取产品信息
    def get_product_detail(self):
        vlist = ('prodid', 'version', 'planamount', 'realamount', 'spec',
                 'basicamount', 'spamount', 'bpamount', 'bpamount', 'pltype')
        res = self.PC.get_producingplan(False, *vlist, autoid=self.ppid)
        self.detail = res[0]

    # 系统根据配方自动领料
    def draw_stuff(self):
        it = QTreeWidgetItemIterator(self.treeWidget_formula)
        while it.value():
            item = it.value()
            # 标记为0的列即为未领够料的记录
            if item.text(9) == '0':
                stuffkind = item.text(2)
                precision = int(item.text(7))
                loss = item.text(8)
                # 处理产品信息的变量,去除系统变量
                item.setText(4, self.reckon_expression(item.text(4), 1))
                # 计划量
                try:
                    presamount = Decimal(
                        rnd(eval(item.text(4), evalenv(self)), precision))
                except SyntaxError:
                    if stuffkind + ' 计划量' not in self.errormsg:
                        self.errormsg.append(stuffkind + ' 计划量')
                    presamount = 0

                # 把计划量加到产品信息变量中
                # self.detail['presamount'] = presamount
                # 实际量公式,去除系统变量
                item.setText(5, self.reckon_expression(item.text(5), 1))
                # 领取量公式,去除系统变量
                item.setText(6, self.reckon_expression(item.text(6), 1))
                # 计算领料量,返回领料情况res, 和标记:是否已经领购料
                res = self.reckon_drawamount(stuffkind, presamount, precision,
                                             item.text(5), item.text(6), loss)
                if len(res):
                    self.treeWidget_drawstuff_add_item(res)
            it += 1
        self.is_drawamount_enough()

    # 把计算结果存到领料树中
    def treeWidget_drawstuff_add_item(self, items: dict):
        try:
            self.stuff_list_additem(items)
            for item in items:
                qtreeitem = QTreeWidgetItem(self.treeWidget_drawstuff)
                qtreeitem.setText(0, str(item['autoid']))
                qtreeitem.setText(1, str(item['stuffkind']))
                qtreeitem.setText(2, item['stuffid'] + ' ' + item['stuffname'])
                qtreeitem.setText(3, item['spec'])
                qtreeitem.setText(4, item['package'])

                qtreeitem.setText(5, str(item['oripresamount']))
                qtreeitem.setText(6, item['basicunit'])

                qtreeitem.setText(7, str(item['newpracamount']))
                qtreeitem.setText(8, item['basicunit'])

                qtreeitem.setText(9, str(item['drawamount']))
                qtreeitem.setText(10, item['basicunit'])

                qtreeitem.setText(11, item['batchno'])
                qtreeitem.setText(12, item['mbatchno'])

                qtreeitem.setText(13, str(item['content']) + item['cunit'])
                qtreeitem.setText(14, str(item['water']) + '%')
                qtreeitem.setText(15, str(item['rdensity']))
                qtreeitem.setText(16, str(item['impurity']))
                qtreeitem.setText(17, str(item['loss']))

                qtreeitem.setText(18, item['supid'] + ' ' + item['supname'])
                qtreeitem.setText(19, item['producer'])

                qtreeitem.setText(20, str(item['presamount']))
                qtreeitem.setText(21, str(item['pracamount']))
                qtreeitem.setText(22, str(item['precision']))

                self.treeWidget_drawstuff.hideColumns(0, 1, 20, 21, 22)
                columns_list = [i for i in range(2, 20)]
                self.treeWidget_drawstuff.resizeColumns(200, *columns_list)
        except KeyError:
            pass

    # 计算系统变量
    def reckon_expression(self, expression, iterdepth):
        # iterdepth:迭代深度,超过50则抛出RuntimeError
        # 产品信息变量,ex: @planamount@, @spec@, @package@
        if iterdepth > 50:
            raise RuntimeError
        pattern = re.findall(r'@[%?!()()::.#\w]*@', expression)
        for item in pattern:
            if len(item[1:-1].split('.')) == 2:
                var_name, var_item = item[1:-1].split('.')
                value = Decimal('0')
                # 标记是否找到了对应的物料
                find_stuff_flag = 0
                for stuff in self.stuff_list:
                    if stuff['stuffkind'] == var_name:
                        find_stuff_flag = 1
                        if var_item == '计划量':
                            value = stuff[VAR_ITEM[var_item]]
                            expression = expression.replace(item, str(value))
                            break
                        else:
                            value += stuff[VAR_ITEM[var_item]]
                        expression = expression.replace(item, str(value))
                # 没有找到对应的物料则再本领料单中继续寻找
                if find_stuff_flag == 0:
                    formula_item = self.get_treeitem(self.treeWidget_formula)
                    while 1:
                        try:
                            treeitem = next(formula_item)
                            if treeitem.text(2) == var_name:
                                if treeitem.text(9) == '0':
                                    # stuffkind = item.text(2)
                                    precision = int(treeitem.text(7))
                                    loss = treeitem.text(8)
                                    # 处理产品信息的变量,去除系统变量
                                    treeitem.setText(
                                        4,
                                        self.reckon_expression(
                                            treeitem.text(4), iterdepth + 1))
                                    # 计划量
                                    try:
                                        presamount = Decimal(
                                            rnd(
                                                eval(treeitem.text(4),
                                                     evalenv(self)),
                                                precision))
                                    except SyntaxError:
                                        if var_name + ' 计划量' not in self.errormsg:
                                            self.errormsg.append(var_name +
                                                                 ' 计划量')
                                        presamount = 0
                                    # 把计划量加到产品信息变量中
                                    # self.detail['presamount'] = presamount
                                    # 实际量公式,去除系统变量
                                    treeitem.setText(
                                        5,
                                        self.reckon_expression(
                                            treeitem.text(5), iterdepth + 1))
                                    # 领取量公式,去除系统变量
                                    treeitem.setText(
                                        6,
                                        self.reckon_expression(
                                            treeitem.text(6), iterdepth + 1))
                                    # 计算领料量,返回领料情况res, 和标记:是否已经领购料
                                    res = self.reckon_drawamount(
                                        var_name, presamount, precision,
                                        treeitem.text(5), treeitem.text(6),
                                        loss)
                                    if len(res):
                                        self.treeWidget_drawstuff_add_item(res)
                                        self.is_drawamount_enough()
                                        expression = self.reckon_expression(
                                            expression, iterdepth + 1)
                        except (StopIteration, RuntimeError) as e:
                            break
            else:
                key = item.replace('@', '')
                if key in self.detail:
                    expression = expression.replace(item,
                                                    str(self.detail[key]))
        #pattern_1 = re.findall(r'@[%?!()()::.#\w]*@', expression)
        return expression

    # 计算实际量
    def reckon_pracamount(self, autoid, presamount, precision, expression):
        # stuffkind: 物料种类
        # presamount: 计划量
        # expression: 实际量的公式
        stuff_detail = []
        # 最终要领取的批次和实际量
        # 分析公式,获取变量
        pattern = re.findall(r'@\w*@', expression)
        # 把变量设置为对应的值
        for item in self.stuff_repository:
            if autoid != item['autoid']:
                continue
            for key in pattern:
                k = key.replace('@', '')
                if k == 'presamount':
                    expression = expression.replace(key, str(presamount))
                elif k in item:
                    expression = expression.replace(key, str(item[k]))
                elif k in self.detail:
                    expression = expression.replace(key, str(self.detail[k]))
            try:
                pracamount = Decimal(
                    rnd(eval(expression, evalenv(self)), precision))
            except SyntaxError:
                if item['stuffkind'] + ' 实际量' not in self.errormsg:
                    self.errormsg.append(item['stuffkind'] + ' 实际量')
                pracamount = 0
            item['pracamount'] = pracamount

    # 计算领取量
    def reckon_drawamount(self,
                          stuffkindorsrid,
                          presamount,
                          precision,
                          prac_expression,
                          draw_expression,
                          loss=0,
                          flat=True):
        # stuffkindorsrid: 根据flat决定类型, True是物料种类,False是srid
        # presamount: 计划量
        # precision: 计算结果精度
        # prac_expression: 实际量公式
        # draw_expression: 领取公式
        # loss: 损耗限度
        # flat: 是否需要继续领下一批物料,默认为True即继续领下一批物料,
        #       False则不再领取下一批物料

        # 要领取的物料批次
        draw_list = []
        # 已经领取了的量
        has_drawamount = 0
        # 分析公式,获取变量
        pattern = re.findall(r'@\w*@', draw_expression)
        # 把变量设置为对应的值
        for item in self.stuff_repository:

            item['oripresamount'] = presamount
            new_expression = draw_expression
            if has_drawamount != 0:
                presamount -= has_drawamount
                has_drawamount = 0
            if stuffkindorsrid != (item['stuffkind']
                                   if flat else str(item['autoid'])):
                continue
            has_draw_stuff = self.get_treeitem(self.treeWidget_drawstuff)
            # 检查该批次是否已经选择过了
            draw_flag = 0
            while 1:
                try:
                    stuff = next(has_draw_stuff)
                    if int(stuff.text(0)) == item['autoid']:
                        draw_flag = 1
                        break
                except StopIteration:
                    break
            if draw_flag == 1:
                continue
            item['loss'] = loss
            item['presamount'] = presamount
            item['precision'] = precision
            # 算出该批次对应的实际量
            self.reckon_pracamount(item['autoid'], presamount, precision,
                                   prac_expression)
            for key in pattern:

                k = key.replace('@', '')
                if k in item:
                    new_expression = new_expression.replace(key, str(item[k]))
                elif k in self.detail:
                    new_expression = new_expression.replace(
                        key, str(self.detail[k]))
            try:
                drawamount = Decimal(
                    rnd(eval(new_expression, evalenv(self)), precision))
            except SyntaxError:
                if stuffkindorsrid + ' 领取量' not in self.errormsg:
                    self.errormsg.append(stuffkindorsrid + ' 领取量')
                drawamount = 0
            if drawamount == 0:
                continue
            elif item['amount'] >= drawamount:
                item['drawamount'] = drawamount
                item['newpracamount'] = item['pracamount']
                draw_list.append(item)
                break
            else:
                # 转化为计划量 = 领取量 * 计划量 / 实际量
                has_drawamount = Decimal(
                    rnd(item['amount'] * presamount / item['pracamount'],
                        precision))
                item['newpracamount'] = rnd(item['amount'], precision)
                item['drawamount'] = rnd(item['amount'], precision)
                draw_list.append(item)
                if not flat:
                    # 指定库存记录时,默认按领够料处理
                    break
        return draw_list

    # 配方点击功能,选择一个物料种类后库存列表中只显示该物料
    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_formula_itemClicked(self, qtreeitem, p_int):
        stuffkind_list = [qtreeitem.text(2)]
        self.get_stuffrep_gt_zero(stuffkind_list)

    # 拖动库存记录到领料表
    @pyqtSlot(QDropEvent, QPoint)
    def on_treeWidget_drawstuff_droped(self, event, pos):
        try:
            data = event.mimeData().data(
                'application/x-qabstractitemmodeldatalist')
            data_items = decode_data(data)
            p_str = data_items[0][0]
            srid = int(p_str)
            # 如果该批次物料已经有领料记录则不做任何操作
            if self.has_drawstuff(p_str):
                return
            stuff = dict()
            for item in self.stuff_repository:
                if srid == item['autoid']:
                    stuff = item
                    break
            if stuff is None:
                raise KeyError
            stuffkind = stuff['stuffkind']
            it_formula = self.get_treeitem(self.treeWidget_formula)

            while 1:
                try:
                    treeitem = next(it_formula)
                    if treeitem.text(2) == stuffkind:
                        planamount_expression = treeitem.text(4)
                        pracamount_expression = treeitem.text(5)
                        drawamount_expression = treeitem.text(6)
                        precision = int(treeitem.text(7))
                        loss = treeitem.text(8)
                        try:
                            presamount = Decimal(
                                rnd(eval(planamount_expression, evalenv(self)),
                                    precision))
                        except SyntaxError:
                            if stuffkind + ' 计划量' not in self.errormsg:
                                self.errormsg.append(stuffkind + ' 计划量')
                            presamount = 0
                        # 没有领够料,继续拖新的物料批次
                        if treeitem.text(9) == '0':
                            # 获取出该物料其他批次的实际领取量
                            it_drawstuff = self.get_treeitem(
                                self.treeWidget_drawstuff)
                            try:
                                new_presamount = presamount
                                while 1:
                                    drawitem = next(it_drawstuff)
                                    if drawitem.text(1) != stuffkind:
                                        continue
                                    # 转化为计划量 = 领取量 * 计划量 / 实际量
                                    has_drawamount = rnd(
                                        Decimal(drawitem.text(9)) *
                                        Decimal(drawitem.text(20)) /
                                        Decimal(drawitem.text(21)),
                                        int(drawitem.text(22)))
                                    new_presamount -= has_drawamount
                            except StopIteration:
                                pass
                            # 计算本批的领取量
                            res = self.reckon_drawamount(
                                p_str, new_presamount, precision,
                                pracamount_expression, drawamount_expression,
                                loss, False)
                        # 已经领够料,还继续拖新的物料批次
                        elif treeitem.text(9) == '1':
                            res = self.reckon_drawamount(
                                p_str, presamount, precision,
                                pracamount_expression, drawamount_expression,
                                loss, False)
                        if len(res):
                            res[0]['oripresamount'] = presamount
                            self.treeWidget_drawstuff_add_item(res)
                        self.is_drawamount_enough()
                        break
                except StopIteration:
                    break
        except ValueError:
            SaveExcept(ValueError, "拖动库存信息时出错,传入的不是srid", p_str,
                       self.stuff_repository)
        except KeyError:
            SaveExcept(ValueError, "拖动库存信息时出错,没有找到对应的库存记录,", p_str,
                       self.stuff_repository)

    # 领够料的物料自动设置成绿色,不够料的物料设置成黄色
    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_formula_itemChanged(self, qtreeitem, p_int):
        if p_int == 9:
            brush = QBrush(1)
            if qtreeitem.text(9) == '1':
                brush.setColor(QColor(85, 255, 127))
            else:
                brush.setColor(QColor(255, 255, 127))
            for i in range(1, 4):
                qtreeitem.setBackground(i, brush)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_drawstuff_itemDoubleClicked(self, qtreeitem, p_int):
        try:
            srid = int(qtreeitem.text(0))
            srdetail = dict()
            for item in self.stuff_repository:
                if item['autoid'] == srid:
                    srdetail = item
                    break
            dialog = ModifyDrawamountModule(srdetail, self)
            self.edittreeitem = qtreeitem
            dialog.modified.connect(self.setdrawamount)
            dialog.exec()
        except ValueError:
            pass

    # 把领料量设置为新的值
    def setdrawamount(self, q_decimal):
        stuffkind = ''
        self.edittreeitem.setText(9, str(q_decimal))
        self.edittreeitem.setText(7, str(q_decimal))
        srid = int(self.edittreeitem.text(0))
        for item in self.stuff_repository:
            if item['autoid'] == srid:
                item['pracamount'] = q_decimal
                item['drawamount'] = q_decimal
                stuffkind = item['stuffkind']
                break
        self.is_drawamount_enough()
        self.edittreeitem = None

    # 判断领取的物料是否足够
    def is_drawamount_enough(self):
        formula_treeitem = self.get_treeitem(self.treeWidget_formula)

        while 1:
            presamount = Decimal('0')
            try:
                fitem = next(formula_treeitem)
                precision = int(fitem.text(7))
                presamount = Decimal(
                    rnd(eval(fitem.text(4), evalenv(self)), precision))
                stuffkind = fitem.text(2)
                drawstuff_treeitem = self.get_treeitem(
                    self.treeWidget_drawstuff)
                while 1:
                    try:
                        ditem = next(drawstuff_treeitem)
                        if ditem.text(1) != stuffkind:
                            continue
                        this_presamount = rnd(
                            Decimal(ditem.text(7)) * Decimal(ditem.text(20)) /
                            Decimal(ditem.text(21)), precision)
                        presamount -= this_presamount
                    except StopIteration:
                        break
                if presamount > 0:
                    fitem.setText(9, '0')
                else:
                    fitem.setText(9, '1')

            except StopIteration:
                break
            except SyntaxError:
                continue

    # 删除已经选择好了的物料
    @pyqtSlot(QPoint)
    def on_treeWidget_drawstuff_customContextMenuRequested(self, pos):
        if self.power[1] == '0':
            return
        sender_widget = self.sender()
        menu = QMenu()
        button1 = menu.addAction("删除该批次物料")
        button2 = menu.addAction("修改领取量")
        global_pos = sender_widget.mapToGlobal(pos)
        action = menu.exec(global_pos)
        # 删除该批次物料
        if action == button1:
            try:
                self.delete_drawstuff(sender_widget.selectedItems())
            except AttributeError:
                pass
        # 修改领取量
        elif action == button2:
            try:
                self.modify_drawstuff(sender_widget.currentItem())
            except AttributeError:
                pass

    # 判断物料是否已经有领取记录
    def has_drawstuff(self, p_str):
        itemiter = self.get_treeitem(self.treeWidget_drawstuff)
        flag = False
        while 1:
            try:
                treeitem = next(itemiter)
                if p_str == treeitem.text(0):
                    flag = True
                    break
            except StopIteration:
                break
        return flag

    # 删除待领取的物料
    def delete_drawstuff(self, qtreeitems):
        # qtreeitems: 选中的项目
        if len(qtreeitems):
            it = QTreeWidgetItemIterator(self.treeWidget_formula)
            root = self.treeWidget_drawstuff.invisibleRootItem()
            for item in qtreeitems:
                root.removeChild(item)
            self.is_drawamount_enough()

    def get_treeitem(self, qtreewidget):
        it = QTreeWidgetItemIterator(qtreewidget)
        while it.value():
            yield it.value()
            it += 1

    @pyqtSlot()
    def on_pushButton_accept_clicked(self):
        it = QTreeWidgetItemIterator(self.treeWidget_drawstuff)
        draw_list = []
        key_list = ['srid', 'stuffkind']
        while it.value():
            treeitem = it.value()
            item = self.qtreeitem2dict(key_list, treeitem)
            for stuff in self.stuff_repository:
                if stuff['autoid'] == int(item['srid']):
                    item['stuffid'] = stuff['stuffid']
                    item['stuffname'] = stuff['stuffname']
                    item['stufftype'] = stuff['stufftype']
                    item['stuffkind'] = stuff['stuffkind']
                    item['spec'] = stuff['spec']
                    item['package'] = stuff['package']
                    item['producer'] = stuff['producer']
                    item['batchno'] = stuff['batchno']
                    item['lrid'] = stuff['lrid']
                    item['content'] = stuff['content']
                    item['cunit'] = stuff['cunit']
                    item['water'] = stuff['water']

                    item['impurity'] = stuff['impurity']
                    item['rdensity'] = stuff['rdensity']
                    item['mbatchno'] = stuff['mbatchno']
                    break
            item['sdpid'] = self.sdpid
            item['ppid'] = self.ppid
            draw_list.append(item)
            it += 1
        sdpid_list = {
            'autoid': self.sdpid,
            'status': 2,
            'providerid': user.user_id,
            'providername': user.user_name,
            'drawdate': user.now_date
        }
        res = self.WC.update_stuffrepository_amount(self.ppid, *draw_list,
                                                    **sdpid_list)
        if res == 'accept':
            self.accept()
        elif res == 'rollback':
            msg = MessageBox(parent=self,
                             text="领料信息异常!",
                             informative="请刷新后重试!")
            msg.exec()
            timer = QTimer(self)
            timer.start(1000)
            timer.timeout.connect(msg.close)

    def qtreeitem2dict(self, key_list: list, q_treeitem: QTreeWidgetItem):
        q_dict = dict()
        q_dict['srid'] = q_treeitem.text(0)
        q_dict['presamount'] = Decimal(q_treeitem.text(5))
        q_dict['checkamount'] = Decimal(q_treeitem.text(5))
        q_dict['presunit'] = q_treeitem.text(6)
        q_dict['pracamount'] = Decimal(q_treeitem.text(7))
        q_dict['pracunit'] = q_treeitem.text(8)
        q_dict['drawamount'] = Decimal(q_treeitem.text(9))
        q_dict['drawunit'] = q_treeitem.text(10)
        q_dict['loss'] = q_treeitem.text(17)
        q_dict['precision'] = int(q_treeitem.text(22))
        return q_dict

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