Beispiel #1
0
class _StorageView(InlineTable, CustomView):

    list_template = 'storage/list.html'
    pdf_template = 'storage/pdf.html'

    # 入库首页列表视图应显示的内容
    column_list = ['number', 'date', 'instoreCategory', 'statusName']
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '日期',
        'instoreCategory': '入库类别',
        'instorageDate': '入库日期',
        'remark': '备注',
        'statusName': '状态',
        'accessory': '附件',
        'name': '名称',
        'category': '类别',
        'quantity': '数量',
        'partNumber': '件号',
        'storehouse': '仓库',
        'shelf': '架位'
    }
    support_flow = partial(StorageFlow, 'storage flow')
    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'instorageDate': partial(DateField, widget=DateWidget()),
        'accessory': partial(StorageOrOutPutMulitFileuploadField),
    }

    one_line_columns = ['accessory']

    inline_model = StorageList
    inline_column = 'storage_id'
    column_export_list = [
        'category', 'partNumber', 'name', 'quantity', 'storehouse', 'shelf'
    ]

    column_details_list = [
        'number',
        'date',
        'instoreCategory',
        'instorageDate',
        'remark',
        'accessory',
    ]
    column_searchable_list = ('instoreCategory', 'number', 'statusName')

    can_extra = False

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/upload_file.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/storage_validation.js',
    ]

    extra_css = [
        '/static/css/datepicker.css',
        '/static/css/bootstrap-datetimepicker.min.css',
        '/static/css/jquery-ui.css',
        '/static/css/pikaday.css',
        '/static/css/dateHeight.css',
    ]

    types_dict = {
        'CGSQ': [PurchaseApplication, 'purchase'],
        'JRSQ': [LendApplication, 'lendApplicationMaterials'],
        'TLD2': [ReturnMaterialOrder, 'returnMaterials'],
        'SXGH': [RepairReturnOrder, 'repairReturnMaterials'],
        'JCGH': [LoanReturnOrder, 'loanReturnMaterials'],
        'CJD2': [DisassembleOrder, 'disassembleMaterials'],
    }

    base_table_columns = [
        ('category', AM_CATEGORY),
        ('partNumber', AM_PARTNUMBER),
        ('serialNum', AM_SERIALNUM),
        ('name', AM_NAME),
        ('quantity', AM_QUANTITY),
        ('unitPrice', AM_UNITPRICE),
        ('unit', AM_UNIT),
        ('applicableModel', AM_APPLICABLEMODEL),
        ('storehouse', AM_STOREHOUSE),
        ('shelf', AM_SHELF),
        ('flyTime', AM_FLYTIME),
        ('engineTime', AM_ENGINETIME),
        ('flightTimes', AM_FLIGHTTIMES),
        ('effectiveDate', AM_EFFECTIVEDATE),
        ('lastCheckDate', AM_LASTCHECKDATE),
        ('nextCheckDate', AM_NEXTCHECKDATE),
        ('certificateNum', AM_CERTIFICATENUM),
        ('airworthinessTagNum', AM_AIRWORTHINESSTAGNUM),
        ('manufacturer', AM_MANUFACTURER),
        ('supplier', AM_SUPPLIER),
    ]

    base_d_r_table_columns = [
        ('category', AM_CATEGORY),
        ('partNumber', AM_PARTNUMBER),
        ('serialNum', AM_SERIALNUM),
        ('name', AM_NAME),
        ('quantity', AM_QUANTITY),
        ('unitPrice', AM_UNITPRICE),
        ('unit', AM_UNIT),
        ('applicableModel', AM_APPLICABLEMODEL),
        ('storehouse', AM_STOREHOUSE),
        ('shelf', AM_SHELF),
        ('flyTime', AM_FLYTIME),
        ('engineTime', AM_ENGINETIME),
        ('flightTimes', AM_FLIGHTTIMES),
        ('effectiveDate', AM_EFFECTIVEDATE),
        ('lastCheckDate', AM_LASTCHECKDATE),
        ('nextCheckDate', AM_NEXTCHECKDATE),
        ('certificateNum', AM_CERTIFICATENUM),
        ('disassembleDate', AM_DISASSEMBLEDATE),
        ('airworthinessTagNum', AM_AIRWORTHINESSTAGNUM),
        ('manufacturer', AM_MANUFACTURER),
        ('supplier', AM_SUPPLIER),
    ]

    # 采购申请入库单
    purchase_table_columns = OrderedDict(base_table_columns)
    # 退料入库单
    return_material_table_columns = deepcopy(base_table_columns)
    return_material_table_columns.extend([('checkInstruction',
                                           AM_CHECKINSTRUCTION)])
    return_material_table_columns = OrderedDict(return_material_table_columns)
    # 拆机入库
    disassemble_table_columns = deepcopy(base_d_r_table_columns)
    disassemble_table_columns.extend([('planeNum', AM_DISPLANENUM)])
    disassemble_table_columns = OrderedDict(disassemble_table_columns)
    # 送修归还入库
    repair_return_table_columns = deepcopy(base_d_r_table_columns)
    repair_return_table_columns.extend([('checkInstruction',
                                         AM_CHECKINSTRUCTION)])
    repair_return_table_columns = OrderedDict(repair_return_table_columns)
    # 借入入库
    lend_table_columns = purchase_table_columns
    # 借出归还入库
    loan_return_table_columns = purchase_table_columns
    # 先给一个默认值
    table_columns = purchase_table_columns
    inst_foreign_model = None

    form_excluded_columns = [
        'statusName', 'borrow', 'loanReturn', 'disassemble', 'returnMaterial',
        'purchaseApplication', 'repairReturnOrder', 'storageList'
    ]

    column_formatters = {
        'accessory': accessory_formatter('accessory'),
    }

    @property
    def form_widget_args(self):
        return {
            'instoreCategory': {
                'readonly': True,
            },
            'number': {
                'readonly': True
            },
        }

    def __init__(self, *args, **kwargs):

        self.relationField = 'storageList'
        self.f_key = 'storage_id'
        self.relationModel = StorageList

        super(_StorageView, self).__init__(*args, **kwargs)

    def init_table_columns(self, whichcolumns):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False
        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = True
        table_columns[1]['need'] = True
        table_columns[3]['need'] = True
        table_columns[3]['readOnly'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[4]['need'] = True
        table_columns[5]['type'] = 'numeric'
        table_columns[5]['format'] = '0.00'
        table_columns[7]['editor'] = 'select'
        table_columns[7]['selectOptions'] = [self.plane_type]
        table_columns[7]['need'] = True
        table_columns[8]['need'] = True
        table_columns[9]['need'] = True
        table_columns[10]['validator'] = 'hhmm'
        table_columns[10]['format'] = '00:00'
        table_columns[11]['validator'] = 'hhmm'
        table_columns[11]['format'] = '00:00'
        table_columns[12]['type'] = 'numeric'
        table_columns[12]['format'] = '0'
        table_columns[13]['type'] = 'date'
        table_columns[13]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[13]['checkNeed'] = True
        table_columns[14]['type'] = 'date'
        table_columns[14]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[15]['type'] = 'date'
        table_columns[15]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[15]['checkNeed'] = True
        table_columns[19]['editor'] = 'select'
        table_columns[19]['selectOptions'] = [
            m.name for m in Supplier.query.all()
        ]

        if whichcolumns in [disassembleStore, repairReturnStore]:
            table_columns[19]['editor'] = 'select'
            table_columns[19]['selectOptions'] = [
                m.name for m in Manufacturer.query.all()
            ]
            table_columns[20]['editor'] = 'select'
            table_columns[20]['selectOptions'] = [
                m.name for m in Supplier.query.all()
            ]
            table_columns[17]['type'] = 'date'
            table_columns[17]['dateFormat'] = 'YYYY-MM-DD'
            if whichcolumns == disassembleStore:
                table_columns[17]['need'] = True
        else:
            table_columns[18]['editor'] = 'select'
            table_columns[18]['selectOptions'] = [
                m.name for m in Manufacturer.query.all()
            ]
        if whichcolumns in [repairReturnStore]:
            table_columns[21]['need'] = True
        if whichcolumns in [disassembleStore]:
            table_columns[21]['readOnly'] = True
        if whichcolumns in [retrunMaterialStore]:
            table_columns[20]['need'] = True
        if whichcolumns in [purchaseStore]:
            table_columns[10]['need'] = True
            table_columns[11]['need'] = True
            table_columns[12]['need'] = True

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/storage_table.js',
        })

        return json.dumps(table_columns)

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.instorageDate.validators = [DataRequired()]
            form.instoreCategory.validators = [DataRequired()]
        return super(_StorageView, self).validate_form(form)

    def on_model_change(self, form, model, is_created):
        category = {
            PurchaseSTORE: 'purchaseApplication',
            LendSTORE: 'borrow',
            LoanReturnSTORE: 'loanReturn',
            RepairReturnSTORE: 'repairReturnOrder',
            ReturnMaterialSTORE: 'returnMaterial',
            DisassembleSTORE: 'disassemble',
        }
        if is_created and model.instoreCategory in category.keys():
            setattr(model, category[model.instoreCategory],
                    self.inst_foreign_model)
        super(_StorageView, self).on_model_change(form, model, is_created)

    def set_default(self, table, name, model, ao_id, columns, field, related):
        instore_isnt = getattr(self._create_form_class, 'instoreCategory')
        self.table_columns = table
        instore_isnt.kwargs['default'] = name
        inst_model = model.query.filter(model.id == ao_id).first()
        if not inst_model:
            return ([], related)
        datas = []
        if not getattr(inst_model, field):
            return ([], related)

        for val in getattr(inst_model, field):
            data = []
            if val.category in ['一般航材', '时控件', '时寿件']:
                for i in range(0, val.quantity):
                    for k in columns:
                        # 对第8个机型添加默认值'Y5B(D)'
                        if len(data) == 7:
                            data.append(self.plane_type)
                            continue
                        if len(data) in [10, 11]:
                            try:
                                data.append(getattr(val, k))
                            except:
                                data.append('00:00')
                            continue
                        if not k:
                            data.append(k)
                            continue
                        if k == 'disassembleDate':
                            if getattr(inst_model, 'disassembleDate'):
                                data.append(inst_model.disassembleDate)
                            continue
                        if k == 'supplier':
                            if getattr(inst_model, 'supplier'):
                                data.append(inst_model.supplier)
                            continue
                        if k not in ['unit', 'quantity']:
                            data.append(getattr(val, k))
                            continue
                        if k == 'unit':
                            pn = getattr(val, 'partNumber')
                            ac = AirmaterialCategory.query.filter_by(
                                partNumber=pn).first()
                            if ac:
                                data.append(ac.unit)
                            else:
                                data.append(None)
                            continue
                        data.append(1)
                    datas.append(data)
                    data = []
                continue
            for k in columns:
                # 对第八个数据机型添加默认值'Y5B(D)'
                if len(data) == 7:
                    data.append(self.plane_type)
                    continue
                if len(data) in [10, 11]:
                    try:
                        data.append(getattr(val, k))
                    except:
                        data.append('00:00')
                    continue
                if not k:
                    data.append(k)
                    continue
                if k == 'disassembleDate':
                    if getattr(inst_model, 'disassembleDate'):
                        data.append(inst_model.disassembleDate)
                    continue
                if k == 'supplier':
                    if getattr(inst_model, 'supplier'):
                        data.append(inst_model.supplier)
                    continue
                if k != 'unit':
                    data.append(getattr(val, k))
                    continue
                pn = getattr(val, 'partNumber')
                ac = AirmaterialCategory.query.filter_by(partNumber=pn).first()
                if ac:
                    data.append(ac.unit)
                else:
                    data.append(None)
            datas.append(data)
        datas = json.dumps(datas)
        self.inst_foreign_model = inst_model

        return (datas, related)

    def create_storge_list(self, model_name=None, ao_id=None):
        if not model_name and not ao_id:
            model_name = request.args.get('model', '')
            ao_id = request.args.get('id', '')
        table_datas = json.dumps([])
        if ao_id and model_name:
            if 'CGSQ' in model_name:
                columns = [
                    'category',
                    'partNumber',
                    None,
                    'name',
                    'quantity',
                    'unitPrice',
                    'unit',
                    None,
                    None,
                    None,
                    'flyTime',
                    0,
                    0,
                    None,
                    None,
                    None,
                    None,
                    None,
                    'manufacturer',
                    'supplier',
                ]
                return self.set_default(self.purchase_table_columns,
                                        PurchaseSTORE, PurchaseApplication,
                                        ao_id, columns, 'purchase',
                                        purchaseStore)

            if 'JRSQ' in model_name:
                columns = [
                    'category',
                    'partNumber',
                    None,
                    'name',
                    'quantity',
                    None,
                    'unit',
                    None,
                    None,
                    None,
                    0,
                    0,
                    0,
                ]
                return self.set_default(self.lend_table_columns, LendSTORE,
                                        LendApplication, ao_id, columns,
                                        'lendApplicationMaterials', lendStore)

            if 'TLD' in model_name:
                columns = [
                    'category', 'partNumber', 'serialNum', 'name', 'quantity',
                    None, 'unit', None, None, None, 0, 0, 0
                ]
                return self.set_default(self.return_material_table_columns,
                                        ReturnMaterialSTORE,
                                        ReturnMaterialOrder, ao_id, columns,
                                        'returnMaterials', retrunMaterialStore)

            if 'CJD' in model_name:

                columns = [
                    'category',
                    'partNumber',
                    'serialNum',
                    'name',
                    'quantity',
                    None,
                    'unit',
                    None,
                    None,
                    None,
                    'flyTime',
                    'engineTime',
                    'flightTimes',
                    'effectiveDate',
                    'lastCheckDate',
                    'nextCheckDate',
                    None,
                    'disassembleDate',
                    None,
                    'manufacturer',
                    None,
                    'planeNum',
                ]
                return self.set_default(self.disassemble_table_columns,
                                        DisassembleSTORE, DisassembleOrder,
                                        ao_id, columns, 'disassembleMaterials',
                                        disassembleStore)

            if 'SXGH' in model_name:
                columns = [
                    'category', 'partNumber', 'serialNum', 'name', 'quantity',
                    None, 'unit', None, None, None, 'flyTime', 'engineTime',
                    'flightTimes', None, 'lastCheckDate', None, None, None,
                    None, 'manufacturer'
                ]
                return self.set_default(self.repair_return_table_columns,
                                        RepairReturnSTORE, RepairReturnOrder,
                                        ao_id, columns,
                                        'repairReturnMaterials',
                                        repairReturnStore)

            if 'JCGH' in model_name:
                columns = [
                    'category', 'partNumber', 'serialNum', 'name', 'quantity',
                    None, 'unit', None, None, None, 'flyTime', 'engineTime',
                    'flightTimes', None, 'lastCheckDate', None, None, None,
                    'manufacturer'
                ]
                return self.set_default(self.loan_return_table_columns,
                                        LoanReturnSTORE, LoanReturnOrder,
                                        ao_id, columns, 'loanReturnMaterials',
                                        loanReturnStore)
        # 如果不是通过别的申请创建 则返回空值
        return (table_datas, '')

    @expose('/new/', methods=['GET', 'POST'])
    def create_view(self):
        if request.method == 'GET':
            ret = self.create_storge_list()
            self._template_args.update({
                'table_columns':
                self.init_table_columns(ret[1]),
                'table_datas':
                ret[0],
            })
        else:
            request_str = request.headers['Referer']
            modelName = re.findall(r"model=(.+?)&", request_str)[0]
            action_id = None
            for val in request_str.split('&'):
                if 'id=' in val:
                    action_id = val.split('=')[1]
                    break
            # action_id = re.findall(r"&id=(.+?)", request_str)[0]
            self.create_storge_list(model_name=modelName, ao_id=action_id)
        # 处理加入入库按钮
        return_url = get_redirect_target() or self.get_url('.index_view')
        if not self.can_create:
            return redirect(return_url)
        form = self.create_form()
        model_name = request.args.get('model', '')
        if request.method == 'GET':
            self.get_accessory_from_before(form, model_name, self.types_dict)

        self.get_edit_details_view_colums(form.instoreCategory.data)
        if not hasattr(form, '_validated_ruleset') or not \
                form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_create_rules,
                                         form=form)

        if self.validate_form(form):
            model = self.create_model(form)
            if model:
                flash(gettext('Record was successfully created.'), 'success')
                return redirect(
                    self.get_save_return_url(model, is_created=True))

        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_create_rules)
        if self.create_modal and request.args.get('modal'):
            template = self.create_modal_template
        else:
            template = self.create_template

        perm = ActionNeedPermission('storage', Finish)
        refuse_op = ('入库', Finish) if perm.can() else None
        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        details_columns = self.get_column_names(
            self.review_details_columns or self.column_details_list, None)

        cfg = ActionViewCfg('', 'fa-bell-o', None, ('保存', Create),
                            ('入库', Finish))

        return self.render(template,
                           action=self.get_url('.create_view', verb='creat'),
                           details_columns=details_columns,
                           get_value=self.get_list_value,
                           return_url=return_url,
                           cancel_url=return_url,
                           action_name=cfg.action_name,
                           icon_value=cfg.icon_value,
                           form=form,
                           agreed=cfg.agreed,
                           refuse=refuse_op,
                           form_opts=form_opts,
                           one_line_columns=self.one_line_columns)

    @expose('/approve-edit-view/', methods=['POST', 'GET'])
    def approve_edit_view(self):
        ao_id = request.args.get('id', '')
        return_url = get_redirect_target() or self.get_url('.index_view')
        model = Storage.query.filter_by(id=ao_id).first()
        if not self.can_edit:
            return redirect(return_url)

        if model is None:
            flash(gettext('Record does not exist.'), 'error')
            return redirect(return_url)
        column = self.get_edit_details_view_colums(model.instoreCategory)
        self._template_args.update({
            'table_columns':
            self.init_table_columns(column),
            'table_datas':
            self.get_table_data_from_db(model),
        })
        model_id = model.id
        form = self.edit_form(obj=model)
        if not hasattr(form, '_validated_ruleset') or not\
                form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_edit_rules,
                                         form=form)
        if self.validate_form(form):
            if self.update_model(form, model):
                if request.method == 'POST' and self.support_flow:
                    self._custom_action(model, request.form)
                flash(gettext('Record was successfully saved.'), 'success')
                return redirect(
                    self.get_save_return_url(model, is_created=False))

        perm = ActionNeedPermission('storage', Finish)
        refuse_op = ('入库', Finish) if perm.can() else None
        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        details_columns = self.get_column_names(
            self.review_details_columns or self.column_details_list, None)

        cfg = ActionViewCfg('', 'fa-bell-o', None, ('保存', Edit),
                            ('入库', Finish))

        return self.render(self.approve_edit_template,
                           action=self.get_url('.approve_edit_view',
                                               verb='edit',
                                               id=model_id),
                           model=model,
                           details_columns=details_columns,
                           get_value=self.get_list_value,
                           return_url=return_url,
                           cancel_url=return_url,
                           action_name=cfg.action_name,
                           icon_value=cfg.icon_value,
                           form=form,
                           agreed=cfg.agreed,
                           refuse=refuse_op,
                           form_opts=form_opts,
                           model_id=model_id,
                           one_line_columns=self.one_line_columns)

    def get_edit_details_view_colums(self, instore_category):
        column = ''
        if instore_category == PurchaseSTORE:
            self.table_columns = self.purchase_table_columns
            column = purchaseStore
        elif instore_category == LendSTORE:
            self.table_columns = self.lend_table_columns
            column = lendStore
        elif instore_category == ReturnMaterialSTORE:
            self.table_columns = self.return_material_table_columns
            column = retrunMaterialStore
        elif instore_category == DisassembleSTORE:
            self.table_columns = self.disassemble_table_columns
            column = disassembleStore
        elif instore_category == RepairReturnSTORE:
            self.table_columns = self.repair_return_table_columns
            column = repairReturnStore
        elif instore_category == LoanReturnSTORE:
            self.table_columns = self.loan_return_table_columns
            column = loanReturnStore

        return column

    @expose('/details/')
    def details_view(self):
        ao_id = request.args.get('id', '')
        inst_model = Storage.query.filter_by(id=ao_id).first()
        if not inst_model or not ao_id:
            raise BackendServiceError('')
        column = self.get_edit_details_view_colums(inst_model.instoreCategory)
        self._template_args.update({
            'table_columns':
            self.get_readonly_table(column),
            'table_datas':
            self.get_table_data_from_db(inst_model),
            'extra_table_js':
            'js/inline_table_details.js'
        })
        return super(_StorageView, self).details_view()

    def get_readonly_table(self, which_columns=None):
        table_columns = json.loads(self.init_table_columns(which_columns))
        for column in table_columns:
            column.update({'readOnly': True})
        return json.dumps(table_columns)

    @expose('/get_pn_from_types/', methods=['GET'])
    def get_pn_from_types(self):
        try:
            types = request.args.get('storage_type')
            if types:
                type_letter = types[:4]
                if type_letter in self.types_dict:
                    inst = self.types_dict[type_letter][0].query.filter_by(
                        number=types).first()
                    materials = getattr(inst, self.types_dict[type_letter][1])
                    data = {}
                    for material in materials:
                        if material.category in data:
                            data[material.category].append(material.partNumber)
                        else:
                            data.update(
                                {material.category: [material.partNumber]})
                    data = json.dumps(data)
                    return jsonify(code=200, data=data, message='Ok')
                else:
                    raise Exception
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=404, message='Not Found')

    @expose('get_pn_from_id', methods=['GET'])
    def get_pn_from_id(self):
        try:
            ids = request.args.get('id')
            if ids:
                cate_dict = {
                    LendSTORE: ['lendApplication', 'lendApplicationMaterials'],
                    LoanReturnSTORE:
                    ['loanReturnOrder', 'loanReturnMaterials'],
                    DisassembleSTORE:
                    ['disassembleOrder', 'disassembleMaterials'],
                    ReturnMaterialSTORE:
                    ['returnMaterialOrder', 'returnMaterials'],
                    RepairReturnSTORE:
                    ['repairReturnOrder', 'repairReturnMaterials'],
                    PurchaseSTORE: ['purchaseApplication', 'purchase'],
                }
                inst = Storage.query.filter_by(id=ids).first()
                cate = inst.instoreCategory
                application = getattr(inst, cate_dict[cate][0])
                materials = getattr(application, cate_dict[cate][1])
                data = {}
                for material in materials:
                    if material.category in data:
                        data[material.category].append(material.partNumber)
                    else:
                        data.update({material.category: [material.partNumber]})
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=404, message='Not Found')

    @expose('/pdf/')
    def pdf_view(self):
        inst_id = request.args.get('id', '')
        inst = self.model.query.filter(self.model.id == inst_id).first()
        extra = {'name': inst.instoreCategory}
        return render_pdf(
            HTML(string=self._view_handler(self.pdf_template, inst_id, True, **
                                           extra)))
Beispiel #2
0
class _ExamineRepairRecordView(CustomView):

    # 排故检修记录列表视图应显示的内容
    column_list = [
        'recordNum', 'faultType', 'planeType', 'jihao', 'maintainDate',
        'faultAdress', 'maintainStaff', 'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'recordNum': '编号',
        'faultType': '故障类型',
        'planeType': '机型',
        'jihao': '飞机注册号',
        'faultDate': '故障发生日期',
        'faultAdress': '故障地点',
        'reportsMaker': '故障报告人',
        'aircraftNumber': '飞行编号',
        'description': '故障描述',
        'maintainStep': '维修措施',
        'maintainDate': '维修日期',
        'maintainStaff': '维修人员',
        'repairFileUrl': '上传附件',
        'checkDate': '检查日期',
        'checkStaff': '检查人员',
        'Soluted': '是否解决故障',
        'remark': '备注',
        'troubleShooting': '关联排故方案编号',
        'statusName': '状态'
    }

    column_searchable_list = (
        'recordNum',
        'faultType',
        'jihao',
        'faultAdress',
        'maintainStaff',
    )

    column_details_list = [
        'recordNum', 'faultType', 'planeType', 'jihao', 'faultDate',
        'faultAdress', 'reportsMaker', 'aircraftNumber', 'maintainDate',
        'maintainStaff', 'checkDate', 'checkStaff', 'Soluted', 'remark',
        'troubleShooting', 'description', 'maintainStep', 'repairFileUrl'
    ]

    form_widget_args = {
        'recordNum': {
            'readonly': True
        },
    }

    form_excluded_columns = ['reservedFault']

    one_line_columns = ['description', 'maintainStep', 'repairFileUrl']

    support_flow = partial(BasicFlow, 'Finish flow', support_create=True)

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/upload_file.js',
        # '/static/js/select_planeType.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/examine_repair_record_validation.js',
    ]

    form_overrides = {
        'repairFileUrl':
        partial(AirworthinessFileuploadField),
        'faultDate':
        partial(DateField, widget=DateWidget()),
        'maintainDate':
        partial(DateField, widget=DateWidget()),
        'checkDate':
        partial(DateField, widget=DateWidget()),
        'description':
        partial(TextAreaField, render_kw={
            'rows': 3,
            'style': 'resize:none;'
        }),
        'maintainStep':
        partial(TextAreaField, render_kw={
            'rows': 3,
            'style': 'resize:none;'
        }),
        'planeType':
        partial(SelectField,
                choices=[(model.value, model.label)
                         for model in get_allowed_models()]),
        'jihao':
        partial(ComponentsDropdownsField),
    }

    column_formatters = {
        'repairFileUrl': accessory_formatter('repairFileUrl'),
    }

    def on_model_change(self, form, model, is_created):
        super(_ExamineRepairRecordView,
              self).on_model_change(form, model, is_created)
        rf_id = request.args.get('id', '')
        view_url = request.args.get('view', '')
        if view_url and 'reservedfault' in view_url and is_created and rf_id:
            model.reservedFault_id = rf_id

    def __init__(self, *args, **kwargs):

        self.extra_js = getattr(self, 'extra_js', [])
        self.extra_css = getattr(self, 'extra_css', [])

        self.column_formatters.update({
            'faultDate': self.date_formatter_date,
            'maintainDate': self.date_formatter_date,
            'checkDate': self.date_formatter_date,
        })

        super(_ExamineRepairRecordView, self).__init__(*args, **kwargs)

    def create_form(self, obj=None):

        self._create_form_class.troubleShooting.kwargs[
            'query_factory'] = trouble_shooting_choices

        ts_id = request.args.get('id', '')
        view_url = request.args.get('view', '')
        if ts_id:
            if view_url and 'troubleshooting' in view_url:
                ts = TroubleShooting.query.filter(
                    TroubleShooting.id == ts_id).first()
                inst = FaultReports.query.join(
                    TroubleShooting,
                    TroubleShooting.faultReports_id == FaultReports.id).filter(
                        TroubleShooting.id == ts_id)
                tmp_form_class = self.get_create_form()
                datas = []
                for key, value in inst[0].__dict__.iteritems():
                    if key not in self.review_details_columns or\
                            key == 'recordNum':
                        continue
                    datas.append(key)
                    tmp = getattr(tmp_form_class, key)
                    tmp.kwargs['default'] = value

                tmp_form_class.troubleShooting.kwargs['default'] = ts
                tmp_form_class.faultType.kwargs['default'] = '严重故障'
                return tmp_form_class(get_form_data(), obj)

            if view_url and 'reservedfault' in view_url:
                rf = ReservedFault.query.filter(
                    ReservedFault.id == ts_id).first()
                return self.create_form_with_default(rf)

        return super(_ExamineRepairRecordView, self).create_form(obj)
Beispiel #3
0
class _ReturnMaterialOrderView(WithInlineTableView):
    # 退料单首页列表视图应显示的内容

    create_template = 'return_material_order/create.html'
    approve_edit_template = 'return_material_order/approve_edit.html'

    column_list = [
        'number', 'returnPerson', 'status', 'returnDate'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '日期',
        'returnPerson': '退料人',
        'returnDate': '退料日期',
        'remark': '备注',
        'returnReason': '退料原因',
        'statusName': '状态',
    }
    column_details_list = [
        'number', 'date', 'returnPerson',
        'returnDate', 'remark', 'returnReason'
    ]

    form_excluded_columns = ['statusName', 'storage', 'returnMaterials']

    # 退料单流程与拆机流程相同
    support_flow = partial(DisassembleOrderFlow, 'return material flow')

    one_line_columns = ['returnReason']

    column_searchable_list = ('number', 'date', 'returnPerson', 'returnDate', 'statusName')

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'returnDate': partial(DateField, widget=DateWidget()),
        'returnReason': partial(TextAreaField, render_kw={'rows': 3, 'style': 'resize:none;'}),

    }

    @property
    def form_widget_args(self):
        return {
            'number': {
                'readonly': True
            },
        }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.returnDate.validators = [DataRequired()]
        return super(_ReturnMaterialOrderView, self).validate_form(form)

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('quantity', AM_QUANTITY),
            ('unit', AM_UNIT),
            ('flightNum', AM_PLANENUM),
        ])
        self.relationField = 'returnMaterials'
        self.f_key = 'application_id'
        self.relationModel = ReturnMaterial

        super(_ReturnMaterialOrderView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = ['一般航材', '工装设备', '消耗品',
                                             '化工品', '时控件', '时寿件']
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[3]['readOnly'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[4]['need'] = True
        table_columns[5]['readOnly'] = True
        table_columns[6]['editor'] = 'select'
        table_columns[6]['selectOptions'] = self.get_aircraft()

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/return_material_order.js',
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': json.dumps([]),
        })
        return super(_ReturnMaterialOrderView, self).create_view()
Beispiel #4
0
class _EngineeringOrderView(CustomView):
    extra_js = [
        '/static/js/upload_file.js',
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/switch_form.js',
        '/static/js/select_planeType.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/engineeringorder_validation.js',
    ]

    # 工程指令列表视图应显示的内容
    column_list = [
        'insNum',
        'insTitle',
        'insCategory',
        'statusName',
    ]
    # 对应内容的中文翻译
    column_labels = {
        'insNum': '指令号',
        'insTitle': '标题',
        'insCategory': '指令类别',
        'relateFileUrl': '相关文档',
        'planeType': '机型',
        'jihao': '飞机注册号',
        'effectPart': '受影响部件',
        'effectEngine': '受影响的发动机',
        'grantTime': '发放期限',
        'finishTime': '完成期限',
        'executeTime': '执行日期',
        'isClaim': '能否索赔',
        'stopHours': '工时停场时',
        'repeatePeriod': '重复周期',
        'ataCode': 'ATA章节号',
        'usability': '适用性',
        'manualChange': '手册更改',
        'isFeedback': '是否反馈',
        'reason': '概述/理由',
        'remark': '备注/说明',
        'statusName': '状态',
        'maintenanceRecord': '关联的维护保养记录',
        'airworthiness': '关联的适航文件编号'
    }

    # 待复核的内容要少
    column_details_list = [
        'insNum', 'insTitle', 'insCategory', 'planeType', 'jihao',
        'effectPart', 'effectEngine', 'grantTime', 'finishTime', 'executeTime',
        'isClaim', 'stopHours', 'repeatePeriod', 'ataCode', 'usability',
        'manualChange', 'isFeedback', 'remark', 'maintenanceRecord',
        'airworthiness', 'reason', 'relateFileUrl'
    ]

    support_flow = partial(EOFlow, 'Default basic approval flow')

    form_excluded_columns = ['troubleshooting', 'maintenanceRecord']

    column_formatters = {
        'relateFileUrl': accessory_formatter('relateFileUrl'),
    }

    one_line_columns = ['reason', 'relateFileUrl']

    column_searchable_list = (
        'insNum',
        'insTitle',
        'insCategory',
    )

    form_overrides = {
        'relateFileUrl':
        partial(EngineeringOrderFileuploadField),
        'repeatePeriod':
        partial(InputSelectMixinField),
        'grantTime':
        partial(DateField, widget=DateWidget()),
        'finishTime':
        partial(DateField, widget=DateWidget()),
        'executeTime':
        partial(DateField, widget=DateWidget()),
        'planeType':
        partial(SelectField,
                choices=[(model.value, model.label)
                         for model in get_allowed_models()]),
        'jihao':
        partial(ComponentsDropdownsField),
    }

    def create_form(self, obj=None):

        ao_id = request.args.get('id', '')

        if ao_id:
            inst = Airworthiness.query.filter(
                Airworthiness.id == ao_id).first()
            return self.create_form_with_default(inst, 'airworthiness')

        return super(_EngineeringOrderView, self).create_form(obj)

    def on_model_change(self, form, model, is_created):
        super(_EngineeringOrderView,
              self).on_model_change(form, model, is_created)
        ao_id = request.args.get('id', '')
        if is_created and ao_id:
            model.airworthiness_id = ao_id

    @property
    def form_widget_args(self):
        return {
            'insNum': {
                'readonly': True
            },
        }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.repeatePeriod.validators = [DataRequired('请输入正数')]
            form.insNum.validators = [DataRequired()]

        return super(_EngineeringOrderView, self).validate_form(form)

    def get_query(self):
        datas = super(_EngineeringOrderView, self).get_query()
        return self.get_recieved_query(datas, 'engineeringorder')
Beispiel #5
0
class _ScrapView(UpdateStorageListFreezedQuantity):
    """报废单视图"""

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/scrap_validation.js',
    ]

    column_list = [
        'number', 'scrapCategory', 'applyPerson', 'applyDate', 'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'applyPerson': '申请人',
        'applyDate': '申请日期',
        'scrapCategory': '报废类型',
        'statusName': '状态',
        'applyReason': '申请原因',
        'partNumber': '件号',
        'serialNum': '序号',
        'name': '名称',
        'category': '类别',
        'quantity': '数量',
    }

    column_searchable_list = ('scrapCategory', 'number', 'statusName',
                              'applyPerson')
    # 查看页面显示的详情
    column_details_list = [
        'number', 'applyPerson', 'applyDate', 'scrapCategory', 'applyReason'
    ]

    form_excluded_columns = ['statusName', 'scrapMaterial', 'putOutStore']

    support_flow = partial(ScrapFlow, 'scrap flow')

    form_overrides = {
        'applyDate': partial(DateField, widget=DateWidget()),
    }
    form_widget_args = {
        'number': {
            'readonly': True
        },
    }

    one_line_columns = ['applyReason']

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
        return super(_ScrapView, self).validate_form(form)

    def get_query(self):
        datas = super(_ScrapView, self).get_query()

        ids = [item.id for item in datas] if datas.count() else []
        role = Role.query.join(BasicAction,
                               Role.id == BasicAction.role_id).filter(
                                   BasicAction.view == True,
                                   BasicAction.model == 'scrap')

        if not role.count():
            return datas

        for val in role:
            if val not in current_user.roles:
                continue
            datas = self.model.query.filter(
                or_(
                    self.model.id.in_(ids),
                    self.model.auditStatus.in_(
                        [Reviewed, SecApproved, Scrapped])))

        return datas

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([('category', AM_CATEGORY),
                                          ('partNumber', AM_PARTNUMBER),
                                          ('serialNum', AM_SERIALNUM),
                                          ('name', AM_NAME),
                                          ('manufacturer', AM_MANUFACTURER),
                                          ('quantity', AM_QUANTITY),
                                          ('effectiveDate', AM_EFFECTIVEDATE),
                                          ('lastCheckDate', AM_LASTCHECKDATE),
                                          ('nextCheckDate', AM_NEXTCHECKDATE)])
        self.relationField = 'scrapMaterial'
        self.f_key = 'application_id'
        self.relationModel = ScrapMaterial

        super(_ScrapView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[2]['editor'] = 'select'
        table_columns[2]['selectOptions'] = []
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['editor'] = 'select'
        table_columns[4]['selectOptions'] = [
            m.name for m in Manufacturer.query.all()
        ]
        table_columns[5]['type'] = 'numeric'
        table_columns[5]['format'] = '0'
        table_columns[5]['need'] = True
        table_columns[6]['editor'] = 'select'
        table_columns[6]['selectOptions'] = []
        table_columns[6]['checkNeed'] = True
        table_columns[7]['type'] = 'date'
        table_columns[7]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[8]['editor'] = 'select'
        table_columns[8]['selectOptions'] = []
        table_columns[8]['checkNeed'] = True

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/scrap_table.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):

        rowid = request.args.getlist('rowid')
        ao_id = request.args.get('id')
        cats = None
        table_datas = []
        if rowid:
            cats = AirMaterialStorageList.query.filter(
                AirMaterialStorageList.id.in_(rowid)).all()
        elif ao_id:
            cats = AirMaterialStorageList.query.filter(
                AirMaterialStorageList.id == ao_id).all()
        if cats:
            table_datas = [[
                cat.category, cat.partNumber, cat.serialNum, cat.name,
                cat.manufacturer, cat.quantity - cat.freezingQuantity,
                cat.effectiveDate, cat.lastCheckDate, cat.nextCheckDate
            ] for cat in cats]

        table_datas = json.dumps(table_datas)

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })

        return super(_ScrapView, self).create_view()

    def get_audit_form_class(self, model, verb):
        if verb == 'review' and model.scrapCategory == '一般':
            return self._action_view_cfg['review_only'].form
        return None
Beispiel #6
0
class _PutOutStoreView(WithInlineTableView):
    # 出库列表视图应显示的内容
    list_template = 'out_storage/list.html'
    column_list = [
        'number',
        'date',
        'outStoreCategory',
        'statusName',
    ]
    pdf_template = 'storage/pdf.html'

    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'outDate': '出库日期',
        'date': '日期',
        'outStoreCategory': '出库类别',
        'loanCategory': '借出类型',
        'borrowCompany': '借用单位',
        'statusName': '状态',
        'remark': '备注',
        'accessory': '附件',
        'companyAddr': '单位地址',
        'contactPerson': '联系人',
        'telephone': '电话',
        'fax': '传真',
        'mailbox': '邮箱',
        'name': '名称',
        'category': '类别',
        'quantity': '数量',
        'partNumber': '件号',
    }
    column_searchable_list = ('outStoreCategory', 'number', 'statusName')

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/upload_file.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/put_out_validate.js',
    ]

    extra_css = [
        '/static/css/datepicker.css',
        '/static/css/bootstrap-datetimepicker.min.css',
        '/static/css/jquery-ui.css',
        '/static/css/pikaday.css',
    ]
    can_extra = False

    one_line_columns = ['accessory']

    inline_model = PutOutStoreMaterial
    inline_column = 'putOutStorage_id'
    column_export_list = ['category', 'partNumber', 'name', 'quantity']

    support_flow = partial(PutOutStoreFlow, 'put out store flow')
    form_overrides = {
        'date':
        partial(DateField, widget=DateWidget()),
        'outDate':
        partial(DateField, widget=DateWidget()),
        'loanCategory':
        partial(SelectField, choices=[
            ('一般', '一般'),
            ('重要', '重要'),
        ]),
        'accessory':
        partial(StorageOrOutPutMulitFileuploadField),
    }

    column_formatters = {
        'accessory': accessory_formatter('accessory'),
    }

    column_details_list = [
        'number', 'outDate', 'date', 'outStoreCategory', 'loanCategory',
        'borrowCompany', 'companyAddr', 'contactPerson', 'telephone', 'fax',
        'mailbox', 'remark', 'accessory'
    ]

    base_table_columns = [
        ('category', AM_CATEGORY),
        ('partNumber', AM_PARTNUMBER),
        ('serialNum', AM_SERIALNUM),
        ('name', AM_NAME),
        ('quantity', AM_QUANTITY),
    ]

    types_dict = {
        'JCSQ': [LoanApplicationOrder],
        'JRGH': [BorrowingInReturnModel],
        'ZJSQ': [AssembleApplication],
        'BFSQ': [Scrap],
        'SXSQ': [RepairApplication],
    }

    # 下面五项为五种出库类型的表体内容
    # 借出出库
    loan_table_columns = deepcopy(base_table_columns)
    loan_table_columns.extend([
        ('manufacturer', AM_MANUFACTURER),
        ('supplier', AM_SUPPLIER),
        ('effectiveDate', AM_EFFECTIVEDATE),
        ('lastCheckDate', AM_LASTCHECKDATE),
        ('nextCheckDate', AM_NEXTCHECKDATE),
        ('flyTime', AM_FLYTIME),
        ('engineTime', AM_ENGINETIME),
        ('flightTimes', AM_FLIGHTTIMES),
        ('unit', AM_UNIT),
    ])
    loan_table_columns = OrderedDict(loan_table_columns)
    # 借入归还出库
    borrow_return_table_columns = deepcopy(base_table_columns)
    borrow_return_table_columns.extend([
        ('manufacturer', AM_MANUFACTURER),
        ('supplier', AM_SUPPLIER),
        ('effectiveDate', AM_EFFECTIVEDATE),
        ('flyTime', AM_FLYTIME),
        ('engineTime', AM_ENGINETIME),
        ('flightTimes', AM_FLIGHTTIMES),
        ('lastCheckDate', AM_LASTCHECKDATE),
        ('nextCheckDate', AM_NEXTCHECKDATE),
    ])
    borrow_return_table_columns = OrderedDict(borrow_return_table_columns)
    # 装机出库
    assemble_table_columns = deepcopy(base_table_columns)
    assemble_table_columns.extend([('manufacturer', AM_MANUFACTURER),
                                   ('supplier', AM_SUPPLIER),
                                   ('effectiveDate', AM_EFFECTIVEDATE),
                                   ('lastCheckDate', AM_LASTCHECKDATE),
                                   ('nextCheckDate', AM_NEXTCHECKDATE),
                                   ('flyTime', AM_FLYTIME),
                                   ('engineTime', AM_ENGINETIME),
                                   ('flightTimes', AM_FLIGHTTIMES),
                                   ('planeNum', AM_PLANENUM)])
    assemble_table_columns = OrderedDict(assemble_table_columns)
    # 送修出库
    repair_table_columns = deepcopy(base_table_columns)
    repair_table_columns.extend([('manufacturer', AM_MANUFACTURER),
                                 ('supplier', AM_SUPPLIER),
                                 ('effectiveDate', AM_EFFECTIVEDATE),
                                 ('flyTime', AM_FLYTIME),
                                 ('engineTime', AM_ENGINETIME),
                                 ('flightTimes', AM_FLIGHTTIMES),
                                 ('lastCheckDate', AM_LASTCHECKDATE),
                                 ('nextCheckDate', AM_NEXTCHECKDATE),
                                 ('planeNum', AM_PLANENUM),
                                 ('repairCompany', AM_REPAIRCOMPANY)])
    repair_table_columns = OrderedDict(repair_table_columns)
    # 报废出库
    scrap_table_columns = deepcopy(base_table_columns)
    scrap_table_columns.extend([('scrapReason', AM_SCRAPREASON),
                                ('effectiveDate', AM_EFFECTIVEDATE),
                                ('nextCheckDate', AM_NEXTCHECKDATE)])
    scrap_table_columns = OrderedDict(scrap_table_columns)
    # 先给一个默认值
    table_columns = loan_table_columns
    inst_foreign_model = None
    # 下面表头所要剔除的内容
    common_exclude_list = [
        'loanCategory',
        'borrowCompany',
        'companyAddr',
        'contactPerson',
        'telephone',
        'fax',
        'mailbox',
    ]

    form_excluded_columns = [
        'statusName',
        'borrowingInReturn',
        'loanApplication',
        'assembleApplication',
        'scrap',
        'repairApplication',
        'putOutStoreMaterials',
    ]

    @property
    def form_widget_args(self):
        return {
            'number': {
                'readonly': True,
            },
            'outStoreCategory': {
                'readonly': True,
            }
        }

    def __init__(self, *args, **kwargs):
        # 深拷贝一个详情,用于后续需要剔除字段的详情视图
        self.relationField = 'putOutStoreMaterials'
        self.f_key = 'putOutStorage_id'
        self.relationModel = PutOutStoreMaterial

        super(_PutOutStoreView, self).__init__(*args, **kwargs)
        self.tmp_columns = deepcopy(self.column_details_list)
        self.tmp_review_columns = deepcopy(self.review_details_columns)

    def init_table_columns(self, whichcolumns):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False
        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['readOnly'] = True
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['readOnly'] = True
        table_columns[1]['need'] = True
        table_columns[2]['editor'] = 'select'
        table_columns[2]['selectOptions'] = []
        table_columns[2]['readOnly'] = True
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[4]['need'] = True

        if whichcolumns == borrowReturnOutStore:
            table_columns[5]['editor'] = 'select'
            table_columns[5]['selectOptions'] = self.get_manufacturer()
            table_columns[6]['editor'] = 'select'
            table_columns[6]['selectOptions'] = self.get_supplier()
            table_columns[7]['readOnly'] = True
            table_columns[7]['checkneed'] = True
            table_columns[8]['validator'] = 'hhmm'
            table_columns[9]['validator'] = 'hhmm'
            table_columns[10]['type'] = 'numeric'
            table_columns[10]['format'] = '0'
            table_columns[11]['type'] = 'date'
            table_columns[11]['dateFormat'] = 'YYYY-MM-DD'
            table_columns[12]['readOnly'] = True
            table_columns[12]['checkNeed'] = True
        if whichcolumns in [loanOutstore]:
            table_columns[5]['editor'] = 'select'
            table_columns[5]['selectOptions'] = self.get_manufacturer()
            table_columns[6]['editor'] = 'select'
            table_columns[6]['selectOptions'] = self.get_supplier()
            table_columns[7]['readOnly'] = True
            table_columns[7]['checkNeed'] = True
            table_columns[8]['type'] = 'date'
            table_columns[8]['dateFormat'] = 'YYYY-MM-DD'
            table_columns[9]['readOnly'] = True
            table_columns[9]['checkNeed'] = True
            table_columns[10]['validator'] = 'hhmm'
            table_columns[11]['validator'] = 'hhmm'
            table_columns[12]['type'] = 'numeric'
            table_columns[12]['format'] = '0'
        if whichcolumns in [assembleOutStore]:
            table_columns[5]['editor'] = 'select'
            table_columns[5]['selectOptions'] = self.get_manufacturer()
            table_columns[6]['editor'] = 'select'
            table_columns[6]['selectOptions'] = self.get_supplier()
            table_columns[7]['readOnly'] = True
            table_columns[7]['checkNeed'] = True
            table_columns[8]['type'] = 'date'
            table_columns[8]['dateFormat'] = 'YYYY-MM-DD'
            table_columns[9]['readOnly'] = True
            table_columns[9]['checkNeed'] = True
            table_columns[10]['validator'] = 'hhmm'
            table_columns[11]['validator'] = 'hhmm'
            table_columns[12]['type'] = 'numeric'
            table_columns[12]['format'] = '0'
            table_columns[13]['editor'] = 'select'
            table_columns[13]['selectOptions'] = self.get_aircraft()
            table_columns[13]['need'] = True
        if whichcolumns in [repairOutStore]:
            table_columns[5]['editor'] = 'select'
            table_columns[5]['selectOptions'] = self.get_manufacturer()
            table_columns[6]['editor'] = 'select'
            table_columns[6]['selectOptions'] = self.get_supplier()
            table_columns[7]['readOnly'] = True
            table_columns[7]['checkneed'] = True
            table_columns[8]['validator'] = 'hhmm'
            table_columns[9]['validator'] = 'hhmm'
            table_columns[10]['type'] = 'numeric'
            table_columns[10]['format'] = '0'
            table_columns[11]['type'] = 'date'
            table_columns[11]['dateFormat'] = 'YYYY-MM-DD'
            table_columns[12]['readOnly'] = True
            table_columns[12]['checkNeed'] = True
            table_columns[12]['need'] = False
            table_columns[13]['editor'] = 'select'
            table_columns[13]['selectOptions'] = self.get_aircraft()
            table_columns[14]['editor'] = 'select'
            table_columns[14]['selectOptions'] = self.get_repair_supplier()

        if whichcolumns == scrapOutStore:
            table_columns[6]['readOnly'] = True
            table_columns[7]['readOnly'] = True

        self._template_args.update({
            'inline_table':
            True,
            'can_add_line':
            False,
            'can_del_line':
            True,
            'extra_table_js':
            'js/put_out_store_table.js',
        })

        return json.dumps(table_columns)

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.outStoreCategory.validators = [DataRequired()]
            form.outDate.validators = [DataRequired()]
        return super(_PutOutStoreView, self).validate_form(form)

    def on_model_change(self, form, model, is_created):
        category = {
            LoanOutSTORE: 'loanApplication',
            BorrowReturnOutSTORE: 'borrowingInReturn',
            AssembleOutSTORE: 'assembleApplication',
            ScrapOutSTORE: 'scrap',
            RepairOutSTORE: 'repairApplication',
        }
        if is_created and model.outStoreCategory in category.keys():
            setattr(model, category[model.outStoreCategory],
                    self.inst_foreign_model)
        super(_PutOutStoreView, self).on_model_change(form, model, is_created)

    def create_form(self, obj=None):
        ret = None
        model_name = request.args.get('model', '')
        if request.method == 'GET':
            ao_id = request.args.get('id', '')
            ret = self.creat_detail_view(ao_id=ao_id,
                                         create=True,
                                         storage_model=model_name)
        else:
            request_str = request.headers['Referer']
            modelName = re.findall(r"model=(.+?)&", request_str)[0]
            action_id = None
            for val in request_str.split('&'):
                if 'id=' in val:
                    action_id = val.split('=')[1]
                    break
            # action_id = ac_id if ''request_str.split('&id=')[1]
            ret = self.creat_detail_view(ao_id=action_id,
                                         create=True,
                                         storage_model=modelName)
        if ret:
            self._template_args.update({
                'table_columns':
                self.init_table_columns(ret[1]),
                'table_datas':
                ret[0],
            })
        self.get_accessory_from_before(self.get_create_form(), model_name,
                                       self.types_dict)
        return self._create_form_class(get_form_data(), obj=obj)

    @expose('/new/', methods=['GET', 'POST'])
    def create_view(self):
        return_url = get_redirect_target() or self.get_url('.index_view')
        if not self.can_create:
            return redirect(return_url)

        form = self.create_form()
        if not hasattr(form, '_validated_ruleset') or not \
                form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_create_rules,
                                         form=form)

        if self.validate_form(form):
            model = self.create_model(form)
            if model:
                flash(gettext('Record was successfully created.'), 'success')
                return redirect(
                    self.get_save_return_url(model, is_created=True))

        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_create_rules)
        if self.create_modal and request.args.get('modal'):
            template = self.create_modal_template
        else:
            template = self.create_template

        perm = ActionNeedPermission('storage', Finish)
        refuse_op = ('出库', Finish) if perm.can() else None
        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        details_columns = self.get_column_names(
            self.review_details_columns or self.column_details_list, None)

        cfg = ActionViewCfg('', 'fa-bell-o', None, ('保存', Create),
                            ('出库', Finish))

        return self.render(template,
                           action=self.get_url('.create_view', verb='creat'),
                           details_columns=details_columns,
                           get_value=self.get_list_value,
                           return_url=return_url,
                           cancel_url=return_url,
                           action_name=cfg.action_name,
                           icon_value=cfg.icon_value,
                           form=form,
                           agreed=cfg.agreed,
                           refuse=refuse_op,
                           form_opts=form_opts,
                           one_line_columns=self.one_line_columns)

    def get_post_create_view_colums(self, outstore_category):
        category_to_columns = {
            LoanOutSTORE: self.loan_table_columns,
            BorrowReturnOutSTORE: self.borrow_return_table_columns,
            AssembleOutSTORE: self.assemble_table_columns,
            RepairOutSTORE: self.repair_table_columns,
            ScrapOutSTORE: self.scrap_table_columns,
        }
        if outstore_category in category_to_columns.keys():
            self.table_columns = category_to_columns[outstore_category]

    @expose('/approve-edit-view/', methods=['POST', 'GET'])
    def approve_edit_view(self):
        ao_id = request.args.get('id', '')
        return_url = get_redirect_target() or self.get_url('.index_view')
        model = PutOutStoreModel.query.filter_by(id=ao_id).first()
        if not self.can_edit:
            return redirect(return_url)

        if model is None:
            flash(gettext('Record does not exist.'), 'error')
            return redirect(return_url)
        model_id = model.id
        form = self.edit_form(obj=model)
        if not hasattr(form, '_validated_ruleset') or not\
                form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_edit_rules,
                                         form=form)
        if self.validate_form(form):
            if self.update_model(form, model):
                if request.method == 'POST' and self.support_flow:
                    self._custom_action(model, request.form)
                flash(gettext('Record was successfully saved.'), 'success')
                return redirect(
                    self.get_save_return_url(model, is_created=False))

        perm = ActionNeedPermission('storage', Finish)
        refuse_op = ('出库', Finish) if perm.can() else None
        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        details_columns = self.get_column_names(
            self.review_details_columns or self.column_details_list, None)

        cfg = ActionViewCfg('', 'fa-bell-o', None, ('保存', Edit),
                            ('出库', Finish))

        return self.render(self.approve_edit_template,
                           action=self.get_url('.approve_edit_view',
                                               verb='edit',
                                               id=model_id),
                           model=model,
                           details_columns=details_columns,
                           get_value=self.get_list_value,
                           return_url=return_url,
                           cancel_url=return_url,
                           action_name=cfg.action_name,
                           icon_value=cfg.icon_value,
                           form=form,
                           agreed=cfg.agreed,
                           refuse=refuse_op,
                           form_opts=form_opts,
                           model_id=model_id,
                           one_line_columns=self.one_line_columns)

    @expose('/details/')
    def details_view(self):
        ao_id = request.args.get('id', '')
        inst_model = PutOutStoreModel.query.filter_by(id=ao_id).first()
        if not ao_id or not inst_model:
            raise BackendServiceError('')
        column = self.get_edit_details_view_colums(inst_model.outStoreCategory)
        self._template_args.update({
            'table_columns':
            self.get_readonly_table(column[0]),
            'table_datas':
            self.get_table_data_from_db(inst_model),
            'extra_table_js':
            'js/inline_table_details.js'
        })
        self.creat_detail_view(exclude_list=column[2])
        return super(_PutOutStoreView, self).details_view()

    def get_readonly_table(self, which_columns=None):
        table_columns = json.loads(self.init_table_columns(which_columns))
        for column in table_columns:
            column.update({'readOnly': True})
        return json.dumps(table_columns)

    def edit_form(self, obj=None):
        ao_id = request.args.get('id', '')
        outStorageModel = PutOutStoreModel.query.filter_by(id=ao_id).first()
        des = self.get_edit_details_view_colums(
            outStorageModel.outStoreCategory)
        converter = self.model_form_converter(self.session, self)
        self._template_args.update({
            'table_columns':
            self.init_table_columns(des[0]),
            'table_datas':
            self.get_table_data_from_db(outStorageModel),
        })
        self._edit_form_class = form.get_form(
            self.model,
            converter,
            base_class=self.form_base_class,
            only=self.form_columns,
            exclude=des[1],
            field_args=self.form_args,
            ignore_hidden=self.ignore_hidden,
            extra_fields=self.form_extra_fields)
        return self._edit_form_class(get_form_data(), obj=obj)

    def get_edit_details_view_colums(self, outstore_category):
        column, tmp_excluded_columns = None, None
        tmp_excluded_columns = deepcopy(self.form_excluded_columns)
        detail_remove_list = []
        if outstore_category == LoanOutSTORE:
            self.table_columns = self.loan_table_columns
            column = loanOutstore
        else:
            detail_remove_list = self.common_exclude_list
        if outstore_category == BorrowReturnOutSTORE:
            tmp_excluded_columns.extend(self.common_exclude_list)
            self.table_columns = self.borrow_return_table_columns
            column = borrowReturnOutStore
        if outstore_category == AssembleOutSTORE:
            tmp_excluded_columns.extend(self.common_exclude_list)
            self.table_columns = self.assemble_table_columns
            column = assembleOutStore
        if outstore_category == RepairOutSTORE:
            tmp_excluded_columns.extend(self.common_exclude_list)
            self.table_columns = self.repair_table_columns
            column = repairOutStore
        if outstore_category == ScrapOutSTORE:
            tmp_excluded_columns.extend(self.common_exclude_list)
            self.table_columns = self.scrap_table_columns
            column = scrapOutStore
        return (column, tmp_excluded_columns, detail_remove_list)

    # 创建 新建和详细信息视图中的字段项
    def creat_detail_view(self,
                          ao_id=None,
                          create=False,
                          storage_model=None,
                          exclude_list=None):
        self.review_details_columns = deepcopy(self.tmp_review_columns)
        if create:
            tmp_excluded_columns = deepcopy(self.form_excluded_columns)
            inst_model, tmp_model, des_model = None, None, None
            table_datas = json.dumps([])
            whichcolumn = None
            if ao_id and storage_model:
                if 'JCSQ' in storage_model:
                    tmp_model = LoanApplicationOrder
                    self.handle_exclude_list(tmp_excluded_columns)
                    self.table_columns = self.loan_table_columns
                    self._create_form_class.outStoreCategory.kwargs[
                        'default'] = LoanOutSTORE
                    des_model = LoanApplicationOrder.query.filter(
                        LoanApplicationOrder.id == ao_id).first()
                    table_datas = [[
                        inst.category,
                        inst.partNumber,
                        inst.serialNum,
                        inst.name,
                        inst.quantity,
                        inst.manufacturer,
                        None,
                        inst.effectiveDate,
                        inst.lastCheckDate,
                        inst.nextCheckDate,
                        inst.flyTime,
                        inst.engineTime,
                        inst.flightTimes,
                    ] for inst in des_model.loanMaterials]
                    table_datas = json.dumps(table_datas)
                    whichcolumn = loanOutstore
                elif 'JRGH' in storage_model:
                    tmp_model = BorrowingInReturnModel
                    self.table_columns = self.borrow_return_table_columns
                    tmp_excluded_columns.extend(self.common_exclude_list)
                    self.handle_exclude_list(tmp_excluded_columns)
                    self._create_form_class.outStoreCategory.kwargs[
                        'default'] = BorrowReturnOutSTORE
                    des_model = BorrowingInReturnModel.query.filter(
                        BorrowingInReturnModel.id == ao_id).first()
                    table_datas = [[
                        inst.category, inst.partNumber, inst.serialNum,
                        inst.name, inst.quantity, None, None,
                        inst.effectiveDate, inst.flyTime, inst.engineTime,
                        inst.flightTimes, inst.lastCheckDate,
                        inst.nextCheckDate
                    ] for inst in des_model.borrowingInReturnMaterials]
                    table_datas = json.dumps(table_datas)
                    whichcolumn = borrowReturnOutStore
                elif 'ZJSQ' in storage_model:
                    tmp_model = AssembleApplication
                    self.table_columns = self.assemble_table_columns
                    tmp_excluded_columns.extend(self.common_exclude_list)
                    self.handle_exclude_list(tmp_excluded_columns)
                    self._create_form_class.outStoreCategory.kwargs[
                        'default'] = AssembleOutSTORE
                    des_model = AssembleApplication.query.filter(
                        AssembleApplication.id == ao_id).first()
                    table_datas = [[
                        inst.category,
                        inst.partNumber,
                        inst.serialNum,
                        inst.name,
                        inst.quantity,
                        inst.manufacturer,
                        None,
                        inst.effectiveDate,
                        inst.lastCheckDate,
                        inst.nextCheckDate,
                        inst.flyTime,
                        inst.engineTime,
                        inst.flightTimes,
                        inst.planeNum,
                    ] for inst in des_model.assembleApplicationList]
                    table_datas = json.dumps(table_datas)
                    whichcolumn = assembleOutStore
                elif 'SXSQ' in storage_model:
                    tmp_model = RepairApplication
                    inst_model = tmp_model.query.filter(
                        tmp_model.id == ao_id).first()
                    self.table_columns = self.repair_table_columns
                    tmp_excluded_columns.extend(self.common_exclude_list)
                    self.handle_exclude_list(tmp_excluded_columns)
                    self._create_form_class.outStoreCategory.kwargs[
                        'default'] = RepairOutSTORE
                    des_model = RepairApplication.query.filter(
                        RepairApplication.id == ao_id).first()
                    table_datas = [[
                        inst.category, inst.partNumber, inst.serialNum,
                        inst.name, inst.quantity, inst.manufacturer, None,
                        inst.effectiveDate, inst.flyTime, inst.engineTime,
                        inst.flightTimes, inst.lastCheckDate,
                        inst.nextCheckDate, inst.planeNum,
                        des_model.repairCompany
                    ] for inst in des_model.repairAppl]
                    table_datas = json.dumps(table_datas)
                    whichcolumn = repairOutStore
                elif 'BFSQ' in storage_model:
                    tmp_model = Scrap
                    self.table_columns = self.scrap_table_columns
                    tmp_excluded_columns.extend(self.common_exclude_list)
                    self.handle_exclude_list(tmp_excluded_columns)
                    self._create_form_class.outStoreCategory.kwargs[
                        'default'] = ScrapOutSTORE
                    des_model = Scrap.query.filter(Scrap.id == ao_id).first()
                    table_datas = [[
                        inst.category, inst.partNumber, inst.serialNum,
                        inst.name, inst.quantity, None, inst.effectiveDate,
                        inst.nextCheckDate
                    ] for inst in des_model.scrapMaterial]
                    table_datas = json.dumps(table_datas)
                    whichcolumn = scrapOutStore
                else:
                    self.handle_exclude_list(tmp_excluded_columns)
                    return (table_datas, whichcolumn)
                self.inst_foreign_model = des_model
                inst_model = tmp_model.query.filter(
                    tmp_model.id == ao_id).first()
                if inst_model:
                    tem_list = list(
                        set(self.review_details_columns) -
                        set(tmp_excluded_columns))
                    for key, value in inst_model.__dict__.iteritems():
                        if key not in tem_list:
                            continue
                        if key in ['remark', 'date', 'statusName', 'number']:
                            continue
                        tmp = getattr(self._create_form_class, key)
                        tmp.kwargs['default'] = value
                    return (table_datas, whichcolumn)
        else:
            self.normal_view()
            for val in exclude_list:
                if val in self.column_details_list:
                    self.column_details_list.remove(val)
                    self.review_details_columns.remove(val)

    def handle_exclude_list(self, tmp_excluded_columns):
        converter = self.model_form_converter(self.session, self)
        self._create_form_class =\
            form.get_form(self.model, converter,
                          base_class=self.form_base_class,
                          only=self.form_columns,
                          exclude=tmp_excluded_columns,
                          field_args=self.form_args,
                          ignore_hidden=self.ignore_hidden,
                          extra_fields=self.form_extra_fields)

    def normal_view(self):
        self.column_details_list = deepcopy(self.tmp_columns)

    def get_export_pdf_column(self, inst_id=None):
        inst = self.model.query.filter(self.model.id == inst_id).first()
        if inst.outStoreCategory != LoanOutSTORE:
            return self._export_columns
        columns = deepcopy(self._export_columns)
        columns.extend([('borrowCompany', '借用单位'), ('contactPerson', '联系人'),
                        ('telephone', '电话')])
        return columns

    @expose('/pdf/')
    def pdf_view(self):
        inst_id = request.args.get('id', '')
        inst = self.model.query.filter(self.model.id == inst_id).first()
        extra = {'name': inst.outStoreCategory}
        return render_pdf(
            HTML(string=self._view_handler(self.pdf_template, inst_id, True, **
                                           extra)))
Beispiel #7
0
class _RepairReturnOrderView(WithInlineTableView):
    """送修归还视图"""
    list_template = 'storage/list.html'
    column_list = [
        'number', 'returnDate', 'repairCompany',
        'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'returnDate': '归还日期',
        'repairCompany': '维修厂商',
        'contactPerson': '联系人',
        'remark': '备注',
        'statusName': '状态',
        'repairApplication': '送修申请单据编号',
    }
    column_searchable_list = ('repairCompany', 'number', 'statusName')
    # 查看页面显示的详情
    column_details_list = [
        'number', 'repairApplication', 'returnDate', 'repairCompany',
        'contactPerson', 'remark',
    ]

    form_excluded_columns = ['statusName', 'repairApplicationNum',
                             'repairReturnMaterials', 'storage']
    support_flow = partial(LoanInReturnFlow, 'repair return application flow')
    form_overrides = {
        'returnDate': partial(DateField, widget=DateWidget()),
        'repairCompany': partial(RefreshRepairSupplierSelectField),
    }
    form_widget_args = {
        'number': {
            'readonly': True
        },
    }
    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/repair_return_validation.js',
    ]

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.repairApplication.validators = [DataRequired()]
            form.returnDate.validators = [DataRequired()]
        return super(_RepairReturnOrderView, self).validate_form(form)

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('quantity', AM_QUANTITY),
            ('manufacturer', AM_MANUFACTURER),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME),
            ('flightTimes', AM_FLIGHTTIMES),
        ])
        self.relationField = 'repairReturnMaterials'
        self.f_key = 'application_id'
        self.relationModel = RepairReturnMaterial

        super(_RepairReturnOrderView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = ['一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件']
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[3]['need'] = True
        table_columns[3]['readOnly'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[4]['readOnly'] = True
        table_columns[6]['type'] = 'date'
        table_columns[6]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[7]['validator'] = 'hhmm'
        table_columns[8]['validator'] = 'hhmm'
        table_columns[9]['type'] = 'numeric'
        table_columns[9]['format'] = '0'

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/repair_return_order.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        ao_id = request.args.get('id', '')
        table_datas = json.dumps([])
        if ao_id:
            inst_model = RepairApplication.query.filter(
                RepairApplication.id == ao_id).first()
            table_datas = [[inst.category, inst.partNumber, inst.serialNum, inst.name,
                            inst.quantity, inst.manufacturer, None, inst.flyTime,
                            inst.engineTime, inst.flightTimes,
                            ] for inst in inst_model.repairAppl]
            table_datas = json.dumps(table_datas)
        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_RepairReturnOrderView, self).create_view()

    def create_form(self, obj=None):
        ao_id = request.args.get('id', '')
        if ao_id:
            inst = RepairApplication.query.filter(
                RepairApplication.id == ao_id).first()
            return self.create_form_with_default(inst, 'repairApplication')
        return super(_RepairReturnOrderView, self).create_form(obj)

    def get_audit_form_class(self, model, verb):
        if verb == 'review':
            return self._action_view_cfg['review_only'].form
        return None
Beispiel #8
0
class _LendApplicationView(ApproveFlowUploadFileView):
    """借入申请"""

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/lend_application_validation.js',
    ]

    column_list = [
        'number',
        'date',
        'lendCategory',
        'companyName',
        'applicationDate',
        'statusName',
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '日期',
        'companyName': '单位名称',
        'companyAddr': '单位地址',
        'contactPerson': '联系人',
        'telephone': '电话',
        'fax': '传真',
        'mailbox': '邮箱',
        'accessory': '附件',
        'partNumber': '件号',
        'serialNum': '序号',
        'name': '名称',
        'lendCategory': '借入类型',
        'category': '类别',
        'flightTime': '飞行小时',
        'engineTime': '发动机小时',
        'quantity': '数量',
        'applicationReason': '申请原因',
        'applicationDate': '申请日期',
        'remark': '备注',
        'statusName': '状态',
        'contractFile': '合同文件',
    }
    # 查看页面显示的详情
    column_details_list = [
        'number', 'lendCategory', 'date', 'applicationDate', 'companyName',
        'companyAddr', 'contactPerson', 'telephone', 'fax', 'mailbox',
        'remark', 'contractFile', 'accessory', 'applicationReason'
    ]

    form_excluded_columns = [
        'statusName', 'storage', 'contractFile', 'borrowingInReturn',
        'lendApplicationMaterials'
    ]

    inline_column = 'lendApplication_id'
    inline_model = LendApplicationMaterial

    column_export_list = [
        'category', 'partNumber', 'name', 'quantity', 'companyName',
        'contactPerson', 'telephone'
    ]

    support_flow = partial(BorrowRequestFlow, 'borrow request storage flow')

    one_line_columns = ['applicationReason', "accessory"]

    column_searchable_list = ('number', 'date', 'lendCategory', 'companyName',
                              'applicationDate', 'statusName')
    airmaterial_category = [
        ('一般航材', '一般航材'),
        ('工装设备', '工装设备'),
        ('消耗品', '消耗品'),
        ('化工品', '化工品'),
    ]

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'applicationDate': partial(DateField, widget=DateWidget()),
        'category': partial(SelectField, choices=airmaterial_category),
        'accessory': partial(AirmaterialFileuploadField),
    }

    column_formatters = {
        'accessory': accessory_formatter('accessory'),
        'contractFile': accessory_formatter('contractFile'),
    }

    form_widget_args = {
        'number': {
            'readonly': True
        },
    }

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([('category', AM_CATEGORY),
                                          ('partNumber', AM_PARTNUMBER),
                                          ('name', AM_NAME),
                                          ('quantity', AM_QUANTITY)])

        self.relationField = 'lendApplicationMaterials'
        self.f_key = 'lendApplication_id'
        self.relationModel = LendApplicationMaterial
        super(_LendApplicationView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[2]['readOnly'] = True
        table_columns[2]['need'] = True
        table_columns[3]['type'] = 'numeric'
        table_columns[3]['format'] = '0'
        table_columns[3]['need'] = True

        self._template_args.update({
            'inline_table':
            True,
            'can_add_line':
            True,
            'can_del_line':
            True,
            'extra_table_js':
            'js/lend_application_table.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):

        rowid = request.args.getlist('rowid')
        aoid = request.args.getlist('aoid')
        if not rowid and not aoid:
            table_datas = json.dumps([])
        else:
            if rowid:
                request_class = AirmaterialCategory
                ids = rowid
            if aoid:
                request_class = AirMaterialStorageList
                ids = aoid

            cats = request_class.query.filter(request_class.id.in_(ids)).all()
            table_datas = [[cat.category, cat.partNumber, cat.name, 1]
                           for cat in cats]
            table_datas = json.dumps(table_datas)

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_LendApplicationView, self).create_view()

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.applicationDate.validators = [DataRequired()]
        return super(_LendApplicationView, self).validate_form(form)

    @expose('/get_pn_form_lend_app/', methods=['GET'])
    def get_pn_form_lend_app(self):
        try:
            num = request.args.get('num')
            if num:
                items = LendApplication.query.filter(
                    LendApplication.number == num).first()
                data = [
                    item.partNumber for item in items.lendApplicationMaterials
                ]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')

        return jsonify(code=404, message='Not Found')

    def get_audit_form_class(self, model, verb):
        if model.lendCategory == '一般航材' and verb == Review:
            return ApproveForm
        return None
Beispiel #9
0
class _AssembleApplicationView(UpdateStorageListFreezedQuantity):

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/assemble_app_validation.js',
    ]
    """装机申请单"""
    column_list = ['number', 'date', 'applyPerson', 'applyDate', 'statusName']
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '单据日期',
        'applyDate': '申请日期',
        'applyPerson': '申请人',
        'remark': '备注',
        'statusName': '状态',
        'putOutStore': '出库',
        'assemble': '装机'
    }

    column_searchable_list = ('applyPerson', 'number', 'statusName')
    # 查看页面显示的详情
    column_details_list = ['number', 'date', 'applyPerson', 'applyDate']

    form_excluded_columns = [
        'statusName', 'assembleApplicationList', 'putOutStore', 'assemble'
    ]
    support_flow = partial(AssembleApplicationFlow, 'purchase request flow')

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'applyDate': partial(DateField, widget=DateWidget())
    }

    form_widget_args = {
        'number': {
            'readonly': True
        },
    }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.applyDate.validators = [DataRequired()]
        return super(_AssembleApplicationView, self).validate_form(form)

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('quantity', AM_QUANTITY),
            ('manufacturer', AM_MANUFACTURER),
            ('unit', AM_UNIT),
            ('planeNum', AM_PLANENUM),
            ('effectiveDate', AM_EFFECTIVEDATE),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('nextCheckDate', AM_NEXTCHECKDATE),
            ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME),
            ('flightTimes', AM_FLIGHTTIMES),
        ])
        self.relationField = 'assembleApplicationList'
        self.f_key = 'assembleapplication_id'
        self.relationModel = AssembleApplicationList

        super(_AssembleApplicationView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[2]['editor'] = 'select'
        table_columns[3]['selectOptions'] = []
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[4]['need'] = True
        table_columns[5]['editor'] = 'select'
        table_columns[5]['selectOptions'] = self.get_manafacturers()
        table_columns[7]['editor'] = 'select'
        table_columns[7]['selectOptions'] = self.get_aircraft()
        table_columns[7]['need'] = True
        table_columns[8]['editor'] = 'select'
        table_columns[8]['selectOptions'] = []
        table_columns[8]['checkNeed'] = True
        table_columns[9]['type'] = 'date'
        table_columns[9]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[10]['editor'] = 'select'
        table_columns[10]['selectOptions'] = []
        table_columns[10]['checkNeed'] = True
        table_columns[11]['validator'] = 'hhmm'
        table_columns[12]['validator'] = 'hhmm'
        table_columns[13]['type'] = 'numeric'
        table_columns[13]['format'] = '0'

        self._template_args.update({
            'inline_table':
            True,
            'can_add_line':
            True,
            'can_del_line':
            True,
            'extra_table_js':
            'js/assemble_application.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        rowid = request.args.getlist('rowid')
        if rowid:
            materials = AirMaterialStorageList.query.filter(
                AirMaterialStorageList.id.in_(rowid)).all()
            table_datas = []
            table_datas = [[
                material.category,
                material.partNumber,
                material.serialNum,
                material.name,
                material.quantity - material.freezingQuantity,
                material.manufacturer,
                material.unit,
                None,
                material.effectiveDate,
                material.lastCheckDate,
                material.nextCheckDate,
                material.flyTime,
                material.engineTime,
                material.flightTimes,
            ] for material in materials]
            table_datas = json.dumps(table_datas)
        else:
            table_datas = json.dumps([])

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_AssembleApplicationView, self).create_view()

    @expose('/get_pn_from_asap_ca/', methods=['GET'])
    def get_pn_from_asap_ca(self):
        try:
            ca = request.args.get('ca')
            num = request.args.get('num')
            if ca and num:
                inst = AssembleApplication.query.filter_by(number=num).first()
                materials = inst.assembleApplicationList
                data = [m.partNumber for m in materials if m.category == ca]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')

        return jsonify(code=404, message='Not Found')

    @expose('/get_number_from_asap_pn/', methods=['GET'])
    def get_number_from_asap_pn(self):
        try:
            pn = request.args.get('pn')
            num = request.args.get('num')
            if pn and num:
                inst = AssembleApplication.query.filter_by(number=num).first()
                materials = inst.assembleApplicationList
                data = [m.quantity for m in materials if m.partNumber == pn]
                data = json.dumps(data[0])
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')

        return jsonify(code=404, message='Not Found')
class _PurchaseApplicationView(ApproveFlowUploadFileView):
    # 采购入库首页列CustomView显示的内容

    create_template = 'purchase_application/create.html'
    approve_edit_template = 'purchase_application/approve_edit.html'

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/purchase_application.js',
    ]

    column_list = [
        'number', 'date', 'supplier', 'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '日期',
        'applicationDate': '申请日期',
        'partNumber': '件号',
        'name': '名称',
        'quantity': '数量',
        'unitPrice': '单价',
        'manufacturer': '生产厂商',
        'supplier': '供应商',
        'contactPerson': '联系人',
        'telephone': '电话',
        'fax': '传真',
        'mailbox': '邮箱',
        'receiver': '收货人',
        'accessory': '附件',
        'applicationInstruction': '申请说明',
        'budget': '预算',
        'remark': '备注',
        'statusName': '状态',
        'contractFile': '合同文件',
        'meetingFile': '会议纪要',
        'purchase': '航材'
    }
    # 查看页面显示的详情
    column_details_list = [
        'number', 'date', 'applicationDate', 'supplier', 'contactPerson',
        'telephone', 'fax', 'mailbox', 'receiver', 'remark', 'contractFile',
        'meetingFile', 'applicationInstruction', 'accessory'
    ]

    form_excluded_columns = ['statusName', 'contractFile', 'meetingFile',
                             'purchase', 'storage']
    support_flow = partial(PurchaseRequestFlow, 'purchase request flow')

    column_searchable_list = ('number', 'date', 'supplier', 'statusName')

    one_line_columns = ['applicationInstruction', 'accessory']

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'applicationDate': partial(DateField, widget=DateWidget()),
        'accessory': partial(AirmaterialFileuploadField),
        'contractFile': partial(AirmaterialFileuploadField),
        'meetingFile': partial(AirmaterialFileuploadField),
        'supplier': partial(RefreshSupplierSelectField),
    }
    column_formatters = {
        'accessory': accessory_formatter('accessory'),
        'contractFile': accessory_formatter('contractFile'),
        'meetingFile': accessory_formatter('meetingFile'),
    }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.applicationDate.validators = [DataRequired()]
        return super(_PurchaseApplicationView, self).validate_form(form)

    form_widget_args = {
        'number': {
            'readonly': True
        },
        'contactPerson': {
            'readonly': True
        },
        'telephone': {
            'readonly': True
        },
        'fax': {
            'readonly': True
        },
        'mailbox': {
            'readonly': True
        },

    }

    def __init__(self, *args, **kwargs):
        self.table_columns = OrderedDict([('category', AM_CATEGORY),
                                          ('partNumber', AM_PARTNUMBER),
                                          ('name', AM_NAME),
                                          ('manufacturer', AM_MANUFACTURER),
                                          ('unitPrice', AM_UNITPRICE),
                                          ('quantity', AM_QUANTITY),
                                          ('budget', AM_BUDGET)])
        self.relationField = 'purchase'
        self.f_key = 'application_id'
        self.relationModel = PurchaseMaterial
        super(_PurchaseApplicationView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = ['一般航材', '工装设备', '消耗品',
                                             '化工品', '时控件', '时寿件']
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[2]['readOnly'] = True
        table_columns[2]['need'] = True
        table_columns[3]['editor'] = 'select'
        table_columns[3]['selectOptions'] = self.get_manafacturers()
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0.00'
        table_columns[4]['validator'] = 'nonnegative'
        table_columns[5]['type'] = 'numeric'
        table_columns[5]['format'] = '0'
        table_columns[5]['need'] = True
        table_columns[6]['type'] = 'numeric'
        table_columns[6]['format'] = '0.00'
        table_columns[6]['readOnly'] = True

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/purchase_application_table.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        rowid = request.args.getlist('rowid')
        aoid = request.args.getlist('aoid')
        if not rowid and not aoid:
            table_datas = json.dumps([])
        else:
            if rowid:
                request_class = AirmaterialCategory
                ids = rowid
            if aoid:
                request_class = AirMaterialStorageList
                ids = aoid
            cats = request_class.query.filter(
                request_class.id.in_(ids)).all()
            table_datas = [[
                    cat.category, cat.partNumber,
                    cat.name, None, None, 1, None
                ] for cat in cats]

            table_datas = json.dumps(table_datas)

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_PurchaseApplicationView, self).create_view()
Beispiel #11
0
class _BorrowingInReturnView(UpdateStorageListFreezedQuantity):
    """借入归还视图"""
    list_template = 'storage/list.html'

    column_list = [
        'number', 'lendCategory', 'companyName', 'borrow', 'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'returnDate': '归还日期',
        'lendCategory': '借入类型',
        'companyName': '单位名称',
        'contactPerson': '联系人',
        'remark': '备注',
        'statusName': '状态',
        'companyAddr': '单位地址',
        'telephone': '联系电话',
        'fax': '传真',
        'mailbox': '邮箱',
        'borrow': '借入申请单号',
        'putOutStore': '出库',
        'name': '名称',
        'category': '类别',
        'quantity': '数量',
        'partNumber': '件号',
    }
    # 查看页面显示的详情
    column_details_list = [
        'number', 'borrow', 'returnDate', 'lendCategory', 'telephone', 'fax',
        'companyAddr', 'mailbox', 'companyName', 'contactPerson', 'remark'
    ]

    form_excluded_columns = [
        'statusName', 'borrowingInReturnMaterials', 'putOutStore'
    ]
    column_searchable_list = ('lendCategory', 'companyName', 'number',
                              'statusName')

    inline_column = 'borrowInReturn_id'
    inline_model = BorrowingInReturnMaterial

    column_export_list = [
        'category', 'partNumber', 'name', 'quantity', 'companyName',
        'contactPerson', 'telephone'
    ]

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/borrow_validation.js',
    ]

    support_flow = partial(BorrowInReturnFlow, 'borrow request storage flow')

    form_overrides = {
        'returnDate': partial(DateField, widget=DateWidget()),
    }

    @property
    def form_widget_args(self):
        return {
            'number': {
                'readonly': True,
            },
            'lendCategory': {
                'readonly': True,
            },
        }

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('quantity', AM_QUANTITY),
            ('effectiveDate', AM_EFFECTIVEDATE),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('nextCheckDate', AM_NEXTCHECKDATE),
            ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME),
            ('flightTimes', AM_FLIGHTTIMES),
        ])

        self.relationField = 'borrowingInReturnMaterials'
        self.f_key = 'borrowInReturn_id'
        self.relationModel = BorrowingInReturnMaterial

        super(_BorrowingInReturnView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False

        table_columns[0]['readOnly'] = True
        table_columns[0]['need'] = True
        table_columns[1]['readOnly'] = True
        table_columns[1]['need'] = True
        table_columns[2]['readOnly'] = True
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['need'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[4]['format'] = '0'
        table_columns[5]['editor'] = 'select'
        table_columns[5]['selectOptions'] = []
        table_columns[5]['checkNeed'] = True
        table_columns[6]['type'] = 'date'
        table_columns[6]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[7]['editor'] = 'select'
        table_columns[7]['selectOptions'] = []
        table_columns[7]['checkNeed'] = True
        table_columns[8]['validator'] = 'hhmm'
        table_columns[9]['validator'] = 'hhmm'
        table_columns[10]['type'] = 'numeric'
        table_columns[10]['format'] = '0'

        self._template_args.update({
            'inline_table':
            True,
            'can_add_line':
            False,
            'can_del_line':
            True,
            'extra_table_js':
            'js/borrowing_in_return_table.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        rowid = request.args.getlist('rowid')
        if rowid:
            cats = AirMaterialStorageList.query.filter(
                AirMaterialStorageList.id.in_(rowid)).all()
            table_datas = [[
                cat.category,
                cat.partNumber,
                cat.serialNum,
                cat.name,
                cat.quantity - cat.freezingQuantity,
                cat.effectiveDate,
                cat.lastCheckDate,
                cat.nextCheckDate,
                cat.flyTime,
                cat.engineTime,
                cat.flightTimes,
            ] for cat in cats]

            table_datas = json.dumps(table_datas)
        else:
            table_datas = json.dumps([])

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_BorrowingInReturnView, self).create_view()

    def create_form(self, obj=None):
        ao_id = request.args.get('id', '')

        if ao_id:
            inst = LendApplication.query.filter(
                LendApplication.id == ao_id).first()
            return self.create_form_with_default(inst, 'borrow')
        self._create_form_class.borrow.kwargs[
            'query_factory'] = lenappllication_choices
        return super(_BorrowingInReturnView, self).create_form(obj)

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.borrow.validators = [DataRequired()]
            form.returnDate.validators = [DataRequired()]
            form.lendCategory.validators = [DataRequired()]
        return super(_BorrowingInReturnView, self).validate_form(form)

    # 从数据库里以单号查询借入申请信息以json返回
    @expose('/get_borrow_info/', methods=['GET'])
    def get_borrow_info(self):
        try:
            borrow = request.args.get('borrow')
            if borrow:
                item = LendApplication.query.filter(
                    LendApplication.number == borrow).first()
                data = [
                    item.lendCategory, item.companyName, item.contactPerson,
                    item.companyAddr, item.telephone, item.fax, item.mailbox
                ]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')

        return jsonify(code=404, message='Not Found')

    def get_audit_form_class(self, model, verb):
        if verb == 'review':
            return self._action_view_cfg['review_only'].form
        return None
Beispiel #12
0
class _CheckWarningView(CustomView):
    column_list = [
        'name', 'category', 'partNumber', 'serialNum', 'shelf', 'storehouse',
        'nextCheckDate', 'operations'
    ]
    # create_template = 'create.html'
    list_template = 'storage/yujing_list.html'
    can_create = False
    can_edit = True
    edit_template = 'storage/yujing_edit.html'

    # 对应内容的中文翻译
    column_labels = {
        'name': '名称',
        'category': '类型',
        'partNumber': '件号',
        'serialNum': '序号',
        'shelf': '架位',
        'nextCheckDate': '下次检查日期',
        'operations': '操作',
        'checkRecord': '检查说明',
        'storehouse': '仓库',
        'lastCheckDate': '记录检查时间'
    }

    support_flow = None

    column_searchable_list = ('name', 'category', 'partNumber')

    index_lists = []

    form_excluded_columns = [
        'name', 'category', 'partNumber', 'serialNum', 'shelf', 'quantity',
        'unit', 'flyTime', 'engineTime', 'flightTimes', 'applicableModel',
        'effectiveDate', 'certificateNum', 'airworthinessTagNum', 'minStock',
        'supplier', 'manufacturer', 'statusName', 'freezingQuantity'
    ]

    form_overrides = {
        'nextCheckDate': partial(DateField, widget=DateWidget()),
        'lastCheckDate': partial(DateField, widget=DateWidget())
    }

    column_formatters = {
        'operations':
        partial(operation_formatter_without_flow, operations=[CheckComplete]),
    }

    def is_accessible(self):
        return ActionNeedPermission('checkwarning', View).can()

    def get_level(self, data, yujing):

        if not data or not yujing:
            return ''
        tmp = datetime.strptime(data, "%Y-%m-%d")
        count = (tmp.date() - datetime.now().date()).days
        level = ''

        if yujing['lv2'] < count <= yujing['lv1']:
            level = 'yellow'
        elif yujing['lv3'] < count <= yujing['lv2']:
            level = 'orange'
        elif count <= yujing['lv3']:
            level = 'red'

        return level

    def get_query(self):
        datas = self.model.query.filter(self.model.nextCheckDate != None,
                                        self.model.nextCheckDate != '')

        return datas

    def get_yujing_level(self):

        cache = current_app.redis_cache._user_cache
        yujing = cache.get('checkwarning')
        if not yujing:
            return ''
        return json.loads(yujing)

    def get_list(self,
                 page,
                 sort_column,
                 sort_desc,
                 search,
                 filters,
                 execute=True,
                 page_size=None):
        self._list_columns = deepcopy(self._tmp_list_columns)
        self.list_template = 'storage/yujing_list.html'
        sort_column = 'nextCheckDate'

        count, datas = super(_CheckWarningView, self).get_list(page,
                                                               sort_column,
                                                               sort_desc,
                                                               search,
                                                               filters,
                                                               execute=True,
                                                               page_size=None)
        count = self.get_query().count()

        self.index_lists = datas
        yujing = self.get_yujing_level()

        levels = [
            self.get_level(x.nextCheckDate, yujing) for x in self.index_lists
        ]
        self._template_args.update({
            'levels': levels,
        })
        category = request.args.get('category', '')
        if category == 'history':
            count, datas = self.history_set()
        return count, datas

    def history_set(self):
        self.list_template = 'storage/check_record.html'
        self._list_columns.remove(('operations', '操作'))
        self._list_columns.append(('lastCheckDate', '上次检查日期'))
        self._list_columns.append(('checkRecord', '检查说明'))
        count, datas = self.get_history()
        levels = []
        self._template_args.update({
            'levels': levels,
        })
        return count, datas

    @expose('/edit/', methods=['GET', 'POST'])
    def edit_view(self):
        return super(_CheckWarningView, self).edit_view()

    def edit_form(self, obj=None):
        obj.lastCheckDate = date_generator()

        return super(_CheckWarningView, self).edit_form(obj)

    def get_history(self):
        version = version_class(self.model)
        query = version.query.filter(version.nextCheckDate != None,
                                     version.nextCheckDate != '').order_by(
                                         version.nextCheckDate).all()
        datas = []
        for item in query:
            if 'nextCheckDate' in item.changeset.keys(
            ) or 'checkRecord' in item.changeset.keys():
                datas.append(item)
        page = request.args.get('page', 0, type=int)
        return len(datas), datas[page * 20:page * 20 + 20]

    def __init__(self, *args, **kwargs):

        self.extra_js = getattr(self, 'extra_js', [])
        self.extra_js.extend([
            # select2
            '/static/js/bootstrap-select.min.js',
            '/static/js/jquery.multi-select.js',
            '/static/js/components-dropdowns.js',
        ])

        self.extra_css = getattr(self, 'extra_css', [])
        self.extra_css.extend([
            '/static/css/mxp.css',
        ])

        super(_CheckWarningView, self).__init__(*args, **kwargs)
        self._tmp_list_columns = deepcopy(self._list_columns)
Beispiel #13
0
class _AssembleView(WithInlineTableView):
    """装机单"""
    list_template = 'storage/list.html'

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/assemble_validate.js',
    ]

    column_list = [
        'number', 'date', 'assemblePerson', 'assembleDate', 'statusName'
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '单据日期',
        'assembleDate': '装机日期',
        'assemblePerson': '装机人',
        'remark': '备注',
        'statusName': '状态',
        'assembleApplication': '装机申请'
    }

    column_searchable_list = ('assemblePerson', 'number', 'statusName')
    # 查看页面显示的详情
    column_details_list = [
        'number', 'date', 'assemblePerson', 'assembleDate',
        'assembleApplication'
    ]

    form_excluded_columns = ['statusName', 'assembleApplicationList']
    support_flow = partial(AssembleFlow, 'purchase request flow')

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'assembleDate': partial(DateField, widget=DateWidget())
    }
    column_formatters = {}

    form_widget_args = {
        'number': {
            'readonly': True
        },
    }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.assembleDate.validators = [DataRequired()]
        return super(_AssembleView, self).validate_form(form)

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('manufacturer', AM_MANUFACTURER),
            ('quantity', AM_QUANTITY),
            ('unit', AM_UNIT),
            ('planeNum', AM_PLANENUM),
            ('effectiveDate', AM_EFFECTIVEDATE),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('nextCheckDate', AM_NEXTCHECKDATE),
            ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME),
            ('flightTimes', AM_FLIGHTTIMES),
        ])
        self.relationField = 'assembleApplicationList'
        self.f_key = 'assemble_id'
        self.relationModel = AssembleApplicationList

        super(_AssembleView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)

        table_columns[0]['readOnly'] = True
        table_columns[0]['need'] = True
        table_columns[1]['readOnly'] = True
        table_columns[1]['need'] = True
        table_columns[2]['readOnly'] = True
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['readOnly'] = True
        table_columns[5]['type'] = 'numeric'
        table_columns[5]['format'] = '0'
        table_columns[5]['need'] = True
        table_columns[6]['readOnly'] = True
        table_columns[7]['need'] = True
        table_columns[7]['editor'] = 'select'
        table_columns[7]['selectOptions'] = self.get_aircraft()
        table_columns[8]['readOnly'] = True
        table_columns[8]['checkNeed'] = True
        table_columns[9]['type'] = 'date'
        table_columns[9]['need'] = True
        table_columns[9]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[10]['readOnly'] = True
        table_columns[10]['checkNeed'] = True
        table_columns[11]['validator'] = 'hhmm'
        table_columns[12]['validator'] = 'hhmm'
        table_columns[13]['type'] = 'numeric'
        table_columns[13]['format'] = '0'

        self._template_args.update({
            'inline_table': True,
            'can_add_line': False,
            'can_del_line': True,
            'extra_table_js': 'js/assemble.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):
        ao_id = request.args.get('id', '')
        table_datas = json.dumps([])
        if ao_id:
            inst_model = AssembleApplication.query.filter(
                AssembleApplication.id == ao_id).first()
            table_datas = [[
                inst.category,
                inst.partNumber,
                inst.serialNum,
                inst.name,
                inst.manufacturer,
                inst.quantity,
                inst.unit,
                inst.planeNum,
                inst.effectiveDate,
                inst.lastCheckDate,
                inst.nextCheckDate,
                inst.flyTime,
                inst.engineTime,
                inst.flightTimes,
            ] for inst in inst_model.assembleApplicationList]
            table_datas = json.dumps(table_datas)
        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_AssembleView, self).create_view()

    def create_form(self, obj=None):
        ao_id = request.args.get('id', '')
        if ao_id:
            inst = AssembleApplication.query.filter(
                AssembleApplication.id == ao_id).first()
            return self.create_form_with_default(inst, 'assembleApplication')
        return super(_AssembleView, self).create_form(obj)
Beispiel #14
0
class _FaultReportsView(CustomView):

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/select_planeType.js',
        '/static/js/fault_report.js',
        '/static/js/upload_file.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/faultreports_validation.js',
    ]

    column_list = [
        'recordNum', 'planeType', 'jihao', 'faultDate', 'faultAdress',
        'reportsMaker', 'aircraftNumber', 'statusName'
    ]

    column_labels = {
        'recordNum': '编号',
        'planeType': '机型',
        'jihao': '飞机注册号',
        'faultDate': '故障发生日期',
        'faultAdress': '故障地点',
        'reportsMaker': '故障报告人',
        'aircraftNumber': '飞行编号',
        'description': '故障描述',
        'relateFileUrl': '上传附件',
        'remark': '备注',
        'statusName': '状态',
    }

    column_details_list = [
        'recordNum', 'planeType', 'jihao', 'faultDate', 'faultAdress',
        'reportsMaker', 'aircraftNumber', 'remark', 'description',
        'relateFileUrl'
    ]

    support_flow = partial(FaultReportsFlow,
                           'fault report flow',
                           next_model=TroubleShooting)

    form_overrides = {
        'faultDate':
        partial(DateField, widget=DateWidget()),
        'relateFileUrl':
        partial(AirworthinessFileuploadField),
        'planeType':
        partial(SelectField,
                choices=[(model.value, model.label)
                         for model in get_allowed_models()]),
        'jihao':
        partial(ComponentsDropdownsField),
    }
    column_searchable_list = (
        'recordNum',
        'faultAdress',
        'reportsMaker',
        'aircraftNumber',
        'jihao',
    )
    form_excluded_columns = ['troubleShootings']

    one_line_columns = ['description', 'relateFileUrl']

    column_formatters = {
        'relateFileUrl': accessory_formatter('relateFileUrl'),
    }

    form_widget_args = {
        'recordNum': {
            'readonly': True
        },
    }

    @expose('/approve-edit-view/', methods=['GET', 'POST'])
    def approve_edit_view(self):

        return super(_FaultReportsView, self).approve_edit_view()
Beispiel #15
0
class _MaintenanceRecordView(CustomView):
    """维护保养记录"""
    create_template = 'unvalidate/create.html'
    approve_edit_template = 'unvalidate/approve_edit.html'

    column_list = [
        'recordNum', 'planeType', 'jihao', 'checkType', 'checkPlace',
        'involvePerson', 'checkDate', 'checkContent', 'statusName'
    ]

    column_labels = {
        'recordNum': '编号',
        'planeType': '机型',
        'jihao': '飞机注册号',
        'checkType': '检查类型',
        'checkPlace': '检查地点',
        'effectPart': '受影响部件',
        'effectEngine': '受影响的发动机',
        'stopTime': '工时停场时',
        'involvePerson': '涉及人员',
        'checkDate': '检查日期',
        'checkContent': '检查内容',
        'statusName': '状态',
        'faultReports': '关联的工程指令'
    }

    column_details_list = [
        'recordNum', 'faultReports', 'planeType', 'jihao', 'checkType',
        'checkPlace', 'effectPart', 'effectEngine', 'stopTime',
        'involvePerson', 'checkDate', 'checkContent'
    ]

    support_flow = partial(BasicFlow, 'Finish flow', support_create=True)
    column_searchable_list = (
        'recordNum',
        'checkType',
        'involvePerson',
        'checkPlace',
        'jihao',
    )

    one_line_columns = ['checkContent']

    form_overrides = {
        'checkDate':
        partial(DateField, widget=DateWidget()),
        'involvePerson':
        partial(choiceRealNameSelectField),
        'planeType':
        partial(SelectField,
                choices=[(model.value, model.label)
                         for model in get_allowed_models()]),
        'jihao':
        partial(ComponentsDropdownsField),
    }

    @property
    def form_widget_args(self):
        return {
            'recordNum': {
                'readonly': True
            },
        }

    def __init__(self, *args, **kwargs):

        self.extra_js = getattr(self, 'extra_js', [])
        self.extra_js.extend([
            '/static/js/bootstrap-datetimepicker.min.js',
            '/static/js/datetimepicker.zh-cn.js',
            '/static/js/select_planeType.js'
        ])

        self.extra_css = getattr(self, 'extra_css', [])
        self.extra_css.extend([
            '/static/css/datepicker.css',
            '/static/css/bootstrap-datetimepicker.min.css',
        ])
        super(_MaintenanceRecordView, self).__init__(*args, **kwargs)

    def create_form(self, obj=None):

        self._create_form_class.faultReports.kwargs[
            'query_factory'] = engineer_choices
        eo_id = request.args.get('id', '')
        if eo_id:
            inst = EngineeringOrder.query.filter(
                EngineeringOrder.id == eo_id).first()
            return self.create_form_with_default(inst, 'faultReports')

        return super(_MaintenanceRecordView, self).create_form(obj)

    def on_model_change(self, form, model, is_created):
        super(_MaintenanceRecordView,
              self).on_model_change(form, model, is_created)
        eo_id = request.args.get('id', '')
        if is_created and eo_id:
            model.faultReports_id = eo_id

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.recordNum.validators = [DataRequired()]
            form.checkDate.validators = [DataRequired()]
            form.checkContent.validators = [DataRequired()]

        return super(_MaintenanceRecordView, self).validate_form(form)
Beispiel #16
0
class _DisassembleOrderView(WithInlineTableView):
    # 拆机单首页列表视图应显示的内容

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/upload_file.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/disassemble_validate.js',
    ]

    column_list = [
        'number',
        'disassemblePerson',
        'disassembleDate',
        'statusName',
    ]
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'date': '单据日期',
        'disassemblePerson': '拆机人',
        'disassembleDate': '拆机日期',
        'remark': '备注',
        'statusName': '状态',
    }
    # 查看页面显示的详情
    column_details_list = [
        'number',
        'date',
        'disassemblePerson',
        'disassembleDate',
        'remark',
    ]

    form_excluded_columns = ['statusName', 'disassembleMaterials', 'storage']

    support_flow = partial(DisassembleOrderFlow, 'disassemble flow')

    column_searchable_list = ('number', 'date', 'disassemblePerson',
                              'disassembleDate', 'statusName')

    form_overrides = {
        'date': partial(DateField, widget=DateWidget()),
        'disassembleDate': partial(DateField, widget=DateWidget()),
    }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.date.validators = [DataRequired()]
            form.disassembleDate.validators = [DataRequired()]
        return super(_DisassembleOrderView, self).validate_form(form)

    def __init__(self, *args, **kwargs):
        self.table_columns = OrderedDict([
            ('planeNum', AM_PLANENUM),
            ('category', AM_CATEGORY),
            ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM),
            ('name', AM_NAME),
            ('quantity', AM_QUANTITY),
            ('unit', AM_UNIT),
            ('manufacturer', AM_MANUFACTURER),
            ('effectiveDate', AM_EFFECTIVEDATE),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('nextCheckDate', AM_NEXTCHECKDATE),
            ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME),
            ('flightTimes', AM_FLIGHTTIMES),
        ])
        self.relationField = 'disassembleMaterials'
        self.f_key = 'disassembleOrder_id'
        self.relationModel = DisassembleMaterial

        super(_DisassembleOrderView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False
        # 设置表格格式
        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = []
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[1]['need'] = True
        table_columns[2]['type'] = 'autocomplete'
        table_columns[2]['readOnly'] = True
        table_columns[2]['source'] = ['']
        table_columns[2]['strict'] = True
        table_columns[2]['trimDropdown'] = False
        table_columns[2]['allowInvalid'] = False
        table_columns[2]['need'] = True
        table_columns[4]['need'] = True
        table_columns[4]['readOnly'] = True
        table_columns[5]['type'] = 'numeric'
        table_columns[5]['format'] = '0'
        table_columns[5]['need'] = True
        table_columns[6]['readOnly'] = True
        table_columns[7]['editor'] = 'select'
        table_columns[7]['selectOptions'] = self.get_manafacturers()
        table_columns[8]['type'] = 'date'
        table_columns[8]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[8]['checkNeed'] = True
        table_columns[9]['type'] = 'date'
        table_columns[9]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[10]['type'] = 'date'
        table_columns[10]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[10]['checkNeed'] = True
        table_columns[11]['validator'] = 'hhmm'
        table_columns[12]['validator'] = 'hhmm'

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/disassemble_order.js',
        })

        return json.dumps(table_columns)

    @property
    def form_widget_args(self):
        return {
            'number': {
                'readonly': True
            },
        }

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': json.dumps([]),
        })
        return super(_DisassembleOrderView, self).create_view()

    @expose('/approve-edit-view/', methods=['POST', 'GET'])
    def approve_edit_view(self):
        self._template_args.update({
            'table_columns': self.init_table_columns(),
        })
        return super(_DisassembleOrderView, self).approve_edit_view()

    def before_edit_form(self, model):
        self._template_args.update({
            'table_datas':
            self.get_table_data_from_db(model),
        })

    @expose('/details/')
    def details_view(self):

        self._template_args.update({
            'table_columns':
            self.get_readonly_table(),
            'table_datas':
            self.get_table_data_from_db(),
            'extra_table_js':
            'js/inline_table_details.js'
        })

        return super(_DisassembleOrderView, self).details_view()

    @expose('/action-view/', methods=['POST', 'GET'])
    def action_view(self):
        self._template_args.update({
            'table_columns':
            self.get_readonly_table(),
            'table_datas':
            self.get_table_data_from_db(),
        })
        return super(_DisassembleOrderView, self).action_view()

    @expose('/get_plane_infos_from_pn/', methods=['POST', 'GET'])
    def get_plane_infos_from_pn(self):
        try:
            ca = request.args.get('ca')
            pn = request.args.get('pn')
            plane_num = request.args.get('planeNum')
            if ca and pn and plane_num:
                data = get_plane_infos_by_pn(pn, plane_num, ca)
                data = json.dumps(data)
            return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=400, message='Not Found')

    @expose('/get_pn_from_bounded_category/', methods=['GET'])
    def get_pn_from_bounded_category(self):
        try:
            ca = request.args.get('ca')
            if ca:
                data = get_pn_by_category(ca)
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=400, message='Not Found')

    @expose('/get-bounded-aircraft/', methods=['POST', 'GET'])
    def get_bounded_aircraft(self):
        bounded = request.args.get('bounded')
        data = self.get_aircraft(bounded)
        data = json.dumps(data)
        return jsonify(code=200, data=data, message='Ok')
Beispiel #17
0
class _RepairApplicationView(ApproveFlowUploadFileView,
                             UpdateStorageListFreezedQuantity):
    """送修申请视图"""
    column_list = ['number', 'applicationDate', 'repairCompany', 'statusName']
    # 对应内容的中文翻译
    column_labels = {
        'number': '编号',
        'applicationDate': '申请日期',
        'repairCompany': '维修厂商',
        'contactPerson': '联系人',
        'telephone': '联系电话',
        'fax': '传真',
        'mailbox': '邮箱',
        'budget': '预算',
        'accessory': '附件',
        'remark': '备注',
        'statusName': '状态',
        'contractFile': '合同文件',
    }

    column_searchable_list = ('repairCompany', 'number', 'statusName')
    # 查看页面显示的详情
    column_details_list = [
        'number',
        'applicationDate',
        'repairCompany',
        'contactPerson',
        'telephone',
        'fax',
        'mailbox',
        'budget',
        'remark',
        'contractFile',
        'accessory',
    ]

    extra_js = [
        '/static/js/bootbox.min.js',
        '/static/js/custom_action.js',
        '/static/js/bootstrap-switch.min.js',
        '/static/js/switch_form.js',
        '/static/js/bootstrap-datetimepicker.min.js',
        '/static/js/datetimepicker.zh-cn.js',
        '/static/js/bootstrap-select.min.js',
        '/static/js/jquery.multi-select.js',
        '/static/js/components-dropdowns.js',
        '/static/js/select_planeType.js',
        '/static/js/inline_table.js',
        '/static/js/numbro.js',
        '/static/js/languages.js',
        '/static/js/zh-CN.min.js',
        '/static/js/jquery.validate.min.js',
        '/static/js/moment.min.js',
        '/static/js/pikaday.js',
        '/static/js/pikaday-zh.js',
        '/static/js/customview_formvalidation.js',
        '/static/js/repair_validation.js',
        '/static/js/upload_file.js',
    ]

    form_excluded_columns = [
        'statusName', 'repairAppl', 'contractFile', 'repairReturnOrder',
        'putOutStore'
    ]
    support_flow = partial(RepairApplicationFlow, 'repair application flow')

    one_line_columns = ['accessory']

    column_formatters = {
        'contractFile': accessory_formatter('contractFile'),
        'accessory': accessory_formatter('accessory'),
    }
    form_overrides = {
        'accessory': partial(AirmaterialFileuploadField),
        'contractFile': partial(AirmaterialFileuploadField),
        'applicationDate': partial(DateField, widget=DateWidget()),
        'repairCompany': partial(RefreshRepairSupplierSelectField),
    }

    form_widget_args = {
        'number': {
            'readonly': True
        },
        'contactPerson': {
            'readonly': True
        },
        'telephone': {
            'readonly': True
        },
        'fax': {
            'readonly': True
        },
        'mailbox': {
            'readonly': True
        },
    }

    def validate_form(self, form):
        if form.__class__.__name__ != self.get_delete_form().__name__:
            form.number.validators = [DataRequired()]
            form.applicationDate.validators = [DataRequired()]
        return super(_RepairApplicationView, self).validate_form(form)

    def __init__(self, *args, **kwargs):

        self.table_columns = OrderedDict([
            ('category', AM_CATEGORY), ('partNumber', AM_PARTNUMBER),
            ('serialNum', AM_SERIALNUM), ('name', AM_NAME),
            ('quantity', AM_QUANTITY), ('manufacturer', AM_MANUFACTURER),
            ('effectiveDate', AM_EFFECTIVEDATE),
            ('lastCheckDate', AM_LASTCHECKDATE),
            ('nextCheckDate', AM_NEXTCHECKDATE), ('planeNum', AM_DISPLANENUM),
            ('planeType', AM_PLANETYPE), ('assembleDate', AM_ASSEMBLEDATE),
            ('disassembleDate', AM_DISASSEMBLEDATE),
            ('repairedReuseDate', AM_REPAIREDREUSEDATE),
            ('totalUseTime', AM_TOTALUSETIME), ('flyTime', AM_FLYTIME),
            ('engineTime', AM_ENGINETIME), ('flightTimes', AM_FLIGHTTIMES)
        ])
        self.relationField = 'repairAppl'
        self.f_key = 'application_id'
        self.relationModel = RepairMaterial

        super(_RepairApplicationView, self).__init__(*args, **kwargs)

    def init_table_columns(self):
        table_columns = []
        for i in range(len(self.table_columns)):
            column = {}
            column.update({'title': self.table_columns.values()[i]})
            table_columns.append(column)
            table_columns[i]['need'] = False

        table_columns[0]['editor'] = 'select'
        table_columns[0]['selectOptions'] = [
            '一般航材', '工装设备', '消耗品', '化工品', '时控件', '时寿件'
        ]
        table_columns[0]['need'] = True
        table_columns[1]['editor'] = 'select'
        table_columns[1]['selectOptions'] = []
        table_columns[1]['need'] = True
        table_columns[2]['editor'] = 'select'
        table_columns[2]['selectOptions'] = []
        table_columns[3]['readOnly'] = True
        table_columns[3]['need'] = True
        table_columns[4]['need'] = True
        table_columns[4]['type'] = 'numeric'
        table_columns[5]['editor'] = 'select'
        table_columns[5]['selectOptions'] = self.get_manafacturers()
        table_columns[6]['editor'] = 'select'
        table_columns[6]['selectOptions'] = []
        table_columns[6]['checkNeed'] = True
        table_columns[7]['type'] = 'date'
        table_columns[7]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[8]['editor'] = 'select'
        table_columns[8]['selectOptions'] = []
        table_columns[8]['checkNeed'] = True
        table_columns[9]['editor'] = 'select'
        table_columns[9]['selectOptions'] = self.get_aircraft()
        table_columns[10]['editor'] = 'select'
        table_columns[10]['selectOptions'] = [self.plane_type]
        table_columns[11]['type'] = 'date'
        table_columns[11]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[12]['type'] = 'date'
        table_columns[12]['dateFormat'] = 'YYYY-MM-DD'
        table_columns[15]['validator'] = 'hhmm'
        table_columns[16]['validator'] = 'hhmm'
        table_columns[17]['type'] = 'numeric'
        table_columns[17]['format'] = '0'

        self._template_args.update({
            'inline_table': True,
            'can_add_line': True,
            'can_del_line': True,
            'extra_table_js': 'js/repair_application.js'
        })

        return json.dumps(table_columns)

    @expose('/new/', methods=('GET', 'POST'))
    def create_view(self):

        rowid = request.args.getlist('rowid')
        if rowid:
            cats = AirMaterialStorageList.query.filter(
                AirMaterialStorageList.id.in_(rowid)).all()
            table_datas = [[
                cat.category, cat.partNumber, cat.serialNum, cat.name,
                cat.quantity - cat.freezingQuantity, cat.manufacturer,
                cat.effectiveDate, cat.lastCheckDate, cat.nextCheckDate, None,
                self.plane_type, None, None, None, None, cat.flyTime,
                cat.engineTime, cat.flightTimes
            ] for cat in cats]

            table_datas = json.dumps(table_datas)
        else:
            table_datas = json.dumps([])

        self._template_args.update({
            'table_columns': self.init_table_columns(),
            'table_datas': table_datas,
        })
        return super(_RepairApplicationView, self).create_view()

    @expose('/approve-edit-view/', methods=['POST', 'GET'])
    def approve_edit_view(self):
        self._template_args.update({
            'table_columns': self.init_table_columns(),
        })
        return super(_RepairApplicationView, self).approve_edit_view()

    def before_edit_form(self, model):
        self._template_args.update({
            'table_datas':
            self.get_table_data_from_db(model),
        })

    @expose('/details/')
    def details_view(self):

        self._template_args.update({
            'table_columns':
            self.get_readonly_table(),
            'table_datas':
            self.get_table_data_from_db(),
            'extra_table_js':
            'js/inline_table_details.js'
        })

        return super(_RepairApplicationView, self).details_view()

    @expose('/getTime/', methods=['GET'])
    def getTime(self):
        try:
            ca = request.args.get('ca')
            if ca:
                items = RepairMaterial.query.filter(
                    RepairMaterial.partNumber == ca).all()
                data = [item.serialNum for item in items]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')

        return jsonify(code=404, message='Not Found')

    @expose('/get_pn_from_repair_ca/', methods=['GET'])
    def get_pn_from_repair_ca(self):
        try:
            ca = request.args.get('ca')
            num = request.args.get('num')
            if ca and num:
                inst = RepairApplication.query.filter_by(number=num).first()
                materials = inst.repairAppl
                data = [m.partNumber for m in materials if m.category == ca]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=404, message='Not Found')

    @expose('/get_sn_from_repair_pn/', methods=['GET'])
    def get_sn_from_repair_pn(self):
        try:
            pn = request.args.get('pn')
            num = request.args.get('num')
            if pn and num:
                inst = RepairApplication.query.filter_by(number=num).first()
                materials = inst.repairAppl
                data = [m.serialNum for m in materials if m.partNumber == pn]
                data = json.dumps(data)
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=404, message='Not Found')

    @expose('/get_from_repair_pn/', methods=['GET'])
    def get_from_repair_pn(self):
        try:
            pn = request.args.get('pn')
            num = request.args.get('num')
            if pn and num:
                inst = RepairApplication.query.filter_by(number=num).first()
                materials = inst.repairAppl
                materials = [m for m in materials if m.partNumber == pn]
                data = [[
                    m.category, m.partNumber, m.serialNum, m.name,
                    m.manufacturer, m.quantity, m.flyTime, m.engineTime,
                    m.flightTimes
                ] for m in materials]
                data = json.dumps(data[0])
                return jsonify(code=200, data=data, message='Ok')
        except Exception:
            return jsonify(code=400, message='Bad Argument')
        return jsonify(code=404, message='Not Found')