diff --git a/bj_power_mes/ent/materialrequest.go b/bj_power_mes/ent/materialrequest.go
index e659474..64eebba 100644
--- a/bj_power_mes/ent/materialrequest.go
+++ b/bj_power_mes/ent/materialrequest.go
@@ -4,6 +4,7 @@ package ent
import (
"bj_power_mes/ent/materialrequest"
+ "encoding/json"
"fmt"
"strings"
"time"
@@ -53,6 +54,8 @@ type MaterialRequest struct {
OutboundNo string `json:"outboundNo,omitempty"`
// 驳回理由(仓库拒发时必填)
RejectReason string `json:"rejectReason,omitempty"`
+ // 跨工位借料来源 stationNo→借用量;空=本工位自取
+ BorrowFrom map[string]int `json:"borrowFrom,omitempty"`
// Operator holds the value of the "operator" field.
Operator string `json:"operator,omitempty"`
// CreatedAt holds the value of the "createdAt" field.
@@ -67,6 +70,8 @@ func (*MaterialRequest) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
+ case materialrequest.FieldBorrowFrom:
+ values[i] = new([]byte)
case materialrequest.FieldNeedAgv, materialrequest.FieldCrossDay:
values[i] = new(sql.NullBool)
case materialrequest.FieldReqQty, materialrequest.FieldSentQty, materialrequest.FieldReturnedQty:
@@ -206,6 +211,14 @@ func (_m *MaterialRequest) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.RejectReason = value.String
}
+ case materialrequest.FieldBorrowFrom:
+ if value, ok := values[i].(*[]byte); !ok {
+ return fmt.Errorf("unexpected type %T for field borrowFrom", values[i])
+ } else if value != nil && len(*value) > 0 {
+ if err := json.Unmarshal(*value, &_m.BorrowFrom); err != nil {
+ return fmt.Errorf("unmarshal field borrowFrom: %w", err)
+ }
+ }
case materialrequest.FieldOperator:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field operator", values[i])
@@ -315,6 +328,9 @@ func (_m *MaterialRequest) String() string {
builder.WriteString("rejectReason=")
builder.WriteString(_m.RejectReason)
builder.WriteString(", ")
+ builder.WriteString("borrowFrom=")
+ builder.WriteString(fmt.Sprintf("%v", _m.BorrowFrom))
+ builder.WriteString(", ")
builder.WriteString("operator=")
builder.WriteString(_m.Operator)
builder.WriteString(", ")
diff --git a/bj_power_mes/ent/materialrequest/materialrequest.go b/bj_power_mes/ent/materialrequest/materialrequest.go
index 88cb44f..4684a83 100644
--- a/bj_power_mes/ent/materialrequest/materialrequest.go
+++ b/bj_power_mes/ent/materialrequest/materialrequest.go
@@ -49,6 +49,8 @@ const (
FieldOutboundNo = "outbound_no"
// FieldRejectReason holds the string denoting the rejectreason field in the database.
FieldRejectReason = "reject_reason"
+ // FieldBorrowFrom holds the string denoting the borrowfrom field in the database.
+ FieldBorrowFrom = "borrow_from"
// FieldOperator holds the string denoting the operator field in the database.
FieldOperator = "operator"
// FieldCreatedAt holds the string denoting the createdat field in the database.
@@ -80,6 +82,7 @@ var Columns = []string{
FieldCrossDay,
FieldOutboundNo,
FieldRejectReason,
+ FieldBorrowFrom,
FieldOperator,
FieldCreatedAt,
FieldUpdatedAt,
diff --git a/bj_power_mes/ent/materialrequest/where.go b/bj_power_mes/ent/materialrequest/where.go
index 5322b5f..6ba4642 100644
--- a/bj_power_mes/ent/materialrequest/where.go
+++ b/bj_power_mes/ent/materialrequest/where.go
@@ -1094,6 +1094,16 @@ func RejectReasonContainsFold(v string) predicate.MaterialRequest {
return predicate.MaterialRequest(sql.FieldContainsFold(FieldRejectReason, v))
}
+// BorrowFromIsNil applies the IsNil predicate on the "borrowFrom" field.
+func BorrowFromIsNil() predicate.MaterialRequest {
+ return predicate.MaterialRequest(sql.FieldIsNull(FieldBorrowFrom))
+}
+
+// BorrowFromNotNil applies the NotNil predicate on the "borrowFrom" field.
+func BorrowFromNotNil() predicate.MaterialRequest {
+ return predicate.MaterialRequest(sql.FieldNotNull(FieldBorrowFrom))
+}
+
// OperatorEQ applies the EQ predicate on the "operator" field.
func OperatorEQ(v string) predicate.MaterialRequest {
return predicate.MaterialRequest(sql.FieldEQ(FieldOperator, v))
diff --git a/bj_power_mes/ent/materialrequest_create.go b/bj_power_mes/ent/materialrequest_create.go
index 9414dfb..5c6fe5c 100644
--- a/bj_power_mes/ent/materialrequest_create.go
+++ b/bj_power_mes/ent/materialrequest_create.go
@@ -256,6 +256,12 @@ func (_c *MaterialRequestCreate) SetNillableRejectReason(v *string) *MaterialReq
return _c
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_c *MaterialRequestCreate) SetBorrowFrom(v map[string]int) *MaterialRequestCreate {
+ _c.mutation.SetBorrowFrom(v)
+ return _c
+}
+
// SetOperator sets the "operator" field.
func (_c *MaterialRequestCreate) SetOperator(v string) *MaterialRequestCreate {
_c.mutation.SetOperator(v)
@@ -648,6 +654,10 @@ func (_c *MaterialRequestCreate) createSpec() (*MaterialRequest, *sqlgraph.Creat
_spec.SetField(materialrequest.FieldRejectReason, field.TypeString, value)
_node.RejectReason = value
}
+ if value, ok := _c.mutation.BorrowFrom(); ok {
+ _spec.SetField(materialrequest.FieldBorrowFrom, field.TypeJSON, value)
+ _node.BorrowFrom = value
+ }
if value, ok := _c.mutation.Operator(); ok {
_spec.SetField(materialrequest.FieldOperator, field.TypeString, value)
_node.Operator = value
diff --git a/bj_power_mes/ent/materialrequest_update.go b/bj_power_mes/ent/materialrequest_update.go
index c6cc627..05f4ae4 100644
--- a/bj_power_mes/ent/materialrequest_update.go
+++ b/bj_power_mes/ent/materialrequest_update.go
@@ -316,6 +316,18 @@ func (_u *MaterialRequestUpdate) SetNillableRejectReason(v *string) *MaterialReq
return _u
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_u *MaterialRequestUpdate) SetBorrowFrom(v map[string]int) *MaterialRequestUpdate {
+ _u.mutation.SetBorrowFrom(v)
+ return _u
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (_u *MaterialRequestUpdate) ClearBorrowFrom() *MaterialRequestUpdate {
+ _u.mutation.ClearBorrowFrom()
+ return _u
+}
+
// SetOperator sets the "operator" field.
func (_u *MaterialRequestUpdate) SetOperator(v string) *MaterialRequestUpdate {
_u.mutation.SetOperator(v)
@@ -535,6 +547,12 @@ func (_u *MaterialRequestUpdate) sqlSave(ctx context.Context) (_node int, err er
if value, ok := _u.mutation.RejectReason(); ok {
_spec.SetField(materialrequest.FieldRejectReason, field.TypeString, value)
}
+ if value, ok := _u.mutation.BorrowFrom(); ok {
+ _spec.SetField(materialrequest.FieldBorrowFrom, field.TypeJSON, value)
+ }
+ if _u.mutation.BorrowFromCleared() {
+ _spec.ClearField(materialrequest.FieldBorrowFrom, field.TypeJSON)
+ }
if value, ok := _u.mutation.Operator(); ok {
_spec.SetField(materialrequest.FieldOperator, field.TypeString, value)
}
@@ -853,6 +871,18 @@ func (_u *MaterialRequestUpdateOne) SetNillableRejectReason(v *string) *Material
return _u
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_u *MaterialRequestUpdateOne) SetBorrowFrom(v map[string]int) *MaterialRequestUpdateOne {
+ _u.mutation.SetBorrowFrom(v)
+ return _u
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (_u *MaterialRequestUpdateOne) ClearBorrowFrom() *MaterialRequestUpdateOne {
+ _u.mutation.ClearBorrowFrom()
+ return _u
+}
+
// SetOperator sets the "operator" field.
func (_u *MaterialRequestUpdateOne) SetOperator(v string) *MaterialRequestUpdateOne {
_u.mutation.SetOperator(v)
@@ -1102,6 +1132,12 @@ func (_u *MaterialRequestUpdateOne) sqlSave(ctx context.Context) (_node *Materia
if value, ok := _u.mutation.RejectReason(); ok {
_spec.SetField(materialrequest.FieldRejectReason, field.TypeString, value)
}
+ if value, ok := _u.mutation.BorrowFrom(); ok {
+ _spec.SetField(materialrequest.FieldBorrowFrom, field.TypeJSON, value)
+ }
+ if _u.mutation.BorrowFromCleared() {
+ _spec.ClearField(materialrequest.FieldBorrowFrom, field.TypeJSON)
+ }
if value, ok := _u.mutation.Operator(); ok {
_spec.SetField(materialrequest.FieldOperator, field.TypeString, value)
}
diff --git a/bj_power_mes/ent/migrate/schema.go b/bj_power_mes/ent/migrate/schema.go
index 7992005..ac017ac 100644
--- a/bj_power_mes/ent/migrate/schema.go
+++ b/bj_power_mes/ent/migrate/schema.go
@@ -614,6 +614,7 @@ var (
{Name: "cross_day", Type: field.TypeBool, Comment: "跨日标记:叫料池行含非今日排产(工位预警+仓库可驳回异常)", Default: false},
{Name: "outbound_no", Type: field.TypeString, Size: 255, Comment: "WMS 出库单号(完成备料回写,多个逗号分隔)", Default: ""},
{Name: "reject_reason", Type: field.TypeString, Size: 128, Comment: "驳回理由(仓库拒发时必填)", Default: ""},
+ {Name: "borrow_from", Type: field.TypeJSON, Nullable: true, Comment: "跨工位借料来源 stationNo→借用量;空=本工位自取", SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "operator", Type: field.TypeString, Size: 64, Default: ""},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
@@ -1175,7 +1176,6 @@ var (
{Name: "project_no", Type: field.TypeString, Size: 64, Comment: "工程编号(已废弃,保留防历史数据迁移)", Default: ""},
{Name: "product_serial", Type: field.TypeString, Size: 64, Comment: "产品序号(工单内每台产品的序号)", Default: ""},
{Name: "created_by", Type: field.TypeString, Size: 64, Comment: "创建人", Default: ""},
- {Name: "due_date", Type: field.TypeTime, Nullable: true, Comment: "完成日期(必填)"},
{Name: "flow_combination", Type: field.TypeJSON, Nullable: true, Comment: "工艺组合 [{flowId,stationNo}] 按工位号升序", SchemaType: map[string]string{"postgres": "jsonb"}},
{Name: "product_process_id", Type: field.TypeInt, Comment: "来源产品工艺ID(0=无来源)", Default: 0},
{Name: "status", Type: field.TypeString, Size: 20, Default: "CREATED"},
@@ -1202,7 +1202,7 @@ var (
{
Name: "workorder_status",
Unique: false,
- Columns: []*schema.Column{WorkOrderColumns[16]},
+ Columns: []*schema.Column{WorkOrderColumns[15]},
},
{
Name: "workorder_product_type_id",
diff --git a/bj_power_mes/ent/mutation.go b/bj_power_mes/ent/mutation.go
index e38da3a..c18e344 100644
--- a/bj_power_mes/ent/mutation.go
+++ b/bj_power_mes/ent/mutation.go
@@ -15871,6 +15871,7 @@ type MaterialRequestMutation struct {
crossDay *bool
outboundNo *string
rejectReason *string
+ borrowFrom *map[string]int
operator *string
createdAt *time.Time
updatedAt *time.Time
@@ -16732,6 +16733,55 @@ func (m *MaterialRequestMutation) ResetRejectReason() {
m.rejectReason = nil
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (m *MaterialRequestMutation) SetBorrowFrom(value map[string]int) {
+ m.borrowFrom = &value
+}
+
+// BorrowFrom returns the value of the "borrowFrom" field in the mutation.
+func (m *MaterialRequestMutation) BorrowFrom() (r map[string]int, exists bool) {
+ v := m.borrowFrom
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldBorrowFrom returns the old "borrowFrom" field's value of the MaterialRequest entity.
+// If the MaterialRequest object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *MaterialRequestMutation) OldBorrowFrom(ctx context.Context) (v map[string]int, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldBorrowFrom is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldBorrowFrom requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldBorrowFrom: %w", err)
+ }
+ return oldValue.BorrowFrom, nil
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (m *MaterialRequestMutation) ClearBorrowFrom() {
+ m.borrowFrom = nil
+ m.clearedFields[materialrequest.FieldBorrowFrom] = struct{}{}
+}
+
+// BorrowFromCleared returns if the "borrowFrom" field was cleared in this mutation.
+func (m *MaterialRequestMutation) BorrowFromCleared() bool {
+ _, ok := m.clearedFields[materialrequest.FieldBorrowFrom]
+ return ok
+}
+
+// ResetBorrowFrom resets all changes to the "borrowFrom" field.
+func (m *MaterialRequestMutation) ResetBorrowFrom() {
+ m.borrowFrom = nil
+ delete(m.clearedFields, materialrequest.FieldBorrowFrom)
+}
+
// SetOperator sets the "operator" field.
func (m *MaterialRequestMutation) SetOperator(s string) {
m.operator = &s
@@ -16887,7 +16937,7 @@ func (m *MaterialRequestMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *MaterialRequestMutation) Fields() []string {
- fields := make([]string, 0, 21)
+ fields := make([]string, 0, 22)
if m.requestNo != nil {
fields = append(fields, materialrequest.FieldRequestNo)
}
@@ -16942,6 +16992,9 @@ func (m *MaterialRequestMutation) Fields() []string {
if m.rejectReason != nil {
fields = append(fields, materialrequest.FieldRejectReason)
}
+ if m.borrowFrom != nil {
+ fields = append(fields, materialrequest.FieldBorrowFrom)
+ }
if m.operator != nil {
fields = append(fields, materialrequest.FieldOperator)
}
@@ -16995,6 +17048,8 @@ func (m *MaterialRequestMutation) Field(name string) (ent.Value, bool) {
return m.OutboundNo()
case materialrequest.FieldRejectReason:
return m.RejectReason()
+ case materialrequest.FieldBorrowFrom:
+ return m.BorrowFrom()
case materialrequest.FieldOperator:
return m.Operator()
case materialrequest.FieldCreatedAt:
@@ -17046,6 +17101,8 @@ func (m *MaterialRequestMutation) OldField(ctx context.Context, name string) (en
return m.OldOutboundNo(ctx)
case materialrequest.FieldRejectReason:
return m.OldRejectReason(ctx)
+ case materialrequest.FieldBorrowFrom:
+ return m.OldBorrowFrom(ctx)
case materialrequest.FieldOperator:
return m.OldOperator(ctx)
case materialrequest.FieldCreatedAt:
@@ -17187,6 +17244,13 @@ func (m *MaterialRequestMutation) SetField(name string, value ent.Value) error {
}
m.SetRejectReason(v)
return nil
+ case materialrequest.FieldBorrowFrom:
+ v, ok := value.(map[string]int)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetBorrowFrom(v)
+ return nil
case materialrequest.FieldOperator:
v, ok := value.(string)
if !ok {
@@ -17301,6 +17365,9 @@ func (m *MaterialRequestMutation) AddField(name string, value ent.Value) error {
// mutation.
func (m *MaterialRequestMutation) ClearedFields() []string {
var fields []string
+ if m.FieldCleared(materialrequest.FieldBorrowFrom) {
+ fields = append(fields, materialrequest.FieldBorrowFrom)
+ }
if m.FieldCleared(materialrequest.FieldUpdatedAt) {
fields = append(fields, materialrequest.FieldUpdatedAt)
}
@@ -17318,6 +17385,9 @@ func (m *MaterialRequestMutation) FieldCleared(name string) bool {
// error if the field is not defined in the schema.
func (m *MaterialRequestMutation) ClearField(name string) error {
switch name {
+ case materialrequest.FieldBorrowFrom:
+ m.ClearBorrowFrom()
+ return nil
case materialrequest.FieldUpdatedAt:
m.ClearUpdatedAt()
return nil
@@ -17383,6 +17453,9 @@ func (m *MaterialRequestMutation) ResetField(name string) error {
case materialrequest.FieldRejectReason:
m.ResetRejectReason()
return nil
+ case materialrequest.FieldBorrowFrom:
+ m.ResetBorrowFrom()
+ return nil
case materialrequest.FieldOperator:
m.ResetOperator()
return nil
@@ -31564,7 +31637,6 @@ type WorkOrderMutation struct {
projectNo *string
productSerial *string
createdBy *string
- dueDate *time.Time
flowCombination *[]map[string]int
appendflowCombination []map[string]int
productProcessId *int
@@ -32199,55 +32271,6 @@ func (m *WorkOrderMutation) ResetCreatedBy() {
m.createdBy = nil
}
-// SetDueDate sets the "dueDate" field.
-func (m *WorkOrderMutation) SetDueDate(t time.Time) {
- m.dueDate = &t
-}
-
-// DueDate returns the value of the "dueDate" field in the mutation.
-func (m *WorkOrderMutation) DueDate() (r time.Time, exists bool) {
- v := m.dueDate
- if v == nil {
- return
- }
- return *v, true
-}
-
-// OldDueDate returns the old "dueDate" field's value of the WorkOrder entity.
-// If the WorkOrder object wasn't provided to the builder, the object is fetched from the database.
-// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
-func (m *WorkOrderMutation) OldDueDate(ctx context.Context) (v *time.Time, err error) {
- if !m.op.Is(OpUpdateOne) {
- return v, errors.New("OldDueDate is only allowed on UpdateOne operations")
- }
- if m.id == nil || m.oldValue == nil {
- return v, errors.New("OldDueDate requires an ID field in the mutation")
- }
- oldValue, err := m.oldValue(ctx)
- if err != nil {
- return v, fmt.Errorf("querying old value for OldDueDate: %w", err)
- }
- return oldValue.DueDate, nil
-}
-
-// ClearDueDate clears the value of the "dueDate" field.
-func (m *WorkOrderMutation) ClearDueDate() {
- m.dueDate = nil
- m.clearedFields[workorder.FieldDueDate] = struct{}{}
-}
-
-// DueDateCleared returns if the "dueDate" field was cleared in this mutation.
-func (m *WorkOrderMutation) DueDateCleared() bool {
- _, ok := m.clearedFields[workorder.FieldDueDate]
- return ok
-}
-
-// ResetDueDate resets all changes to the "dueDate" field.
-func (m *WorkOrderMutation) ResetDueDate() {
- m.dueDate = nil
- delete(m.clearedFields, workorder.FieldDueDate)
-}
-
// SetFlowCombination sets the "flowCombination" field.
func (m *WorkOrderMutation) SetFlowCombination(value []map[string]int) {
m.flowCombination = &value
@@ -32769,7 +32792,7 @@ func (m *WorkOrderMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *WorkOrderMutation) Fields() []string {
- fields := make([]string, 0, 23)
+ fields := make([]string, 0, 22)
if m.workOrderNo != nil {
fields = append(fields, workorder.FieldWorkOrderNo)
}
@@ -32806,9 +32829,6 @@ func (m *WorkOrderMutation) Fields() []string {
if m.createdBy != nil {
fields = append(fields, workorder.FieldCreatedBy)
}
- if m.dueDate != nil {
- fields = append(fields, workorder.FieldDueDate)
- }
if m.flowCombination != nil {
fields = append(fields, workorder.FieldFlowCombination)
}
@@ -32871,8 +32891,6 @@ func (m *WorkOrderMutation) Field(name string) (ent.Value, bool) {
return m.ProductSerial()
case workorder.FieldCreatedBy:
return m.CreatedBy()
- case workorder.FieldDueDate:
- return m.DueDate()
case workorder.FieldFlowCombination:
return m.FlowCombination()
case workorder.FieldProductProcessId:
@@ -32926,8 +32944,6 @@ func (m *WorkOrderMutation) OldField(ctx context.Context, name string) (ent.Valu
return m.OldProductSerial(ctx)
case workorder.FieldCreatedBy:
return m.OldCreatedBy(ctx)
- case workorder.FieldDueDate:
- return m.OldDueDate(ctx)
case workorder.FieldFlowCombination:
return m.OldFlowCombination(ctx)
case workorder.FieldProductProcessId:
@@ -33041,13 +33057,6 @@ func (m *WorkOrderMutation) SetField(name string, value ent.Value) error {
}
m.SetCreatedBy(v)
return nil
- case workorder.FieldDueDate:
- v, ok := value.(time.Time)
- if !ok {
- return fmt.Errorf("unexpected type %T for field %s", value, name)
- }
- m.SetDueDate(v)
- return nil
case workorder.FieldFlowCombination:
v, ok := value.([]map[string]int)
if !ok {
@@ -33211,9 +33220,6 @@ func (m *WorkOrderMutation) AddField(name string, value ent.Value) error {
// mutation.
func (m *WorkOrderMutation) ClearedFields() []string {
var fields []string
- if m.FieldCleared(workorder.FieldDueDate) {
- fields = append(fields, workorder.FieldDueDate)
- }
if m.FieldCleared(workorder.FieldFlowCombination) {
fields = append(fields, workorder.FieldFlowCombination)
}
@@ -33249,9 +33255,6 @@ func (m *WorkOrderMutation) FieldCleared(name string) bool {
// error if the field is not defined in the schema.
func (m *WorkOrderMutation) ClearField(name string) error {
switch name {
- case workorder.FieldDueDate:
- m.ClearDueDate()
- return nil
case workorder.FieldFlowCombination:
m.ClearFlowCombination()
return nil
@@ -33317,9 +33320,6 @@ func (m *WorkOrderMutation) ResetField(name string) error {
case workorder.FieldCreatedBy:
m.ResetCreatedBy()
return nil
- case workorder.FieldDueDate:
- m.ResetDueDate()
- return nil
case workorder.FieldFlowCombination:
m.ResetFlowCombination()
return nil
diff --git a/bj_power_mes/ent/runtime.go b/bj_power_mes/ent/runtime.go
index 15b7149..7c47ee0 100644
--- a/bj_power_mes/ent/runtime.go
+++ b/bj_power_mes/ent/runtime.go
@@ -1090,17 +1090,17 @@ func init() {
// materialrequest.RejectReasonValidator is a validator for the "rejectReason" field. It is called by the builders before save.
materialrequest.RejectReasonValidator = materialrequestDescRejectReason.Validators[0].(func(string) error)
// materialrequestDescOperator is the schema descriptor for operator field.
- materialrequestDescOperator := materialrequestFields[19].Descriptor()
+ materialrequestDescOperator := materialrequestFields[20].Descriptor()
// materialrequest.DefaultOperator holds the default value on creation for the operator field.
materialrequest.DefaultOperator = materialrequestDescOperator.Default.(string)
// materialrequest.OperatorValidator is a validator for the "operator" field. It is called by the builders before save.
materialrequest.OperatorValidator = materialrequestDescOperator.Validators[0].(func(string) error)
// materialrequestDescCreatedAt is the schema descriptor for createdAt field.
- materialrequestDescCreatedAt := materialrequestFields[20].Descriptor()
+ materialrequestDescCreatedAt := materialrequestFields[21].Descriptor()
// materialrequest.DefaultCreatedAt holds the default value on creation for the createdAt field.
materialrequest.DefaultCreatedAt = materialrequestDescCreatedAt.Default.(func() time.Time)
// materialrequestDescUpdatedAt is the schema descriptor for updatedAt field.
- materialrequestDescUpdatedAt := materialrequestFields[21].Descriptor()
+ materialrequestDescUpdatedAt := materialrequestFields[22].Descriptor()
// materialrequest.DefaultUpdatedAt holds the default value on creation for the updatedAt field.
materialrequest.DefaultUpdatedAt = materialrequestDescUpdatedAt.Default.(func() time.Time)
// materialrequest.UpdateDefaultUpdatedAt holds the default value on update for the updatedAt field.
@@ -1860,21 +1860,21 @@ func init() {
// workorder.CreatedByValidator is a validator for the "createdBy" field. It is called by the builders before save.
workorder.CreatedByValidator = workorderDescCreatedBy.Validators[0].(func(string) error)
// workorderDescProductProcessId is the schema descriptor for productProcessId field.
- workorderDescProductProcessId := workorderFields[15].Descriptor()
+ workorderDescProductProcessId := workorderFields[14].Descriptor()
// workorder.DefaultProductProcessId holds the default value on creation for the productProcessId field.
workorder.DefaultProductProcessId = workorderDescProductProcessId.Default.(int)
// workorderDescStatus is the schema descriptor for status field.
- workorderDescStatus := workorderFields[16].Descriptor()
+ workorderDescStatus := workorderFields[15].Descriptor()
// workorder.DefaultStatus holds the default value on creation for the status field.
workorder.DefaultStatus = workorderDescStatus.Default.(string)
// workorder.StatusValidator is a validator for the "status" field. It is called by the builders before save.
workorder.StatusValidator = workorderDescStatus.Validators[0].(func(string) error)
// workorderDescCreatedAt is the schema descriptor for createdAt field.
- workorderDescCreatedAt := workorderFields[22].Descriptor()
+ workorderDescCreatedAt := workorderFields[21].Descriptor()
// workorder.DefaultCreatedAt holds the default value on creation for the createdAt field.
workorder.DefaultCreatedAt = workorderDescCreatedAt.Default.(func() time.Time)
// workorderDescUpdatedAt is the schema descriptor for updatedAt field.
- workorderDescUpdatedAt := workorderFields[23].Descriptor()
+ workorderDescUpdatedAt := workorderFields[22].Descriptor()
// workorder.DefaultUpdatedAt holds the default value on creation for the updatedAt field.
workorder.DefaultUpdatedAt = workorderDescUpdatedAt.Default.(func() time.Time)
// workorder.UpdateDefaultUpdatedAt holds the default value on update for the updatedAt field.
diff --git a/bj_power_mes/ent/workorder.go b/bj_power_mes/ent/workorder.go
index 71a66a0..be0038d 100644
--- a/bj_power_mes/ent/workorder.go
+++ b/bj_power_mes/ent/workorder.go
@@ -42,8 +42,6 @@ type WorkOrder struct {
ProductSerial string `json:"productSerial,omitempty"`
// 创建人
CreatedBy string `json:"createdBy,omitempty"`
- // 完成日期(必填)
- DueDate *time.Time `json:"dueDate,omitempty"`
// 工艺组合 [{flowId,stationNo}] 按工位号升序
FlowCombination []map[string]int `json:"flowCombination,omitempty"`
// 来源产品工艺ID(0=无来源)
@@ -78,7 +76,7 @@ func (*WorkOrder) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullInt64)
case workorder.FieldWorkOrderNo, workorder.FieldProductCode, workorder.FieldProductName, workorder.FieldContractNo, workorder.FieldOwnershipType, workorder.FieldProjectNo, workorder.FieldProductSerial, workorder.FieldCreatedBy, workorder.FieldStatus:
values[i] = new(sql.NullString)
- case workorder.FieldDueDate, workorder.FieldPlanStart, workorder.FieldPlanEnd, workorder.FieldCompletedAt, workorder.FieldActualStart, workorder.FieldCreatedAt, workorder.FieldUpdatedAt:
+ case workorder.FieldPlanStart, workorder.FieldPlanEnd, workorder.FieldCompletedAt, workorder.FieldActualStart, workorder.FieldCreatedAt, workorder.FieldUpdatedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
@@ -173,13 +171,6 @@ func (_m *WorkOrder) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.CreatedBy = value.String
}
- case workorder.FieldDueDate:
- if value, ok := values[i].(*sql.NullTime); !ok {
- return fmt.Errorf("unexpected type %T for field dueDate", values[i])
- } else if value.Valid {
- _m.DueDate = new(time.Time)
- *_m.DueDate = value.Time
- }
case workorder.FieldFlowCombination:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field flowCombination", values[i])
@@ -321,11 +312,6 @@ func (_m *WorkOrder) String() string {
builder.WriteString("createdBy=")
builder.WriteString(_m.CreatedBy)
builder.WriteString(", ")
- if v := _m.DueDate; v != nil {
- builder.WriteString("dueDate=")
- builder.WriteString(v.Format(time.ANSIC))
- }
- builder.WriteString(", ")
builder.WriteString("flowCombination=")
builder.WriteString(fmt.Sprintf("%v", _m.FlowCombination))
builder.WriteString(", ")
diff --git a/bj_power_mes/ent/workorder/where.go b/bj_power_mes/ent/workorder/where.go
index 4168d0c..e32da5b 100644
--- a/bj_power_mes/ent/workorder/where.go
+++ b/bj_power_mes/ent/workorder/where.go
@@ -114,11 +114,6 @@ func CreatedBy(v string) predicate.WorkOrder {
return predicate.WorkOrder(sql.FieldEQ(FieldCreatedBy, v))
}
-// DueDate applies equality check predicate on the "dueDate" field. It's identical to DueDateEQ.
-func DueDate(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldEQ(FieldDueDate, v))
-}
-
// ProductProcessId applies equality check predicate on the "productProcessId" field. It's identical to ProductProcessIdEQ.
func ProductProcessId(v int) predicate.WorkOrder {
return predicate.WorkOrder(sql.FieldEQ(FieldProductProcessId, v))
@@ -839,56 +834,6 @@ func CreatedByContainsFold(v string) predicate.WorkOrder {
return predicate.WorkOrder(sql.FieldContainsFold(FieldCreatedBy, v))
}
-// DueDateEQ applies the EQ predicate on the "dueDate" field.
-func DueDateEQ(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldEQ(FieldDueDate, v))
-}
-
-// DueDateNEQ applies the NEQ predicate on the "dueDate" field.
-func DueDateNEQ(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldNEQ(FieldDueDate, v))
-}
-
-// DueDateIn applies the In predicate on the "dueDate" field.
-func DueDateIn(vs ...time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldIn(FieldDueDate, vs...))
-}
-
-// DueDateNotIn applies the NotIn predicate on the "dueDate" field.
-func DueDateNotIn(vs ...time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldNotIn(FieldDueDate, vs...))
-}
-
-// DueDateGT applies the GT predicate on the "dueDate" field.
-func DueDateGT(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldGT(FieldDueDate, v))
-}
-
-// DueDateGTE applies the GTE predicate on the "dueDate" field.
-func DueDateGTE(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldGTE(FieldDueDate, v))
-}
-
-// DueDateLT applies the LT predicate on the "dueDate" field.
-func DueDateLT(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldLT(FieldDueDate, v))
-}
-
-// DueDateLTE applies the LTE predicate on the "dueDate" field.
-func DueDateLTE(v time.Time) predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldLTE(FieldDueDate, v))
-}
-
-// DueDateIsNil applies the IsNil predicate on the "dueDate" field.
-func DueDateIsNil() predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldIsNull(FieldDueDate))
-}
-
-// DueDateNotNil applies the NotNil predicate on the "dueDate" field.
-func DueDateNotNil() predicate.WorkOrder {
- return predicate.WorkOrder(sql.FieldNotNull(FieldDueDate))
-}
-
// FlowCombinationIsNil applies the IsNil predicate on the "flowCombination" field.
func FlowCombinationIsNil() predicate.WorkOrder {
return predicate.WorkOrder(sql.FieldIsNull(FieldFlowCombination))
diff --git a/bj_power_mes/ent/workorder/workorder.go b/bj_power_mes/ent/workorder/workorder.go
index 37f3c65..21b0244 100644
--- a/bj_power_mes/ent/workorder/workorder.go
+++ b/bj_power_mes/ent/workorder/workorder.go
@@ -37,8 +37,6 @@ const (
FieldProductSerial = "product_serial"
// FieldCreatedBy holds the string denoting the createdby field in the database.
FieldCreatedBy = "created_by"
- // FieldDueDate holds the string denoting the duedate field in the database.
- FieldDueDate = "due_date"
// FieldFlowCombination holds the string denoting the flowcombination field in the database.
FieldFlowCombination = "flow_combination"
// FieldProductProcessId holds the string denoting the productprocessid field in the database.
@@ -78,7 +76,6 @@ var Columns = []string{
FieldProjectNo,
FieldProductSerial,
FieldCreatedBy,
- FieldDueDate,
FieldFlowCombination,
FieldProductProcessId,
FieldStatus,
@@ -222,11 +219,6 @@ func ByCreatedBy(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedBy, opts...).ToFunc()
}
-// ByDueDate orders the results by the dueDate field.
-func ByDueDate(opts ...sql.OrderTermOption) OrderOption {
- return sql.OrderByField(FieldDueDate, opts...).ToFunc()
-}
-
// ByProductProcessId orders the results by the productProcessId field.
func ByProductProcessId(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldProductProcessId, opts...).ToFunc()
diff --git a/bj_power_mes/ent/workorder_create.go b/bj_power_mes/ent/workorder_create.go
index 8b5a20c..fef7d55 100644
--- a/bj_power_mes/ent/workorder_create.go
+++ b/bj_power_mes/ent/workorder_create.go
@@ -172,20 +172,6 @@ func (_c *WorkOrderCreate) SetNillableCreatedBy(v *string) *WorkOrderCreate {
return _c
}
-// SetDueDate sets the "dueDate" field.
-func (_c *WorkOrderCreate) SetDueDate(v time.Time) *WorkOrderCreate {
- _c.mutation.SetDueDate(v)
- return _c
-}
-
-// SetNillableDueDate sets the "dueDate" field if the given value is not nil.
-func (_c *WorkOrderCreate) SetNillableDueDate(v *time.Time) *WorkOrderCreate {
- if v != nil {
- _c.SetDueDate(*v)
- }
- return _c
-}
-
// SetFlowCombination sets the "flowCombination" field.
func (_c *WorkOrderCreate) SetFlowCombination(v []map[string]int) *WorkOrderCreate {
_c.mutation.SetFlowCombination(v)
@@ -586,10 +572,6 @@ func (_c *WorkOrderCreate) createSpec() (*WorkOrder, *sqlgraph.CreateSpec) {
_spec.SetField(workorder.FieldCreatedBy, field.TypeString, value)
_node.CreatedBy = value
}
- if value, ok := _c.mutation.DueDate(); ok {
- _spec.SetField(workorder.FieldDueDate, field.TypeTime, value)
- _node.DueDate = &value
- }
if value, ok := _c.mutation.FlowCombination(); ok {
_spec.SetField(workorder.FieldFlowCombination, field.TypeJSON, value)
_node.FlowCombination = value
diff --git a/bj_power_mes/ent/workorder_update.go b/bj_power_mes/ent/workorder_update.go
index bba06c5..639c59b 100644
--- a/bj_power_mes/ent/workorder_update.go
+++ b/bj_power_mes/ent/workorder_update.go
@@ -226,26 +226,6 @@ func (_u *WorkOrderUpdate) SetNillableCreatedBy(v *string) *WorkOrderUpdate {
return _u
}
-// SetDueDate sets the "dueDate" field.
-func (_u *WorkOrderUpdate) SetDueDate(v time.Time) *WorkOrderUpdate {
- _u.mutation.SetDueDate(v)
- return _u
-}
-
-// SetNillableDueDate sets the "dueDate" field if the given value is not nil.
-func (_u *WorkOrderUpdate) SetNillableDueDate(v *time.Time) *WorkOrderUpdate {
- if v != nil {
- _u.SetDueDate(*v)
- }
- return _u
-}
-
-// ClearDueDate clears the value of the "dueDate" field.
-func (_u *WorkOrderUpdate) ClearDueDate() *WorkOrderUpdate {
- _u.mutation.ClearDueDate()
- return _u
-}
-
// SetFlowCombination sets the "flowCombination" field.
func (_u *WorkOrderUpdate) SetFlowCombination(v []map[string]int) *WorkOrderUpdate {
_u.mutation.SetFlowCombination(v)
@@ -560,12 +540,6 @@ func (_u *WorkOrderUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.CreatedBy(); ok {
_spec.SetField(workorder.FieldCreatedBy, field.TypeString, value)
}
- if value, ok := _u.mutation.DueDate(); ok {
- _spec.SetField(workorder.FieldDueDate, field.TypeTime, value)
- }
- if _u.mutation.DueDateCleared() {
- _spec.ClearField(workorder.FieldDueDate, field.TypeTime)
- }
if value, ok := _u.mutation.FlowCombination(); ok {
_spec.SetField(workorder.FieldFlowCombination, field.TypeJSON, value)
}
@@ -840,26 +814,6 @@ func (_u *WorkOrderUpdateOne) SetNillableCreatedBy(v *string) *WorkOrderUpdateOn
return _u
}
-// SetDueDate sets the "dueDate" field.
-func (_u *WorkOrderUpdateOne) SetDueDate(v time.Time) *WorkOrderUpdateOne {
- _u.mutation.SetDueDate(v)
- return _u
-}
-
-// SetNillableDueDate sets the "dueDate" field if the given value is not nil.
-func (_u *WorkOrderUpdateOne) SetNillableDueDate(v *time.Time) *WorkOrderUpdateOne {
- if v != nil {
- _u.SetDueDate(*v)
- }
- return _u
-}
-
-// ClearDueDate clears the value of the "dueDate" field.
-func (_u *WorkOrderUpdateOne) ClearDueDate() *WorkOrderUpdateOne {
- _u.mutation.ClearDueDate()
- return _u
-}
-
// SetFlowCombination sets the "flowCombination" field.
func (_u *WorkOrderUpdateOne) SetFlowCombination(v []map[string]int) *WorkOrderUpdateOne {
_u.mutation.SetFlowCombination(v)
@@ -1204,12 +1158,6 @@ func (_u *WorkOrderUpdateOne) sqlSave(ctx context.Context) (_node *WorkOrder, er
if value, ok := _u.mutation.CreatedBy(); ok {
_spec.SetField(workorder.FieldCreatedBy, field.TypeString, value)
}
- if value, ok := _u.mutation.DueDate(); ok {
- _spec.SetField(workorder.FieldDueDate, field.TypeTime, value)
- }
- if _u.mutation.DueDateCleared() {
- _spec.ClearField(workorder.FieldDueDate, field.TypeTime)
- }
if value, ok := _u.mutation.FlowCombination(); ok {
_spec.SetField(workorder.FieldFlowCombination, field.TypeJSON, value)
}
diff --git a/bj_power_mes/frontend/src/help.js b/bj_power_mes/frontend/src/help.js
index 2406ade..1cb1356 100644
--- a/bj_power_mes/frontend/src/help.js
+++ b/bj_power_mes/frontend/src/help.js
@@ -43,7 +43,7 @@ export const helpWorkOrder = {
{ name: '数量', source: '手工填写整数。', purpose: '本工单生产总数量(合同台数),决定需求量与排产上限', fill: '整数 ≥1,如 100' },
{ name: '工序工位', source: '按产品工艺的工序顺序,每道工序从下拉选一个工位(候选=工位管理里绑定该工序的启用工位)。保存为 [{flowId,stationNo}]。', purpose: '本工单的执行路线;自动排产/备料拆分/产线下发均按此组合派生', fill: '系统按工艺顺序自动推荐工位(第1道取候选最小工位,第N道取大于上一道已选且候选最小的工位);可逐道修改,下拉只列合法候选(第N道候选=绑定该工序且工位号>第N-1道已选);工位号须按工序顺序严格递增' },
{ name: '状态', source: '新建时选"已创建",后续由流程推进。', purpose: '工单生命周期:创建→发布→生产→完成', fill: '新建时选"已创建";也可在列表操作列点「状态」快捷流转(发布/开工/完工)' },
- { name: '要求完成日期', source: '手工填写,建单/编辑时必填。', purpose: '记录工单要求/承诺完成日期,用于交付与绩效统计;与「实际完成」(系统记录的真实完工时间)是两个独立字段', fill: '建单时选择日期,必填' },
+ { name: '计划开始 / 计划完成', source: '建单/编辑时选填(计划开始可空)。', purpose: '记录工单计划交付窗口;系统不再单独维护「要求完成日期」字段(已移除)', fill: '建单时选择日期' },
{ name: '时间字段口径', source: '建单填写 + 系统自动记录。', purpose: '计划开始/计划完成=建单填写的计划区间;实际开始=首次"下发并开工"的时间(系统落库);实际完成=本工单全部工件报工完成、置"已完成"的时间(系统落库)。("完成日期"是要求/承诺完成日期,属上一条独立字段)', fill: '建单填计划开始/计划完成(选填);实际开始/实际完成由系统自动写,无需手填' },
{ name: '创建人', source: '系统自动记录(当前登录账号)。', purpose: '追溯工单由谁创建', fill: '只读,自动带入' }
]
diff --git a/bj_power_mes/frontend/src/pages/AlertRule.vue b/bj_power_mes/frontend/src/pages/AlertRule.vue
index 7581af1..ba23b10 100644
--- a/bj_power_mes/frontend/src/pages/AlertRule.vue
+++ b/bj_power_mes/frontend/src/pages/AlertRule.vue
@@ -63,8 +63,10 @@ import { helpAlertRule } from '../help'
// 各类型规则含义与阈值单位(前端展示用,阈值统一存 float;0=未配置不触发)
const ruleMeta = {
inspection_ng: { label: '检验不合格', unit: '', note: '事件触发型:出现检验不合格即报警,阈值暂不使用' },
- inventory_low: { label: '库存低于阈值', unit: '件', note: '当某物料可用库存低于该件数时报警' },
- task_overdue: { label: '任务超期', unit: '小时', note: '当工单超过该小时数仍未完工时报警' }
+ inventory_low: { label: '库存低于阈值', unit: '件', note: '当某物料可用库存低于该件数时报警(库存真源在 WMS,常规缺货预警用 WMS 侧规则)' },
+ task_overdue: { label: '任务超期', unit: '小时', note: '当工单计划结束时间已过且未完工超过该小时数时报警;0=任何超期即报' },
+ call_overdue: { label: '叫料备料超时', unit: '小时', note: '叫料单待备料(PENDING)超过该小时数即报警;0=超 1 小时即报' },
+ agv_failed: { label: 'AGV任务失败', unit: '', note: '事件型:AGV 派车任务失败(近24小时内)即报警,阈值不使用' }
}
const rules = ref([])
diff --git a/bj_power_mes/frontend/src/pages/DailyPlan.vue b/bj_power_mes/frontend/src/pages/DailyPlan.vue
index 4c06f20..c29e3db 100644
--- a/bj_power_mes/frontend/src/pages/DailyPlan.vue
+++ b/bj_power_mes/frontend/src/pages/DailyPlan.vue
@@ -272,7 +272,6 @@
{{ productNameOfUnplanned(row) }}
-
{{ woStatusText(row.status) }}
@@ -336,7 +335,7 @@ const total = ref(0)
const page = ref(1)
const pageSize = ref(50)
const productTypes = ref([])
-const dialog = reactive({ show: false, id: 0, orderNo: '', planDate: '', planRange: [], mode: 'AVG', planQty: 1, productType: '', productCode: '', productName: '', woQty: '', woStart: '', woDue: '', stationPlanQty: {}, combination: [] })
+const dialog = reactive({ show: false, id: 0, orderNo: '', planDate: '', planRange: [], mode: 'AVG', planQty: 1, productType: '', productCode: '', productName: '', woQty: '', woStart: '', woPlanEnd: '', stationPlanQty: {}, combination: [] })
// 工位号→接驳台编码、工位号→名称
const stationDockMap = ref({})
@@ -583,7 +582,7 @@ async function loadWorkOrderInfo() {
const wo = await ensureWorkOrder(dialog.orderNo)
if (!wo) {
dialog.productType = ''; dialog.productCode = ''; dialog.productName = ''; dialog.woQty = ''
- dialog.combination = []; dialog.woStart = ''; dialog.woDue = ''
+ dialog.combination = []; dialog.woStart = ''; dialog.woPlanEnd = ''
return
}
dialog.productCode = wo.productCode || ''
@@ -593,18 +592,18 @@ async function loadWorkOrderInfo() {
const pt = productTypes.value.find((p) => p.id === wo.productTypeId)
dialog.productType = pt ? (pt.name + (pt.code ? ' / ' + pt.code : '')) : ''
dialog.woStart = wo.planStart ? String(wo.planStart).slice(0, 10) : ''
- dialog.woDue = wo.dueDate ? String(wo.dueDate).slice(0, 10) : ''
+ dialog.woPlanEnd = wo.planEnd ? String(wo.planEnd).slice(0, 10) : ''
if (!dialog.id) {
const today = todayStr()
const start = dialog.woStart || today
- const end = dialog.woDue || addDays(7)
+ const end = dialog.woPlanEnd || addDays(7)
// 起期不晚于止期;若起期晚于止期(如止期已过期)则退化为单日,避免 el-date-picker 报错
dialog.planRange = start <= end ? [start, end] : [end, end]
}
}
async function onOrderChange() {
await loadWorkOrderInfo()
- if (dialog.id && (dialog.woStart || dialog.woDue)) dialog.planDate = dialog.woStart || dialog.woDue
+ if (dialog.id && (dialog.woStart || dialog.woPlanEnd)) dialog.planDate = dialog.woStart || dialog.woPlanEnd
}
function openAdd(presetOrderNo) {
Object.assign(dialog, {
@@ -624,7 +623,7 @@ function openEdit(row) {
loadAlloc()
}
function warnOutOfWindow(dates) {
- const s = dialog.woStart || ''; const e = dialog.woDue || ''
+ const s = dialog.woStart || ''; const e = dialog.woPlanEnd || ''
if ((!s && !e) || !dialog.orderNo) return
if (dates.some((d) => (s && d < s) || (e && d > e))) ElMessage.warning('所选日期超出工单执行期间')
}
diff --git a/bj_power_mes/frontend/src/pages/MaterialRequest.vue b/bj_power_mes/frontend/src/pages/MaterialRequest.vue
index 3cdceba..cf747e6 100644
--- a/bj_power_mes/frontend/src/pages/MaterialRequest.vue
+++ b/bj_power_mes/frontend/src/pages/MaterialRequest.vue
@@ -49,6 +49,12 @@
+
+
+ {{ borrowText(row) }}
+ —
+
+
{{ Number(row.sentQty || 0) > 0 ? fmtQty(row.sentQty) : '—' }}
@@ -103,6 +109,21 @@ const STATUS_TAG = {
const statusText = (s) => STATUS_TEXT[s] || s || '—'
const statusTag = (s) => STATUS_TAG[s] || 'info'
+// 借料来源:material_request.borrow_from(stationNo→借用量);本工位自取不计,仅展示真正借出的兄弟工位
+function hasBorrow(row) {
+ const b = row.borrowFrom || {}
+ const self = String(row.stationNo)
+ return Object.entries(b).some(([k, v]) => Number(v) > 0 && String(k) !== self)
+}
+function borrowText(row) {
+ const b = row.borrowFrom || {}
+ const self = String(row.stationNo)
+ const parts = Object.entries(b)
+ .filter(([k, v]) => Number(v) > 0 && String(k) !== self)
+ .map(([k, v]) => `工位${k}:${fmtQty(v)}`)
+ return parts.length ? parts.join(',') : '—'
+}
+
function fmtQty(v) {
const n = Number(v || 0)
return Number.isInteger(n) ? String(n) : n.toFixed(2)
@@ -116,13 +137,13 @@ async function load() {
async function exportCsv() {
if (!(await confirmExport(list.value.length, '叫料单记录'))) return
const header = ['叫料单号', '来源', '图号', '物料名称', '单位', '序列号方式', '工位', '接驳台',
- '请求量', '实发量', '退库量', '跨日', 'WMS出库单号', '状态', '驳回理由', '数量不符单号', '操作人']
+ '借料来源', '请求量', '实发量', '退库量', '跨日', 'WMS出库单号', '状态', '驳回理由', '数量不符单号', '操作人']
const srcOf = (r) => (r.source === 'REFILL' ? '数量不符补发' : '工位叫料')
const lines = [header.join(',')]
for (const r of list.value) {
const cells = [
r.requestNo, srcOf(r), r.materialCode, r.materialName, r.unit,
- r.snMode === 1 ? '序列号=是' : '序列号=否', r.stationNo, r.targetDock,
+ r.snMode === 1 ? '序列号=是' : '序列号=否', r.stationNo, r.targetDock, borrowText(r),
r.reqQty, r.sentQty, r.returnedQty, r.crossDay ? '非当日' : '',
r.outboundNo, statusText(r.status), r.rejectReason, r.refReportNo, r.operator
]
diff --git a/bj_power_mes/frontend/src/pages/ProductProcess.vue b/bj_power_mes/frontend/src/pages/ProductProcess.vue
index 5c5fcde..6cb8d32 100644
--- a/bj_power_mes/frontend/src/pages/ProductProcess.vue
+++ b/bj_power_mes/frontend/src/pages/ProductProcess.vue
@@ -1,6 +1,8 @@
+
diff --git a/bj_power_mes/frontend/src/pages/ProductType.vue b/bj_power_mes/frontend/src/pages/ProductType.vue
index d4d8305..1ea26a0 100644
--- a/bj_power_mes/frontend/src/pages/ProductType.vue
+++ b/bj_power_mes/frontend/src/pages/ProductType.vue
@@ -30,7 +30,7 @@
重置
新增物料档案
模板下载
- Excel 导入
+ Excel 导入
导出
@@ -255,30 +255,48 @@ async function downloadTemplate() {
a.click()
URL.revokeObjectURL(a.href)
} catch (e) {
- ElMessage.error('模板下载失败')
+ ElMessage.error(e?.response?.data?.message || '模板下载失败:网络异常,请稍后重试')
}
}
-// Excel 导入:隐藏 file input 触发 → 上传 → 展示结果(成功/失败行明细)
+// Excel 导入(2026-11-02 条目16:与 WMS 物料档案导入同风格):
+// 选文件 → 二次确认(文件名+影响说明)→ 上传 → 结构化结果(成功条数 / 失败行明细弹窗)→ 刷新列表
const importInput = ref(null)
+const importing = ref(false)
function triggerImport() { importInput.value && importInput.value.click() }
async function onImportFile(e) {
const file = e.target.files && e.target.files[0]
if (e.target.value) e.target.value = '' // 允许重复选同一文件
if (!file) return
+ try {
+ await ElMessageBox.confirm(
+ `确认导入物料文件「${file.name}」?导入将批量写入物料档案,失败行明细将在导入后逐行列出。`,
+ '批量导入确认', { type: 'warning', confirmButtonText: '确认导入', cancelButtonText: '取消' })
+ } catch {
+ return
+ }
+ importing.value = true
const fd = new FormData()
fd.append('file', file)
try {
const res = await request.post('/product-types/import', fd, { headers: { 'Content-Type': 'multipart/form-data' } })
const r = res || {}
- const detail = (r.errors || []).slice(0, 8).map((x) => `第${x.row}行:${x.message}`).join('\n')
- ElMessage.success(`导入完成:成功 ${r.success || 0} 行,失败 ${r.failed || 0} 行${detail ? '\n' + detail : ''}`)
- if ((r.failed || 0) > 0) {
- console.warn('物料档案导入失败明细', r.errors)
+ const errs = r.errors || []
+ if (errs.length) {
+ const lines = errs.slice(0, 10).map((x) => `第${x.row}行 ${x.materialCode || ''}:${x.message}`).join(';')
+ ElMessageBox.alert(
+ lines + (errs.length > 10 ? ` …(共 ${errs.length} 条失败明细,请修正后重新导入失败行)` : '(请修正后重新导入失败行)'),
+ `导入完成:成功 ${r.success || 0} 行,失败 ${errs.length} 行`,
+ { type: 'warning', confirmButtonText: '知道了' }
+ ).catch(() => {})
+ } else {
+ ElMessage.success(`导入成功 ${r.success || 0} 条`)
}
load()
} catch (err) {
ElMessage.error(err?.response?.data?.message || err?.message || '导入失败')
+ } finally {
+ importing.value = false
}
}
async function exportXlsx() {
diff --git a/bj_power_mes/frontend/src/pages/Settings.vue b/bj_power_mes/frontend/src/pages/Settings.vue
index b57f78c..fd28ce2 100644
--- a/bj_power_mes/frontend/src/pages/Settings.vue
+++ b/bj_power_mes/frontend/src/pages/Settings.vue
@@ -35,6 +35,10 @@
1=允许(默认,叫料池含非今日排产时工位端预警提示,仓库可正常发也可按「非当日」驳回);0=禁止
+
+
+ 1=允许(默认):工位自身额度不足时,可手动从「同工艺其他工位」的剩余额度借料;0=禁止,超额叫料直接拒绝
+
开启(默认)后,拧紧扭矩不合格立即在预警中心产生报警;关闭则只记录不合格标记、不弹报警
@@ -95,7 +99,7 @@ const loading = ref(false)
const saving = ref(false)
const testing = ref(false)
const testMsg = ref('')
-const form = reactive({ wmsBaseURL: '', demandDays: 5, extrapWindow: 3, extrapCap: 365, logRetentionDays: 0, pipelineCache: 0, allowCrossDay: 1, torqueNgAlert: true, dashboardRefreshSeconds: 5, archiveRemindDays: 7, dashboardTitle: '', dashboardVoice: true })
+const form = reactive({ wmsBaseURL: '', demandDays: 5, extrapWindow: 3, extrapCap: 365, logRetentionDays: 0, pipelineCache: 0, allowCrossDay: 1, allowBorrow: 1, torqueNgAlert: true, dashboardRefreshSeconds: 5, archiveRemindDays: 7, dashboardTitle: '', dashboardVoice: true })
const info = ref({})
async function load() {
@@ -110,6 +114,7 @@ async function load() {
logRetentionDays: data.logRetentionDays ?? 0,
pipelineCache: data.pipelineCache ?? 0,
allowCrossDay: data.allowCrossDay ?? 1,
+ allowBorrow: data.allowBorrow ?? 1,
torqueNgAlert: data.torqueNgAlert ?? true,
dashboardRefreshSeconds: data.dashboardRefreshSeconds ?? 5,
archiveRemindDays: data.archiveRemindDays ?? 7,
diff --git a/bj_power_mes/frontend/src/pages/Station.vue b/bj_power_mes/frontend/src/pages/Station.vue
index 1235ec1..16ca0f5 100644
--- a/bj_power_mes/frontend/src/pages/Station.vue
+++ b/bj_power_mes/frontend/src/pages/Station.vue
@@ -94,20 +94,13 @@
全部显示
-
+
-
+
编辑
- stationCommand(row, c)">
- 更多 ▾
-
-
- 页签
- {{ row.status === 'ENABLED' ? '停用' : '启用' }}
- 删除
-
-
-
+ 页签
+ {{ row.status === 'ENABLED' ? '停用' : '启用' }}
+ 删除
@@ -116,21 +109,25 @@
-
+
物理工位 1~12 为硬件锁定,不可新增
- 1~12 为物理产线工位(已锁定),0 为虚拟工位,≥13 为扩展工位。创建后不可修改。
+ 1~12 为物理产线工位(已锁定,中间连续、不可插入虚拟工位);负数(-1、-2…)为产线前段虚拟工位(排在工位1之前);≥13 为扩展工位。创建后不可修改。
- {{ dlg.stationType === 'OFFLINE' ? '线下位(虚拟,不连 PLC)' : '线上位(连 PLC)' }}
+
+
+
+
+ {{ dlg.stationType === 'OFFLINE' ? '线下位(虚拟,不连 PLC)' : '线上位(连 PLC)' }}
- 工位类型由系统按产线初始配置固定,不可修改。
+ {{ dlg.isBuiltin ? '内置工位类型由产线初始配置固定,不可修改。' : '非内置工位可调整类型(看板按「线下位」统计虚拟工位)。' }}
@@ -232,12 +229,7 @@ async function toggleStationStatus(row) {
load()
}
-// 操作列「更多 ▾」分发:页签 / 停用·启用 / 删除(启停互斥:启用显「停用」、停用显「启用」)
-function stationCommand(row, c) {
- if (c === 'tabs') openTabs(row)
- else if (c === 'disable' || c === 'enable') toggleStationStatus(row)
- else if (c === 'del') remove(row)
-}
+// 操作列按钮已外露(2026-11-02):页签/停用·启用/删除直接绑定,不再经"更多"下拉分发
const dlg = reactive({ show: false, isAdd: false, title: '', id: 0, stationNo: 1, name: '', stationType: 'OFFLINE', isBuiltin: false })
diff --git a/bj_power_mes/frontend/src/pages/WorkOrder.vue b/bj_power_mes/frontend/src/pages/WorkOrder.vue
index 8d37dfb..b96b045 100644
--- a/bj_power_mes/frontend/src/pages/WorkOrder.vue
+++ b/bj_power_mes/frontend/src/pages/WorkOrder.vue
@@ -19,10 +19,6 @@
-
-
-
@@ -69,9 +65,6 @@
{{ fmtTime(row.createdAt) }}
-
- {{ fmtDateOnly(row.dueDate) }}
-
{{ fmtDateOnly(row.planStart) }}
@@ -144,16 +137,12 @@
:title="ppWarnings.length > 1 ? ppWarnings.map((w, i) => (i + 1) + '. ' + w).join(';') : ppWarnings[0]" />
- 已按产品工艺自动推荐每道工序的工位(贪心:工序顺序 + 工位号严格递增),可逐道改;改某道后后续候选自动重算。
- 查看产品工艺/路线卡
+ 已按该产品的「产品工艺」自动为每道工序推荐一个执行工位(工件在产线上不回头,后道工位号必须大于前道);每道可改,改后后续工序的候选自动更新。
+ 查看产品工艺
-
-
-
@@ -162,6 +151,8 @@
+
工序
工序(工艺)
- 工位(按工序顺序递增)
+ 工位(可多选,按工序顺序递增)
第 {{ i + 1 }} 道
{{ r.flowName || ('工序' + r.flowId) }}
-
+
@@ -187,9 +179,9 @@
执行路线:{{ routeText }}
- (执行顺序=工位号升序,可跳过未选工位)
+ (按工位号从小到大依次执行)
- 系统按「工序顺序 + 工位号严格递增(产线单向不回头)」自动推荐默认工位;改某道后,后续工序候选自动重算,非法组合无法选到。保存时后端仍会二次校验。
+ 每道工序执行一个工位;推荐规则与组合校验说明见「产品工艺」页顶部说明。
该产品暂无产品工艺或工艺未配置工序,暂无可推荐的工序工位。可到「产品工艺」页创建后重新选择产品型号;不选产品工艺时工单可不带工艺组合(排产/开工前须配置)。
@@ -206,7 +198,7 @@
+ :title="`项目开始:${fmtDateOnly(sched.planStart)} 工单数量:${sched.quantity} 已完工:${sched.finishedNum}`" />
@@ -267,7 +259,7 @@
+ :empty-text="usage.emptyTip || '该工单工艺组合未配置物料清单'">
@@ -345,7 +337,7 @@
{{ detail.row.scheduledQty ?? 0 }} 台
{{ detail.row.remainQty ?? 0 }} 台
{{ detail.row.productSerial || '-' }}
- {{ fmtDateOnly(detail.row.dueDate) }}
+ {{ fmtDateOnly(detail.row.planEnd) }}
{{ fmtDateOnly(detail.row.planStart) }}
{{ fmtDateOnly(detail.row.planEnd) }}
{{ fmtDateOnly(detail.row.actualStart) }}
@@ -437,7 +429,7 @@ const ownershipText = (t) => (ownershipOptions.find((o) => o.v === t) || {}).l |
// 工件SN列表(详情抽屉):状态/当前工位/类型(sn_mode:1=序列号=是 2=序列号=否,取自产品图号对应物料档案)
const pieceStatusMap = { NEW: '待上线', ONLINE: '已上线', PROCESSING: '在制', SEMI_STORED: '半成品入库', DONE: '完工', SCRAPPED: '报废' }
const pieceStatusText = (s) => pieceStatusMap[s] || s
-const stationText = (n) => (n > 0 ? '工位' + n : '-')
+const stationText = (n) => (n !== 0 ? '工位' + n : '-')
const snModeText = (m) => (m === 1 ? '序列号=是' : m === 2 ? '序列号=否' : '-')
// 状态流转:给出当前状态可执行的下一个动作(按钮文案随当前状态变化,方案 A)
@@ -456,17 +448,18 @@ function statusActions(status) {
return map[status] || []
}
-const query = reactive({ orderNo: '', productCode: '', productName: '', contractNo: '', ownershipType: '', status: '', dueRange: null })
+const query = reactive({ orderNo: '', productCode: '', productName: '', contractNo: '', ownershipType: '', status: '' })
function resetFilters() {
- Object.assign(query, { orderNo: '', productCode: '', productName: '', contractNo: '', ownershipType: '', status: '', dueRange: null })
+ Object.assign(query, { orderNo: '', productCode: '', productName: '', contractNo: '', ownershipType: '', status: '' })
load()
}
const list = ref([])
const productTypes = ref([])
// 工序工位:数据源=工位(含 flowId/flowName/stationNo/status/name)+ 产品工艺工序顺序
-// 模型=「每道工序选一个工位」(2026-10-20 工单建单需求:自动推荐+用户可改+动态约束)
-// processRows 每行 { seq, flowId, flowName, stationNo, options:[{stationNo,name}], error }
+// 模型=「每道工序可绑定多个有序工位」(2026-11-02 多工位同工序:工件按工位号升序依次经过各工位,
+// 同一工序的多个工位整体须排在上一道工序之后;产线单向不回头)。
+// processRows 每行 { seq, flowId, flowName, stationNos:[int], options:[{stationNo,name}], error }
const stations = ref([])
const flows = ref([])
const processRows = ref([])
@@ -483,8 +476,13 @@ function boundStations(flowId) {
.sort((a, b) => a.stationNo - b.stationNo)
}
-// 按产品工艺工序顺序构建工序行,并贪心填默认工位:
-// 第1道取候选最小工位;第N道(N≥2)取「大于第N-1道已选工位」的候选最小工位
+// 已选工位中的最大工位号(无则返回 -Infinity,便于首道工序允许负数虚拟工位)
+function maxSelected(arr) {
+ if (!arr || !arr.length) return -Infinity
+ return Math.max(...arr)
+}
+
+// 按产品工艺工序顺序构建工序行
function buildProcessRows(pp) {
comboStaleWarn.value = ''
if (!pp || !pp.flows || !pp.flows.length) {
@@ -499,29 +497,29 @@ function buildProcessRows(pp) {
seq: it.seq,
flowId: it.flowId,
flowName: it.flowName || ('工序' + it.flowId),
- stationNo: 0,
+ stationNos: [],
options: [],
error: ''
}))
recomputeCandidates(0)
}
-// 从 fromIdx 起重算候选 + 自动修正后续已选(不在新候选中则替换为最小候选)+ 收集红字
+// 从 fromIdx 起重算候选 + 自动修正(去掉越界选择、空则补最小候选)+ 收集红字。
+// 单调约束:本道工序全部工位须排在上一道工序全部工位之后(前向唯一约束),
+// 配合后端 ValidateWorkOrderComboStrict 的整区间严格递增校验。
function recomputeCandidates(fromIdx) {
- let prev = fromIdx > 0 ? processRows.value[fromIdx - 1].stationNo : 0
+ let prev = fromIdx > 0 ? maxSelected(processRows.value[fromIdx - 1].stationNos) : -Infinity
for (let i = fromIdx; i < processRows.value.length; i++) {
const r = processRows.value[i]
- const lower = i === 0 ? -1 : prev // 第1道无下限;后续=上一道已选工位号
+ const lower = prev // 后续=上一道已选最大工位号(首道允许负数虚拟工位)
const cands = boundStations(r.flowId).filter((o) => o.stationNo > lower)
r.options = cands
- if (r.stationNo > 0 && cands.some((o) => o.stationNo === r.stationNo)) {
- // 当前选择仍合法,保留
- } else if (cands.length) {
- r.stationNo = cands[0].stationNo // 自动替换为最小合法候选
- } else {
- r.stationNo = 0 // 无候选:留空,由红字提示
+ // 仅保留仍合法的已选,去掉越界项
+ r.stationNos = (r.stationNos || []).filter((n) => cands.some((o) => o.stationNo === n))
+ if (r.stationNos.length === 0 && cands.length) {
+ r.stationNos = [cands[0].stationNo] // 无候选以外的默认:补最小合法候选
}
- prev = r.stationNo
+ prev = r.stationNos.length ? maxSelected(r.stationNos) : lower
}
collectComboError()
}
@@ -530,10 +528,9 @@ function recomputeCandidates(fromIdx) {
function collectComboError() {
for (let i = 0; i < processRows.value.length; i++) {
const r = processRows.value[i]
- if (r.stationNo === 0 && r.options.length === 0) {
- const prevNo = i > 0 ? processRows.value[i - 1].stationNo : 0
- const prevName = i > 0 ? processRows.value[i - 1].flowName : ''
- comboError.value = `工位${prevNo} 之后没有能做工序「${r.flowName}」的工位,请改选第${i}道工序`
+ if ((!r.stationNos || r.stationNos.length === 0) && r.options.length === 0) {
+ const prevNo = i > 0 ? maxSelected(processRows.value[i - 1].stationNos) : 0
+ comboError.value = `工位${prevNo} 之后没有能做工序「${r.flowName}」的工位,请改选第${i + 1}道工序`
return
}
}
@@ -545,11 +542,11 @@ function onProcessStationChange(i) {
recomputeCandidates(i + 1)
}
-// 组合结果(按工位号升序即执行路线):仅含已选工序
+// 组合结果(展开为 工序-工位 扁平条目,按工位号升序即执行路线):仅含已选工序
const flowCombination = computed(() =>
processRows.value
- .filter((r) => r.stationNo > 0)
- .map((r) => ({ flowId: r.flowId, stationNo: r.stationNo }))
+ .flatMap((r) => (r.stationNos || []).map((n) => ({ flowId: r.flowId, stationNo: n })))
+ .filter((c) => c.stationNo !== 0)
.sort((a, b) => a.stationNo - b.stationNo)
)
const routeText = computed(() => flowCombination.value.map((c) => c.stationNo).join('→'))
@@ -563,22 +560,22 @@ function buildEditProcessRows(row) {
if (pp && pp.flows && pp.flows.length) {
buildProcessRows(pp)
for (const r of processRows.value) {
- const c = combo.find((x) => x.flowId === r.flowId && x.stationNo > 0)
- if (c) r.stationNo = c.stationNo
+ const ns = combo.filter((x) => x.flowId === r.flowId && x.stationNo !== 0).map((x) => x.stationNo)
+ r.stationNos = ns
}
recomputeCandidates(0) // 已保存合法则保留,失效则自动修正
} else if (combo.length) {
const byFlow = new Map()
for (const c of combo) {
- if (c.flowId > 0 && c.stationNo > 0) {
- const cur = byFlow.get(c.flowId)
- if (cur === undefined || c.stationNo < cur) byFlow.set(c.flowId, c.stationNo)
+ if (c.flowId > 0 && c.stationNo !== 0) {
+ if (!byFlow.has(c.flowId)) byFlow.set(c.flowId, [])
+ byFlow.get(c.flowId).push(c.stationNo)
}
}
- const ordered = [...byFlow.entries()].sort((a, b) => a[1] - b[1])
- processRows.value = ordered.map(([fid, no], i) => {
+ const ordered = [...byFlow.entries()].sort((a, b) => Math.min(...a[1]) - Math.min(...b[1]))
+ processRows.value = ordered.map(([fid, nos], i) => {
const f = flows.value.find((x) => x.id === fid)
- return { seq: i + 1, flowId: fid, flowName: f ? f.name : ('工序' + fid), stationNo: no, options: boundStations(fid), error: '' }
+ return { seq: i + 1, flowId: fid, flowName: f ? f.name : ('工序' + fid), stationNos: nos.slice().sort((a, b) => a - b), options: boundStations(fid), error: '' }
})
comboError.value = ''
} else {
@@ -630,9 +627,15 @@ async function loadComboData() {
}
// ---------- 工单单台用料汇总(只读) ----------
-const usage = reactive({ show: false, orderNo: '', rows: [], loading: false })
+const usage = reactive({ show: false, orderNo: '', rows: [], loading: false, emptyTip: '' })
async function openUsage(row) {
- Object.assign(usage, { show: true, orderNo: row.workOrderNo, rows: [], loading: true })
+ // 空态细分(2026-11-02):接口对"组合为空"与"组合工艺均未配物料"都返回空数组,
+ // 前端按工单快照组合区分提示,避免"先建单后配工艺物料"时误导为配置丢失
+ const combo = Array.isArray(row.flowCombination) ? row.flowCombination : []
+ const tip = combo.length
+ ? '该工单工艺组合中的工序尚未配置物料清单:请到「工艺」页为对应工序配置物料(物料实时按当前清单汇总,配置后重新打开即显示)。'
+ : '该工单建单时未选择工序工位组合(快照为空):编辑工单选择产品工艺/工序工位并保存后,才能按组合汇总用料;仅事后配置工艺物料不会自动关联到已建工单。'
+ Object.assign(usage, { show: true, orderNo: row.workOrderNo, rows: [], loading: true, emptyTip: tip })
try {
usage.rows = (await request.get('/order-usage', { params: { orderNo: row.workOrderNo } })) || []
} finally {
@@ -735,15 +738,16 @@ function stepReqText(row) {
return parts.length ? parts.join(';') : '—'
}
-const dialog = reactive({ show: false, id: 0, workOrderNo: '', productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', planEnd: '', status: 'CREATED', productProcessId: 0 })
+const dialog = reactive({ show: false, id: 0, workOrderNo: '', productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, planStart: '', planEnd: '', status: 'CREATED', productProcessId: 0 })
// ---------- 产品工艺(2026-10-09):建单选产品自动带出默认产品工艺,自动填工艺组合(快捷选择+偏差提示) ----------
const productProcesses = ref([])
const ppWarnings = ref([])
const router = useRouter()
-// 工单不嵌路线卡(客户裁定):想看定义层就跳「产品工艺」页查看/打印路线卡
+// 工单不嵌路线卡(客户裁定):想看定义层就跳「工艺」页(默认产品工艺 tab)查看/打印路线卡
+// 2026-11-02 修复:原跳 /product-process 无此路由(命中 catch-all 被静默重定向,表现为"点击没反应")
function goProductProcess() {
- router.push('/product-process')
+ router.push('/process-flow')
}
async function loadProductProcesses() {
@@ -789,11 +793,9 @@ async function applyProductProcess(id) {
}
async function load() {
- const [dueFrom, dueTo] = query.dueRange || []
const params = {
orderNo: query.orderNo, productCode: query.productCode, productName: query.productName,
- contractNo: query.contractNo, ownershipType: query.ownershipType, status: query.status,
- dueFrom: dueFrom || '', dueTo: dueTo || ''
+ contractNo: query.contractNo, ownershipType: query.ownershipType, status: query.status
}
const data = await request.get('/work-orders', { params })
list.value = data || []
@@ -820,7 +822,7 @@ function onProductTypeChange(id) {
loadProductProcesses()
}
function openCreate() {
- Object.assign(dialog, { show: true, id: 0, workOrderNo: genOrderNo(), productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', planEnd: '', status: 'CREATED', productProcessId: 0 })
+ Object.assign(dialog, { show: true, id: 0, workOrderNo: genOrderNo(), productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, planStart: '', planEnd: '', status: 'CREATED', productProcessId: 0 })
productProcesses.value = []
ppWarnings.value = []
processRows.value = []
@@ -828,7 +830,7 @@ function openCreate() {
comboStaleWarn.value = ''
}
async function openEdit(row) {
- Object.assign(dialog, { show: true, id: row.id, workOrderNo: row.workOrderNo, productTypeId: row.productTypeId, productCode: row.productCode, productName: row.productName, contractNo: row.contractNo || '', ownershipType: row.ownershipType || '', productSerial: row.productSerial || '', quantity: row.quantity, dueDate: row.dueDate ? String(row.dueDate).slice(0, 10) : '', planStart: row.planStart ? String(row.planStart).slice(0, 10) : '', planEnd: row.planEnd ? String(row.planEnd).slice(0, 10) : '', status: row.status, productProcessId: row.productProcessId || 0 })
+ Object.assign(dialog, { show: true, id: row.id, workOrderNo: row.workOrderNo, productTypeId: row.productTypeId, productCode: row.productCode, productName: row.productName, contractNo: row.contractNo || '', ownershipType: row.ownershipType || '', productSerial: row.productSerial || '', quantity: row.quantity, planStart: row.planStart ? String(row.planStart).slice(0, 10) : '', planEnd: row.planEnd ? String(row.planEnd).slice(0, 10) : '', status: row.status, productProcessId: row.productProcessId || 0 })
// 编辑:带出该产品可选的产品工艺(不自动重填组合,保留已保存组合)
productProcesses.value = []
ppWarnings.value = []
@@ -843,20 +845,19 @@ async function openEdit(row) {
buildEditProcessRows(row)
}
async function save() {
- if (!dialog.dueDate) return ElMessage.warning('请选择要求完成日期(必填)')
// 归属(一级编号)二选一口径:类型必选;合同号/科技项目号必填编号,其他可空
if (!dialog.ownershipType) return ElMessage.warning('请选择归属类型(合同号/科技项目号/其他)')
if (dialog.ownershipType !== 'other' && !String(dialog.contractNo || '').trim()) {
return ElMessage.warning(dialog.ownershipType === 'project' ? '归属类型为科技项目号,请填写归属编号' : '归属类型为合同号,请填写归属编号')
}
- // 工序工位:带产品工艺时每道工序必须选工位(前端即时拦,后端仍兜底)
- if (dialog.productProcessId > 0 && processRows.value.some((r) => r.stationNo === 0)) {
- const miss = processRows.value.filter((r) => r.stationNo === 0).map((r) => r.flowName).join('、')
- return ElMessage.warning('请为每道工序选择工位:' + miss)
+ // 工序工位:带产品工艺时每道工序必须至少选一个工位(前端即时拦,后端仍兜底)
+ if (dialog.productProcessId > 0 && processRows.value.some((r) => !r.stationNos || r.stationNos.length === 0)) {
+ const miss = processRows.value.filter((r) => !r.stationNos || r.stationNos.length === 0).map((r) => r.flowName).join('、')
+ return ElMessage.warning('请为每道工序至少选择一个工位:' + miss)
}
// 建单不强制工艺组合(工单≠开工):排产/开工时由后端校验组合非空
if (!flowCombination.value.length) ElMessage.warning('未选择工艺组合:排产/开工前须配置')
- const body = { id: dialog.id, workOrderNo: dialog.workOrderNo, productTypeId: dialog.productTypeId, productCode: dialog.productCode, productName: dialog.productName, contractNo: dialog.contractNo, ownershipType: dialog.ownershipType, productSerial: dialog.productSerial, quantity: dialog.quantity, dueDate: dialog.dueDate, planStart: dialog.planStart, planEnd: dialog.planEnd, flowCombination: flowCombination.value, productProcessId: dialog.productProcessId || 0 }
+ const body = { id: dialog.id, workOrderNo: dialog.workOrderNo, productTypeId: dialog.productTypeId, productCode: dialog.productCode, productName: dialog.productName, contractNo: dialog.contractNo, ownershipType: dialog.ownershipType, productSerial: dialog.productSerial, quantity: dialog.quantity, planStart: dialog.planStart, planEnd: dialog.planEnd, flowCombination: flowCombination.value, productProcessId: dialog.productProcessId || 0 }
let resp = null
if (dialog.id) resp = await request.put('/work-orders', body)
else resp = await request.post('/work-orders', body)
@@ -944,11 +945,11 @@ async function doForceComplete() {
}
// ---- 自动排产(引导式,M9 定稿:预览逐日可调、总数据必须对上)----
-const sched = reactive({ show: false, orderNo: '', mode: 'AVG', dailyQty: 1, segments: [{ range: null }], planStart: '', dueDate: '', quantity: 0, finishedNum: 0, preview: null, previewing: false, applying: false })
+const sched = reactive({ show: false, orderNo: '', mode: 'AVG', dailyQty: 1, segments: [{ range: null }], planStart: '', quantity: 0, finishedNum: 0, preview: null, previewing: false, applying: false })
function openAutoSchedule(row) {
Object.assign(sched, {
show: true, orderNo: row.workOrderNo, mode: 'AVG', dailyQty: 1, segments: [{ range: null }],
- planStart: row.planStart || '', dueDate: row.dueDate || '', quantity: row.quantity || 0, finishedNum: row.finishedNum || 0,
+ planStart: row.planStart || '', quantity: row.quantity || 0, finishedNum: row.finishedNum || 0,
preview: null, previewing: false, applying: false
})
}
diff --git a/bj_power_mes/internal/db/db.go b/bj_power_mes/internal/db/db.go
index 76d9424..2c7741a 100644
--- a/bj_power_mes/internal/db/db.go
+++ b/bj_power_mes/internal/db/db.go
@@ -119,7 +119,9 @@ var schemaPatchSQL = []string{
`ALTER TABLE IF EXISTS work_order_bom ADD COLUMN IF NOT EXISTS related_standard varchar(255) NOT NULL DEFAULT ''`,
`ALTER TABLE process_step ADD COLUMN IF NOT EXISTS attachment jsonb NOT NULL DEFAULT '[]'::jsonb`,
`ALTER TABLE work_order ADD COLUMN IF NOT EXISTS created_by varchar(64) NOT NULL DEFAULT ''`,
- `ALTER TABLE work_order ADD COLUMN IF NOT EXISTS due_date timestamp`,
+ // 2026-11-02 移除冗余字段「要求完成日期」(due_date):统一使用 plan_start/plan_end。
+ // ent 不再生成该列;存量库在此显式 DROP(幂等),避免脏列残留。
+ `ALTER TABLE work_order DROP COLUMN IF EXISTS due_date`,
`ALTER TABLE work_order ADD COLUMN IF NOT EXISTS actual_start timestamp`,
`ALTER TABLE workpiece_process ADD COLUMN IF NOT EXISTS duration_sec integer NOT NULL DEFAULT 0`,
@@ -346,6 +348,8 @@ var schemaPatchSQL = []string{
`ALTER TABLE material_request ADD COLUMN IF NOT EXISTS reject_reason varchar(128) NOT NULL DEFAULT ''`,
`ALTER TABLE material_request ADD COLUMN IF NOT EXISTS cross_day boolean NOT NULL DEFAULT false`,
`ALTER TABLE material_request ADD COLUMN IF NOT EXISTS outbound_no varchar(255) NOT NULL DEFAULT ''`,
+ // 跨工位借料来源(2026-11-02):记录叫料单实际消耗了哪些工位的叫料池额度(同工序候选工位间借用)
+ `ALTER TABLE material_request ADD COLUMN IF NOT EXISTS borrow_from jsonb NOT NULL DEFAULT '{}'::jsonb`,
`CREATE INDEX IF NOT EXISTS materialrequest_station_no ON material_request (station_no)`,
// 叫料单不绑工单/不绑排产(B5 定稿):删列及其索引;补发来源由 ref_report_no 承载
`DROP INDEX IF EXISTS materialrequest_order_no`,
diff --git a/bj_power_mes/internal/handler/alert_scan.go b/bj_power_mes/internal/handler/alert_scan.go
index 5e0c2fc..df46952 100644
--- a/bj_power_mes/internal/handler/alert_scan.go
+++ b/bj_power_mes/internal/handler/alert_scan.go
@@ -8,15 +8,22 @@ import (
"bj_power_mes/internal/svc"
)
-// StartAlertScanner 预警定时扫描器:每小时扫描一次工单超期(task_overdue),
+// StartAlertScanner 预警定时扫描器:每小时扫描一次(工单超期 task_overdue /
+// 叫料备料超时 call_overdue / AGV 派车失败 agv_failed),
// 服务启动后立即扫描一次。各扫描项内部自带「规则启用才生效 + 未读去重」,重复运行无副作用。
func StartAlertScanner(ctx *svc.ServiceContext) {
go func() {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
- logic.New(ctx).ScanTaskOverdue(context.Background())
+ scanAll(ctx)
for range ticker.C {
- logic.New(ctx).ScanTaskOverdue(context.Background())
+ scanAll(ctx)
}
}()
}
+
+func scanAll(ctx *svc.ServiceContext) {
+ logic.New(ctx).ScanTaskOverdue(context.Background())
+ logic.New(ctx).ScanCallOverdue(context.Background())
+ logic.New(ctx).ScanAgvFailed(context.Background())
+}
diff --git a/bj_power_mes/internal/handler/processcard_pdf.go b/bj_power_mes/internal/handler/processcard_pdf.go
index 92b02ec..e8a0e0e 100644
--- a/bj_power_mes/internal/handler/processcard_pdf.go
+++ b/bj_power_mes/internal/handler/processcard_pdf.go
@@ -277,7 +277,7 @@ func renderWorkOrderCardPdf(pdf *gofpdf.Fpdf, c *workOrderCard) {
rows := [][]string{}
for _, s := range c.ProcessSteps {
rows = append(rows, []string{
- strconv.Itoa(s.Seq), s.ProcessName, strconv.Itoa(s.StationNo), s.CollectCN,
+ strconv.Itoa(s.Seq), s.ProcessName, s.StationNo, s.CollectCN,
s.ActualStart, s.ActualEnd, s.Operators, s.Status, s.Auditor,
})
}
diff --git a/bj_power_mes/internal/handler/processcard_workorder.go b/bj_power_mes/internal/handler/processcard_workorder.go
index 30b244e..ff986ad 100644
--- a/bj_power_mes/internal/handler/processcard_workorder.go
+++ b/bj_power_mes/internal/handler/processcard_workorder.go
@@ -70,7 +70,7 @@ type woProcessStep struct {
Seq int `json:"seq"`
ProcessName string `json:"processName"`
CollectCN string `json:"collectCN"`
- StationNo int `json:"stationNo"`
+ StationNo string `json:"stationNo"`
PlanHours string `json:"planHours"`
ActualStart string `json:"actualStart"`
ActualEnd string `json:"actualEnd"`
@@ -345,7 +345,8 @@ func buildWorkOrderCard(ctx context.Context, svcCtx *svc.ServiceContext, workOrd
// 路线:工单工艺组合 → 工位顺序;未配置则全产线已配置工位
seq := []int{}
- if items, _ := logic.RouteStationsFromWO(ctx, client, wo); len(items) > 0 {
+ items, _ := logic.RouteStationsFromWO(ctx, client, wo)
+ if len(items) > 0 {
seq = logic.RouteStationsOfWO(items)
} else {
sts, _ := client.Station.Query().Where(station.FlowIdGT(0)).Order(ent.Asc(station.FieldStationNo)).All(ctx)
@@ -357,10 +358,8 @@ func buildWorkOrderCard(ctx context.Context, svcCtx *svc.ServiceContext, workOrd
card.ProcessSeqNote = joinInts(seq)
sts, _ := client.Station.Query().Where(station.StationNoIn(seq...)).All(ctx)
- stationByNo := map[int]*ent.Station{}
flowIds := []int{}
for _, s := range sts {
- stationByNo[s.StationNo] = s
if s.FlowId > 0 {
flowIds = append(flowIds, s.FlowId)
}
@@ -438,15 +437,13 @@ func buildWorkOrderCard(ctx context.Context, svcCtx *svc.ServiceContext, workOrd
signByStep[s.StepId][s.SignRole] = append(signByStep[s.StepId][s.SignRole], s)
}
- // 组装工序实绩行
- for _, no := range seq {
- st := stationByNo[no]
- if st == nil {
- continue
- }
- for _, s := range stepsByFlow[st.FlowId] {
- key := fmt.Sprintf("%d|%s", st.FlowId, s.Name)
- ps := woProcessStep{Seq: s.Seq, ProcessName: s.Name, CollectCN: ppCollectCN(s.CollectType), StationNo: no, PlanHours: "-",
+ // 组装工序实绩行(并行候选工位模型:按工序聚合,工位列展示该工序的全部候选工位,避免重复渲染)
+ route := logic.GroupFlowRoute(items)
+ for _, fr := range route {
+ for _, s := range stepsByFlow[fr.FlowId] {
+ key := fmt.Sprintf("%d|%s", fr.FlowId, s.Name)
+ ps := woProcessStep{Seq: s.Seq, ProcessName: s.Name, CollectCN: ppCollectCN(s.CollectType),
+ StationNo: joinInts(fr.Stations), PlanHours: "-",
NeedCheck: s.NeedCheck, NeedAudit: s.NeedAudit, AuditRole: s.AuditRole}
a := actByKey[key]
if a != nil && a.hasRecord {
diff --git a/bj_power_mes/internal/handler/production/production.go b/bj_power_mes/internal/handler/production/production.go
index bb08d12..f33b150 100644
--- a/bj_power_mes/internal/handler/production/production.go
+++ b/bj_power_mes/internal/handler/production/production.go
@@ -220,7 +220,7 @@ type orderRow struct {
func OrderQueryInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
orderNo := r.URL.Query().Get("orderNo")
- list, err := logic.New(svcCtx).ListWorkOrders(r.Context(), orderNo, "", "", "", "", "", "", "", "", 0)
+ list, err := logic.New(svcCtx).ListWorkOrders(r.Context(), orderNo, "", "", "", "", "", "", 0)
if err != nil {
httpx.Fail(w, 2004, err.Error())
return
diff --git a/bj_power_mes/internal/handler/production/workorder.go b/bj_power_mes/internal/handler/production/workorder.go
index 7709d4d..6ca53e8 100644
--- a/bj_power_mes/internal/handler/production/workorder.go
+++ b/bj_power_mes/internal/handler/production/workorder.go
@@ -160,7 +160,7 @@ func ListWorkOrdersHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
}
data, err := logic.New(svcCtx).ListWorkOrders(r.Context(),
q.Get("orderNo"), q.Get("status"), q.Get("productCode"), q.Get("productName"),
- q.Get("contractNo"), q.Get("ownershipType"), q.Get("dueFrom"), q.Get("dueTo"),
+ q.Get("contractNo"), q.Get("ownershipType"),
q.Get("keyword"), limit)
if err != nil {
httpx.Fail(w, 3004, err.Error())
diff --git a/bj_power_mes/internal/logic/alert_scan.go b/bj_power_mes/internal/logic/alert_scan.go
index 5d69c8a..8bc08ee 100644
--- a/bj_power_mes/internal/logic/alert_scan.go
+++ b/bj_power_mes/internal/logic/alert_scan.go
@@ -6,19 +6,22 @@ import (
"strconv"
"time"
+ "bj_power_mes/ent/agvtask"
"bj_power_mes/ent/alert"
"bj_power_mes/ent/alertrule"
+ "bj_power_mes/ent/materialrequest"
"bj_power_mes/ent/workorder"
)
// AlertTypeTaskOverdue 任务超期预警类型(与 schema/alert_rule.go 占位规则及 AlertRule.vue 一致)
const AlertTypeTaskOverdue = "task_overdue"
-// ScanTaskOverdue 定时扫描工单超期:计划结束时间已过期且未完工(COMPLETED/CLOSED)的工单,
+// ScanTaskOverdue 定时扫描工单超期:计划结束时间已过期且未完工的工单,
// 按 enabled 的 task_overdue 规则逐单落预警。
// 去重:同工单已存在未读 task_overdue 预警则跳过,避免每次扫描重复轰炸。
-// 门禁:不存在 enabled 的 task_overdue 规则时不产生预警(与 AlertRule 页面启用态联动;
-// 默认占位规则为停用,实施在 AlertRule 页启用后扫描器才生效)。
+// 门禁:不存在 enabled 的 task_overdue 规则时不产生预警(与 AlertRule 页面启用态联动)。
+// 状态口径修正(2026-11-02 条目15):工单状态机为 CREATED/IN_PROGRESS/PAUSED/DONE/CANCELLED,
+// 原排除 COMPLETED/CLOSED(不存在)导致已完成工单也被反复报警。
func (s *Service) ScanTaskOverdue(ctx context.Context) {
enabled, err := s.ctx.EntClient.AlertRule.Query().
Where(alertrule.Type(AlertTypeTaskOverdue), alertrule.Enabled(true)).Exist(ctx)
@@ -30,7 +33,7 @@ func (s *Service) ScanTaskOverdue(ctx context.Context) {
Where(
workorder.PlanEndNotNil(),
workorder.PlanEndLT(now),
- workorder.StatusNotIn("COMPLETED", "CLOSED"),
+ workorder.StatusNotIn("DONE", "CANCELLED"),
).All(ctx)
if err != nil {
return
@@ -53,3 +56,65 @@ func (s *Service) ScanTaskOverdue(ctx context.Context) {
s.Evaluate(ctx, AlertTypeTaskOverdue, overdueHours, title, content, "work_order", refId, wo.WorkOrderNo)
}
}
+
+// ScanCallOverdue 定时扫描叫料单备料超时(2026-11-02 条目15 新增):
+// PENDING(待备料)状态、创建后超过阈值小时仍未发货的叫料单 → call_overdue 预警。
+// 阈值 0 = 任何未备料超 1 小时即报;去重:同叫料单已存在未读 call_overdue 预警则跳过。
+func (s *Service) ScanCallOverdue(ctx context.Context) {
+ enabled, err := s.ctx.EntClient.AlertRule.Query().
+ Where(alertrule.Type("call_overdue"), alertrule.Enabled(true)).Exist(ctx)
+ if err != nil || !enabled {
+ return
+ }
+ now := time.Now()
+ rs, err := s.ctx.EntClient.MaterialRequest.Query().
+ Where(materialrequest.StatusEQ("PENDING")).All(ctx)
+ if err != nil {
+ return
+ }
+ for _, r := range rs {
+ pendingHours := now.Sub(r.CreatedAt).Hours()
+ if pendingHours < 1 {
+ continue // 1 小时内的正常备料不报
+ }
+ refId := r.RequestNo
+ exists, _ := s.ctx.EntClient.Alert.Query().
+ Where(alert.TypeEQ("call_overdue"), alert.RefIdEQ(refId), alert.StatusEQ("UNREAD")).Exist(ctx)
+ if exists {
+ continue
+ }
+ title := fmt.Sprintf("叫料单 %s 待备料已超 %.0f 小时", r.RequestNo, pendingHours)
+ content := fmt.Sprintf("叫料单 %s(%s %s,工位%d → %s)自 %s 起一直待备料(PENDING),已超 %.0f 小时,请仓库尽快处理或驳回。",
+ r.RequestNo, r.MaterialCode, r.MaterialName, r.StationNo, r.TargetDock,
+ r.CreatedAt.Format("2006-01-02 15:04"), pendingHours)
+ s.Evaluate(ctx, "call_overdue", pendingHours, title, content, "material_request", refId, "")
+ }
+}
+
+// ScanAgvFailed 定时扫描 AGV 任务失败(2026-11-02 条目15 新增):
+// 近 24 小时内 status=FAILED 的派车任务 → agv_failed 预警(自动派车失败已在失败当场落预警,
+// 本扫描兜底手动补派失败/轮询置失败等未落预警的场景)。去重:同任务未读 agv_failed 预警仅一条。
+func (s *Service) ScanAgvFailed(ctx context.Context) {
+ enabled, err := s.ctx.EntClient.AlertRule.Query().
+ Where(alertrule.Type("agv_failed"), alertrule.Enabled(true)).Exist(ctx)
+ if err != nil || !enabled {
+ return
+ }
+ since := time.Now().Add(-24 * time.Hour).Unix()
+ tasks, err := s.ctx.EntClient.AgvTask.Query().
+ Where(agvtask.StatusEQ("FAILED"), agvtask.CreatedAtGTE(since)).All(ctx)
+ if err != nil {
+ return
+ }
+ for _, t := range tasks {
+ exists, _ := s.ctx.EntClient.Alert.Query().
+ Where(alert.TypeEQ("agv_failed"), alert.RefIdEQ(t.TaskNo), alert.StatusEQ("UNREAD")).Exist(ctx)
+ if exists {
+ continue
+ }
+ title := fmt.Sprintf("AGV 任务 %s 派车失败", t.TaskNo)
+ content := fmt.Sprintf("AGV 任务 %s(%s → %s)状态 FAILED:%s。请到「AGV配送」页查看并手动补派或改人工配送。",
+ t.TaskNo, t.SourceDock, t.TargetDock, t.Remark)
+ s.Evaluate(ctx, "agv_failed", 1, title, content, "agv_task", t.TaskNo, "")
+ }
+}
diff --git a/bj_power_mes/internal/logic/call.go b/bj_power_mes/internal/logic/call.go
index 523e2f6..fb50838 100644
--- a/bj_power_mes/internal/logic/call.go
+++ b/bj_power_mes/internal/logic/call.go
@@ -33,6 +33,12 @@ import (
// 叫料单七态:PENDING 待备料 → SHIPPED 已发货 → DONE 已完成(签收);
// 分支终态 CANCELLED(待备料撤销)/REJECTED(仓库拒发);退库 RETURNING → RETURNED(仓库确认收回,仅签收前)。
+// BorrowSource 同工序候选工位的某物料可借明细(供工位端手动分配借料来源)
+type BorrowSource struct {
+ StationNo int `json:"stationNo"`
+ Avail int `json:"avail"`
+}
+
// CallPoolRow 叫料池行(含派生可用量,供叫料页)
type CallPoolRow struct {
StationNo int `json:"stationNo"`
@@ -45,15 +51,18 @@ type CallPoolRow struct {
SentQty int `json:"sentQty"`
ReservedQty int `json:"reservedQty"`
AvailQty int `json:"availQty"`
+ BorrowAvail int `json:"borrowAvail"` // 同工序其他工位对该物料的可借剩余额度(仅供前端提示与限额)
+ BorrowSources []BorrowSource `json:"borrowSources"` // 同工序其他工位该物料的可借明细(stationNo→可用),供手动分配借料
CrossDay bool `json:"crossDay"`
PlanDates string `json:"planDates"`
}
// CallItem 叫料明细行:一个物料 + 一个量 + 一个目标接驳台 = 一张叫料单 = 一个托盘 = 一次配送
type CallItem struct {
- MaterialCode string `json:"materialCode"`
- Qty int `json:"qty"`
- Dock string `json:"dock"`
+ MaterialCode string `json:"materialCode"`
+ Qty int `json:"qty"`
+ Dock string `json:"dock"`
+ Borrow map[string]int `json:"borrow"` // 超额时的借料分配:来源工位号(字符串)→借用量;空=不借(本工位自取)
}
// CallQuery 叫料单查询条件(零值=不过滤)
@@ -75,6 +84,74 @@ func poolAvail(req, adj, sent, reserved int) int {
return a
}
+// distributeAmount 把 total 按 alloc 各来源的占比拆分到来源工位,保证各来源合计 == total、
+// 且每来源不超过其预约量 alloc;余数按工位号升序逐 1 补齐(用于借料场景的实发/退库回补分摊)。
+// alloc 为空或 total<=0 返回空表。
+func distributeAmount(total int, alloc map[string]int) map[string]int {
+ out := map[string]int{}
+ if total <= 0 || len(alloc) == 0 {
+ return out
+ }
+ sum := 0
+ keys := make([]string, 0, len(alloc))
+ for k, v := range alloc {
+ keys = append(keys, k)
+ sum += v
+ }
+ if sum <= 0 {
+ return out
+ }
+ sort.Strings(keys)
+ rem := total
+ for _, k := range keys {
+ f := total * alloc[k] / sum
+ if f > rem {
+ f = rem
+ }
+ out[k] = f
+ rem -= f
+ }
+ for i := 0; i < len(keys) && rem > 0; i++ {
+ out[keys[i]]++
+ rem--
+ }
+ return out
+}
+
+// borrowLogEntry 收集一次叫料中"涉及借料"的明细,待事务提交后写操作日志(避免事务回滚产生孤儿日志)
+type borrowLogEntry struct {
+ reqNo string
+ materialCode string
+ alloc map[string]int
+}
+
+// borrowDetail 生成借料追溯描述(不含操作人前缀):
+// "向工位[6]借用[3]个[物料A],向工位[9]借用[2]个[物料A],共借料[5]个(本工位自取[5]个)";无借料返回空串。
+func borrowDetail(alloc map[string]int, self int, materialCode string) string {
+ parts := []string{}
+ total := 0
+ selfAmt := 0
+ keys := make([]string, 0, len(alloc))
+ for k := range alloc {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ v := alloc[k]
+ total += v
+ n, e := strconv.Atoi(k)
+ if e != nil || n == self {
+ selfAmt += v
+ continue
+ }
+ parts = append(parts, fmt.Sprintf("向工位[%d]借用[%d]个[%s]", n, v, materialCode))
+ }
+ if len(parts) == 0 {
+ return ""
+ }
+ return fmt.Sprintf("%s,共借料[%d]个(本工位自取[%d]个)", strings.Join(parts, ","), total, selfAmt)
+}
+
// splitQtyToStations 把日总量 dayQty 拆分到 stations 各工位:
// 优先使用 stationQty 显式分配(其和>0 时直接采用);否则平均分配(余数补到前面工位)。
func splitQtyToStations(stations []int, dayQty int, stationQty map[int]int) []int {
@@ -276,7 +353,7 @@ func (s *Service) recomputePoolStations(ctx context.Context, stationNos []int) (
return changed, nil
}
-// StationPool 查某工位的叫料池行(叫料页;可用量派生)。
+// StationPool 查某工位的叫料池行(叫料页;可用量 + 同工序可借额度派生)。
func (s *Service) StationPool(ctx context.Context, stationNo int) ([]CallPoolRow, error) {
rows, err := s.ctx.EntClient.CallPool.Query().
Where(callpool.StationNo(stationNo)).
@@ -284,6 +361,33 @@ func (s *Service) StationPool(ctx context.Context, stationNo int) ([]CallPoolRow
if err != nil {
return nil, err
}
+ // 同工序候选工位对该物料的可借剩余额度明细(仅同 FlowId 的启用工位之间可借;且须基础设置开启借料)
+ borrowByMat := map[string]int{}
+ borrowSrcByMat := map[string][]BorrowSource{}
+ if allowBorrow := s.CfgInt(ctx, CfgAllowBorrow, 1) == 1; allowBorrow {
+ if self, e := s.ctx.EntClient.Station.Query().Where(station.StationNo(stationNo)).First(ctx); e == nil && self.FlowId > 0 {
+ if sibs, e2 := s.ctx.EntClient.Station.Query().
+ Where(station.FlowId(self.FlowId), station.StationNoNEQ(stationNo), station.StatusEQ("ENABLED")).All(ctx); e2 == nil && len(sibs) > 0 {
+ sibNos := make([]int, 0, len(sibs))
+ for _, sb := range sibs {
+ sibNos = append(sibNos, sb.StationNo)
+ }
+ if sibRows, e3 := s.ctx.EntClient.CallPool.Query().Where(callpool.StationNoIn(sibNos...)).All(ctx); e3 == nil {
+ for _, sr := range sibRows {
+ a := poolAvail(sr.ReqQty, sr.AdjQty, sr.SentQty, sr.ReservedQty)
+ if a <= 0 {
+ continue
+ }
+ borrowByMat[sr.MaterialCode] += a
+ borrowSrcByMat[sr.MaterialCode] = append(borrowSrcByMat[sr.MaterialCode], BorrowSource{StationNo: sr.StationNo, Avail: a})
+ }
+ }
+ }
+ }
+ }
+ for k := range borrowSrcByMat {
+ sort.Slice(borrowSrcByMat[k], func(i, j int) bool { return borrowSrcByMat[k][i].StationNo < borrowSrcByMat[k][j].StationNo })
+ }
out := make([]CallPoolRow, 0, len(rows))
for _, r := range rows {
out = append(out, CallPoolRow{
@@ -297,6 +401,8 @@ func (s *Service) StationPool(ctx context.Context, stationNo int) ([]CallPoolRow
SentQty: r.SentQty,
ReservedQty: r.ReservedQty,
AvailQty: poolAvail(r.ReqQty, r.AdjQty, r.SentQty, r.ReservedQty),
+ BorrowAvail: borrowByMat[r.MaterialCode],
+ BorrowSources: borrowSrcByMat[r.MaterialCode],
CrossDay: r.CrossDay,
PlanDates: r.PlanDates,
})
@@ -355,7 +461,22 @@ func (s *Service) CreateCallOrders(ctx context.Context, stationNo int, items []C
if st.Status == "DISABLED" {
return 0, errors.New("工位已停用,不能叫料")
}
+ // 同工序候选工位(同 FlowId、启用、非本工位):本工位不足时向其借用剩余额度
+ sibNos := []int{}
+ if st.FlowId > 0 {
+ if sibs, e := s.ctx.EntClient.Station.Query().
+ Where(station.FlowId(st.FlowId), station.StationNoNEQ(stationNo), station.StatusEQ("ENABLED")).All(ctx); e == nil {
+ for _, sb := range sibs {
+ sibNos = append(sibNos, sb.StationNo)
+ }
+ }
+ }
+ sibSet := map[int]bool{}
+ for _, n := range sibNos {
+ sibSet[n] = true
+ }
allowCross := s.CfgInt(ctx, CfgAllowCrossDay, 1) == 1
+ allowBorrow := s.CfgInt(ctx, CfgAllowBorrow, 1) == 1
// 接驳台校验:目标接驳台必须属于该工位(一工位左L/右R 两个,真源=dock 表)
dockSet := map[string]bool{}
if dks, e := s.ctx.EntClient.Dock.Query().Where(dock.StationNo(stationNo)).All(ctx); e == nil {
@@ -389,32 +510,104 @@ func (s *Service) CreateCallOrders(ctx context.Context, stationNo int, items []C
}()
created := 0
ts := time.Now().UnixNano()
+ borrowLogs := []borrowLogEntry{}
for _, it := range items {
- row, rerr := tx.CallPool.Query().
+ ownRow, rerr := tx.CallPool.Query().
Where(callpool.StationNo(stationNo), callpool.MaterialCode(it.MaterialCode)).
ForUpdate().First(ctx)
- if rerr != nil || row == nil {
+ if rerr != nil || ownRow == nil {
return created, errors.New("叫料池无该物料行(该工位未排产或工艺无此物料)")
}
- if !allowCross && row.CrossDay {
+ if !allowCross && ownRow.CrossDay {
return created, errors.New("该料来自非今日排产,当前设置不允许跨日叫料")
}
- avail := poolAvail(row.ReqQty, row.AdjQty, row.SentQty, row.ReservedQty)
- if it.Qty > avail {
- return created, fmt.Errorf("%s 可用量不足(可用 %d,请求 %d)", it.MaterialCode, avail, it.Qty)
+ // 跨工位借料(手动分配):叫料量 = 本工位自取(ownTake) + 借料(borrow);本工位先占 ownTake,借料逐源占兄弟工位
+ alloc := map[string]int{}
+ ownAvail := poolAvail(ownRow.ReqQty, ownRow.AdjQty, ownRow.SentQty, ownRow.ReservedQty)
+ borrow := it.Borrow
+ sumB := 0
+ for _, amt := range borrow {
+ sumB += amt
}
- if _, uerr := tx.CallPool.UpdateOneID(row.ID).AddReservedQty(it.Qty).Save(ctx); uerr != nil {
- return created, uerr
+ ownTake := it.Qty - sumB
+ if ownTake < 0 {
+ return created, fmt.Errorf("%s 借料分配合计 %d 超出叫料总量 %d(本工位自取 + 借料 之和 不得超过 叫料总量)", it.MaterialCode, sumB, it.Qty)
+ }
+ if ownTake > ownAvail {
+ return created, fmt.Errorf("%s 本工位自取 %d 超出可用 %d(请减少自取量或增加借料)", it.MaterialCode, ownTake, ownAvail)
+ }
+ if ownTake > 0 {
+ if _, uerr := tx.CallPool.UpdateOneID(ownRow.ID).AddReservedQty(ownTake).Save(ctx); uerr != nil {
+ return created, uerr
+ }
+ alloc[strconv.Itoa(stationNo)] = ownTake
+ }
+ if sumB > 0 {
+ if !allowBorrow {
+ return created, fmt.Errorf("%s 自身可用 %d,系统未开启借料功能,超额叫料被拒绝(请求 %d)", it.MaterialCode, ownAvail, it.Qty)
+ }
+ // 严格收口(2026-11-02 主控):仅当本工位可用额度为 0(完全没料)时才允许借料;本工位仍有料则禁止借料。
+ if ownAvail > 0 {
+ return created, fmt.Errorf("%s 本工位仍有可用额度 %d,无需借料;仅当本工位可用为 0 时才可借料", it.MaterialCode, ownAvail)
+ }
+ for src, amt := range borrow {
+ if amt <= 0 {
+ return created, errors.New("借料量必须为正数")
+ }
+ n, e := strconv.Atoi(src)
+ if e != nil {
+ return created, errors.New("借料工位号非法")
+ }
+ if n == stationNo {
+ return created, errors.New("不能向本工位自身借料")
+ }
+ if !sibSet[n] {
+ return created, fmt.Errorf("工位 %d 不在可借候选工位内(仅同工艺候选工位可借)", n)
+ }
+ }
+ // 并发校验:逐源锁池子行,校验实际余量,不足则打回让工人重填
+ srcs := make([]string, 0, len(borrow))
+ for k := range borrow {
+ srcs = append(srcs, k)
+ }
+ sort.Strings(srcs)
+ for _, src := range srcs {
+ amt := borrow[src]
+ n, _ := strconv.Atoi(src)
+ sr, serr := tx.CallPool.Query().
+ Where(callpool.StationNo(n), callpool.MaterialCode(it.MaterialCode)).
+ ForUpdate().First(ctx)
+ if serr != nil || sr == nil {
+ return created, fmt.Errorf("借料工位 %d 无该物料池行", n)
+ }
+ if !allowCross && sr.CrossDay {
+ return created, fmt.Errorf("借料工位 %d 该料为跨日排产,当前不允许跨日借料", n)
+ }
+ sa := poolAvail(sr.ReqQty, sr.AdjQty, sr.SentQty, sr.ReservedQty)
+ if amt > sa {
+ return created, fmt.Errorf("向工位 %d 借料 %d 超出其当前可用 %d(可能被其他工位同时借走,请重新分配)", n, amt, sa)
+ }
+ if _, uerr := tx.CallPool.UpdateOneID(sr.ID).AddReservedQty(amt).Save(ctx); uerr != nil {
+ return created, uerr
+ }
+ alloc[src] = amt
+ }
+ } else if it.Qty > ownAvail {
+ // 未借料但本工位不足(前端 max 已限制,这里兜底拦截)
+ return created, fmt.Errorf("%s 自身可用 %d 不足(请求 %d),请开启借料或从同工序工位借料", it.MaterialCode, ownAvail, it.Qty)
}
reqNo := fmt.Sprintf("MR%d", ts+int64(created))
if _, cerr := tx.MaterialRequest.Create().
- SetRequestNo(reqNo).SetMaterialCode(it.MaterialCode).SetMaterialName(row.MaterialName).
- SetUnit(row.Unit).SetSnMode(row.SnMode).SetReqQty(float64(it.Qty)).
+ SetRequestNo(reqNo).SetMaterialCode(it.MaterialCode).SetMaterialName(ownRow.MaterialName).
+ SetUnit(ownRow.Unit).SetSnMode(ownRow.SnMode).SetReqQty(float64(it.Qty)).
SetStatus("PENDING").SetStationNo(stationNo).SetTargetDock(it.Dock).
- SetCrossDay(row.CrossDay).SetSource(source).SetRefReportNo(refReportNo).
- SetNeedAgv(true).SetOperator(operator).Save(ctx); cerr != nil {
+ SetCrossDay(ownRow.CrossDay).SetSource(source).SetRefReportNo(refReportNo).
+ SetBorrowFrom(alloc).SetNeedAgv(true).SetOperator(operator).Save(ctx); cerr != nil {
return created, cerr
}
+ if d := borrowDetail(alloc, stationNo, it.MaterialCode); d != "" {
+ borrowLogs = append(borrowLogs, borrowLogEntry{reqNo: reqNo, materialCode: it.MaterialCode, alloc: alloc})
+ }
created++
}
if cerr := tx.Commit(); cerr != nil {
@@ -424,6 +617,10 @@ func (s *Service) CreateCallOrders(ctx context.Context, stationNo int, items []C
s.ctx.EventLog.Write(ctx, "call.create", "", operator, "material_request", "",
fmt.Sprintf("工位%d 发起叫料 %d 项", stationNo, created),
map[string]any{"stationNo": stationNo, "count": created, "source": source, "refReportNo": refReportNo})
+ for _, bl := range borrowLogs {
+ s.ctx.EventLog.Write(ctx, "call.create", "", operator, "material_request", bl.reqNo,
+ "操作人["+operator+"] "+borrowDetail(bl.alloc, stationNo, bl.materialCode), nil)
+ }
s.notifyDashboard()
return created, nil
}
@@ -478,7 +675,15 @@ func (s *Service) CancelCall(ctx context.Context, requestNo string, stationNo in
if locked.Status != "PENDING" {
return errors.New("仅待备料的叫料单可取消")
}
- releaseReserveTx(ctx, tx, locked.StationNo, locked.MaterialCode, int(locked.ReqQty))
+ alloc := locked.BorrowFrom
+ if len(alloc) == 0 {
+ alloc = map[string]int{strconv.Itoa(locked.StationNo): int(locked.ReqQty)}
+ }
+ for src, amt := range alloc {
+ if srcNo, e := strconv.Atoi(src); e == nil {
+ releaseReserveTx(ctx, tx, srcNo, locked.MaterialCode, amt)
+ }
+ }
if _, uerr := tx.MaterialRequest.UpdateOneID(locked.ID).SetStatus("CANCELLED").Save(ctx); uerr != nil {
return uerr
}
@@ -486,8 +691,12 @@ func (s *Service) CancelCall(ctx context.Context, requestNo string, stationNo in
return cerr
}
committed = true
+ cancelDesc := "叫料单取消"
+ if d := borrowDetail(alloc, locked.StationNo, locked.MaterialCode); d != "" {
+ cancelDesc = "操作人[" + operator + "] 取消叫料," + d
+ }
s.ctx.EventLog.Write(ctx, "call.cancel", "", operator, "material_request", requestNo,
- "叫料单取消", map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode})
+ cancelDesc, map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode})
s.notifyDashboard()
return nil
}
@@ -544,7 +753,15 @@ func (s *Service) RejectCall(ctx context.Context, requestNo, reason, operator st
if locked.Status != "PENDING" {
return errors.New("仅待备料的叫料单可驳回")
}
- releaseReserveTx(ctx, tx, locked.StationNo, locked.MaterialCode, int(locked.ReqQty))
+ alloc := locked.BorrowFrom
+ if len(alloc) == 0 {
+ alloc = map[string]int{strconv.Itoa(locked.StationNo): int(locked.ReqQty)}
+ }
+ for src, amt := range alloc {
+ if srcNo, e := strconv.Atoi(src); e == nil {
+ releaseReserveTx(ctx, tx, srcNo, locked.MaterialCode, amt)
+ }
+ }
if _, uerr := tx.MaterialRequest.UpdateOneID(locked.ID).
SetStatus("REJECTED").SetRejectReason(strings.TrimSpace(reason)).Save(ctx); uerr != nil {
return uerr
@@ -553,8 +770,12 @@ func (s *Service) RejectCall(ctx context.Context, requestNo, reason, operator st
return cerr
}
committed = true
+ rejectDesc := "叫料单驳回"
+ if d := borrowDetail(alloc, locked.StationNo, locked.MaterialCode); d != "" {
+ rejectDesc = "操作人[" + operator + "] 驳回叫料," + d
+ }
s.ctx.EventLog.Write(ctx, "call.reject", "", operator, "material_request", requestNo,
- "叫料单驳回", map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode,
+ rejectDesc, map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode,
"reason": strings.TrimSpace(reason), "crossDay": locked.CrossDay})
s.notifyDashboard()
return nil
@@ -626,14 +847,25 @@ func (s *Service) CompleteCall(ctx context.Context, requestNo string, sentQty fl
if locked.Status != "PENDING" {
return errors.New("仅待备料的叫料单可完成备料")
}
- // 池子:占用 −请求量(差额自动释放)+ 已发 +实发量
- poolRow, perr := tx.CallPool.Query().
- Where(callpool.StationNo(locked.StationNo), callpool.MaterialCode(locked.MaterialCode)).
- ForUpdate().First(ctx)
- if perr == nil && poolRow != nil {
- if _, uerr := tx.CallPool.UpdateOneID(poolRow.ID).
- AddSentQty(int(actual)).AddReservedQty(-int(locked.ReqQty)).Save(ctx); uerr != nil {
- return uerr
+ // 池子:按真实消耗来源(含借料)记账——占用 −预约量(差额自动释放)+ 已发 +实发量
+ alloc := locked.BorrowFrom
+ if len(alloc) == 0 {
+ alloc = map[string]int{strconv.Itoa(locked.StationNo): int(locked.ReqQty)}
+ }
+ ship := distributeAmount(int(actual), alloc)
+ for src, amt := range ship {
+ srcNo, e := strconv.Atoi(src)
+ if e != nil {
+ continue
+ }
+ poolRow, perr := tx.CallPool.Query().
+ Where(callpool.StationNo(srcNo), callpool.MaterialCode(locked.MaterialCode)).
+ ForUpdate().First(ctx)
+ if perr == nil && poolRow != nil {
+ if _, uerr := tx.CallPool.UpdateOneID(poolRow.ID).
+ AddSentQty(amt).AddReservedQty(-alloc[src]).Save(ctx); uerr != nil {
+ return uerr
+ }
}
}
upd := tx.MaterialRequest.UpdateOneID(locked.ID).
@@ -648,8 +880,12 @@ func (s *Service) CompleteCall(ctx context.Context, requestNo string, sentQty fl
return cerr
}
committed = true
+ completeDesc := "仓库完成备料"
+ if d := borrowDetail(ship, locked.StationNo, locked.MaterialCode); d != "" {
+ completeDesc = "操作人[" + operator + "] 完成备料(含借料)," + d
+ }
s.ctx.EventLog.Write(ctx, "call.complete", "", operator, "material_request", requestNo,
- "仓库完成备料", map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode,
+ completeDesc, map[string]any{"stationNo": locked.StationNo, "materialCode": locked.MaterialCode,
"reqQty": locked.ReqQty, "sentQty": actual, "outboundNo": outboundNo})
s.notifyDashboard()
// AGV 自动派车(best-effort,2026-10-14 迁 MES):由 MES 调度海康 RCS,失败仅记日志不阻断叫料完成
@@ -691,12 +927,23 @@ func (s *Service) ConfirmReturn(ctx context.Context, requestNo, operator string)
if locked.Status != "RETURNING" {
return errors.New("仅退库中的叫料单可确认收回")
}
- poolRow, perr := tx.CallPool.Query().
- Where(callpool.StationNo(locked.StationNo), callpool.MaterialCode(locked.MaterialCode)).
- ForUpdate().First(ctx)
- if perr == nil && poolRow != nil {
- if _, uerr := tx.CallPool.UpdateOneID(poolRow.ID).AddSentQty(-int(ret)).Save(ctx); uerr != nil {
- return uerr
+ alloc := locked.BorrowFrom
+ if len(alloc) == 0 {
+ alloc = map[string]int{strconv.Itoa(locked.StationNo): int(ret)}
+ }
+ back := distributeAmount(int(ret), alloc)
+ for src, amt := range back {
+ srcNo, e := strconv.Atoi(src)
+ if e != nil {
+ continue
+ }
+ poolRow, perr := tx.CallPool.Query().
+ Where(callpool.StationNo(srcNo), callpool.MaterialCode(locked.MaterialCode)).
+ ForUpdate().First(ctx)
+ if perr == nil && poolRow != nil {
+ if _, uerr := tx.CallPool.UpdateOneID(poolRow.ID).AddSentQty(-amt).Save(ctx); uerr != nil {
+ return uerr
+ }
}
}
if _, uerr := tx.MaterialRequest.UpdateOneID(locked.ID).
@@ -707,8 +954,12 @@ func (s *Service) ConfirmReturn(ctx context.Context, requestNo, operator string)
return cerr
}
committed = true
+ returnDesc := "仓库确认收回,叫料单关闭"
+ if d := borrowDetail(back, locked.StationNo, locked.MaterialCode); d != "" {
+ returnDesc = "操作人[" + operator + "] 确认收回(含借料回补)," + d
+ }
s.ctx.EventLog.Write(ctx, "call.return_confirm", "", operator, "material_request", requestNo,
- "仓库确认收回,叫料单关闭", map[string]any{"stationNo": locked.StationNo,
+ returnDesc, map[string]any{"stationNo": locked.StationNo,
"materialCode": locked.MaterialCode, "returnedQty": ret})
s.notifyDashboard()
return nil
diff --git a/bj_power_mes/internal/logic/dailyplan.go b/bj_power_mes/internal/logic/dailyplan.go
index f2119ba..c45db0b 100644
--- a/bj_power_mes/internal/logic/dailyplan.go
+++ b/bj_power_mes/internal/logic/dailyplan.go
@@ -390,7 +390,6 @@ type UnplannedWorkOrder struct {
OrderNo string `json:"orderNo"`
ProductTypeId int `json:"productTypeId"`
Quantity int `json:"quantity"`
- DueDate string `json:"dueDate"`
Status string `json:"status"`
}
@@ -413,15 +412,10 @@ func (s *Service) ListUnplannedWorkOrders(ctx context.Context) ([]*UnplannedWork
if planned[wo.WorkOrderNo] {
continue
}
- due := ""
- if wo.DueDate != nil {
- due = wo.DueDate.Format("2006-01-02")
- }
out = append(out, &UnplannedWorkOrder{
OrderNo: wo.WorkOrderNo,
ProductTypeId: wo.ProductTypeId,
Quantity: wo.Quantity,
- DueDate: due,
Status: wo.Status,
})
}
@@ -441,7 +435,7 @@ type ForScheduleWorkOrder struct {
// ListWorkOrdersForSchedule 返回未排满(剩余可排 > 0)的工单,供日排产工单号下拉过滤。
// 与 /daily-plans/unplanned("完全未排产"横幅入口)区分:本接口包含"部分排产"的工单。
func (s *Service) ListWorkOrdersForSchedule(ctx context.Context, keyword string) ([]*ForScheduleWorkOrder, error) {
- wos, err := s.ListWorkOrders(ctx, "", "", "", "", "", "", "", "", keyword, 0)
+ wos, err := s.ListWorkOrders(ctx, "", "", "", "", "", "", keyword, 0)
if err != nil {
return nil, err
}
diff --git a/bj_power_mes/internal/logic/processflow.go b/bj_power_mes/internal/logic/processflow.go
index bb9b036..2a0f4bf 100644
--- a/bj_power_mes/internal/logic/processflow.go
+++ b/bj_power_mes/internal/logic/processflow.go
@@ -155,6 +155,10 @@ func (s *Service) SaveFlow(ctx context.Context, req FlowReq, operator string) er
// 保存时所选工位一律改绑到本流程(覆盖旧绑定),不再报"已被启用流程绑定"冲突。
var flowID int
if req.Id > 0 {
+ // 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺禁止改内容(含启停)
+ if err := s.guardFlowEditable(ctx, req.Id); err != nil {
+ return err
+ }
upd := s.ctx.EntClient.ProcessFlow.UpdateOneID(req.Id).
SetName(req.Name).SetStatus(status).SetRemark(req.Remark)
if req.PdfFile != "" {
@@ -233,6 +237,10 @@ func (s *Service) syncStationFlow(ctx context.Context, stationNo, flowID int) er
}
func (s *Service) DeleteFlow(ctx context.Context, id int, operator string) error {
+ // 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺禁止删除
+ if err := s.guardFlowEditable(ctx, id); err != nil {
+ return err
+ }
// 删除前先解除所有工位绑定,再清步骤与流程本身
_, _ = s.ctx.EntClient.Station.Update().
Where(station.FlowId(id)).
@@ -327,11 +335,30 @@ func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) {
// 内置工位(种子/初始化数据,is_builtin=true)需连 PLC 并必须按工位号顺序流转,
// 不允许手动更改工位类型;页面新增的工位一律为非内置,可改类型、可删除。
// 接驳台为独立主数据(MES dock 表),一个工位可绑定多个接驳台,关系以 dock.station_no 为准,页面不维护。
+// stationHasActiveWorkOrder 工位是否正被"进行中"工单的生产路线引用(flow_combination 含该 stationNo)。
+// 进行中 = IN_PROGRESS(执行中) / PAUSED(已暂停) / RELEASED(残量已下发待开工):这些状态下路线已固定,禁止改绑定。
+func (s *Service) stationHasActiveWorkOrder(ctx context.Context, stationNo int) (bool, error) {
+ active := []string{"IN_PROGRESS", "PAUSED", "RELEASED"}
+ orders, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.StatusIn(active...)).All(ctx)
+ if err != nil {
+ return false, err
+ }
+ for _, o := range orders {
+ for _, item := range o.FlowCombination {
+ if item["stationNo"] == stationNo {
+ return true, nil
+ }
+ }
+ }
+ return false, nil
+}
+
// 校验为收集式(报错一次收全 + 每条带怎么办,2026-10-20):类型/流程/托盘/在途指令全部列出、一次性返回。
func (s *Service) SaveStation(ctx context.Context, req StationReq, operator string) error {
- if req.StationNo < 0 {
- return errors.New("工位号非法(需 ≥ 0)")
- }
+ // 工位号规则(2026-11-02 产线布局业务调整):
+ // 1~12 内置物理工位(硬件锁定,不可新增/占用);负数(-1、-2…)= 产线前段虚拟工位(排在工位1之前);
+ // ≥13 扩展工位;0 保留(历史虚拟位已废弃,不再用于新建)。
+ // 工位号 ≤ 0 仅允许线下位(虚拟工位,不连 PLC、仅记录)。
if req.StationNo == 0 && req.Name == "" {
return errors.New("工位号非法")
}
@@ -342,13 +369,21 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri
// 禁止通过本接口新增或占用,避免与内置物理工位冲突、或绕过前端改物理工位号。
// 物理工位号只能由种子/初始化数据产生;页面新增请使用虚拟工位(0)或扩展工位号(≥13)。
if req.StationNo >= 1 && req.StationNo <= 12 {
- return errors.New("工位号 1~12 为内置物理产线工位(硬件锁定),不可通过本接口新增或占用;新增工位请使用虚拟工位(0)或扩展工位号(≥13)")
+ return errors.New("工位号 1~12 为内置物理产线工位(硬件锁定),不可通过本接口新增或占用;产线前段虚拟工位请用负数号(-1、-2…),12 之后扩展用 ≥13")
}
ve := verr.New()
if req.Name == "" {
ve.Add("name", "请填写工位名称", "在「工位名称」输入框填写名称后保存")
}
+ // 工位类型:尊重请求(修复:此前新增一律落 LINE,前端建"线下位"实际存成线上位,
+ // 导致看板虚拟工位列表为空——2026-11-02 条目14根因)
stype := "LINE"
+ if req.StationType != nil && *req.StationType == "OFFLINE" {
+ stype = "OFFLINE"
+ }
+ if req.StationNo <= 0 && stype != "OFFLINE" {
+ ve.Add("stationNo", "工位号 ≤ 0 仅允许线下位(虚拟工位)", "类型选「线下位」后再保存")
+ }
if req.FlowId != nil && *req.FlowId > 0 {
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, *req.FlowId)
if fErr != nil {
@@ -391,6 +426,14 @@ plcOffline := false
bindFlow := 0
if req.FlowId != nil {
bindFlow = *req.FlowId
+ // 进行中工单守卫(2026-11-02 工位管理需求):工位正被进行中工单的生产路线引用时,禁止修改/解除绑定工艺。
+ // 仅当绑定关系真的发生变化(含解绑/换绑)时才拦截;重复保存原绑定不误伤。
+ if *req.FlowId != st.FlowId {
+ if busy, bErr := s.stationHasActiveWorkOrder(ctx, st.StationNo); bErr == nil && busy {
+ ve.Add("flowId", fmt.Sprintf("工位%d 存在正在进行的工单(生产路线包含此工位),禁止修改绑定工艺", st.StationNo),
+ "请先将该工位的进行中工单完工或取消,再修改绑定工艺")
+ }
+ }
if n, _ := s.ctx.EntClient.PlcSendLog.Query().
Where(plcsendlog.Status("SENT"), plcsendlog.StationNo(st.StationNo)).Count(ctx); n > 0 {
ve.AddAction("flowId", fmt.Sprintf("工位%d 有正在执行的指令,不能修改配置", st.StationNo),
@@ -425,6 +468,16 @@ if err := ve.OrNil(); err != nil {
return err
}
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
+ // 类型调整:仅非内置工位允许 LINE↔OFFLINE(2026-11-02:修复存量虚拟工位被存成 LINE 后
+ // 看板"暂无虚拟工位"无法自愈的问题);内置工位类型锁定不变。
+ if req.StationType != nil && !st.IsBuiltin {
+ if nt := *req.StationType; (nt == "LINE" || nt == "OFFLINE") && nt != st.StationType {
+ upd.SetStationType(nt)
+ s.ctx.EventLog.Write(ctx, "station.type_change", "", operator, "station", "",
+ fmt.Sprintf("工位%d 类型变更:%s → %s", st.StationNo, st.StationType, nt),
+ map[string]any{"stationNo": st.StationNo, "before": st.StationType, "after": nt})
+ }
+ }
if req.FlowId != nil {
upd.SetFlowId(bindFlow) // 0=解绑
}
@@ -916,6 +969,11 @@ func (s *Service) SaveFlowMaterials(ctx context.Context, flowId int, items []Flo
if _, err := s.ctx.EntClient.ProcessFlow.Get(ctx, flowId); err != nil {
return errors.New("工艺不存在")
}
+ // 条目12 守卫(2026-11-02):被执行中/已暂停工单引用的工艺,物料清单禁止整表覆盖
+ //(叫料池/单台用料均实时读本清单,改了会改变在产工单的备料口径)
+ if err := s.guardFlowEditable(ctx, flowId); err != nil {
+ return err
+ }
// WMS 物料存在性校验(缺失拒绝;不可达降级放行)
codes := make([]string, 0, len(items))
seen := map[string]bool{}
diff --git a/bj_power_mes/internal/logic/route.go b/bj_power_mes/internal/logic/route.go
index 69654c6..af7635e 100644
--- a/bj_power_mes/internal/logic/route.go
+++ b/bj_power_mes/internal/logic/route.go
@@ -12,6 +12,7 @@ import (
"bj_power_mes/ent"
"bj_power_mes/ent/productprocessitem"
"bj_power_mes/ent/station"
+ "bj_power_mes/ent/workorder"
"bj_power_mes/internal/verr"
)
@@ -36,12 +37,13 @@ func RouteStationsFromWO(ctx context.Context, client *ent.Client, wo *ent.WorkOr
return items, nil
}
-// flowMapsToItems jsonb 原始值 → 组合条目(过滤 flowId/stationNo 非正的脏条目)
+// flowMapsToItems jsonb 原始值 → 组合条目(过滤 flowId 非正 / stationNo 为 0 的脏条目;
+// stationNo 允许负数:负数=产线前段虚拟工位,2026-11-02)
func flowMapsToItems(raw []map[string]int) []FlowItem {
items := make([]FlowItem, 0, len(raw))
for _, m := range raw {
flowId, no := m["flowId"], m["stationNo"]
- if flowId > 0 && no > 0 {
+ if flowId > 0 && no != 0 {
items = append(items, FlowItem{FlowId: flowId, StationNo: no})
}
}
@@ -84,6 +86,105 @@ func StationFlowMapOfWO(items []FlowItem) map[int]int {
return m
}
+// ---------- 并行候选工位:工序级路线(一道工序可配置多个候选工位) ----------
+
+// FlowRouteStep 工序级路线步骤:一道工序(工艺) + 其全部候选工位。
+// 并行模型(2026-11-02):工件在任一候选工位报工一次即完成该工序,候选工位间为「可任选」关系而非串行顺序。
+type FlowRouteStep struct {
+ FlowId int // 工艺ID
+ Stations []int // 候选工位号(升序)
+ MinNo int // 候选最小工位号(用于工序顺序)
+ MaxNo int // 候选最大工位号(用于进度推进)
+ Seq int // 工序顺序(按 MinNo 升序,从1起)
+}
+
+// groupFlowRoute 扁平组合条目 → 工序级路线(同 flowId 归并为一道工序,多工位为其候选集)。
+// 工序顺序按各工序候选最小工位号升序(产线单向不回头)。
+func groupFlowRoute(items []FlowItem) []FlowRouteStep {
+ byFlow := map[int][]int{}
+ for _, it := range items {
+ byFlow[it.FlowId] = append(byFlow[it.FlowId], it.StationNo)
+ }
+ steps := make([]FlowRouteStep, 0, len(byFlow))
+ for fid, sts := range byFlow {
+ sort.Ints(sts)
+ steps = append(steps, FlowRouteStep{FlowId: fid, Stations: sts, MinNo: sts[0], MaxNo: sts[len(sts)-1]})
+ }
+ sort.SliceStable(steps, func(i, j int) bool { return steps[i].MinNo < steps[j].MinNo })
+ for i := range steps {
+ steps[i].Seq = i + 1
+ }
+ return steps
+}
+
+// FlowRouteOfWO 工单 flow_combination → 工序级路线(含候选工位)。
+func FlowRouteOfWO(ctx context.Context, client *ent.Client, wo *ent.WorkOrder) ([]FlowRouteStep, error) {
+ if wo == nil {
+ return nil, nil
+ }
+ return groupFlowRoute(flowMapsToItems(wo.FlowCombination)), nil
+}
+
+// GroupFlowRoute 导出版:扁平组合条目 → 工序级路线(handler 包渲染流程卡用)。
+func GroupFlowRoute(items []FlowItem) []FlowRouteStep {
+ return groupFlowRoute(items)
+}
+
+// DistinctFlowCount 路线中工序(工艺)去重计数:并行模型下完工/进度按「工序数」而非「工位数」判定。
+func DistinctFlowCount(items []FlowItem) int {
+ m := map[int]bool{}
+ for _, it := range items {
+ m[it.FlowId] = true
+ }
+ return len(m)
+}
+
+// intsContains 整数切片包含判断(候选工位校验用)。
+func intsContains(ns []int, v int) bool {
+ for _, n := range ns {
+ if n == v {
+ return true
+ }
+ }
+ return false
+}
+
+// FlowUsedByActiveOrders 工艺是否被「执行中/已暂停」工单的工艺组合引用(2026-11-02 条目12 守卫)。
+// 背景:工单 flow_combination 是建单快照,但生产流程卡的定义层(工序清单/步骤门禁)每次
+// 请求实时渲染 ProcessFlow/ProcessStep——改基础工艺会改掉在产工单的流程卡展示。
+// 与产品工艺规则1同口径:执行中禁改,建议复制新工艺给新工单用。命中返回工单号列表。
+func (s *Service) FlowUsedByActiveOrders(ctx context.Context, flowId int) ([]string, error) {
+ wos, err := s.ctx.EntClient.WorkOrder.Query().
+ Where(workorder.StatusIn("IN_PROGRESS", "PAUSED")).All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var hit []string
+ for _, w := range wos {
+ for _, m := range w.FlowCombination {
+ if m["flowId"] == flowId {
+ hit = append(hit, w.WorkOrderNo)
+ break
+ }
+ }
+ }
+ return hit, nil
+}
+
+// guardFlowEditable 基础工艺内容(名称/步骤/绑定/物料清单/删除)变更守卫:
+// 被执行中/已暂停工单引用 → 拒绝并给出「怎么办」。
+func (s *Service) guardFlowEditable(ctx context.Context, flowId int) error {
+ hits, err := s.FlowUsedByActiveOrders(ctx, flowId)
+ if err != nil {
+ return err
+ }
+ if len(hits) > 0 {
+ return fmt.Errorf("该工艺被执行中/已暂停的工单引用(%s),不能修改或删除;如需调整请复制一份新工艺,新工单使用新工艺",
+ strings.Join(hits, "、"))
+ }
+ return nil
+}
+
// ValidateFlowCombination 保存工单时校验工艺组合(收集式实现,见 ValidateFlowCombinationCollect;
// 保留原签名供既有调用方使用,错误为收集式 ValidationError,handler 经 FailErr 输出结构化清单)。
func (s *Service) ValidateFlowCombination(ctx context.Context, raw []map[string]int) ([]FlowItem, error) {
@@ -166,18 +267,19 @@ func (s *Service) ValidateWorkOrderComboStrict(ctx context.Context, ppId int, co
for _, f := range flows {
flowName[f.ID] = f.Name
}
- // 组合按 flowId 归并(正常每道一条;后端不信任前端,取最小工位号代表该道)
+ // 组合按 flowId 归并(一道工序可配置多个有序工位:基于「产线单向不回头」,
+ // 本道工序的全部工位必须都在上一道工序的全部工位之后,即各工序的工位区间互不交叉、整体严格递增)。
byFlow := map[int][]int{}
for _, c := range combo {
fid, no := c["flowId"], c["stationNo"]
- if fid > 0 && no > 0 {
+ if fid > 0 && no != 0 {
byFlow[fid] = append(byFlow[fid], no)
}
}
for k := range byFlow {
sort.Ints(byFlow[k])
}
- prevSeq, prevName, prevStation := 0, "", 0
+ prevName, prevMax := "", 0
for _, it := range items {
name := flowName[it.FlowId]
if name == "" {
@@ -188,23 +290,48 @@ func (s *Service) ValidateWorkOrderComboStrict(ctx context.Context, ppId int, co
// 规则①:该道工序未选工位
ve.Add("flowCombination",
fmt.Sprintf("第%d道工序「%s」未选工位", it.Seq, name),
- fmt.Sprintf("请为第%d道工序「%s」选择一个绑定了该工序的工位", it.Seq, name))
+ fmt.Sprintf("请为第%d道工序「%s」选择至少一个绑定了该工序的工位", it.Seq, name))
continue
}
- sel := sts[0]
- if prevStation > 0 && sel <= prevStation {
- // 规则②:工位号未严格递增(产线单向不能回头)
- ve.Add("flowCombination",
- fmt.Sprintf("第%d道工序「%s」选的工位%d,不大于第%d道工序「%s」的工位%d",
- it.Seq, name, sel, prevSeq, prevName, prevStation),
- fmt.Sprintf("产线单向不能回头,请把工序「%s」的工位改为工位%d 之后,或调整工序「%s」的工位",
- name, prevStation, prevName))
+ // 同工序内重复工位(脏数据)拦截
+ seen := map[int]bool{}
+ dup := false
+ for _, n := range sts {
+ if seen[n] {
+ dup = true
+ break
+ }
+ seen[n] = true
}
- prevSeq, prevName, prevStation = it.Seq, name, sel
+ if dup {
+ ve.Add("flowCombination",
+ fmt.Sprintf("第%d道工序「%s」的工位列表存在重复(工位%d)", it.Seq, name, sts[0]),
+ fmt.Sprintf("请在第%d道工序「%s」中去重工位", it.Seq, name))
+ continue
+ }
+ minS, maxS := sts[0], sts[len(sts)-1]
+ if prevMax > 0 && minS <= prevMax {
+ // 规则②:本道工序工位区间未整体在上一道之后(产线单向不能回头 / 工序工位不可交叉)
+ ve.Add("flowCombination",
+ fmt.Sprintf("第%d道工序「%s」的工位(%s)未整体排在上一道工序「%s」(工位%d)之后",
+ it.Seq, name, strings.Join(intsToStrs(sts), ","), prevName, prevMax),
+ fmt.Sprintf("产线单向不能回头:请把工序「%s」的工位都改到工位%d 之后,或调整工序顺序",
+ name, prevMax))
+ }
+ prevName, prevMax = name, maxS
}
return ve
}
+// intsToStrs 整数切片转字符串切片(校验消息用)
+func intsToStrs(ns []int) []string {
+ out := make([]string, 0, len(ns))
+ for _, n := range ns {
+ out = append(out, "工位"+strconv.Itoa(n))
+ }
+ return out
+}
+
// ValidateWOCombinationForSchedule 排产前校验(工单组合是唯一路线源头,排产只继承不可改):
// 组合为空不可排产;组合里每个工位当前绑定工艺必须与工单一致且工位启用。
func (s *Service) ValidateWOCombinationForSchedule(ctx context.Context, wo *ent.WorkOrder) error {
diff --git a/bj_power_mes/internal/logic/seed.go b/bj_power_mes/internal/logic/seed.go
index 10fa422..1f3f4e9 100644
--- a/bj_power_mes/internal/logic/seed.go
+++ b/bj_power_mes/internal/logic/seed.go
@@ -301,8 +301,9 @@ func seedAlertRules(ctx context.Context, s *Service) {
Where(alertrule.Type("torque_ng")).SetEnabled(false).Save(ctx); err != nil {
_ = err // 表为空时影响 0 行属正常,非致命
}
- // inspection_ng 默认启用(事件触发型,出现检验不合格即报警,阈值不使用);
- // inventory_low / task_overdue 默认停用(占位,由实施按需启用)。
+ // 默认启用(2026-11-02 条目15 优化):inspection_ng=事件触发型;
+ // task_overdue=工单超期(扫描已修正状态口径);call_overdue=叫料备料超时;
+ // agv_failed=AGV 派车失败。inventory_low 默认停用(库存真源在 WMS,由 WMS 侧库存阈值预警承担)。
placeholders := []struct {
typ string
name string
@@ -310,7 +311,9 @@ func seedAlertRules(ctx context.Context, s *Service) {
}{
{"inspection_ng", "检验不合格预警", true},
{"inventory_low", "库存低于阈值预警", false},
- {"task_overdue", "任务超期预警", false},
+ {"task_overdue", "任务超期预警", true},
+ {"call_overdue", "叫料单备料超时预警", true},
+ {"agv_failed", "AGV任务失败预警", true},
}
for _, p := range placeholders {
// B2.3 幂等对齐:占位规则以 seed 定义的启用态为准(inspection_ng 强制启用,inventory_low/task_overdue 默认停用)。
diff --git a/bj_power_mes/internal/logic/semi.go b/bj_power_mes/internal/logic/semi.go
index 1be9d39..515f2f9 100644
--- a/bj_power_mes/internal/logic/semi.go
+++ b/bj_power_mes/internal/logic/semi.go
@@ -38,7 +38,7 @@ func (s *Service) SemiFlow(ctx context.Context, req SemiReq, operator string) er
return errors.New("工件未上线,无法暂存退库")
}
completedText := ""
- if wp.CurrentStationNo > 0 {
+ if wp.CurrentStationNo != 0 {
completedText = "已完成至工位" + itoa(wp.CurrentStationNo)
}
// 归属随产品工号自动继承:工件 → 工单 → 归属类型/归属编号/产品工号
diff --git a/bj_power_mes/internal/logic/settings.go b/bj_power_mes/internal/logic/settings.go
index e0dfac8..33d42ac 100644
--- a/bj_power_mes/internal/logic/settings.go
+++ b/bj_power_mes/internal/logic/settings.go
@@ -31,6 +31,8 @@ const (
CfgPipelineCache = "pipeline_cache"
// CfgAllowCrossDay 允许叫非今日排产的料(B5 跨日:1=允许(默认,工位端预警提示),0=禁止)
CfgAllowCrossDay = "call.allow_cross_day"
+ // CfgAllowBorrow 允许跨工位借料(1=允许(默认);0=禁止,超额叫料直接拒绝)
+ CfgAllowBorrow = "call.allow_borrow"
// CfgTorqueNgAlert 拧紧不合格报警开关(B2.1):1=开启(默认,拧紧扭矩不合格立即落预警),0=关闭(只写 step_data + 置待处置标记,不落预警)
CfgTorqueNgAlert = "torque.ng.alert.enabled"
// CfgDashboardRefreshSeconds 看板大屏轮询兜底刷新间隔(秒,1~10):仅影响 SSE 实时通道不可用时的 HTTP 轮询周期(默认 5)
@@ -58,6 +60,7 @@ type SettingsVO struct {
LogRetentionDays int `json:"logRetentionDays"` // 事件日志保留天数(0=不清理)
PipelineCache int `json:"pipelineCache"` // 滚筒线缓存模式(1=缓存并行,0=串行;预留,PLC 真机接入时生效)
AllowCrossDay int `json:"allowCrossDay"` // 允许叫非今日排产的料(1=允许(默认),0=禁止)
+ AllowBorrow int `json:"allowBorrow"` // 允许跨工位借料(1=允许(默认),0=禁止;关闭后超额叫料直接拒绝)
TorqueNgAlert bool `json:"torqueNgAlert"` // 拧紧不合格报警开关(1=开启,0=关闭)
DashboardRefreshSeconds int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,1~10)
ArchiveRemindDays int `json:"archiveRemindDays"` // 数据归档提醒周期(天,0=关闭)
@@ -82,6 +85,7 @@ type SettingsReq struct {
LogRetentionDays *int `json:"logRetentionDays"`
PipelineCache *int `json:"pipelineCache"`
AllowCrossDay *int `json:"allowCrossDay"`
+ AllowBorrow *int `json:"allowBorrow"`
TorqueNgAlert *bool `json:"torqueNgAlert"` // B2.1 拧紧不合格报警开关(nil=不改)
DashboardRefreshSeconds *int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,nil=不改)
ArchiveRemindDays *int `json:"archiveRemindDays"` // 数据归档提醒周期(天,nil=不改)
@@ -97,6 +101,7 @@ var settingsDefaults = map[string]int{
CfgLogRetention: 0,
CfgPipelineCache: 0,
CfgAllowCrossDay: 1,
+ CfgAllowBorrow: 1,
CfgTorqueNgAlert: 1, // B2.1 默认开启拧紧不合格报警
CfgDashboardRefreshSeconds: 5, // 看板轮询兜底刷新间隔(秒)
CfgArchiveRemindDays: 7, // 数据归档提醒周期(天)
@@ -119,6 +124,7 @@ func (s *Service) GetSettings(ctx context.Context) (*SettingsVO, error) {
LogRetentionDays: cfgIntFrom(kv, CfgLogRetention),
PipelineCache: cfgIntFrom(kv, CfgPipelineCache),
AllowCrossDay: cfgIntFrom(kv, CfgAllowCrossDay),
+ AllowBorrow: cfgIntFrom(kv, CfgAllowBorrow),
TorqueNgAlert: s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1, // B2.1 默认开启
DashboardRefreshSeconds: cfgIntFrom(kv, CfgDashboardRefreshSeconds),
ArchiveRemindDays: cfgIntFrom(kv, CfgArchiveRemindDays),
@@ -157,6 +163,7 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st
{CfgLogRetention, req.LogRetentionDays, 0, 3650, "事件日志保留天数(0=不清理)"},
{CfgPipelineCache, req.PipelineCache, 0, 1, "滚筒线缓存模式(1=启用缓存位并行流转,0=串行不缓存);预留配置,PLC 真机接入时生效"},
{CfgAllowCrossDay, req.AllowCrossDay, 0, 1, "允许叫非今日排产的料(1=允许,工位端预警提示;0=禁止)"},
+ {CfgAllowBorrow, req.AllowBorrow, 0, 1, "允许跨工位借料(1=允许(默认),工位端手动分配借料来源;0=禁止,超额叫料直接拒绝)"},
{CfgDashboardRefreshSeconds, req.DashboardRefreshSeconds, 1, 10, "看板轮询兜底刷新间隔(秒,1~10,仅 SSE 不可用时的 HTTP 轮询周期)"},
{CfgArchiveRemindDays, req.ArchiveRemindDays, 0, 365, "数据归档提醒周期(天,0=关闭;距上次成功备份超过该天数时提醒)"},
}
diff --git a/bj_power_mes/internal/logic/workorder.go b/bj_power_mes/internal/logic/workorder.go
index 2ed4044..79de1bd 100644
--- a/bj_power_mes/internal/logic/workorder.go
+++ b/bj_power_mes/internal/logic/workorder.go
@@ -31,8 +31,6 @@ type WorkOrderReq struct {
ContractNo string `json:"contractNo"`
OwnershipType string `json:"ownershipType"` // workorder=合同号/project=科技项目号/other=其他
ProductSerial string `json:"productSerial"`
- // 完成日期(必填,前端强制;yyyy-MM-dd)
- DueDate string `json:"dueDate"`
// 工艺组合(唯一路线源头):[{flowId,stationNo}],工位号即顺序号,按工位号升序执行、可跳过未选工位
FlowCombination []map[string]int `json:"flowCombination"`
// 来源产品工艺(2026-10-09):建单选产品时带出默认产品工艺并自动填组合;
@@ -125,12 +123,6 @@ func (s *Service) CreateWorkOrder(ctx context.Context, req WorkOrderReq, operato
wo, _ = client.WorkOrder.UpdateOneID(wo.ID).SetPlanEnd(t).Save(ctx)
}
}
- // 完成日期(Item M):前端必填,后端有值即落库
- if req.DueDate != "" {
- if t, err := parseDate(req.DueDate); err == nil {
- wo, _ = client.WorkOrder.UpdateOneID(wo.ID).SetDueDate(t).Save(ctx)
- }
- }
// 工艺组合(唯一路线源头):收集式校验已通过,此处直接写入
if len(comboItems) > 0 {
if _, err := client.WorkOrder.UpdateOneID(wo.ID).SetFlowCombination(flowItemsToMaps(comboItems)).Save(ctx); err != nil {
@@ -308,11 +300,6 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
u.SetPlanEnd(t)
}
}
- if req.DueDate != "" {
- if t, err := parseDate(req.DueDate); err == nil {
- u.SetDueDate(t)
- }
- }
if err := u.Exec(ctx); err != nil {
return err
}
@@ -328,7 +315,7 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
// 工程编号查询已随编号体系改造移除,字段保留仅防历史迁移)。
// keyword:跨字段模糊(工单号/产品编码/产品名称/合同号 任一命中),供下拉远程搜索用;
// limit:>0 时启用截断(封顶 200),仅下拉搜索场景传参,列表页不传=全量,行为向后兼容。
-func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, dueFrom, dueTo, keyword string, limit int) ([]*ent.WorkOrder, error) {
+func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, keyword string, limit int) ([]*ent.WorkOrder, error) {
q := s.ctx.EntClient.WorkOrder.Query()
if orderNo != "" {
q = q.Where(workorder.WorkOrderNoContainsFold(orderNo))
@@ -348,17 +335,6 @@ func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCo
if ownershipType != "" {
q = q.Where(workorder.OwnershipType(ownershipType))
}
- // 完成日期范围(Item M)
- if dueFrom != "" {
- if t, err := parseDate(dueFrom); err == nil {
- q = q.Where(workorder.DueDateGTE(t))
- }
- }
- if dueTo != "" {
- if t, err := parseDate(dueTo); err == nil {
- q = q.Where(workorder.DueDateLTE(t))
- }
- }
// keyword 跨字段模糊(下拉远程搜索):工单号/产品编码/产品名称/合同号 任一命中
if keyword != "" {
kw := workorder.Or(
diff --git a/bj_power_mes/internal/logic/workpiece.go b/bj_power_mes/internal/logic/workpiece.go
index 1438973..b4645cd 100644
--- a/bj_power_mes/internal/logic/workpiece.go
+++ b/bj_power_mes/internal/logic/workpiece.go
@@ -28,6 +28,15 @@ import (
func itoa(n int) string { return strconv.Itoa(n) }
+// joinIntsLocal 整数切片转逗号串(reonline 候选工位提示用,避免跨包依赖)。
+func joinIntsLocal(ns []int) string {
+ p := make([]string, 0, len(ns))
+ for _, v := range ns {
+ p = append(p, itoa(v))
+ }
+ return strings.Join(p, ",")
+}
+
// evalLogic 依据考核逻辑判定
func evalLogic(c *ent.StepCriterion, v float64) bool {
switch c.Logic {
@@ -210,17 +219,15 @@ func (s *Service) onlineNewWorkpiece(ctx context.Context, wp *ent.Workpiece, req
if len(items) == 0 {
return "", nil, errors.New("工单未配置工艺组合")
}
- first := items[0].StationNo
- for _, it := range items {
- if it.StationNo < first {
- first = it.StationNo
- }
- }
- if req.StationNo <= 0 {
+ // 并行候选工位:新件建档可落在「首道工序」的任一候选工位(闲着的工位去哪个)
+ route := groupFlowRoute(items)
+ firstStations := route[0].Stations
+ if req.StationNo == 0 {
return "", nil, errors.New("建档落点工位必填")
}
- if req.StationNo != first {
- return "", nil, fmt.Errorf("新件建档必须落在工序1工位(工位%d),当前落点工位%d不符合资格", first, req.StationNo)
+ if !intsContains(firstStations, req.StationNo) {
+ return "", nil, fmt.Errorf("新件建档必须落在第1道工序的候选工位(%s)之一,当前落点工位%d不符合资格",
+ joinIntsLocal(firstStations), req.StationNo)
}
station := req.StationNo
if _, e := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
@@ -252,42 +259,51 @@ func (s *Service) reonlineWorkpiece(ctx context.Context, wp *ent.Workpiece, req
if len(items) == 0 {
return "", nil, errors.New("工单未配置工艺组合")
}
- next, nextFlow := 0, 0
- for _, it := range items {
- if it.StationNo > wp.CurrentStationNo && (next == 0 || it.StationNo < next) {
- next, nextFlow = it.StationNo, it.FlowId
+ route := groupFlowRoute(items)
+ nextSeq, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, wp.Sn, route)
+ if doneAll {
+ return "", nil, fmt.Errorf("工件已报工至最后一道工序,工艺组合中无下一站")
+ }
+ var nextFlow *FlowRouteStep
+ for i := range route {
+ if route[i].Seq == nextSeq {
+ nextFlow = &route[i]
+ break
}
}
- if next == 0 {
- return "", nil, fmt.Errorf("工件已报工至工位%d,工艺组合中无下一站", wp.CurrentStationNo)
- }
- // 二.4 资格校验:半成品(SEMI_STORED)重上线落点须为后续工序工位(=下一站);落点未传时按下一站执行
- if req.StationNo > 0 && req.StationNo != next {
- return "", nil, fmt.Errorf("半成品重上线须落在后续工序工位(工位%d),当前落点工位%d不符合资格", next, req.StationNo)
+ next := nextFlow.MinNo
+ // 二.4 资格校验:半成品(SEMI_STORED)重上线落点须为下一工序的候选工位之一;落点未传时按下一工序最小工位执行
+ if req.StationNo > 0 && !intsContains(nextFlow.Stations, req.StationNo) {
+ return "", nil, fmt.Errorf("半成品重上线须落在下一工序(候选工位%s)内,当前落点工位%d不符合资格",
+ joinIntsLocal(nextFlow.Stations), req.StationNo)
}
if err := s.SemiFlow(ctx, SemiReq{Sn: wp.Sn, OrderNo: wp.OrderNo, Action: "OUTBOUND"}, operator); err != nil {
return "", nil, fmt.Errorf("重上线失败:%s", err.Error())
}
- // 出库一次解锁一次(问题.md 一.5):置回 ONLINE,写物理位置=下一站,等待在所选工位重新上线建档。
+ // 出库一次解锁一次(问题.md 一.5):置回 ONLINE,写物理位置=所选落点(缺省下一工序最小工位),等待在所选工位重新上线建档。
+ land := req.StationNo
+ if land == 0 {
+ land = next
+ }
if _, e := s.ctx.EntClient.Workpiece.UpdateOneID(wp.ID).
- SetStatus("ONLINE").SetAtStationNo(next).Save(ctx); e != nil {
+ SetStatus("ONLINE").SetAtStationNo(land).Save(ctx); e != nil {
return "", nil, fmt.Errorf("重上线解锁状态失败:%s", e.Error())
}
// 二.2 物理位置 + 三.2 状态流水 SEMI_STORED→ONLINE(出库 SEMI_OUT)
- s.writeLifecycle(ctx, wp.Sn, wp.OrderNo, "SEMI_STORED", "ONLINE", next, 0, operator, "workstation", "半成品出库重上线")
- msg := fmt.Sprintf("重上线成功,继续执行:工位%d·%s", next, s.flowNameById(ctx, nextFlow))
- if s.GetStationPaused(ctx, next) {
- msg += "(注意:工位" + itoa(next) + "已停止接单)"
+ s.writeLifecycle(ctx, wp.Sn, wp.OrderNo, "SEMI_STORED", "ONLINE", land, 0, operator, "workstation", "半成品出库重上线")
+ msg := fmt.Sprintf("重上线成功,继续执行:工位%d·%s", land, s.flowNameById(ctx, nextFlow.FlowId))
+ if s.GetStationPaused(ctx, land) {
+ msg += "(注意:工位" + itoa(land) + "已停止接单)"
}
s.ctx.EventLog.Write(ctx, "workpiece.reonline", wp.OrderNo, operator, "workpiece", wp.Sn,
- "工件重上线(暂存退库后出库继续)", map[string]any{"nextStationNo": next, "nextFlowId": nextFlow, "pointNo": req.PointNo})
+ "工件重上线(暂存退库后出库继续)", map[string]any{"nextStationNo": land, "nextFlowId": nextFlow.FlowId, "pointNo": req.PointNo})
// 工件当前位置落账(点位台账:重上线即占位)
if err := s.occupyStartPoint(ctx, req.PointNo, wp.Sn, wp.OrderNo, operator); err != nil {
return "", nil, err
}
s.notifyDashboard()
// PLC↔MES 对账(#8 T5 建档提交):提示不拦,仅透出 mismatch 供终端弹窗
- mm, _ := s.detectAndRecord(ctx, next, "terminal", wp.OrderNo, operator)
+ mm, _ := s.detectAndRecord(ctx, land, "terminal", wp.OrderNo, operator)
return msg, mm, nil
}
@@ -385,7 +401,7 @@ func parseClientTime(s string) (time.Time, error) {
// 电气件按单台用量逐颗SN、结构件至少一个批次号;缺料直接拒绝报工并返回缺料清单。
// 顺序校验(工单工艺组合为唯一路线源头):报工工位必须在组合中、工艺匹配,且不可倒序(可跳过未选工位)。
func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, operator string, operatorId int) error {
- if req.Sn == "" || req.StationNo <= 0 {
+ if req.Sn == "" || req.StationNo == 0 {
return errors.New("sn 与 stationNo 必填")
}
// PLC↔MES 对账(#8 T4 报工提交):命中 mismatch 则阻断报工,提示先处理该工位托盘位异常
@@ -420,23 +436,33 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
if err != nil || wo == nil {
return errors.New("工件所属工单不存在")
}
- items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo)
- matched := false
- for _, it := range items {
- if it.StationNo == req.StationNo {
- matched = true
- if it.FlowId != flowId {
- return fmt.Errorf("工位%d当前工艺与工单工艺组合不匹配", req.StationNo)
- }
+ // 并行候选工位模型(2026-11-02):同工序可配置多个候选工位,工件在任一候选工位报工一次即完成该工序;
+ // 不可跳工序(须按工序顺序),同工序已报工则不可重复报工。
+ route, _ := FlowRouteOfWO(ctx, s.ctx.EntClient, wo)
+ if len(route) == 0 {
+ return errors.New("工单未配置工艺组合")
+ }
+ var cur *FlowRouteStep
+ for i := range route {
+ if route[i].FlowId == flowId && intsContains(route[i].Stations, req.StationNo) {
+ cur = &route[i]
break
}
}
- if !matched {
- return fmt.Errorf("工位%d不在该工单的工艺组合中,不可报工", req.StationNo)
+ if cur == nil {
+ return fmt.Errorf("工位%d不在该工序「%s」的候选工位中,不可报工", req.StationNo, s.flowNameById(ctx, flowId))
}
- if req.StationNo <= wp.CurrentStationNo {
- return errors.New("不可倒序报工:工件已报工到工位" + itoa(wp.CurrentStationNo) +
- ",不能在工位" + itoa(req.StationNo) + "重复/回退报工")
+ // 不可跳工序 / 不可重复:本工序必须是第一个「尚未有 DONE 报工」的工序
+ nextSeq, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, req.Sn, route)
+ if doneAll {
+ return errors.New("该工件所有工序已报工完成")
+ }
+ if cur.Seq != nextSeq {
+ if done, _ := s.ctx.EntClient.WorkpieceProcess.Query().
+ Where(workpieceprocess.Sn(req.Sn), workpieceprocess.FlowId(flowId), workpieceprocess.Status("DONE")).Exist(ctx); done {
+ return errors.New("该工序已报工完成,不可重复报工")
+ }
+ return errors.New("不可跳工序:请先完成上一道工序")
}
// 报工是"装机绑定→校验齐套→写实绩→写步骤考核→回写结果/工件状态"的多步写,必须整体事务化(方案 U3):
// 任一步失败全部回滚,杜绝"实绩已建但工件状态没推进/结果没落"的半成品脏数据;
@@ -468,7 +494,8 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
// 阶段2:检测确认(needCheck)强校验——服务端为准,前端勾选只是辅助提示。
// 本工位在本工艺组合中的出现序号 k 对应步骤 seq=k,标记“需要检测确认”的步骤须带 checked=true。
// k 由组合派生(第 k 次出现 ↔ 步骤 seq=k),与签字校验同源,避免跨工位误拦。
- k := stationSeqInFlow(items, flowId, req.StationNo)
+ // 并行候选工位:每道工序只报工一次(对应一次步骤序号),与历史「1工序1工位」语义一致,k 恒为 1
+ k := 1
if err := s.validateNeedCheck(ctx, client, req, flowId, k); err != nil {
return err
}
@@ -605,6 +632,19 @@ func stationSeqInFlow(items []FlowItem, flowId, stationNo int) int {
return k
}
+// firstUndoneFlowSeq 返回工件尚未完成(无 DONE 报工记录)的第一道工序序号(route.Seq);
+// 全部完成返回 (0, true)。并行候选工位模型下,工序完成以「该工序任一候选工位已报工 DONE」判定。
+func (s *Service) firstUndoneFlowSeq(ctx context.Context, client *ent.Client, sn string, route []FlowRouteStep) (int, bool) {
+ for _, f := range route {
+ done, _ := client.WorkpieceProcess.Query().
+ Where(workpieceprocess.Sn(sn), workpieceprocess.FlowId(f.FlowId), workpieceprocess.Status("DONE")).Exist(ctx)
+ if !done {
+ return f.Seq, false
+ }
+ }
+ return 0, true
+}
+
// validateNeedSign 签字机制(需求B)服务端强校验,返回本工位在本工艺组合中的出现序号 k:
// 组合条目(按工位号升序)与工艺步骤 seq 一一对应——本工艺在组合中第 k 次出现 ↔ 步骤 seq=k。
// - needOperatorSign:仅校验「本次报工步骤」(seq=k),报工请求必须携带对应操作工签字;
@@ -773,7 +813,7 @@ func (s *Service) DoneWorkpiece(ctx context.Context, req DoneReq, operator strin
// 二.2 物理位置:完工/入库均清空 at_station(件已离产线/入半成品库)。
// 三.2 入库次数统一 count(action='SEMI_IN'),不再依赖 semiflow(CountSemiStored 已删)。
routeItems, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo)
- routeCount := len(routeItems)
+ routeCount := DistinctFlowCount(routeItems) // 并行候选工位:按工序数判定,而非工位数
reported := 0
if routeCount > 0 {
reported, _ = s.ctx.EntClient.WorkpieceProcess.Query().
@@ -1063,21 +1103,17 @@ func (s *Service) WorkpiecesInProcess(ctx context.Context, stationNo int, orderN
return wo
}
for _, wp := range list {
- // 路线 = 工单工艺组合(唯一路线源头);未配置组合则无路线(maxStation=0)
+ // 路线 = 工单工艺组合(唯一路线源头);并行候选工位按工序级聚合
items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, getWO(wp))
- seq := RouteStationsOfWO(items)
- maxStation := 0
- for _, c := range seq {
- if c > maxStation {
- maxStation = c
- }
- }
+ route := groupFlowRoute(items)
+ total := DistinctFlowCount(items)
// 显示口径按 status 派生(原 0/13 魔法值已废除,业务定稿·一.10):
// 待流转 = ONLINE 未报工(未分配工位)
- // 末端待取件 = PROCESSING 且已报工至工艺路线末端工位
+ // 末端待取件 = PROCESSING 且所有工序已报工完成
// 其余 = 真实工位显示名
cur := wp.CurrentStationNo
- atEnd := wp.Status == "PROCESSING" && maxStation > 0 && cur >= maxStation
+ _, doneAll := s.firstUndoneFlowSeq(ctx, s.ctx.EntClient, wp.Sn, route)
+ atEnd := wp.Status == "PROCESSING" && doneAll
switch scope {
case "pending":
if wp.Status != "ONLINE" || cur > 0 {
@@ -1133,7 +1169,7 @@ func (s *Service) WorkpiecesInProcess(ctx context.Context, stationNo int, orderN
OnlineAt: onlineAt,
DwellSec: dwell,
DoneSteps: done,
- TotalSteps: len(seq),
+ TotalSteps: total,
})
}
return out, nil
diff --git a/bj_power_mes/public/index.html b/bj_power_mes/public/index.html
index 4ae5dc3..c0896d5 100644
--- a/bj_power_mes/public/index.html
+++ b/bj_power_mes/public/index.html
@@ -6,7 +6,7 @@
MES 产线控制
-
+
diff --git a/bj_power_mes/schema/material_request.go b/bj_power_mes/schema/material_request.go
index 27b307a..97ba12f 100644
--- a/bj_power_mes/schema/material_request.go
+++ b/bj_power_mes/schema/material_request.go
@@ -4,6 +4,7 @@ import (
"time"
"entgo.io/ent"
+ "entgo.io/ent/dialect"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
@@ -56,6 +57,12 @@ func (MaterialRequest) Fields() []ent.Field {
field.Bool("crossDay").Default(false).Comment("跨日标记:叫料池行含非今日排产(工位预警+仓库可驳回异常)"),
field.String("outboundNo").Default("").MaxLen(255).Comment("WMS 出库单号(完成备料回写,多个逗号分隔)"),
field.String("rejectReason").Default("").MaxLen(128).Comment("驳回理由(仓库拒发时必填)"),
+ // 跨工位借料来源:sourceStationNo(字符串键)→实际借用量;空 {} = 本工位自取(不借)。
+ // 当本工位可用不足时,系统自动从「同工艺候选工位」的剩余额度借用并如实记录;借出工位额度相应扣减。
+ // 叫料池四数账按真实消耗的工位行记账(与是否借料无关),来源仅用于追溯与额度回补。
+ field.JSON("borrowFrom", map[string]int{}).Optional().SchemaType(map[string]string{
+ dialect.Postgres: "jsonb",
+ }).Comment("跨工位借料来源 stationNo→借用量;空=本工位自取"),
field.String("operator").Default("").MaxLen(64),
field.Time("createdAt").Default(time.Now).Immutable(),
field.Time("updatedAt").Default(time.Now).UpdateDefault(time.Now).Optional().Nillable(),
diff --git a/bj_power_mes/schema/work_order.go b/bj_power_mes/schema/work_order.go
index 5f31eff..2e2c65b 100644
--- a/bj_power_mes/schema/work_order.go
+++ b/bj_power_mes/schema/work_order.go
@@ -38,9 +38,8 @@ func (WorkOrder) Fields() []ent.Field {
// 工程编号已被合同号顶替(客户口径):字段保留仅防历史数据迁移,UI 不再展示/录入/查询
field.String("projectNo").Default("").MaxLen(64).Comment("工程编号(已废弃,保留防历史数据迁移)"),
field.String("productSerial").Default("").MaxLen(64).Comment("产品序号(工单内每台产品的序号)"),
- // 创建人(取当前登录用户)+ 完成日期(必填)
+ // 创建人(取当前登录用户)
field.String("createdBy").Default("").MaxLen(64).Comment("创建人"),
- field.Time("dueDate").Optional().Nillable().Comment("完成日期(必填)"),
// 工艺组合:本工单经过的 工艺→工位 清单(按工位号升序即执行顺序,可跳位、不可倒序)。
// 由建单/编辑时人工勾选(绑定工位默认全选);自动排产/备料/报工/PLC 全部以它为唯一路线源头。
field.JSON("flowCombination", []map[string]int{}).Optional().SchemaType(map[string]string{
diff --git a/bj_power_wms/ent/migrate/schema.go b/bj_power_wms/ent/migrate/schema.go
index 07f0fbb..f1d265e 100644
--- a/bj_power_wms/ent/migrate/schema.go
+++ b/bj_power_wms/ent/migrate/schema.go
@@ -606,6 +606,7 @@ var (
{Name: "box_no", Type: field.TypeString, Nullable: true, Comment: "箱号(装箱出库时填写,用于整箱发货追溯)"},
{Name: "box_sn_list", Type: field.TypeString, Nullable: true, Comment: "装箱 SN 清单(JSON 数组字符串)"},
{Name: "contract_no", Type: field.TypeString, Nullable: true, Comment: "合同号(装箱选填)"},
+ {Name: "borrow_from", Type: field.TypeJSON, Nullable: true, Comment: "跨工位借料来源 stationNo→借用量(call 备料出库专用);空=本工位自取"},
{Name: "inspection_no", Type: field.TypeString, Nullable: true, Comment: "检测单号(溯源关联检验单据)"},
{Name: "product_work_no", Type: field.TypeString, Nullable: true, Comment: "产品工号(随库存带入,出库记录展示/筛选)"},
{Name: "created_at", Type: field.TypeInt64, Comment: "创建时间"},
@@ -640,7 +641,7 @@ var (
{
Name: "outboundorder_inspection_no",
Unique: false,
- Columns: []*schema.Column{OutboundOrdersColumns[27]},
+ Columns: []*schema.Column{OutboundOrdersColumns[28]},
},
},
}
diff --git a/bj_power_wms/ent/mutation.go b/bj_power_wms/ent/mutation.go
index 0132ac1..42b5689 100644
--- a/bj_power_wms/ent/mutation.go
+++ b/bj_power_wms/ent/mutation.go
@@ -17584,6 +17584,7 @@ type OutboundOrderMutation struct {
box_no *string
box_sn_list *string
contract_no *string
+ borrowFrom *map[string]int
inspection_no *string
product_work_no *string
created_at *int64
@@ -18922,6 +18923,55 @@ func (m *OutboundOrderMutation) ResetContractNo() {
delete(m.clearedFields, outboundorder.FieldContractNo)
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (m *OutboundOrderMutation) SetBorrowFrom(value map[string]int) {
+ m.borrowFrom = &value
+}
+
+// BorrowFrom returns the value of the "borrowFrom" field in the mutation.
+func (m *OutboundOrderMutation) BorrowFrom() (r map[string]int, exists bool) {
+ v := m.borrowFrom
+ if v == nil {
+ return
+ }
+ return *v, true
+}
+
+// OldBorrowFrom returns the old "borrowFrom" field's value of the OutboundOrder entity.
+// If the OutboundOrder object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *OutboundOrderMutation) OldBorrowFrom(ctx context.Context) (v map[string]int, err error) {
+ if !m.op.Is(OpUpdateOne) {
+ return v, errors.New("OldBorrowFrom is only allowed on UpdateOne operations")
+ }
+ if m.id == nil || m.oldValue == nil {
+ return v, errors.New("OldBorrowFrom requires an ID field in the mutation")
+ }
+ oldValue, err := m.oldValue(ctx)
+ if err != nil {
+ return v, fmt.Errorf("querying old value for OldBorrowFrom: %w", err)
+ }
+ return oldValue.BorrowFrom, nil
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (m *OutboundOrderMutation) ClearBorrowFrom() {
+ m.borrowFrom = nil
+ m.clearedFields[outboundorder.FieldBorrowFrom] = struct{}{}
+}
+
+// BorrowFromCleared returns if the "borrowFrom" field was cleared in this mutation.
+func (m *OutboundOrderMutation) BorrowFromCleared() bool {
+ _, ok := m.clearedFields[outboundorder.FieldBorrowFrom]
+ return ok
+}
+
+// ResetBorrowFrom resets all changes to the "borrowFrom" field.
+func (m *OutboundOrderMutation) ResetBorrowFrom() {
+ m.borrowFrom = nil
+ delete(m.clearedFields, outboundorder.FieldBorrowFrom)
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (m *OutboundOrderMutation) SetInspectionNo(s string) {
m.inspection_no = &s
@@ -19110,7 +19160,7 @@ func (m *OutboundOrderMutation) Type() string {
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *OutboundOrderMutation) Fields() []string {
- fields := make([]string, 0, 29)
+ fields := make([]string, 0, 30)
if m.outbound_no != nil {
fields = append(fields, outboundorder.FieldOutboundNo)
}
@@ -19189,6 +19239,9 @@ func (m *OutboundOrderMutation) Fields() []string {
if m.contract_no != nil {
fields = append(fields, outboundorder.FieldContractNo)
}
+ if m.borrowFrom != nil {
+ fields = append(fields, outboundorder.FieldBorrowFrom)
+ }
if m.inspection_no != nil {
fields = append(fields, outboundorder.FieldInspectionNo)
}
@@ -19258,6 +19311,8 @@ func (m *OutboundOrderMutation) Field(name string) (ent.Value, bool) {
return m.BoxSnList()
case outboundorder.FieldContractNo:
return m.ContractNo()
+ case outboundorder.FieldBorrowFrom:
+ return m.BorrowFrom()
case outboundorder.FieldInspectionNo:
return m.InspectionNo()
case outboundorder.FieldProductWorkNo:
@@ -19325,6 +19380,8 @@ func (m *OutboundOrderMutation) OldField(ctx context.Context, name string) (ent.
return m.OldBoxSnList(ctx)
case outboundorder.FieldContractNo:
return m.OldContractNo(ctx)
+ case outboundorder.FieldBorrowFrom:
+ return m.OldBorrowFrom(ctx)
case outboundorder.FieldInspectionNo:
return m.OldInspectionNo(ctx)
case outboundorder.FieldProductWorkNo:
@@ -19522,6 +19579,13 @@ func (m *OutboundOrderMutation) SetField(name string, value ent.Value) error {
}
m.SetContractNo(v)
return nil
+ case outboundorder.FieldBorrowFrom:
+ v, ok := value.(map[string]int)
+ if !ok {
+ return fmt.Errorf("unexpected type %T for field %s", value, name)
+ }
+ m.SetBorrowFrom(v)
+ return nil
case outboundorder.FieldInspectionNo:
v, ok := value.(string)
if !ok {
@@ -19678,6 +19742,9 @@ func (m *OutboundOrderMutation) ClearedFields() []string {
if m.FieldCleared(outboundorder.FieldContractNo) {
fields = append(fields, outboundorder.FieldContractNo)
}
+ if m.FieldCleared(outboundorder.FieldBorrowFrom) {
+ fields = append(fields, outboundorder.FieldBorrowFrom)
+ }
if m.FieldCleared(outboundorder.FieldInspectionNo) {
fields = append(fields, outboundorder.FieldInspectionNo)
}
@@ -19752,6 +19819,9 @@ func (m *OutboundOrderMutation) ClearField(name string) error {
case outboundorder.FieldContractNo:
m.ClearContractNo()
return nil
+ case outboundorder.FieldBorrowFrom:
+ m.ClearBorrowFrom()
+ return nil
case outboundorder.FieldInspectionNo:
m.ClearInspectionNo()
return nil
@@ -19844,6 +19914,9 @@ func (m *OutboundOrderMutation) ResetField(name string) error {
case outboundorder.FieldContractNo:
m.ResetContractNo()
return nil
+ case outboundorder.FieldBorrowFrom:
+ m.ResetBorrowFrom()
+ return nil
case outboundorder.FieldInspectionNo:
m.ResetInspectionNo()
return nil
diff --git a/bj_power_wms/ent/outboundorder.go b/bj_power_wms/ent/outboundorder.go
index f296cca..be7d943 100644
--- a/bj_power_wms/ent/outboundorder.go
+++ b/bj_power_wms/ent/outboundorder.go
@@ -4,6 +4,7 @@ package ent
import (
"bj_power_wms/ent/outboundorder"
+ "encoding/json"
"fmt"
"strings"
@@ -68,6 +69,8 @@ type OutboundOrder struct {
BoxSnList string `json:"boxSnList,omitempty"`
// 合同号(装箱选填)
ContractNo string `json:"contractNo,omitempty"`
+ // 跨工位借料来源 stationNo→借用量(call 备料出库专用);空=本工位自取
+ BorrowFrom map[string]int `json:"borrowFrom,omitempty"`
// 检测单号(溯源关联检验单据)
InspectionNo string `json:"inspectionNo,omitempty"`
// 产品工号(随库存带入,出库记录展示/筛选)
@@ -82,6 +85,8 @@ func (*OutboundOrder) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
+ case outboundorder.FieldBorrowFrom:
+ values[i] = new([]byte)
case outboundorder.FieldNeedAgv:
values[i] = new(sql.NullBool)
case outboundorder.FieldID, outboundorder.FieldManageMode, outboundorder.FieldSnMode, outboundorder.FieldQuantity, outboundorder.FieldCreatedAt:
@@ -265,6 +270,14 @@ func (_m *OutboundOrder) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.ContractNo = value.String
}
+ case outboundorder.FieldBorrowFrom:
+ if value, ok := values[i].(*[]byte); !ok {
+ return fmt.Errorf("unexpected type %T for field borrowFrom", values[i])
+ } else if value != nil && len(*value) > 0 {
+ if err := json.Unmarshal(*value, &_m.BorrowFrom); err != nil {
+ return fmt.Errorf("unmarshal field borrowFrom: %w", err)
+ }
+ }
case outboundorder.FieldInspectionNo:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field inspection_no", values[i])
@@ -397,6 +410,9 @@ func (_m *OutboundOrder) String() string {
builder.WriteString("contract_no=")
builder.WriteString(_m.ContractNo)
builder.WriteString(", ")
+ builder.WriteString("borrowFrom=")
+ builder.WriteString(fmt.Sprintf("%v", _m.BorrowFrom))
+ builder.WriteString(", ")
builder.WriteString("inspection_no=")
builder.WriteString(_m.InspectionNo)
builder.WriteString(", ")
diff --git a/bj_power_wms/ent/outboundorder/outboundorder.go b/bj_power_wms/ent/outboundorder/outboundorder.go
index 7d52a15..1ae3d3d 100644
--- a/bj_power_wms/ent/outboundorder/outboundorder.go
+++ b/bj_power_wms/ent/outboundorder/outboundorder.go
@@ -63,6 +63,8 @@ const (
FieldBoxSnList = "box_sn_list"
// FieldContractNo holds the string denoting the contract_no field in the database.
FieldContractNo = "contract_no"
+ // FieldBorrowFrom holds the string denoting the borrowfrom field in the database.
+ FieldBorrowFrom = "borrow_from"
// FieldInspectionNo holds the string denoting the inspection_no field in the database.
FieldInspectionNo = "inspection_no"
// FieldProductWorkNo holds the string denoting the product_work_no field in the database.
@@ -102,6 +104,7 @@ var Columns = []string{
FieldBoxNo,
FieldBoxSnList,
FieldContractNo,
+ FieldBorrowFrom,
FieldInspectionNo,
FieldProductWorkNo,
FieldCreatedAt,
diff --git a/bj_power_wms/ent/outboundorder/where.go b/bj_power_wms/ent/outboundorder/where.go
index d7e907a..862c5a1 100644
--- a/bj_power_wms/ent/outboundorder/where.go
+++ b/bj_power_wms/ent/outboundorder/where.go
@@ -1938,6 +1938,16 @@ func ContractNoContainsFold(v string) predicate.OutboundOrder {
return predicate.OutboundOrder(sql.FieldContainsFold(FieldContractNo, v))
}
+// BorrowFromIsNil applies the IsNil predicate on the "borrowFrom" field.
+func BorrowFromIsNil() predicate.OutboundOrder {
+ return predicate.OutboundOrder(sql.FieldIsNull(FieldBorrowFrom))
+}
+
+// BorrowFromNotNil applies the NotNil predicate on the "borrowFrom" field.
+func BorrowFromNotNil() predicate.OutboundOrder {
+ return predicate.OutboundOrder(sql.FieldNotNull(FieldBorrowFrom))
+}
+
// InspectionNoEQ applies the EQ predicate on the "inspection_no" field.
func InspectionNoEQ(v string) predicate.OutboundOrder {
return predicate.OutboundOrder(sql.FieldEQ(FieldInspectionNo, v))
diff --git a/bj_power_wms/ent/outboundorder_create.go b/bj_power_wms/ent/outboundorder_create.go
index e4fe8d6..647dfc7 100644
--- a/bj_power_wms/ent/outboundorder_create.go
+++ b/bj_power_wms/ent/outboundorder_create.go
@@ -369,6 +369,12 @@ func (_c *OutboundOrderCreate) SetNillableContractNo(v *string) *OutboundOrderCr
return _c
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_c *OutboundOrderCreate) SetBorrowFrom(v map[string]int) *OutboundOrderCreate {
+ _c.mutation.SetBorrowFrom(v)
+ return _c
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (_c *OutboundOrderCreate) SetInspectionNo(v string) *OutboundOrderCreate {
_c.mutation.SetInspectionNo(v)
@@ -636,6 +642,10 @@ func (_c *OutboundOrderCreate) createSpec() (*OutboundOrder, *sqlgraph.CreateSpe
_spec.SetField(outboundorder.FieldContractNo, field.TypeString, value)
_node.ContractNo = value
}
+ if value, ok := _c.mutation.BorrowFrom(); ok {
+ _spec.SetField(outboundorder.FieldBorrowFrom, field.TypeJSON, value)
+ _node.BorrowFrom = value
+ }
if value, ok := _c.mutation.InspectionNo(); ok {
_spec.SetField(outboundorder.FieldInspectionNo, field.TypeString, value)
_node.InspectionNo = value
@@ -1138,6 +1148,24 @@ func (u *OutboundOrderUpsert) ClearContractNo() *OutboundOrderUpsert {
return u
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (u *OutboundOrderUpsert) SetBorrowFrom(v map[string]int) *OutboundOrderUpsert {
+ u.Set(outboundorder.FieldBorrowFrom, v)
+ return u
+}
+
+// UpdateBorrowFrom sets the "borrowFrom" field to the value that was provided on create.
+func (u *OutboundOrderUpsert) UpdateBorrowFrom() *OutboundOrderUpsert {
+ u.SetExcluded(outboundorder.FieldBorrowFrom)
+ return u
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (u *OutboundOrderUpsert) ClearBorrowFrom() *OutboundOrderUpsert {
+ u.SetNull(outboundorder.FieldBorrowFrom)
+ return u
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (u *OutboundOrderUpsert) SetInspectionNo(v string) *OutboundOrderUpsert {
u.Set(outboundorder.FieldInspectionNo, v)
@@ -1743,6 +1771,27 @@ func (u *OutboundOrderUpsertOne) ClearContractNo() *OutboundOrderUpsertOne {
})
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (u *OutboundOrderUpsertOne) SetBorrowFrom(v map[string]int) *OutboundOrderUpsertOne {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.SetBorrowFrom(v)
+ })
+}
+
+// UpdateBorrowFrom sets the "borrowFrom" field to the value that was provided on create.
+func (u *OutboundOrderUpsertOne) UpdateBorrowFrom() *OutboundOrderUpsertOne {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.UpdateBorrowFrom()
+ })
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (u *OutboundOrderUpsertOne) ClearBorrowFrom() *OutboundOrderUpsertOne {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.ClearBorrowFrom()
+ })
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (u *OutboundOrderUpsertOne) SetInspectionNo(v string) *OutboundOrderUpsertOne {
return u.Update(func(s *OutboundOrderUpsert) {
@@ -2521,6 +2570,27 @@ func (u *OutboundOrderUpsertBulk) ClearContractNo() *OutboundOrderUpsertBulk {
})
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (u *OutboundOrderUpsertBulk) SetBorrowFrom(v map[string]int) *OutboundOrderUpsertBulk {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.SetBorrowFrom(v)
+ })
+}
+
+// UpdateBorrowFrom sets the "borrowFrom" field to the value that was provided on create.
+func (u *OutboundOrderUpsertBulk) UpdateBorrowFrom() *OutboundOrderUpsertBulk {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.UpdateBorrowFrom()
+ })
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (u *OutboundOrderUpsertBulk) ClearBorrowFrom() *OutboundOrderUpsertBulk {
+ return u.Update(func(s *OutboundOrderUpsert) {
+ s.ClearBorrowFrom()
+ })
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (u *OutboundOrderUpsertBulk) SetInspectionNo(v string) *OutboundOrderUpsertBulk {
return u.Update(func(s *OutboundOrderUpsert) {
diff --git a/bj_power_wms/ent/outboundorder_update.go b/bj_power_wms/ent/outboundorder_update.go
index a906d69..c082cf7 100644
--- a/bj_power_wms/ent/outboundorder_update.go
+++ b/bj_power_wms/ent/outboundorder_update.go
@@ -520,6 +520,18 @@ func (_u *OutboundOrderUpdate) ClearContractNo() *OutboundOrderUpdate {
return _u
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_u *OutboundOrderUpdate) SetBorrowFrom(v map[string]int) *OutboundOrderUpdate {
+ _u.mutation.SetBorrowFrom(v)
+ return _u
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (_u *OutboundOrderUpdate) ClearBorrowFrom() *OutboundOrderUpdate {
+ _u.mutation.ClearBorrowFrom()
+ return _u
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (_u *OutboundOrderUpdate) SetInspectionNo(v string) *OutboundOrderUpdate {
_u.mutation.SetInspectionNo(v)
@@ -763,6 +775,12 @@ func (_u *OutboundOrderUpdate) sqlSave(ctx context.Context) (_node int, err erro
if _u.mutation.ContractNoCleared() {
_spec.ClearField(outboundorder.FieldContractNo, field.TypeString)
}
+ if value, ok := _u.mutation.BorrowFrom(); ok {
+ _spec.SetField(outboundorder.FieldBorrowFrom, field.TypeJSON, value)
+ }
+ if _u.mutation.BorrowFromCleared() {
+ _spec.ClearField(outboundorder.FieldBorrowFrom, field.TypeJSON)
+ }
if value, ok := _u.mutation.InspectionNo(); ok {
_spec.SetField(outboundorder.FieldInspectionNo, field.TypeString, value)
}
@@ -1294,6 +1312,18 @@ func (_u *OutboundOrderUpdateOne) ClearContractNo() *OutboundOrderUpdateOne {
return _u
}
+// SetBorrowFrom sets the "borrowFrom" field.
+func (_u *OutboundOrderUpdateOne) SetBorrowFrom(v map[string]int) *OutboundOrderUpdateOne {
+ _u.mutation.SetBorrowFrom(v)
+ return _u
+}
+
+// ClearBorrowFrom clears the value of the "borrowFrom" field.
+func (_u *OutboundOrderUpdateOne) ClearBorrowFrom() *OutboundOrderUpdateOne {
+ _u.mutation.ClearBorrowFrom()
+ return _u
+}
+
// SetInspectionNo sets the "inspection_no" field.
func (_u *OutboundOrderUpdateOne) SetInspectionNo(v string) *OutboundOrderUpdateOne {
_u.mutation.SetInspectionNo(v)
@@ -1567,6 +1597,12 @@ func (_u *OutboundOrderUpdateOne) sqlSave(ctx context.Context) (_node *OutboundO
if _u.mutation.ContractNoCleared() {
_spec.ClearField(outboundorder.FieldContractNo, field.TypeString)
}
+ if value, ok := _u.mutation.BorrowFrom(); ok {
+ _spec.SetField(outboundorder.FieldBorrowFrom, field.TypeJSON, value)
+ }
+ if _u.mutation.BorrowFromCleared() {
+ _spec.ClearField(outboundorder.FieldBorrowFrom, field.TypeJSON)
+ }
if value, ok := _u.mutation.InspectionNo(); ok {
_spec.SetField(outboundorder.FieldInspectionNo, field.TypeString, value)
}
diff --git a/bj_power_wms/ent/runtime.go b/bj_power_wms/ent/runtime.go
index dfe0379..9067f3b 100644
--- a/bj_power_wms/ent/runtime.go
+++ b/bj_power_wms/ent/runtime.go
@@ -437,7 +437,7 @@ func init() {
// outboundorder.DefaultQuantity holds the default value on creation for the quantity field.
outboundorder.DefaultQuantity = outboundorderDescQuantity.Default.(int)
// outboundorderDescCreatedAt is the schema descriptor for created_at field.
- outboundorderDescCreatedAt := outboundorderFields[28].Descriptor()
+ outboundorderDescCreatedAt := outboundorderFields[29].Descriptor()
// outboundorder.DefaultCreatedAt holds the default value on creation for the created_at field.
outboundorder.DefaultCreatedAt = outboundorderDescCreatedAt.Default.(func() int64)
permissionFields := schema.Permission{}.Fields()
diff --git a/bj_power_wms/frontend/src/components/OutboundRecords.vue b/bj_power_wms/frontend/src/components/OutboundRecords.vue
index ce7f507..73836e7 100644
--- a/bj_power_wms/frontend/src/components/OutboundRecords.vue
+++ b/bj_power_wms/frontend/src/components/OutboundRecords.vue
@@ -41,6 +41,13 @@ const recPage = reactive({ current: 1, size: 10 })
function snOf(row) { return (row.details || []).map(d => d.snCode).filter(Boolean).join(',') }
+// 借料来源展示(出库单 borrow_from 已排除本工位自取,直接展示借出的兄弟工位)
+function borrowText(row) {
+ const b = row.borrowFrom || {}
+ const parts = Object.entries(b).filter(([, v]) => Number(v) > 0).map(([k, v]) => `工位${k} ${v}个`)
+ return parts.length ? parts.join('、') : ''
+}
+
async function loadRecords() {
loadingRec.value = true
try {
@@ -84,6 +91,12 @@ function downloadCSV() {
.then((name) => { if (name) ElMessage.success('已导出:' + name) })
.catch(() => ElMessage.error('导出失败'))
}
+// 出库单详情 + 打印(收口借料知情权:库房租户实物凭证须可见借料来源)
+const detailRow = ref(null)
+const detailVisible = ref(false)
+function openDetail(row) { detailRow.value = row; detailVisible.value = true }
+function doPrint() { window.print() }
+
onMounted(loadRecords)
@@ -175,6 +188,12 @@ onMounted(loadRecords)
{{ row.targetStation || '-' }}
+
+
+ {{ borrowText(row) }}
+ —
+
+
{{ row.boxNo || '-' }}
@@ -185,6 +204,11 @@ onMounted(loadRecords)
{{ fmtTime(row.createdAt) }}
+
+
+ 详情
+
+
+
+
+
+
出库单 · {{ detailRow.outboundNo }}
+
+ {{ detailRow.outboundNo }}
+ {{ typeLabel(detailRow.outboundType) }}
+ {{ categoryLabel(detailRow.outboundCategory) }}
+ {{ detailRow.materialCode }}
+ {{ detailRow.quantity }}
+ {{ detailRow.targetStation || '-' }}
+ {{ detailRow.targetDock || '-' }}
+ {{ detailRow.boxNo || '-' }}
+ {{ detailRow.snCodes || '-' }}
+ {{ detailRow.operator }}
+ {{ fmtTime(detailRow.createdAt) }}
+ {{ detailRow.remark || '-' }}
+
+ {{ borrowText(detailRow) }}
+ —(本工位自取,无借料)
+
+
+
+
+ 关闭
+ 打印
+
+
+
+
diff --git a/bj_power_wms/frontend/src/layouts/MainLayout.vue b/bj_power_wms/frontend/src/layouts/MainLayout.vue
index c926cf3..dcdb01d 100644
--- a/bj_power_wms/frontend/src/layouts/MainLayout.vue
+++ b/bj_power_wms/frontend/src/layouts/MainLayout.vue
@@ -82,7 +82,7 @@ let alertInited = false
async function pollAlerts() {
try {
- const data = await request.get('/api/alerts', { params: { status: 'unread', pageSize: 1 } })
+ const data = await request.get('/alerts', { params: { status: 'unread', pageSize: 1 } })
const n = (data && data.unreadCount) || 0
// 首轮仅初始化角标;之后未读数增加时弹提示,避免反复骚扰
if (alertInited && n > unreadAlerts.value) {
@@ -142,6 +142,7 @@ const menuGroups = [
{ path: '/attachment', title: '附件中心', icon: Folder, code: 'attachment:view' },
{ path: '/data-archive', title: '数据归档', icon: Tools, code: 'backup:manage' },
{ path: '/alert-center', title: '预警中心', icon: Bell },
+ { path: '/alert-rule', title: '预警规则', icon: Bell },
{ path: '/settings', title: '基础设置', icon: Setting, code: 'sys.settings:view' }
]
}
diff --git a/bj_power_wms/frontend/src/pages/AlertCenter.vue b/bj_power_wms/frontend/src/pages/AlertCenter.vue
index ed79401..bfb22be 100644
--- a/bj_power_wms/frontend/src/pages/AlertCenter.vue
+++ b/bj_power_wms/frontend/src/pages/AlertCenter.vue
@@ -64,33 +64,7 @@
-
-
- 预警规则配置
-
-
-
-
-
-
-
-
-
-
-
- {{ thresholdUnit(row.code) }}
-
-
-
-
-
-
-
-
-
- 说明:阈值仅对「来料检超期未检」(超期小时) 与「库龄超档」(超期天) 生效;其余规则阈值不参与判定。
-
-
+
@@ -104,7 +78,8 @@ const ruleMeta = {
inspection_overdue: '来料检超期未检',
backup_overdue: '备份超期',
sync_failed: '物料同步失败',
- inventory_age: '库龄超档'
+ inventory_age: '库龄超档',
+ negative_stock: '库存负数异常'
}
const levelMeta = { info: '信息', warning: '警告', error: '严重' }
function levelTag(l) {
@@ -112,11 +87,6 @@ function levelTag(l) {
if (l === 'warning') return 'warning'
return 'info'
}
-function thresholdUnit(code) {
- if (code === 'inspection_overdue') return '小时'
- if (code === 'inventory_age') return '天'
- return '(未使用)'
-}
const list = ref([])
const total = ref(0)
@@ -127,9 +97,6 @@ const pageSize = ref(20)
const filters = reactive({ status: '', ruleCode: '' })
-const rules = ref([])
-const rulesLoading = ref(false)
-
function fmtTime(t) {
if (!t) return '-'
const d = new Date(t * 1000)
@@ -147,7 +114,7 @@ async function load() {
status: filters.status || undefined,
ruleCode: filters.ruleCode || undefined
}
- const data = await request.get('/api/alerts', { params })
+ const data = await request.get('/alerts', { params })
list.value = (data && data.list) || []
total.value = (data && data.total) || 0
} catch (e) {
@@ -180,7 +147,7 @@ async function resolve(row) {
}
row._resolving = true
try {
- await request.post(`/api/alerts/${row.id}/read`)
+ await request.post(`/alerts/${row.id}/read`)
ElMessage.success('已标记已读')
load()
} catch (e) {
@@ -199,7 +166,7 @@ async function readAll() {
}
readAllLoading.value = true
try {
- await request.post('/api/alerts/read-all')
+ await request.post('/alerts/read-all')
ElMessage.success('已全部标记为已读')
load()
} catch (e) {
@@ -209,38 +176,8 @@ async function readAll() {
}
}
-async function loadRules() {
- rulesLoading.value = true
- try {
- const data = await request.get('/api/alert-rules')
- rules.value = (data || []).map((r) => ({ ...r, enabled: !!r.enabled }))
- } catch (e) {
- ElMessage.error(e?.message || '加载规则失败')
- } finally {
- rulesLoading.value = false
- }
-}
-let saveTimer = null
-function saveRule(row) {
- clearTimeout(saveTimer)
- saveTimer = setTimeout(async () => {
- try {
- await request.post('/api/alert-rules/update', {
- code: row.code,
- enabled: row.enabled,
- threshold: row.threshold,
- remark: row.remark
- })
- ElMessage.success('规则已保存')
- } catch (e) {
- ElMessage.error(e?.message || '保存失败')
- }
- }, 300)
-}
-
onMounted(() => {
load()
- loadRules()
})
diff --git a/bj_power_wms/frontend/src/pages/AlertRule.vue b/bj_power_wms/frontend/src/pages/AlertRule.vue
new file mode 100644
index 0000000..dffb030
--- /dev/null
+++ b/bj_power_wms/frontend/src/pages/AlertRule.vue
@@ -0,0 +1,97 @@
+
+
+
+
+
diff --git a/bj_power_wms/frontend/src/pages/BaseData.vue b/bj_power_wms/frontend/src/pages/BaseData.vue
index 7fb51ee..67e1870 100644
--- a/bj_power_wms/frontend/src/pages/BaseData.vue
+++ b/bj_power_wms/frontend/src/pages/BaseData.vue
@@ -792,7 +792,12 @@ async function onMaterialFile(e) {