Beispiel #1
0
class UnloadTaskModelView(ModelView):
    __form_columns__ = [
        ColumnSpec("id", label=u"编号"),
        ColumnSpec("customer", label=u"客户"),
        InputColumnSpec("product", group_by=Product.product_type, label=u"产品",
                        filter_=lambda q: q.filter(Product.enabled == True)),
        InputColumnSpec("weight", label=u"重量"),
        InputColumnSpec("harbor", label=u"装卸点"),
        PlaceHolderColumnSpec(col_name="pic_url", label=u"图片", template_fname="pic-snippet.html",
                              form_width_class="col-lg-3"),
        PlaceHolderColumnSpec(col_name="log_list", label=u"日志", template_fname="logs-snippet.html"), ]

    def preprocess(self, obj):
        return UnloadTaskWrapper(obj)

    def try_create(self):
        raise PermissionDenied

    def try_edit(self, objs=None):
        CargoClerkPermission.test()

        if any(obj.unload_session.status == cargo_const.STATUS_CLOSED for obj in objs):
            raise PermissionDenied

    def edit_hint_message(self, objs, read_only=False):
        if read_only:
            return u"本卸货会话已经关闭,所以不能修改卸货任务"
        return super(UnloadTaskModelView, self).edit_hint_message(objs, read_only)

    @login_required
    def try_view(self, processed_objs=None):
        pass
Beispiel #2
0
    def get_list_columns(self):
        def gr_item_formatter(v, obj):
            # 格式化每个发货单,未打印或者过期,需要提示出来
            ret = unicode(v)
            if v.pay_in_cash and not v.is_paid:
                ret += u'<small class="text-danger"> (未支付)</small>'
            if not v.MSSQL_ID:
                ret += u'<small class="text-danger"> (未导入)</small>'
            if v.stale:
                ret += u'<small class="text-danger"> (过期)</small>'
            return ret

        return [
            "id", "plate_",
            ColumnSpec("tare",
                       label=u"净重(公斤)",
                       formatter=lambda v, obj: sum(
                           dt.weight for dt in obj.delivery_task_list)),
            "create_time", "finish_time", "with_person", "status",
            ListColumnSpec("customer_list_unwrapped",
                           label=u"客 户",
                           compressed=True),
            ListColumnSpec("consignment_list_unwrapped",
                           label=u"发货单",
                           compressed=True,
                           item_col_spec=ColumnSpec(
                               "", formatter=gr_item_formatter))
        ]
Beispiel #3
0
 def get_list_columns(self):
     return [
         "id", "consignment_id", "delivery_session", "actor", "create_time",
         "customer", "pay_in_cash",
         ColumnSpec("is_paid", formatter=lambda v, obj: u"是"
                    if v else u"否"),
         ColumnSpec("notes", trunc=8), "MSSQL_ID"
     ]
Beispiel #4
0
    def get_form_columns(self, obj=None):

        form_columns = [ColumnSpec("id", label=u"编号"), ColumnSpec("create_time"), ColumnSpec("harbor"),
                        InputColumnSpec("product", group_by=Product.product_type),
                        InputColumnSpec("due_time", validators=[validators.Required(message=u"该字段不能为空")]), "weight"]
        if obj and obj.order_type == constants.EXTRA_ORDER_TYPE:
            form_columns.extend(["quantity", "unit", "spec", "type"])
        form_columns.extend(["tech_req", "urgent", "returned",
                             PlaceHolderColumnSpec("pic_url", label=u"图片", template_fname="pic-snippet.html",
                                                   form_width_class="col-lg-3"),
                             PlaceHolderColumnSpec("log_list", label=u"日志", template_fname="logs-snippet.html")])
        return form_columns
Beispiel #5
0
    def get_form_columns(self, obj=None):
        columns = [
            ColumnSpec("id", label=u"编号"),
            InputColumnSpec("weight", label=u"重量(公斤)")
        ]
        measured_by_weight = obj and obj.store_bill_list and any(
            store_bill.sub_order.measured_by_weight
            for store_bill in self.preprocess(obj).store_bill_list)
        if obj and not measured_by_weight:
            columns.extend([
                InputColumnSpec("quantity", label=u"数量"),
                ColumnSpec("unit", label=u"单位")
            ])

        columns.append(
            ListColumnSpec("store_bill_list",
                           label=u"仓单列表",
                           css_class="list-group",
                           item_css_class="list-group-item",
                           form_width_class="col-lg-3"))

        if obj and not measured_by_weight:
            columns.append(
                ListColumnSpec("spec_type_list",
                               label=u"规格-型号列表",
                               css_class="list-group",
                               item_css_class="list-group-item",
                               form_width_class="col-lg-3"))
        columns.extend([
            ListColumnSpec(
                "pic_url_list",
                label=u"图片",
                formatter=lambda v, obj: None if not v else [i[-1] for i in v],
                item_col_spec=ImageColumnSpec(
                    "",
                    css_class="img-polaroid",
                    alt=obj.product.name if obj and obj.product else ""),
                css_class="list-group",
                form_width_class="col-lg-3",
                item_css_class="list-group-item"),
            PlaceHolderColumnSpec("log_list",
                                  label=u"日志",
                                  template_fname="logs-snippet.html")
        ])
        return columns
Beispiel #6
0
 def get_form_columns(self, obj=None):
     columns = [
         ColumnSpec("id"), "qir.work_command", "customer", "product",
         InputColumnSpec("harbor", validators=[Required(u"不能为空")]), "weight"
     ]
     if obj and not StoreBillWrapper(obj).sub_order.measured_by_weight:
         columns.extend([
             "quantity",
             ColumnSpec("unit", label=u"单位"),
             ColumnSpec("sub_order.spec", label=u"型号"),
             ColumnSpec("sub_order.type", label=u"规格"),
         ])
     columns.extend([
         ColumnSpec("create_time"),
         ColumnSpec("printed",
                    label=u"是否打印",
                    formatter=lambda v, obj: u"是" if v else u"否"),
         ColumnSpec("sub_order.id", label=u"子订单号"),
         "sub_order.order.customer_order_number",
         PlaceHolderColumnSpec("pic_url",
                               label=u"图片",
                               template_fname="pic-snippet.html",
                               form_width_class="col-lg-3"),
         PlaceHolderColumnSpec("log_list",
                               label=u"日志",
                               template_fname="logs-snippet.html")
     ])
     return columns
Beispiel #7
0
    def get_form_columns(self, obj=None):
        columns = [
            ColumnSpec("id"),
            InputColumnSpec("product", group_by=models.Product.product_type),
            "weight"
        ]

        if obj and not ConsignmentWrapper(obj.consignment).measured_by_weight:
            columns.extend(["quantity", "unit", "spec", "type"])
        columns.extend(["returned_weight", "team"])
        return columns
Beispiel #8
0
    def get_form_columns(self, obj=None):
        __form_columns__ = OrderedDict()

        __form_columns__[u"发货会话详情"] = [
            ColumnSpec("id"), "plate_", "tare", "with_person",
            ColumnSpec("create_time"),
            ColumnSpec("finish_time"),
            PlaceHolderColumnSpec(col_name="log_list",
                                  label=u"日志",
                                  template_fname="logs-snippet.html")
        ]

        __form_columns__[u"发货任务列表"] = [
            PlaceHolderColumnSpec(
                "delivery_task_list",
                label="",
                template_fname="delivery/delivery-task-list-snippet.html")
        ]

        __form_columns__[u"发货单列表"] = [
            PlaceHolderColumnSpec(
                "consignment_list",
                label="",
                template_fname="delivery/consignment-list-snippet.html")
        ]
        if obj and obj.status not in [
                constants.delivery.STATUS_CLOSED,
                constants.delivery.STATUS_DISMISSED
        ]:
            __form_columns__[u"已选择仓单列表"] = [
                PlaceHolderColumnSpec(
                    "store_bill_list",
                    label="",
                    template_fname="delivery/store-bill-list-snippet.html")
            ]
        return __form_columns__
Beispiel #9
0
    def get_list_columns(self):
        def gr_item_formatter(v, obj):
            # 格式化每个收货单,未打印或者过期,需要提示出来
            ret = unicode(v)
            v = GoodsReceiptWrapper(v)
            if not v.printed:
                ret += u'<small class="text-danger"> (未打印)</small>'
            if v.stale:
                ret += u'<small class="text-danger"> (过期)</small>'
            return ret

        return ["id", "plate_", "create_time", "finish_time", "with_person", "status",
                ListColumnSpec("customer_list_unwrapped", label=u"客 户", compressed=True),
                ListColumnSpec("goods_receipt_list_unwrapped",
                               label=u"收货单",
                               compressed=True,
                               item_col_spec=ColumnSpec("", formatter=gr_item_formatter))]
Beispiel #10
0
    def get_form_columns(self, obj=None):
        self.__form_columns__ = OrderedDict()
        self.__form_columns__[u"发货单详情"] = [
            ColumnSpec("consignment_id"),
            ColumnSpec("actor"),
            ColumnSpec("create_time"),
            ColumnSpec("customer"),
            ColumnSpec("delivery_session")
        ]
        from lite_mms.permissions.roles import CargoClerkPermission

        if CargoClerkPermission.can():
            self.__form_columns__[u"发货单详情"].extend(
                ("notes", InputColumnSpec("pay_in_cash", label=u"现金支付")))
        else:
            self.__form_columns__[u"发货单详情"].extend(
                (ColumnSpec("notes"),
                 ColumnSpec("pay_in_cash",
                            formatter=lambda v, obj: u"现金支付" if v else u"月结")))
        if obj and obj.pay_in_cash:
            self.__form_columns__[u"发货单详情"].append(
                ColumnSpec("is_paid",
                           formatter=lambda v, obj: u"是" if v else u"否"))

        col_specs = [
            ColumnSpec("id", label=u"编号"),
            ColumnSpec("product",
                       label=u"产品",
                       formatter=lambda v, obj: unicode(v.product_type) + "-" +
                       unicode(v)),
            ColumnSpec("weight", label=u"重量(公斤)")
        ]
        sum_fields = ["weight"]

        if obj and not self.preprocess(obj).measured_by_weight:
            col_specs.extend([
                ColumnSpec("spec", label=u"型号"),
                ColumnSpec("type", label=u"规格"),
                ColumnSpec("quantity", label=u"数量"),
                ColumnSpec("unit", label=u"单位")
            ])
            sum_fields.append("quantity")

        col_specs.extend([
            ColumnSpec("returned_weight", label=u"退镀重量(公斤)"),
            ColumnSpec("team", label=u"生产班组")
        ])
        sum_fields.append("returned_weight")

        self.__form_columns__[u"产品列表"] = [
            TableColumnSpec("product_list_unwrapped",
                            label="",
                            col_specs=col_specs,
                            sum_fields=sum_fields)
        ]

        return self.__form_columns__
Beispiel #11
0
class OrderModelView(ModelView):
    list_template = "order/order-list.html"

    def try_create(self):
        raise PermissionDenied

    can_batchly_edit = False

    @login_required
    def try_view(self, processed_objs=None):
        pass

    def __list_filters__(self):
        if SchedulerPermission.can():
            return [filters.EqualTo("finish_time", value=None),
                    filters.EqualTo("refined", value=True),
                    filters.EqualTo("dispatched", value=True),
                    only_unfinished_filter
            ]
        else:
            return []

    __list_columns__ = ["id", "customer_order_number", "goods_receipt.customer", "net_weight", "remaining_weight",
                        PlaceHolderColumnSpec(col_name="manufacturing_work_command_list", label=u"生产中重量",
                                              template_fname="order/todo-work-command-list-snippet.html",
                                              doc=u"若大于0,请敦促车间生产"),
                        PlaceHolderColumnSpec(col_name="qi_work_command_list", label=u"待质检重量",
                                              template_fname="order/qi-list-snippet.html"),
                        PlaceHolderColumnSpec(col_name="done_work_command_list", label=u"已完成重量",
                                              template_fname="order/done-work-command-list-snippet.html",
                                              doc=u"指订单下所有是最后一道工序的工单,这类工单的工序后质量之和"),
                        PlaceHolderColumnSpec(col_name="to_deliver_store_bill_list", label=u"待发货重量",
                                              template_fname="order/store-bill-list-snippet.html"),
                        "delivered_weight", "create_time", "dispatched_time", "goods_receipt",
                        ColumnSpec("urgent",
                                   formatter=lambda v, obj: u"<span class='text-danger'>是</span>" if v else u"否"),
                        ColumnSpec("refined",
                                   formatter=lambda v, obj: u"<span class='text-danger'>否</span>" if not v else u"是")]

    def repr_obj(self, obj):
        return unicode(obj) + "<br /><p class='text-center'><small class='muted'>" + unicode(
            obj.goods_receipt.customer) + "</small></p>"

    __sortable_columns__ = ["id", "customer_order_number", "goods_receipt.customer", "create_time", "goods_receipt"]

    __column_labels__ = {"customer_order_number": u"订单号", "goods_receipt.customer": u"客户", "create_time": u"创建时间",
                         "goods_receipt": u"收货单", "net_weight": u"收货重量", "remaining_weight": u"待调度重量",
                         "delivered_weight": u"已发货重量", "refined": u"完善", "urgent": u"加急", "product": u"产品",
                         "category": u"类型", "dispatched_time": u"下发时间"}

    __column_docs__ = {"remaining_weight": u"若大于0,请敦促调度员排产"}

    __column_formatters__ = {
        "urgent": lambda v, obj: u"是" if v else u"否",
        "customer_order_number": lambda v, obj: v.join(
            ["" if not obj.warning else '<i class=" fa fa-exclamation-triangle"></i>',
             u"<b>(退货)</b>" if any(so.returned for so in obj.sub_order_list) else ""]),
        "remaining_weight": lambda v, obj: unicode(v + obj.to_work_weight),
        "refined": lambda v, obj: u"是" if v else u"否",
        "create_time": lambda v, obj: v.strftime("%m-%d %H") + u"点",
        "dispatched_time": lambda v, obj: v.strftime("%m-%d %H") + u"点" if v and obj.dispatched else ""}

    def get_column_filters(self):
        from datetime import datetime, timedelta

        today = datetime.today()
        yesterday = today.date()
        week_ago = (today - timedelta(days=7)).date()
        _30days_ago = (today - timedelta(days=30)).date()
        ret = [filters.EqualTo("goods_receipt.customer", name=u"是"),
               filters.BiggerThan("create_time", name=u"在", options=[
                   (yesterday, u'一天内'), (week_ago, u'一周内'), (_30days_ago, u'30天内')]),
               category_filter]
        if not SchedulerPermission.can():
            ret.append(only_unfinished_filter)
        return ret

    def preprocess(self, model):
        from lite_mms.apis.order import OrderWrapper

        return OrderWrapper(model)

    def get_customized_actions(self, processed_objs=None):
        __customized_actions__ = []
        if CargoClerkPermission.can():
            from lite_mms.portal.order.actions import dispatch_action, mark_refined_action, account_action, \
                new_extra_order_action

            if processed_objs:
                if not processed_objs[0].refined:
                    __customized_actions__.append(mark_refined_action)
                    if not processed_objs[0].dispatched and not processed_objs[0].measured_by_weight:
                        __customized_actions__.append(new_extra_order_action)
                elif not processed_objs[0].dispatched:
                    __customized_actions__.append(dispatch_action)
                if processed_objs[0].can_account:
                    __customized_actions__.append(account_action)
            else:
                __customized_actions__ = [dispatch_action, mark_refined_action, account_action]
        return __customized_actions__

    def patch_row_attr(self, idx, row):
        if not row.refined:
            return {"class": "warning", "title": u"此订单没有完善,请先完善订单"}
        elif row.urgent and row.remaining_quantity:
            return {"class": "danger", "title": u"此订单请加急完成"}
        elif row.warning:
            return {"title": u"此订单的收货重量大于未分配重量,生产中重量,已发货重量,待发货重量之和"}

    def url_for_object(self, model, **kwargs):
        if model:
            return url_for("order.order", id_=model.id, **kwargs)
        else:
            return url_for("order.order", **kwargs)

    __default_order__ = ("id", "desc")

    def get_form_columns(self, obj=None):
        form_columns = OrderedDict()
        form_columns[u"订单详情"] = [
            "customer_order_number", ColumnSpec("goods_receipt.customer"),
            ColumnSpec("goods_receipt", css_class="control-text", label=u"收货单"), "net_weight",
            ColumnSpec("create_time"),
            ColumnSpec("dispatched_time", formatter=lambda v, obj: v if v and obj.dispatched else ""),
            PlaceHolderColumnSpec("log_list", label=u"日志", template_fname="logs-snippet.html")]

        form_columns[u"子订单列表"] = [
            PlaceHolderColumnSpec("sub_order_list", template_fname="order/sub-order-list-snippet.html", label="")]
        if SchedulerPermission.can():
            from lite_mms.portal.manufacture.views import work_command_view

            form_columns[u"工单列表"] = [TableColumnSpec("work_command_list", label="", col_specs=[
                LinkColumnSpec("id", label=u"编号", anchor=lambda v: v,
                               formatter=lambda v, obj: work_command_view.url_for_object(obj, url=request.url)),
                ColumnSpec("sub_order.id", label=u"子订单编号"), ColumnSpec("product", label=u"产品名称"),
                ColumnSpec("urgent", label=u"加急",
                           formatter=lambda v, obj: u"<span class='text-danger'>是</span>" if v else u"否"),
                ColumnSpec("sub_order.returned", label=u"退镀",
                           formatter=lambda v, obj: u"<span class='text-danger'>是</span>" if v else u"否"),
                ColumnSpec("org_weight", label=u"工序前重量"), ColumnSpec("org_cnt", label=u"工序前数量"),
                ColumnSpec("unit", label=u"单位"), ColumnSpec("processed_weight", label=u"工序后重量"),
                ColumnSpec("processed_cnt", label=u"工序后数量"), ColumnSpec("tech_req", label=u"技术要求"),
                ColumnSpec("department", label=u"车间"), ColumnSpec("team", label=u"班组"),
                ColumnSpec("qi", label=u"质检员"), ColumnSpec("status_name", label=u"状态")])]

        form_columns[u'订单流程图'] = [
            PlaceHolderColumnSpec('work_flow_json', template_fname='order/order-work-flow-snippet.html', label='')]
        return form_columns

    def try_edit(self, processed_objs=None):
        Permission.union(SchedulerPermission, CargoClerkPermission).test()
        if processed_objs and processed_objs[0].refined or processed_objs[0].dispatched:
            raise PermissionDenied

    def edit_hint_message(self, obj, read_only=False):
        if read_only:
            if SchedulerPermission.can():
                return u"正在排产订单%s" % obj.customer_order_number
            else:
                if obj.refined:
                    return u"订单%s已标记完善,不能修改" % obj.customer_order_number
                if obj.refined:
                    return u"订单%s已下发,不能修改" % obj.customer_order_number
                return ""
        else:
            return super(OrderModelView, self).edit_hint_message(obj, read_only)
Beispiel #12
0
    def get_form_columns(self, obj=None):
        form_columns = OrderedDict()
        form_columns[u"订单详情"] = [
            "customer_order_number", ColumnSpec("goods_receipt.customer"),
            ColumnSpec("goods_receipt", css_class="control-text", label=u"收货单"), "net_weight",
            ColumnSpec("create_time"),
            ColumnSpec("dispatched_time", formatter=lambda v, obj: v if v and obj.dispatched else ""),
            PlaceHolderColumnSpec("log_list", label=u"日志", template_fname="logs-snippet.html")]

        form_columns[u"子订单列表"] = [
            PlaceHolderColumnSpec("sub_order_list", template_fname="order/sub-order-list-snippet.html", label="")]
        if SchedulerPermission.can():
            from lite_mms.portal.manufacture.views import work_command_view

            form_columns[u"工单列表"] = [TableColumnSpec("work_command_list", label="", col_specs=[
                LinkColumnSpec("id", label=u"编号", anchor=lambda v: v,
                               formatter=lambda v, obj: work_command_view.url_for_object(obj, url=request.url)),
                ColumnSpec("sub_order.id", label=u"子订单编号"), ColumnSpec("product", label=u"产品名称"),
                ColumnSpec("urgent", label=u"加急",
                           formatter=lambda v, obj: u"<span class='text-danger'>是</span>" if v else u"否"),
                ColumnSpec("sub_order.returned", label=u"退镀",
                           formatter=lambda v, obj: u"<span class='text-danger'>是</span>" if v else u"否"),
                ColumnSpec("org_weight", label=u"工序前重量"), ColumnSpec("org_cnt", label=u"工序前数量"),
                ColumnSpec("unit", label=u"单位"), ColumnSpec("processed_weight", label=u"工序后重量"),
                ColumnSpec("processed_cnt", label=u"工序后数量"), ColumnSpec("tech_req", label=u"技术要求"),
                ColumnSpec("department", label=u"车间"), ColumnSpec("team", label=u"班组"),
                ColumnSpec("qi", label=u"质检员"), ColumnSpec("status_name", label=u"状态")])]

        form_columns[u'订单流程图'] = [
            PlaceHolderColumnSpec('work_flow_json', template_fname='order/order-work-flow-snippet.html', label='')]
        return form_columns
Beispiel #13
0
class UnloadSessionModelView(ModelView):
    edit_template = "cargo/unload-session.html"

    can_batchly_edit = False

    def try_edit(self, objs=None):
        CargoClerkPermission.test()

        def _try_edit(obj_):
            if obj_ and obj_.finish_time:
                raise PermissionDenied

        if isinstance(objs, (list, tuple)):
            for obj_ in objs:
                _try_edit(obj_)
        else:
            _try_edit(objs)

    def repr_obj(self, obj):
        return unicode(obj) + "(" + cargo_const.desc_status(
            obj.status) + ")" + "<br /><p class='text-center'><small class='muted'>" + '&nbsp;' + ",".join(
            [unicode(customer) for customer in obj.customer_list]) + "</small></p>"

    def get_list_columns(self):
        def gr_item_formatter(v, obj):
            # 格式化每个收货单,未打印或者过期,需要提示出来
            ret = unicode(v)
            v = GoodsReceiptWrapper(v)
            if not v.printed:
                ret += u'<small class="text-danger"> (未打印)</small>'
            if v.stale:
                ret += u'<small class="text-danger"> (过期)</small>'
            return ret

        return ["id", "plate_", "create_time", "finish_time", "with_person", "status",
                ListColumnSpec("customer_list_unwrapped", label=u"客 户", compressed=True),
                ListColumnSpec("goods_receipt_list_unwrapped",
                               label=u"收货单",
                               compressed=True,
                               item_col_spec=ColumnSpec("", formatter=gr_item_formatter))]

    __column_labels__ = {"id": u"编号", "plate_": u"车辆", "create_time": u"创建时间", "finish_time": u"结束时间",
                         "with_person": u"驾驶室", "status": u"状态", "goods_receipt_list": u"收货单", "gross_weight": u"净重"}

    def patch_row_attr(self, idx, obj):
        test = len(obj.customer_list) > len(obj.goods_receipt_list)
        stale = False
        unprinted = False
        for gr in obj.goods_receipt_list:
            if not gr.printed:
                unprinted = True
            if gr.stale:
                stale = True
        if test or stale:
            return {
                "title": u"有客户收货单没有生成,或者存在已经过期的收货单, 强烈建议您重新生成收货单!",
                "class": "danger"}
        elif unprinted:
            return {
                "title": u"有客户收货单没有打印",
                "class": "warning"}

    __column_formatters__ = {
        "create_time": lambda v, obj: v.strftime("%m月%d日 %H点").decode("utf-8"),
        "finish_time": lambda v, obj: v.strftime("%m月%d日 %H点").decode("utf-8") if v else "--",
        "with_person": lambda v, obj: u'有人' if v else u'无人',
        "status": lambda v, obj: cargo_const.desc_status(v),
    }

    __default_order__ = ("id", "desc")

    __sortable_columns__ = ["id", "plate", "create_time", "finish_time"]

    from flask.ext.databrowser import filters
    from datetime import datetime, timedelta

    today = datetime.today()
    yesterday = today.date()
    week_ago = (today - timedelta(days=7)).date()
    _30days_ago = (today - timedelta(days=30)).date()

    __column_filters__ = [filters.BiggerThan("create_time", name=u"在", default_value=str(yesterday),
                                             options=[(yesterday, u'一天内'), (week_ago, u'一周内'),
                                                      (_30days_ago, u'30天内')]),
                          filters.EqualTo("plate_", name=u"是"),
                          filters.Only("status", display_col_name=u"仅展示未完成会话", test=lambda col: ~col.in_(
                              [cargo_const.STATUS_CLOSED, cargo_const.STATUS_DISMISSED]), notation="__only_unclosed"),
    ]

    def try_view(self, processed_objs=None):
        from flask.ext.principal import Permission

        Permission.union(CargoClerkPermission, AdminPermission).test()

    def preprocess(self, model):
        return UnloadSessionWrapper(model)

    def get_customized_actions(self, model_list=None):
        from lite_mms.portal.cargo.actions import (CloseAction, OpenAction,
                                                   CreateReceiptAction, BatchPrintGoodsReceipt,
                                                   DeleteUnloadSessionAction)

        class _PrintGoodsReceipt(BaseAction):
            def op_upon_list(self, objs, model_list):
                obj = objs[0]
                return redirect(url_for("goods_receipt.goods_receipts_batch_print",
                                        id_=",".join([str(gr.id) for gr in obj.goods_receipt_list]), url=request.url))

        action_list = []
        create_action = CreateReceiptAction(u"生成收货单")
        if model_list is None:  # for list
            action_list.extend([CloseAction(u"关闭"), OpenAction(u"打开"),  create_action,
                                DeleteUnloadSessionAction(u"删除", None)])
        else:
            if len(model_list) == 1:
                if model_list[0].status in [cargo_const.STATUS_CLOSED, cargo_const.STATUS_DISMISSED]:
                    action_list.append(OpenAction(u"打开"))
                else:
                    action_list.append(CloseAction(u"关闭"))
                if create_action.test_enabled(model_list[0]) == 0:
                    action_list.append(create_action)
                if model_list[0].goods_receipt_list:
                    action_list.append(_PrintGoodsReceipt(u"打印收货单"))
        return action_list

    def get_list_help(self):
        return render_template("cargo/us-list-help.html")

    # ================= FORM PART ============================
    def get_create_columns(self):
        def filter_plate(q):
            unfinished_us_list = UnloadSession.query.filter(UnloadSession.finish_time == None)
            unfinished_ds_list = DeliverySession.query.filter(DeliverySession.finish_time == None)
            plates = [us.plate for us in unfinished_us_list]
            plates.extend(ds.plate for ds in unfinished_ds_list)
            return q.filter(~Plate.name.in_(plates))
            # return q.filter(
            #    and_(~exists().where(UnloadSession.plate == Plate.name).where(UnloadSession.finish_time == None),
            #         ~exists().where(DeliverySession.finish_time == None).where(DeliverySession.plate == Plate.name)))

        return [InputColumnSpec("plate_", filter_=filter_plate),
                InputColumnSpec("with_person", label=u"驾驶室是否有人"),
                "gross_weight"]

    def edit_hint_message(self, obj, read_only=False):
        if read_only:
            return u"已关闭的卸货会话不能修改"
        else:
            return super(UnloadSessionModelView, self).edit_hint_message(obj, read_only)

    __form_columns__ = OrderedDict()
    __form_columns__[u"详细信息"] = [
        "plate_",
        InputColumnSpec("gross_weight", label=u"毛重"),
        InputColumnSpec("with_person", label=u"驾驶室是否有人"),
        ColumnSpec("status", label=u"状态", formatter=lambda v, obj: cargo_const.desc_status(v)),
        InputColumnSpec("create_time", label=u"创建时间", read_only=True),
        InputColumnSpec("finish_time", label=u"结束时间", read_only=True),
        PlaceHolderColumnSpec(col_name="log_list", label=u"日志", template_fname="logs-snippet.html")
    ]
    __form_columns__[u"收货任务列表"] = [
        PlaceHolderColumnSpec(col_name="task_list", label=u"",
                              template_fname="cargo/unload-task-list-snippet.html")]
    __form_columns__[u"收货单列表"] = [
        PlaceHolderColumnSpec(col_name="goods_receipt_list", label=u"", template_fname="cargo/gr-list-snippet.html")]

    def get_edit_help(self, objs):
        return render_template("cargo/us-edit-help.html")

    def get_create_help(self):
        return render_template("cargo/us-create-help.html")
Beispiel #14
0
class GoodsReceiptModelView(ModelView):
    edit_template = "cargo/goods-receipt.html"

    can_batchly_edit = True

    __default_order__ = ("create_time", "desc")

    def try_create(self):
        raise PermissionDenied

    def preprocess(self, obj):
        return GoodsReceiptWrapper(obj)

    @login_required
    def try_view(self, processed_objs=None):
        pass

    __sortable_columns__ = ["id", "create_time"]

    __list_columns__ = ["id", "receipt_id", "customer", "unload_session.plate",
                        InputColumnSpec("order", formatter=lambda v, obj: v or "--", label=u"订单"),
                        ColumnSpec("printed", formatter=lambda v, obj: u"是" if v else u"否", label=u"是否打印"),
                        ColumnSpec("stale", formatter=lambda v, obj: u"是" if v else u"否", label=u"是否过时"),
                        ColumnSpec("create_time",
                                   formatter=lambda v, obj: v.strftime("%y年%m月%d日 %H时%M分").decode("utf-8"),
                                   label=u"创建时间"), ColumnSpec("creator"),
                        ListColumnSpec("goods_receipt_entries", label=u"产品", compressed=True,
                                       item_col_spec=ColumnSpec("", formatter=lambda v, obj: unicode(
                                           v.product.product_type) + u"-" + unicode(v.product)))]

    def patch_row_attr(self, idx, obj):
        if obj.stale:
            return {
                "class": "danger",
                "title": u"本收货单已经过时,请回到卸货会话重新生成"
            }
        if not obj.printed:
            return {
                "class": "warning",
                "title": u"本收货单尚未打印"
            }

    from flask.ext.databrowser import filters
    from datetime import datetime, timedelta

    today = datetime.today()
    yesterday = today.date()
    week_ago = (today - timedelta(days=7)).date()
    _30days_ago = (today - timedelta(days=30)).date()

    class NoneOrder(filters.Only):
        def set_sa_criterion(self, q):
            if self.value:
                return q.filter(GoodsReceipt.order == None)
            else:
                return q

    __column_filters__ = [filters.BiggerThan("create_time", name=u"在", default_value=str(yesterday),
                                             options=[(yesterday, u'一天内'), (week_ago, u'一周内'),
                                                      (_30days_ago, u'30天内')]),
                          filters.EqualTo("customer", name=u"是"),
                          filters.Only("printed", display_col_name=u"仅展示未打印收货单", test=lambda col: ~col,
                                       notation="__only_unprinted"),
                          NoneOrder("order", display_col_name=u"仅展示未生成订单", test=None, notation="__none")]

    __form_columns__ = OrderedDict()
    __form_columns__[u"详细信息"] = [
        "receipt_id", "customer", "unload_session.plate",
        ColumnSpec("create_time", label=u"创建时间"),
        ColumnSpec("creator"),
        ColumnSpec("printed", label=u"是否打印",
                   formatter=lambda v,
                                    obj: u"是" if v else u'<span class="text-danger">否</span>'),
        ColumnSpec("stale", label=u"是否过时",
                   formatter=lambda v, obj: u'<span class="text-danger">是</span>' if v else u"否"),
        PlaceHolderColumnSpec("log_list", label=u"日志", template_fname="logs-snippet.html")]

    __form_columns__[u"产品列表"] = [
        TableColumnSpec(
            "goods_receipt_entries", label="", preprocess=lambda obj: GoodsReceiptWrapper(obj),
            col_specs=[
                LinkColumnSpec("id", label=u"编号", anchor=lambda v: v,
                               formatter=lambda v, obj: goods_receipt_entry_view.url_for_object(obj, url=request.url)),
                ColumnSpec("product", label=u"产品"),
                ColumnSpec("product.product_type", label=u"产品类型"),
                ColumnSpec("weight", label=u"净重(公斤)"),
                PlaceHolderColumnSpec(col_name="pic_url", label=u"图片",
                                      template_fname="pic-snippet.html",
                                      form_width_class="col-lg-3")])]

    __column_labels__ = {"receipt_id": u'编 号', "customer": u'客 户', "unload_session.plate": u"车牌号",
                         "printed": u'是否打印', "stale": u"是否过时", "create_time": u"创建时间", "order": u"订 单",
                         "creator": u"创建者"}

    def get_customized_actions(self, objs=None):
        from lite_mms.portal.cargo.actions import PrintGoodsReceipt, BatchPrintGoodsReceipt, CreateOrderAction, \
            CreateExtraOrderAction, ViewOrderAction, DeleteGoodsReceiptAction

        delete_goods_receipt_action = DeleteGoodsReceiptAction(u"删除")
        if not objs:
            if g.request_from_mobile:
                return [delete_goods_receipt_action]
            else:
                return [BatchPrintGoodsReceipt(u"批量打印"), delete_goods_receipt_action]
        else:
            def _get_actions(obj):
                if obj.order:
                    return [ViewOrderAction(u"查看订单")]
                else:
                    _actions = [CreateOrderAction(u"生成计重类型订单"), CreateExtraOrderAction(u"生成计件类型订单")]
                    if not obj.printed:
                        _actions.append(delete_goods_receipt_action)
                    return _actions

            if isinstance(objs, (list, tuple)):
                if len(objs) == 1:
                    actions = _get_actions(objs[0])
                else:
                    actions = []
            else:
                actions = _get_actions(objs)
            if not g.request_from_mobile:
                actions.append(PrintGoodsReceipt(u"打印"))
            return actions

    def try_edit(self, objs=None):
        def _try_edit(obj):
            if obj:
                if isinstance(obj, self.data_browser.db.Model):
                    obj = self.preprocess(obj)
                if obj.stale or obj.order:
                    raise PermissionDenied

        CargoClerkPermission.test()

        if isinstance(objs, (list, tuple)):
            return any(_try_edit(obj) for obj in objs)
        else:
            return _try_edit(objs)

    def edit_hint_message(self, obj, read_only=False):
        if read_only:
            if obj.order:
                return u"已生成订单的收货单不能修改"
            else:
                return u"已过时的收货单不能修改"
        else:
            return super(GoodsReceiptModelView, self).edit_hint_message(obj, read_only)

    def batch_edit_hint_message(self, objs, read_only=False):
        if read_only:
            obj_ids = ",".join([obj.receipt_id for obj in objs])
            for obj in objs:
                if obj.order:
                    return u"收货单%s已生成订单,不能批量修改%s" % (obj.receipt_id, obj_ids)
                elif obj.stale:
                    return u"收货单%s已过时,不能批量修改%s" % (obj.receipt_id, obj_ids)
            else:
                return u"存在不能修改的收货单"
        else:
            return super(GoodsReceiptModelView, self).edit_hint_message(objs, read_only)

    def get_batch_form_columns(self, preprocessed_objs=None):
        return ["customer", "receipt_id", "create_time", "printed"]