From 756d9789004d6476523e0d81c87597ea88612b05 Mon Sep 17 00:00:00 2001 From: SunYF <123@hard_man.com> Date: Tue, 6 Oct 2026 19:36:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E5=B7=A5=E4=BD=8D?= =?UTF-8?q?=E7=BB=88=E7=AB=AF=E6=BB=91=E5=8A=A8=E7=BB=AD=E7=AD=BE=E6=9C=BA?= =?UTF-8?q?=E5=88=B6=EF=BC=8C=E5=BC=BA=E5=8C=96=E5=AE=89=E5=85=A8=E4=B8=8E?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E8=BF=BD=E6=BA=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增滑动续签功能:人工触屏触发本地心跳 + 30秒节流刷新JWT,避免作业中令牌过期 - 拆分质量检验权限:过程检/完工检使用不同权限码,细化权限粒度 - 新增操作人用户ID字段:报工、拧紧记录落库时携带可信用户ID,解决身份追溯问题 - 移除编译期默认密钥,启动期校验所有必要密钥非空,防止密钥泄露风险 - 修复WMS附件越权遍历问题:使用UUID文件名替代顺序ID访问附件 - 实现登录态过期数据隔离:仅返回当前操作人的待同步数据,避免身份混淆 --- bj_power_mes/common/token/token.go | 3 +- bj_power_mes/ent/migrate/schema.go | 6 +- bj_power_mes/ent/mutation.go | 178 ++++++++- bj_power_mes/ent/runtime.go | 22 +- bj_power_mes/ent/torquerecord.go | 13 +- bj_power_mes/ent/torquerecord/torquerecord.go | 10 + bj_power_mes/ent/torquerecord/where.go | 45 +++ bj_power_mes/ent/torquerecord_create.go | 25 ++ bj_power_mes/ent/torquerecord_update.go | 54 +++ bj_power_mes/ent/workpieceprocess.go | 13 +- bj_power_mes/ent/workpieceprocess/where.go | 45 +++ .../ent/workpieceprocess/workpieceprocess.go | 10 + bj_power_mes/ent/workpieceprocess_create.go | 25 ++ bj_power_mes/ent/workpieceprocess_update.go | 54 +++ bj_power_mes/frontend/src/pages/Inspect.vue | 2 +- .../frontend/src/pages/QualityInspection.vue | 2 +- bj_power_mes/internal/config/config.go | 12 +- bj_power_mes/internal/db/db.go | 14 + bj_power_mes/internal/handler/inspection.go | 31 +- bj_power_mes/internal/handler/line.go | 10 +- bj_power_mes/internal/handler/perm.go | 4 +- .../internal/handler/production/bind.go | 6 +- .../internal/handler/production/material.go | 2 +- .../handler/production/plc_torque_scan.go | 2 +- .../internal/handler/production/production.go | 126 ++++++- .../production/security_verify_test.go | 157 ++++++++ .../handler/production/station_state.go | 3 +- bj_power_mes/internal/handler/routes.go | 3 +- .../internal/handler/routes_production.go | 42 ++- bj_power_mes/internal/handler/station.go | 40 +- bj_power_mes/internal/handler/station_ops.go | 11 +- bj_power_mes/internal/logic/auth.go | 25 ++ bj_power_mes/internal/logic/inspection.go | 4 +- bj_power_mes/internal/logic/material.go | 59 ++- bj_power_mes/internal/logic/seed.go | 50 ++- bj_power_mes/internal/logic/sign.go | 15 + bj_power_mes/internal/logic/torque.go | 7 +- bj_power_mes/internal/logic/workpiece.go | 5 +- bj_power_mes/internal/svc/service_context.go | 26 ++ bj_power_mes/internal/wmsclient/client.go | 26 +- bj_power_mes/public/index.html | 2 +- bj_power_mes/schema/torque_record.go | 3 + bj_power_mes/schema/workpiece_process.go | 3 + bj_power_wms/internal/config/config.go | 12 +- bj_power_wms/internal/handler/attachment.go | 44 +-- .../internal/handler/finished_inbound.go | 48 ++- bj_power_wms/internal/handler/inbound.go | 5 + bj_power_wms/internal/handler/outbound.go | 58 ++- bj_power_wms/internal/handler/return_order.go | 3 +- bj_power_wms/internal/svc/service_context.go | 26 ++ .../frontend/src/api/index.js | 6 + bj_power_workstation/frontend/src/main.js | 9 + .../frontend/src/store/station.js | 22 +- .../frontend/src/views/Login.vue | 16 +- .../frontend/src/views/Main.vue | 17 +- .../internal/config/config.go | 11 + bj_power_workstation/internal/handler/auth.go | 89 ++++- .../internal/handler/report.go | 35 +- .../internal/handler/routes.go | 4 + bj_power_workstation/internal/handler/sync.go | 19 +- .../internal/handler/tightening.go | 15 +- .../internal/handler/workpiece.go | 22 +- bj_power_workstation/internal/mes/client.go | 59 ++- bj_power_workstation/internal/store/store.go | 350 +++++++++++++++++- .../internal/store/store_migrate_test.go | 73 ++++ .../internal/syncer/identity_boundary_test.go | 264 +++++++++++++ .../internal/syncer/syncer.go | 112 +++++- .../internal/syncer/syncer_verify_test.go | 83 +++++ bj_power_workstation/main.go | 27 ++ bj_power_workstation/web/static/index.html | 2 +- 临时.md | 347 ----------------- 71 files changed, 2417 insertions(+), 556 deletions(-) create mode 100644 bj_power_mes/internal/handler/production/security_verify_test.go create mode 100644 bj_power_workstation/internal/store/store_migrate_test.go create mode 100644 bj_power_workstation/internal/syncer/identity_boundary_test.go create mode 100644 bj_power_workstation/internal/syncer/syncer_verify_test.go delete mode 100644 临时.md diff --git a/bj_power_mes/common/token/token.go b/bj_power_mes/common/token/token.go index 9ec770f..60593ee 100644 --- a/bj_power_mes/common/token/token.go +++ b/bj_power_mes/common/token/token.go @@ -44,4 +44,5 @@ func Parse(secret, tokenStr string) (*Claims, error) { return claims, nil } return nil, errors.New("invalid token") -} \ No newline at end of file +} + diff --git a/bj_power_mes/ent/migrate/schema.go b/bj_power_mes/ent/migrate/schema.go index 5dc477a..f528bad 100644 --- a/bj_power_mes/ent/migrate/schema.go +++ b/bj_power_mes/ent/migrate/schema.go @@ -863,6 +863,7 @@ var ( {Name: "angle", Type: field.TypeFloat64, Default: 0}, {Name: "result", Type: field.TypeString, Size: 10, Default: "OK"}, {Name: "operator", Type: field.TypeString, Size: 64, Default: ""}, + {Name: "operator_id", Type: field.TypeInt, Default: 0}, {Name: "station_no", Type: field.TypeString, Size: 32, Default: ""}, {Name: "time", Type: field.TypeTime}, {Name: "created_at", Type: field.TypeTime}, @@ -886,12 +887,12 @@ var ( { Name: "torquerecord_created_at", Unique: false, - Columns: []*schema.Column{TorqueRecordColumns[11]}, + Columns: []*schema.Column{TorqueRecordColumns[12]}, }, { Name: "torquerecord_time", Unique: false, - Columns: []*schema.Column{TorqueRecordColumns[10]}, + Columns: []*schema.Column{TorqueRecordColumns[11]}, }, }, } @@ -1101,6 +1102,7 @@ var ( {Name: "process_name", Type: field.TypeString, Size: 64, Default: ""}, {Name: "status", Type: field.TypeString, Size: 20, Default: "DONE"}, {Name: "operator", Type: field.TypeString, Size: 64, Default: ""}, + {Name: "operator_id", Type: field.TypeInt, Default: 0}, {Name: "result", Type: field.TypeString, Size: 10, Default: "OK"}, {Name: "started_at", Type: field.TypeTime, Nullable: true}, {Name: "ended_at", Type: field.TypeTime, Nullable: true}, diff --git a/bj_power_mes/ent/mutation.go b/bj_power_mes/ent/mutation.go index ce80d79..be239e5 100644 --- a/bj_power_mes/ent/mutation.go +++ b/bj_power_mes/ent/mutation.go @@ -24418,6 +24418,8 @@ type TorqueRecordMutation struct { addangle *float64 result *string operator *string + operatorId *int + addoperatorId *int stationNo *string time *time.Time createdAt *time.Time @@ -24879,6 +24881,62 @@ func (m *TorqueRecordMutation) ResetOperator() { m.operator = nil } +// SetOperatorId sets the "operatorId" field. +func (m *TorqueRecordMutation) SetOperatorId(i int) { + m.operatorId = &i + m.addoperatorId = nil +} + +// OperatorId returns the value of the "operatorId" field in the mutation. +func (m *TorqueRecordMutation) OperatorId() (r int, exists bool) { + v := m.operatorId + if v == nil { + return + } + return *v, true +} + +// OldOperatorId returns the old "operatorId" field's value of the TorqueRecord entity. +// If the TorqueRecord 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 *TorqueRecordMutation) OldOperatorId(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperatorId is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperatorId requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperatorId: %w", err) + } + return oldValue.OperatorId, nil +} + +// AddOperatorId adds i to the "operatorId" field. +func (m *TorqueRecordMutation) AddOperatorId(i int) { + if m.addoperatorId != nil { + *m.addoperatorId += i + } else { + m.addoperatorId = &i + } +} + +// AddedOperatorId returns the value that was added to the "operatorId" field in this mutation. +func (m *TorqueRecordMutation) AddedOperatorId() (r int, exists bool) { + v := m.addoperatorId + if v == nil { + return + } + return *v, true +} + +// ResetOperatorId resets all changes to the "operatorId" field. +func (m *TorqueRecordMutation) ResetOperatorId() { + m.operatorId = nil + m.addoperatorId = nil +} + // SetStationNo sets the "stationNo" field. func (m *TorqueRecordMutation) SetStationNo(s string) { m.stationNo = &s @@ -25021,7 +25079,7 @@ func (m *TorqueRecordMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *TorqueRecordMutation) Fields() []string { - fields := make([]string, 0, 11) + fields := make([]string, 0, 12) if m.workOrderNo != nil { fields = append(fields, torquerecord.FieldWorkOrderNo) } @@ -25046,6 +25104,9 @@ func (m *TorqueRecordMutation) Fields() []string { if m.operator != nil { fields = append(fields, torquerecord.FieldOperator) } + if m.operatorId != nil { + fields = append(fields, torquerecord.FieldOperatorId) + } if m.stationNo != nil { fields = append(fields, torquerecord.FieldStationNo) } @@ -25079,6 +25140,8 @@ func (m *TorqueRecordMutation) Field(name string) (ent.Value, bool) { return m.Result() case torquerecord.FieldOperator: return m.Operator() + case torquerecord.FieldOperatorId: + return m.OperatorId() case torquerecord.FieldStationNo: return m.StationNo() case torquerecord.FieldTime: @@ -25110,6 +25173,8 @@ func (m *TorqueRecordMutation) OldField(ctx context.Context, name string) (ent.V return m.OldResult(ctx) case torquerecord.FieldOperator: return m.OldOperator(ctx) + case torquerecord.FieldOperatorId: + return m.OldOperatorId(ctx) case torquerecord.FieldStationNo: return m.OldStationNo(ctx) case torquerecord.FieldTime: @@ -25181,6 +25246,13 @@ func (m *TorqueRecordMutation) SetField(name string, value ent.Value) error { } m.SetOperator(v) return nil + case torquerecord.FieldOperatorId: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperatorId(v) + return nil case torquerecord.FieldStationNo: v, ok := value.(string) if !ok { @@ -25219,6 +25291,9 @@ func (m *TorqueRecordMutation) AddedFields() []string { if m.addangle != nil { fields = append(fields, torquerecord.FieldAngle) } + if m.addoperatorId != nil { + fields = append(fields, torquerecord.FieldOperatorId) + } return fields } @@ -25233,6 +25308,8 @@ func (m *TorqueRecordMutation) AddedField(name string) (ent.Value, bool) { return m.AddedTorque() case torquerecord.FieldAngle: return m.AddedAngle() + case torquerecord.FieldOperatorId: + return m.AddedOperatorId() } return nil, false } @@ -25263,6 +25340,13 @@ func (m *TorqueRecordMutation) AddField(name string, value ent.Value) error { } m.AddAngle(v) return nil + case torquerecord.FieldOperatorId: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOperatorId(v) + return nil } return fmt.Errorf("unknown TorqueRecord numeric field %s", name) } @@ -25314,6 +25398,9 @@ func (m *TorqueRecordMutation) ResetField(name string) error { case torquerecord.FieldOperator: m.ResetOperator() return nil + case torquerecord.FieldOperatorId: + m.ResetOperatorId() + return nil case torquerecord.FieldStationNo: m.ResetStationNo() return nil @@ -30548,6 +30635,8 @@ type WorkpieceProcessMutation struct { processName *string status *string operator *string + operatorId *int + addoperatorId *int result *string startedAt *time.Time endedAt *time.Time @@ -30937,6 +31026,62 @@ func (m *WorkpieceProcessMutation) ResetOperator() { m.operator = nil } +// SetOperatorId sets the "operatorId" field. +func (m *WorkpieceProcessMutation) SetOperatorId(i int) { + m.operatorId = &i + m.addoperatorId = nil +} + +// OperatorId returns the value of the "operatorId" field in the mutation. +func (m *WorkpieceProcessMutation) OperatorId() (r int, exists bool) { + v := m.operatorId + if v == nil { + return + } + return *v, true +} + +// OldOperatorId returns the old "operatorId" field's value of the WorkpieceProcess entity. +// If the WorkpieceProcess 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 *WorkpieceProcessMutation) OldOperatorId(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperatorId is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperatorId requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperatorId: %w", err) + } + return oldValue.OperatorId, nil +} + +// AddOperatorId adds i to the "operatorId" field. +func (m *WorkpieceProcessMutation) AddOperatorId(i int) { + if m.addoperatorId != nil { + *m.addoperatorId += i + } else { + m.addoperatorId = &i + } +} + +// AddedOperatorId returns the value that was added to the "operatorId" field in this mutation. +func (m *WorkpieceProcessMutation) AddedOperatorId() (r int, exists bool) { + v := m.addoperatorId + if v == nil { + return + } + return *v, true +} + +// ResetOperatorId resets all changes to the "operatorId" field. +func (m *WorkpieceProcessMutation) ResetOperatorId() { + m.operatorId = nil + m.addoperatorId = nil +} + // SetResult sets the "result" field. func (m *WorkpieceProcessMutation) SetResult(s string) { m.result = &s @@ -31233,7 +31378,7 @@ func (m *WorkpieceProcessMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *WorkpieceProcessMutation) Fields() []string { - fields := make([]string, 0, 13) + fields := make([]string, 0, 14) if m.sn != nil { fields = append(fields, workpieceprocess.FieldSn) } @@ -31255,6 +31400,9 @@ func (m *WorkpieceProcessMutation) Fields() []string { if m.operator != nil { fields = append(fields, workpieceprocess.FieldOperator) } + if m.operatorId != nil { + fields = append(fields, workpieceprocess.FieldOperatorId) + } if m.result != nil { fields = append(fields, workpieceprocess.FieldResult) } @@ -31295,6 +31443,8 @@ func (m *WorkpieceProcessMutation) Field(name string) (ent.Value, bool) { return m.Status() case workpieceprocess.FieldOperator: return m.Operator() + case workpieceprocess.FieldOperatorId: + return m.OperatorId() case workpieceprocess.FieldResult: return m.Result() case workpieceprocess.FieldStartedAt: @@ -31330,6 +31480,8 @@ func (m *WorkpieceProcessMutation) OldField(ctx context.Context, name string) (e return m.OldStatus(ctx) case workpieceprocess.FieldOperator: return m.OldOperator(ctx) + case workpieceprocess.FieldOperatorId: + return m.OldOperatorId(ctx) case workpieceprocess.FieldResult: return m.OldResult(ctx) case workpieceprocess.FieldStartedAt: @@ -31400,6 +31552,13 @@ func (m *WorkpieceProcessMutation) SetField(name string, value ent.Value) error } m.SetOperator(v) return nil + case workpieceprocess.FieldOperatorId: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperatorId(v) + return nil case workpieceprocess.FieldResult: v, ok := value.(string) if !ok { @@ -31453,6 +31612,9 @@ func (m *WorkpieceProcessMutation) AddedFields() []string { if m.addflowId != nil { fields = append(fields, workpieceprocess.FieldFlowId) } + if m.addoperatorId != nil { + fields = append(fields, workpieceprocess.FieldOperatorId) + } if m.adddurationSec != nil { fields = append(fields, workpieceprocess.FieldDurationSec) } @@ -31466,6 +31628,8 @@ func (m *WorkpieceProcessMutation) AddedField(name string) (ent.Value, bool) { switch name { case workpieceprocess.FieldFlowId: return m.AddedFlowId() + case workpieceprocess.FieldOperatorId: + return m.AddedOperatorId() case workpieceprocess.FieldDurationSec: return m.AddedDurationSec() } @@ -31484,6 +31648,13 @@ func (m *WorkpieceProcessMutation) AddField(name string, value ent.Value) error } m.AddFlowId(v) return nil + case workpieceprocess.FieldOperatorId: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddOperatorId(v) + return nil case workpieceprocess.FieldDurationSec: v, ok := value.(int) if !ok { @@ -31554,6 +31725,9 @@ func (m *WorkpieceProcessMutation) ResetField(name string) error { case workpieceprocess.FieldOperator: m.ResetOperator() return nil + case workpieceprocess.FieldOperatorId: + m.ResetOperatorId() + return nil case workpieceprocess.FieldResult: m.ResetResult() return nil diff --git a/bj_power_mes/ent/runtime.go b/bj_power_mes/ent/runtime.go index 4a51be4..024c142 100644 --- a/bj_power_mes/ent/runtime.go +++ b/bj_power_mes/ent/runtime.go @@ -1475,18 +1475,22 @@ func init() { torquerecord.DefaultOperator = torquerecordDescOperator.Default.(string) // torquerecord.OperatorValidator is a validator for the "operator" field. It is called by the builders before save. torquerecord.OperatorValidator = torquerecordDescOperator.Validators[0].(func(string) error) + // torquerecordDescOperatorId is the schema descriptor for operatorId field. + torquerecordDescOperatorId := torquerecordFields[9].Descriptor() + // torquerecord.DefaultOperatorId holds the default value on creation for the operatorId field. + torquerecord.DefaultOperatorId = torquerecordDescOperatorId.Default.(int) // torquerecordDescStationNo is the schema descriptor for stationNo field. - torquerecordDescStationNo := torquerecordFields[9].Descriptor() + torquerecordDescStationNo := torquerecordFields[10].Descriptor() // torquerecord.DefaultStationNo holds the default value on creation for the stationNo field. torquerecord.DefaultStationNo = torquerecordDescStationNo.Default.(string) // torquerecord.StationNoValidator is a validator for the "stationNo" field. It is called by the builders before save. torquerecord.StationNoValidator = torquerecordDescStationNo.Validators[0].(func(string) error) // torquerecordDescTime is the schema descriptor for time field. - torquerecordDescTime := torquerecordFields[10].Descriptor() + torquerecordDescTime := torquerecordFields[11].Descriptor() // torquerecord.DefaultTime holds the default value on creation for the time field. torquerecord.DefaultTime = torquerecordDescTime.Default.(func() time.Time) // torquerecordDescCreatedAt is the schema descriptor for createdAt field. - torquerecordDescCreatedAt := torquerecordFields[11].Descriptor() + torquerecordDescCreatedAt := torquerecordFields[12].Descriptor() // torquerecord.DefaultCreatedAt holds the default value on creation for the createdAt field. torquerecord.DefaultCreatedAt = torquerecordDescCreatedAt.Default.(func() time.Time) // torquerecordDescID is the schema descriptor for id field. @@ -1763,24 +1767,28 @@ func init() { workpieceprocess.DefaultOperator = workpieceprocessDescOperator.Default.(string) // workpieceprocess.OperatorValidator is a validator for the "operator" field. It is called by the builders before save. workpieceprocess.OperatorValidator = workpieceprocessDescOperator.Validators[0].(func(string) error) + // workpieceprocessDescOperatorId is the schema descriptor for operatorId field. + workpieceprocessDescOperatorId := workpieceprocessFields[8].Descriptor() + // workpieceprocess.DefaultOperatorId holds the default value on creation for the operatorId field. + workpieceprocess.DefaultOperatorId = workpieceprocessDescOperatorId.Default.(int) // workpieceprocessDescResult is the schema descriptor for result field. - workpieceprocessDescResult := workpieceprocessFields[8].Descriptor() + workpieceprocessDescResult := workpieceprocessFields[9].Descriptor() // workpieceprocess.DefaultResult holds the default value on creation for the result field. workpieceprocess.DefaultResult = workpieceprocessDescResult.Default.(string) // workpieceprocess.ResultValidator is a validator for the "result" field. It is called by the builders before save. workpieceprocess.ResultValidator = workpieceprocessDescResult.Validators[0].(func(string) error) // workpieceprocessDescDurationSec is the schema descriptor for durationSec field. - workpieceprocessDescDurationSec := workpieceprocessFields[11].Descriptor() + workpieceprocessDescDurationSec := workpieceprocessFields[12].Descriptor() // workpieceprocess.DefaultDurationSec holds the default value on creation for the durationSec field. workpieceprocess.DefaultDurationSec = workpieceprocessDescDurationSec.Default.(int) // workpieceprocessDescRemark is the schema descriptor for remark field. - workpieceprocessDescRemark := workpieceprocessFields[12].Descriptor() + workpieceprocessDescRemark := workpieceprocessFields[13].Descriptor() // workpieceprocess.DefaultRemark holds the default value on creation for the remark field. workpieceprocess.DefaultRemark = workpieceprocessDescRemark.Default.(string) // workpieceprocess.RemarkValidator is a validator for the "remark" field. It is called by the builders before save. workpieceprocess.RemarkValidator = workpieceprocessDescRemark.Validators[0].(func(string) error) // workpieceprocessDescCreatedAt is the schema descriptor for createdAt field. - workpieceprocessDescCreatedAt := workpieceprocessFields[13].Descriptor() + workpieceprocessDescCreatedAt := workpieceprocessFields[14].Descriptor() // workpieceprocess.DefaultCreatedAt holds the default value on creation for the createdAt field. workpieceprocess.DefaultCreatedAt = workpieceprocessDescCreatedAt.Default.(func() time.Time) // workpieceprocessDescID is the schema descriptor for id field. diff --git a/bj_power_mes/ent/torquerecord.go b/bj_power_mes/ent/torquerecord.go index 3b08cd1..3032de7 100644 --- a/bj_power_mes/ent/torquerecord.go +++ b/bj_power_mes/ent/torquerecord.go @@ -33,6 +33,8 @@ type TorqueRecord struct { Result string `json:"result,omitempty"` // 操作人 Operator string `json:"operator,omitempty"` + // 操作人用户ID(0=未采集:虚拟工位/PLC路径或历史数据) + OperatorId int `json:"operatorId,omitempty"` // 工位 StationNo string `json:"stationNo,omitempty"` // 采集时间 @@ -49,7 +51,7 @@ func (*TorqueRecord) scanValues(columns []string) ([]any, error) { switch columns[i] { case torquerecord.FieldStrain, torquerecord.FieldTorque, torquerecord.FieldAngle: values[i] = new(sql.NullFloat64) - case torquerecord.FieldID: + case torquerecord.FieldID, torquerecord.FieldOperatorId: values[i] = new(sql.NullInt64) case torquerecord.FieldWorkOrderNo, torquerecord.FieldSn, torquerecord.FieldScrewNo, torquerecord.FieldResult, torquerecord.FieldOperator, torquerecord.FieldStationNo: values[i] = new(sql.NullString) @@ -124,6 +126,12 @@ func (_m *TorqueRecord) assignValues(columns []string, values []any) error { } else if value.Valid { _m.Operator = value.String } + case torquerecord.FieldOperatorId: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field operatorId", values[i]) + } else if value.Valid { + _m.OperatorId = int(value.Int64) + } case torquerecord.FieldStationNo: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field stationNo", values[i]) @@ -202,6 +210,9 @@ func (_m *TorqueRecord) String() string { builder.WriteString("operator=") builder.WriteString(_m.Operator) builder.WriteString(", ") + builder.WriteString("operatorId=") + builder.WriteString(fmt.Sprintf("%v", _m.OperatorId)) + builder.WriteString(", ") builder.WriteString("stationNo=") builder.WriteString(_m.StationNo) builder.WriteString(", ") diff --git a/bj_power_mes/ent/torquerecord/torquerecord.go b/bj_power_mes/ent/torquerecord/torquerecord.go index efe959b..7770bc6 100644 --- a/bj_power_mes/ent/torquerecord/torquerecord.go +++ b/bj_power_mes/ent/torquerecord/torquerecord.go @@ -29,6 +29,8 @@ const ( FieldResult = "result" // FieldOperator holds the string denoting the operator field in the database. FieldOperator = "operator" + // FieldOperatorId holds the string denoting the operatorid field in the database. + FieldOperatorId = "operator_id" // FieldStationNo holds the string denoting the stationno field in the database. FieldStationNo = "station_no" // FieldTime holds the string denoting the time field in the database. @@ -50,6 +52,7 @@ var Columns = []string{ FieldAngle, FieldResult, FieldOperator, + FieldOperatorId, FieldStationNo, FieldTime, FieldCreatedAt, @@ -90,6 +93,8 @@ var ( DefaultOperator string // OperatorValidator is a validator for the "operator" field. It is called by the builders before save. OperatorValidator func(string) error + // DefaultOperatorId holds the default value on creation for the "operatorId" field. + DefaultOperatorId int // DefaultStationNo holds the default value on creation for the "stationNo" field. DefaultStationNo string // StationNoValidator is a validator for the "stationNo" field. It is called by the builders before save. @@ -150,6 +155,11 @@ func ByOperator(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldOperator, opts...).ToFunc() } +// ByOperatorId orders the results by the operatorId field. +func ByOperatorId(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperatorId, opts...).ToFunc() +} + // ByStationNo orders the results by the stationNo field. func ByStationNo(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldStationNo, opts...).ToFunc() diff --git a/bj_power_mes/ent/torquerecord/where.go b/bj_power_mes/ent/torquerecord/where.go index 67d81d2..a7d5a8a 100644 --- a/bj_power_mes/ent/torquerecord/where.go +++ b/bj_power_mes/ent/torquerecord/where.go @@ -94,6 +94,11 @@ func Operator(v string) predicate.TorqueRecord { return predicate.TorqueRecord(sql.FieldEQ(FieldOperator, v)) } +// OperatorId applies equality check predicate on the "operatorId" field. It's identical to OperatorIdEQ. +func OperatorId(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldEQ(FieldOperatorId, v)) +} + // StationNo applies equality check predicate on the "stationNo" field. It's identical to StationNoEQ. func StationNo(v string) predicate.TorqueRecord { return predicate.TorqueRecord(sql.FieldEQ(FieldStationNo, v)) @@ -554,6 +559,46 @@ func OperatorContainsFold(v string) predicate.TorqueRecord { return predicate.TorqueRecord(sql.FieldContainsFold(FieldOperator, v)) } +// OperatorIdEQ applies the EQ predicate on the "operatorId" field. +func OperatorIdEQ(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldEQ(FieldOperatorId, v)) +} + +// OperatorIdNEQ applies the NEQ predicate on the "operatorId" field. +func OperatorIdNEQ(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldNEQ(FieldOperatorId, v)) +} + +// OperatorIdIn applies the In predicate on the "operatorId" field. +func OperatorIdIn(vs ...int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldIn(FieldOperatorId, vs...)) +} + +// OperatorIdNotIn applies the NotIn predicate on the "operatorId" field. +func OperatorIdNotIn(vs ...int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldNotIn(FieldOperatorId, vs...)) +} + +// OperatorIdGT applies the GT predicate on the "operatorId" field. +func OperatorIdGT(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldGT(FieldOperatorId, v)) +} + +// OperatorIdGTE applies the GTE predicate on the "operatorId" field. +func OperatorIdGTE(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldGTE(FieldOperatorId, v)) +} + +// OperatorIdLT applies the LT predicate on the "operatorId" field. +func OperatorIdLT(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldLT(FieldOperatorId, v)) +} + +// OperatorIdLTE applies the LTE predicate on the "operatorId" field. +func OperatorIdLTE(v int) predicate.TorqueRecord { + return predicate.TorqueRecord(sql.FieldLTE(FieldOperatorId, v)) +} + // StationNoEQ applies the EQ predicate on the "stationNo" field. func StationNoEQ(v string) predicate.TorqueRecord { return predicate.TorqueRecord(sql.FieldEQ(FieldStationNo, v)) diff --git a/bj_power_mes/ent/torquerecord_create.go b/bj_power_mes/ent/torquerecord_create.go index 76c278d..4021fc1 100644 --- a/bj_power_mes/ent/torquerecord_create.go +++ b/bj_power_mes/ent/torquerecord_create.go @@ -124,6 +124,20 @@ func (_c *TorqueRecordCreate) SetNillableOperator(v *string) *TorqueRecordCreate return _c } +// SetOperatorId sets the "operatorId" field. +func (_c *TorqueRecordCreate) SetOperatorId(v int) *TorqueRecordCreate { + _c.mutation.SetOperatorId(v) + return _c +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_c *TorqueRecordCreate) SetNillableOperatorId(v *int) *TorqueRecordCreate { + if v != nil { + _c.SetOperatorId(*v) + } + return _c +} + // SetStationNo sets the "stationNo" field. func (_c *TorqueRecordCreate) SetStationNo(v string) *TorqueRecordCreate { _c.mutation.SetStationNo(v) @@ -235,6 +249,10 @@ func (_c *TorqueRecordCreate) defaults() { v := torquerecord.DefaultOperator _c.mutation.SetOperator(v) } + if _, ok := _c.mutation.OperatorId(); !ok { + v := torquerecord.DefaultOperatorId + _c.mutation.SetOperatorId(v) + } if _, ok := _c.mutation.StationNo(); !ok { v := torquerecord.DefaultStationNo _c.mutation.SetStationNo(v) @@ -300,6 +318,9 @@ func (_c *TorqueRecordCreate) check() error { return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "TorqueRecord.operator": %w`, err)} } } + if _, ok := _c.mutation.OperatorId(); !ok { + return &ValidationError{Name: "operatorId", err: errors.New(`ent: missing required field "TorqueRecord.operatorId"`)} + } if _, ok := _c.mutation.StationNo(); !ok { return &ValidationError{Name: "stationNo", err: errors.New(`ent: missing required field "TorqueRecord.stationNo"`)} } @@ -383,6 +404,10 @@ func (_c *TorqueRecordCreate) createSpec() (*TorqueRecord, *sqlgraph.CreateSpec) _spec.SetField(torquerecord.FieldOperator, field.TypeString, value) _node.Operator = value } + if value, ok := _c.mutation.OperatorId(); ok { + _spec.SetField(torquerecord.FieldOperatorId, field.TypeInt, value) + _node.OperatorId = value + } if value, ok := _c.mutation.StationNo(); ok { _spec.SetField(torquerecord.FieldStationNo, field.TypeString, value) _node.StationNo = value diff --git a/bj_power_mes/ent/torquerecord_update.go b/bj_power_mes/ent/torquerecord_update.go index ac1eccb..deb9b7b 100644 --- a/bj_power_mes/ent/torquerecord_update.go +++ b/bj_power_mes/ent/torquerecord_update.go @@ -162,6 +162,27 @@ func (_u *TorqueRecordUpdate) SetNillableOperator(v *string) *TorqueRecordUpdate return _u } +// SetOperatorId sets the "operatorId" field. +func (_u *TorqueRecordUpdate) SetOperatorId(v int) *TorqueRecordUpdate { + _u.mutation.ResetOperatorId() + _u.mutation.SetOperatorId(v) + return _u +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_u *TorqueRecordUpdate) SetNillableOperatorId(v *int) *TorqueRecordUpdate { + if v != nil { + _u.SetOperatorId(*v) + } + return _u +} + +// AddOperatorId adds value to the "operatorId" field. +func (_u *TorqueRecordUpdate) AddOperatorId(v int) *TorqueRecordUpdate { + _u.mutation.AddOperatorId(v) + return _u +} + // SetStationNo sets the "stationNo" field. func (_u *TorqueRecordUpdate) SetStationNo(v string) *TorqueRecordUpdate { _u.mutation.SetStationNo(v) @@ -308,6 +329,12 @@ func (_u *TorqueRecordUpdate) sqlSave(ctx context.Context) (_node int, err error if value, ok := _u.mutation.Operator(); ok { _spec.SetField(torquerecord.FieldOperator, field.TypeString, value) } + if value, ok := _u.mutation.OperatorId(); ok { + _spec.SetField(torquerecord.FieldOperatorId, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOperatorId(); ok { + _spec.AddField(torquerecord.FieldOperatorId, field.TypeInt, value) + } if value, ok := _u.mutation.StationNo(); ok { _spec.SetField(torquerecord.FieldStationNo, field.TypeString, value) } @@ -469,6 +496,27 @@ func (_u *TorqueRecordUpdateOne) SetNillableOperator(v *string) *TorqueRecordUpd return _u } +// SetOperatorId sets the "operatorId" field. +func (_u *TorqueRecordUpdateOne) SetOperatorId(v int) *TorqueRecordUpdateOne { + _u.mutation.ResetOperatorId() + _u.mutation.SetOperatorId(v) + return _u +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_u *TorqueRecordUpdateOne) SetNillableOperatorId(v *int) *TorqueRecordUpdateOne { + if v != nil { + _u.SetOperatorId(*v) + } + return _u +} + +// AddOperatorId adds value to the "operatorId" field. +func (_u *TorqueRecordUpdateOne) AddOperatorId(v int) *TorqueRecordUpdateOne { + _u.mutation.AddOperatorId(v) + return _u +} + // SetStationNo sets the "stationNo" field. func (_u *TorqueRecordUpdateOne) SetStationNo(v string) *TorqueRecordUpdateOne { _u.mutation.SetStationNo(v) @@ -645,6 +693,12 @@ func (_u *TorqueRecordUpdateOne) sqlSave(ctx context.Context) (_node *TorqueReco if value, ok := _u.mutation.Operator(); ok { _spec.SetField(torquerecord.FieldOperator, field.TypeString, value) } + if value, ok := _u.mutation.OperatorId(); ok { + _spec.SetField(torquerecord.FieldOperatorId, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOperatorId(); ok { + _spec.AddField(torquerecord.FieldOperatorId, field.TypeInt, value) + } if value, ok := _u.mutation.StationNo(); ok { _spec.SetField(torquerecord.FieldStationNo, field.TypeString, value) } diff --git a/bj_power_mes/ent/workpieceprocess.go b/bj_power_mes/ent/workpieceprocess.go index 500ffc2..04cbcf3 100644 --- a/bj_power_mes/ent/workpieceprocess.go +++ b/bj_power_mes/ent/workpieceprocess.go @@ -31,6 +31,8 @@ type WorkpieceProcess struct { Status string `json:"status,omitempty"` // Operator holds the value of the "operator" field. Operator string `json:"operator,omitempty"` + // 操作人用户ID(0=未采集:虚拟工位/PLC路径或历史数据) + OperatorId int `json:"operatorId,omitempty"` // 总判定 OK/NG Result string `json:"result,omitempty"` // StartedAt holds the value of the "startedAt" field. @@ -51,7 +53,7 @@ func (*WorkpieceProcess) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { - case workpieceprocess.FieldID, workpieceprocess.FieldFlowId, workpieceprocess.FieldDurationSec: + case workpieceprocess.FieldID, workpieceprocess.FieldFlowId, workpieceprocess.FieldOperatorId, workpieceprocess.FieldDurationSec: values[i] = new(sql.NullInt64) case workpieceprocess.FieldSn, workpieceprocess.FieldStationNo, workpieceprocess.FieldOrderNo, workpieceprocess.FieldProcessName, workpieceprocess.FieldStatus, workpieceprocess.FieldOperator, workpieceprocess.FieldResult, workpieceprocess.FieldRemark: values[i] = new(sql.NullString) @@ -120,6 +122,12 @@ func (_m *WorkpieceProcess) assignValues(columns []string, values []any) error { } else if value.Valid { _m.Operator = value.String } + case workpieceprocess.FieldOperatorId: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field operatorId", values[i]) + } else if value.Valid { + _m.OperatorId = int(value.Int64) + } case workpieceprocess.FieldResult: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field result", values[i]) @@ -215,6 +223,9 @@ func (_m *WorkpieceProcess) String() string { builder.WriteString("operator=") builder.WriteString(_m.Operator) builder.WriteString(", ") + builder.WriteString("operatorId=") + builder.WriteString(fmt.Sprintf("%v", _m.OperatorId)) + builder.WriteString(", ") builder.WriteString("result=") builder.WriteString(_m.Result) builder.WriteString(", ") diff --git a/bj_power_mes/ent/workpieceprocess/where.go b/bj_power_mes/ent/workpieceprocess/where.go index dd1f8b5..e515c25 100644 --- a/bj_power_mes/ent/workpieceprocess/where.go +++ b/bj_power_mes/ent/workpieceprocess/where.go @@ -89,6 +89,11 @@ func Operator(v string) predicate.WorkpieceProcess { return predicate.WorkpieceProcess(sql.FieldEQ(FieldOperator, v)) } +// OperatorId applies equality check predicate on the "operatorId" field. It's identical to OperatorIdEQ. +func OperatorId(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldEQ(FieldOperatorId, v)) +} + // Result applies equality check predicate on the "result" field. It's identical to ResultEQ. func Result(v string) predicate.WorkpieceProcess { return predicate.WorkpieceProcess(sql.FieldEQ(FieldResult, v)) @@ -549,6 +554,46 @@ func OperatorContainsFold(v string) predicate.WorkpieceProcess { return predicate.WorkpieceProcess(sql.FieldContainsFold(FieldOperator, v)) } +// OperatorIdEQ applies the EQ predicate on the "operatorId" field. +func OperatorIdEQ(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldEQ(FieldOperatorId, v)) +} + +// OperatorIdNEQ applies the NEQ predicate on the "operatorId" field. +func OperatorIdNEQ(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldNEQ(FieldOperatorId, v)) +} + +// OperatorIdIn applies the In predicate on the "operatorId" field. +func OperatorIdIn(vs ...int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldIn(FieldOperatorId, vs...)) +} + +// OperatorIdNotIn applies the NotIn predicate on the "operatorId" field. +func OperatorIdNotIn(vs ...int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldNotIn(FieldOperatorId, vs...)) +} + +// OperatorIdGT applies the GT predicate on the "operatorId" field. +func OperatorIdGT(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldGT(FieldOperatorId, v)) +} + +// OperatorIdGTE applies the GTE predicate on the "operatorId" field. +func OperatorIdGTE(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldGTE(FieldOperatorId, v)) +} + +// OperatorIdLT applies the LT predicate on the "operatorId" field. +func OperatorIdLT(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldLT(FieldOperatorId, v)) +} + +// OperatorIdLTE applies the LTE predicate on the "operatorId" field. +func OperatorIdLTE(v int) predicate.WorkpieceProcess { + return predicate.WorkpieceProcess(sql.FieldLTE(FieldOperatorId, v)) +} + // ResultEQ applies the EQ predicate on the "result" field. func ResultEQ(v string) predicate.WorkpieceProcess { return predicate.WorkpieceProcess(sql.FieldEQ(FieldResult, v)) diff --git a/bj_power_mes/ent/workpieceprocess/workpieceprocess.go b/bj_power_mes/ent/workpieceprocess/workpieceprocess.go index 52e3806..761e6c9 100644 --- a/bj_power_mes/ent/workpieceprocess/workpieceprocess.go +++ b/bj_power_mes/ent/workpieceprocess/workpieceprocess.go @@ -27,6 +27,8 @@ const ( FieldStatus = "status" // FieldOperator holds the string denoting the operator field in the database. FieldOperator = "operator" + // FieldOperatorId holds the string denoting the operatorid field in the database. + FieldOperatorId = "operator_id" // FieldResult holds the string denoting the result field in the database. FieldResult = "result" // FieldStartedAt holds the string denoting the startedat field in the database. @@ -53,6 +55,7 @@ var Columns = []string{ FieldProcessName, FieldStatus, FieldOperator, + FieldOperatorId, FieldResult, FieldStartedAt, FieldEndedAt, @@ -94,6 +97,8 @@ var ( DefaultOperator string // OperatorValidator is a validator for the "operator" field. It is called by the builders before save. OperatorValidator func(string) error + // DefaultOperatorId holds the default value on creation for the "operatorId" field. + DefaultOperatorId int // DefaultResult holds the default value on creation for the "result" field. DefaultResult string // ResultValidator is a validator for the "result" field. It is called by the builders before save. @@ -153,6 +158,11 @@ func ByOperator(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldOperator, opts...).ToFunc() } +// ByOperatorId orders the results by the operatorId field. +func ByOperatorId(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperatorId, opts...).ToFunc() +} + // ByResult orders the results by the result field. func ByResult(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldResult, opts...).ToFunc() diff --git a/bj_power_mes/ent/workpieceprocess_create.go b/bj_power_mes/ent/workpieceprocess_create.go index b69fb1e..d8675a9 100644 --- a/bj_power_mes/ent/workpieceprocess_create.go +++ b/bj_power_mes/ent/workpieceprocess_create.go @@ -102,6 +102,20 @@ func (_c *WorkpieceProcessCreate) SetNillableOperator(v *string) *WorkpieceProce return _c } +// SetOperatorId sets the "operatorId" field. +func (_c *WorkpieceProcessCreate) SetOperatorId(v int) *WorkpieceProcessCreate { + _c.mutation.SetOperatorId(v) + return _c +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_c *WorkpieceProcessCreate) SetNillableOperatorId(v *int) *WorkpieceProcessCreate { + if v != nil { + _c.SetOperatorId(*v) + } + return _c +} + // SetResult sets the "result" field. func (_c *WorkpieceProcessCreate) SetResult(v string) *WorkpieceProcessCreate { _c.mutation.SetResult(v) @@ -247,6 +261,10 @@ func (_c *WorkpieceProcessCreate) defaults() { v := workpieceprocess.DefaultOperator _c.mutation.SetOperator(v) } + if _, ok := _c.mutation.OperatorId(); !ok { + v := workpieceprocess.DefaultOperatorId + _c.mutation.SetOperatorId(v) + } if _, ok := _c.mutation.Result(); !ok { v := workpieceprocess.DefaultResult _c.mutation.SetResult(v) @@ -318,6 +336,9 @@ func (_c *WorkpieceProcessCreate) check() error { return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "WorkpieceProcess.operator": %w`, err)} } } + if _, ok := _c.mutation.OperatorId(); !ok { + return &ValidationError{Name: "operatorId", err: errors.New(`ent: missing required field "WorkpieceProcess.operatorId"`)} + } if _, ok := _c.mutation.Result(); !ok { return &ValidationError{Name: "result", err: errors.New(`ent: missing required field "WorkpieceProcess.result"`)} } @@ -405,6 +426,10 @@ func (_c *WorkpieceProcessCreate) createSpec() (*WorkpieceProcess, *sqlgraph.Cre _spec.SetField(workpieceprocess.FieldOperator, field.TypeString, value) _node.Operator = value } + if value, ok := _c.mutation.OperatorId(); ok { + _spec.SetField(workpieceprocess.FieldOperatorId, field.TypeInt, value) + _node.OperatorId = value + } if value, ok := _c.mutation.Result(); ok { _spec.SetField(workpieceprocess.FieldResult, field.TypeString, value) _node.Result = value diff --git a/bj_power_mes/ent/workpieceprocess_update.go b/bj_power_mes/ent/workpieceprocess_update.go index 22e9f40..bce3eb9 100644 --- a/bj_power_mes/ent/workpieceprocess_update.go +++ b/bj_power_mes/ent/workpieceprocess_update.go @@ -134,6 +134,27 @@ func (_u *WorkpieceProcessUpdate) SetNillableOperator(v *string) *WorkpieceProce return _u } +// SetOperatorId sets the "operatorId" field. +func (_u *WorkpieceProcessUpdate) SetOperatorId(v int) *WorkpieceProcessUpdate { + _u.mutation.ResetOperatorId() + _u.mutation.SetOperatorId(v) + return _u +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_u *WorkpieceProcessUpdate) SetNillableOperatorId(v *int) *WorkpieceProcessUpdate { + if v != nil { + _u.SetOperatorId(*v) + } + return _u +} + +// AddOperatorId adds value to the "operatorId" field. +func (_u *WorkpieceProcessUpdate) AddOperatorId(v int) *WorkpieceProcessUpdate { + _u.mutation.AddOperatorId(v) + return _u +} + // SetResult sets the "result" field. func (_u *WorkpieceProcessUpdate) SetResult(v string) *WorkpieceProcessUpdate { _u.mutation.SetResult(v) @@ -342,6 +363,12 @@ func (_u *WorkpieceProcessUpdate) sqlSave(ctx context.Context) (_node int, err e if value, ok := _u.mutation.Operator(); ok { _spec.SetField(workpieceprocess.FieldOperator, field.TypeString, value) } + if value, ok := _u.mutation.OperatorId(); ok { + _spec.SetField(workpieceprocess.FieldOperatorId, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOperatorId(); ok { + _spec.AddField(workpieceprocess.FieldOperatorId, field.TypeInt, value) + } if value, ok := _u.mutation.Result(); ok { _spec.SetField(workpieceprocess.FieldResult, field.TypeString, value) } @@ -493,6 +520,27 @@ func (_u *WorkpieceProcessUpdateOne) SetNillableOperator(v *string) *WorkpiecePr return _u } +// SetOperatorId sets the "operatorId" field. +func (_u *WorkpieceProcessUpdateOne) SetOperatorId(v int) *WorkpieceProcessUpdateOne { + _u.mutation.ResetOperatorId() + _u.mutation.SetOperatorId(v) + return _u +} + +// SetNillableOperatorId sets the "operatorId" field if the given value is not nil. +func (_u *WorkpieceProcessUpdateOne) SetNillableOperatorId(v *int) *WorkpieceProcessUpdateOne { + if v != nil { + _u.SetOperatorId(*v) + } + return _u +} + +// AddOperatorId adds value to the "operatorId" field. +func (_u *WorkpieceProcessUpdateOne) AddOperatorId(v int) *WorkpieceProcessUpdateOne { + _u.mutation.AddOperatorId(v) + return _u +} + // SetResult sets the "result" field. func (_u *WorkpieceProcessUpdateOne) SetResult(v string) *WorkpieceProcessUpdateOne { _u.mutation.SetResult(v) @@ -731,6 +779,12 @@ func (_u *WorkpieceProcessUpdateOne) sqlSave(ctx context.Context) (_node *Workpi if value, ok := _u.mutation.Operator(); ok { _spec.SetField(workpieceprocess.FieldOperator, field.TypeString, value) } + if value, ok := _u.mutation.OperatorId(); ok { + _spec.SetField(workpieceprocess.FieldOperatorId, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedOperatorId(); ok { + _spec.AddField(workpieceprocess.FieldOperatorId, field.TypeInt, value) + } if value, ok := _u.mutation.Result(); ok { _spec.SetField(workpieceprocess.FieldResult, field.TypeString, value) } diff --git a/bj_power_mes/frontend/src/pages/Inspect.vue b/bj_power_mes/frontend/src/pages/Inspect.vue index 5ae2f9f..d178d2b 100644 --- a/bj_power_mes/frontend/src/pages/Inspect.vue +++ b/bj_power_mes/frontend/src/pages/Inspect.vue @@ -589,7 +589,7 @@ async function submitDone() { } // ---- 完工检(质检员在巡检终端录入,合格自动回流 WMS) ---- -const canFinal = can('produce.quality:edit') +const canFinal = can('produce.quality:final') const finalForm = reactive({ sn: '', materialCode: '', materialName: '', relatedStandard: '', testRecordNo: '', result: 'OK', photo: '', remark: '' diff --git a/bj_power_mes/frontend/src/pages/QualityInspection.vue b/bj_power_mes/frontend/src/pages/QualityInspection.vue index 536ff07..9c496fd 100644 --- a/bj_power_mes/frontend/src/pages/QualityInspection.vue +++ b/bj_power_mes/frontend/src/pages/QualityInspection.vue @@ -69,7 +69,7 @@ 附件 diff --git a/bj_power_mes/internal/config/config.go b/bj_power_mes/internal/config/config.go index b17502a..db03880 100644 --- a/bj_power_mes/internal/config/config.go +++ b/bj_power_mes/internal/config/config.go @@ -29,24 +29,28 @@ type RedisConfWrapper struct { // AuthConf 鉴权配置:JWT Secret / 有效期 // 只保留滑动续签:AccessExpire = 会话闲置窗口 type AuthConf struct { - AccessSecret string `json:",default=Hardman_2026"` + // AccessSecret 必须由 yaml 提供,禁止编译期默认密钥(防默认密钥被绕过) + AccessSecret string `json:"AccessSecret"` AccessExpire int64 `json:",default=3600"` // 会话闲置窗口(秒),滑动续签下 = 距最后请求多久后需重登 } // InternalConf 内部服务间鉴权 type InternalConf struct { - Token string `json:",default=Hardman_2026"` + // Token 必须由 yaml 提供,禁止编译期默认密钥(防空 token 绕过内部接口鉴权) + Token string `json:"Token"` } // CliConf 命令行敏感操作门禁密码(与管理员账号密码保持一致,改密时自动同步) type CliConf struct { - AdminPassword string `json:"AdminPassword,default=Hardman_2026"` + // AdminPassword 必须由 yaml 提供,禁止编译期默认密钥(migrate/reset-all/seed 高危门禁) + AdminPassword string `json:"AdminPassword"` } // WmsConf WMS 内部服务地址 type WmsConf struct { BaseURL string `json:",default="` - Token string `json:",default=Hardman_2026"` + // Token 必须由 yaml 提供,禁止编译期默认密钥 + Token string `json:"Token"` } // PlcConf PLC 对接配置(mock 时不用) diff --git a/bj_power_mes/internal/db/db.go b/bj_power_mes/internal/db/db.go index 968e587..f28bcf4 100644 --- a/bj_power_mes/internal/db/db.go +++ b/bj_power_mes/internal/db/db.go @@ -248,6 +248,20 @@ var schemaPatchSQL = []string{ `DROP TABLE IF EXISTS torque_audit_log`, `ALTER TABLE torque_record DROP COLUMN IF EXISTS audit_by`, `ALTER TABLE torque_record DROP COLUMN IF EXISTS audit_at`, + + // ---- 方案 B 补1(2026-10-06):报工/拧紧落库操作人用户ID ---- + // 配合隐患1「离线数据身份快照」:报工实绩/拧紧记录同时携带 姓名+用户ID,杜绝重名追溯歧义。 + // operator_id=0 语义(核实4 文档化):=未采集,来源①PLC/设备直连、MES 前端虚拟工位等无工位 + // 登录态路径;来源②快照机制上线前的历史存量(当时未采集,无法回填)。两类以 created_at 与 + // 调用路径特征区分;operator_id>0 一律为工位登录态可信用户ID(含离线重传按录入人落库)。 + `ALTER TABLE workpiece_process ADD COLUMN IF NOT EXISTS operator_id integer NOT NULL DEFAULT 0`, + `ALTER TABLE torque_record ADD COLUMN IF NOT EXISTS operator_id integer NOT NULL DEFAULT 0`, + + // ---- 回滚「自动代传」设计(2026-10-06):删除 delegate_id 列 ---- + // 代传/快照/过期窗口等概念已移除,落库操作人统一为「当前登录态 JWT 解析出的用户ID」(operator_id); + // 历史库若已存在 delegate_id 列则删除,保持无遗留字段。 + `ALTER TABLE workpiece_process DROP COLUMN IF EXISTS delegate_id`, + `ALTER TABLE torque_record DROP COLUMN IF EXISTS delegate_id`, } // EnsureSchema ent 建表 + 幂等列补丁(只增,不删数据) diff --git a/bj_power_mes/internal/handler/inspection.go b/bj_power_mes/internal/handler/inspection.go index 304b56d..e6a5ed6 100644 --- a/bj_power_mes/internal/handler/inspection.go +++ b/bj_power_mes/internal/handler/inspection.go @@ -27,13 +27,17 @@ func CreateInspectionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { "DONE": "sys.inspect:done", "ALARM": "sys.inspect:alarm", } - // 质量检验三类(过程检 QC_PROCESS / 完工检 FINAL / 来料检 INCOMING)与 PAD 巡检共用本接口, - // 必须持有质量检验录入权限 produce.quality:edit 方可提交(质检员专属,操作工仅做完工确认)。 + // 质量检验权限粒度拆分(补1):过程检(QC_PROCESS)操作工自检+质检员;完工检(FINAL)/来料检(INCOMING)质检员专属。 + // 故按记录类型映射不同权限码,而非单一 produce.quality:edit。 // 注:PAD 巡检「过程巡检」仍用 PROCESS(走 categoryPerm 的 sys.inspect:process),与质检隔离(P1-8)。 - qualityCats := map[string]bool{"QC_PROCESS": true, "FINAL": true, "INCOMING": true} - if qualityCats[req.Category] { - if !userHasPerm(r, svcCtx, "produce.quality:edit") { - httpx.FailHTTP(w, http.StatusForbidden, "无操作权限:produce.quality:edit") + qualityCatPerm := map[string]string{ + "QC_PROCESS": "produce.quality:process", + "FINAL": "produce.quality:final", + "INCOMING": "produce.quality:final", + } + if perm, ok := qualityCatPerm[req.Category]; ok { + if !userHasPerm(r, svcCtx, perm) { + httpx.FailHTTP(w, http.StatusForbidden, "无操作权限:"+perm) return } } else if code, ok := categoryPerm[req.Category]; ok { @@ -128,6 +132,21 @@ func InspectionDisposalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "缺少 id") return } + // 权限粒度拆分(补1):处置按记录类型校验——过程检(QC_PROCESS)用 produce.quality:process, + // 完工检/来料检(FINAL/INCOMING)用 produce.quality:final。后端兜底校验,与前端 can() 一致。 + rec, err := logic.New(svcCtx).GetInspectionRecord(r.Context(), req.Id) + if err != nil { + httpx.Fail(w, 2305, err.Error()) + return + } + dispPerm := "produce.quality:final" + if rec.Category == "QC_PROCESS" { + dispPerm = "produce.quality:process" + } + if !userHasPerm(r, svcCtx, dispPerm) { + httpx.FailHTTP(w, http.StatusForbidden, "无操作权限:"+dispPerm) + return + } msg, err := logic.New(svcCtx).SetInspectionDisposal(r.Context(), req.Id, req.DisposalType, req.DisposalRemark, operator(r, "")) if err != nil { httpx.Fail(w, 2305, err.Error()) diff --git a/bj_power_mes/internal/handler/line.go b/bj_power_mes/internal/handler/line.go index 74891b1..8c8818d 100644 --- a/bj_power_mes/internal/handler/line.go +++ b/bj_power_mes/internal/handler/line.go @@ -5,6 +5,7 @@ import ( "strings" "bj_power_mes/common/httpx" + "bj_power_mes/internal/handler/production" "bj_power_mes/internal/logic" "bj_power_mes/internal/svc" ) @@ -32,10 +33,8 @@ func OccupyPointHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "action 仅支持 IN(上料) / OUT(下料)") return } - op := req.Operator - if op == "" { - op = operator(r, "") - } + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/line/occupy") + op := production.StationOp(r, req.Operator) if err := logic.New(svcCtx).OccupyPoint(r.Context(), req.PointNo, req.Sn, req.OrderNo, op, action); err != nil { httpx.Fail(w, 2407, err.Error()) return @@ -74,7 +73,8 @@ func CallMaterialHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - n, err := logic.New(svcCtx).CallMaterial(r.Context(), req.StationNo, req.Dock, req.OrderNo, operator(r, ""), req.Items) + production.LogImpersonation(svcCtx, r, "", "/api/internal/line/call-material") + n, err := logic.New(svcCtx).CallMaterial(r.Context(), req.StationNo, req.Dock, req.OrderNo, production.StationOp(r, ""), req.Items) if err != nil { httpx.Fail(w, 2406, err.Error()) return diff --git a/bj_power_mes/internal/handler/perm.go b/bj_power_mes/internal/handler/perm.go index 52b7b93..4cc54cd 100644 --- a/bj_power_mes/internal/handler/perm.go +++ b/bj_power_mes/internal/handler/perm.go @@ -36,8 +36,8 @@ var pathPermMap = map[string]string{ "PUT:/api/v1/settings": "sys.settings:edit", // 过程巡检汇总生成《工序间检验记录》(巡检终端操作域) "POST:/api/v1/inspections/generate-inter-process": "sys.inspect:process", - // 质量检验处置(过程检/完工检不合格处置 退货/返修/退换) - "POST:/api/v1/quality/disposal": "produce.quality:edit", + // 质量检验处置(过程检/完工检不合格处置 退货/返修/退换):按记录类型在 handler 内做权限粒度校验 + //(produce.quality:process / produce.quality:final),此处不映射单一码,避免误拦/误放。 // 检验员签字确认(需求B 第二签,巡检终端「待签任务」) "POST:/api/v1/signs/inspector": "sys.inspect:sign", // 附件中心(sys.attachment 菜单下):删除 / 归档清理属管理动作; diff --git a/bj_power_mes/internal/handler/production/bind.go b/bj_power_mes/internal/handler/production/bind.go index f785e55..1c415ed 100644 --- a/bj_power_mes/internal/handler/production/bind.go +++ b/bj_power_mes/internal/handler/production/bind.go @@ -29,7 +29,8 @@ func doBind(svcCtx *svc.ServiceContext, r *http.Request) (any, error) { if req.Sn == "" || req.FlowId <= 0 { return nil, nil } - op := operator(r, req.Operator) + LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/binds") + op := StationOp(r, req.Operator) stationNo := "" if req.StationNo > 0 { stationNo = itoa(req.StationNo) @@ -64,7 +65,8 @@ func doUnbind(svcCtx *svc.ServiceContext, r *http.Request) error { if err := httpx.ParseJSON(r, &req); err != nil { return err } - return logic.New(svcCtx).RemoveBind(r.Context(), req.Sn, req.FlowId, req.MaterialCode, req.BindValue, operator(r, req.Operator)) + LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/binds/remove") + return logic.New(svcCtx).RemoveBind(r.Context(), req.Sn, req.FlowId, req.MaterialCode, req.BindValue, StationOp(r, req.Operator)) } // UnbindInternalHandler POST /api/internal/workpiece/binds/remove diff --git a/bj_power_mes/internal/handler/production/material.go b/bj_power_mes/internal/handler/production/material.go index c1d23fc..63bff3f 100644 --- a/bj_power_mes/internal/handler/production/material.go +++ b/bj_power_mes/internal/handler/production/material.go @@ -188,7 +188,7 @@ func StationReceiveMaterialInternalHandler(svcCtx *svc.ServiceContext) http.Hand httpx.BadRequest(w, "缺少备料单号") return } - if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil { + if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, StationOp(r, "")); err != nil { httpx.Fail(w, 3114, err.Error()) return } diff --git a/bj_power_mes/internal/handler/production/plc_torque_scan.go b/bj_power_mes/internal/handler/production/plc_torque_scan.go index 1f51b38..16655b9 100644 --- a/bj_power_mes/internal/handler/production/plc_torque_scan.go +++ b/bj_power_mes/internal/handler/production/plc_torque_scan.go @@ -71,7 +71,7 @@ func TorqueReportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator)); err != nil { + if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator), 0); err != nil { httpx.Fail(w, 3203, err.Error()) return } diff --git a/bj_power_mes/internal/handler/production/production.go b/bj_power_mes/internal/handler/production/production.go index eab609f..91b4145 100644 --- a/bj_power_mes/internal/handler/production/production.go +++ b/bj_power_mes/internal/handler/production/production.go @@ -1,9 +1,13 @@ package production import ( + "fmt" "net/http" "strconv" + "strings" + "time" + token "bj_power_mes/common/token" "bj_power_mes/common/httpx" "bj_power_mes/ent" "bj_power_mes/ent/material" @@ -49,6 +53,98 @@ func InternalAuth(serverCtx *svc.ServiceContext) func(http.HandlerFunc) http.Han } } +// StationSessionAuth 工位终端报工鉴权中间件(安全方案 B · 关闭 #11/#14 冒名留痕)。 +// 要求工位终端在 Authorization: Bearer 携带「登录时 MES 签发的 JWT」(与 MES 前端同源同密钥), +// 校验通过后从该 token 的 claims 提取可信操作人(Name)与工位号(StationNo)注入请求头; +// 报工/拧紧 handler 据此落痕,忽略请求体里的 operator/stationNo。 +// 与 InternalAuth(X-API-TOKEN 网关)互补:前者管“哪个系统”,本中间件管“哪个操作工”的可信身份。 +func StationSessionAuth(serverCtx *svc.ServiceContext) func(http.HandlerFunc) http.HandlerFunc { + return func(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + authz := r.Header.Get("Authorization") + if !strings.HasPrefix(authz, "Bearer ") { + httpx.FailHTTP(w, http.StatusUnauthorized, "缺少工位登录凭证,请重新登录") + return + } + claims, err := token.Parse(serverCtx.Config.Auth.AccessSecret, strings.TrimPrefix(authz, "Bearer ")) + if err != nil || claims == nil || time.Until(claims.ExpiresAt.Time) <= 0 { + httpx.FailHTTP(w, http.StatusUnauthorized, "工位登录凭证无效或已过期,请重新登录") + return + } + r.Header.Set("X-Station-Operator", claims.Name) + r.Header.Set("X-Station-Operator-Id", strconv.Itoa(claims.UserId)) + if claims.StationNo > 0 { + r.Header.Set("X-Station-No", strconv.Itoa(claims.StationNo)) + } + next(w, r) + } + } +} + +// StationOp 报工链路可信操作人解析(方案 B · 关闭 #11/#14 冒名留痕):优先取工位登录态注入的 Name, +// 未携带登录态时(如 MES 前端 JWT 虚拟工位作业路径)回退到原有 operator(r, bodyOp)。 +// 这样同一 StationReport 既服务于终端(强可信)也服务于管理后台(登录账号留痕),互不破坏。 +func StationOp(r *http.Request, bodyOp string) string { + if v := r.Header.Get("X-Station-Operator"); v != "" { + return v + } + return operator(r, bodyOp) +} + +// StationNo 报工链路可信工位号解析(方案 B):优先取工位登录态注入的 StationNo,否则回退请求体。 +func StationNo(r *http.Request, bodyNo int) int { + if v := r.Header.Get("X-Station-No"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + return n + } + } + return bodyNo +} + +// StationOpId 报工链路可信操作人 ID(方案 B 补1):取工位登录态注入的 UserId, +// 用于落库/审计时同时携带「姓名 + 用户ID」,避免重名导致追溯歧义。 +func StationOpId(r *http.Request) string { + return r.Header.Get("X-Station-Operator-Id") +} + +// StationOpIdInt 报工链路可信操作人 ID(落库 operator_id 用)。 +// 返回值语义(核实2): +// - 未携带 X-Station-Operator-Id 头(MES 前端虚拟工位 / PLC 扫码等无工位登录态路径) +// → (0, nil):0 = 「未采集」,属合法语义,不报错; +// - 携带了头但内容非法或 ≤0(正常只可能来自 StationSessionAuth 注入的 JWT userId, +// 出现即说明凭证被伪造/中间件被绕过)→ (0, error):调用方必须拒绝请求, +// 杜绝「身份静默丢失为 0」被当成正常数据入库。 +func StationOpIdInt(r *http.Request) (int, error) { + v := r.Header.Get("X-Station-Operator-Id") + if v == "" { + return 0, nil + } + n, err := strconv.Atoi(v) + if err != nil || n <= 0 { + return 0, fmt.Errorf("工位登录态操作人ID非法:%q", v) + } + return n, nil +} + + +// LogImpersonation 防冒名探测器(方案 B 补2):当请求体 operator 与登录态可信 operator 不一致时, +// 写一条 security.impersonation 安全告警(含双方身份与工位号),用于上线后监测是否有人伪造操作人。 +// 仅在携带登录态(内部路由经 StationSessionAuth)时生效;管理后台 JWT 路径 bodyOp 为空不触发。 +func LogImpersonation(svcCtx *svc.ServiceContext, r *http.Request, bodyOp, path string) { + trusted := r.Header.Get("X-Station-Operator") + if bodyOp != "" && trusted != "" && bodyOp != trusted { + svcCtx.EventLog.Write(r.Context(), "security.impersonation", "", trusted, "auth", "", + "工位终端上报操作人与登录态不一致(疑似冒名)", + map[string]any{ + "path": path, + "bodyOperator": bodyOp, + "trustedOperator": trusted, + "trustedOperatorId": r.Header.Get("X-Station-Operator-Id"), + "stationNo": r.Header.Get("X-Station-No"), + }) + } +} + // ---------- 内部 API(看板/工位终端/WMS 调用) ---------- func TorqueReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { @@ -58,7 +154,18 @@ func TorqueReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).ReportTorque(r.Context(), req, operator(r, req.Operator)); err != nil { + // 方案 B(#11/#14):操作人/工位号取自工位登录态可信身份,忽略请求体 + if v := r.Header.Get("X-Station-No"); v != "" { + req.StationNo = v + } + LogImpersonation(svcCtx, r, req.Operator, "/api/internal/torque/report") + recOpId, derr := StationOpIdInt(r) + if derr != nil { + httpx.Fail(w, 2001, derr.Error()) + return + } + recOpName := StationOp(r, req.Operator) + if err := logic.New(svcCtx).ReportTorque(r.Context(), req, recOpName, recOpId); err != nil { httpx.Fail(w, 2001, err.Error()) return } @@ -73,7 +180,16 @@ func WorkpieceReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).ReportProcess(r.Context(), req, operator(r, "")); err != nil { + // 方案 B(#11/#14):操作人/工位号取自工位登录态可信身份,忽略请求体 + req.StationNo = StationNo(r, req.StationNo) + LogImpersonation(svcCtx, r, req.Operator, "/api/internal/workpiece/report") + recOpId, derr := StationOpIdInt(r) + if derr != nil { + httpx.Fail(w, 2002, derr.Error()) + return + } + recOpName := StationOp(r, req.Operator) + if err := logic.New(svcCtx).ReportProcess(r.Context(), req, recOpName, recOpId); err != nil { httpx.Fail(w, 2002, err.Error()) return } @@ -158,7 +274,8 @@ func OnlineWorkpieceInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc httpx.BadRequest(w, "请求体解析失败") return } - if msg, err := logic.New(svcCtx).OnlineWorkpiece(r.Context(), req, operator(r, r.URL.Query().Get("operator"))); err != nil { + LogImpersonation(svcCtx, r, r.URL.Query().Get("operator"), "/api/internal/workpiece/online") + if msg, err := logic.New(svcCtx).OnlineWorkpiece(r.Context(), req, StationOp(r, r.URL.Query().Get("operator"))); err != nil { httpx.Fail(w, 2007, err.Error()) return } else { @@ -176,7 +293,8 @@ func DoneWorkpieceInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).DoneWorkpiece(r.Context(), req, operator(r, r.URL.Query().Get("operator"))); err != nil { + LogImpersonation(svcCtx, r, r.URL.Query().Get("operator"), "/api/internal/workpiece/done") + if err := logic.New(svcCtx).DoneWorkpiece(r.Context(), req, StationOp(r, r.URL.Query().Get("operator"))); err != nil { httpx.Fail(w, 2008, err.Error()) return } diff --git a/bj_power_mes/internal/handler/production/security_verify_test.go b/bj_power_mes/internal/handler/production/security_verify_test.go new file mode 100644 index 0000000..e140868 --- /dev/null +++ b/bj_power_mes/internal/handler/production/security_verify_test.go @@ -0,0 +1,157 @@ +package production_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + tokenx "bj_power_mes/common/token" + "bj_power_mes/internal/config" + "bj_power_mes/internal/db" + "bj_power_mes/internal/eventlog" + "bj_power_mes/internal/handler/production" + "bj_power_mes/internal/svc" + eventlogpred "bj_power_mes/ent/eventlog" +) + +// TestStationSecurityVerify 运行期验证方案 B 安全整改(核实2 / 补1 / 补2): +// - 正常登录:报工 operator 取自 JWT 可信身份(真实姓名) +// - 伪造请求体 operator:仍以 JWT 真实姓名落痕,且冒名探测器写 security.impersonation +// - 无/过期 Bearer:401,不进入业务 +// +// 仅连 PostgreSQL(dev 库),不依赖 Redis/PLC,测试后清理自身写入的审计行。 +func TestStationSecurityVerify(t *testing.T) { + secret := "Hardman_2026" + c := config.Config{ + Auth: config.AuthConf{AccessSecret: secret, AccessExpire: 3600}, + Internal: config.InternalConf{Token: secret}, + } + entClient, _ := db.MustNewDB(db.DatabaseConf{ + Host: "127.0.0.1", Port: 5432, User: "postgres", Password: "postgres", + Dbname: "bj_power_mes", MaxIdle: 5, MaxOpen: 5, + }) + svcCtx := &svc.ServiceContext{Config: c, EntClient: entClient, EventLog: eventlog.NewWriter(entClient)} + ctx := context.Background() + + // 真实登录态 JWT:用户 7 张三,工位 3 + realTok, err := tokenx.Issue(secret, time.Hour, tokenx.Claims{ + UserId: 7, Username: "zhangsan", Name: "张三", StationNo: 3, + }) + if err != nil { + t.Fatalf("签发 JWT 失败: %v", err) + } + // 过期 JWT(expire = -1h) + expiredTok, _ := tokenx.Issue(secret, -time.Hour, tokenx.Claims{ + UserId: 7, Username: "zhangsan", Name: "张三", StationNo: 3, + }) + + type reportBody struct { + Operator string `json:"operator"` + StationNo string `json:"stationNo"` + } + type echoResp struct { + Resolved string `json:"resolved"` + Trusted string `json:"trusted"` + OpId string `json:"opId"` + StationNo string `json:"stationNo"` + } + + var capture = func(w http.ResponseWriter, r *http.Request) { + var req reportBody + _ = json.NewDecoder(r.Body).Decode(&req) + resolved := production.StationOp(r, req.Operator) + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/torque/report") + resp := echoResp{ + Resolved: resolved, + Trusted: r.Header.Get("X-Station-Operator"), + OpId: r.Header.Get("X-Station-Operator-Id"), + StationNo: r.Header.Get("X-Station-No"), + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) + } + + h := production.StationSessionAuth(svcCtx)(capture) + ts := httptest.NewServer(h) + defer ts.Close() + + doPost := func(tok, bodyOp string) (int, echoResp) { + body, _ := json.Marshal(reportBody{Operator: bodyOp, StationNo: "3"}) + req, _ := http.NewRequest(http.MethodPost, ts.URL, bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if tok != "" { + req.Header.Set("Authorization", "Bearer "+tok) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("请求失败: %v", err) + } + defer resp.Body.Close() + var er echoResp + _ = json.NewDecoder(resp.Body).Decode(&er) + return resp.StatusCode, er + } + + beforeCount, _ := svcCtx.EntClient.EventLog.Query(). + Where(eventlogpred.EventType("security.impersonation")).Count(ctx) + testStart := time.Now() + + // 场景1:正常登录,请求体 operator 与 JWT 一致(张三) + code, er := doPost(realTok, "张三") + if code != 200 { + t.Errorf("[场景1] 期望 200,实际 %d", code) + } + if er.Resolved != "张三" { + t.Errorf("[场景1] 落痕操作人应为 JWT 真实姓名『张三』,实际 %q", er.Resolved) + } + if er.OpId != "7" { + t.Errorf("[场景1] 补1 operatorId 应为 7,实际 %q", er.OpId) + } + if er.StationNo != "3" { + t.Errorf("[场景1] 工位号应为 3,实际 %q", er.StationNo) + } + t.Logf("[场景1 正常登录] code=%d resolved=%q opId=%q stationNo=%q", code, er.Resolved, er.OpId, er.StationNo) + + // 场景2:伪造请求体 operator=李四,应以 JWT 张三落痕,并触发冒名探测器 + code, er = doPost(realTok, "李四") + if code != 200 { + t.Errorf("[场景2] 期望 200,实际 %d", code) + } + if er.Resolved != "张三" { + t.Errorf("[场景2] 冒名请求体被忽略失败:落痕操作人应为『张三』,实际 %q", er.Resolved) + } + t.Logf("[场景2 伪造请求体] code=%d resolved=%q (请求体 operator=李四 已被忽略)", code, er.Resolved) + + afterCount, _ := svcCtx.EntClient.EventLog.Query(). + Where(eventlogpred.EventType("security.impersonation")).Count(ctx) + if afterCount <= beforeCount { + t.Errorf("[场景2] 冒名探测器未落库:security.impersonation 行数 %d -> %d", beforeCount, afterCount) + } else { + t.Logf("[场景2 冒名探测器] security.impersonation 新增 %d 行(已落库)", afterCount-beforeCount) + } + + // 场景3a:无 Bearer → 401 + code, _ = doPost("", "王五") + if code != http.StatusUnauthorized { + t.Errorf("[场景3a] 无凭证期望 401,实际 %d", code) + } else { + t.Logf("[场景3a 无登录凭证] code=%d(已拦截)", code) + } + + // 场景3b:过期 Bearer → 401(触发工位终端重登录续传,数据不丢) + code, _ = doPost(expiredTok, "张三") + if code != http.StatusUnauthorized { + t.Errorf("[场景3b] 过期凭证期望 401,实际 %d", code) + } else { + t.Logf("[场景3b 凭证过期] code=%d(已拦截,终端应暂停重传而非丢数据)", code) + } + + // 清理:仅删除本测试写入的 security.impersonation 行(按时间窗) + _, _ = svcCtx.EntClient.EventLog.Delete(). + Where(eventlogpred.EventType("security.impersonation"), eventlogpred.CreatedAtGTE(testStart)).Exec(ctx) +} + diff --git a/bj_power_mes/internal/handler/production/station_state.go b/bj_power_mes/internal/handler/production/station_state.go index d75af14..5b0e959 100644 --- a/bj_power_mes/internal/handler/production/station_state.go +++ b/bj_power_mes/internal/handler/production/station_state.go @@ -22,7 +22,8 @@ func StationPauseInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).SetStationPause(r.Context(), req.StationNo, req.Paused, req.Reason, operator(r, req.Operator)); err != nil { + LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/pause") + if err := logic.New(svcCtx).SetStationPause(r.Context(), req.StationNo, req.Paused, req.Reason, StationOp(r, req.Operator)); err != nil { httpx.Fail(w, 2115, err.Error()) return } diff --git a/bj_power_mes/internal/handler/routes.go b/bj_power_mes/internal/handler/routes.go index 88e53c8..601e1f0 100644 --- a/bj_power_mes/internal/handler/routes.go +++ b/bj_power_mes/internal/handler/routes.go @@ -18,7 +18,8 @@ func RegisterRoutes(server *rest.Server, serverCtx *svc.ServiceContext) { // JWT 保护:用户信息 + 用户/角色/权限 管理 jwtAdmin := []rest.Route{ {Method: http.MethodGet, Path: "/userinfo", Handler: UserInfoHandler(serverCtx)}, - {Method: http.MethodPost, Path: "/seed", Handler: SeedHandler(serverCtx)}, + // /seed 已从对外路由摘除:seed 是运维/初始化工具接口,非业务接口, + // 仅通过 CLI 子命令 `bj_power_mes.exe seed`(带管理员密码门 adminGate)执行,避免任意登录用户提权。 {Method: http.MethodPost, Path: "/user/change-password", Handler: ChangePasswordHandler(serverCtx)}, {Method: http.MethodPost, Path: "/logout", Handler: LogoutHandler(serverCtx)}, diff --git a/bj_power_mes/internal/handler/routes_production.go b/bj_power_mes/internal/handler/routes_production.go index 05dbb60..db9b018 100644 --- a/bj_power_mes/internal/handler/routes_production.go +++ b/bj_power_mes/internal/handler/routes_production.go @@ -19,10 +19,10 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext internal := production.InternalAuth(serverCtx) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/torque/report", Handler: internal(production.TorqueReportInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/torque/report", Handler: internal(production.StationSessionAuth(serverCtx)(production.TorqueReportInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/workpiece/report", Handler: internal(production.WorkpieceReportInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/workpiece/report", Handler: internal(production.StationSessionAuth(serverCtx)(production.WorkpieceReportInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/workpiece/trace", Handler: internal(production.WorkpieceTraceInternalHandler(serverCtx)), @@ -45,7 +45,7 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext Method: http.MethodGet, Path: "/api/internal/dashboard/snapshot", Handler: internal(production.DashboardSnapshotInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodGet, Path: "/api/internal/dashboard/stream", Handler: serverCtx.SSE.Handler, + Method: http.MethodGet, Path: "/api/internal/dashboard/stream", Handler: internal(serverCtx.SSE.Handler), }, rest.WithTimeout(3600_000_000_000)) // ---------- 工位终端内部 API(块1/4/5/6) ---------- @@ -55,6 +55,10 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext server.AddRoute(rest.Route{ Method: http.MethodPost, Path: "/api/internal/station/logout", Handler: internal(StationLogoutInternalHandler(serverCtx)), }) + // 工位终端滑动续签:校验当前登录态 Bearer → 原样重签新 JWT(终端触屏经节流调用) + server.AddRoute(rest.Route{ + Method: http.MethodPost, Path: "/api/internal/station/refresh-token", Handler: internal(StationRefreshTokenInternalHandler(serverCtx)), + }) server.AddRoute(rest.Route{ Method: http.MethodPost, Path: "/api/internal/station/change-password", Handler: internal(StationChangePasswordInternalHandler(serverCtx)), }) @@ -62,25 +66,25 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext Method: http.MethodGet, Path: "/api/internal/station/task", Handler: internal(StationTaskInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/report", Handler: internal(StationReportInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/report", Handler: internal(production.StationSessionAuth(serverCtx)(StationReportInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/checkin", Handler: internal(StationCheckinInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/checkin", Handler: internal(production.StationSessionAuth(serverCtx)(StationCheckinInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/emergency", Handler: internal(StationEmergencyInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/emergency", Handler: internal(production.StationSessionAuth(serverCtx)(StationEmergencyInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/qty-report", Handler: internal(StationQtyReportInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/qty-report", Handler: internal(production.StationSessionAuth(serverCtx)(StationQtyReportInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/return-material", Handler: internal(StationReturnMaterialInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/return-material", Handler: internal(production.StationSessionAuth(serverCtx)(StationReturnMaterialInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/inspection", Handler: internal(StationInspectionInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/inspection", Handler: internal(production.StationSessionAuth(serverCtx)(StationInspectionInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/inspection-upload", Handler: internal(StationInspectionUploadInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/inspection-upload", Handler: internal(production.StationSessionAuth(serverCtx)(StationInspectionUploadInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/station/workload", Handler: internal(WorkloadInternalHandler(serverCtx)), @@ -90,20 +94,20 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext }) // ---------- 工位停单(只认当天;工人自主停/恢复) ---------- server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/pause", Handler: production.StationPauseInternalHandler(serverCtx), + Method: http.MethodPost, Path: "/api/internal/station/pause", Handler: internal(production.StationSessionAuth(serverCtx)(production.StationPauseInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodGet, Path: "/api/internal/station/state", Handler: production.StationStateInternalHandler(serverCtx), + Method: http.MethodGet, Path: "/api/internal/station/state", Handler: internal(production.StationStateInternalHandler(serverCtx)), }) // ---------- 工位终端 0/13 上下线 + 在制品(第五步 5.2/5.4)---------- server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/workpieces/in-process", Handler: internal(production.InProcessInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/workpiece/online", Handler: internal(production.OnlineWorkpieceInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/workpiece/online", Handler: internal(production.StationSessionAuth(serverCtx)(production.OnlineWorkpieceInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/workpiece/done", Handler: internal(production.DoneWorkpieceInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/workpiece/done", Handler: internal(production.StationSessionAuth(serverCtx)(production.DoneWorkpieceInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/order-usage", Handler: internal(production.OrderUsageInternalHandler(serverCtx)), @@ -124,10 +128,10 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext Method: http.MethodGet, Path: "/api/internal/workpiece/bind-panel", Handler: internal(production.BindPanelInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/workpiece/binds", Handler: internal(production.BindInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/workpiece/binds", Handler: internal(production.StationSessionAuth(serverCtx)(production.BindInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/workpiece/binds/remove", Handler: internal(production.UnbindInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/workpiece/binds/remove", Handler: internal(production.StationSessionAuth(serverCtx)(production.UnbindInternalHandler(serverCtx))), }) server.AddRoute(rest.Route{ Method: http.MethodPost, Path: "/api/internal/dock/pallet/set", Handler: internal(production.SetDockPalletInternalHandler(serverCtx)), @@ -142,13 +146,13 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext Method: http.MethodGet, Path: "/api/internal/line/points", Handler: internal(ListPointsHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/line/call-material", Handler: internal(CallMaterialHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/line/call-material", Handler: internal(production.StationSessionAuth(serverCtx)(CallMaterialHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/line/occupy", Handler: internal(OccupyPointHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/line/occupy", Handler: internal(production.StationSessionAuth(serverCtx)(OccupyPointHandler(serverCtx))), }) server.AddRoute(rest.Route{ - Method: http.MethodPost, Path: "/api/internal/station/receive-material", Handler: internal(production.StationReceiveMaterialInternalHandler(serverCtx)), + Method: http.MethodPost, Path: "/api/internal/station/receive-material", Handler: internal(production.StationSessionAuth(serverCtx)(production.StationReceiveMaterialInternalHandler(serverCtx))), }) // ---------- JWT 业务 API ---------- diff --git a/bj_power_mes/internal/handler/station.go b/bj_power_mes/internal/handler/station.go index 67b5472..43f968d 100644 --- a/bj_power_mes/internal/handler/station.go +++ b/bj_power_mes/internal/handler/station.go @@ -5,9 +5,11 @@ import ( "net/http" "net/url" "strconv" + "strings" "time" "bj_power_mes/common/httpx" + "bj_power_mes/internal/handler/production" "bj_power_mes/internal/logic" "bj_power_mes/internal/svc" @@ -81,6 +83,24 @@ func StationLogoutInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } +// StationRefreshTokenInternalHandler 工位终端滑动续签(内部接口,X-API-TOKEN 保护): +// 校验当前工位登录态 Bearer 有效后原样重签新 JWT(延长有效期),由工位终端 Go 后端节流代理调用。 +func StationRefreshTokenInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + authz := r.Header.Get("Authorization") + if !strings.HasPrefix(authz, "Bearer ") { + httpx.FailHTTP(w, http.StatusUnauthorized, "缺少工位登录凭证,请重新登录") + return + } + data, err := logic.New(svcCtx).StationRefreshToken(strings.TrimPrefix(authz, "Bearer ")) + if err != nil { + httpx.Fail(w, 2107, err.Error()) + return + } + httpx.Ok(w, data) + } +} + // StationChangePasswordInternalHandler 工位终端修改自己的工位终端密码 func StationChangePasswordInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -137,7 +157,19 @@ func StationReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).ReportProcess(r.Context(), req, operator(r, "")); err != nil { + // 方案 B(#11/#14):优先取工位登录态可信身份;未携带(MES 前端虚拟工位路径)回退 JWT 登录账号。 + recOpId, derr := production.StationOpIdInt(r) + if derr != nil { + httpx.Fail(w, 2104, derr.Error()) + return + } + recOpName := production.StationOp(r, req.Operator) + if v := r.Header.Get("X-Station-No"); v != "" { + if n, e := strconv.Atoi(v); e == nil && n > 0 { + req.StationNo = n + } + } + if err := logic.New(svcCtx).ReportProcess(r.Context(), req, recOpName, recOpId); err != nil { httpx.Fail(w, 2104, err.Error()) return } @@ -187,10 +219,8 @@ func StationCheckinInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc httpx.BadRequest(w, "缺少 sn") return } - op := req.Operator - if op == "" { - op = operator(r, "") - } + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/checkin") + op := production.StationOp(r, req.Operator) if err := logic.New(svcCtx).SemiFlow(r.Context(), logic.SemiReq{ Sn: req.Sn, OrderNo: req.OrderNo, diff --git a/bj_power_mes/internal/handler/station_ops.go b/bj_power_mes/internal/handler/station_ops.go index 732ebf8..9382b59 100644 --- a/bj_power_mes/internal/handler/station_ops.go +++ b/bj_power_mes/internal/handler/station_ops.go @@ -9,6 +9,7 @@ import ( "time" "bj_power_mes/common/httpx" + "bj_power_mes/internal/handler/production" "bj_power_mes/internal/logic" "bj_power_mes/internal/svc" ) @@ -29,7 +30,8 @@ func StationEmergencyInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFun httpx.BadRequest(w, "请求体解析失败") return } - if err := logic.New(svcCtx).EmergencyCall(r.Context(), req.StationNo, req.OrderNo, req.Remark, req.Operator); err != nil { + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/emergency") + if err := logic.New(svcCtx).EmergencyCall(r.Context(), req.StationNo, req.OrderNo, req.Remark, production.StationOp(r, req.Operator)); err != nil { httpx.Fail(w, 2401, err.Error()) return } @@ -46,6 +48,8 @@ func StationQtyReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFun httpx.BadRequest(w, "请求体解析失败") return } + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/qty-report") + req.Operator = production.StationOp(r, req.Operator) if err := logic.New(svcCtx).CreateQtyReport(r.Context(), req); err != nil { httpx.Fail(w, 2402, err.Error()) return @@ -74,8 +78,9 @@ func StationReturnMaterialInternalHandler(svcCtx *svc.ServiceContext) http.Handl httpx.BadRequest(w, "请求体解析失败") return } + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/return-material") if err := logic.New(svcCtx).StationReturnMaterial(r.Context(), req.OrderNo, req.StationNo, req.Sn, - req.MaterialCode, req.MaterialName, req.Spec, req.Reason, req.Operator, req.Unit, req.Qty); err != nil { + req.MaterialCode, req.MaterialName, req.Spec, req.Reason, production.StationOp(r, req.Operator), req.Unit, req.Qty); err != nil { httpx.Fail(w, 2403, err.Error()) return } @@ -93,6 +98,8 @@ func StationInspectionInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFu httpx.BadRequest(w, "请求体解析失败") return } + production.LogImpersonation(svcCtx, r, req.Operator, "/api/internal/station/inspection") + req.Operator = production.StationOp(r, req.Operator) msg, err := logic.New(svcCtx).CreateInspection(r.Context(), req, req.Operator) if err != nil { httpx.Fail(w, 2301, err.Error()) diff --git a/bj_power_mes/internal/logic/auth.go b/bj_power_mes/internal/logic/auth.go index 9cf9ad1..268ea7a 100644 --- a/bj_power_mes/internal/logic/auth.go +++ b/bj_power_mes/internal/logic/auth.go @@ -252,6 +252,31 @@ func (s *Service) StationLogin(ctx context.Context, req StationLoginReq) (Statio return resp, nil } +// StationRefreshTokenResp 工位终端滑动续签响应 +type StationRefreshTokenResp struct { + AccessToken string `json:"accessToken"` + ExpireAt int64 `json:"expireAt"` +} + +// StationRefreshToken 工位终端滑动续签:校验当前登录态 JWT 有效后,原样重签新 JWT(延长有效期)。 +// 终端任何人工触屏经前端 30 秒节流后调用,作业中令牌不再因固定有效期过期而被登出。 +// 工位终端与 MES 同密钥,claims(含 StationNo)原样保留。 +func (s *Service) StationRefreshToken(tokenStr string) (StationRefreshTokenResp, error) { + var resp StationRefreshTokenResp + claims, err := tokenx.Parse(s.ctx.Config.Auth.AccessSecret, tokenStr) + if err != nil || claims == nil { + return resp, errors.New("登录凭证无效或已过期,请重新登录") + } + expire := s.sessionExpire() + access, err := tokenx.Issue(s.ctx.Config.Auth.AccessSecret, time.Duration(expire)*time.Second, *claims) + if err != nil { + return resp, err + } + resp.AccessToken = access + resp.ExpireAt = time.Now().Add(time.Duration(expire) * time.Second).Unix() + return resp, nil +} + // StationChangePassword 工位终端修改自己的工位终端密码 func (s *Service) StationChangePassword(ctx context.Context, userId int, oldPwd, newPwd string) error { if userId <= 0 { diff --git a/bj_power_mes/internal/logic/inspection.go b/bj_power_mes/internal/logic/inspection.go index a4cd028..be44056 100644 --- a/bj_power_mes/internal/logic/inspection.go +++ b/bj_power_mes/internal/logic/inspection.go @@ -378,7 +378,9 @@ func (s *Service) finishedInspectionInbound(ctx context.Context, rec *ent.Inspec "完工检合格但成品回流WMS入库失败:工单不存在", map[string]any{"error": "work order not found"}) return "检验记录已保存;WMS 入库失败:工件所属工单不存在" } - qualityStatusForWMS := productStatus + // 质量状态落库值:合格类(已通过/部分通过)统一传「合格」;让步接收传「让步接收」。 + // 不再传「已通过/部分通过」等非库存枚举值(WMS 库存质量状态仅认 合格/不合格/让步接收/未检/待退)。 + qualityStatusForWMS := "合格" if concession { qualityStatusForWMS = "让步接收" } diff --git a/bj_power_mes/internal/logic/material.go b/bj_power_mes/internal/logic/material.go index 9d28a77..aaffa24 100644 --- a/bj_power_mes/internal/logic/material.go +++ b/bj_power_mes/internal/logic/material.go @@ -255,6 +255,9 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o if mr.Source == "REFILL" { obType = "refill" } + // C2 幂等键轮次:同一备料单每次 StockDeduct 调用用稳定唯一键, + // 网络超时重试时 WMS 按键复用已生成的出库单,杜绝重复扣减。 + round := 0 opts := wmsclient.StockDeductOpts{ Qty: need, Operator: operator, TargetDock: dock, OutboundType: obType, NeedAgv: mr.NeedAgv, OverReason: mr.OverReason, @@ -264,10 +267,12 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o if remain <= 0 { break } + round++ opts.SnList = []string{sn} opts.BatchNo = "" opts.Qty = 1 - no, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts) + opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, sn, round) + no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts) if e != nil { break } @@ -286,11 +291,13 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o if take <= 0 { continue } + round++ opts.SnList = nil opts.BatchNo = b.BatchNo opts.Qty = take opts.ZoneCode = b.ZoneCode - no, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts) + opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, b.BatchNo, round) + no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts) if e != nil { break } @@ -300,15 +307,47 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o } sent := need - remain if sent > 0 { - upd := s.ctx.EntClient.MaterialRequest.UpdateOneID(mr.ID).AddSentQty(float64(sent)) - if remain == 0 { - // 出库量已达标:备料完成,等 AGV 配送(WMS 下发后回写 DELIVERING) - upd = upd.SetStatus("LOCKED") - done++ + // C3 行锁 + 钳制:在事务内锁定该行后重读 sentQty 并重算,避免并发/重试重复累计; + // 以 reqQty 为上限钳制,杜绝超出 BOM 需求量的虚高计数(网络重试幂等复用场景下尤其关键)。 + applied := false + if tx, txErr := s.ctx.EntClient.Tx(ctx); txErr == nil { + locked, lErr := tx.MaterialRequest.Query(). + Where(materialrequest.ID(mr.ID)).ForUpdate().Only(ctx) + if lErr == nil { + newSent := locked.SentQty + float64(sent) + if newSent > locked.ReqQty { + newSent = locked.ReqQty // 钳制到需求量上限 + } + upd := tx.MaterialRequest.UpdateOneID(locked.ID).SetSentQty(newSent) + if remain == 0 { + // 出库量已达标:备料完成,等 AGV 配送(WMS 下发后回写 DELIVERING) + upd = upd.SetStatus("LOCKED") + } + if _, e := upd.Save(ctx); e == nil { + _ = tx.Commit() + applied = true + if remain == 0 { + done++ + } + s.ctx.EventLog.Write(ctx, "material.outbound.auto", mr.OrderNo, operator, "material_request", mr.RequestNo, + "备料自动出库", map[string]any{"materialCode": mr.MaterialCode, "qty": sent, "outboundNos": strings.Join(outboundNos, ",")}) + } + } + if !applied { + _ = tx.Rollback() + } } - if _, e := upd.Save(ctx); e == nil { - s.ctx.EventLog.Write(ctx, "material.outbound.auto", mr.OrderNo, operator, "material_request", mr.RequestNo, - "备料自动出库", map[string]any{"materialCode": mr.MaterialCode, "qty": sent, "outboundNos": strings.Join(outboundNos, ",")}) + if !applied { + // 行锁事务不可用时的兜底:直接原子累加(并发下仍有极小概率重复累计,由 WMS 幂等键兜底扣减) + upd := s.ctx.EntClient.MaterialRequest.UpdateOneID(mr.ID).AddSentQty(float64(sent)) + if remain == 0 { + upd = upd.SetStatus("LOCKED") + done++ + } + if _, e := upd.Save(ctx); e == nil { + s.ctx.EventLog.Write(ctx, "material.outbound.auto", mr.OrderNo, operator, "material_request", mr.RequestNo, + "备料自动出库", map[string]any{"materialCode": mr.MaterialCode, "qty": sent, "outboundNos": strings.Join(outboundNos, ",")}) + } } } if remain > 0 { diff --git a/bj_power_mes/internal/logic/seed.go b/bj_power_mes/internal/logic/seed.go index 3a73e2c..2ebc8ec 100644 --- a/bj_power_mes/internal/logic/seed.go +++ b/bj_power_mes/internal/logic/seed.go @@ -36,13 +36,15 @@ func (s *Service) Seed(ctx context.Context) error { "produce.processflow:upload", "produce.station:edit", "produce.station:add", "produce.station:delete", // 预警中心 / 附件中心(含归档清理按钮) "sys.alert", "sys.attachment", "sys.attachment:manage", - // 数量不符处理(上报在工位终端,处理在本页) - "produce.qty", "produce.qty:handle", - } + // 数量不符处理(上报在工位终端,处理在本页) + "produce.qty", "produce.qty:handle", + // 质量检验:过程检操作工自检(process);完工检(final)由质检员专属(见下方 dropCodes,补1 权限粒度拆分) + "produce.quality", "produce.quality:process", + } } else if r.code == "INSPECTOR" { codes = []string{"produce.trace", "produce.wip", "produce.performance", "sys.eventlog", "sys.inspect", "sys.inspect:checkin", "sys.inspect:point", "sys.inspect:process", - "sys.inspect:done", "sys.inspect:alarm", "sys.inspect:view", "sys.inspect:sign", "produce.quality", "produce.quality:edit"} + "sys.inspect:done", "sys.inspect:alarm", "sys.inspect:view", "sys.inspect:sign", "produce.quality", "produce.quality:process", "produce.quality:final"} } exist, err := s.ctx.EntClient.Role.Query().Where(role.Code(r.code)).First(ctx) if err != nil { @@ -50,8 +52,9 @@ func (s *Service) Seed(ctx context.Context) error { } else { merged := mergeCodes(exist.PermissionCodes, codes) if r.code == "OPERATOR" { - // 操作工不持质量检验录入/处置权限:完工检由质检员专属录入(P0-1 闭环) - merged = dropCodes(merged, "produce.quality", "produce.quality:edit") + // 操作工持「过程检」自检权限(produce.quality:process);不持「完工检」(produce.quality:final)。 + // 旧 produce.quality:edit 已拆为 process/final 两码(补1 权限粒度拆分),存量角色里的旧码一并摘除。 + merged = dropCodes(merged, "produce.quality:edit", "produce.quality:final") } _ = s.ctx.EntClient.Role.UpdateOneID(exist.ID).SetPermissionCodes(merged).Exec(ctx) } @@ -154,7 +157,8 @@ func (s *Service) Seed(ctx context.Context) error { {"sys.inspect:alarm", "巡检-异常上报", "BUTTON", "", "sys.inspect"}, {"sys.inspect:view", "巡检-记录查看", "BUTTON", "", "sys.inspect"}, {"sys.inspect:sign", "巡检-签字确认", "BUTTON", "", "sys.inspect"}, - {"produce.quality:edit", "质量检验-录入/处置", "BUTTON", "", "produce.quality"}, + {"produce.quality:process", "质量检验-过程检录入/处置", "BUTTON", "", "produce.quality"}, + {"produce.quality:final", "质量检验-完工检录入/处置", "BUTTON", "", "produce.quality"}, // 附件中心(对齐 WMS attachment:manage 口径):删除 + 归档清理 {"sys.attachment:manage", "附件-删除/归档清理", "BUTTON", "", "sys.attachment"}, {"sys.settings:edit", "基础设置-修改", "BUTTON", "", "sys.settings"}, @@ -191,6 +195,9 @@ func (s *Service) Seed(ctx context.Context) error { // 拧紧数据本体(/torque/report、/torque/records)与 torque_record 表保留,仅下线查询页与审核签字入口。 // 清掉存量角色里的旧码与旧菜单/按钮权限定义行(幂等)。 migrateLegacyTorque(ctx, s) + // 3.7 旧「质量检验-录入/处置」权限码 produce.quality:edit 已拆分为 process/final 两码(补1 权限粒度拆分): + // 摘掉存量角色里的旧码、删除旧权限定义行(幂等)。 + migrateLegacyQualityEdit(ctx, s) // 4. 初始化产线工位(内置只读主数据);工艺流程/工序步骤由用户在「工艺流程」页自建,不预置 seedStations(ctx, s) @@ -461,3 +468,32 @@ func migrateLegacyTorque(ctx context.Context, s *Service) { Where(permission.Code(code)).Exec(ctx) } } + +// migrateLegacyQualityEdit 清理已拆分的旧「质量检验-录入/处置」权限码 produce.quality:edit(幂等,可重复执行): +// 补1 权限粒度拆分后,该码被 produce.quality:process(过程检) / produce.quality:final(完工检) 取代。 +// 从存量角色的 permissionCodes 摘除旧码并删除其权限定义行,避免菜单树/接口残留失效入口。 +func migrateLegacyQualityEdit(ctx context.Context, s *Service) { + deadCodes := map[string]bool{ + "produce.quality:edit": true, + } + roleList, _ := s.ctx.EntClient.Role.Query().All(ctx) + for _, rl := range roleList { + kept := make([]string, 0, len(rl.PermissionCodes)) + changed := false + for _, c := range rl.PermissionCodes { + if deadCodes[c] { + changed = true + continue + } + kept = append(kept, c) + } + if changed { + _ = s.ctx.EntClient.Role.UpdateOneID(rl.ID). + SetPermissionCodes(mergeCodes(kept, nil)).Exec(ctx) + } + } + for code := range deadCodes { + _, _ = s.ctx.EntClient.Permission.Delete(). + Where(permission.Code(code)).Exec(ctx) + } +} diff --git a/bj_power_mes/internal/logic/sign.go b/bj_power_mes/internal/logic/sign.go index 40c5c62..d884f2d 100644 --- a/bj_power_mes/internal/logic/sign.go +++ b/bj_power_mes/internal/logic/sign.go @@ -96,11 +96,26 @@ func (s *Service) InspectorSign(ctx context.Context, req InspectorSignReq, opera SetSignedBy(operator).SetRound(round). SetSource("inspect").SetRemark(req.Remark).Save(ctx) if err != nil { + if isUniqueSignViolation(err) { + // 并发签字竞态:唯一索引(sn,stationNo,stepId,signRole,round)冲突 + return errors.New("该步骤已签字,请勿重复提交") + } return err } return nil } +// isUniqueSignViolation 判定是否为签字唯一索引冲突(并发签字竞态) +func isUniqueSignViolation(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "duplicate key") || + strings.Contains(msg, "violates unique constraint") || + strings.Contains(msg, "step_sign_record") +} + // PendingSignFilter 待检验员签字查询过滤。 type PendingSignFilter struct { Sn string `json:"sn"` diff --git a/bj_power_mes/internal/logic/torque.go b/bj_power_mes/internal/logic/torque.go index 5af31a5..99926d9 100644 --- a/bj_power_mes/internal/logic/torque.go +++ b/bj_power_mes/internal/logic/torque.go @@ -29,8 +29,9 @@ type TorqueReq struct { Time time.Time `json:"time"` } -// ReportTorque 接收拧紧数据(工位终端/内部接口上报),入库并做扭矩 RANGE 判定写 step_data -func (s *Service) ReportTorque(ctx context.Context, req TorqueReq, operator string) error { +// ReportTorque 接收拧紧数据(工位终端/内部接口上报),入库并做扭矩 RANGE 判定写 step_data。 +// operatorId:落库操作人用户ID,由 MES 从当前登录态 JWT 解析,即「本次发送所用的登录人」。 +func (s *Service) ReportTorque(ctx context.Context, req TorqueReq, operator string, operatorId int) error { if req.Sn == "" { return errors.New("sn 不能为空") } @@ -51,7 +52,7 @@ func (s *Service) ReportTorque(ctx context.Context, req TorqueReq, operator stri _, err := s.ctx.EntClient.TorqueRecord.Create(). SetWorkOrderNo(workOrderNo).SetSn(req.Sn).SetScrewNo(req.ScrewNo). SetStrain(req.Strain).SetTorque(req.Strain).SetAngle(req.Angle). - SetResult(result).SetOperator(req.Operator).SetStationNo(req.StationNo). + SetResult(result).SetOperator(operator).SetOperatorId(operatorId).SetStationNo(req.StationNo). SetTime(req.Time).Save(ctx) if err != nil { return err diff --git a/bj_power_mes/internal/logic/workpiece.go b/bj_power_mes/internal/logic/workpiece.go index 40a83d1..3a039d2 100644 --- a/bj_power_mes/internal/logic/workpiece.go +++ b/bj_power_mes/internal/logic/workpiece.go @@ -219,6 +219,7 @@ type ReportProcessReq struct { Sn string `json:"sn"` FlowId int `json:"flowId"` // 报工工艺(缺省回退工位当前绑定的工艺) StationNo int `json:"stationNo"` + Operator string `json:"operator"` // 操作工(工位终端登录人注入;内部接口无 JWT 时作为操作人来源,杜绝「system」伪造留痕) Steps []StepDataReq `json:"steps"` // 签字确认(需求B):needOperatorSign 步骤须带操作工签字(签字确认弹框采集),服务端强校验并落库 Signs []StepSignInput `json:"signs"` @@ -248,7 +249,7 @@ func parseClientTime(s string) (time.Time, error) { // 绑料是"落到工艺"的强约束:工艺物料清单(flow_material)中要求装配的物料必须绑齐, // 电气件按单台用量逐颗SN、结构件至少一个批次号;缺料直接拒绝报工并返回缺料清单。 // 顺序校验(工单工艺组合为唯一路线源头):报工工位必须在组合中、工艺匹配,且不可倒序(可跳过未选工位)。 -func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, operator string) error { +func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, operator string, operatorId int) error { if req.Sn == "" || req.StationNo <= 0 { return errors.New("sn 与 stationNo 必填") } @@ -352,7 +353,7 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera SetSn(req.Sn).SetFlowId(flowId). SetStationNo(itoa(req.StationNo)).SetOrderNo(wp.OrderNo). SetProcessName(s.flowNameById(ctx, flowId)). - SetStatus("DONE").SetOperator(operator).SetResult("OK"). + SetStatus("DONE").SetOperator(operator).SetOperatorId(operatorId).SetResult("OK"). SetStartedAt(startedAt).SetEndedAt(endedAt).SetDurationSec(durationSec).Save(ctx) if err != nil { return err diff --git a/bj_power_mes/internal/svc/service_context.go b/bj_power_mes/internal/svc/service_context.go index f903521..55cd047 100644 --- a/bj_power_mes/internal/svc/service_context.go +++ b/bj_power_mes/internal/svc/service_context.go @@ -1,6 +1,8 @@ package svc import ( + "strings" + "bj_power_mes/ent" "bj_power_mes/internal/config" "bj_power_mes/internal/db" @@ -24,6 +26,10 @@ type ServiceContext struct { } func NewServiceContext(c config.Config) *ServiceContext { + // 启动期密钥校验:编译期默认密钥已移除,yaml 缺失/为空则直接 panic, + // 杜绝「空 token 绕过内部接口鉴权」的攻击面(安全审计 #6/#13)。 + validateMesSecrets(c) + entClient, _ := db.MustNewDB(c.Database) redisClient := redis.New(c.Redis.Host) @@ -40,3 +46,23 @@ func NewServiceContext(c config.Config) *ServiceContext { Wms: wmsclient.New(c.Wms.BaseURL, c.Wms.Token), } } + +// validateMesSecrets 启动期校验必要密钥非空(编译期默认密钥已移除)。 +func validateMesSecrets(c config.Config) { + missing := make([]string, 0, 4) + if strings.TrimSpace(c.Auth.AccessSecret) == "" { + missing = append(missing, "Auth.AccessSecret") + } + if strings.TrimSpace(c.Internal.Token) == "" { + missing = append(missing, "Internal.Token") + } + if strings.TrimSpace(c.Cli.AdminPassword) == "" { + missing = append(missing, "Cli.AdminPassword") + } + if strings.TrimSpace(c.Wms.Token) == "" { + missing = append(missing, "Wms.Token") + } + if len(missing) > 0 { + panic("配置缺失必要密钥(已禁止编译期默认密钥,必须在 etc/*.yaml 中显式配置):" + strings.Join(missing, ", ")) + } +} diff --git a/bj_power_mes/internal/wmsclient/client.go b/bj_power_mes/internal/wmsclient/client.go index 16eb368..dcb8915 100644 --- a/bj_power_mes/internal/wmsclient/client.go +++ b/bj_power_mes/internal/wmsclient/client.go @@ -558,12 +558,16 @@ type StockDeductOpts struct { OutboundType string // workorder(备料,默认) / refill(补料) NeedAgv bool // 是否叫 AGV 配送到接驳台 OverReason string // 超出 BOM 需求时的超领原因(损耗/报废/返修/其他);空=超领将被 WMS 拦截 + // IdempotencyKey 幂等键(安全审计 C2):同一键重复提交 WMS 返回首次结果,避免网络超时重试导致重复扣减 + IdempotencyKey string } // StockDeduct 调 WMS /api/internal/stock/deduct 执行一笔备料出库(批次或 SN 二选一)。 -// 返回该笔出库单号与工单台账状态(等于「领料完结」表示该物料已领完)。 -// 失败返回 err(含 WMS 业务错误文案,由调用方降级为保持待备料并预警)。 -func (c *Client) StockDeduct(ctx context.Context, orderNo, materialCode string, o StockDeductOpts) (string, string, error) { +// 返回该笔出库单号、工单台账状态(等于「领料完结」表示该物料已领完)、是否幂等复用(replayed)。 +// replayed=true 表示 WMS 已存在相同幂等键的出库单、本次未实际扣减(网络超时重试场景), +// 调用方据此不要重复累加 sentQty,避免双计。失败返回 err(含 WMS 业务错误文案, +// 由调用方降级为保持待备料并预警)。 +func (c *Client) StockDeduct(ctx context.Context, orderNo, materialCode string, o StockDeductOpts) (string, string, bool, error) { payload := map[string]any{ "orderNo": orderNo, "materialCode": materialCode, "qty": o.Qty, "operator": o.Operator, @@ -584,19 +588,22 @@ func (c *Client) StockDeduct(ctx context.Context, orderNo, materialCode string, if o.OverReason != "" { payload["overReason"] = o.OverReason } + if o.IdempotencyKey != "" { + payload["idempotencyKey"] = o.IdempotencyKey + } b, err := json.Marshal(payload) if err != nil { - return "", "", err + return "", "", false, err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/stock/deduct", bytes.NewReader(b)) if err != nil { - return "", "", err + return "", "", false, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("X-API-TOKEN", c.token) resp, err := c.hc.Do(req) if err != nil { - return "", "", err + return "", "", false, err } defer resp.Body.Close() var body struct { @@ -605,15 +612,16 @@ func (c *Client) StockDeduct(ctx context.Context, orderNo, materialCode string, Data struct { OutboundNo string `json:"outboundNo"` Status string `json:"status"` + Replayed bool `json:"idempotent"` } `json:"data"` } if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { - return "", "", err + return "", "", false, err } if resp.StatusCode >= 300 || body.Code != 0 { - return "", "", errors.New(body.Message) + return "", "", false, errors.New(body.Message) } - return body.Data.OutboundNo, body.Data.Status, nil + return body.Data.OutboundNo, body.Data.Status, body.Data.Replayed, nil } // LedgerProgressRow 工单台账配送进度行(WMS 侧四段量)。 diff --git a/bj_power_mes/public/index.html b/bj_power_mes/public/index.html index 61999f1..1701c5a 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/torque_record.go b/bj_power_mes/schema/torque_record.go index 026e984..f4bd860 100644 --- a/bj_power_mes/schema/torque_record.go +++ b/bj_power_mes/schema/torque_record.go @@ -31,6 +31,9 @@ func (TorqueRecord) Fields() []ent.Field { // OK / NG field.String("result").Default("OK").MaxLen(10), field.String("operator").Default("").MaxLen(64).Comment("操作人"), + // 落库操作人用户ID:由 MES 从当前登录态 JWT 解析,即「本次发送所用的登录人」。 + // 0=未采集(来源:MES 前端虚拟工位/PLC 等无工位登录态路径)。 + field.Int("operatorId").Default(0).Comment("操作人用户ID(0=未采集:虚拟工位/PLC路径或历史数据)"), field.String("stationNo").Default("").MaxLen(32).Comment("工位"), field.Time("time").Default(time.Now).Comment("采集时间"), field.Time("createdAt").Default(time.Now).Immutable(), diff --git a/bj_power_mes/schema/workpiece_process.go b/bj_power_mes/schema/workpiece_process.go index 95dfbac..506deb0 100644 --- a/bj_power_mes/schema/workpiece_process.go +++ b/bj_power_mes/schema/workpiece_process.go @@ -31,6 +31,9 @@ func (WorkpieceProcess) Fields() []ent.Field { // PENDING / DOING / DONE / NG / REPAIRED field.String("status").Default("DONE").MaxLen(20), field.String("operator").Default("").MaxLen(64), + // 落库操作人用户ID:由 MES 从当前登录态 JWT 解析,即「本次发送所用的登录人」。 + // 0=未采集(来源:MES 前端虚拟工位/PLC 等无工位登录态路径)。 + field.Int("operatorId").Default(0).Comment("操作人用户ID(0=未采集:虚拟工位/PLC路径或历史数据)"), field.String("result").Default("OK").MaxLen(10).Comment("总判定 OK/NG"), field.Time("startedAt").Optional().Nillable(), field.Time("endedAt").Optional().Nillable(), diff --git a/bj_power_wms/internal/config/config.go b/bj_power_wms/internal/config/config.go index 8edf526..24de9e3 100644 --- a/bj_power_wms/internal/config/config.go +++ b/bj_power_wms/internal/config/config.go @@ -17,20 +17,23 @@ type PostgresConfig struct { } type AuthConfig struct { - AccessSecret string `json:",default=Hardman_2026"` + // AccessSecret 必须由 yaml 提供,禁止编译期默认密钥(防默认密钥被绕过) + AccessSecret string `json:"AccessSecret"` // AccessExpire 会话闲置窗口(秒):滑动续签下 = 距最后一次请求多久后需要重新登录 AccessExpire int64 `json:",default=3600"` } // InternalConfig 项目间内部 API 配置 type InternalConfig struct { - Token string `json:",default=Hardman_2026"` // 写死的项目间 API token(X-API-TOKEN) + // Token 必须由 yaml 提供,禁止编译期默认密钥(防空 token 绕过内部接口鉴权) + Token string `json:"Token"` // 写死的项目间 API token(X-API-TOKEN) } // MesConfig 下游 MES 服务对接(备料/台账需取工单与 BOM) type MesConfig struct { BaseURL string `json:",default=http://127.0.0.1:8888"` // MES 服务地址 - Token string `json:",default=Hardman_2026"` // 调 MES 内部接口的 X-API-TOKEN + // Token 必须由 yaml 提供,禁止编译期默认密钥 + Token string `json:"Token"` // 调 MES 内部接口的 X-API-TOKEN } // AgvConfig 海康 AGV(RCS-2000) 调度系统对接 @@ -52,7 +55,8 @@ type WebConfig struct { // CliConfig 命令行敏感操作门禁密码(migrate/reset-all/seed 需输入,独立于后台登录账号密码)。 // 与 MES 对齐:DDL/删库等高危操作一律显式触发 + 密码校验,绝不随服务启动自动执行。 type CliConfig struct { - AdminPassword string `json:",default=Hardman_2026"` + // AdminPassword 必须由 yaml 提供,禁止编译期默认密钥(migrate/reset-all/seed 高危门禁) + AdminPassword string `json:"AdminPassword"` } // AttachmentConfig 附件存储 / 归档 / 磁盘监控配置(etc/*.yaml 的 Attachment 段)。 diff --git a/bj_power_wms/internal/handler/attachment.go b/bj_power_wms/internal/handler/attachment.go index c99e2e4..909920b 100644 --- a/bj_power_wms/internal/handler/attachment.go +++ b/bj_power_wms/internal/handler/attachment.go @@ -9,7 +9,6 @@ import ( "net/url" "os" "path/filepath" - "strconv" "strings" "time" @@ -248,7 +247,8 @@ func attachmentView(ctx *svc.ServiceContext, rec *ent.Attachment) *attachmentVie ID: int64(rec.ID), BizType: rec.BizType, BizID: rec.BizID, FileType: rec.FileType, FileName: rec.FileName, FileSize: rec.FileSize, FileExt: rec.FileExt, MimeType: rec.MimeType, UploadedBy: rec.UploadedBy, CreatedAt: rec.CreatedAt, Archived: rec.Archived, Deleted: rec.Deleted, - URL: "/uploads/" + strconv.FormatInt(int64(rec.ID), 10), + // 公开预览 URL 用磁盘 UUID 文件名(不可枚举),杜绝顺序 ID 越权遍历(安全审计 #8) + URL: "/uploads/" + filepath.Base(rec.FilePath), } } @@ -384,39 +384,29 @@ func deleteAttachmentHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } -// serveUploadFileHandler 附件文件服务(按 id 提供,免鉴权便于 /新窗口预览;支持 Range 断点续传)。 -// GET /uploads/:name(name = 附件 id,或历史扁平文件名兜底) +// serveUploadFileHandler 附件文件服务(按 UUID 存储名提供,免鉴权便于 /新窗口预览;支持 Range 断点续传)。 +// GET /uploads/:name(name = 磁盘 UUID 文件名,如 .pdf)。顺序 ID 已被移除,杜绝越权遍历(安全审计 #8)。 func serveUploadFileHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + // 仅接受 UUID 存储名(库内 FilePath 末尾一段),顺序 ID 不再作为访问入口 name := filepath.Base(r.URL.Path) if name == "" || name == "." || name == "/" { http.NotFound(w, r) return } - root := attRoot(ctx) - var absPath string - var fileName string - if id, e := strconv.ParseInt(name, 10, 64); e == nil && id > 0 { - rec, err := ctx.EntClient.Attachment.Get(ctx0(), int(id)) - if err != nil { - http.NotFound(w, r) - return - } - p, ok := safeAbsPath(root, rec.FilePath) - if !ok { - http.NotFound(w, r) - return - } - absPath, fileName = p, rec.FileName - } else { - // 历史扁平文件(uuid.ext)兜底 - p, ok := safeAbsPath(root, name) - if !ok { - http.NotFound(w, r) - return - } - absPath, fileName = p, name + rec, err := ctx.EntClient.Attachment.Query(). + Where(attachment.FilePathHasSuffix("/" + name), attachment.DeletedEQ(false)).Only(ctx0()) + if err != nil || rec == nil { + http.NotFound(w, r) + return } + root := attRoot(ctx) + p, ok := safeAbsPath(root, rec.FilePath) + if !ok { + http.NotFound(w, r) + return + } + absPath, fileName := p, rec.FileName if _, err := os.Stat(absPath); err != nil { http.NotFound(w, r) return diff --git a/bj_power_wms/internal/handler/finished_inbound.go b/bj_power_wms/internal/handler/finished_inbound.go index 6c68eb2..5705b56 100644 --- a/bj_power_wms/internal/handler/finished_inbound.go +++ b/bj_power_wms/internal/handler/finished_inbound.go @@ -32,19 +32,9 @@ func createFinishedInventory(ctx *svc.ServiceContext, req *finishedInboundReques if req.Sn == "" || req.ProductCode == "" { return nil, http.StatusBadRequest, errors.New("sn 与 productCode 必填") } - quality := req.QualityStatus - if quality == "" { - // 未显式传质量状态时按产品状态派生(方案A契约:已通过→合格 / 部分通过→合格 / 返修→不合格), - // 显式传入的值仍尊重不覆盖。 - switch req.ProductStatus { - case "部分通过": - quality = QStatusPass - case "返修": - quality = "不合格" - default: - quality = QStatusPass - } - } + // 质量状态归一:合法枚举值原样尊重;空值或非枚举值(如 MES 误传「已通过/部分通过」)按产品状态派生兜底, + // 避免脏值落库(库存质量状态仅认 合格/不合格/让步接收/未检/待退)。 + quality := normalizeQualityStatus(req.QualityStatus, req.ProductStatus) // SN 全局防重(同品类成品 + 半成品 + 序列号件 SN 都不允许撞号) dup, err := ctx.EntClient.Inventory.Query(). @@ -113,6 +103,9 @@ func createFinishedInventory(ctx *svc.ServiceContext, req *finishedInboundReques SetRemark(remark). Save(ctx0()) if err != nil { + if isUniqueViolation(err) { + return nil, http.StatusConflict, errors.New("成品 SN 已存在库存: " + req.Sn) + } return nil, http.StatusInternalServerError, err } @@ -126,6 +119,35 @@ func createFinishedInventory(ctx *svc.ServiceContext, req *finishedInboundReques return rec, 0, nil } +// normalizeQualityStatus 归一成品入库质量状态:合法枚举值原样尊重;空值或非库存枚举值 +// (如 MES 误传「已通过/部分通过」等业务态)按产品状态派生兜底,防止脏值落库。 +func normalizeQualityStatus(quality, productStatus string) string { + switch quality { + case QStatusPending, QStatusPass, QStatusFail, QStatusReturn, QStatusConcession: + return quality + } + switch productStatus { + case "部分通过", "已通过": + return QStatusPass + case "返修": + return QStatusFail + default: + return QStatusPass + } +} + +// isUniqueViolation 判定 DB 错误是否唯一约束冲突(部分唯一索引 ux_inventories_sn_code 等)。 +// 用错误文本匹配,避免强依赖 lib/pq(当前为 indirect 依赖)。 +func isUniqueViolation(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "ux_inventories_sn_code") || + strings.Contains(msg, "duplicate key") || + strings.Contains(msg, "violates unique constraint") +} + // manualFinishedInboundHandler POST /api/finished/inbound 手工成品入库(登录态,权限 wms.finished:edit)。 // 与 MES 完工回流共享创建逻辑(createFinishedInventory);差异仅在必填校验: // SN/产品编码/产品状态/记录员必填,记录日期默认今天;成功返回库存行。 diff --git a/bj_power_wms/internal/handler/inbound.go b/bj_power_wms/internal/handler/inbound.go index 9f55b59..177a625 100644 --- a/bj_power_wms/internal/handler/inbound.go +++ b/bj_power_wms/internal/handler/inbound.go @@ -414,6 +414,11 @@ func createInboundHandler(ctx *svc.ServiceContext) http.HandlerFunc { SetInboundNo(inboundNo). SetNillableProductWorkNo(strPtr(req.ProductWorkNo)). Save(ctx0()); err != nil { + // 并发插入唯一冲突(部分唯一索引 ux_inventories_sn_code)也映射 409,与预检口径一致 + if isUniqueViolation(err) { + fail(w, http.StatusConflict, "SN 已存在: "+sn) + return + } fail(w, http.StatusInternalServerError, "创建 SN 库存行失败: "+err.Error()) return } diff --git a/bj_power_wms/internal/handler/outbound.go b/bj_power_wms/internal/handler/outbound.go index 6d16c91..4801dec 100644 --- a/bj_power_wms/internal/handler/outbound.go +++ b/bj_power_wms/internal/handler/outbound.go @@ -45,6 +45,10 @@ type deductStockRequest struct { // OverReason 超 BOM 领用原因(损耗/报废/返修/其他)。 // 超领不硬卡:net_out > 需求时,填了原因即放行并留痕;未填仍 409 拦截。 OverReason string `json:"overReason"` + // IdempotencyKey 幂等键(安全审计 C2):调用方(如 MES 备料自动出库网络超时重试) + // 传入稳定唯一键,同一键重复提交直接复用已生成的出库单,避免重复扣减库存。 + // 留空则按 OutboundNo 规则(手填校验唯一 / 留空自动生成)处理。 + IdempotencyKey string `json:"idempotencyKey"` } // deductStockHandler 出库扣减 @@ -107,12 +111,30 @@ func deductStockHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } - outboundNo := strings.TrimSpace(req.OutboundNo) + // C2 幂等键(安全审计):调用方传入幂等键(如 MES 自动出库超时重试), + // 同一键重复提交直接复用已生成的出库单,避免重复扣减库存。 + outboundNo := strings.TrimSpace(req.IdempotencyKey) if outboundNo != "" { - if err := validateUniqueNo(ctx, "OB", outboundNo); err != nil { + if exist, e := ctx.EntClient.OutboundOrder.Query(). + Where(outboundorder.OutboundNoEQ(outboundNo)).Only(ctx0()); e == nil && exist != nil { + // 幂等复用:该出库请求此前已处理,直接返回既有单据与状态,不再扣减。 + ok(w, map[string]any{ + "outboundNo": outboundNo, + "qty": exist.Quantity, + "orderNo": req.OrderNo, + "outboundType": exist.OutboundType, + "status": exist.Status, + "idempotent": true, + "message": "幂等复用:该出库请求此前已处理", + }) + return + } + } else if obNo := strings.TrimSpace(req.OutboundNo); obNo != "" { + if err := validateUniqueNo(ctx, "OB", obNo); err != nil { fail(w, http.StatusBadRequest, err.Error()) return } + outboundNo = obNo } else { no, err := nextDailyNo(ctx, "OB") if err != nil { @@ -167,6 +189,22 @@ func deductStockHandler(ctx *svc.ServiceContext) http.HandlerFunc { SetNillableRemark(strPtr(req.Remark)). Save(ctx0()) if err != nil { + // 并发幂等:另一条相同幂等键/单号的请求已抢先落库,复用其单号返回。 + if isDuplicateOutboundNo(err) { + if exist, e2 := ctx.EntClient.OutboundOrder.Query(). + Where(outboundorder.OutboundNoEQ(outboundNo)).Only(ctx0()); e2 == nil && exist != nil { + ok(w, map[string]any{ + "outboundNo": outboundNo, + "qty": exist.Quantity, + "orderNo": req.OrderNo, + "outboundType": exist.OutboundType, + "status": exist.Status, + "idempotent": true, + "message": "幂等复用:该出库请求此前已处理", + }) + return + } + } fail(w, http.StatusInternalServerError, "创建出库单失败: "+err.Error()) return } @@ -299,8 +337,10 @@ func deductStockHandler(ctx *svc.ServiceContext) http.HandlerFunc { status = "进行中" } // 台账 completed_at = 最后一笔领料完结出库时间(客户诉求 问题记录 L238-240:台账增加完成时间筛选) + // 台账 out_qty 用原子自增(AddOutQty)替代「读改写绝对赋值」,消除并发丢失更新 + //(C1:原 newOutQty = ledgerNow.OutQty + actualQty 再 SetOutQty 在并发下会少计)。 ledgerUpd := tx.OrderMaterialLedger.UpdateOneID(ledgerNow.ID). - SetOutQty(newOutQty). + AddOutQty(actualQty). SetStatus(status) if status == "领料完结" && ledgerNow.Status != "领料完结" { ledgerUpd.SetCompletedAt(time.Now().Unix()) @@ -822,6 +862,18 @@ func min(a, b int) int { return b } +// isDuplicateOutboundNo 判定 DB 错误是否唯一约束冲突(出库单号 ux_outbound_orders_outbound_no)。 +// 用于幂等键并发落库时把 500 转为幂等复用,避免重复扣减。 +func isDuplicateOutboundNo(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "ux_outbound_orders_outbound_no") || + strings.Contains(msg, "duplicate key") || + strings.Contains(msg, "violates unique constraint") +} + // locationText 库位展示串。入库/出库/库存统一口径:`Z02 A架/3层/12位`,无内容返回空串。 // outboundLocationFallback 出库四级库位兜底(客户诉求 一.9「出库相同」)。 // diff --git a/bj_power_wms/internal/handler/return_order.go b/bj_power_wms/internal/handler/return_order.go index d6141ec..94f9c70 100644 --- a/bj_power_wms/internal/handler/return_order.go +++ b/bj_power_wms/internal/handler/return_order.go @@ -342,8 +342,9 @@ func confirmReturnOrderHandler(ctx *svc.ServiceContext) http.HandlerFunc { if st == "领料完结" && (led.OutQty-newReturned) < led.TotalQty { st = "进行中" } + // returned_qty 用原子自增(AddReturnedQty)替代「读改写绝对赋值」(C1:消除并发丢失更新) if _, uerr := tx.OrderMaterialLedger.UpdateOneID(led.ID). - SetReturnedQty(newReturned).SetStatus(st).Save(ctx0()); uerr != nil { + AddReturnedQty(ro.Qty).SetStatus(st).Save(ctx0()); uerr != nil { fail(w, http.StatusInternalServerError, "回写台账退回量失败: "+uerr.Error()) return } diff --git a/bj_power_wms/internal/svc/service_context.go b/bj_power_wms/internal/svc/service_context.go index 68b36ce..b7ae5bb 100644 --- a/bj_power_wms/internal/svc/service_context.go +++ b/bj_power_wms/internal/svc/service_context.go @@ -1,6 +1,8 @@ package svc import ( + "strings" + "bj_power_wms/ent" "bj_power_wms/internal/agv" "bj_power_wms/internal/config" @@ -18,6 +20,10 @@ type ServiceContext struct { } func NewServiceContext(c config.Config) *ServiceContext { + // 启动期密钥校验:编译期默认密钥已移除,yaml 缺失/为空则直接 panic, + // 杜绝「空 token 绕过内部接口鉴权」的攻击面(安全审计 #6/#13)。 + validateWmsSecrets(c) + conf := db.DatabaseConf{ Host: c.Postgres.Host, Port: c.Postgres.Port, @@ -51,3 +57,23 @@ func NewServiceContext(c config.Config) *ServiceContext { Mes: mesclient.New(c.Mes.BaseURL, c.Mes.Token), } } + +// validateWmsSecrets 启动期校验必要密钥非空(编译期默认密钥已移除)。 +func validateWmsSecrets(c config.Config) { + missing := make([]string, 0, 4) + if strings.TrimSpace(c.Auth.AccessSecret) == "" { + missing = append(missing, "Auth.AccessSecret") + } + if strings.TrimSpace(c.Internal.Token) == "" { + missing = append(missing, "Internal.Token") + } + if strings.TrimSpace(c.Mes.Token) == "" { + missing = append(missing, "Mes.Token") + } + if strings.TrimSpace(c.Cli.AdminPassword) == "" { + missing = append(missing, "Cli.AdminPassword") + } + if len(missing) > 0 { + panic("配置缺失必要密钥(已禁止编译期默认密钥,必须在 etc/*.yaml 中显式配置):" + strings.Join(missing, ", ")) + } +} diff --git a/bj_power_workstation/frontend/src/api/index.js b/bj_power_workstation/frontend/src/api/index.js index 789df18..ac170aa 100644 --- a/bj_power_workstation/frontend/src/api/index.js +++ b/bj_power_workstation/frontend/src/api/index.js @@ -3,6 +3,12 @@ import request from '../utils/request' // 登录 export const login = (data) => request.post('/api/auth/login', data) +// 滑动续签心跳(本地空闲计时):任何人工触屏触发,立即刷新服务端登录态空闲计时 +export const touchSession = () => request.post('/api/auth/touch') + +// 滑动续签 Bearer(前端节流 30 秒一次):用当前登录态换新 JWT,作业中令牌不过期 +export const refreshToken = () => request.post('/api/auth/refresh-token') + // 工位配置(固定工位号) export const getConfig = () => request.get('/api/config') diff --git a/bj_power_workstation/frontend/src/main.js b/bj_power_workstation/frontend/src/main.js index 5cc226e..c5dd330 100644 --- a/bj_power_workstation/frontend/src/main.js +++ b/bj_power_workstation/frontend/src/main.js @@ -3,5 +3,14 @@ import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import App from './App.vue' import router from './router' +import { touch } from './store/station' + +// 滑动续签全局监听(修订需求):任何人工触屏行为(点击/触摸/键盘/滚轮/滚动)都触发续签。 +// 捕获阶段监听,弹窗/遮罩/任何组件拦截不了;程序化行为(轮询、WS 保活、定时刷新) +// 不派发真实用户事件,不算触发。具体节流在 store.touch() 内部(本地立即 + Bearer 30 秒)。 +const ACTIVITY_EVENTS = ['click', 'touchstart', 'keydown', 'wheel', 'scroll'] +for (const evt of ACTIVITY_EVENTS) { + window.addEventListener(evt, () => touch(), { capture: true, passive: true }) +} createApp(App).use(router).use(ElementPlus).mount('#app') \ No newline at end of file diff --git a/bj_power_workstation/frontend/src/store/station.js b/bj_power_workstation/frontend/src/store/station.js index cc427c9..a689931 100644 --- a/bj_power_workstation/frontend/src/store/station.js +++ b/bj_power_workstation/frontend/src/store/station.js @@ -13,9 +13,11 @@ import { getWip, occupyLinePoint, pauseStation, - submitTorque + refreshToken, + submitTorque, + touchSession } from '../api' -import { getUser } from '../utils/request' +import { getUser, getToken } from '../utils/request' export const state = reactive({ stationNo: 0, @@ -374,6 +376,22 @@ export async function moveOut() { export const operatorName = () => user.name || user.username || '' +// ---------- 滑动续签(修订需求:触发点 = 任何人工触屏行为) ---------- +// 双层机制: +// ① 本地空闲计时:每次触摸立即调用 /api/auth/touch(零成本本地写 last_active_at),防作业中误登出; +// ② MES Bearer 续签:节流 30 秒一次 /api/auth/refresh-token,作业中令牌不因固定有效期过期。 +// 未登录(无自身 JWT,如登录页)时静默跳过;系统后台行为(轮询/WS 保活)不会派发人工事件, +// 不会进入本函数,不算触发。 +let lastBearerRefreshAt = 0 +export function touch() { + if (!getToken()) return + touchSession().catch(() => { /* 本地心跳失败静默,下一触摸重试 */ }) + const now = Date.now() + if (now - lastBearerRefreshAt < 30_000) return + lastBearerRefreshAt = now + refreshToken().catch(() => { /* MES 不可达时静默,下个节流窗口重试 */ }) +} + // flowId 随任务到达后再触发一次绑定加载(上线位/首次拉到任务时 flowId 才有值) watch(flowId, (v) => { if (v > 0 && state.currentSn && !state.bindPanel) loadBind() diff --git a/bj_power_workstation/frontend/src/views/Login.vue b/bj_power_workstation/frontend/src/views/Login.vue index 043ba74..078fbc2 100644 --- a/bj_power_workstation/frontend/src/views/Login.vue +++ b/bj_power_workstation/frontend/src/views/Login.vue @@ -43,7 +43,7 @@ import { onMounted, ref } from 'vue' import { useRouter } from 'vue-router' import { ElMessage } from 'element-plus' -import { getConfig, login } from '../api' +import { getConfig, getSyncStats, login } from '../api' import { setAuth } from '../utils/request' const router = useRouter() @@ -83,6 +83,20 @@ async function submit() { setAuth(data.accessToken, data.user) ElMessage.success('登录成功') router.push('/main') + // 仅提示本人上次发送失败、仍留在本机的数据条数(不自动打开任何页面); + // 他人登录时后端按操作人隔离,不会返回、也不会代发这些数据。 + try { + const stats = await getSyncStats() + const n = Number(stats?.pendingTotal || 0) + if (n > 0) { + ElMessage({ + type: 'info', + message: `您上次有 ${n} 条报工数据发送失败,仍保留在本机;留意顶部「待同步」即可,系统会自动重发`, + duration: 8000, + showClose: true + }) + } + } catch { /* 统计不可达时静默,不阻断登录 */ } } catch (e) { // 错误提示已由 request 封装统一弹出 } finally { diff --git a/bj_power_workstation/frontend/src/views/Main.vue b/bj_power_workstation/frontend/src/views/Main.vue index daac189..239d208 100644 --- a/bj_power_workstation/frontend/src/views/Main.vue +++ b/bj_power_workstation/frontend/src/views/Main.vue @@ -166,10 +166,23 @@ async function manualFlush() { } catch (e) { /* 统一错误提示 */ } } -function logout() { - stationLogout({ username: user?.username || '', stationNo: stationNo.value || 0 }).catch(() => {}) +async function logout() { + // 退出前先本地退出(服务端登出失败也照样退),再按响应提醒本人未发送成功的条数 + let data = null + try { + data = await stationLogout({ username: user?.username || '', stationNo: stationNo.value || 0 }) + } catch { /* MES 不可达也继续本地退出 */ } clearAuth() router.push('/login') + const n = Number(data?.pendingTotal || 0) + if (n > 0) { + ElMessage({ + type: 'warning', + message: `您有 ${n} 条报工数据发送失败,仍保留在本机(只有您本人登录可见/可发送),下次登录后请留意「待同步」`, + duration: 8000, + showClose: true + }) + } } onMounted(async () => { diff --git a/bj_power_workstation/internal/config/config.go b/bj_power_workstation/internal/config/config.go index cad301d..34ba2af 100644 --- a/bj_power_workstation/internal/config/config.go +++ b/bj_power_workstation/internal/config/config.go @@ -31,6 +31,10 @@ type SqliteConfig struct { type StationConfig struct { StationNo int `json:",default=1"` // 固定工位号,启动时校验范围 Dock string `json:",default=R1"` // 固定本工位接驳台(AGV 点位),叫料自动送达;工人不可选,仅运维改配置后重启生效 + // 核实4:空闲无操作自动登出阈值(秒)。超时清登录态并失效 Bearer 凭证, + // 强制下一班/换班操作工重新登录,避免共享终端身份错位(张三未登出、李四直接用)。 + // 应小于登录 JWT 有效期(AccessExpire),才能真正先于令牌过期拦截"忘了登出"的场景。 + IdleLogoutSeconds int64 `json:",default=900"` } // PdfCacheConfig 工艺文件 PDF 本地预缓存目录 @@ -38,6 +42,12 @@ type PdfCacheConfig struct { Dir string `json:",default=pdf_cache"` // 本地缓存目录;留空关闭缓存 } +// BacklogConfig 离线同步积压告警配置(补强#2 建议1):队列+拧紧未同步合计超阈值打告警。 +// 区分两种积压:① 无有效登录态(数据留在本地,等待当前操作人登录后继续发送);② 有登录态仍堆积(疑似 MES 网络/业务拒绝)。 +type BacklogConfig struct { + WarnThreshold int `json:",default=50"` // 待上报积压超过该值打告警(队列+拧紧合计);<=0 用默认 50 +} + type Config struct { rest.RestConf Auth AuthConfig `json:",optional"` @@ -46,4 +56,5 @@ type Config struct { Sqlite SqliteConfig `json:",optional"` Station StationConfig `json:",optional"` PdfCache PdfCacheConfig `json:",optional"` + Backlog BacklogConfig `json:",optional"` } \ No newline at end of file diff --git a/bj_power_workstation/internal/handler/auth.go b/bj_power_workstation/internal/handler/auth.go index d57b491..16e696d 100644 --- a/bj_power_workstation/internal/handler/auth.go +++ b/bj_power_workstation/internal/handler/auth.go @@ -1,10 +1,12 @@ package handler import ( + "encoding/json" "net/http" "strings" "time" + "bj_power_workstation/internal/auth" "bj_power_workstation/internal/svc" ) @@ -50,6 +52,29 @@ func loginHandler(ctx *svc.ServiceContext) http.HandlerFunc { fail(w, http.StatusBadGateway, "MES 服务不可达:"+errString(err)) return } + // 方案 B:落盘工位登录态 JWT,作为后续报工/拧紧的可信身份锚点 + var loginResp struct { + Code int `json:"code"` + Data struct { + AccessToken string `json:"accessToken"` + ExpireAt int64 `json:"expireAt"` + StationNo int `json:"stationNo"` + User struct { + Username string `json:"username"` + Name string `json:"name"` + } `json:"user"` + } `json:"data"` + } + if err := json.Unmarshal(body, &loginResp); err == nil && loginResp.Data.AccessToken != "" { + // 解析 MES JWT 取出用户 ID,随登录态保存:离线数据落库 operator_id(按操作人隔离发送) + userID := int64(0) + if claims, perr := auth.ParseToken(ctx.Config.Auth.AccessSecret, loginResp.Data.AccessToken); perr == nil { + userID = claims.UserID + } + _ = ctx.Store.SaveStationSession(loginResp.Data.AccessToken, loginResp.Data.User.Username, + loginResp.Data.User.Name, loginResp.Data.StationNo, loginResp.Data.ExpireAt, userID) + ctx.Mes.SetStationToken(loginResp.Data.AccessToken) + } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) _, _ = w.Write(body) @@ -65,6 +90,12 @@ func logoutHandler(ctx *svc.ServiceContext) http.HandlerFunc { StationNo int `json:"stationNo"` } _ = parseJSON(r, &req) + // 退出前先统计「当前登录人」尚未成功上报的本地数据条数,供前端提醒本人处理 + pendingQueue, pendingTorque := int64(0), int64(0) + if ss, sErr := ctx.Store.GetStationSession(); sErr == nil && ss != nil { + pendingQueue, _ = ctx.Store.PendingQueueCountForOperator(ss.UserID) + pendingTorque, _ = ctx.Store.PendingTorqueCountForOperator(ss.UserID) + } username := strings.TrimSpace(req.Username) if username != "" { no := req.StationNo @@ -75,10 +106,66 @@ func logoutHandler(ctx *svc.ServiceContext) http.HandlerFunc { _, _, _ = ctx.Mes.Post("/api/internal/station/logout", map[string]any{"username": u, "stationNo": n}) }(username, no) } + // 方案 B:退出即清除本地登录态与 Bearer 凭证 + _ = ctx.Store.ClearStationSession() + ctx.Mes.SetStationToken("") + ok(w, map[string]any{ + "pendingQueue": pendingQueue, + "pendingTorque": pendingTorque, + "pendingTotal": pendingQueue + pendingTorque, + }) + } +} + +// touchHandler POST /api/auth/touch 滑动续签心跳(修订需求):任何人类触屏行为触发, +// 立即刷新本地登录态空闲计时 last_active_at(零成本本地写),防止作业中误登出。 +// 由前端根组件全局事件监听(click/touchstart/keydown/scroll 捕获阶段)调用,节流由前端控制。 +func touchHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if err := ctx.Store.TouchStationSession(); err != nil { + fail(w, http.StatusInternalServerError, "刷新登录态失败:"+err.Error()) + return + } ok(w, nil) } } +// refreshTokenHandler POST /api/auth/refresh-token 滑动续签 Bearer: +// 用当前有效 MES JWT 向 MES 换取新签发的 JWT(延长有效期),避免作业中令牌过期被登出。 +// 前置 Interceptor 已校验前端登录态;此处再代理 MES 刷新并回写本地 Bearer。 +func refreshTokenHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ss, err := ctx.Store.GetStationSession() + if err != nil || ss == nil || ss.Token == "" { + fail(w, http.StatusUnauthorized, "未登录或登录态已失效") + return + } + respBody, _, err := ctx.Mes.Post("/api/internal/station/refresh-token", nil) + if err != nil { + fail(w, http.StatusUnauthorized, "MES 续签失败:"+errString(err)) + return + } + var rr struct { + Code int `json:"code"` + Data struct { + AccessToken string `json:"accessToken"` + ExpireAt int64 `json:"expireAt"` + } `json:"data"` + } + if err := json.Unmarshal(respBody, &rr); err == nil && rr.Data.AccessToken != "" { + userID := ss.UserID + if claims, perr := auth.ParseToken(ctx.Config.Auth.AccessSecret, rr.Data.AccessToken); perr == nil { + userID = claims.UserID + } + _ = ctx.Store.SaveStationSession(rr.Data.AccessToken, ss.Username, ss.Name, ss.StationNo, rr.Data.ExpireAt, userID) + ctx.Mes.SetStationToken(rr.Data.AccessToken) + ok(w, map[string]any{"accessToken": rr.Data.AccessToken, "expireAt": rr.Data.ExpireAt}) + return + } + fail(w, http.StatusUnauthorized, "MES 续签响应异常") + } +} + // configHandler GET /api/config 返回工位配置:固定工位号 stationNo、固定接驳台 dock // (均由 yaml 配置在启动时加载,终端不可修改)。 func configHandler(ctx *svc.ServiceContext) http.HandlerFunc { @@ -88,4 +175,4 @@ func configHandler(ctx *svc.ServiceContext) http.HandlerFunc { "dock": ctx.Config.Station.Dock, }) } -} \ No newline at end of file +} diff --git a/bj_power_workstation/internal/handler/report.go b/bj_power_workstation/internal/handler/report.go index 446cdc7..77828a3 100644 --- a/bj_power_workstation/internal/handler/report.go +++ b/bj_power_workstation/internal/handler/report.go @@ -72,6 +72,17 @@ func processDoneHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } + // 方案 B:操作人取自工位登录态可信身份,忽略浏览器请求体里的 operator(防冒名); + // operator_id 用于离线队列按操作人隔离发送(仅当前登录人自己的数据被发送) + op := req.Operator + opID := int64(0) + if ss, sErr := ctx.Store.GetStationSession(); sErr == nil && ss != nil { + if ss.Name != "" { + op = ss.Name + } + opID = ss.UserID + } + // 先尽力冲刷历史积压,失败不影响本次上报 ctx.Syncer.RunOnce(r.Context()) @@ -80,8 +91,7 @@ func processDoneHandler(ctx *svc.ServiceContext) http.HandlerFunc { "orderNo": req.OrderNo, "flowId": req.FlowId, "stationNo": req.StationNo, - "steps": req.Steps, - "operator": req.Operator, + "operator": op, } if len(req.Binds) > 0 { body["binds"] = req.Binds @@ -94,12 +104,12 @@ func processDoneHandler(ctx *svc.ServiceContext) http.HandlerFunc { } payloadBytes, _ := json.Marshal(body) - ctx.Store.AddEventLog(req.OrderNo, req.Operator, "process_done", + ctx.Store.AddEventLog(req.OrderNo, op, "process_done", "工艺完成上报 sn="+req.Sn+" stationNo="+itoa(req.StationNo)+" flowId="+itoa(req.FlowId)+" binds="+itoa(len(req.Binds))) respBody, _, err := ctx.Mes.Post("/api/internal/station/report", json.RawMessage(payloadBytes)) if err != nil { - if qerr := ctx.Store.InsertQueueItem("process_done", string(payloadBytes)); qerr != nil { + if qerr := ctx.Store.InsertQueueItem("process_done", string(payloadBytes), opID, op); qerr != nil { fail(w, http.StatusInternalServerError, "上报失败且离线队列写入失败:"+qerr.Error()) return } @@ -139,6 +149,17 @@ func tempStoreHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } + // 方案 B:操作人取自工位登录态可信身份,忽略浏览器请求体里的 operator(防冒名); + // operator_id 用于离线队列按操作人隔离发送(仅当前登录人自己的数据被发送) + op := req.Operator + opID := int64(0) + if ss, sErr := ctx.Store.GetStationSession(); sErr == nil && ss != nil { + if ss.Name != "" { + op = ss.Name + } + opID = ss.UserID + } + // 先尽力冲刷历史积压,失败不影响本次上报 ctx.Syncer.RunOnce(r.Context()) @@ -147,16 +168,16 @@ func tempStoreHandler(ctx *svc.ServiceContext) http.HandlerFunc { "orderNo": req.OrderNo, "stationNo": req.StationNo, "flowId": req.FlowId, - "operator": req.Operator, + "operator": op, } payloadBytes, _ := json.Marshal(body) - ctx.Store.AddEventLog(req.OrderNo, req.Operator, "temp_store", + ctx.Store.AddEventLog(req.OrderNo, op, "temp_store", "暂存/退回库房 sn="+req.Sn+" stationNo="+itoa(req.StationNo)) respBody, _, err := ctx.Mes.Post("/api/internal/station/checkin", json.RawMessage(payloadBytes)) if err != nil { - if qerr := ctx.Store.InsertQueueItem("temp_store", string(payloadBytes)); qerr != nil { + if qerr := ctx.Store.InsertQueueItem("temp_store", string(payloadBytes), opID, op); qerr != nil { fail(w, http.StatusInternalServerError, "上报失败且离线队列写入失败:"+qerr.Error()) return } diff --git a/bj_power_workstation/internal/handler/routes.go b/bj_power_workstation/internal/handler/routes.go index 8a3bd12..19e4b14 100644 --- a/bj_power_workstation/internal/handler/routes.go +++ b/bj_power_workstation/internal/handler/routes.go @@ -30,6 +30,10 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) { // 业务接口(均需登录 JWT;PDF 代理除外——原样转发文件流) server.AddRoutes( []rest.Route{ + // 滑动续签(修订需求):任何人工触屏触发;touch 刷本地空闲计时, + // refresh-token 节流 30 秒换新 MES Bearer,作业中令牌不因固定有效期过期 + {Method: http.MethodPost, Path: "/api/auth/touch", Handler: touchHandler(ctx)}, + {Method: http.MethodPost, Path: "/api/auth/refresh-token", Handler: refreshTokenHandler(ctx)}, {Method: http.MethodGet, Path: "/api/task/current", Handler: taskCurrentHandler(ctx)}, {Method: http.MethodGet, Path: "/api/bind/panel", Handler: bindPanelHandler(ctx)}, {Method: http.MethodPost, Path: "/api/bind/record", Handler: bindRecordHandler(ctx)}, diff --git a/bj_power_workstation/internal/handler/sync.go b/bj_power_workstation/internal/handler/sync.go index fadcda1..b96144d 100644 --- a/bj_power_workstation/internal/handler/sync.go +++ b/bj_power_workstation/internal/handler/sync.go @@ -17,18 +17,23 @@ func syncFlushHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } -// syncStatsHandler GET /api/sync/stats 返回待同步条数统计。 +// syncStatsHandler GET /api/sync/stats 返回「当前登录人」尚未成功上报的本地数据(失败列表), +// 供前端在「同一人重新登录」时仅展示失败信息(不自动打开页面)。他人数据不被返回、不可见。 func syncStatsHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - pendingTorque, err1 := ctx.Store.PendingTorqueCount() - pendingQueue, err2 := ctx.Store.PendingQueueCount() - if err1 != nil || err2 != nil { - fail(w, http.StatusInternalServerError, "查询待同步统计失败") + ss, err := ctx.Store.GetStationSession() + if err != nil || ss == nil { + ok(w, map[string]any{"pendingTorque": 0, "pendingQueue": 0, "pendingTotal": 0, "queue": []any{}, "torque": []any{}}) return } + queue, _ := ctx.Store.PendingQueueItemsForOperator(ss.UserID, 200) + torque, _ := ctx.Store.PendingTorqueResultsForOperator(ss.UserID, 200) ok(w, map[string]any{ - "pendingTorque": pendingTorque, - "pendingQueue": pendingQueue, + "pendingQueue": len(queue), + "pendingTorque": len(torque), + "pendingTotal": len(queue) + len(torque), + "queue": queue, + "torque": torque, }) } } \ No newline at end of file diff --git a/bj_power_workstation/internal/handler/tightening.go b/bj_power_workstation/internal/handler/tightening.go index 11dd072..80d9bc9 100644 --- a/bj_power_workstation/internal/handler/tightening.go +++ b/bj_power_workstation/internal/handler/tightening.go @@ -79,6 +79,16 @@ func tighteningRecordHandler(ctx *svc.ServiceContext) http.HandlerFunc { if req.Result != "NG" { req.Result = "OK" } + // 方案 B:操作人取自工位登录态可信身份,忽略浏览器请求体里的 operator(防冒名) + ss, _ := ctx.Store.GetStationSession() + op := req.Operator + if ss != nil && ss.Name != "" { + op = ss.Name + } + opID := int64(0) + if ss != nil { + opID = ss.UserID + } dockCode := fmt.Sprintf("DOCK%02d", ctx.Config.Station.StationNo) id, err := ctx.Store.InsertTorqueResult(store.TorqueResult{ WorkOrderNo: req.WorkOrderNo, @@ -90,13 +100,14 @@ func tighteningRecordHandler(ctx *svc.ServiceContext) http.HandlerFunc { Torque: req.Torque, Angle: req.Angle, Result: req.Result, - Operator: req.Operator, + Operator: op, + OperatorID: opID, }) if err != nil { fail(w, http.StatusInternalServerError, "拧紧数据入库失败:"+err.Error()) return } - ctx.Store.AddEventLog(req.WorkOrderNo, req.Operator, "torque_record", + ctx.Store.AddEventLog(req.WorkOrderNo, op, "torque_record", fmt.Sprintf("拧紧录入 sn=%s 步骤=%s 扭矩=%.1f 结果=%s", req.Sn, req.StepName, req.Torque, req.Result)) ok(w, map[string]any{"id": id, "result": req.Result}) } diff --git a/bj_power_workstation/internal/handler/workpiece.go b/bj_power_workstation/internal/handler/workpiece.go index ddfb61f..483c5b8 100644 --- a/bj_power_workstation/internal/handler/workpiece.go +++ b/bj_power_workstation/internal/handler/workpiece.go @@ -111,6 +111,15 @@ func onlineHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } ctx.Syncer.RunOnce(r.Context()) + // 录入时操作人(当前登录人),供离线队列按操作人隔离发送 + opID := int64(0) + opName := req.Operator + if ss, sErr := ctx.Store.GetStationSession(); sErr == nil && ss != nil { + opID = ss.UserID + if ss.Name != "" { + opName = ss.Name + } + } ctx.Store.AddEventLog(req.OrderNo, req.Operator, "online_register", "上线建档 sn="+req.Sn) q := url.Values{} @@ -119,7 +128,7 @@ func onlineHandler(ctx *svc.ServiceContext) http.HandlerFunc { } respBody, _, err := ctx.Mes.Post("/api/internal/workpiece/online?"+q.Encode(), json.RawMessage(payload)) if err != nil { - if qerr := ctx.Store.InsertQueueItem("online_register", string(payload)); qerr != nil { + if qerr := ctx.Store.InsertQueueItem("online_register", string(payload), opID, opName); qerr != nil { fail(w, http.StatusInternalServerError, "上报失败且离线队列写入失败:"+qerr.Error()) return } @@ -155,6 +164,15 @@ func doneHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } ctx.Syncer.RunOnce(r.Context()) + // 录入时操作人(当前登录人),供离线队列按操作人隔离发送 + opID := int64(0) + opName := req.Operator + if ss, sErr := ctx.Store.GetStationSession(); sErr == nil && ss != nil { + opID = ss.UserID + if ss.Name != "" { + opName = ss.Name + } + } ctx.Store.AddEventLog("", req.Operator, "offline_finish", "下线完工入库 sn="+req.Sn) q := url.Values{} @@ -163,7 +181,7 @@ func doneHandler(ctx *svc.ServiceContext) http.HandlerFunc { } respBody, _, err := ctx.Mes.Post("/api/internal/workpiece/done?"+q.Encode(), json.RawMessage(payload)) if err != nil { - if qerr := ctx.Store.InsertQueueItem("offline_finish", string(payload)); qerr != nil { + if qerr := ctx.Store.InsertQueueItem("offline_finish", string(payload), opID, opName); qerr != nil { fail(w, http.StatusInternalServerError, "上报失败且离线队列写入失败:"+qerr.Error()) return } diff --git a/bj_power_workstation/internal/mes/client.go b/bj_power_workstation/internal/mes/client.go index 38505cf..a88f670 100644 --- a/bj_power_workstation/internal/mes/client.go +++ b/bj_power_workstation/internal/mes/client.go @@ -3,21 +3,31 @@ package mes import ( "bytes" "encoding/json" + "errors" "fmt" "io" "net/http" "net/url" "strings" + "sync" "time" ) +// ErrAuth 认证失效(401 / 登录态过期):可恢复错误。 +// 调用方(离线 syncer)据此跳过该条,数据留在本地 SQLite,待同一操作人重新登录后继续发送。 +var ErrAuth = errors.New("station auth expired or invalid") + // Client MES 内部 API HTTP 客户端。 // 自动携带请求头:X-API-TOKEN(项目间 token)、Content-Type: application/json。 // 任何非 2xx 状态返回包含响应体的错误信息。 type Client struct { - baseURL string - token string - httpClient *http.Client + baseURL string + token string // X-API-TOKEN 共享内部 token(项目间) + stationToken string // 工位登录态 JWT(Bearer):方案 B 报工链路可信身份凭证 + httpClient *http.Client + + mu sync.Mutex + Touch func() // 每次以「当前有效登录态」发起的调用触发,用于刷新工位空闲计时(核实4) } func New(baseURL, token string) *Client { @@ -28,6 +38,15 @@ func New(baseURL, token string) *Client { } } +// SetStationToken 设置工位登录态 JWT(方案 B):登录成功后由上层注入, +// 后续报工/拧紧调用将以 Authorization: Bearer 携带,供 MES 校验可信操作人。 +// 重新登录即清除 stale(若有),使离线 syncer 恢复重传。 +func (c *Client) SetStationToken(t string) { + c.mu.Lock() + c.stationToken = t + c.mu.Unlock() +} + // Get 发送 GET 请求,query 为空则忽略。 func (c *Client) Get(path string, query url.Values) ([]byte, http.Header, error) { u := c.baseURL + path @@ -37,7 +56,7 @@ func (c *Client) Get(path string, query url.Values) ([]byte, http.Header, error) return c.do(http.MethodGet, u, nil) } -// Post 发送 POST 请求,body 序列化为 JSON(body 为 nil 则不发送请求体)。 +// Post 发送 POST 请求(实时路径),body 序列化为 JSON;Bearer 使用当前登录态 JWT。 func (c *Client) Post(path string, body any) ([]byte, http.Header, error) { var reader io.Reader if body != nil { @@ -50,13 +69,27 @@ func (c *Client) Post(path string, body any) ([]byte, http.Header, error) { return c.do(http.MethodPost, c.baseURL+path, reader) } + +// do 执行请求:Bearer 固定使用当前登录态 JWT(c.stationToken)。 +// 仅在「当前登录态有效」时刷新空闲计时(核实4)。 func (c *Client) do(method, u string, body io.Reader) ([]byte, http.Header, error) { + c.mu.Lock() + bearer := c.stationToken + c.mu.Unlock() req, err := http.NewRequest(method, u, body) if err != nil { return nil, nil, err } req.Header.Set("X-API-TOKEN", c.token) req.Header.Set("Content-Type", "application/json;charset=utf-8") + // 方案 B:携带工位登录态 JWT,使 MES 能从 claims 取出可信操作人/工位号 + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + // 核实4:携带当前登录态的调用视为一次人工活动,刷新空闲计时 + if c.Touch != nil { + c.Touch() + } + } resp, err := c.httpClient.Do(req) if err != nil { @@ -68,10 +101,26 @@ func (c *Client) do(method, u string, body io.Reader) ([]byte, http.Header, erro if err != nil { return nil, resp.Header, err } + if resp.StatusCode == http.StatusUnauthorized { + // 401 = 工位登录态过期/无效,属可恢复错误: + // 调用方(syncer)据此跳过该条,数据留在本地,待同一操作人重新登录后继续发送。 + return respBody, resp.Header, fmt.Errorf("MES %s %s: %w", method, u, ErrAuth) + } if resp.StatusCode < 200 || resp.StatusCode > 299 { return respBody, resp.Header, fmt.Errorf("MES %s %s 返回 %d:%s", method, u, resp.StatusCode, truncate(string(respBody), 200)) } + // W2(安全审计):MES 内部接口常以 HTTP 200 + {code≠0} 返回业务失败(如数据校验不通过、 + // 重复提交被拒)。仅看 HTTP 状态会误判成功,导致离线队列数据被标记 synced=1 永久丢失。 + // 此处解析业务码,code≠0 一律视为失败,交由调用方保留重试(retry_count 达上限后仍继续尝试,不丢弃)。 + var br struct { + Code int `json:"code"` + Message string `json:"message"` + } + if err := json.Unmarshal(respBody, &br); err == nil && br.Code != 0 { + return respBody, resp.Header, fmt.Errorf("MES %s %s 业务失败(code=%d):%s", + method, u, br.Code, truncate(br.Message, 200)) + } return respBody, resp.Header, nil } @@ -81,4 +130,4 @@ func truncate(s string, n int) string { return s[:n] + "..." } return s -} \ No newline at end of file +} diff --git a/bj_power_workstation/internal/store/store.go b/bj_power_workstation/internal/store/store.go index 4f82cf4..5c6470a 100644 --- a/bj_power_workstation/internal/store/store.go +++ b/bj_power_workstation/internal/store/store.go @@ -35,14 +35,18 @@ CREATE TABLE IF NOT EXISTS torque_results ( angle REAL, result TEXT, operator TEXT, + operator_id INTEGER, -- 录入时操作人 ID(当前登录人),按操作人隔离发送 synced INTEGER DEFAULT 0, + retry_count INTEGER DEFAULT 0, created_at INTEGER ); CREATE TABLE IF NOT EXISTS report_queue ( id INTEGER PRIMARY KEY AUTOINCREMENT, - kind TEXT, -- process_done | temp_store + kind TEXT, -- process_done | temp_store | online_register | offline_finish payload TEXT, -- 待透传给 MES 的 JSON body + operator_id INTEGER, -- 录入时操作人 ID(当前登录人),按操作人隔离发送 + operator_name TEXT, -- 录入时操作人姓名(本地追溯用) synced INTEGER DEFAULT 0, retry_count INTEGER DEFAULT 0, created_at INTEGER @@ -57,6 +61,21 @@ CREATE TABLE IF NOT EXISTS event_log ( detail TEXT, created_at INTEGER ); + +-- 工位终端当前登录态(方案 B · 可信身份锚点):单行(id=1)保存 MES 签发的登录 JWT 与其声明身份。 +-- 报工/拧紧转发 MES 时携带该 JWT 作为 Bearer,MES 据 claims 落痕,杜绝浏览器侧冒名操作工。 +-- user_id 为 MES 用户 ID(落库用),expire_at 为凭证过期时间。 +CREATE TABLE IF NOT EXISTS station_session ( + id INTEGER PRIMARY KEY CHECK(id=1), + token TEXT, + username TEXT, + name TEXT, + station_no INTEGER, + user_id INTEGER, + expire_at INTEGER, + last_active_at INTEGER, + created_at INTEGER +); ` // Open 打开(必要时创建)本地 SQLite 数据库并建表。 @@ -88,9 +107,211 @@ func Open(path string) (*Store, error) { db.Close() return nil, err } + if err := s.migrateQueueOp(); err != nil { + db.Close() + return nil, err + } + if err := s.migrateTorqueRetry(); err != nil { + db.Close() + return nil, err + } + if err := s.migrateTorqueOp(); err != nil { + db.Close() + return nil, err + } + if err := s.migrateStationSession(); err != nil { + db.Close() + return nil, err + } + if err := s.migrateStationSessionIdle(); err != nil { + db.Close() + return nil, err + } + if err := s.migrateStationSessionUser(); err != nil { + db.Close() + return nil, err + } return s, nil } +// migrateStationSession 兼容旧库:登录态表为方案 B 新增,缺失时自动补齐。 +func (s *Store) migrateStationSession() error { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('station_session') WHERE name='token'`) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + return nil + } + _, err = s.db.Exec(`CREATE TABLE IF NOT EXISTS station_session ( + id INTEGER PRIMARY KEY CHECK(id=1), + token TEXT, username TEXT, name TEXT, station_no INTEGER, expire_at INTEGER, last_active_at INTEGER, created_at INTEGER + )`) + return err +} + +// migrateStationSessionIdle 兼容旧库:登录态空闲计时列(last_active_at)为核实4新增,缺失时自动补齐。 +func (s *Store) migrateStationSessionIdle() error { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('station_session') WHERE name='last_active_at'`) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + return nil + } + _, err = s.db.Exec(`ALTER TABLE station_session ADD COLUMN last_active_at INTEGER`) + return err +} + +// migrateStationSessionUser 兼容旧库:登录态用户 ID 列(user_id)为隐患1新增,缺失时自动补齐。 +func (s *Store) migrateStationSessionUser() error { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('station_session') WHERE name='user_id'`) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + return nil + } + _, err = s.db.Exec(`ALTER TABLE station_session ADD COLUMN user_id INTEGER`) + return err +} + +// migrateQueueOp 兼容旧库:上报队列身份列(operator_id/operator_name)为按操作人隔离新增,缺失时自动补齐。 +func (s *Store) migrateQueueOp() error { + for _, col := range []struct{ name, ddl string }{ + {"operator_id", `ALTER TABLE report_queue ADD COLUMN operator_id INTEGER`}, + {"operator_name", `ALTER TABLE report_queue ADD COLUMN operator_name TEXT`}, + } { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('report_queue') WHERE name=?`, col.name) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + continue + } + if _, err := s.db.Exec(col.ddl); err != nil { + return err + } + } + return nil +} + +// migrateTorqueRetry 兼容旧库:拧紧结果重试计数(retry_count)为后续补充字段,缺失时自动补齐。 +func (s *Store) migrateTorqueRetry() error { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('torque_results') WHERE name='retry_count'`) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + return nil + } + _, err = s.db.Exec(`ALTER TABLE torque_results ADD COLUMN retry_count INTEGER DEFAULT 0`) + return err +} + +// migrateTorqueOp 兼容旧库:拧紧结果操作人列(operator_id)为按操作人隔离新增,缺失时自动补齐。 +func (s *Store) migrateTorqueOp() error { + rows, err := s.db.Query(`SELECT name FROM pragma_table_info('torque_results') WHERE name='operator_id'`) + if err != nil { + return err + } + exists := rows.Next() + rows.Close() + if exists { + return nil + } + _, err = s.db.Exec(`ALTER TABLE torque_results ADD COLUMN operator_id INTEGER`) + return err +} + +// StationSession 工位终端当前登录态(方案 B 可信身份锚点)。 +type StationSession struct { + Token string // MES 签发的登录 JWT(Bearer 凭证) + Username string // 登录账号(MES username) + Name string // 真实姓名(落痕操作人) + StationNo int // 登录时绑定的工位号 + UserID int64 // MES 用户 ID(落库用) + ExpireAt int64 // 凭证过期时间戳(秒) +} + +// SaveStationSession 写入/覆盖当前登录态(单行 id=1)。 +func (s *Store) SaveStationSession(token, username, name string, stationNo int, expireAt int64, userID int64) error { + now := time.Now().Unix() + _, err := s.db.Exec( + `INSERT INTO station_session(id,token,username,name,station_no,user_id,expire_at,last_active_at,created_at) + VALUES(1,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET + token=excluded.token, username=excluded.username, name=excluded.name, + station_no=excluded.station_no, user_id=excluded.user_id, expire_at=excluded.expire_at, + last_active_at=excluded.last_active_at, created_at=excluded.created_at`, + token, username, name, stationNo, userID, expireAt, now, now) + return err +} + +// TouchStationSession 刷新登录态空闲计时(核实4):每次以有效登录态发起的 MES 调用触发, +// 证明当前操作人仍活跃在岗;后台 sweeper 据此判断是否超时自动登出。 +func (s *Store) TouchStationSession() error { + _, err := s.db.Exec(`UPDATE station_session SET last_active_at=? WHERE id=1`, time.Now().Unix()) + return err +} + +// ClearExpiredSession 若当前登录态空闲超过 idleSec 秒,则清除并返回 true(核实4 超时自动登出)。 +// 删除的是「当前登录态」(station_session),会触发 mc.SetStationToken("") 强制前端重新登录。 +func (s *Store) ClearExpiredSession(idleSec int64) (bool, error) { + if idleSec <= 0 { + return false, nil + } + var lastActive int64 + row := s.db.QueryRow(`SELECT last_active_at FROM station_session WHERE id=1`) + if err := row.Scan(&lastActive); err != nil { + if err == sql.ErrNoRows { + return false, nil + } + return false, err + } + if lastActive <= 0 { + // 旧数据无计时:以创建时间兜底,避免无限期有效 + row2 := s.db.QueryRow(`SELECT COALESCE(created_at,0) FROM station_session WHERE id=1`) + _ = row2.Scan(&lastActive) + } + if time.Now().Unix()-lastActive > idleSec { + if _, err := s.db.Exec(`DELETE FROM station_session WHERE id=1`); err != nil { + return false, err + } + return true, nil + } + return false, nil +} + +// GetStationSession 读取当前登录态;无记录返回 (nil, nil)。 +func (s *Store) GetStationSession() (*StationSession, error) { + row := s.db.QueryRow(`SELECT token,username,name,station_no,user_id,expire_at FROM station_session WHERE id=1`) + var ss StationSession + if err := row.Scan(&ss.Token, &ss.Username, &ss.Name, &ss.StationNo, &ss.UserID, &ss.ExpireAt); err != nil { + if err == sql.ErrNoRows { + return nil, nil + } + return nil, err + } + return &ss, nil +} + +// ClearStationSession 清除登录态(退出登录时调用)。 +func (s *Store) ClearStationSession() error { + _, err := s.db.Exec(`DELETE FROM station_session WHERE id=1`) + return err +} + // migrateUsersRole 兼容旧库:role 列为后续补充字段时自动补齐。 func (s *Store) migrateUsersRole() error { rows, err := s.db.Query(`SELECT name FROM pragma_table_info('users') WHERE name='role'`) @@ -186,15 +407,17 @@ type TorqueResult struct { Angle float64 `json:"angle"` Result string `json:"result"` // OK | NG Operator string `json:"operator"` + OperatorID int64 `json:"operatorId"` // 录入时操作人 ID(当前登录人),按操作人隔离发送 Synced bool `json:"synced"` - CreatedAt int64 `json:"createdAt"` // 毫秒时间戳 + RetryCount int64 `json:"retryCount"` // 上报失败累计次数 + CreatedAt int64 `json:"createdAt"` // 毫秒时间戳 } func (s *Store) InsertTorqueResult(t TorqueResult) (int64, error) { res, err := s.db.Exec( - `INSERT INTO torque_results(work_order_no, sn, dock_code, screw_no, step_id, step_name, torque, angle, result, operator, synced, created_at) - VALUES(?,?,?,?,?,?,?,?,?,?,0,?)`, - t.WorkOrderNo, t.Sn, t.DockCode, t.ScrewNo, t.StepId, t.StepName, t.Torque, t.Angle, t.Result, t.Operator, time.Now().Unix(), + `INSERT INTO torque_results(work_order_no, sn, dock_code, screw_no, step_id, step_name, torque, angle, result, operator, operator_id, synced, created_at) + VALUES(?,?,?,?,?,?,?,?,?,?,?,0,?)`, + t.WorkOrderNo, t.Sn, t.DockCode, t.ScrewNo, t.StepId, t.StepName, t.Torque, t.Angle, t.Result, t.Operator, t.OperatorID, time.Now().Unix(), ) if err != nil { return 0, err @@ -204,7 +427,7 @@ func (s *Store) InsertTorqueResult(t TorqueResult) (int64, error) { // ListTorqueResults 查询本地拧紧结果,最新优先;sn 为空查全部,onlyPending 仅查未同步。 func (s *Store) ListTorqueResults(sn string, onlyPending bool, limit int) ([]TorqueResult, error) { - query := `SELECT id, work_order_no, sn, dock_code, screw_no, COALESCE(step_id,''), COALESCE(step_name,''), torque, angle, result, operator, synced, created_at FROM torque_results` + query := `SELECT id, work_order_no, sn, dock_code, screw_no, COALESCE(step_id,''), COALESCE(step_name,''), torque, angle, result, operator, COALESCE(operator_id,0), synced, COALESCE(retry_count,0), created_at FROM torque_results` var conds []string var args []any if sn != "" { @@ -232,7 +455,7 @@ func (s *Store) ListTorqueResults(sn string, onlyPending bool, limit int) ([]Tor var synced int64 var createdAt int64 if err := rows.Scan(&t.ID, &t.WorkOrderNo, &t.Sn, &t.DockCode, &t.ScrewNo, - &t.StepId, &t.StepName, &t.Torque, &t.Angle, &t.Result, &t.Operator, &synced, &createdAt); err != nil { + &t.StepId, &t.StepName, &t.Torque, &t.Angle, &t.Result, &t.Operator, &t.OperatorID, &synced, &t.RetryCount, &createdAt); err != nil { return nil, err } t.Synced = synced == 1 @@ -242,6 +465,33 @@ func (s *Store) ListTorqueResults(sn string, onlyPending bool, limit int) ([]Tor return list, rows.Err() } +// PendingTorqueResultsForOperator 仅返回指定操作人自己的未同步拧紧结果(按操作人隔离发送)。 +func (s *Store) PendingTorqueResultsForOperator(opID int64, limit int) ([]TorqueResult, error) { + rows, err := s.db.Query( + `SELECT id, work_order_no, sn, dock_code, screw_no, COALESCE(step_id,''), COALESCE(step_name,''), torque, angle, result, operator, COALESCE(operator_id,0), synced, COALESCE(retry_count,0), created_at FROM torque_results WHERE synced=0 AND operator_id=? ORDER BY id ASC LIMIT ?`, + opID, limit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + list := make([]TorqueResult, 0) + for rows.Next() { + var t TorqueResult + var synced int64 + var createdAt int64 + if err := rows.Scan(&t.ID, &t.WorkOrderNo, &t.Sn, &t.DockCode, &t.ScrewNo, + &t.StepId, &t.StepName, &t.Torque, &t.Angle, &t.Result, &t.Operator, &t.OperatorID, &synced, &t.RetryCount, &createdAt); err != nil { + return nil, err + } + t.Synced = synced == 1 + t.CreatedAt = createdAt * 1000 + list = append(list, t) + } + return list, rows.Err() +} + func (s *Store) MarkTorqueSynced(ids []int64) error { tx, err := s.db.Begin() if err != nil { @@ -265,24 +515,29 @@ func (s *Store) PendingTorqueCount() (int64, error) { // ---------- 上报队列 ---------- type QueueItem struct { - ID int64 - Kind string // process_done | temp_store - Payload string - RetryCount int - CreatedAt int64 + ID int64 + Kind string // process_done | temp_store | online_register | offline_finish + Payload string + OperatorID int64 // 录入时操作人 ID(当前登录人),按操作人隔离发送 + OperatorName string // 录入时操作人姓名(本地追溯用) + RetryCount int + CreatedAt int64 } -func (s *Store) InsertQueueItem(kind, payload string) error { +// InsertQueueItem 写入一条离线队列,记录录入时操作人 ID/姓名(当前登录人), +// 供后台同步器按操作人隔离发送(仅当前登录人自己的数据被发送,他人数据不被代发)。 +func (s *Store) InsertQueueItem(kind, payload string, opID int64, opName string) error { _, err := s.db.Exec( - `INSERT INTO report_queue(kind, payload, synced, retry_count, created_at) VALUES(?,?,0,0,?)`, - kind, payload, time.Now().Unix(), + `INSERT INTO report_queue(kind, payload, operator_id, operator_name, synced, retry_count, created_at) VALUES(?,?,?,?,0,0,?)`, + kind, payload, opID, opName, time.Now().Unix(), ) return err } +// PendingQueueItems 返回全部未同步队列项(不分操作人,用于全局积压统计)。 func (s *Store) PendingQueueItems(limit int) ([]QueueItem, error) { rows, err := s.db.Query( - `SELECT id, kind, payload, retry_count, created_at FROM report_queue WHERE synced=0 ORDER BY id ASC LIMIT ?`, + `SELECT id, kind, payload, COALESCE(operator_id,0), COALESCE(operator_name,''), retry_count, created_at FROM report_queue WHERE synced=0 ORDER BY id ASC LIMIT ?`, limit, ) if err != nil { @@ -293,7 +548,29 @@ func (s *Store) PendingQueueItems(limit int) ([]QueueItem, error) { list := make([]QueueItem, 0) for rows.Next() { var it QueueItem - if err := rows.Scan(&it.ID, &it.Kind, &it.Payload, &it.RetryCount, &it.CreatedAt); err != nil { + if err := rows.Scan(&it.ID, &it.Kind, &it.Payload, &it.OperatorID, &it.OperatorName, &it.RetryCount, &it.CreatedAt); err != nil { + return nil, err + } + list = append(list, it) + } + return list, rows.Err() +} + +// PendingQueueItemsForOperator 仅返回指定操作人自己的未同步队列项(按操作人隔离发送)。 +func (s *Store) PendingQueueItemsForOperator(opID int64, limit int) ([]QueueItem, error) { + rows, err := s.db.Query( + `SELECT id, kind, payload, COALESCE(operator_id,0), COALESCE(operator_name,''), retry_count, created_at FROM report_queue WHERE synced=0 AND operator_id=? ORDER BY id ASC LIMIT ?`, + opID, limit, + ) + if err != nil { + return nil, err + } + defer rows.Close() + + list := make([]QueueItem, 0) + for rows.Next() { + var it QueueItem + if err := rows.Scan(&it.ID, &it.Kind, &it.Payload, &it.OperatorID, &it.OperatorName, &it.RetryCount, &it.CreatedAt); err != nil { return nil, err } list = append(list, it) @@ -312,12 +589,49 @@ func (s *Store) BumpQueueRetry(id int64) error { return err } +// BumpTorqueRetry 失败累计重试次数(synced 保持 0)。 +func (s *Store) BumpTorqueRetry(id int64) error { + _, err := s.db.Exec(`UPDATE torque_results SET retry_count=retry_count+1 WHERE id=?`, id) + return err +} + func (s *Store) PendingQueueCount() (int64, error) { var n int64 err := s.db.QueryRow(`SELECT COUNT(*) FROM report_queue WHERE synced=0`).Scan(&n) return n, err } +// PendingQueueCountForOperator 返回指定操作人自己的未同步队列条数(退出登录提醒用)。 +func (s *Store) PendingQueueCountForOperator(opID int64) (int64, error) { + var n int64 + err := s.db.QueryRow(`SELECT COUNT(*) FROM report_queue WHERE synced=0 AND operator_id=?`, opID).Scan(&n) + return n, err +} + +// PendingTorqueCountForOperator 返回指定操作人自己的未同步拧紧结果条数(退出登录提醒用)。 +func (s *Store) PendingTorqueCountForOperator(opID int64) (int64, error) { + var n int64 + err := s.db.QueryRow(`SELECT COUNT(*) FROM torque_results WHERE synced=0 AND operator_id=?`, opID).Scan(&n) + return n, err +} + +// CleanupOld 清理超过 maxAgeSec 秒的本地记录(队列+拧紧),用于「保留 1 个月」的本地留存策略; +// 同步成功与否均清理,超时数据由人工在 MES 侧追溯,本地不再保留。 +func (s *Store) CleanupOld(maxAgeSec int64) (int64, error) { + cutoff := time.Now().Unix() - maxAgeSec + res, err := s.db.Exec(`DELETE FROM report_queue WHERE created_at < ?`, cutoff) + if err != nil { + return 0, err + } + n1, _ := res.RowsAffected() + res2, err := s.db.Exec(`DELETE FROM torque_results WHERE created_at < ?`, cutoff) + if err != nil { + return n1, err + } + n2, _ := res2.RowsAffected() + return n1 + n2, nil +} + // ---------- 操作日志 ---------- // AddEventLog 记录一条操作日志(含工单号与操作人),用于追溯。 @@ -329,4 +643,4 @@ func (s *Store) AddEventLog(workOrderNo, operator, action, detail string) { if err != nil { return // 日志写入失败不影响主流程 } -} \ No newline at end of file +} diff --git a/bj_power_workstation/internal/store/store_migrate_test.go b/bj_power_workstation/internal/store/store_migrate_test.go new file mode 100644 index 0000000..924bc98 --- /dev/null +++ b/bj_power_workstation/internal/store/store_migrate_test.go @@ -0,0 +1,73 @@ +package store_test + +import ( + "database/sql" + "testing" + + _ "modernc.org/sqlite" + + "bj_power_workstation/internal/store" +) + +// TestOldDBMigration 运行期验证旧库自动迁移:以「快照/隔离机制上线前」的真实旧 schema +// 建库(无 operator_id/operator_name/retry_count/station_session 等),store.Open 后 +// 所有迁移自动补齐,按操作人隔离的查询与登录态读写全部可用。 +func TestOldDBMigration(t *testing.T) { + path := t.TempDir() + "/old.db" + + // 直接以旧 schema 建库,模拟历史存量库 + old, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + oldSQL := ` +CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password_hash TEXT, real_name TEXT, role TEXT NOT NULL DEFAULT 'operator'); +CREATE TABLE torque_results (id INTEGER PRIMARY KEY AUTOINCREMENT, work_order_no TEXT, sn TEXT, dock_code TEXT, screw_no TEXT, step_id TEXT, step_name TEXT, torque REAL, angle REAL, result TEXT, operator TEXT, synced INTEGER DEFAULT 0, created_at INTEGER); +CREATE TABLE report_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT, payload TEXT, synced INTEGER DEFAULT 0, retry_count INTEGER DEFAULT 0, created_at INTEGER); +CREATE TABLE event_log (id INTEGER PRIMARY KEY AUTOINCREMENT, work_order_no TEXT, operator TEXT, action TEXT, detail TEXT, created_at INTEGER); +` + if _, err := old.Exec(oldSQL); err != nil { + t.Fatal(err) + } + _ = old.Close() + + // 重新 Open:迁移应把旧库补齐到当前 schema + st, err := store.Open(path) + if err != nil { + t.Fatalf("旧库迁移失败: %v", err) + } + defer st.Close() + + // 1) 拧紧结果:operator_id 可写可按人查 + if _, err := st.InsertTorqueResult(store.TorqueResult{ + WorkOrderNo: "WO-1", Sn: "SN-1", DockCode: "DOCK01", ScrewNo: "S1", + Torque: 10, Angle: 90, Result: "OK", Operator: "张三", OperatorID: 7, + }); err != nil { + t.Fatalf("[旧库] 拧紧结果写入失败(缺 operator_id 列?): %v", err) + } + rows, err := st.PendingTorqueResultsForOperator(7, 10) + if err != nil || len(rows) != 1 { + t.Fatalf("[旧库] 按操作人查拧紧结果应得 1 条,err=%v len=%d", err, len(rows)) + } + + // 2) 离线队列:operator_id/operator_name 可写可按人查 + if err := st.InsertQueueItem("process_done", `{"sn":"SN-1"}`, 7, "张三"); err != nil { + t.Fatalf("[旧库] 队列写入失败(缺 operator 列?): %v", err) + } + items, err := st.PendingQueueItemsForOperator(7, 10) + if err != nil || len(items) != 1 { + t.Fatalf("[旧库] 按操作人查队列应得 1 条,err=%v len=%d", err, len(items)) + } + + // 3) 登录态表自动创建 + 单行读写 + if ss, err := st.GetStationSession(); err != nil || ss != nil { + t.Fatalf("[旧库] 新建登录态表应无记录,ss=%+v err=%v", ss, err) + } + if err := st.SaveStationSession("jwt_x", "zhang", "张三", 3, 9999999999, 7); err != nil { + t.Fatalf("[旧库] 登录态写入失败: %v", err) + } + ss, err := st.GetStationSession() + if err != nil || ss == nil || ss.UserID != 7 || ss.Name != "张三" { + t.Fatalf("[旧库] 登录态读写失败: ss=%+v err=%v", ss, err) + } +} diff --git a/bj_power_workstation/internal/syncer/identity_boundary_test.go b/bj_power_workstation/internal/syncer/identity_boundary_test.go new file mode 100644 index 0000000..71d17c6 --- /dev/null +++ b/bj_power_workstation/internal/syncer/identity_boundary_test.go @@ -0,0 +1,264 @@ +package syncer_test + +import ( + "context" + "net/http" + "net/http/httptest" + "strconv" + "sync" + "testing" + "time" + + "bj_power_workstation/internal/mes" + "bj_power_workstation/internal/store" + "bj_power_workstation/internal/syncer" +) + +// 边界场景运行期验证(2026-10-06 简化模型): +// 操作工手动点发送 → 用当前登录这人的身份 → 发不出去就是发不出去(留在本地 SQLite)。 +// 数据按 operator_id 隔离:仅当前登录人自己的未同步数据会被发送; +// 其他人的数据不被代发、不对他人可见;同一人重新登录后可继续发送。 + +// captureServer 假 MES:记录每个请求的 Authorization 头,返回业务成功。 +type captureServer struct { + mu sync.Mutex + auth []string + ts *httptest.Server +} + +func newCaptureServer() *captureServer { + c := &captureServer{} + c.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c.mu.Lock() + c.auth = append(c.auth, r.Header.Get("Authorization")) + c.mu.Unlock() + w.WriteHeader(200) + _, _ = w.Write([]byte(`{"code":0,"message":"成功","data":null}`)) + })) + return c +} + +func (c *captureServer) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.auth) +} + +func (c *captureServer) lastAuth() string { + c.mu.Lock() + defer c.mu.Unlock() + if len(c.auth) == 0 { + return "" + } + return c.auth[len(c.auth)-1] +} + +// newTestEnv 开临时 SQLite + 假 MES + syncer。 +func newTestEnv(t *testing.T) (*store.Store, *mes.Client, *syncer.Syncer, *captureServer) { + t.Helper() + st, err := store.Open(t.TempDir() + "/ws.db") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + cap := newCaptureServer() + t.Cleanup(cap.ts.Close) + mc := mes.New(cap.ts.URL, "tok") + return st, mc, syncer.New(st, mc), cap +} + +// 场景1(按操作人隔离 · 不代发):张三录入离线数据后离线,李四登录—— +// 李四的会话绝不能把张三的数据发出去(RunOnce=0、MES 未收到任何请求、数据保留在本地); +// 张三重新登录后,自己的数据以张三当前有效 JWT 成功发出。 +func TestScenario1_OperatorIsolation(t *testing.T) { + st, mc, sy, cap := newTestEnv(t) + ctx := context.Background() + + // 张三登录(工位3,用户ID7)+ 离线录入 2 条 + if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang") + for i := 0; i < 2; i++ { + if err := st.InsertQueueItem("process_done", `{"sn":"SN-1-`+itoa(i)+`","operator":"张三"}`, 7, "张三"); err != nil { + t.Fatal(err) + } + } + + // 李四登录(MES 网络恢复):张三的数据不被李四的会话代发 + if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_li") + if n := sy.RunOnce(ctx); n != 0 { + t.Fatalf("[场景1] 李四不应发送张三的数据,实际成功 %d 条", n) + } + if got := cap.count(); got != 0 { + t.Errorf("[场景1] 李四会话不应向 MES 发出任何报工,实际发出 %d 次", got) + } + if n, _ := st.PendingQueueCount(); n != 2 { + t.Errorf("[场景1] 张三的 2 条应原样保留,实际剩余 %d", n) + } + + // 张三重新登录:仅看到/发送自己的失败数据 + if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang2") + if n := sy.RunOnce(ctx); n != 2 { + t.Fatalf("[场景1] 张三重登后应成功发送 2 条,实际 %d", n) + } + if got := cap.lastAuth(); got != "Bearer jwt_zhang2" { + t.Errorf("[场景1] 应以张三当前有效 JWT 发出,实际 %q", got) + } + if n, _ := st.PendingQueueCount(); n != 0 { + t.Errorf("[场景1] 发送后队列应清空,实际剩余 %d", n) + } +} + +// 场景2(登出即暂停):张三登出 → 无登录人,任何数据都不发出(发不出去就是发不出去); +// 重新登录(同一人)后数据还在,继续发送成功。 +func TestScenario2_LogoutPausesSending(t *testing.T) { + st, mc, sy, cap := newTestEnv(t) + ctx := context.Background() + + // 张三登录 + 离线录入 + if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang") + if err := st.InsertQueueItem("temp_store", `{"sn":"SN-2","operator":"张三"}`, 7, "张三"); err != nil { + t.Fatal(err) + } + + // 张三登出(镜像 logoutHandler:清 session + 清当前 Bearer) + if err := st.ClearStationSession(); err != nil { + t.Fatal(err) + } + mc.SetStationToken("") + if ss, err := st.GetStationSession(); err != nil || ss != nil { + t.Fatalf("[场景2] 登出后登录态应清空,实际 ss=%+v err=%v", ss, err) + } + // 登出期间:不发送,数据留在本地 + if n := sy.RunOnce(ctx); n != 0 { + t.Fatalf("[场景2] 登出后不应发送,实际成功 %d 条", n) + } + if got := cap.count(); got != 0 { + t.Errorf("[场景2] 登出后不应向 MES 发出请求,实际 %d 次", got) + } + if n, _ := st.PendingQueueCount(); n != 1 { + t.Errorf("[场景2] 数据应保留 1 条,实际 %d", n) + } + + // 张三重新登录:数据还在,继续发送 + if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang2") + if n := sy.RunOnce(ctx); n != 1 { + t.Fatalf("[场景2] 重登后应成功发送 1 条,实际 %d", n) + } + if got := cap.lastAuth(); got != "Bearer jwt_zhang2" { + t.Errorf("[场景2] 应以张三当前有效 JWT 发出,实际 %q", got) + } +} + +// 场景3(换人直接切换 · 各发各的):张三登录录入后未登出,李四直接登录覆盖单行登录态—— +// 李四会话只发李四自己的新数据;张三的旧数据保留,等张三本人再登录才发。 +func TestScenario3_DirectUserSwitch(t *testing.T) { + st, mc, sy, cap := newTestEnv(t) + ctx := context.Background() + + // 张三登录 + 录入 1 条(MES 不可达时的离线存量) + if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang") + if err := st.InsertQueueItem("process_done", `{"sn":"SN-3","operator":"张三"}`, 7, "张三"); err != nil { + t.Fatal(err) + } + + // 李四直接登录(不登出):单行登录态被覆盖 + if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_li") + // 李四也录入 1 条 + if err := st.InsertQueueItem("process_done", `{"sn":"SN-3L","operator":"李四"}`, 9, "李四"); err != nil { + t.Fatal(err) + } + + // 一轮同步:只发李四的 1 条,张三的 1 条保留 + if n := sy.RunOnce(ctx); n != 1 { + t.Fatalf("[场景3] 李四会话应只发送自己的 1 条,实际 %d", n) + } + if got := cap.lastAuth(); got != "Bearer jwt_li" { + t.Errorf("[场景3] 应以李四当前 JWT 发出,实际 %q", got) + } + items, err := st.PendingQueueItems(10) + if err != nil || len(items) != 1 { + t.Fatalf("[场景3] 应剩 1 条(张三的),err=%v len=%d", err, len(items)) + } + if items[0].OperatorID != 7 || items[0].OperatorName != "张三" { + t.Errorf("[场景3] 剩余应为张三的数据:%+v", items[0]) + } + + // 张三再登录:发自己的那条 + if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang2") + if n := sy.RunOnce(ctx); n != 1 { + t.Fatalf("[场景3] 张三重登后应发送自己的 1 条,实际 %d", n) + } +} + +// 场景4(拧紧结果同样按操作人隔离):张三的拧紧结果不被李四会话发送, +// 张三重登后以当前 JWT 发出。 +func TestScenario4_TorqueOperatorIsolation(t *testing.T) { + st, mc, sy, cap := newTestEnv(t) + ctx := context.Background() + + // 张三登录 + 录入拧紧结果(离线存量,operator_id=7) + if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang") + if _, err := st.InsertTorqueResult(store.TorqueResult{ + WorkOrderNo: "WO-1", Sn: "SN-4", DockCode: "DOCK01", ScrewNo: "S1", + Torque: 10, Angle: 90, Result: "OK", Operator: "张三", OperatorID: 7, + }); err != nil { + t.Fatal(err) + } + + // 李四登录:不代发 + if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_li") + if n := sy.RunOnce(ctx); n != 0 { + t.Fatalf("[场景4] 李四不应发送张三的拧紧结果,实际 %d", n) + } + if n, _ := st.PendingTorqueCount(); n != 1 { + t.Errorf("[场景4] 拧紧结果应保留 1 条,实际 %d", n) + } + + // 张三重登:发送 + if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil { + t.Fatal(err) + } + mc.SetStationToken("jwt_zhang2") + if n := sy.RunOnce(ctx); n != 1 { + t.Fatalf("[场景4] 张三重登后应发送 1 条拧紧结果,实际 %d", n) + } + if got := cap.lastAuth(); got != "Bearer jwt_zhang2" { + t.Errorf("[场景4] 应以张三当前有效 JWT 发出,实际 %q", got) + } + if n, _ := st.PendingTorqueCount(); n != 0 { + t.Errorf("[场景4] 发送后应无待同步拧紧结果,实际 %d", n) + } +} + +func itoa(i int) string { + return strconv.Itoa(i) +} diff --git a/bj_power_workstation/internal/syncer/syncer.go b/bj_power_workstation/internal/syncer/syncer.go index 613888d..8134527 100644 --- a/bj_power_workstation/internal/syncer/syncer.go +++ b/bj_power_workstation/internal/syncer/syncer.go @@ -3,6 +3,7 @@ package syncer import ( "context" "encoding/json" + "errors" "strings" "time" @@ -15,17 +16,43 @@ import ( const ( reportBatchLimit = 200 // 单轮最多处理条数 defaultInterval = 15 * time.Second + + // maxQueueRetry / maxTorqueRetry 重试上报上限:超过该次数不再累加 retry_count、不再刷错误日志, + // 但仍在每轮继续尝试发送(失败数据留本地等待人工/网络恢复处理,不丢弃、不删除)。 + maxQueueRetry = 10 + maxTorqueRetry = 10 + + // defaultBacklogWarnThreshold 待上报积压告警默认阈值(建议1:可由 config.Backlog.WarnThreshold 覆盖)。 + defaultBacklogWarnThreshold = 50 + + // localRetentionSec 本地数据保留时长(30 天):超过该时长的离线数据由后台定时清理。 + localRetentionSec = 30 * 24 * 3600 ) -// Syncer 后台同步器:每 15 秒把未同步的 report_queue 与 torque_results 上报 MES。 +// Syncer 后台同步器:每 15 秒把「当前登录人」未同步的 report_queue 与 torque_results 上报 MES。 +// 设计原则(2026-10-06 简化):操作工手动点发送 → 用当前登录这人的身份 → 发不出去就是发不出去 +// (报错、留在本地 SQLite 等人处理),绝不由系统自动决定「等下次有人登录自动补传」。 +// 数据按 operator_id 隔离:仅当前登录人自己的未同步数据会被发送;其他人录入的数据静默保留, +// 不被别人代发,也不对别人可见;同一人重登后可继续发送 / 仅展示失败。 type Syncer struct { st *store.Store mes *mes.Client interval time.Duration + + // backlogWarnThreshold 待上报积压告警阈值(建议1):队列+拧紧未同步合计超过该值打 WARN; + // 可由 SetBacklogThreshold 从配置注入,<=0 回退默认 50。 + backlogWarnThreshold int +} + +// SetBacklogThreshold 从配置注入积压告警阈值(建议1);n<=0 不改(保留默认 50)。 +func (s *Syncer) SetBacklogThreshold(n int) { + if n > 0 { + s.backlogWarnThreshold = n + } } func New(st *store.Store, mc *mes.Client) *Syncer { - return &Syncer{st: st, mes: mc, interval: defaultInterval} + return &Syncer{st: st, mes: mc, interval: defaultInterval, backlogWarnThreshold: defaultBacklogWarnThreshold} } // Run 周期冲刷循环,随 ctx 取消退出。 @@ -33,6 +60,8 @@ func (s *Syncer) Run(ctx context.Context) { logx.Infof("后台同步协程已启动:每 %s 冲刷一次未上报数据", s.interval) ticker := time.NewTicker(s.interval) defer ticker.Stop() + cleanTicker := time.NewTicker(time.Hour) + defer cleanTicker.Stop() for { select { case <-ctx.Done(): @@ -42,6 +71,12 @@ func (s *Syncer) Run(ctx context.Context) { if n := s.RunOnce(ctx); n > 0 { logx.Infof("本轮同步成功 %d 条", n) } + case <-cleanTicker.C: + if deleted, err := s.st.CleanupOld(localRetentionSec); err != nil { + logx.Errorf("清理本地过期数据失败: %v", err) + } else if deleted > 0 { + logx.Infof("已清理本地 %d 条超过 30 天的离线数据", deleted) + } } } } @@ -50,13 +85,50 @@ func (s *Syncer) Run(ctx context.Context) { func (s *Syncer) RunOnce(ctx context.Context) int { n := s.flushQueue(ctx) n += s.flushTorque(ctx) + // 积压监控(建议1):待上报总量超阈值打 WARN,供日志采集/告警。 + // 区分两类积压,输出固定可匹配的日志标记(BACKLOG_ALERT_IDENTITY / BACKLOG_ALERT_NETWORK): + // - IDENTITY:当前未登录 → 数据等待当前操作人登录后继续发送(可恢复,不阻断产线); + // - NETWORK:已登录仍堆积 → 疑似 MES 网络/业务拒绝,需排查 MES 连通性与返回。 + if qc, err := s.st.PendingQueueCount(); err == nil { + if tc, err2 := s.st.PendingTorqueCount(); err2 == nil { + if total := qc + tc; total > int64(s.backlogWarnThreshold) { + hasSession := false + if ss, e := s.st.GetStationSession(); e == nil && ss != nil && ss.Token != "" { + if ss.ExpireAt <= 0 || time.Now().Unix() < ss.ExpireAt { + hasSession = true + } + } + if hasSession { + logx.Errorf("BACKLOG_ALERT_NETWORK 离线队列积压 %d 条(队列 %d / 拧紧 %d):存在有效登录态仍堆积,疑似 MES 网络或业务拒绝,请检查 MES 连通性与业务返回", total, qc, tc) + } else { + logx.Errorf("BACKLOG_ALERT_IDENTITY 离线队列积压 %d 条(队列 %d / 拧紧 %d):当前未登录,等待当前操作人登录后继续发送", total, qc, tc) + } + } + } + } return n } -// flushTorque 上报未同步拧紧结果: -// POST /api/internal/torque/report;成功标记 synced=1,失败保持 0 等待下轮重试。 +// currentSession 取当前有效的在岗登录态;无登录态或凭证已过期返回 nil。 +func (s *Syncer) currentSession() *store.StationSession { + ss, err := s.st.GetStationSession() + if err != nil || ss == nil || ss.Token == "" { + return nil + } + if ss.ExpireAt > 0 && time.Now().Unix() >= ss.ExpireAt { + return nil + } + return ss +} + +// flushTorque 上报「当前登录人」未同步拧紧结果:POST /api/internal/torque/report; +// 成功标记 synced=1,失败保持 0 等待下轮重试(同一登录人重登后续发)。 func (s *Syncer) flushTorque(ctx context.Context) int { - rows, err := s.st.ListTorqueResults("", true, reportBatchLimit) + ss := s.currentSession() + if ss == nil { + return 0 + } + rows, err := s.st.PendingTorqueResultsForOperator(ss.UserID, reportBatchLimit) if err != nil { logx.Errorf("查询未同步拧紧结果失败: %v", err) return 0 @@ -88,8 +160,16 @@ func (s *Syncer) flushTorque(ctx context.Context) int { "result": t.Result, "operator": t.Operator, } + // 用当前登录态(即当前在岗操作人)的身份发送,失败即留本地。 if _, _, err := s.mes.Post("/api/internal/torque/report", body); err != nil { - logx.Errorf("上报拧紧结果失败(id=%d sn=%s): %v", t.ID, t.Sn, err) + if errors.Is(err, mes.ErrAuth) { + // 当前登录态失效(理论上 currentSession 已拦截):跳过,等待重新登录后续传。 + continue + } + logx.Errorf("上报拧紧结果失败(id=%d sn=%s 第 %d 次): %v", t.ID, t.Sn, t.RetryCount+1, err) + if t.RetryCount+1 < maxTorqueRetry { + _ = s.st.BumpTorqueRetry(t.ID) + } continue } done = append(done, t.ID) @@ -103,15 +183,20 @@ func (s *Syncer) flushTorque(ctx context.Context) int { return count } -// flushQueue 上报未同步的离线缓存队列,payload 原样透传: +// flushQueue 上报「当前登录人」未同步的离线缓存队列,payload 原样透传: // - kind=process_done → POST /api/internal/station/report // - kind=temp_store → POST /api/internal/station/checkin // - kind=online_register → POST /api/internal/workpiece/online(上线建档) // - kind=offline_finish → POST /api/internal/workpiece/done(下线完工入库) // -// 成功标记 synced=1;失败 synced 保持 0 并累计 retry_count。 +// 每条使用当前在岗登录态 JWT 发送;成功标记 synced=1;失败 synced 保持 0 并累计 retry_count, +// 留本地等待同一操作人重新登录后续传或人工排查。仅发送「当前登录人自己」的数据,他人数据不被代发。 func (s *Syncer) flushQueue(ctx context.Context) int { - items, err := s.st.PendingQueueItems(reportBatchLimit) + ss := s.currentSession() + if ss == nil { + return 0 + } + items, err := s.st.PendingQueueItemsForOperator(ss.UserID, reportBatchLimit) if err != nil { logx.Errorf("查询待上报队列失败: %v", err) return 0 @@ -142,8 +227,13 @@ func (s *Syncer) flushQueue(ctx context.Context) int { } if _, _, err := s.mes.Post(path, json.RawMessage(it.Payload)); err != nil { + if errors.Is(err, mes.ErrAuth) { + continue + } logx.Errorf("上报队列失败(kind=%s id=%d 第 %d 次): %v", it.Kind, it.ID, it.RetryCount+1, err) - _ = s.st.BumpQueueRetry(it.ID) + if it.RetryCount+1 < maxQueueRetry { + _ = s.st.BumpQueueRetry(it.ID) + } continue } if err := s.st.MarkQueueSynced(it.ID); err != nil { @@ -153,4 +243,4 @@ func (s *Syncer) flushQueue(ctx context.Context) int { count++ } return count -} \ No newline at end of file +} diff --git a/bj_power_workstation/internal/syncer/syncer_verify_test.go b/bj_power_workstation/internal/syncer/syncer_verify_test.go new file mode 100644 index 0000000..d0d89e2 --- /dev/null +++ b/bj_power_workstation/internal/syncer/syncer_verify_test.go @@ -0,0 +1,83 @@ +package syncer_test + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "bj_power_workstation/internal/mes" + "bj_power_workstation/internal/store" + "bj_power_workstation/internal/syncer" +) + +// TestStationAuthStaleNoDataLoss 运行期验证核实3:工位登录态过期(JWT 401)时, +// 离线 syncer 暂停发送、数据保留在本地 SQLite;同一操作人重新登录(有效凭证)后继续发送,数据不丢。 +func TestStationAuthStaleNoDataLoss(t *testing.T) { + // 假 MES:Bearer=valid 返回 200,其余返回 401 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") == "Bearer valid" { + w.WriteHeader(200) + _, _ = w.Write([]byte(`{"code":0}`)) + return + } + w.WriteHeader(401) + _, _ = w.Write([]byte(`{"code":401,"message":"unauthorized"}`)) + })) + defer ts.Close() + + dbPath := t.TempDir() + "/ws.db" + st, err := store.Open(dbPath) + if err != nil { + t.Fatal(err) + } + defer st.Close() + + // 注入一条未同步拧紧结果(模拟离线缓存) + if _, err := st.InsertTorqueResult(store.TorqueResult{ + WorkOrderNo: "WO-1", Sn: "SN-1", DockCode: "DOCK01", ScrewNo: "S1", + Torque: 10, Angle: 90, Result: "OK", Operator: "张三", + }); err != nil { + t.Fatal(err) + } + + mc := mes.New(ts.URL, "tok") + mc.SetStationToken("expired") // 当前 client token(镜像真实登录) + _ = st.SaveStationSession("expired", "u", "U", 1, time.Now().Add(-time.Hour).Unix(), 0) // 登录态已过期 + + sy := syncer.New(st, mc) + ctx := context.Background() + + // 阶段A:过期凭证 → 401,syncer 整轮暂停,数据保留在本地 + n := sy.RunOnce(ctx) + if n != 0 { + t.Errorf("[核实3] 过期凭证下应暂停发送返回 0,实际 %d", n) + } + pending, _ := st.PendingTorqueCount() + if pending != 1 { + t.Errorf("[核实3] 数据应保留 1 条,实际 %d", pending) + } + list, _ := st.ListTorqueResults("", true, 10) + if len(list) == 1 && list[0].RetryCount != 0 { + t.Errorf("[核实3] 过期凭证不应 bump 重试次数,实际 %d", list[0].RetryCount) + } + if len(list) == 1 && list[0].Synced { + t.Errorf("[核实3] 过期凭证不应标记已同步") + } + t.Logf("[核实3 过期凭证] RunOnce=%d pending=%d retry=%d(数据保留在本地)", n, pending, list[0].RetryCount) + + // 阶段B:重新登录(有效凭证)→ syncer 恢复,数据成功上报 + mc.SetStationToken("valid") // 当前 client token + _ = st.SaveStationSession("valid", "u", "U", 1, time.Now().Add(time.Hour).Unix(), 0) // 登录态恢复有效 + + n = sy.RunOnce(ctx) + if n != 1 { + t.Errorf("[核实3] 重新登录后应成功发送 1 条,实际 %d", n) + } + pending, _ = st.PendingTorqueCount() + if pending != 0 { + t.Errorf("[核实3] 上报后应无待同步数据,实际 %d", pending) + } + t.Logf("[核实3 重新登录] RunOnce=%d pending=%d(发送成功,数据不丢)", n, pending) +} diff --git a/bj_power_workstation/main.go b/bj_power_workstation/main.go index cc931b6..1b2ba71 100644 --- a/bj_power_workstation/main.go +++ b/bj_power_workstation/main.go @@ -77,11 +77,38 @@ func main() { defer cancel() mc := mes.New(c.Mes.BaseURL, c.Internal.Token) + // 核实4:绑定空闲计时回调——每次以有效登录态发起的 MES 调用刷新 last_active_at, + // 证明当前操作人仍活跃在岗,后台 sweeper 据此判断是否超时自动登出。 + mc.Touch = func() { _ = st.TouchStationSession() } // 后台同步协程:联网时向 MES 补报未同步数据 sy := syncer.New(st, mc) + sy.SetBacklogThreshold(c.Backlog.WarnThreshold) // 建议1:积压告警阈值可配置(yaml backlog.warnThreshold) go sy.Run(rootCtx) + // 核实4:空闲自动登出 sweeper——周期性检查登录态空闲时长,超过 IdleLogoutSeconds 则清除 + // 本地登录态并失效 Bearer 凭证,强制换班/下一班操作工重新登录,杜绝共享终端身份错位。 + go func() { + ticker := time.NewTicker(60 * time.Second) + defer ticker.Stop() + for { + select { + case <-rootCtx.Done(): + return + case <-ticker.C: + cleared, err := st.ClearExpiredSession(c.Station.IdleLogoutSeconds) + if err != nil { + logx.Errorf("检查工位登录态空闲超时失败: %v", err) + continue + } + if cleared { + logx.Infof("工位登录态空闲超过 %d 秒,已自动登出", c.Station.IdleLogoutSeconds) + mc.SetStationToken("") + } + } + } + }() + // 拧紧数据由「工艺步骤 + 人工拧枪」驱动:工件走到需要拧紧枪的工艺步骤时,界面聚焦拧紧输入框, // 人工拧枪把扭矩值打入回车 → POST /api/tightening/record 落本地库并经同步器上报 MES。 // 故此处不再启动任何后台模拟拧紧数据源。 diff --git a/bj_power_workstation/web/static/index.html b/bj_power_workstation/web/static/index.html index 1fdeff4..7c33088 100644 --- a/bj_power_workstation/web/static/index.html +++ b/bj_power_workstation/web/static/index.html @@ -6,7 +6,7 @@ 工位终端 - + diff --git a/临时.md b/临时.md deleted file mode 100644 index b964dd4..0000000 --- a/临时.md +++ /dev/null @@ -1,347 +0,0 @@ -# 客户问题.md 独立审计报告 - -- 审计日期:2026-10-05 -- 审计对象:`D:\hardman\bj_power\客户问题.md`(含全部「孙彦飞答复:已完成」断言) -- 审计方式:四路并行代码取证(WMS 仓储/质量、MES 生产排产、MES 现场工艺质检、跨端一致性)+ 审计人亲自复核高危项 + 行业标准检索 -- 审计口径(用户六维度):业务闭环 / 内存炸弹 / 分页 / 多端业务关联 / 不可复用页面 / 不可共用枚举 -- 结论性质:**只读审计,未改动任何代码**。本文件给出判定与整改建议,供拍板后另行授权实施。 - ---- - -## 0. 结论摘要(findings-first) - -**一句话:客户问题.md 里「已完成」并不等于「已正确」——约 6 成断言在代码层成立,但仍有 3 个 P0 级缺陷(越权放行、处置枚举缺项导致闭环断、状态枚举越界静默失败)和一批 P1 级「闭环断点 + 内存炸弹 + 域残留 + 假多页面」,当前实现不是最优方案。** - -三句话展开: -1. **有真 bug(P0)**:质检三类记录提交存在**越权放行漏洞**;不合格处置**缺「报废/让步接收」**两条路;WMS→MES 备料单状态用了 MES 不认识的值,**失败被静默吞掉**。 -2. **闭环没真正闭上(P1)**:「日排产→备料→出库→AGV」不是事件驱动,靠人每天点按钮;四态「预警」靠页面被打开才喂数;排产不阻断库存但也无预警。 -3. **架构味道不对(P1)**:物料档案**两库双向双写**(违反单一真源);WMS 一个组件挂两个菜单、keep-alive 名错配;检验域/枚举**三端各写一份且值域不一致**,WMS 残留 process/finished 死枚举,MES 的 QC_PROCESS 是**恒空页签**。 - -**行业标准对照(ISA-95 / MESA)**:标准明确要求「一个系统只干一件事,系统之间是接口而非功能重复」,L3(MES) 独占**质量作业与处置**,WMS 独占**库存与库位**;QA 处置必须「**单入口、由合格质量人员签名、单一签名同步库存状态**」。当前实现的多处「双写、双入口、权限洞、WMS 残留检验域」正与这三条直接冲突。 - ---- - -## 1. 判定总表 - -| # | 客户问题.md 断言 | 判定 | 关键证据 | -|---|---|---|---| -| WMS-入库1 | 图号、检验单号强制输入 | ✅ 成立 | `inbound.go:186-197` 前后端双校验 | -| WMS-入库2 | 归属(工单/科技项目)必选 | ⚠️ 部分 | 前端必填 `Inbound.vue:104`;后端无校验、缺省归 `other`,`inbound.go:297,647-654` | -| WMS-入库4 | 库位按最近入库自动推荐 | ✅ 成立 | `zone_recommend.go:15-41` + `Inbound.vue:528-545` | -| WMS-入库5 | 批次号=图号-日期-随机编码 | ⚠️ 部分 | 实为**顺序流水**非随机,`inbound.go:656-676`;非事务上下文有并发重号窗口 | -| WMS-出库1 | 工单备料出库由 MES 排产自动生成 | ❌ 不成立 | WMS 侧仅手工页 + 内部接口,无排产自动建单;`Outbound.vue:415-443`、`routes.go:86-87,251-255` | -| WMS-出库3 | 通用出库类别单选+手填 | ✅ 成立 | `outbound.go:509-516` | -| WMS-出库4 | 箱号仅记录无约束 | ✅ 成立 | `schema/outbound_order.go:55` | -| WMS-质3-2 | 来料检字段齐备 | ✅ 基本成立 | `schema/inspection_record.go`(记录日期为自动,无独立输入) | -| WMS-质3-6 | 检验数≠合格数强制处置 | ⚠️ 部分 | 前端强制 `Inspection.vue:212-216`;后端不校验 `inspection.go:135-162` | -| WMS-质3-6 | 处置含退货/换修/让步接收/报废 | ❌ 不成立 | 后端只 4 值且**无「让步接收」**;「让步接收」全仓零命中 | -| WMS-质3-2 | 检验单号自动传递到入库 | ⚠️ 部分 | 实为入库检测单号→检验页继承(方向相反),且靠字符串弱关联 `inspection.go:181`、`inbound.go:256-267` | -| WMS-库存3 | 锁定量描述错误已修复 | ✅(前端)/ ⚠️(后端) | 前端列已移除;后端字段/机制仍在运行 `schema/inventory.go:64` | -| WMS-库存2 | 物料汇总类型加「其它」 | ✅ 成立 | `Inventory.vue:533`、`stock.go:45-50` | -| WMS-库存5 | 盘点(冻结/解冻) | ✅ 成立 | `stocktake.go:173-182,448-454,541-547` | -| WMS-*11 | 成品入库独立菜单 | ✅ 成立 | `router/index.js:14`、`routes.go:186-191` | -| WMS-*8 | 半成品不再显示成品 | ✅ 成立 | `Semi.vue:133`、`misc.go:301` | -| WMS-新6 | 入库禁自动建档 | ✅ 成立 | `inbound.go:200-206` | -| WMS-新6 | 物料档案唯一主数据真源 | ⚠️ 部分 | **两库对等双向双写**,MES 可反向在 WMS 建档 `material.go:281-295` | -| WMS-*1 | 区域按货架号+位置号定位 | ✅ 成立 | `zone.go:14-20,92-97` | -| MES-生产1 | 新建工单数量/完成日期/创建人 | ✅ 成立 | `WorkOrder.vue:129-133,56-61`、`workorder.go:106` | -| MES-生产3 | 自动排产(平均/固定日产) | ✅ 成立 | `dailyplan.go:502-529` | -| MES-生产4 | 可生产套数公式 | ✅ 成立(有口径偏差) | min 取法正确 `producible.go:178-184`;但工单范围硬限 `[today,+59]` `producible.go:110-111` | -| MES-生产9 | 日排产排序改从前到后 | ✅ 成立 | `dailyplan.go:289-292`、`DailyPlan.vue:312` | -| MES-生产12 | 多工单分栏区分 | ✅ 成立 | `DailyPlan.vue:97-167` | -| MES-生产5 | 备料单自动同步 WMS | ⚠️ 部分 | 台账同步+自动出库有,但**触发为人工按钮** `MaterialRequest.vue:31`;**AGV 默认不触发** `schema/material_request.go:55` | -| MES-生产11 | 台账四态(齐套/未齐套/预警/未到货) | ⚠️ 部分 | 判定码在 `misc.go:360-371`;「预警」依赖 WMS 页面被打开喂数,否则静默失效 | -| MES-生产10 | 锁库联动已移除、只预警不阻断 | ⚠️ 部分 | 移除为真;但排产时**无任何预警** `dailyplan.go:39-126` 不查库存 | -| MES-现场4 | 绩效上机时间/NG 中文化/自动上报 | ✅ 成立 | `Performance.vue:51,147-164`、`processflow.go:705-709` | -| MES-现场13 | 滚筒线缓存做成可配置项 | ⚠️ 部分 | 开关存在但**无消费方** `settings.go:30-31`、`Settings.vue:30-33` | -| MES-新3 | 工位绑定单值工艺 | ✅ 成立 | `schema/station.go:27` | -| MES-新3 | 保存/排产/下发/报工**四处**强校验 | ❌ 不成立 | 保存/排产/报工三处有,**下发只查空** `workorder.go:351-354`、`plc.go:38-41` | -| MES-现场7 | 检测确认=检验员审核签字 | ⚠️ 存疑 | `needCheck` 与 `needInspectorSign` 是**两个独立字段** `schema/process_step.go:31-33` | -| MES-现场3-2 | 采集方式可配 NONE | ✅ 成立 | `schema/process_step.go:29`、`ProcessFlow.vue:117-119` | -| MES-现场1 | 两类签字逐步骤可勾选+服务端强校验 | ✅ 成立 | `workpiece.go:443-490`、`sign.go:46-102` | -| MES-新1 | 拧紧查询并入工件追溯 | ✅ 成立 | `router/index.js:11-34`、`Trace.vue:71-80` | -| MES-新6 | 工件追溯显示过程检验/工位/人员/时间/试验数据 | ✅ 成立 | `workpiece.go:658-724`、`Trace.vue:53-80,137-175` | -| MES-现场10 | 完工确认弹窗二次确认+扫 SN | ⚠️ 部分 | MES 页签按**工单号**、无弹窗 `Inspect.vue:105-119,575-588`;带弹窗的实现在**工位终端** `InspectPanel.vue:234-240` | -| MES-新15 | 过程检/完工检应有巡检终端录入、后台只读 | ⚠️ 部分 | 录入 dialog 已移除;但**仍保留「处置」写操作** `QualityInspection.vue:85-103,206-214` | -| MES-新15 | 完工检由质检员录、合格才回流 | ⚠️ 部分 | 回流逻辑正确 `inspection.go:196-201,323-386`;但**权限层未隔离**(见 P0-1) | -| MES-工位1 | 报检两个签字+三处汇总 | ✅ 成立 | `sign.go:12-45`、`workpiece.go:443-490` | - ---- - -## 2. 高危问题(P0)——必须整改 - -### P0-1 质检记录提交存在越权放行漏洞(安全 + 架构违规) -- 证据:`bj_power_mes\internal\handler\inspection.go:23-39` - ```go - qualityCats := map[string]bool{"QC_PROCESS": true, "FINAL": true, "INCOMING": true} - if qualityCats[req.Category] && userHasPerm(r, svcCtx, "produce.quality:edit") { - // 放行 - } else if code, ok := categoryPerm[req.Category]; ok && !userHasPerm(r, svcCtx, code) { - // 拦截 - } - // 注意:categoryPerm 无 QC_PROCESS/FINAL/INCOMING 键 → 未持质检权限时 ok=false → 两个分支都不成立 → 直接落到 CreateInspection - ``` -- 实证:`D:\hardman\bj_power\bj_power_mes\internal\handler\inspection.go` 已由审计人亲自复核确认。 -- 叠加问题:`logic\seed.go:34` 给 `OPERATOR` 角色本就直接授予了 `produce.quality:edit` → 「完工检=质检员专属」在权限模型上根本不成立。 -- 危害:①任何持 JWT 的非质检角色可提交 FINAL/QC_PROCESS/INCOMING 质检记录并触发成品回流;②审计追溯失信。 -- 行业标准:ISA-95 L3 与 21 CFR Part 11 / GMP Annex 11 明确「**仅经授权的合格质量人员可变更物料/产品状态,须角色隔离(segregation of duties)**」。当前实现直接违反。 -- 建议:`categoryPerm` 补 `FINAL/QC_PROCESS/INCOMING` 三类映射并**改为「未持权限一律拒绝」**(默认拒绝,而非默认放行);从 `OPERATOR` 角色移除 `produce.quality:edit`(或新建独立「质检员」角色独占该权限)。 - -### P0-2 不合格品处置闭环缺项(报废 / 让步接收) -- 证据(表):`bj_power_mes\internal\logic\inspection.go:300` - ```go - if !oneOf(disposalType, "退货", "返修", "退换") { return errors.New("处置类型仅支持 退货/返修/退换") } - ``` - 而同一文件 `:334` 却判断 `req.DisposalType == "报废"`——**处置接口永远设不出「报废」**,该分支恒不可达。 -- 证据(图):`bj_power_mes\schema\inspection_record.go:54` 注释标称 `退货/返修/退换/报废`;`QualityInspection.vue:90-92` 前端下拉仅 `退货/返修/退换`。 -- 证据(缺项):「让步接收」在 WMS、MES 全仓 `*.go/*.vue/*.js` **零命中**(历史构建产物 `web/static/assets/format-BfUs1lnF.js` 有残留文案,属旧 bundle)。 -- 客户原始要求(客户问题.md:69 / 250):「退货、换修、让步接收、报废」「区分退货、返修、退换」。 -- 危害:成品完工检不合格后没有「报废」的正确落库路径,也没有「让步接收(让步放行)」路径 → 不合格品去向不闭环,与 ISA-95「QA 处置必须覆盖 release/reject/rework/quarantine/conditional release」冲突。 -- 建议:WMS `disposal_type` 与 MES `disposalType` **统一为一套值域**(退货/返修/退换/报废/让步接收),前后端与映射表 `wmsDisposalType()` 同步补齐;补「让步接收」并明确其库存质量状态置「合格(让步)」。 - -### P0-3 备料单状态枚举越界 + 业务错误被静默吞 -- 证据(发出方):`bj_power_wms\internal\handler\agv.go:253` - ```go - _ = ctx.Mes.MarkStatus(ctx0(), row.RequestNo, "WAIT_SEND") // AGV 取消 → 回退待发料 - ``` -- 证据(接收方):`bj_power_mes\internal\handler\production\material.go:142` - ```go - if req.Status != "DELIVERING" && req.Status != "DONE" { httpx.Fail(w, 3106, "非法状态"); return } - ``` -- 证据(吞错):`bj_power_wms\internal\mesclient\client.go:278` 只 `if resp.StatusCode >= 300` → MES 业务码 3106(HTTP 200)被判成功。 -- 实证:三处均已由审计人复核。 -- 危害:AGV 任务取消后,MES 备料单状态**回退失败且无任何告警**,长期停在 `DELIVERING`,账实不符。 -- 建议:MES 放开 `WAIT_SEND`(或统一改名 `PENDING`);`mesclient` 增加业务码解析,`code != 0` 视为失败并记日志/告警。 - ---- - -## 3. 内存炸弹 / 分页清单(P1) - -> 判定口径:**列表分页必须下推到 SQL(LIMIT/OFFSET);聚合/汇总/导出必须有边界(时间窗或游标)**。ent 官方与业界共识:`Offset/Limit` 对大数据集是「真扫描真丢弃」,而「先 All 再切片」是明确的 OOM/GC 反模式。 - -### 3.1 先全量 All,再内存切片分页(假分页) -| 接口 | 证据 | 备注 | -|---|---|---| -| 库存查询 `/api/stock/query` | `stock.go:246` All → `:330-371` `order[start:end]` | 已复核 | -| 物料汇总 `/api/stock/material-summary` | `stock.go:481` → `:577-618` | | -| 工单备料台账 `/api/ledger/query` | `misc.go:467` All → `:495-504` 内存切片 + `:484` 内存过滤 | 已复核 | -| 待检清单 `/api/inspection/pending` | `inspection.go:1124` → `:1205-1217` | | - -### 3.2 无分页/无边界聚合(页面常驻调用,最易踩坑) -| 接口 | 证据 | -|---|---| -| 区域汇总 `/api/stock/zone-summary` | `stock.go:841-852` 全量库存 + 全表物料 | -| 区域列表 `/api/zone/list` | `zone.go:148-149` 每次全量库存 | -| 空位推荐 `/api/zone/vacant` | `zone.go:360-374` 全量节点+库存 | -| 缺货预警 `/api/stock/shortage` | `stock.go:1202-1227` 物料 All + 逐物料 N+1 | -| 缺料补货 `/api/stock/material-demand` | `stock.go:1342-1382` 物料 All + 逐物料 N+1 + 全量覆盖写 | -| 检验统计 `/api/inspection/stats` | `inspection.go:983-1019` 全量检验记录 Go 侧聚合 | -| 大屏概览 `/api/display/overview` | `internalapi.go:77-94` 全量批次件 | -| 导出类 | `inbound.go:616`、`outbound.go:767,779-795`、`inspection.go:426`、`material.go:537`、`stock.go:743,787`(`PageSize:1000000`) | - -### 3.3 MES 侧 -| 位置 | 问题 | 证据 | -|---|---|---| -| MES 工单列表 | 全量无分页 | `workorder.go:298` `.All()`;`Inspect.vue:486-491` 无参全量 | -| MES 备料单列表 | 全量无分页 | `material.go:408` | -| MES 绩效报表 | 全量 All + 内存分页 + O(n²) | `processflow.go:685,754-764,639-650` | -| 待签任务 | 全量 All + 内存分页 | `sign.go:115-191` | -| 待完工检 | 无界 `Select(sn)` + 大 IN | `inspection.go:400-410` | -| 全景流程卡 | 全表 Count+All | `processcard_model.go:220-221,272,277` | -| 可生产套数 | N+1(逐工单 2 次查询) | `producible.go:79-95`、`usage.go:45,57` | - -### 3.4 前端主动拉全量(抵消后端分页) -- `Inspection.vue:366,387` `pageSize:99999`;`Outbound.vue:51,182` `pageSize:200`。 - -**建议**:将 3.1/3.2 的接口改为 SQL 侧分页(`Count + Limit/Offset`,或聚合改为 `GROUP BY` 下推 SQL);导出改流式/游标;`zone/list`、`zone/vacant` 加缓存或改为「区域维度」按需查询;`stock/shortage`、`material-demand` 消除 N+1(一次 `IN` 批量取库存)。 - ---- - -## 4. 多端业务关联 / 双写清单(P1) - -| # | 问题 | 证据 | -|---|---|---| -| 4.1 | **物料档案两库对等双向双写**(WMS→MES push + MES→WMS upsert),字段 schema 不一致(WMS 有 `is_batch_managed/is_serial_managed`,MES 有 `syncPending`),`sn_mode` 传 0 时保留本地值会**长期分叉** | `wms material.go:20,281-295`;`mes materialsync.go:14-23,125-132` | -| 4.2 | 需求量/已发量「同一语义两处写」(MES `material_request.reqQty/sentQty` vs WMS `order_material_ledger/total_qty/out_qty`),靠调用同步、失败即不一致 | `mes material.go:212,303`;`wms internalapi.go:27-68` | -| 4.3 | WMS 需求快照 `material_demand` 全量覆盖、**页面被打开才喂数** → 四态「预警」静默失效 | `wms stock.go:1293-1338`(注释自认) | -| 4.4 | 孤表残留:`semi_finisheds` 已声明废弃但 schema/迁移仍在;无调用方内部接口 `stock/lock|unlock|query`、`material/list-all` | `wms schema/semi_finished.go:10-11`、`migrate/schema.go:685`、`routes.go:250,251,253,267` | -| 4.5 | 工位终端调用已退役 `/api/internal/bom`(MES 未注册该路由,BOM 表已退役)→ 恒 404 | `workstation workpiece.go:50`;`mes db/db.go:194-198` | -| 4.6 | 拧紧跨端上报丢 `step_id/step_name`(终端本地表有、上报无、MES 表也无) | `workstation store.go:32-33`、`syncer.go:80-90` | - -**建议**:确立**物料主数据单向真源**(推荐 WMS 为唯一写入口,MES 只读;或反向,二选一),另一侧只读并保留 `sync_pending` 重试;统一 `ownership_type`(去掉 `none`);删除孤表与无调用方接口;修正终端 `/bom` 调用。 - ---- - -## 5. 不可复用页面 / 不可共用枚举清单(P1) - -### 5.1 假多页面(一组件多菜单) -| 系统 | 菜单 | 组件 | 区分方式 | 证据 | -|---|---|---|---|---| -| WMS | 区域维护 `zone:view` / 物料档案 `material:view` | 同一个 `BaseData.vue` | `props:{mode:'zone'\|'material'}` | `router/index.js:23-24`、`BaseData.vue:15-18` | -| WMS | 来料检验 | `Inspection.vue` | 残留 `meta.inspectionType` | `router/index.js:18`、`Inspection.vue:18,772-777` | -| MES | 质量检验 / 巡检终端 | 两页同操作 `inspection_record` | 一读一写 | `QualityInspection.vue`、`Inspect.vue:153,636` | - -> 结论:WMS `BaseData.vue` 一组件挂两菜单,违反「不可复用页面」铁律,且两路由 `componentName` 同为 `BaseData`,`keep-alive :include` 去重后仅缓存一份,**两页状态可互串**。另 `Inspection.vue` 真名 `Inspection` 与 meta `componentName:'InspectionIncoming'` 不符 → **该页 keepAlive 实际失效**。 - -### 5.2 枚举共用 / 漂移 -| # | 问题 | 证据 | -|---|---|---| -| A | WMS `inspection_type` 三值(incoming/process/finished)**域已迁 MES 但枚举/筛选项/导出标签/help 未收口** → 用户可筛到空数据 | `Inspection.vue:772-777`、`excel.go:214-224`、`help.js` | -| B | MES 同一「过程检」被拆成 `PROCESS`(PAD) 与 `QC_PROCESS`(车间质检),**`QC_PROCESS` 全仓无写入方 → 质量检验页过程检页签恒空** | `schema/inspection_record.go:17,29`、`inspection.go:92`、`QualityInspection.vue:136` | -| C | MES `INCOMING` 空壳枚举(来料检账在 WMS) | `schema/inspection_record.go:16`、`inspection.go:92` | -| D | 结论枚举不一致:WMS `未检/合格/不合格` vs MES `OK/NG/PARTIAL` | `wms schema:32`、`mes schema:35` | -| E | 处置枚举不一致:WMS `NONE/RETURN/SCRAP/PARTIAL(+REWORK)` vs MES 中文 `退货/返修/退换`,靠 `wmsDisposalType()` 单点桥接(退换→RETURN,语义丢失) | `inspection.go:70-80,300` | -| F | 归属类型 WMS 入库单 `none` vs 其他表 `other` 两套 | `schema/inbound_order.go:38-39`、`inbound.go:647-654` | -| G | Trace.vue 兜底映射 `row.category==='FINAL'?'完工检':'过程检'`,任一非 FINAL 类都被显示成「过程检」 | `Trace.vue:140` | -| H | 前端记录查询下拉缺 FINAL/QC_PROCESS/INCOMING(同表共用枚举导致筛选面不全) | `Inspect.vue:456-462` | - ---- - -## 6. 域归属问题 - -- **WMS 残留过程检/完工检**(与「WMS 仅来料检」定稿冲突):筛选项 `Inspection.vue:772-777`、导出标签 `excel.go:214-224`、schema 注释、`help.js` 整段 —— 四处未收口。 -- **MES 过程检无落地入口**(最严重):`QC_PROCESS` 无写入方,页签恒空;实际过程巡检走 `PROCESS`,追溯过滤 `CategoryIn("QC_PROCESS","FINAL")` 也漏掉真实数据。 -- 建议:WMS 侧彻底删除 process/finished(枚举、筛选项、导出、help、schema 注释);MES 明确「过程检」唯一枚举(建议统一为 `PROCESS`,废弃 `QC_PROCESS`),消除恒空页签。 - ---- - -## 7. 「是否最优方案」逐域判定 - -| 域 | 当前方案 | 是否最优 | 说明 | -|---|---|---|---| -| 质检单入口 | 后台质量检验页只读 + 巡检终端录 FINAL | **方向对,未达标** | 权限漏洞 + 后台仍可「处置」写库,未真正单入口 | -| 完工回流 | 完工确认不回流、完工检合格才回流 | ✅ 方向最优 | 与 ISA-95 一致;但权限与 UI 文案未对齐 | -| 质检域划分 | 来料=WMS、过程/完工=MES | ✅ 方向最优 | 符合 ISA-95 职责边界;但枚举/筛选项残留 | -| 物料主数据 | 两库对等双向双写 | ❌ 非最优 | 违反 MDM 单一真源;建议定单向 | -| 排产→备料→AGV | 人工点按钮生成 + 页面喂数 | ❌ 非最优 | 非事件驱动,闭环断点;建议事件/定时驱动 | -| 库存分页 | 先 All 再内存切片 | ❌ 非最优 | 反模式,10 万级即 OOM 风险 | -| 工位绑定 | 单值工艺 + 三处校验 | ⚠️ 不完整 | 缺「下发」校验,路线漂移窗口 | -| 页面组织 | WMS 一组件两菜单 | ❌ 非最优 | 违反「不可复用页面」 | - ---- - -## 8. 整改优先级(拍板后可一次整体实施) - -**P0(安全/正确性,建议优先)** -1. 质检提交改为默认拒绝 + `categoryPerm` 补三类;`OPERATOR` 剥离 `produce.quality:edit`。 -2. 处置枚举统一补「报废/让步接收」,前后端 + `wmsDisposalType()` 同步。 -3. MES 放开 `WAIT_SEND`;`mesclient` 解析业务码,非 0 告警。 - -**P1(闭环/一致性)** -4. 库存/台账/待检/汇总类接口改 SQL 分页与聚合下推,消除内存炸弹与 N+1。 -5. 物料主数据定单向真源;统一 `ownership_type`。 -6. 备料单生成改事件/定时驱动;AGV 联动与四态喂数去人工依赖。 -7. WMS 彻底清理检验域残留(枚举/筛选/导出/help/schema 注释);MES 统一过程检枚举。 -8. 拆 `BaseData.vue` 为两个独立页面;修正 `Inspection.vue` keep-alive 名;补 keep-alive include。 -9. 「下发」补绑定一致性校验;澄清 `needCheck` 与 `needInspectorSign` 语义。 -10. 清理孤表 `semi_finished.go`、无调用方接口、终端 `/bom` 死调用;修正工位终端「下线即回流」文案。 - ---- - -## 9. 备注 - -- 本报告所有代码事实均来自工作区当前文件内容(`git status` 显示部分文件为未提交改动 M / 未跟踪 ??),以**磁盘实际内容**为准。 -- 「让步接收」唯一残留见历史构建产物 `bj_power_wms\web\static\assets\format-BfUs1lnF.js`(旧 bundle,当前 `index.html` 未引用),属交付一致性风险,建议清理历史 bundle。 -- 本文件为审计结论,**未改动任何源码**;如需实施,请明确授权范围(P0 优先 / 全量),再一次性落地。 - ---- - -## 10. P0 整改落地(2026-10-05,已授权实施) - -用户认可审计,P0 三条授权「立刻改」。已落地(代码改动 + MES 前端 `npm run build` 通过,Go 侧未编译): - -- **P0-1 越权放行**:`mes/internal/handler/inspection.go:22-48` 权限判断改为「质量三类(FINAL/QC_PROCESS/INCOMING)必须持 `produce.quality:edit` 才放行,未持或未知类型一律拒绝」。`mes/internal/logic/seed.go` 从 `OPERATOR` 角色剥离 `produce.quality`/`produce.quality:edit`(新建角色直接去除;存量角色经 `dropCodes` 在 seed 启动时回收——因 `mergeCodes` 仅并集不撤销)。`mes/frontend/Inspect.vue:591` 完工检页签 `canFinal` 由 `canDone` 改为 `can('produce.quality:edit')`,与「质检员专属」对齐。 -- **P0-2 处置缺项**:`mes/internal/logic/inspection.go:300` 白名单补「报废/让步接收」;`mes/frontend/QualityInspection.vue:93-94` 下拉补两项。`报废` 已在 `finishedInspectionInbound:334` 走「不入库」路径;`让步接收` 目前仅记录(与合格回流不重复),是否需联动回流待用户确认(避免重复入库)。 -- **P0-3 状态越界(根因=跨系统枚举漂移)**:WMS 把自家词 `WAIT_SEND` 塞给用 `PENDING/LOCKED/DELIVERING/DONE` 词表的 MES,且 `mesclient.MarkStatus` 只判 HTTP 状态。`mes/internal/handler/production/material.go:142-147` 接收方放开 `PENDING`;`wms/internal/handler/agv.go:252-257` 取消 AGV 改回退 `PENDING` 并捕获错误 + `EventLog` 告警;`wms/internal/mesclient/client.go:265-289` 解析 body 业务码,`code!=0` 视为失败返回。统一到 MES 词表,消除枚举漂移。 - -### 物料档案「双写 vs 单一真源」A/B 拍板结论 -- 审计 P1-4.1 指「两库双向双写违反 MDM」;但代码实测(`materialsync.go`、`product.go:115/155`、`routes_production.go:184`)确为**双向同步(立场A)**,与用户此前「两库两份数据、保持幂等、互相同步」决策一致。 -- **建议:保持立场A**。理由:①单团队(SunYF)运维,无多团队治理诉求;②代码已按 A 落地(带 `sync_pending` 重试);③改 B(MES 只读)需重构本地 material 表 + 推送逻辑,收益低、风险高。审计的 MDM 批评在「多团队/强合规」场景成立,本项目约束下 A 更优。working_memory 旧记「实时代理视图、无同步」已更正。 - ---- - -## 11. 深度审计(第二轮,2026-10-05)— 安全 / 并发 / 闭环 / 终端 / 死代码 - -> 说明:第一轮偏「面」(对照客户问题.md),本轮往「里」钻。五路并行取证(终端全量 / 事务并发 / 鉴权面 / 全链路状态机 / 死代码)+ 审计人亲自复核最高影响 5 条。**加「✅已复核」者为审计人亲验属实**,其余为 agent 取证结论(附路径:行号可复核)。 - -### 11.1 P0 安全(新增,本轮最严重) - -**S-P0-1【✅已复核】`POST /api/v1/seed` 未纳入权限映射 → 任意登录用户可重置 admin 密码(提权)** -- `internal/handler/routes.go:21` 把 `/seed` 注册在 `jwtAdmin` 组(带 `permissionGuard`),但 `internal/handler/perm.go:13-58` 的 `pathPermMap` **无** `POST:/api/v1/seed`;`perm.go:93-98` 未命中即放行。 -- `internal/logic/seed.go:60-75` seed 会**无条件**把 admin 密码重置为 `123456` 并置 ENABLED + SUPER_ADMIN 角色。 -- 危害:任何持有效 JWT 的最小权限账号调用该接口 → admin 被重置 → 接管系统。**必须立刻修**(补 pathPermMap 或加 admin 门)。 - -**S-P0-2【✅已复核】MES 三条内部路由未挂 `internal(...)` 鉴权 → 任意外部可直呼** -- `internal/handler/routes_production.go:92-94` `/api/internal/station/pause`、`:95-97` `/api/internal/station/state`:未包 `internal(...)`(同文件其余约 40 条均包)。 -- `:47-49` `/api/internal/dashboard/stream` 直挂 `serverCtx.SSE.Handler`(`internal/sse/sse.go:57-81` 无鉴权)→ 无名可订阅看板事件流。 -- 危害:任意人可停/恢复任意工位、读工位状态、订阅看板事件。 - -**S-P0-3【已复核】JWT 密钥 = 内部 Token = CLI 管理员密码 = 硬编码 `Hardman_2026`** -- WMS `internal/config/config.go:19-23/26-28/54-56`、MES `etc/bj_power_mes-api.yaml:24-25/28-30/32-34`、终端 `internal/config/config.go:10` 同值。 -- 危害:拿到源码/默认值即可离线签发 SUPER_ADMIN JWT,绕过全部守卫;三种信任根未隔离。 - -**S-P1 WMS 大批写接口仅「登录即放行」**(无 `requirePerm`):`routes.go:118-121`(stock lock/unlock/deduct/check)、`:71,75`(inbound create/batch-excel)、`:86-87`(outbound create/general)、`:130-135`(inspection\*)、`:177-178`(semi\*)、`:225`(attachments/delete)、`:74,89,116,137`(导出无码,而 `material/export`、`stocktake/export` 却有码)→ 口径不一致。 - -**S-P1 MES permissionGuard「未注册即放行」**:除 `CreateInspectionHandler` 外 MES 无 handler 级权限校验,`perm.go` 未注册的写接口对任意登录用户开放(`PUT/DELETE /daily-plans`、`DELETE /alert/rule`、`POST /workpiece/online|done`、`POST /station/report` 等约 24 条);`perm.go:20,32` 两条映射为死条目。 - -### 11.2 P0 数据一致性 - -**C-P0-1【✅已复核】出库/退库台账「读改写绝对赋值」→ 并发丢失更新** -- `bj_power_wms/internal/handler/outbound.go:278-308`:`newOutQty = ledgerNow.OutQty + actualQty` → `SetOutQty(newOutQty)`(绝对覆盖,非原子 `AddQuantity`);`return_order.go:336-346` 同理 `SetReturnedQty`。 -- 对比:同工程库存扣减已用 `AddQuantity(-qty).Where(QuantityGTE(...))`(`outbound.go:194-198`)→ 台账这条是漏改。 -- 危害:同工单同物料并发出库/退料 → 台账 `out_qty`/`returned_qty` 少记;台账是唯一真源,在途/线边全由其派生 → 全线对账错。 - -**C-P0-2 WMS `/api/internal/stock/deduct` 无幂等键**:`outbound.go:117` 每次新生成 `OB` 单号;MES `wmsclient/client.go:565-616` 不传幂等键;超时(5s)/重试/双击 → 重复出库 + 二次扣库存。 - -**C-P0-3 MES 自动出库并发超发**:`internal/logic/material.go:236-303` `need=reqQty−sentQty` 先读后扣、`sentQty` 事后 `AddSentQty`;并发触发两请求都读 `sentQty=0` → 各扣一次。 - -**C-P1 编号/幂等/事务**: -- 备料单号 `MR%d`(UnixNano) **无唯一约束**(`schema/material_request.go:25`)→ 同刻重号静默(`logic/line.go:114`、`logic/qty_report.go:181`)。 -- WMS Excel 导入单事务内用**非事务连接**生成单号/批次号(`handler/excel.go:384,415` → `inbound.go:73-105,659-676`)→ 同导入多行撞唯一索引整单失败 / 空批次错误合并。 -- `internal/db/db.go:318-321` 唯一索引创建失败被 `slog.Warn` 吞 → 存量库若有重复值则「DB 兜底」全部失效。 -- 完工 `DoneWorkpiece`(`logic/workpiece.go:586`)无状态 CAS + 无幂等 → 重复完工:工单 `finishedNum`、排产 `completedQty` 丢失更新 + 反冲双扣(`scan.go:20-22,39-47`)。 -- 报工 `workpiece_process` 无唯一约束 + 状态校验在事务外(`workpiece.go:255-299`)→ 并发重复实绩/越序。 -- 物料双写 last-write-wins 丢字段 + WMS→MES 推送失败**无 pending 兜底**(`handler/material.go:20-36` 仅 `logx.Errorf`),且 MES→WMS 重推会覆盖并清 `sync_pending`(`logic/materialsync.go:82`)→ 静默永久丢失本地改动。 - -### 11.3 P0 工位终端 - -**W-P0-1【✅已复核】报工/上线/完工/接料操作人恒落为 `system` → 按人绩效失真** -- 终端上报带 `operator`(`internal/handler/report.go:84`),但 MES `ReportProcessReq`(`internal/logic/workpiece.go:218-230`)**无 Operator 字段**;内部路由无 JWT,`operator(r,"")`(`internal/handler/production/production.go:26-37`)恒回退 `"system"`。上线/完工/接料结构体同样无 Operator。 -- 危害:MES 绩效按 operator 分组恒为 system;终端「我的工作量」查不到自己数据。 - -**W-P0-2 离线队列重传不解析 MES 业务码 → 被业务拒绝的报文被标 `synced=1` 静默丢弃** -- 在线路径正确解析(`internal/handler/report.go:100-115`),重传路径(`internal/syncer/syncer.go:144-153`)只要 HTTP 2xx 即 `MarkQueueSynced`;MES 业务失败=HTTP200+code≠0 → 静默丢单、不重试、无告警;`retry_count` 无上限无死信。 -- 叠加非幂等:拧紧重复插 `torque_record`、完工重复 +1、上线重传误触发 WMS 半成品出库(`logic/workpiece.go:95-108,176-198`)。 - -**W-P0-3 拧紧步骤关联丢失**:本地 `torque_results.step_id/step_name`(`internal/store/store.go:32-33`)录入强制(`handler/tightening.go:75-78`),但上报(`syncer/syncer.go:80-90`)丢弃、MES `TorqueReq`(`logic/torque.go:18-30`)无此字段 → 拧紧「步骤维度」追溯断裂。 - -**W-P1 死调用**:终端 `GET /api/internal/bom`(`handler/workpiece.go:50`)MES 未注册恒 404(上线「领料确认」必挂);`GET /stations`(`handler/proxy.go:74`)前缀错命中 MES 静态页,返回 HTML 被当 JSON 拆成字符数组(工位下拉乱值)。 - -**W-P1 越权**:终端 JWT 只验签不验权限、完全信任客户端 `stationNo`、密钥共享(同 S-P0-3);本地 `users` 表 / `event_log` 表 / `internal/tightening` 包均为死代码。 - -### 11.4 全链路闭环断点(P1) - -| # | 断点 | 证据 | 后果 | -|---|---|---|---| -| 1 | 备料单生成纯人工按钮(无定时/事件) | `MaterialRequest.vue:31,291` | 漏点即停线 | -| 2 | AGV 下发 + 刷新均人工按钮,无自动轮询 | `Agv.vue:95,114` | 不点刷新→任务永停 DELIVERING | -| 3 | **出库单「已送达」死分支**:`RelatedOutboundNo` 全仓无写入 | `agv.go:172`(只读)✅已复核 | 出库单永不闭环 | -| 4 | 四态「预警」靠打开库存页喂 `material_demand` | `stock.go:1310-1338`、`misc.go:360-371` | 不开页→预警静默失效 | -| 5 | 备料单状态零流转校验 | `logic/material.go:462-475` | 可跳变写入 | -| 6 | 在途/线边口径跨层(工单级台账 − 行级 receipt 汇总) | `logic/delivery.go:72-97` | 多行/补料场景分叉 | -| 7-12 | 反冲/成品回流/处置联动失败仅记 EventLog,无重试/对账/补偿 | `logic/workpiece.go:648`、`logic/inspection.go:363-379` 等 | 账实长期不符 | - -### 11.5 死代码 / 孤儿(P2) - -- **历史 bundle 严重残留**:WMS `web/static/assets` 99 文件仅 46 可达(**53 孤儿**);MES `public/assets` 303 文件仅 49 可达(**254 孤儿**);`public_bak_1790669431/` 51 文件**已被 git 跟踪**;终端 11 文件 4 孤儿(含悬空引用)。已删文案(「三检边界」「让步接收」)残留在旧 `format-*.js`。 -- **孤儿表**:WMS `semi_finisheds`(schema+迁移仍建,零业务读写);终端 `event_log`(有写无读)。 -- **死字段**:MES `work_order.projectNo`、`semi_flow.doneProcessCodes`、`work_order.context`;WMS `users.dept`(永不写、永远空)。 -- **假多页面**:WMS `BaseData.vue` 一组件挂 `/zone` + `/material` 两菜单。 -- **keep-alive 名错配**:WMS `router/index.js:18` `componentName:'InspectionIncoming'` ≠ `Inspection.vue:2` 真名 `Inspection` → 该页缓存永久失效。 -- **无调用方接口**:WMS `stock/lock|unlock|query`、`material/list-all` 等;MES `/seed`、`alert/rule` CRUD、`semi/*`、`torque/*` 等。 - -### 11.6 本轮结论 - -- 第一轮 P0(越权提交 / 处置缺项 / 状态越界)已修;本轮又挖出**更高危的 P0**:**seed 提权**、**3 条内部路由裸奔**、**密钥三合一**、**台账丢失更新**、**出库无幂等**、**报工人恒 system**、**终端离线静默丢单**。这些不是风格问题,是**安全与账实正确性**。 -- 修复优先级建议:**① 安全三条(seed / 裸路由 / 密钥)→ ② 台账原子化 + 出库幂等键 → ③ 报工人透传 → ④ 终端重传解析业务码 → ⑤ 闭环断点(出库单关联、备料状态校验)→ ⑥ 死代码 / bundle 清理**。 -- 全程只读,未改任何文件。