diff --git a/.gitignore b/.gitignore index 8dccea8..6351480 100644 --- a/.gitignore +++ b/.gitignore @@ -75,5 +75,6 @@ debug/ /demo_seed.py /shots/ /e2e_tmp/ +/attachments/ /__pycache__/ /shots_capture.log diff --git a/bj_power_mes/bj_power_mes.go b/bj_power_mes/bj_power_mes.go index e4aa2ea..f448d74 100644 --- a/bj_power_mes/bj_power_mes.go +++ b/bj_power_mes/bj_power_mes.go @@ -215,6 +215,9 @@ func main() { // 磁盘空间监控:每天 DiskCheckHour 点检测附件根目录剩余空间 handler.StartDiskMonitor(ctx) + // 事件日志保留期清理:每小时检查,保留天数在「基础设置」页配置(0=不清理) + handler.StartEventLogRetention(ctx) + fmt.Printf("Starting bj_power_mes server at %s:%d...\n", c.Host, c.Port) gologx.Infof("Starting bj_power_mes server at %s:%d...", c.Host, c.Port) diff --git a/bj_power_mes/ent/bomitem.go b/bj_power_mes/ent/bomitem.go deleted file mode 100644 index 7814ecf..0000000 --- a/bj_power_mes/ent/bomitem.go +++ /dev/null @@ -1,245 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "bj_power_mes/ent/bomitem" - "encoding/json" - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" -) - -// BomItem is the model entity for the BomItem schema. -type BomItem struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // 产品编码 - ProductCode string `json:"productCode,omitempty"` - // 物料清单名称:同一型号多份并存(如 厂家A/厂家B/含半成品),工单按名选用 - BomName string `json:"bomName,omitempty"` - // 物料编码 - MaterialCode string `json:"materialCode,omitempty"` - // MaterialName holds the value of the "materialName" field. - MaterialName string `json:"materialName,omitempty"` - // Spec holds the value of the "spec" field. - Spec string `json:"spec,omitempty"` - // Unit holds the value of the "unit" field. - Unit string `json:"unit,omitempty"` - // ManageMode holds the value of the "manageMode" field. - ManageMode string `json:"manageMode,omitempty"` - // 单台用量 - UnitQty float64 `json:"unitQty,omitempty"` - // 损耗率% - LossRate float64 `json:"lossRate,omitempty"` - // 相关标准(检验细则) - RelatedStandard string `json:"relatedStandard,omitempty"` - // 需求总量=总台数*单台*(1+损耗) - RequiredQty float64 `json:"requiredQty,omitempty"` - // 电气件SN下发列表(可选) - SerialSns []string `json:"serialSns,omitempty"` - // CreatedAt holds the value of the "createdAt" field. - CreatedAt time.Time `json:"createdAt,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*BomItem) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case bomitem.FieldSerialSns: - values[i] = new([]byte) - case bomitem.FieldUnitQty, bomitem.FieldLossRate, bomitem.FieldRequiredQty: - values[i] = new(sql.NullFloat64) - case bomitem.FieldID: - values[i] = new(sql.NullInt64) - case bomitem.FieldProductCode, bomitem.FieldBomName, bomitem.FieldMaterialCode, bomitem.FieldMaterialName, bomitem.FieldSpec, bomitem.FieldUnit, bomitem.FieldManageMode, bomitem.FieldRelatedStandard: - values[i] = new(sql.NullString) - case bomitem.FieldCreatedAt: - values[i] = new(sql.NullTime) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the BomItem fields. -func (_m *BomItem) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case bomitem.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - case bomitem.FieldProductCode: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field productCode", values[i]) - } else if value.Valid { - _m.ProductCode = value.String - } - case bomitem.FieldBomName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field bomName", values[i]) - } else if value.Valid { - _m.BomName = value.String - } - case bomitem.FieldMaterialCode: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field materialCode", values[i]) - } else if value.Valid { - _m.MaterialCode = value.String - } - case bomitem.FieldMaterialName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field materialName", values[i]) - } else if value.Valid { - _m.MaterialName = value.String - } - case bomitem.FieldSpec: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field spec", values[i]) - } else if value.Valid { - _m.Spec = value.String - } - case bomitem.FieldUnit: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field unit", values[i]) - } else if value.Valid { - _m.Unit = value.String - } - case bomitem.FieldManageMode: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field manageMode", values[i]) - } else if value.Valid { - _m.ManageMode = value.String - } - case bomitem.FieldUnitQty: - if value, ok := values[i].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field unitQty", values[i]) - } else if value.Valid { - _m.UnitQty = value.Float64 - } - case bomitem.FieldLossRate: - if value, ok := values[i].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field lossRate", values[i]) - } else if value.Valid { - _m.LossRate = value.Float64 - } - case bomitem.FieldRelatedStandard: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field relatedStandard", values[i]) - } else if value.Valid { - _m.RelatedStandard = value.String - } - case bomitem.FieldRequiredQty: - if value, ok := values[i].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field requiredQty", values[i]) - } else if value.Valid { - _m.RequiredQty = value.Float64 - } - case bomitem.FieldSerialSns: - if value, ok := values[i].(*[]byte); !ok { - return fmt.Errorf("unexpected type %T for field serialSns", values[i]) - } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &_m.SerialSns); err != nil { - return fmt.Errorf("unmarshal field serialSns: %w", err) - } - } - case bomitem.FieldCreatedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field createdAt", values[i]) - } else if value.Valid { - _m.CreatedAt = value.Time - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the BomItem. -// This includes values selected through modifiers, order, etc. -func (_m *BomItem) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this BomItem. -// Note that you need to call BomItem.Unwrap() before calling this method if this BomItem -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *BomItem) Update() *BomItemUpdateOne { - return NewBomItemClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the BomItem entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *BomItem) Unwrap() *BomItem { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: BomItem is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *BomItem) String() string { - var builder strings.Builder - builder.WriteString("BomItem(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("productCode=") - builder.WriteString(_m.ProductCode) - builder.WriteString(", ") - builder.WriteString("bomName=") - builder.WriteString(_m.BomName) - builder.WriteString(", ") - builder.WriteString("materialCode=") - builder.WriteString(_m.MaterialCode) - builder.WriteString(", ") - builder.WriteString("materialName=") - builder.WriteString(_m.MaterialName) - builder.WriteString(", ") - builder.WriteString("spec=") - builder.WriteString(_m.Spec) - builder.WriteString(", ") - builder.WriteString("unit=") - builder.WriteString(_m.Unit) - builder.WriteString(", ") - builder.WriteString("manageMode=") - builder.WriteString(_m.ManageMode) - builder.WriteString(", ") - builder.WriteString("unitQty=") - builder.WriteString(fmt.Sprintf("%v", _m.UnitQty)) - builder.WriteString(", ") - builder.WriteString("lossRate=") - builder.WriteString(fmt.Sprintf("%v", _m.LossRate)) - builder.WriteString(", ") - builder.WriteString("relatedStandard=") - builder.WriteString(_m.RelatedStandard) - builder.WriteString(", ") - builder.WriteString("requiredQty=") - builder.WriteString(fmt.Sprintf("%v", _m.RequiredQty)) - builder.WriteString(", ") - builder.WriteString("serialSns=") - builder.WriteString(fmt.Sprintf("%v", _m.SerialSns)) - builder.WriteString(", ") - builder.WriteString("createdAt=") - builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) - builder.WriteByte(')') - return builder.String() -} - -// BomItems is a parsable slice of BomItem. -type BomItems []*BomItem diff --git a/bj_power_mes/ent/bomitem/bomitem.go b/bj_power_mes/ent/bomitem/bomitem.go deleted file mode 100644 index ad3ed24..0000000 --- a/bj_power_mes/ent/bomitem/bomitem.go +++ /dev/null @@ -1,183 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package bomitem - -import ( - "time" - - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the bomitem type in the database. - Label = "bom_item" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldProductCode holds the string denoting the productcode field in the database. - FieldProductCode = "product_code" - // FieldBomName holds the string denoting the bomname field in the database. - FieldBomName = "bom_name" - // FieldMaterialCode holds the string denoting the materialcode field in the database. - FieldMaterialCode = "material_code" - // FieldMaterialName holds the string denoting the materialname field in the database. - FieldMaterialName = "material_name" - // FieldSpec holds the string denoting the spec field in the database. - FieldSpec = "spec" - // FieldUnit holds the string denoting the unit field in the database. - FieldUnit = "unit" - // FieldManageMode holds the string denoting the managemode field in the database. - FieldManageMode = "manage_mode" - // FieldUnitQty holds the string denoting the unitqty field in the database. - FieldUnitQty = "unit_qty" - // FieldLossRate holds the string denoting the lossrate field in the database. - FieldLossRate = "loss_rate" - // FieldRelatedStandard holds the string denoting the relatedstandard field in the database. - FieldRelatedStandard = "related_standard" - // FieldRequiredQty holds the string denoting the requiredqty field in the database. - FieldRequiredQty = "required_qty" - // FieldSerialSns holds the string denoting the serialsns field in the database. - FieldSerialSns = "serial_sns" - // FieldCreatedAt holds the string denoting the createdat field in the database. - FieldCreatedAt = "created_at" - // Table holds the table name of the bomitem in the database. - Table = "work_order_bom" -) - -// Columns holds all SQL columns for bomitem fields. -var Columns = []string{ - FieldID, - FieldProductCode, - FieldBomName, - FieldMaterialCode, - FieldMaterialName, - FieldSpec, - FieldUnit, - FieldManageMode, - FieldUnitQty, - FieldLossRate, - FieldRelatedStandard, - FieldRequiredQty, - FieldSerialSns, - FieldCreatedAt, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -var ( - // DefaultProductCode holds the default value on creation for the "productCode" field. - DefaultProductCode string - // ProductCodeValidator is a validator for the "productCode" field. It is called by the builders before save. - ProductCodeValidator func(string) error - // DefaultBomName holds the default value on creation for the "bomName" field. - DefaultBomName string - // BomNameValidator is a validator for the "bomName" field. It is called by the builders before save. - BomNameValidator func(string) error - // MaterialCodeValidator is a validator for the "materialCode" field. It is called by the builders before save. - MaterialCodeValidator func(string) error - // DefaultMaterialName holds the default value on creation for the "materialName" field. - DefaultMaterialName string - // MaterialNameValidator is a validator for the "materialName" field. It is called by the builders before save. - MaterialNameValidator func(string) error - // DefaultSpec holds the default value on creation for the "spec" field. - DefaultSpec string - // SpecValidator is a validator for the "spec" field. It is called by the builders before save. - SpecValidator func(string) error - // DefaultUnit holds the default value on creation for the "unit" field. - DefaultUnit string - // UnitValidator is a validator for the "unit" field. It is called by the builders before save. - UnitValidator func(string) error - // DefaultManageMode holds the default value on creation for the "manageMode" field. - DefaultManageMode string - // ManageModeValidator is a validator for the "manageMode" field. It is called by the builders before save. - ManageModeValidator func(string) error - // DefaultUnitQty holds the default value on creation for the "unitQty" field. - DefaultUnitQty float64 - // DefaultLossRate holds the default value on creation for the "lossRate" field. - DefaultLossRate float64 - // DefaultRelatedStandard holds the default value on creation for the "relatedStandard" field. - DefaultRelatedStandard string - // RelatedStandardValidator is a validator for the "relatedStandard" field. It is called by the builders before save. - RelatedStandardValidator func(string) error - // DefaultRequiredQty holds the default value on creation for the "requiredQty" field. - DefaultRequiredQty float64 - // DefaultCreatedAt holds the default value on creation for the "createdAt" field. - DefaultCreatedAt func() time.Time - // IDValidator is a validator for the "id" field. It is called by the builders before save. - IDValidator func(int) error -) - -// OrderOption defines the ordering options for the BomItem queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByProductCode orders the results by the productCode field. -func ByProductCode(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldProductCode, opts...).ToFunc() -} - -// ByBomName orders the results by the bomName field. -func ByBomName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldBomName, opts...).ToFunc() -} - -// ByMaterialCode orders the results by the materialCode field. -func ByMaterialCode(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldMaterialCode, opts...).ToFunc() -} - -// ByMaterialName orders the results by the materialName field. -func ByMaterialName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldMaterialName, opts...).ToFunc() -} - -// BySpec orders the results by the spec field. -func BySpec(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldSpec, opts...).ToFunc() -} - -// ByUnit orders the results by the unit field. -func ByUnit(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUnit, opts...).ToFunc() -} - -// ByManageMode orders the results by the manageMode field. -func ByManageMode(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldManageMode, opts...).ToFunc() -} - -// ByUnitQty orders the results by the unitQty field. -func ByUnitQty(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUnitQty, opts...).ToFunc() -} - -// ByLossRate orders the results by the lossRate field. -func ByLossRate(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldLossRate, opts...).ToFunc() -} - -// ByRelatedStandard orders the results by the relatedStandard field. -func ByRelatedStandard(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldRelatedStandard, opts...).ToFunc() -} - -// ByRequiredQty orders the results by the requiredQty field. -func ByRequiredQty(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldRequiredQty, opts...).ToFunc() -} - -// ByCreatedAt orders the results by the createdAt field. -func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() -} diff --git a/bj_power_mes/ent/bomitem/where.go b/bj_power_mes/ent/bomitem/where.go deleted file mode 100644 index 5b70dbf..0000000 --- a/bj_power_mes/ent/bomitem/where.go +++ /dev/null @@ -1,820 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package bomitem - -import ( - "bj_power_mes/ent/predicate" - "time" - - "entgo.io/ent/dialect/sql" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldID, id)) -} - -// ProductCode applies equality check predicate on the "productCode" field. It's identical to ProductCodeEQ. -func ProductCode(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldProductCode, v)) -} - -// BomName applies equality check predicate on the "bomName" field. It's identical to BomNameEQ. -func BomName(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldBomName, v)) -} - -// MaterialCode applies equality check predicate on the "materialCode" field. It's identical to MaterialCodeEQ. -func MaterialCode(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldMaterialCode, v)) -} - -// MaterialName applies equality check predicate on the "materialName" field. It's identical to MaterialNameEQ. -func MaterialName(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldMaterialName, v)) -} - -// Spec applies equality check predicate on the "spec" field. It's identical to SpecEQ. -func Spec(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldSpec, v)) -} - -// Unit applies equality check predicate on the "unit" field. It's identical to UnitEQ. -func Unit(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldUnit, v)) -} - -// ManageMode applies equality check predicate on the "manageMode" field. It's identical to ManageModeEQ. -func ManageMode(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldManageMode, v)) -} - -// UnitQty applies equality check predicate on the "unitQty" field. It's identical to UnitQtyEQ. -func UnitQty(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldUnitQty, v)) -} - -// LossRate applies equality check predicate on the "lossRate" field. It's identical to LossRateEQ. -func LossRate(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldLossRate, v)) -} - -// RelatedStandard applies equality check predicate on the "relatedStandard" field. It's identical to RelatedStandardEQ. -func RelatedStandard(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldRelatedStandard, v)) -} - -// RequiredQty applies equality check predicate on the "requiredQty" field. It's identical to RequiredQtyEQ. -func RequiredQty(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldRequiredQty, v)) -} - -// CreatedAt applies equality check predicate on the "createdAt" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldCreatedAt, v)) -} - -// ProductCodeEQ applies the EQ predicate on the "productCode" field. -func ProductCodeEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldProductCode, v)) -} - -// ProductCodeNEQ applies the NEQ predicate on the "productCode" field. -func ProductCodeNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldProductCode, v)) -} - -// ProductCodeIn applies the In predicate on the "productCode" field. -func ProductCodeIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldProductCode, vs...)) -} - -// ProductCodeNotIn applies the NotIn predicate on the "productCode" field. -func ProductCodeNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldProductCode, vs...)) -} - -// ProductCodeGT applies the GT predicate on the "productCode" field. -func ProductCodeGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldProductCode, v)) -} - -// ProductCodeGTE applies the GTE predicate on the "productCode" field. -func ProductCodeGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldProductCode, v)) -} - -// ProductCodeLT applies the LT predicate on the "productCode" field. -func ProductCodeLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldProductCode, v)) -} - -// ProductCodeLTE applies the LTE predicate on the "productCode" field. -func ProductCodeLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldProductCode, v)) -} - -// ProductCodeContains applies the Contains predicate on the "productCode" field. -func ProductCodeContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldProductCode, v)) -} - -// ProductCodeHasPrefix applies the HasPrefix predicate on the "productCode" field. -func ProductCodeHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldProductCode, v)) -} - -// ProductCodeHasSuffix applies the HasSuffix predicate on the "productCode" field. -func ProductCodeHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldProductCode, v)) -} - -// ProductCodeEqualFold applies the EqualFold predicate on the "productCode" field. -func ProductCodeEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldProductCode, v)) -} - -// ProductCodeContainsFold applies the ContainsFold predicate on the "productCode" field. -func ProductCodeContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldProductCode, v)) -} - -// BomNameEQ applies the EQ predicate on the "bomName" field. -func BomNameEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldBomName, v)) -} - -// BomNameNEQ applies the NEQ predicate on the "bomName" field. -func BomNameNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldBomName, v)) -} - -// BomNameIn applies the In predicate on the "bomName" field. -func BomNameIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldBomName, vs...)) -} - -// BomNameNotIn applies the NotIn predicate on the "bomName" field. -func BomNameNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldBomName, vs...)) -} - -// BomNameGT applies the GT predicate on the "bomName" field. -func BomNameGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldBomName, v)) -} - -// BomNameGTE applies the GTE predicate on the "bomName" field. -func BomNameGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldBomName, v)) -} - -// BomNameLT applies the LT predicate on the "bomName" field. -func BomNameLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldBomName, v)) -} - -// BomNameLTE applies the LTE predicate on the "bomName" field. -func BomNameLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldBomName, v)) -} - -// BomNameContains applies the Contains predicate on the "bomName" field. -func BomNameContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldBomName, v)) -} - -// BomNameHasPrefix applies the HasPrefix predicate on the "bomName" field. -func BomNameHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldBomName, v)) -} - -// BomNameHasSuffix applies the HasSuffix predicate on the "bomName" field. -func BomNameHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldBomName, v)) -} - -// BomNameEqualFold applies the EqualFold predicate on the "bomName" field. -func BomNameEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldBomName, v)) -} - -// BomNameContainsFold applies the ContainsFold predicate on the "bomName" field. -func BomNameContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldBomName, v)) -} - -// MaterialCodeEQ applies the EQ predicate on the "materialCode" field. -func MaterialCodeEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldMaterialCode, v)) -} - -// MaterialCodeNEQ applies the NEQ predicate on the "materialCode" field. -func MaterialCodeNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldMaterialCode, v)) -} - -// MaterialCodeIn applies the In predicate on the "materialCode" field. -func MaterialCodeIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldMaterialCode, vs...)) -} - -// MaterialCodeNotIn applies the NotIn predicate on the "materialCode" field. -func MaterialCodeNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldMaterialCode, vs...)) -} - -// MaterialCodeGT applies the GT predicate on the "materialCode" field. -func MaterialCodeGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldMaterialCode, v)) -} - -// MaterialCodeGTE applies the GTE predicate on the "materialCode" field. -func MaterialCodeGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldMaterialCode, v)) -} - -// MaterialCodeLT applies the LT predicate on the "materialCode" field. -func MaterialCodeLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldMaterialCode, v)) -} - -// MaterialCodeLTE applies the LTE predicate on the "materialCode" field. -func MaterialCodeLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldMaterialCode, v)) -} - -// MaterialCodeContains applies the Contains predicate on the "materialCode" field. -func MaterialCodeContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldMaterialCode, v)) -} - -// MaterialCodeHasPrefix applies the HasPrefix predicate on the "materialCode" field. -func MaterialCodeHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldMaterialCode, v)) -} - -// MaterialCodeHasSuffix applies the HasSuffix predicate on the "materialCode" field. -func MaterialCodeHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldMaterialCode, v)) -} - -// MaterialCodeEqualFold applies the EqualFold predicate on the "materialCode" field. -func MaterialCodeEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldMaterialCode, v)) -} - -// MaterialCodeContainsFold applies the ContainsFold predicate on the "materialCode" field. -func MaterialCodeContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldMaterialCode, v)) -} - -// MaterialNameEQ applies the EQ predicate on the "materialName" field. -func MaterialNameEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldMaterialName, v)) -} - -// MaterialNameNEQ applies the NEQ predicate on the "materialName" field. -func MaterialNameNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldMaterialName, v)) -} - -// MaterialNameIn applies the In predicate on the "materialName" field. -func MaterialNameIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldMaterialName, vs...)) -} - -// MaterialNameNotIn applies the NotIn predicate on the "materialName" field. -func MaterialNameNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldMaterialName, vs...)) -} - -// MaterialNameGT applies the GT predicate on the "materialName" field. -func MaterialNameGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldMaterialName, v)) -} - -// MaterialNameGTE applies the GTE predicate on the "materialName" field. -func MaterialNameGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldMaterialName, v)) -} - -// MaterialNameLT applies the LT predicate on the "materialName" field. -func MaterialNameLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldMaterialName, v)) -} - -// MaterialNameLTE applies the LTE predicate on the "materialName" field. -func MaterialNameLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldMaterialName, v)) -} - -// MaterialNameContains applies the Contains predicate on the "materialName" field. -func MaterialNameContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldMaterialName, v)) -} - -// MaterialNameHasPrefix applies the HasPrefix predicate on the "materialName" field. -func MaterialNameHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldMaterialName, v)) -} - -// MaterialNameHasSuffix applies the HasSuffix predicate on the "materialName" field. -func MaterialNameHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldMaterialName, v)) -} - -// MaterialNameEqualFold applies the EqualFold predicate on the "materialName" field. -func MaterialNameEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldMaterialName, v)) -} - -// MaterialNameContainsFold applies the ContainsFold predicate on the "materialName" field. -func MaterialNameContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldMaterialName, v)) -} - -// SpecEQ applies the EQ predicate on the "spec" field. -func SpecEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldSpec, v)) -} - -// SpecNEQ applies the NEQ predicate on the "spec" field. -func SpecNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldSpec, v)) -} - -// SpecIn applies the In predicate on the "spec" field. -func SpecIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldSpec, vs...)) -} - -// SpecNotIn applies the NotIn predicate on the "spec" field. -func SpecNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldSpec, vs...)) -} - -// SpecGT applies the GT predicate on the "spec" field. -func SpecGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldSpec, v)) -} - -// SpecGTE applies the GTE predicate on the "spec" field. -func SpecGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldSpec, v)) -} - -// SpecLT applies the LT predicate on the "spec" field. -func SpecLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldSpec, v)) -} - -// SpecLTE applies the LTE predicate on the "spec" field. -func SpecLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldSpec, v)) -} - -// SpecContains applies the Contains predicate on the "spec" field. -func SpecContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldSpec, v)) -} - -// SpecHasPrefix applies the HasPrefix predicate on the "spec" field. -func SpecHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldSpec, v)) -} - -// SpecHasSuffix applies the HasSuffix predicate on the "spec" field. -func SpecHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldSpec, v)) -} - -// SpecEqualFold applies the EqualFold predicate on the "spec" field. -func SpecEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldSpec, v)) -} - -// SpecContainsFold applies the ContainsFold predicate on the "spec" field. -func SpecContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldSpec, v)) -} - -// UnitEQ applies the EQ predicate on the "unit" field. -func UnitEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldUnit, v)) -} - -// UnitNEQ applies the NEQ predicate on the "unit" field. -func UnitNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldUnit, v)) -} - -// UnitIn applies the In predicate on the "unit" field. -func UnitIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldUnit, vs...)) -} - -// UnitNotIn applies the NotIn predicate on the "unit" field. -func UnitNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldUnit, vs...)) -} - -// UnitGT applies the GT predicate on the "unit" field. -func UnitGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldUnit, v)) -} - -// UnitGTE applies the GTE predicate on the "unit" field. -func UnitGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldUnit, v)) -} - -// UnitLT applies the LT predicate on the "unit" field. -func UnitLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldUnit, v)) -} - -// UnitLTE applies the LTE predicate on the "unit" field. -func UnitLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldUnit, v)) -} - -// UnitContains applies the Contains predicate on the "unit" field. -func UnitContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldUnit, v)) -} - -// UnitHasPrefix applies the HasPrefix predicate on the "unit" field. -func UnitHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldUnit, v)) -} - -// UnitHasSuffix applies the HasSuffix predicate on the "unit" field. -func UnitHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldUnit, v)) -} - -// UnitEqualFold applies the EqualFold predicate on the "unit" field. -func UnitEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldUnit, v)) -} - -// UnitContainsFold applies the ContainsFold predicate on the "unit" field. -func UnitContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldUnit, v)) -} - -// ManageModeEQ applies the EQ predicate on the "manageMode" field. -func ManageModeEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldManageMode, v)) -} - -// ManageModeNEQ applies the NEQ predicate on the "manageMode" field. -func ManageModeNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldManageMode, v)) -} - -// ManageModeIn applies the In predicate on the "manageMode" field. -func ManageModeIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldManageMode, vs...)) -} - -// ManageModeNotIn applies the NotIn predicate on the "manageMode" field. -func ManageModeNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldManageMode, vs...)) -} - -// ManageModeGT applies the GT predicate on the "manageMode" field. -func ManageModeGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldManageMode, v)) -} - -// ManageModeGTE applies the GTE predicate on the "manageMode" field. -func ManageModeGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldManageMode, v)) -} - -// ManageModeLT applies the LT predicate on the "manageMode" field. -func ManageModeLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldManageMode, v)) -} - -// ManageModeLTE applies the LTE predicate on the "manageMode" field. -func ManageModeLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldManageMode, v)) -} - -// ManageModeContains applies the Contains predicate on the "manageMode" field. -func ManageModeContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldManageMode, v)) -} - -// ManageModeHasPrefix applies the HasPrefix predicate on the "manageMode" field. -func ManageModeHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldManageMode, v)) -} - -// ManageModeHasSuffix applies the HasSuffix predicate on the "manageMode" field. -func ManageModeHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldManageMode, v)) -} - -// ManageModeEqualFold applies the EqualFold predicate on the "manageMode" field. -func ManageModeEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldManageMode, v)) -} - -// ManageModeContainsFold applies the ContainsFold predicate on the "manageMode" field. -func ManageModeContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldManageMode, v)) -} - -// UnitQtyEQ applies the EQ predicate on the "unitQty" field. -func UnitQtyEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldUnitQty, v)) -} - -// UnitQtyNEQ applies the NEQ predicate on the "unitQty" field. -func UnitQtyNEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldUnitQty, v)) -} - -// UnitQtyIn applies the In predicate on the "unitQty" field. -func UnitQtyIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldUnitQty, vs...)) -} - -// UnitQtyNotIn applies the NotIn predicate on the "unitQty" field. -func UnitQtyNotIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldUnitQty, vs...)) -} - -// UnitQtyGT applies the GT predicate on the "unitQty" field. -func UnitQtyGT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldUnitQty, v)) -} - -// UnitQtyGTE applies the GTE predicate on the "unitQty" field. -func UnitQtyGTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldUnitQty, v)) -} - -// UnitQtyLT applies the LT predicate on the "unitQty" field. -func UnitQtyLT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldUnitQty, v)) -} - -// UnitQtyLTE applies the LTE predicate on the "unitQty" field. -func UnitQtyLTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldUnitQty, v)) -} - -// LossRateEQ applies the EQ predicate on the "lossRate" field. -func LossRateEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldLossRate, v)) -} - -// LossRateNEQ applies the NEQ predicate on the "lossRate" field. -func LossRateNEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldLossRate, v)) -} - -// LossRateIn applies the In predicate on the "lossRate" field. -func LossRateIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldLossRate, vs...)) -} - -// LossRateNotIn applies the NotIn predicate on the "lossRate" field. -func LossRateNotIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldLossRate, vs...)) -} - -// LossRateGT applies the GT predicate on the "lossRate" field. -func LossRateGT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldLossRate, v)) -} - -// LossRateGTE applies the GTE predicate on the "lossRate" field. -func LossRateGTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldLossRate, v)) -} - -// LossRateLT applies the LT predicate on the "lossRate" field. -func LossRateLT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldLossRate, v)) -} - -// LossRateLTE applies the LTE predicate on the "lossRate" field. -func LossRateLTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldLossRate, v)) -} - -// RelatedStandardEQ applies the EQ predicate on the "relatedStandard" field. -func RelatedStandardEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldRelatedStandard, v)) -} - -// RelatedStandardNEQ applies the NEQ predicate on the "relatedStandard" field. -func RelatedStandardNEQ(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldRelatedStandard, v)) -} - -// RelatedStandardIn applies the In predicate on the "relatedStandard" field. -func RelatedStandardIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldRelatedStandard, vs...)) -} - -// RelatedStandardNotIn applies the NotIn predicate on the "relatedStandard" field. -func RelatedStandardNotIn(vs ...string) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldRelatedStandard, vs...)) -} - -// RelatedStandardGT applies the GT predicate on the "relatedStandard" field. -func RelatedStandardGT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldRelatedStandard, v)) -} - -// RelatedStandardGTE applies the GTE predicate on the "relatedStandard" field. -func RelatedStandardGTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldRelatedStandard, v)) -} - -// RelatedStandardLT applies the LT predicate on the "relatedStandard" field. -func RelatedStandardLT(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldRelatedStandard, v)) -} - -// RelatedStandardLTE applies the LTE predicate on the "relatedStandard" field. -func RelatedStandardLTE(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldRelatedStandard, v)) -} - -// RelatedStandardContains applies the Contains predicate on the "relatedStandard" field. -func RelatedStandardContains(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContains(FieldRelatedStandard, v)) -} - -// RelatedStandardHasPrefix applies the HasPrefix predicate on the "relatedStandard" field. -func RelatedStandardHasPrefix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasPrefix(FieldRelatedStandard, v)) -} - -// RelatedStandardHasSuffix applies the HasSuffix predicate on the "relatedStandard" field. -func RelatedStandardHasSuffix(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldHasSuffix(FieldRelatedStandard, v)) -} - -// RelatedStandardEqualFold applies the EqualFold predicate on the "relatedStandard" field. -func RelatedStandardEqualFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldEqualFold(FieldRelatedStandard, v)) -} - -// RelatedStandardContainsFold applies the ContainsFold predicate on the "relatedStandard" field. -func RelatedStandardContainsFold(v string) predicate.BomItem { - return predicate.BomItem(sql.FieldContainsFold(FieldRelatedStandard, v)) -} - -// RequiredQtyEQ applies the EQ predicate on the "requiredQty" field. -func RequiredQtyEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldRequiredQty, v)) -} - -// RequiredQtyNEQ applies the NEQ predicate on the "requiredQty" field. -func RequiredQtyNEQ(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldRequiredQty, v)) -} - -// RequiredQtyIn applies the In predicate on the "requiredQty" field. -func RequiredQtyIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldRequiredQty, vs...)) -} - -// RequiredQtyNotIn applies the NotIn predicate on the "requiredQty" field. -func RequiredQtyNotIn(vs ...float64) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldRequiredQty, vs...)) -} - -// RequiredQtyGT applies the GT predicate on the "requiredQty" field. -func RequiredQtyGT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldRequiredQty, v)) -} - -// RequiredQtyGTE applies the GTE predicate on the "requiredQty" field. -func RequiredQtyGTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldRequiredQty, v)) -} - -// RequiredQtyLT applies the LT predicate on the "requiredQty" field. -func RequiredQtyLT(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldRequiredQty, v)) -} - -// RequiredQtyLTE applies the LTE predicate on the "requiredQty" field. -func RequiredQtyLTE(v float64) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldRequiredQty, v)) -} - -// SerialSnsIsNil applies the IsNil predicate on the "serialSns" field. -func SerialSnsIsNil() predicate.BomItem { - return predicate.BomItem(sql.FieldIsNull(FieldSerialSns)) -} - -// SerialSnsNotNil applies the NotNil predicate on the "serialSns" field. -func SerialSnsNotNil() predicate.BomItem { - return predicate.BomItem(sql.FieldNotNull(FieldSerialSns)) -} - -// CreatedAtEQ applies the EQ predicate on the "createdAt" field. -func CreatedAtEQ(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "createdAt" field. -func CreatedAtNEQ(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "createdAt" field. -func CreatedAtIn(vs ...time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "createdAt" field. -func CreatedAtNotIn(vs ...time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "createdAt" field. -func CreatedAtGT(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "createdAt" field. -func CreatedAtGTE(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "createdAt" field. -func CreatedAtLT(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "createdAt" field. -func CreatedAtLTE(v time.Time) predicate.BomItem { - return predicate.BomItem(sql.FieldLTE(FieldCreatedAt, v)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.BomItem) predicate.BomItem { - return predicate.BomItem(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.BomItem) predicate.BomItem { - return predicate.BomItem(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.BomItem) predicate.BomItem { - return predicate.BomItem(sql.NotPredicates(p)) -} diff --git a/bj_power_mes/ent/bomitem_create.go b/bj_power_mes/ent/bomitem_create.go deleted file mode 100644 index bf9a582..0000000 --- a/bj_power_mes/ent/bomitem_create.go +++ /dev/null @@ -1,532 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "bj_power_mes/ent/bomitem" - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" -) - -// BomItemCreate is the builder for creating a BomItem entity. -type BomItemCreate struct { - config - mutation *BomItemMutation - hooks []Hook -} - -// SetProductCode sets the "productCode" field. -func (_c *BomItemCreate) SetProductCode(v string) *BomItemCreate { - _c.mutation.SetProductCode(v) - return _c -} - -// SetNillableProductCode sets the "productCode" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableProductCode(v *string) *BomItemCreate { - if v != nil { - _c.SetProductCode(*v) - } - return _c -} - -// SetBomName sets the "bomName" field. -func (_c *BomItemCreate) SetBomName(v string) *BomItemCreate { - _c.mutation.SetBomName(v) - return _c -} - -// SetNillableBomName sets the "bomName" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableBomName(v *string) *BomItemCreate { - if v != nil { - _c.SetBomName(*v) - } - return _c -} - -// SetMaterialCode sets the "materialCode" field. -func (_c *BomItemCreate) SetMaterialCode(v string) *BomItemCreate { - _c.mutation.SetMaterialCode(v) - return _c -} - -// SetMaterialName sets the "materialName" field. -func (_c *BomItemCreate) SetMaterialName(v string) *BomItemCreate { - _c.mutation.SetMaterialName(v) - return _c -} - -// SetNillableMaterialName sets the "materialName" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableMaterialName(v *string) *BomItemCreate { - if v != nil { - _c.SetMaterialName(*v) - } - return _c -} - -// SetSpec sets the "spec" field. -func (_c *BomItemCreate) SetSpec(v string) *BomItemCreate { - _c.mutation.SetSpec(v) - return _c -} - -// SetNillableSpec sets the "spec" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableSpec(v *string) *BomItemCreate { - if v != nil { - _c.SetSpec(*v) - } - return _c -} - -// SetUnit sets the "unit" field. -func (_c *BomItemCreate) SetUnit(v string) *BomItemCreate { - _c.mutation.SetUnit(v) - return _c -} - -// SetNillableUnit sets the "unit" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableUnit(v *string) *BomItemCreate { - if v != nil { - _c.SetUnit(*v) - } - return _c -} - -// SetManageMode sets the "manageMode" field. -func (_c *BomItemCreate) SetManageMode(v string) *BomItemCreate { - _c.mutation.SetManageMode(v) - return _c -} - -// SetNillableManageMode sets the "manageMode" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableManageMode(v *string) *BomItemCreate { - if v != nil { - _c.SetManageMode(*v) - } - return _c -} - -// SetUnitQty sets the "unitQty" field. -func (_c *BomItemCreate) SetUnitQty(v float64) *BomItemCreate { - _c.mutation.SetUnitQty(v) - return _c -} - -// SetNillableUnitQty sets the "unitQty" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableUnitQty(v *float64) *BomItemCreate { - if v != nil { - _c.SetUnitQty(*v) - } - return _c -} - -// SetLossRate sets the "lossRate" field. -func (_c *BomItemCreate) SetLossRate(v float64) *BomItemCreate { - _c.mutation.SetLossRate(v) - return _c -} - -// SetNillableLossRate sets the "lossRate" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableLossRate(v *float64) *BomItemCreate { - if v != nil { - _c.SetLossRate(*v) - } - return _c -} - -// SetRelatedStandard sets the "relatedStandard" field. -func (_c *BomItemCreate) SetRelatedStandard(v string) *BomItemCreate { - _c.mutation.SetRelatedStandard(v) - return _c -} - -// SetNillableRelatedStandard sets the "relatedStandard" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableRelatedStandard(v *string) *BomItemCreate { - if v != nil { - _c.SetRelatedStandard(*v) - } - return _c -} - -// SetRequiredQty sets the "requiredQty" field. -func (_c *BomItemCreate) SetRequiredQty(v float64) *BomItemCreate { - _c.mutation.SetRequiredQty(v) - return _c -} - -// SetNillableRequiredQty sets the "requiredQty" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableRequiredQty(v *float64) *BomItemCreate { - if v != nil { - _c.SetRequiredQty(*v) - } - return _c -} - -// SetSerialSns sets the "serialSns" field. -func (_c *BomItemCreate) SetSerialSns(v []string) *BomItemCreate { - _c.mutation.SetSerialSns(v) - return _c -} - -// SetCreatedAt sets the "createdAt" field. -func (_c *BomItemCreate) SetCreatedAt(v time.Time) *BomItemCreate { - _c.mutation.SetCreatedAt(v) - return _c -} - -// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil. -func (_c *BomItemCreate) SetNillableCreatedAt(v *time.Time) *BomItemCreate { - if v != nil { - _c.SetCreatedAt(*v) - } - return _c -} - -// SetID sets the "id" field. -func (_c *BomItemCreate) SetID(v int) *BomItemCreate { - _c.mutation.SetID(v) - return _c -} - -// Mutation returns the BomItemMutation object of the builder. -func (_c *BomItemCreate) Mutation() *BomItemMutation { - return _c.mutation -} - -// Save creates the BomItem in the database. -func (_c *BomItemCreate) Save(ctx context.Context) (*BomItem, error) { - _c.defaults() - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *BomItemCreate) SaveX(ctx context.Context) *BomItem { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *BomItemCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *BomItemCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_c *BomItemCreate) defaults() { - if _, ok := _c.mutation.ProductCode(); !ok { - v := bomitem.DefaultProductCode - _c.mutation.SetProductCode(v) - } - if _, ok := _c.mutation.BomName(); !ok { - v := bomitem.DefaultBomName - _c.mutation.SetBomName(v) - } - if _, ok := _c.mutation.MaterialName(); !ok { - v := bomitem.DefaultMaterialName - _c.mutation.SetMaterialName(v) - } - if _, ok := _c.mutation.Spec(); !ok { - v := bomitem.DefaultSpec - _c.mutation.SetSpec(v) - } - if _, ok := _c.mutation.Unit(); !ok { - v := bomitem.DefaultUnit - _c.mutation.SetUnit(v) - } - if _, ok := _c.mutation.ManageMode(); !ok { - v := bomitem.DefaultManageMode - _c.mutation.SetManageMode(v) - } - if _, ok := _c.mutation.UnitQty(); !ok { - v := bomitem.DefaultUnitQty - _c.mutation.SetUnitQty(v) - } - if _, ok := _c.mutation.LossRate(); !ok { - v := bomitem.DefaultLossRate - _c.mutation.SetLossRate(v) - } - if _, ok := _c.mutation.RelatedStandard(); !ok { - v := bomitem.DefaultRelatedStandard - _c.mutation.SetRelatedStandard(v) - } - if _, ok := _c.mutation.RequiredQty(); !ok { - v := bomitem.DefaultRequiredQty - _c.mutation.SetRequiredQty(v) - } - if _, ok := _c.mutation.CreatedAt(); !ok { - v := bomitem.DefaultCreatedAt() - _c.mutation.SetCreatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *BomItemCreate) check() error { - if _, ok := _c.mutation.ProductCode(); !ok { - return &ValidationError{Name: "productCode", err: errors.New(`ent: missing required field "BomItem.productCode"`)} - } - if v, ok := _c.mutation.ProductCode(); ok { - if err := bomitem.ProductCodeValidator(v); err != nil { - return &ValidationError{Name: "productCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.productCode": %w`, err)} - } - } - if _, ok := _c.mutation.BomName(); !ok { - return &ValidationError{Name: "bomName", err: errors.New(`ent: missing required field "BomItem.bomName"`)} - } - if v, ok := _c.mutation.BomName(); ok { - if err := bomitem.BomNameValidator(v); err != nil { - return &ValidationError{Name: "bomName", err: fmt.Errorf(`ent: validator failed for field "BomItem.bomName": %w`, err)} - } - } - if _, ok := _c.mutation.MaterialCode(); !ok { - return &ValidationError{Name: "materialCode", err: errors.New(`ent: missing required field "BomItem.materialCode"`)} - } - if v, ok := _c.mutation.MaterialCode(); ok { - if err := bomitem.MaterialCodeValidator(v); err != nil { - return &ValidationError{Name: "materialCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialCode": %w`, err)} - } - } - if _, ok := _c.mutation.MaterialName(); !ok { - return &ValidationError{Name: "materialName", err: errors.New(`ent: missing required field "BomItem.materialName"`)} - } - if v, ok := _c.mutation.MaterialName(); ok { - if err := bomitem.MaterialNameValidator(v); err != nil { - return &ValidationError{Name: "materialName", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialName": %w`, err)} - } - } - if _, ok := _c.mutation.Spec(); !ok { - return &ValidationError{Name: "spec", err: errors.New(`ent: missing required field "BomItem.spec"`)} - } - if v, ok := _c.mutation.Spec(); ok { - if err := bomitem.SpecValidator(v); err != nil { - return &ValidationError{Name: "spec", err: fmt.Errorf(`ent: validator failed for field "BomItem.spec": %w`, err)} - } - } - if _, ok := _c.mutation.Unit(); !ok { - return &ValidationError{Name: "unit", err: errors.New(`ent: missing required field "BomItem.unit"`)} - } - if v, ok := _c.mutation.Unit(); ok { - if err := bomitem.UnitValidator(v); err != nil { - return &ValidationError{Name: "unit", err: fmt.Errorf(`ent: validator failed for field "BomItem.unit": %w`, err)} - } - } - if _, ok := _c.mutation.ManageMode(); !ok { - return &ValidationError{Name: "manageMode", err: errors.New(`ent: missing required field "BomItem.manageMode"`)} - } - if v, ok := _c.mutation.ManageMode(); ok { - if err := bomitem.ManageModeValidator(v); err != nil { - return &ValidationError{Name: "manageMode", err: fmt.Errorf(`ent: validator failed for field "BomItem.manageMode": %w`, err)} - } - } - if _, ok := _c.mutation.UnitQty(); !ok { - return &ValidationError{Name: "unitQty", err: errors.New(`ent: missing required field "BomItem.unitQty"`)} - } - if _, ok := _c.mutation.LossRate(); !ok { - return &ValidationError{Name: "lossRate", err: errors.New(`ent: missing required field "BomItem.lossRate"`)} - } - if _, ok := _c.mutation.RelatedStandard(); !ok { - return &ValidationError{Name: "relatedStandard", err: errors.New(`ent: missing required field "BomItem.relatedStandard"`)} - } - if v, ok := _c.mutation.RelatedStandard(); ok { - if err := bomitem.RelatedStandardValidator(v); err != nil { - return &ValidationError{Name: "relatedStandard", err: fmt.Errorf(`ent: validator failed for field "BomItem.relatedStandard": %w`, err)} - } - } - if _, ok := _c.mutation.RequiredQty(); !ok { - return &ValidationError{Name: "requiredQty", err: errors.New(`ent: missing required field "BomItem.requiredQty"`)} - } - if _, ok := _c.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "createdAt", err: errors.New(`ent: missing required field "BomItem.createdAt"`)} - } - if v, ok := _c.mutation.ID(); ok { - if err := bomitem.IDValidator(v); err != nil { - return &ValidationError{Name: "id", err: fmt.Errorf(`ent: validator failed for field "BomItem.id": %w`, err)} - } - } - return nil -} - -func (_c *BomItemCreate) sqlSave(ctx context.Context) (*BomItem, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != _node.ID { - id := _spec.ID.Value.(int64) - _node.ID = int(id) - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *BomItemCreate) createSpec() (*BomItem, *sqlgraph.CreateSpec) { - var ( - _node = &BomItem{config: _c.config} - _spec = sqlgraph.NewCreateSpec(bomitem.Table, sqlgraph.NewFieldSpec(bomitem.FieldID, field.TypeInt)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.ProductCode(); ok { - _spec.SetField(bomitem.FieldProductCode, field.TypeString, value) - _node.ProductCode = value - } - if value, ok := _c.mutation.BomName(); ok { - _spec.SetField(bomitem.FieldBomName, field.TypeString, value) - _node.BomName = value - } - if value, ok := _c.mutation.MaterialCode(); ok { - _spec.SetField(bomitem.FieldMaterialCode, field.TypeString, value) - _node.MaterialCode = value - } - if value, ok := _c.mutation.MaterialName(); ok { - _spec.SetField(bomitem.FieldMaterialName, field.TypeString, value) - _node.MaterialName = value - } - if value, ok := _c.mutation.Spec(); ok { - _spec.SetField(bomitem.FieldSpec, field.TypeString, value) - _node.Spec = value - } - if value, ok := _c.mutation.Unit(); ok { - _spec.SetField(bomitem.FieldUnit, field.TypeString, value) - _node.Unit = value - } - if value, ok := _c.mutation.ManageMode(); ok { - _spec.SetField(bomitem.FieldManageMode, field.TypeString, value) - _node.ManageMode = value - } - if value, ok := _c.mutation.UnitQty(); ok { - _spec.SetField(bomitem.FieldUnitQty, field.TypeFloat64, value) - _node.UnitQty = value - } - if value, ok := _c.mutation.LossRate(); ok { - _spec.SetField(bomitem.FieldLossRate, field.TypeFloat64, value) - _node.LossRate = value - } - if value, ok := _c.mutation.RelatedStandard(); ok { - _spec.SetField(bomitem.FieldRelatedStandard, field.TypeString, value) - _node.RelatedStandard = value - } - if value, ok := _c.mutation.RequiredQty(); ok { - _spec.SetField(bomitem.FieldRequiredQty, field.TypeFloat64, value) - _node.RequiredQty = value - } - if value, ok := _c.mutation.SerialSns(); ok { - _spec.SetField(bomitem.FieldSerialSns, field.TypeJSON, value) - _node.SerialSns = value - } - if value, ok := _c.mutation.CreatedAt(); ok { - _spec.SetField(bomitem.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - return _node, _spec -} - -// BomItemCreateBulk is the builder for creating many BomItem entities in bulk. -type BomItemCreateBulk struct { - config - err error - builders []*BomItemCreate -} - -// Save creates the BomItem entities in the database. -func (_c *BomItemCreateBulk) Save(ctx context.Context) ([]*BomItem, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*BomItem, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*BomItemMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil && nodes[i].ID == 0 { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *BomItemCreateBulk) SaveX(ctx context.Context) []*BomItem { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *BomItemCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *BomItemCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/bj_power_mes/ent/bomitem_update.go b/bj_power_mes/ent/bomitem_update.go deleted file mode 100644 index 3a8eab5..0000000 --- a/bj_power_mes/ent/bomitem_update.go +++ /dev/null @@ -1,780 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "bj_power_mes/ent/bomitem" - "bj_power_mes/ent/predicate" - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/dialect/sql/sqljson" - "entgo.io/ent/schema/field" -) - -// BomItemUpdate is the builder for updating BomItem entities. -type BomItemUpdate struct { - config - hooks []Hook - mutation *BomItemMutation - modifiers []func(*sql.UpdateBuilder) -} - -// Where appends a list predicates to the BomItemUpdate builder. -func (_u *BomItemUpdate) Where(ps ...predicate.BomItem) *BomItemUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetProductCode sets the "productCode" field. -func (_u *BomItemUpdate) SetProductCode(v string) *BomItemUpdate { - _u.mutation.SetProductCode(v) - return _u -} - -// SetNillableProductCode sets the "productCode" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableProductCode(v *string) *BomItemUpdate { - if v != nil { - _u.SetProductCode(*v) - } - return _u -} - -// SetBomName sets the "bomName" field. -func (_u *BomItemUpdate) SetBomName(v string) *BomItemUpdate { - _u.mutation.SetBomName(v) - return _u -} - -// SetNillableBomName sets the "bomName" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableBomName(v *string) *BomItemUpdate { - if v != nil { - _u.SetBomName(*v) - } - return _u -} - -// SetMaterialCode sets the "materialCode" field. -func (_u *BomItemUpdate) SetMaterialCode(v string) *BomItemUpdate { - _u.mutation.SetMaterialCode(v) - return _u -} - -// SetNillableMaterialCode sets the "materialCode" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableMaterialCode(v *string) *BomItemUpdate { - if v != nil { - _u.SetMaterialCode(*v) - } - return _u -} - -// SetMaterialName sets the "materialName" field. -func (_u *BomItemUpdate) SetMaterialName(v string) *BomItemUpdate { - _u.mutation.SetMaterialName(v) - return _u -} - -// SetNillableMaterialName sets the "materialName" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableMaterialName(v *string) *BomItemUpdate { - if v != nil { - _u.SetMaterialName(*v) - } - return _u -} - -// SetSpec sets the "spec" field. -func (_u *BomItemUpdate) SetSpec(v string) *BomItemUpdate { - _u.mutation.SetSpec(v) - return _u -} - -// SetNillableSpec sets the "spec" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableSpec(v *string) *BomItemUpdate { - if v != nil { - _u.SetSpec(*v) - } - return _u -} - -// SetUnit sets the "unit" field. -func (_u *BomItemUpdate) SetUnit(v string) *BomItemUpdate { - _u.mutation.SetUnit(v) - return _u -} - -// SetNillableUnit sets the "unit" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableUnit(v *string) *BomItemUpdate { - if v != nil { - _u.SetUnit(*v) - } - return _u -} - -// SetManageMode sets the "manageMode" field. -func (_u *BomItemUpdate) SetManageMode(v string) *BomItemUpdate { - _u.mutation.SetManageMode(v) - return _u -} - -// SetNillableManageMode sets the "manageMode" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableManageMode(v *string) *BomItemUpdate { - if v != nil { - _u.SetManageMode(*v) - } - return _u -} - -// SetUnitQty sets the "unitQty" field. -func (_u *BomItemUpdate) SetUnitQty(v float64) *BomItemUpdate { - _u.mutation.ResetUnitQty() - _u.mutation.SetUnitQty(v) - return _u -} - -// SetNillableUnitQty sets the "unitQty" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableUnitQty(v *float64) *BomItemUpdate { - if v != nil { - _u.SetUnitQty(*v) - } - return _u -} - -// AddUnitQty adds value to the "unitQty" field. -func (_u *BomItemUpdate) AddUnitQty(v float64) *BomItemUpdate { - _u.mutation.AddUnitQty(v) - return _u -} - -// SetLossRate sets the "lossRate" field. -func (_u *BomItemUpdate) SetLossRate(v float64) *BomItemUpdate { - _u.mutation.ResetLossRate() - _u.mutation.SetLossRate(v) - return _u -} - -// SetNillableLossRate sets the "lossRate" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableLossRate(v *float64) *BomItemUpdate { - if v != nil { - _u.SetLossRate(*v) - } - return _u -} - -// AddLossRate adds value to the "lossRate" field. -func (_u *BomItemUpdate) AddLossRate(v float64) *BomItemUpdate { - _u.mutation.AddLossRate(v) - return _u -} - -// SetRelatedStandard sets the "relatedStandard" field. -func (_u *BomItemUpdate) SetRelatedStandard(v string) *BomItemUpdate { - _u.mutation.SetRelatedStandard(v) - return _u -} - -// SetNillableRelatedStandard sets the "relatedStandard" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableRelatedStandard(v *string) *BomItemUpdate { - if v != nil { - _u.SetRelatedStandard(*v) - } - return _u -} - -// SetRequiredQty sets the "requiredQty" field. -func (_u *BomItemUpdate) SetRequiredQty(v float64) *BomItemUpdate { - _u.mutation.ResetRequiredQty() - _u.mutation.SetRequiredQty(v) - return _u -} - -// SetNillableRequiredQty sets the "requiredQty" field if the given value is not nil. -func (_u *BomItemUpdate) SetNillableRequiredQty(v *float64) *BomItemUpdate { - if v != nil { - _u.SetRequiredQty(*v) - } - return _u -} - -// AddRequiredQty adds value to the "requiredQty" field. -func (_u *BomItemUpdate) AddRequiredQty(v float64) *BomItemUpdate { - _u.mutation.AddRequiredQty(v) - return _u -} - -// SetSerialSns sets the "serialSns" field. -func (_u *BomItemUpdate) SetSerialSns(v []string) *BomItemUpdate { - _u.mutation.SetSerialSns(v) - return _u -} - -// AppendSerialSns appends value to the "serialSns" field. -func (_u *BomItemUpdate) AppendSerialSns(v []string) *BomItemUpdate { - _u.mutation.AppendSerialSns(v) - return _u -} - -// ClearSerialSns clears the value of the "serialSns" field. -func (_u *BomItemUpdate) ClearSerialSns() *BomItemUpdate { - _u.mutation.ClearSerialSns() - return _u -} - -// Mutation returns the BomItemMutation object of the builder. -func (_u *BomItemUpdate) Mutation() *BomItemMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *BomItemUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *BomItemUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *BomItemUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *BomItemUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *BomItemUpdate) check() error { - if v, ok := _u.mutation.ProductCode(); ok { - if err := bomitem.ProductCodeValidator(v); err != nil { - return &ValidationError{Name: "productCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.productCode": %w`, err)} - } - } - if v, ok := _u.mutation.BomName(); ok { - if err := bomitem.BomNameValidator(v); err != nil { - return &ValidationError{Name: "bomName", err: fmt.Errorf(`ent: validator failed for field "BomItem.bomName": %w`, err)} - } - } - if v, ok := _u.mutation.MaterialCode(); ok { - if err := bomitem.MaterialCodeValidator(v); err != nil { - return &ValidationError{Name: "materialCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialCode": %w`, err)} - } - } - if v, ok := _u.mutation.MaterialName(); ok { - if err := bomitem.MaterialNameValidator(v); err != nil { - return &ValidationError{Name: "materialName", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialName": %w`, err)} - } - } - if v, ok := _u.mutation.Spec(); ok { - if err := bomitem.SpecValidator(v); err != nil { - return &ValidationError{Name: "spec", err: fmt.Errorf(`ent: validator failed for field "BomItem.spec": %w`, err)} - } - } - if v, ok := _u.mutation.Unit(); ok { - if err := bomitem.UnitValidator(v); err != nil { - return &ValidationError{Name: "unit", err: fmt.Errorf(`ent: validator failed for field "BomItem.unit": %w`, err)} - } - } - if v, ok := _u.mutation.ManageMode(); ok { - if err := bomitem.ManageModeValidator(v); err != nil { - return &ValidationError{Name: "manageMode", err: fmt.Errorf(`ent: validator failed for field "BomItem.manageMode": %w`, err)} - } - } - if v, ok := _u.mutation.RelatedStandard(); ok { - if err := bomitem.RelatedStandardValidator(v); err != nil { - return &ValidationError{Name: "relatedStandard", err: fmt.Errorf(`ent: validator failed for field "BomItem.relatedStandard": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (_u *BomItemUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BomItemUpdate { - _u.modifiers = append(_u.modifiers, modifiers...) - return _u -} - -func (_u *BomItemUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(bomitem.Table, bomitem.Columns, sqlgraph.NewFieldSpec(bomitem.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.ProductCode(); ok { - _spec.SetField(bomitem.FieldProductCode, field.TypeString, value) - } - if value, ok := _u.mutation.BomName(); ok { - _spec.SetField(bomitem.FieldBomName, field.TypeString, value) - } - if value, ok := _u.mutation.MaterialCode(); ok { - _spec.SetField(bomitem.FieldMaterialCode, field.TypeString, value) - } - if value, ok := _u.mutation.MaterialName(); ok { - _spec.SetField(bomitem.FieldMaterialName, field.TypeString, value) - } - if value, ok := _u.mutation.Spec(); ok { - _spec.SetField(bomitem.FieldSpec, field.TypeString, value) - } - if value, ok := _u.mutation.Unit(); ok { - _spec.SetField(bomitem.FieldUnit, field.TypeString, value) - } - if value, ok := _u.mutation.ManageMode(); ok { - _spec.SetField(bomitem.FieldManageMode, field.TypeString, value) - } - if value, ok := _u.mutation.UnitQty(); ok { - _spec.SetField(bomitem.FieldUnitQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedUnitQty(); ok { - _spec.AddField(bomitem.FieldUnitQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.LossRate(); ok { - _spec.SetField(bomitem.FieldLossRate, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedLossRate(); ok { - _spec.AddField(bomitem.FieldLossRate, field.TypeFloat64, value) - } - if value, ok := _u.mutation.RelatedStandard(); ok { - _spec.SetField(bomitem.FieldRelatedStandard, field.TypeString, value) - } - if value, ok := _u.mutation.RequiredQty(); ok { - _spec.SetField(bomitem.FieldRequiredQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedRequiredQty(); ok { - _spec.AddField(bomitem.FieldRequiredQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.SerialSns(); ok { - _spec.SetField(bomitem.FieldSerialSns, field.TypeJSON, value) - } - if value, ok := _u.mutation.AppendedSerialSns(); ok { - _spec.AddModifier(func(u *sql.UpdateBuilder) { - sqljson.Append(u, bomitem.FieldSerialSns, value) - }) - } - if _u.mutation.SerialSnsCleared() { - _spec.ClearField(bomitem.FieldSerialSns, field.TypeJSON) - } - _spec.AddModifiers(_u.modifiers...) - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{bomitem.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// BomItemUpdateOne is the builder for updating a single BomItem entity. -type BomItemUpdateOne struct { - config - fields []string - hooks []Hook - mutation *BomItemMutation - modifiers []func(*sql.UpdateBuilder) -} - -// SetProductCode sets the "productCode" field. -func (_u *BomItemUpdateOne) SetProductCode(v string) *BomItemUpdateOne { - _u.mutation.SetProductCode(v) - return _u -} - -// SetNillableProductCode sets the "productCode" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableProductCode(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetProductCode(*v) - } - return _u -} - -// SetBomName sets the "bomName" field. -func (_u *BomItemUpdateOne) SetBomName(v string) *BomItemUpdateOne { - _u.mutation.SetBomName(v) - return _u -} - -// SetNillableBomName sets the "bomName" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableBomName(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetBomName(*v) - } - return _u -} - -// SetMaterialCode sets the "materialCode" field. -func (_u *BomItemUpdateOne) SetMaterialCode(v string) *BomItemUpdateOne { - _u.mutation.SetMaterialCode(v) - return _u -} - -// SetNillableMaterialCode sets the "materialCode" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableMaterialCode(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetMaterialCode(*v) - } - return _u -} - -// SetMaterialName sets the "materialName" field. -func (_u *BomItemUpdateOne) SetMaterialName(v string) *BomItemUpdateOne { - _u.mutation.SetMaterialName(v) - return _u -} - -// SetNillableMaterialName sets the "materialName" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableMaterialName(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetMaterialName(*v) - } - return _u -} - -// SetSpec sets the "spec" field. -func (_u *BomItemUpdateOne) SetSpec(v string) *BomItemUpdateOne { - _u.mutation.SetSpec(v) - return _u -} - -// SetNillableSpec sets the "spec" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableSpec(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetSpec(*v) - } - return _u -} - -// SetUnit sets the "unit" field. -func (_u *BomItemUpdateOne) SetUnit(v string) *BomItemUpdateOne { - _u.mutation.SetUnit(v) - return _u -} - -// SetNillableUnit sets the "unit" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableUnit(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetUnit(*v) - } - return _u -} - -// SetManageMode sets the "manageMode" field. -func (_u *BomItemUpdateOne) SetManageMode(v string) *BomItemUpdateOne { - _u.mutation.SetManageMode(v) - return _u -} - -// SetNillableManageMode sets the "manageMode" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableManageMode(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetManageMode(*v) - } - return _u -} - -// SetUnitQty sets the "unitQty" field. -func (_u *BomItemUpdateOne) SetUnitQty(v float64) *BomItemUpdateOne { - _u.mutation.ResetUnitQty() - _u.mutation.SetUnitQty(v) - return _u -} - -// SetNillableUnitQty sets the "unitQty" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableUnitQty(v *float64) *BomItemUpdateOne { - if v != nil { - _u.SetUnitQty(*v) - } - return _u -} - -// AddUnitQty adds value to the "unitQty" field. -func (_u *BomItemUpdateOne) AddUnitQty(v float64) *BomItemUpdateOne { - _u.mutation.AddUnitQty(v) - return _u -} - -// SetLossRate sets the "lossRate" field. -func (_u *BomItemUpdateOne) SetLossRate(v float64) *BomItemUpdateOne { - _u.mutation.ResetLossRate() - _u.mutation.SetLossRate(v) - return _u -} - -// SetNillableLossRate sets the "lossRate" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableLossRate(v *float64) *BomItemUpdateOne { - if v != nil { - _u.SetLossRate(*v) - } - return _u -} - -// AddLossRate adds value to the "lossRate" field. -func (_u *BomItemUpdateOne) AddLossRate(v float64) *BomItemUpdateOne { - _u.mutation.AddLossRate(v) - return _u -} - -// SetRelatedStandard sets the "relatedStandard" field. -func (_u *BomItemUpdateOne) SetRelatedStandard(v string) *BomItemUpdateOne { - _u.mutation.SetRelatedStandard(v) - return _u -} - -// SetNillableRelatedStandard sets the "relatedStandard" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableRelatedStandard(v *string) *BomItemUpdateOne { - if v != nil { - _u.SetRelatedStandard(*v) - } - return _u -} - -// SetRequiredQty sets the "requiredQty" field. -func (_u *BomItemUpdateOne) SetRequiredQty(v float64) *BomItemUpdateOne { - _u.mutation.ResetRequiredQty() - _u.mutation.SetRequiredQty(v) - return _u -} - -// SetNillableRequiredQty sets the "requiredQty" field if the given value is not nil. -func (_u *BomItemUpdateOne) SetNillableRequiredQty(v *float64) *BomItemUpdateOne { - if v != nil { - _u.SetRequiredQty(*v) - } - return _u -} - -// AddRequiredQty adds value to the "requiredQty" field. -func (_u *BomItemUpdateOne) AddRequiredQty(v float64) *BomItemUpdateOne { - _u.mutation.AddRequiredQty(v) - return _u -} - -// SetSerialSns sets the "serialSns" field. -func (_u *BomItemUpdateOne) SetSerialSns(v []string) *BomItemUpdateOne { - _u.mutation.SetSerialSns(v) - return _u -} - -// AppendSerialSns appends value to the "serialSns" field. -func (_u *BomItemUpdateOne) AppendSerialSns(v []string) *BomItemUpdateOne { - _u.mutation.AppendSerialSns(v) - return _u -} - -// ClearSerialSns clears the value of the "serialSns" field. -func (_u *BomItemUpdateOne) ClearSerialSns() *BomItemUpdateOne { - _u.mutation.ClearSerialSns() - return _u -} - -// Mutation returns the BomItemMutation object of the builder. -func (_u *BomItemUpdateOne) Mutation() *BomItemMutation { - return _u.mutation -} - -// Where appends a list predicates to the BomItemUpdate builder. -func (_u *BomItemUpdateOne) Where(ps ...predicate.BomItem) *BomItemUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *BomItemUpdateOne) Select(field string, fields ...string) *BomItemUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated BomItem entity. -func (_u *BomItemUpdateOne) Save(ctx context.Context) (*BomItem, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *BomItemUpdateOne) SaveX(ctx context.Context) *BomItem { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *BomItemUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *BomItemUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *BomItemUpdateOne) check() error { - if v, ok := _u.mutation.ProductCode(); ok { - if err := bomitem.ProductCodeValidator(v); err != nil { - return &ValidationError{Name: "productCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.productCode": %w`, err)} - } - } - if v, ok := _u.mutation.BomName(); ok { - if err := bomitem.BomNameValidator(v); err != nil { - return &ValidationError{Name: "bomName", err: fmt.Errorf(`ent: validator failed for field "BomItem.bomName": %w`, err)} - } - } - if v, ok := _u.mutation.MaterialCode(); ok { - if err := bomitem.MaterialCodeValidator(v); err != nil { - return &ValidationError{Name: "materialCode", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialCode": %w`, err)} - } - } - if v, ok := _u.mutation.MaterialName(); ok { - if err := bomitem.MaterialNameValidator(v); err != nil { - return &ValidationError{Name: "materialName", err: fmt.Errorf(`ent: validator failed for field "BomItem.materialName": %w`, err)} - } - } - if v, ok := _u.mutation.Spec(); ok { - if err := bomitem.SpecValidator(v); err != nil { - return &ValidationError{Name: "spec", err: fmt.Errorf(`ent: validator failed for field "BomItem.spec": %w`, err)} - } - } - if v, ok := _u.mutation.Unit(); ok { - if err := bomitem.UnitValidator(v); err != nil { - return &ValidationError{Name: "unit", err: fmt.Errorf(`ent: validator failed for field "BomItem.unit": %w`, err)} - } - } - if v, ok := _u.mutation.ManageMode(); ok { - if err := bomitem.ManageModeValidator(v); err != nil { - return &ValidationError{Name: "manageMode", err: fmt.Errorf(`ent: validator failed for field "BomItem.manageMode": %w`, err)} - } - } - if v, ok := _u.mutation.RelatedStandard(); ok { - if err := bomitem.RelatedStandardValidator(v); err != nil { - return &ValidationError{Name: "relatedStandard", err: fmt.Errorf(`ent: validator failed for field "BomItem.relatedStandard": %w`, err)} - } - } - return nil -} - -// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. -func (_u *BomItemUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BomItemUpdateOne { - _u.modifiers = append(_u.modifiers, modifiers...) - return _u -} - -func (_u *BomItemUpdateOne) sqlSave(ctx context.Context) (_node *BomItem, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(bomitem.Table, bomitem.Columns, sqlgraph.NewFieldSpec(bomitem.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "BomItem.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, bomitem.FieldID) - for _, f := range fields { - if !bomitem.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != bomitem.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.ProductCode(); ok { - _spec.SetField(bomitem.FieldProductCode, field.TypeString, value) - } - if value, ok := _u.mutation.BomName(); ok { - _spec.SetField(bomitem.FieldBomName, field.TypeString, value) - } - if value, ok := _u.mutation.MaterialCode(); ok { - _spec.SetField(bomitem.FieldMaterialCode, field.TypeString, value) - } - if value, ok := _u.mutation.MaterialName(); ok { - _spec.SetField(bomitem.FieldMaterialName, field.TypeString, value) - } - if value, ok := _u.mutation.Spec(); ok { - _spec.SetField(bomitem.FieldSpec, field.TypeString, value) - } - if value, ok := _u.mutation.Unit(); ok { - _spec.SetField(bomitem.FieldUnit, field.TypeString, value) - } - if value, ok := _u.mutation.ManageMode(); ok { - _spec.SetField(bomitem.FieldManageMode, field.TypeString, value) - } - if value, ok := _u.mutation.UnitQty(); ok { - _spec.SetField(bomitem.FieldUnitQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedUnitQty(); ok { - _spec.AddField(bomitem.FieldUnitQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.LossRate(); ok { - _spec.SetField(bomitem.FieldLossRate, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedLossRate(); ok { - _spec.AddField(bomitem.FieldLossRate, field.TypeFloat64, value) - } - if value, ok := _u.mutation.RelatedStandard(); ok { - _spec.SetField(bomitem.FieldRelatedStandard, field.TypeString, value) - } - if value, ok := _u.mutation.RequiredQty(); ok { - _spec.SetField(bomitem.FieldRequiredQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.AddedRequiredQty(); ok { - _spec.AddField(bomitem.FieldRequiredQty, field.TypeFloat64, value) - } - if value, ok := _u.mutation.SerialSns(); ok { - _spec.SetField(bomitem.FieldSerialSns, field.TypeJSON, value) - } - if value, ok := _u.mutation.AppendedSerialSns(); ok { - _spec.AddModifier(func(u *sql.UpdateBuilder) { - sqljson.Append(u, bomitem.FieldSerialSns, value) - }) - } - if _u.mutation.SerialSnsCleared() { - _spec.ClearField(bomitem.FieldSerialSns, field.TypeJSON) - } - _spec.AddModifiers(_u.modifiers...) - _node = &BomItem{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{bomitem.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/bj_power_mes/ent/client.go b/bj_power_mes/ent/client.go index 3412282..73cafdc 100644 --- a/bj_power_mes/ent/client.go +++ b/bj_power_mes/ent/client.go @@ -15,7 +15,6 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" "bj_power_mes/ent/eventlog" @@ -35,6 +34,7 @@ import ( "bj_power_mes/ent/stationstate" "bj_power_mes/ent/stepcriterion" "bj_power_mes/ent/stepdata" + "bj_power_mes/ent/sysconfig" "bj_power_mes/ent/torqueauditlog" "bj_power_mes/ent/torquerecord" "bj_power_mes/ent/user" @@ -62,8 +62,6 @@ type Client struct { AssociationTrace *AssociationTraceClient // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient - // BomItem is the client for interacting with the BomItem builders. - BomItem *BomItemClient // DailyPlan is the client for interacting with the DailyPlan builders. DailyPlan *DailyPlanClient // Dock is the client for interacting with the Dock builders. @@ -102,6 +100,8 @@ type Client struct { StepCriterion *StepCriterionClient // StepData is the client for interacting with the StepData builders. StepData *StepDataClient + // SysConfig is the client for interacting with the SysConfig builders. + SysConfig *SysConfigClient // TorqueAuditLog is the client for interacting with the TorqueAuditLog builders. TorqueAuditLog *TorqueAuditLogClient // TorqueRecord is the client for interacting with the TorqueRecord builders. @@ -133,7 +133,6 @@ func (c *Client) init() { c.AlertRule = NewAlertRuleClient(c.config) c.AssociationTrace = NewAssociationTraceClient(c.config) c.Attachment = NewAttachmentClient(c.config) - c.BomItem = NewBomItemClient(c.config) c.DailyPlan = NewDailyPlanClient(c.config) c.Dock = NewDockClient(c.config) c.EventLog = NewEventLogClient(c.config) @@ -153,6 +152,7 @@ func (c *Client) init() { c.StationState = NewStationStateClient(c.config) c.StepCriterion = NewStepCriterionClient(c.config) c.StepData = NewStepDataClient(c.config) + c.SysConfig = NewSysConfigClient(c.config) c.TorqueAuditLog = NewTorqueAuditLogClient(c.config) c.TorqueRecord = NewTorqueRecordClient(c.config) c.User = NewUserClient(c.config) @@ -257,7 +257,6 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { AlertRule: NewAlertRuleClient(cfg), AssociationTrace: NewAssociationTraceClient(cfg), Attachment: NewAttachmentClient(cfg), - BomItem: NewBomItemClient(cfg), DailyPlan: NewDailyPlanClient(cfg), Dock: NewDockClient(cfg), EventLog: NewEventLogClient(cfg), @@ -277,6 +276,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { StationState: NewStationStateClient(cfg), StepCriterion: NewStepCriterionClient(cfg), StepData: NewStepDataClient(cfg), + SysConfig: NewSysConfigClient(cfg), TorqueAuditLog: NewTorqueAuditLogClient(cfg), TorqueRecord: NewTorqueRecordClient(cfg), User: NewUserClient(cfg), @@ -308,7 +308,6 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) AlertRule: NewAlertRuleClient(cfg), AssociationTrace: NewAssociationTraceClient(cfg), Attachment: NewAttachmentClient(cfg), - BomItem: NewBomItemClient(cfg), DailyPlan: NewDailyPlanClient(cfg), Dock: NewDockClient(cfg), EventLog: NewEventLogClient(cfg), @@ -328,6 +327,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) StationState: NewStationStateClient(cfg), StepCriterion: NewStepCriterionClient(cfg), StepData: NewStepDataClient(cfg), + SysConfig: NewSysConfigClient(cfg), TorqueAuditLog: NewTorqueAuditLogClient(cfg), TorqueRecord: NewTorqueRecordClient(cfg), User: NewUserClient(cfg), @@ -365,13 +365,13 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.BomItem, c.DailyPlan, - c.Dock, c.EventLog, c.FlowMaterial, c.InspectionRecord, c.LinePoint, + c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.DailyPlan, c.Dock, + c.EventLog, c.FlowMaterial, c.InspectionRecord, c.LinePoint, c.MaterialQtyReport, c.MaterialRequest, c.Permission, c.PlcMoveCmd, c.PlcSendLog, c.ProcessFlow, c.ProcessStep, c.Role, c.SemiFlow, c.Station, - c.StationState, c.StepCriterion, c.StepData, c.TorqueAuditLog, c.TorqueRecord, - c.User, c.UserStation, c.WorkOrder, c.Workpiece, c.WorkpieceBind, - c.WorkpieceProcess, + c.StationState, c.StepCriterion, c.StepData, c.SysConfig, c.TorqueAuditLog, + c.TorqueRecord, c.User, c.UserStation, c.WorkOrder, c.Workpiece, + c.WorkpieceBind, c.WorkpieceProcess, } { n.Use(hooks...) } @@ -381,13 +381,13 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.BomItem, c.DailyPlan, - c.Dock, c.EventLog, c.FlowMaterial, c.InspectionRecord, c.LinePoint, + c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.DailyPlan, c.Dock, + c.EventLog, c.FlowMaterial, c.InspectionRecord, c.LinePoint, c.MaterialQtyReport, c.MaterialRequest, c.Permission, c.PlcMoveCmd, c.PlcSendLog, c.ProcessFlow, c.ProcessStep, c.Role, c.SemiFlow, c.Station, - c.StationState, c.StepCriterion, c.StepData, c.TorqueAuditLog, c.TorqueRecord, - c.User, c.UserStation, c.WorkOrder, c.Workpiece, c.WorkpieceBind, - c.WorkpieceProcess, + c.StationState, c.StepCriterion, c.StepData, c.SysConfig, c.TorqueAuditLog, + c.TorqueRecord, c.User, c.UserStation, c.WorkOrder, c.Workpiece, + c.WorkpieceBind, c.WorkpieceProcess, } { n.Intercept(interceptors...) } @@ -404,8 +404,6 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.AssociationTrace.mutate(ctx, m) case *AttachmentMutation: return c.Attachment.mutate(ctx, m) - case *BomItemMutation: - return c.BomItem.mutate(ctx, m) case *DailyPlanMutation: return c.DailyPlan.mutate(ctx, m) case *DockMutation: @@ -444,6 +442,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.StepCriterion.mutate(ctx, m) case *StepDataMutation: return c.StepData.mutate(ctx, m) + case *SysConfigMutation: + return c.SysConfig.mutate(ctx, m) case *TorqueAuditLogMutation: return c.TorqueAuditLog.mutate(ctx, m) case *TorqueRecordMutation: @@ -997,139 +997,6 @@ func (c *AttachmentClient) mutate(ctx context.Context, m *AttachmentMutation) (V } } -// BomItemClient is a client for the BomItem schema. -type BomItemClient struct { - config -} - -// NewBomItemClient returns a client for the BomItem from the given config. -func NewBomItemClient(c config) *BomItemClient { - return &BomItemClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `bomitem.Hooks(f(g(h())))`. -func (c *BomItemClient) Use(hooks ...Hook) { - c.hooks.BomItem = append(c.hooks.BomItem, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `bomitem.Intercept(f(g(h())))`. -func (c *BomItemClient) Intercept(interceptors ...Interceptor) { - c.inters.BomItem = append(c.inters.BomItem, interceptors...) -} - -// Create returns a builder for creating a BomItem entity. -func (c *BomItemClient) Create() *BomItemCreate { - mutation := newBomItemMutation(c.config, OpCreate) - return &BomItemCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of BomItem entities. -func (c *BomItemClient) CreateBulk(builders ...*BomItemCreate) *BomItemCreateBulk { - return &BomItemCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *BomItemClient) MapCreateBulk(slice any, setFunc func(*BomItemCreate, int)) *BomItemCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &BomItemCreateBulk{err: fmt.Errorf("calling to BomItemClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*BomItemCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &BomItemCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for BomItem. -func (c *BomItemClient) Update() *BomItemUpdate { - mutation := newBomItemMutation(c.config, OpUpdate) - return &BomItemUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *BomItemClient) UpdateOne(_m *BomItem) *BomItemUpdateOne { - mutation := newBomItemMutation(c.config, OpUpdateOne, withBomItem(_m)) - return &BomItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *BomItemClient) UpdateOneID(id int) *BomItemUpdateOne { - mutation := newBomItemMutation(c.config, OpUpdateOne, withBomItemID(id)) - return &BomItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for BomItem. -func (c *BomItemClient) Delete() *BomItemDelete { - mutation := newBomItemMutation(c.config, OpDelete) - return &BomItemDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *BomItemClient) DeleteOne(_m *BomItem) *BomItemDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *BomItemClient) DeleteOneID(id int) *BomItemDeleteOne { - builder := c.Delete().Where(bomitem.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &BomItemDeleteOne{builder} -} - -// Query returns a query builder for BomItem. -func (c *BomItemClient) Query() *BomItemQuery { - return &BomItemQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeBomItem}, - inters: c.Interceptors(), - } -} - -// Get returns a BomItem entity by its id. -func (c *BomItemClient) Get(ctx context.Context, id int) (*BomItem, error) { - return c.Query().Where(bomitem.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *BomItemClient) GetX(ctx context.Context, id int) *BomItem { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *BomItemClient) Hooks() []Hook { - return c.hooks.BomItem -} - -// Interceptors returns the client interceptors. -func (c *BomItemClient) Interceptors() []Interceptor { - return c.inters.BomItem -} - -func (c *BomItemClient) mutate(ctx context.Context, m *BomItemMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&BomItemCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&BomItemUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&BomItemUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&BomItemDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown BomItem mutation op: %q", m.Op()) - } -} - // DailyPlanClient is a client for the DailyPlan schema. type DailyPlanClient struct { config @@ -3657,6 +3524,139 @@ func (c *StepDataClient) mutate(ctx context.Context, m *StepDataMutation) (Value } } +// SysConfigClient is a client for the SysConfig schema. +type SysConfigClient struct { + config +} + +// NewSysConfigClient returns a client for the SysConfig from the given config. +func NewSysConfigClient(c config) *SysConfigClient { + return &SysConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `sysconfig.Hooks(f(g(h())))`. +func (c *SysConfigClient) Use(hooks ...Hook) { + c.hooks.SysConfig = append(c.hooks.SysConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `sysconfig.Intercept(f(g(h())))`. +func (c *SysConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.SysConfig = append(c.inters.SysConfig, interceptors...) +} + +// Create returns a builder for creating a SysConfig entity. +func (c *SysConfigClient) Create() *SysConfigCreate { + mutation := newSysConfigMutation(c.config, OpCreate) + return &SysConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SysConfig entities. +func (c *SysConfigClient) CreateBulk(builders ...*SysConfigCreate) *SysConfigCreateBulk { + return &SysConfigCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *SysConfigClient) MapCreateBulk(slice any, setFunc func(*SysConfigCreate, int)) *SysConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SysConfigCreateBulk{err: fmt.Errorf("calling to SysConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SysConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SysConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SysConfig. +func (c *SysConfigClient) Update() *SysConfigUpdate { + mutation := newSysConfigMutation(c.config, OpUpdate) + return &SysConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SysConfigClient) UpdateOne(_m *SysConfig) *SysConfigUpdateOne { + mutation := newSysConfigMutation(c.config, OpUpdateOne, withSysConfig(_m)) + return &SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SysConfigClient) UpdateOneID(id int) *SysConfigUpdateOne { + mutation := newSysConfigMutation(c.config, OpUpdateOne, withSysConfigID(id)) + return &SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SysConfig. +func (c *SysConfigClient) Delete() *SysConfigDelete { + mutation := newSysConfigMutation(c.config, OpDelete) + return &SysConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SysConfigClient) DeleteOne(_m *SysConfig) *SysConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SysConfigClient) DeleteOneID(id int) *SysConfigDeleteOne { + builder := c.Delete().Where(sysconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SysConfigDeleteOne{builder} +} + +// Query returns a query builder for SysConfig. +func (c *SysConfigClient) Query() *SysConfigQuery { + return &SysConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSysConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a SysConfig entity by its id. +func (c *SysConfigClient) Get(ctx context.Context, id int) (*SysConfig, error) { + return c.Query().Where(sysconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SysConfigClient) GetX(ctx context.Context, id int) *SysConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SysConfigClient) Hooks() []Hook { + return c.hooks.SysConfig +} + +// Interceptors returns the client interceptors. +func (c *SysConfigClient) Interceptors() []Interceptor { + return c.inters.SysConfig +} + +func (c *SysConfigClient) mutate(ctx context.Context, m *SysConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SysConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SysConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SysConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown SysConfig mutation op: %q", m.Op()) + } +} + // TorqueAuditLogClient is a client for the TorqueAuditLog schema. type TorqueAuditLogClient struct { config @@ -4724,18 +4724,18 @@ func (c *WorkpieceProcessClient) mutate(ctx context.Context, m *WorkpieceProcess // hooks and interceptors per client, for fast access. type ( hooks struct { - Alert, AlertRule, AssociationTrace, Attachment, BomItem, DailyPlan, Dock, - EventLog, FlowMaterial, InspectionRecord, LinePoint, MaterialQtyReport, - MaterialRequest, Permission, PlcMoveCmd, PlcSendLog, ProcessFlow, ProcessStep, - Role, SemiFlow, Station, StationState, StepCriterion, StepData, TorqueAuditLog, + Alert, AlertRule, AssociationTrace, Attachment, DailyPlan, Dock, EventLog, + FlowMaterial, InspectionRecord, LinePoint, MaterialQtyReport, MaterialRequest, + Permission, PlcMoveCmd, PlcSendLog, ProcessFlow, ProcessStep, Role, SemiFlow, + Station, StationState, StepCriterion, StepData, SysConfig, TorqueAuditLog, TorqueRecord, User, UserStation, WorkOrder, Workpiece, WorkpieceBind, WorkpieceProcess []ent.Hook } inters struct { - Alert, AlertRule, AssociationTrace, Attachment, BomItem, DailyPlan, Dock, - EventLog, FlowMaterial, InspectionRecord, LinePoint, MaterialQtyReport, - MaterialRequest, Permission, PlcMoveCmd, PlcSendLog, ProcessFlow, ProcessStep, - Role, SemiFlow, Station, StationState, StepCriterion, StepData, TorqueAuditLog, + Alert, AlertRule, AssociationTrace, Attachment, DailyPlan, Dock, EventLog, + FlowMaterial, InspectionRecord, LinePoint, MaterialQtyReport, MaterialRequest, + Permission, PlcMoveCmd, PlcSendLog, ProcessFlow, ProcessStep, Role, SemiFlow, + Station, StationState, StepCriterion, StepData, SysConfig, TorqueAuditLog, TorqueRecord, User, UserStation, WorkOrder, Workpiece, WorkpieceBind, WorkpieceProcess []ent.Interceptor } diff --git a/bj_power_mes/ent/ent.go b/bj_power_mes/ent/ent.go index e03dbd2..277952f 100644 --- a/bj_power_mes/ent/ent.go +++ b/bj_power_mes/ent/ent.go @@ -7,7 +7,6 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" "bj_power_mes/ent/eventlog" @@ -27,6 +26,7 @@ import ( "bj_power_mes/ent/stationstate" "bj_power_mes/ent/stepcriterion" "bj_power_mes/ent/stepdata" + "bj_power_mes/ent/sysconfig" "bj_power_mes/ent/torqueauditlog" "bj_power_mes/ent/torquerecord" "bj_power_mes/ent/user" @@ -108,7 +108,6 @@ func checkColumn(t, c string) error { alertrule.Table: alertrule.ValidColumn, associationtrace.Table: associationtrace.ValidColumn, attachment.Table: attachment.ValidColumn, - bomitem.Table: bomitem.ValidColumn, dailyplan.Table: dailyplan.ValidColumn, dock.Table: dock.ValidColumn, eventlog.Table: eventlog.ValidColumn, @@ -128,6 +127,7 @@ func checkColumn(t, c string) error { stationstate.Table: stationstate.ValidColumn, stepcriterion.Table: stepcriterion.ValidColumn, stepdata.Table: stepdata.ValidColumn, + sysconfig.Table: sysconfig.ValidColumn, torqueauditlog.Table: torqueauditlog.ValidColumn, torquerecord.Table: torquerecord.ValidColumn, user.Table: user.ValidColumn, diff --git a/bj_power_mes/ent/hook/hook.go b/bj_power_mes/ent/hook/hook.go index b6ca4b8..a2cc695 100644 --- a/bj_power_mes/ent/hook/hook.go +++ b/bj_power_mes/ent/hook/hook.go @@ -56,18 +56,6 @@ func (f AttachmentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AttachmentMutation", m) } -// The BomItemFunc type is an adapter to allow the use of ordinary -// function as BomItem mutator. -type BomItemFunc func(context.Context, *ent.BomItemMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f BomItemFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.BomItemMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.BomItemMutation", m) -} - // The DailyPlanFunc type is an adapter to allow the use of ordinary // function as DailyPlan mutator. type DailyPlanFunc func(context.Context, *ent.DailyPlanMutation) (ent.Value, error) @@ -296,6 +284,18 @@ func (f StepDataFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, er return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.StepDataMutation", m) } +// The SysConfigFunc type is an adapter to allow the use of ordinary +// function as SysConfig mutator. +type SysConfigFunc func(context.Context, *ent.SysConfigMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SysConfigFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SysConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SysConfigMutation", m) +} + // The TorqueAuditLogFunc type is an adapter to allow the use of ordinary // function as TorqueAuditLog mutator. type TorqueAuditLogFunc func(context.Context, *ent.TorqueAuditLogMutation) (ent.Value, error) diff --git a/bj_power_mes/ent/migrate/schema.go b/bj_power_mes/ent/migrate/schema.go index cf24e55..39fbd64 100644 --- a/bj_power_mes/ent/migrate/schema.go +++ b/bj_power_mes/ent/migrate/schema.go @@ -147,41 +147,6 @@ var ( }, }, } - // WorkOrderBomColumns holds the columns for the "work_order_bom" table. - WorkOrderBomColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "product_code", Type: field.TypeString, Size: 64, Default: ""}, - {Name: "bom_name", Type: field.TypeString, Size: 64, Default: "默认"}, - {Name: "material_code", Type: field.TypeString, Size: 64}, - {Name: "material_name", Type: field.TypeString, Size: 128, Default: ""}, - {Name: "spec", Type: field.TypeString, Size: 128, Default: ""}, - {Name: "unit", Type: field.TypeString, Size: 16, Default: ""}, - {Name: "manage_mode", Type: field.TypeString, Size: 10, Default: "2"}, - {Name: "unit_qty", Type: field.TypeFloat64, Default: 0}, - {Name: "loss_rate", Type: field.TypeFloat64, Default: 0}, - {Name: "related_standard", Type: field.TypeString, Size: 255, Default: ""}, - {Name: "required_qty", Type: field.TypeFloat64, Default: 0}, - {Name: "serial_sns", Type: field.TypeJSON, Nullable: true, SchemaType: map[string]string{"postgres": "jsonb"}}, - {Name: "created_at", Type: field.TypeTime}, - } - // WorkOrderBomTable holds the schema information for the "work_order_bom" table. - WorkOrderBomTable = &schema.Table{ - Name: "work_order_bom", - Columns: WorkOrderBomColumns, - PrimaryKey: []*schema.Column{WorkOrderBomColumns[0]}, - Indexes: []*schema.Index{ - { - Name: "bomitem_product_code", - Unique: false, - Columns: []*schema.Column{WorkOrderBomColumns[1]}, - }, - { - Name: "bomitem_product_code_bom_name_material_code", - Unique: true, - Columns: []*schema.Column{WorkOrderBomColumns[1], WorkOrderBomColumns[2], WorkOrderBomColumns[3]}, - }, - }, - } // DailyPlanColumns holds the columns for the "daily_plan" table. DailyPlanColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -721,6 +686,7 @@ var ( {Name: "is_builtin", Type: field.TypeBool, Default: false}, {Name: "has_dock", Type: field.TypeBool, Default: false}, {Name: "dock_code", Type: field.TypeString, Size: 20, Default: ""}, + {Name: "visible_tabs", Type: field.TypeJSON, Nullable: true}, {Name: "created_at", Type: field.TypeTime}, } // StationTable holds the schema information for the "station" table. @@ -824,6 +790,19 @@ var ( }, }, } + // SysConfigColumns holds the columns for the "sys_config" table. + SysConfigColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "key", Type: field.TypeString, Unique: true, Size: 64}, + {Name: "value", Type: field.TypeString, Size: 512}, + {Name: "remark", Type: field.TypeString, Nullable: true, Size: 255}, + } + // SysConfigTable holds the schema information for the "sys_config" table. + SysConfigTable = &schema.Table{ + Name: "sys_config", + Columns: SysConfigColumns, + PrimaryKey: []*schema.Column{SysConfigColumns[0]}, + } // TorqueAuditLogColumns holds the columns for the "torque_audit_log" table. TorqueAuditLogColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -1150,7 +1129,6 @@ var ( AlertRuleTable, AssociationTraceTable, AttachmentTable, - WorkOrderBomTable, DailyPlanTable, DockTable, EventLogTable, @@ -1170,6 +1148,7 @@ var ( StationStateTable, StepCriterionTable, StepDataTable, + SysConfigTable, TorqueAuditLogTable, TorqueRecordTable, UserTable, @@ -1194,9 +1173,6 @@ func init() { AttachmentTable.Annotation = &entsql.Annotation{ Table: "attachment", } - WorkOrderBomTable.Annotation = &entsql.Annotation{ - Table: "work_order_bom", - } DailyPlanTable.Annotation = &entsql.Annotation{ Table: "daily_plan", } @@ -1254,6 +1230,9 @@ func init() { StepDataTable.Annotation = &entsql.Annotation{ Table: "step_data", } + SysConfigTable.Annotation = &entsql.Annotation{ + Table: "sys_config", + } TorqueAuditLogTable.Annotation = &entsql.Annotation{ Table: "torque_audit_log", } diff --git a/bj_power_mes/ent/mutation.go b/bj_power_mes/ent/mutation.go index fb3a245..19f88a9 100644 --- a/bj_power_mes/ent/mutation.go +++ b/bj_power_mes/ent/mutation.go @@ -7,7 +7,6 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" "bj_power_mes/ent/eventlog" @@ -28,6 +27,7 @@ import ( "bj_power_mes/ent/stationstate" "bj_power_mes/ent/stepcriterion" "bj_power_mes/ent/stepdata" + "bj_power_mes/ent/sysconfig" "bj_power_mes/ent/torqueauditlog" "bj_power_mes/ent/torquerecord" "bj_power_mes/ent/user" @@ -59,7 +59,6 @@ const ( TypeAlertRule = "AlertRule" TypeAssociationTrace = "AssociationTrace" TypeAttachment = "Attachment" - TypeBomItem = "BomItem" TypeDailyPlan = "DailyPlan" TypeDock = "Dock" TypeEventLog = "EventLog" @@ -79,6 +78,7 @@ const ( TypeStationState = "StationState" TypeStepCriterion = "StepCriterion" TypeStepData = "StepData" + TypeSysConfig = "SysConfig" TypeTorqueAuditLog = "TorqueAuditLog" TypeTorqueRecord = "TorqueRecord" TypeUser = "User" @@ -3610,1127 +3610,6 @@ func (m *AttachmentMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Attachment edge %s", name) } -// BomItemMutation represents an operation that mutates the BomItem nodes in the graph. -type BomItemMutation struct { - config - op Op - typ string - id *int - productCode *string - bomName *string - materialCode *string - materialName *string - spec *string - unit *string - manageMode *string - unitQty *float64 - addunitQty *float64 - lossRate *float64 - addlossRate *float64 - relatedStandard *string - requiredQty *float64 - addrequiredQty *float64 - serialSns *[]string - appendserialSns []string - createdAt *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*BomItem, error) - predicates []predicate.BomItem -} - -var _ ent.Mutation = (*BomItemMutation)(nil) - -// bomitemOption allows management of the mutation configuration using functional options. -type bomitemOption func(*BomItemMutation) - -// newBomItemMutation creates new mutation for the BomItem entity. -func newBomItemMutation(c config, op Op, opts ...bomitemOption) *BomItemMutation { - m := &BomItemMutation{ - config: c, - op: op, - typ: TypeBomItem, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withBomItemID sets the ID field of the mutation. -func withBomItemID(id int) bomitemOption { - return func(m *BomItemMutation) { - var ( - err error - once sync.Once - value *BomItem - ) - m.oldValue = func(ctx context.Context) (*BomItem, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().BomItem.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withBomItem sets the old BomItem of the mutation. -func withBomItem(node *BomItem) bomitemOption { - return func(m *BomItemMutation) { - m.oldValue = func(context.Context) (*BomItem, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m BomItemMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m BomItemMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of BomItem entities. -func (m *BomItemMutation) SetID(id int) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *BomItemMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *BomItemMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().BomItem.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetProductCode sets the "productCode" field. -func (m *BomItemMutation) SetProductCode(s string) { - m.productCode = &s -} - -// ProductCode returns the value of the "productCode" field in the mutation. -func (m *BomItemMutation) ProductCode() (r string, exists bool) { - v := m.productCode - if v == nil { - return - } - return *v, true -} - -// OldProductCode returns the old "productCode" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldProductCode(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProductCode is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProductCode requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldProductCode: %w", err) - } - return oldValue.ProductCode, nil -} - -// ResetProductCode resets all changes to the "productCode" field. -func (m *BomItemMutation) ResetProductCode() { - m.productCode = nil -} - -// SetBomName sets the "bomName" field. -func (m *BomItemMutation) SetBomName(s string) { - m.bomName = &s -} - -// BomName returns the value of the "bomName" field in the mutation. -func (m *BomItemMutation) BomName() (r string, exists bool) { - v := m.bomName - if v == nil { - return - } - return *v, true -} - -// OldBomName returns the old "bomName" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldBomName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldBomName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldBomName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldBomName: %w", err) - } - return oldValue.BomName, nil -} - -// ResetBomName resets all changes to the "bomName" field. -func (m *BomItemMutation) ResetBomName() { - m.bomName = nil -} - -// SetMaterialCode sets the "materialCode" field. -func (m *BomItemMutation) SetMaterialCode(s string) { - m.materialCode = &s -} - -// MaterialCode returns the value of the "materialCode" field in the mutation. -func (m *BomItemMutation) MaterialCode() (r string, exists bool) { - v := m.materialCode - if v == nil { - return - } - return *v, true -} - -// OldMaterialCode returns the old "materialCode" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldMaterialCode(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMaterialCode is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMaterialCode requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMaterialCode: %w", err) - } - return oldValue.MaterialCode, nil -} - -// ResetMaterialCode resets all changes to the "materialCode" field. -func (m *BomItemMutation) ResetMaterialCode() { - m.materialCode = nil -} - -// SetMaterialName sets the "materialName" field. -func (m *BomItemMutation) SetMaterialName(s string) { - m.materialName = &s -} - -// MaterialName returns the value of the "materialName" field in the mutation. -func (m *BomItemMutation) MaterialName() (r string, exists bool) { - v := m.materialName - if v == nil { - return - } - return *v, true -} - -// OldMaterialName returns the old "materialName" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldMaterialName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMaterialName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMaterialName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMaterialName: %w", err) - } - return oldValue.MaterialName, nil -} - -// ResetMaterialName resets all changes to the "materialName" field. -func (m *BomItemMutation) ResetMaterialName() { - m.materialName = nil -} - -// SetSpec sets the "spec" field. -func (m *BomItemMutation) SetSpec(s string) { - m.spec = &s -} - -// Spec returns the value of the "spec" field in the mutation. -func (m *BomItemMutation) Spec() (r string, exists bool) { - v := m.spec - if v == nil { - return - } - return *v, true -} - -// OldSpec returns the old "spec" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldSpec(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSpec is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSpec requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSpec: %w", err) - } - return oldValue.Spec, nil -} - -// ResetSpec resets all changes to the "spec" field. -func (m *BomItemMutation) ResetSpec() { - m.spec = nil -} - -// SetUnit sets the "unit" field. -func (m *BomItemMutation) SetUnit(s string) { - m.unit = &s -} - -// Unit returns the value of the "unit" field in the mutation. -func (m *BomItemMutation) Unit() (r string, exists bool) { - v := m.unit - if v == nil { - return - } - return *v, true -} - -// OldUnit returns the old "unit" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldUnit(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUnit is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUnit requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUnit: %w", err) - } - return oldValue.Unit, nil -} - -// ResetUnit resets all changes to the "unit" field. -func (m *BomItemMutation) ResetUnit() { - m.unit = nil -} - -// SetManageMode sets the "manageMode" field. -func (m *BomItemMutation) SetManageMode(s string) { - m.manageMode = &s -} - -// ManageMode returns the value of the "manageMode" field in the mutation. -func (m *BomItemMutation) ManageMode() (r string, exists bool) { - v := m.manageMode - if v == nil { - return - } - return *v, true -} - -// OldManageMode returns the old "manageMode" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldManageMode(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldManageMode is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldManageMode requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldManageMode: %w", err) - } - return oldValue.ManageMode, nil -} - -// ResetManageMode resets all changes to the "manageMode" field. -func (m *BomItemMutation) ResetManageMode() { - m.manageMode = nil -} - -// SetUnitQty sets the "unitQty" field. -func (m *BomItemMutation) SetUnitQty(f float64) { - m.unitQty = &f - m.addunitQty = nil -} - -// UnitQty returns the value of the "unitQty" field in the mutation. -func (m *BomItemMutation) UnitQty() (r float64, exists bool) { - v := m.unitQty - if v == nil { - return - } - return *v, true -} - -// OldUnitQty returns the old "unitQty" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldUnitQty(ctx context.Context) (v float64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUnitQty is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUnitQty requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUnitQty: %w", err) - } - return oldValue.UnitQty, nil -} - -// AddUnitQty adds f to the "unitQty" field. -func (m *BomItemMutation) AddUnitQty(f float64) { - if m.addunitQty != nil { - *m.addunitQty += f - } else { - m.addunitQty = &f - } -} - -// AddedUnitQty returns the value that was added to the "unitQty" field in this mutation. -func (m *BomItemMutation) AddedUnitQty() (r float64, exists bool) { - v := m.addunitQty - if v == nil { - return - } - return *v, true -} - -// ResetUnitQty resets all changes to the "unitQty" field. -func (m *BomItemMutation) ResetUnitQty() { - m.unitQty = nil - m.addunitQty = nil -} - -// SetLossRate sets the "lossRate" field. -func (m *BomItemMutation) SetLossRate(f float64) { - m.lossRate = &f - m.addlossRate = nil -} - -// LossRate returns the value of the "lossRate" field in the mutation. -func (m *BomItemMutation) LossRate() (r float64, exists bool) { - v := m.lossRate - if v == nil { - return - } - return *v, true -} - -// OldLossRate returns the old "lossRate" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldLossRate(ctx context.Context) (v float64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLossRate is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLossRate requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldLossRate: %w", err) - } - return oldValue.LossRate, nil -} - -// AddLossRate adds f to the "lossRate" field. -func (m *BomItemMutation) AddLossRate(f float64) { - if m.addlossRate != nil { - *m.addlossRate += f - } else { - m.addlossRate = &f - } -} - -// AddedLossRate returns the value that was added to the "lossRate" field in this mutation. -func (m *BomItemMutation) AddedLossRate() (r float64, exists bool) { - v := m.addlossRate - if v == nil { - return - } - return *v, true -} - -// ResetLossRate resets all changes to the "lossRate" field. -func (m *BomItemMutation) ResetLossRate() { - m.lossRate = nil - m.addlossRate = nil -} - -// SetRelatedStandard sets the "relatedStandard" field. -func (m *BomItemMutation) SetRelatedStandard(s string) { - m.relatedStandard = &s -} - -// RelatedStandard returns the value of the "relatedStandard" field in the mutation. -func (m *BomItemMutation) RelatedStandard() (r string, exists bool) { - v := m.relatedStandard - if v == nil { - return - } - return *v, true -} - -// OldRelatedStandard returns the old "relatedStandard" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldRelatedStandard(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRelatedStandard is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRelatedStandard requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRelatedStandard: %w", err) - } - return oldValue.RelatedStandard, nil -} - -// ResetRelatedStandard resets all changes to the "relatedStandard" field. -func (m *BomItemMutation) ResetRelatedStandard() { - m.relatedStandard = nil -} - -// SetRequiredQty sets the "requiredQty" field. -func (m *BomItemMutation) SetRequiredQty(f float64) { - m.requiredQty = &f - m.addrequiredQty = nil -} - -// RequiredQty returns the value of the "requiredQty" field in the mutation. -func (m *BomItemMutation) RequiredQty() (r float64, exists bool) { - v := m.requiredQty - if v == nil { - return - } - return *v, true -} - -// OldRequiredQty returns the old "requiredQty" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldRequiredQty(ctx context.Context) (v float64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRequiredQty is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRequiredQty requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRequiredQty: %w", err) - } - return oldValue.RequiredQty, nil -} - -// AddRequiredQty adds f to the "requiredQty" field. -func (m *BomItemMutation) AddRequiredQty(f float64) { - if m.addrequiredQty != nil { - *m.addrequiredQty += f - } else { - m.addrequiredQty = &f - } -} - -// AddedRequiredQty returns the value that was added to the "requiredQty" field in this mutation. -func (m *BomItemMutation) AddedRequiredQty() (r float64, exists bool) { - v := m.addrequiredQty - if v == nil { - return - } - return *v, true -} - -// ResetRequiredQty resets all changes to the "requiredQty" field. -func (m *BomItemMutation) ResetRequiredQty() { - m.requiredQty = nil - m.addrequiredQty = nil -} - -// SetSerialSns sets the "serialSns" field. -func (m *BomItemMutation) SetSerialSns(s []string) { - m.serialSns = &s - m.appendserialSns = nil -} - -// SerialSns returns the value of the "serialSns" field in the mutation. -func (m *BomItemMutation) SerialSns() (r []string, exists bool) { - v := m.serialSns - if v == nil { - return - } - return *v, true -} - -// OldSerialSns returns the old "serialSns" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldSerialSns(ctx context.Context) (v []string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldSerialSns is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldSerialSns requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldSerialSns: %w", err) - } - return oldValue.SerialSns, nil -} - -// AppendSerialSns adds s to the "serialSns" field. -func (m *BomItemMutation) AppendSerialSns(s []string) { - m.appendserialSns = append(m.appendserialSns, s...) -} - -// AppendedSerialSns returns the list of values that were appended to the "serialSns" field in this mutation. -func (m *BomItemMutation) AppendedSerialSns() ([]string, bool) { - if len(m.appendserialSns) == 0 { - return nil, false - } - return m.appendserialSns, true -} - -// ClearSerialSns clears the value of the "serialSns" field. -func (m *BomItemMutation) ClearSerialSns() { - m.serialSns = nil - m.appendserialSns = nil - m.clearedFields[bomitem.FieldSerialSns] = struct{}{} -} - -// SerialSnsCleared returns if the "serialSns" field was cleared in this mutation. -func (m *BomItemMutation) SerialSnsCleared() bool { - _, ok := m.clearedFields[bomitem.FieldSerialSns] - return ok -} - -// ResetSerialSns resets all changes to the "serialSns" field. -func (m *BomItemMutation) ResetSerialSns() { - m.serialSns = nil - m.appendserialSns = nil - delete(m.clearedFields, bomitem.FieldSerialSns) -} - -// SetCreatedAt sets the "createdAt" field. -func (m *BomItemMutation) SetCreatedAt(t time.Time) { - m.createdAt = &t -} - -// CreatedAt returns the value of the "createdAt" field in the mutation. -func (m *BomItemMutation) CreatedAt() (r time.Time, exists bool) { - v := m.createdAt - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "createdAt" field's value of the BomItem entity. -// If the BomItem 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 *BomItemMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "createdAt" field. -func (m *BomItemMutation) ResetCreatedAt() { - m.createdAt = nil -} - -// Where appends a list predicates to the BomItemMutation builder. -func (m *BomItemMutation) Where(ps ...predicate.BomItem) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the BomItemMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *BomItemMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.BomItem, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *BomItemMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *BomItemMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (BomItem). -func (m *BomItemMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *BomItemMutation) Fields() []string { - fields := make([]string, 0, 13) - if m.productCode != nil { - fields = append(fields, bomitem.FieldProductCode) - } - if m.bomName != nil { - fields = append(fields, bomitem.FieldBomName) - } - if m.materialCode != nil { - fields = append(fields, bomitem.FieldMaterialCode) - } - if m.materialName != nil { - fields = append(fields, bomitem.FieldMaterialName) - } - if m.spec != nil { - fields = append(fields, bomitem.FieldSpec) - } - if m.unit != nil { - fields = append(fields, bomitem.FieldUnit) - } - if m.manageMode != nil { - fields = append(fields, bomitem.FieldManageMode) - } - if m.unitQty != nil { - fields = append(fields, bomitem.FieldUnitQty) - } - if m.lossRate != nil { - fields = append(fields, bomitem.FieldLossRate) - } - if m.relatedStandard != nil { - fields = append(fields, bomitem.FieldRelatedStandard) - } - if m.requiredQty != nil { - fields = append(fields, bomitem.FieldRequiredQty) - } - if m.serialSns != nil { - fields = append(fields, bomitem.FieldSerialSns) - } - if m.createdAt != nil { - fields = append(fields, bomitem.FieldCreatedAt) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *BomItemMutation) Field(name string) (ent.Value, bool) { - switch name { - case bomitem.FieldProductCode: - return m.ProductCode() - case bomitem.FieldBomName: - return m.BomName() - case bomitem.FieldMaterialCode: - return m.MaterialCode() - case bomitem.FieldMaterialName: - return m.MaterialName() - case bomitem.FieldSpec: - return m.Spec() - case bomitem.FieldUnit: - return m.Unit() - case bomitem.FieldManageMode: - return m.ManageMode() - case bomitem.FieldUnitQty: - return m.UnitQty() - case bomitem.FieldLossRate: - return m.LossRate() - case bomitem.FieldRelatedStandard: - return m.RelatedStandard() - case bomitem.FieldRequiredQty: - return m.RequiredQty() - case bomitem.FieldSerialSns: - return m.SerialSns() - case bomitem.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *BomItemMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case bomitem.FieldProductCode: - return m.OldProductCode(ctx) - case bomitem.FieldBomName: - return m.OldBomName(ctx) - case bomitem.FieldMaterialCode: - return m.OldMaterialCode(ctx) - case bomitem.FieldMaterialName: - return m.OldMaterialName(ctx) - case bomitem.FieldSpec: - return m.OldSpec(ctx) - case bomitem.FieldUnit: - return m.OldUnit(ctx) - case bomitem.FieldManageMode: - return m.OldManageMode(ctx) - case bomitem.FieldUnitQty: - return m.OldUnitQty(ctx) - case bomitem.FieldLossRate: - return m.OldLossRate(ctx) - case bomitem.FieldRelatedStandard: - return m.OldRelatedStandard(ctx) - case bomitem.FieldRequiredQty: - return m.OldRequiredQty(ctx) - case bomitem.FieldSerialSns: - return m.OldSerialSns(ctx) - case bomitem.FieldCreatedAt: - return m.OldCreatedAt(ctx) - } - return nil, fmt.Errorf("unknown BomItem field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *BomItemMutation) SetField(name string, value ent.Value) error { - switch name { - case bomitem.FieldProductCode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetProductCode(v) - return nil - case bomitem.FieldBomName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetBomName(v) - return nil - case bomitem.FieldMaterialCode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMaterialCode(v) - return nil - case bomitem.FieldMaterialName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMaterialName(v) - return nil - case bomitem.FieldSpec: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSpec(v) - return nil - case bomitem.FieldUnit: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUnit(v) - return nil - case bomitem.FieldManageMode: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetManageMode(v) - return nil - case bomitem.FieldUnitQty: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUnitQty(v) - return nil - case bomitem.FieldLossRate: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLossRate(v) - return nil - case bomitem.FieldRelatedStandard: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRelatedStandard(v) - return nil - case bomitem.FieldRequiredQty: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRequiredQty(v) - return nil - case bomitem.FieldSerialSns: - v, ok := value.([]string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetSerialSns(v) - return nil - case bomitem.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - } - return fmt.Errorf("unknown BomItem field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *BomItemMutation) AddedFields() []string { - var fields []string - if m.addunitQty != nil { - fields = append(fields, bomitem.FieldUnitQty) - } - if m.addlossRate != nil { - fields = append(fields, bomitem.FieldLossRate) - } - if m.addrequiredQty != nil { - fields = append(fields, bomitem.FieldRequiredQty) - } - return fields -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *BomItemMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case bomitem.FieldUnitQty: - return m.AddedUnitQty() - case bomitem.FieldLossRate: - return m.AddedLossRate() - case bomitem.FieldRequiredQty: - return m.AddedRequiredQty() - } - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *BomItemMutation) AddField(name string, value ent.Value) error { - switch name { - case bomitem.FieldUnitQty: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddUnitQty(v) - return nil - case bomitem.FieldLossRate: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddLossRate(v) - return nil - case bomitem.FieldRequiredQty: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddRequiredQty(v) - return nil - } - return fmt.Errorf("unknown BomItem numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *BomItemMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(bomitem.FieldSerialSns) { - fields = append(fields, bomitem.FieldSerialSns) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *BomItemMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *BomItemMutation) ClearField(name string) error { - switch name { - case bomitem.FieldSerialSns: - m.ClearSerialSns() - return nil - } - return fmt.Errorf("unknown BomItem nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *BomItemMutation) ResetField(name string) error { - switch name { - case bomitem.FieldProductCode: - m.ResetProductCode() - return nil - case bomitem.FieldBomName: - m.ResetBomName() - return nil - case bomitem.FieldMaterialCode: - m.ResetMaterialCode() - return nil - case bomitem.FieldMaterialName: - m.ResetMaterialName() - return nil - case bomitem.FieldSpec: - m.ResetSpec() - return nil - case bomitem.FieldUnit: - m.ResetUnit() - return nil - case bomitem.FieldManageMode: - m.ResetManageMode() - return nil - case bomitem.FieldUnitQty: - m.ResetUnitQty() - return nil - case bomitem.FieldLossRate: - m.ResetLossRate() - return nil - case bomitem.FieldRelatedStandard: - m.ResetRelatedStandard() - return nil - case bomitem.FieldRequiredQty: - m.ResetRequiredQty() - return nil - case bomitem.FieldSerialSns: - m.ResetSerialSns() - return nil - case bomitem.FieldCreatedAt: - m.ResetCreatedAt() - return nil - } - return fmt.Errorf("unknown BomItem field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *BomItemMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *BomItemMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *BomItemMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *BomItemMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *BomItemMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *BomItemMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *BomItemMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown BomItem unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *BomItemMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown BomItem edge %s", name) -} - // DailyPlanMutation represents an operation that mutates the DailyPlan nodes in the graph. type DailyPlanMutation struct { config @@ -19305,24 +18184,26 @@ func (m *SemiFlowMutation) ResetEdge(name string) error { // StationMutation represents an operation that mutates the Station nodes in the graph. type StationMutation struct { config - op Op - typ string - id *int - stationNo *int - addstationNo *int - name *string - flowId *int - addflowId *int - stationType *string - status *string - isBuiltin *bool - hasDock *bool - dockCode *string - createdAt *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Station, error) - predicates []predicate.Station + op Op + typ string + id *int + stationNo *int + addstationNo *int + name *string + flowId *int + addflowId *int + stationType *string + status *string + isBuiltin *bool + hasDock *bool + dockCode *string + visibleTabs *[]string + appendvisibleTabs []string + createdAt *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Station, error) + predicates []predicate.Station } var _ ent.Mutation = (*StationMutation)(nil) @@ -19771,6 +18652,71 @@ func (m *StationMutation) ResetDockCode() { m.dockCode = nil } +// SetVisibleTabs sets the "visibleTabs" field. +func (m *StationMutation) SetVisibleTabs(s []string) { + m.visibleTabs = &s + m.appendvisibleTabs = nil +} + +// VisibleTabs returns the value of the "visibleTabs" field in the mutation. +func (m *StationMutation) VisibleTabs() (r []string, exists bool) { + v := m.visibleTabs + if v == nil { + return + } + return *v, true +} + +// OldVisibleTabs returns the old "visibleTabs" field's value of the Station entity. +// If the Station 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 *StationMutation) OldVisibleTabs(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVisibleTabs is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVisibleTabs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVisibleTabs: %w", err) + } + return oldValue.VisibleTabs, nil +} + +// AppendVisibleTabs adds s to the "visibleTabs" field. +func (m *StationMutation) AppendVisibleTabs(s []string) { + m.appendvisibleTabs = append(m.appendvisibleTabs, s...) +} + +// AppendedVisibleTabs returns the list of values that were appended to the "visibleTabs" field in this mutation. +func (m *StationMutation) AppendedVisibleTabs() ([]string, bool) { + if len(m.appendvisibleTabs) == 0 { + return nil, false + } + return m.appendvisibleTabs, true +} + +// ClearVisibleTabs clears the value of the "visibleTabs" field. +func (m *StationMutation) ClearVisibleTabs() { + m.visibleTabs = nil + m.appendvisibleTabs = nil + m.clearedFields[station.FieldVisibleTabs] = struct{}{} +} + +// VisibleTabsCleared returns if the "visibleTabs" field was cleared in this mutation. +func (m *StationMutation) VisibleTabsCleared() bool { + _, ok := m.clearedFields[station.FieldVisibleTabs] + return ok +} + +// ResetVisibleTabs resets all changes to the "visibleTabs" field. +func (m *StationMutation) ResetVisibleTabs() { + m.visibleTabs = nil + m.appendvisibleTabs = nil + delete(m.clearedFields, station.FieldVisibleTabs) +} + // SetCreatedAt sets the "createdAt" field. func (m *StationMutation) SetCreatedAt(t time.Time) { m.createdAt = &t @@ -19841,7 +18787,7 @@ func (m *StationMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *StationMutation) Fields() []string { - fields := make([]string, 0, 9) + fields := make([]string, 0, 10) if m.stationNo != nil { fields = append(fields, station.FieldStationNo) } @@ -19866,6 +18812,9 @@ func (m *StationMutation) Fields() []string { if m.dockCode != nil { fields = append(fields, station.FieldDockCode) } + if m.visibleTabs != nil { + fields = append(fields, station.FieldVisibleTabs) + } if m.createdAt != nil { fields = append(fields, station.FieldCreatedAt) } @@ -19893,6 +18842,8 @@ func (m *StationMutation) Field(name string) (ent.Value, bool) { return m.HasDock() case station.FieldDockCode: return m.DockCode() + case station.FieldVisibleTabs: + return m.VisibleTabs() case station.FieldCreatedAt: return m.CreatedAt() } @@ -19920,6 +18871,8 @@ func (m *StationMutation) OldField(ctx context.Context, name string) (ent.Value, return m.OldHasDock(ctx) case station.FieldDockCode: return m.OldDockCode(ctx) + case station.FieldVisibleTabs: + return m.OldVisibleTabs(ctx) case station.FieldCreatedAt: return m.OldCreatedAt(ctx) } @@ -19987,6 +18940,13 @@ func (m *StationMutation) SetField(name string, value ent.Value) error { } m.SetDockCode(v) return nil + case station.FieldVisibleTabs: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVisibleTabs(v) + return nil case station.FieldCreatedAt: v, ok := value.(time.Time) if !ok { @@ -20054,6 +19014,9 @@ func (m *StationMutation) ClearedFields() []string { if m.FieldCleared(station.FieldFlowId) { fields = append(fields, station.FieldFlowId) } + if m.FieldCleared(station.FieldVisibleTabs) { + fields = append(fields, station.FieldVisibleTabs) + } return fields } @@ -20071,6 +19034,9 @@ func (m *StationMutation) ClearField(name string) error { case station.FieldFlowId: m.ClearFlowId() return nil + case station.FieldVisibleTabs: + m.ClearVisibleTabs() + return nil } return fmt.Errorf("unknown Station nullable field %s", name) } @@ -20103,6 +19069,9 @@ func (m *StationMutation) ResetField(name string) error { case station.FieldDockCode: m.ResetDockCode() return nil + case station.FieldVisibleTabs: + m.ResetVisibleTabs() + return nil case station.FieldCreatedAt: m.ResetCreatedAt() return nil @@ -22864,6 +21833,462 @@ func (m *StepDataMutation) ResetEdge(name string) error { return fmt.Errorf("unknown StepData edge %s", name) } +// SysConfigMutation represents an operation that mutates the SysConfig nodes in the graph. +type SysConfigMutation struct { + config + op Op + typ string + id *int + key *string + value *string + remark *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*SysConfig, error) + predicates []predicate.SysConfig +} + +var _ ent.Mutation = (*SysConfigMutation)(nil) + +// sysconfigOption allows management of the mutation configuration using functional options. +type sysconfigOption func(*SysConfigMutation) + +// newSysConfigMutation creates new mutation for the SysConfig entity. +func newSysConfigMutation(c config, op Op, opts ...sysconfigOption) *SysConfigMutation { + m := &SysConfigMutation{ + config: c, + op: op, + typ: TypeSysConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSysConfigID sets the ID field of the mutation. +func withSysConfigID(id int) sysconfigOption { + return func(m *SysConfigMutation) { + var ( + err error + once sync.Once + value *SysConfig + ) + m.oldValue = func(ctx context.Context) (*SysConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SysConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSysConfig sets the old SysConfig of the mutation. +func withSysConfig(node *SysConfig) sysconfigOption { + return func(m *SysConfigMutation) { + m.oldValue = func(context.Context) (*SysConfig, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m SysConfigMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m SysConfigMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SysConfigMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SysConfigMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SysConfig.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetKey sets the "key" field. +func (m *SysConfigMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *SysConfigMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the SysConfig entity. +// If the SysConfig 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 *SysConfigMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *SysConfigMutation) ResetKey() { + m.key = nil +} + +// SetValue sets the "value" field. +func (m *SysConfigMutation) SetValue(s string) { + m.value = &s +} + +// Value returns the value of the "value" field in the mutation. +func (m *SysConfigMutation) Value() (r string, exists bool) { + v := m.value + if v == nil { + return + } + return *v, true +} + +// OldValue returns the old "value" field's value of the SysConfig entity. +// If the SysConfig 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 *SysConfigMutation) OldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// ResetValue resets all changes to the "value" field. +func (m *SysConfigMutation) ResetValue() { + m.value = nil +} + +// SetRemark sets the "remark" field. +func (m *SysConfigMutation) SetRemark(s string) { + m.remark = &s +} + +// Remark returns the value of the "remark" field in the mutation. +func (m *SysConfigMutation) Remark() (r string, exists bool) { + v := m.remark + if v == nil { + return + } + return *v, true +} + +// OldRemark returns the old "remark" field's value of the SysConfig entity. +// If the SysConfig 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 *SysConfigMutation) OldRemark(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRemark is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRemark requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRemark: %w", err) + } + return oldValue.Remark, nil +} + +// ClearRemark clears the value of the "remark" field. +func (m *SysConfigMutation) ClearRemark() { + m.remark = nil + m.clearedFields[sysconfig.FieldRemark] = struct{}{} +} + +// RemarkCleared returns if the "remark" field was cleared in this mutation. +func (m *SysConfigMutation) RemarkCleared() bool { + _, ok := m.clearedFields[sysconfig.FieldRemark] + return ok +} + +// ResetRemark resets all changes to the "remark" field. +func (m *SysConfigMutation) ResetRemark() { + m.remark = nil + delete(m.clearedFields, sysconfig.FieldRemark) +} + +// Where appends a list predicates to the SysConfigMutation builder. +func (m *SysConfigMutation) Where(ps ...predicate.SysConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SysConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SysConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SysConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SysConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SysConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SysConfig). +func (m *SysConfigMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SysConfigMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.key != nil { + fields = append(fields, sysconfig.FieldKey) + } + if m.value != nil { + fields = append(fields, sysconfig.FieldValue) + } + if m.remark != nil { + fields = append(fields, sysconfig.FieldRemark) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SysConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case sysconfig.FieldKey: + return m.Key() + case sysconfig.FieldValue: + return m.Value() + case sysconfig.FieldRemark: + return m.Remark() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SysConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case sysconfig.FieldKey: + return m.OldKey(ctx) + case sysconfig.FieldValue: + return m.OldValue(ctx) + case sysconfig.FieldRemark: + return m.OldRemark(ctx) + } + return nil, fmt.Errorf("unknown SysConfig field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SysConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case sysconfig.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case sysconfig.FieldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + case sysconfig.FieldRemark: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRemark(v) + return nil + } + return fmt.Errorf("unknown SysConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SysConfigMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SysConfigMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SysConfigMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SysConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SysConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(sysconfig.FieldRemark) { + fields = append(fields, sysconfig.FieldRemark) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SysConfigMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SysConfigMutation) ClearField(name string) error { + switch name { + case sysconfig.FieldRemark: + m.ClearRemark() + return nil + } + return fmt.Errorf("unknown SysConfig nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SysConfigMutation) ResetField(name string) error { + switch name { + case sysconfig.FieldKey: + m.ResetKey() + return nil + case sysconfig.FieldValue: + m.ResetValue() + return nil + case sysconfig.FieldRemark: + m.ResetRemark() + return nil + } + return fmt.Errorf("unknown SysConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SysConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SysConfigMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SysConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SysConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SysConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SysConfigMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SysConfigMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SysConfig unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *SysConfigMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SysConfig edge %s", name) +} + // TorqueAuditLogMutation represents an operation that mutates the TorqueAuditLog nodes in the graph. type TorqueAuditLogMutation struct { config diff --git a/bj_power_mes/ent/predicate/predicate.go b/bj_power_mes/ent/predicate/predicate.go index 2cb433f..957a0a8 100644 --- a/bj_power_mes/ent/predicate/predicate.go +++ b/bj_power_mes/ent/predicate/predicate.go @@ -18,9 +18,6 @@ type AssociationTrace func(*sql.Selector) // Attachment is the predicate function for attachment builders. type Attachment func(*sql.Selector) -// BomItem is the predicate function for bomitem builders. -type BomItem func(*sql.Selector) - // DailyPlan is the predicate function for dailyplan builders. type DailyPlan func(*sql.Selector) @@ -78,6 +75,9 @@ type StepCriterion func(*sql.Selector) // StepData is the predicate function for stepdata builders. type StepData func(*sql.Selector) +// SysConfig is the predicate function for sysconfig builders. +type SysConfig func(*sql.Selector) + // TorqueAuditLog is the predicate function for torqueauditlog builders. type TorqueAuditLog func(*sql.Selector) diff --git a/bj_power_mes/ent/runtime.go b/bj_power_mes/ent/runtime.go index f55db85..ec43a66 100644 --- a/bj_power_mes/ent/runtime.go +++ b/bj_power_mes/ent/runtime.go @@ -7,7 +7,6 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" "bj_power_mes/ent/eventlog" @@ -27,6 +26,7 @@ import ( "bj_power_mes/ent/stationstate" "bj_power_mes/ent/stepcriterion" "bj_power_mes/ent/stepdata" + "bj_power_mes/ent/sysconfig" "bj_power_mes/ent/torqueauditlog" "bj_power_mes/ent/torquerecord" "bj_power_mes/ent/user" @@ -253,74 +253,6 @@ func init() { attachmentDescID := attachmentFields[0].Descriptor() // attachment.IDValidator is a validator for the "id" field. It is called by the builders before save. attachment.IDValidator = attachmentDescID.Validators[0].(func(int) error) - bomitemFields := schema.BomItem{}.Fields() - _ = bomitemFields - // bomitemDescProductCode is the schema descriptor for productCode field. - bomitemDescProductCode := bomitemFields[1].Descriptor() - // bomitem.DefaultProductCode holds the default value on creation for the productCode field. - bomitem.DefaultProductCode = bomitemDescProductCode.Default.(string) - // bomitem.ProductCodeValidator is a validator for the "productCode" field. It is called by the builders before save. - bomitem.ProductCodeValidator = bomitemDescProductCode.Validators[0].(func(string) error) - // bomitemDescBomName is the schema descriptor for bomName field. - bomitemDescBomName := bomitemFields[2].Descriptor() - // bomitem.DefaultBomName holds the default value on creation for the bomName field. - bomitem.DefaultBomName = bomitemDescBomName.Default.(string) - // bomitem.BomNameValidator is a validator for the "bomName" field. It is called by the builders before save. - bomitem.BomNameValidator = bomitemDescBomName.Validators[0].(func(string) error) - // bomitemDescMaterialCode is the schema descriptor for materialCode field. - bomitemDescMaterialCode := bomitemFields[3].Descriptor() - // bomitem.MaterialCodeValidator is a validator for the "materialCode" field. It is called by the builders before save. - bomitem.MaterialCodeValidator = bomitemDescMaterialCode.Validators[0].(func(string) error) - // bomitemDescMaterialName is the schema descriptor for materialName field. - bomitemDescMaterialName := bomitemFields[4].Descriptor() - // bomitem.DefaultMaterialName holds the default value on creation for the materialName field. - bomitem.DefaultMaterialName = bomitemDescMaterialName.Default.(string) - // bomitem.MaterialNameValidator is a validator for the "materialName" field. It is called by the builders before save. - bomitem.MaterialNameValidator = bomitemDescMaterialName.Validators[0].(func(string) error) - // bomitemDescSpec is the schema descriptor for spec field. - bomitemDescSpec := bomitemFields[5].Descriptor() - // bomitem.DefaultSpec holds the default value on creation for the spec field. - bomitem.DefaultSpec = bomitemDescSpec.Default.(string) - // bomitem.SpecValidator is a validator for the "spec" field. It is called by the builders before save. - bomitem.SpecValidator = bomitemDescSpec.Validators[0].(func(string) error) - // bomitemDescUnit is the schema descriptor for unit field. - bomitemDescUnit := bomitemFields[6].Descriptor() - // bomitem.DefaultUnit holds the default value on creation for the unit field. - bomitem.DefaultUnit = bomitemDescUnit.Default.(string) - // bomitem.UnitValidator is a validator for the "unit" field. It is called by the builders before save. - bomitem.UnitValidator = bomitemDescUnit.Validators[0].(func(string) error) - // bomitemDescManageMode is the schema descriptor for manageMode field. - bomitemDescManageMode := bomitemFields[7].Descriptor() - // bomitem.DefaultManageMode holds the default value on creation for the manageMode field. - bomitem.DefaultManageMode = bomitemDescManageMode.Default.(string) - // bomitem.ManageModeValidator is a validator for the "manageMode" field. It is called by the builders before save. - bomitem.ManageModeValidator = bomitemDescManageMode.Validators[0].(func(string) error) - // bomitemDescUnitQty is the schema descriptor for unitQty field. - bomitemDescUnitQty := bomitemFields[8].Descriptor() - // bomitem.DefaultUnitQty holds the default value on creation for the unitQty field. - bomitem.DefaultUnitQty = bomitemDescUnitQty.Default.(float64) - // bomitemDescLossRate is the schema descriptor for lossRate field. - bomitemDescLossRate := bomitemFields[9].Descriptor() - // bomitem.DefaultLossRate holds the default value on creation for the lossRate field. - bomitem.DefaultLossRate = bomitemDescLossRate.Default.(float64) - // bomitemDescRelatedStandard is the schema descriptor for relatedStandard field. - bomitemDescRelatedStandard := bomitemFields[10].Descriptor() - // bomitem.DefaultRelatedStandard holds the default value on creation for the relatedStandard field. - bomitem.DefaultRelatedStandard = bomitemDescRelatedStandard.Default.(string) - // bomitem.RelatedStandardValidator is a validator for the "relatedStandard" field. It is called by the builders before save. - bomitem.RelatedStandardValidator = bomitemDescRelatedStandard.Validators[0].(func(string) error) - // bomitemDescRequiredQty is the schema descriptor for requiredQty field. - bomitemDescRequiredQty := bomitemFields[11].Descriptor() - // bomitem.DefaultRequiredQty holds the default value on creation for the requiredQty field. - bomitem.DefaultRequiredQty = bomitemDescRequiredQty.Default.(float64) - // bomitemDescCreatedAt is the schema descriptor for createdAt field. - bomitemDescCreatedAt := bomitemFields[13].Descriptor() - // bomitem.DefaultCreatedAt holds the default value on creation for the createdAt field. - bomitem.DefaultCreatedAt = bomitemDescCreatedAt.Default.(func() time.Time) - // bomitemDescID is the schema descriptor for id field. - bomitemDescID := bomitemFields[0].Descriptor() - // bomitem.IDValidator is a validator for the "id" field. It is called by the builders before save. - bomitem.IDValidator = bomitemDescID.Validators[0].(func(int) error) dailyplanFields := schema.DailyPlan{}.Fields() _ = dailyplanFields // dailyplanDescOrderNo is the schema descriptor for orderNo field. @@ -1238,7 +1170,7 @@ func init() { // station.DockCodeValidator is a validator for the "dockCode" field. It is called by the builders before save. station.DockCodeValidator = stationDescDockCode.Validators[0].(func(string) error) // stationDescCreatedAt is the schema descriptor for createdAt field. - stationDescCreatedAt := stationFields[9].Descriptor() + stationDescCreatedAt := stationFields[10].Descriptor() // station.DefaultCreatedAt holds the default value on creation for the createdAt field. station.DefaultCreatedAt = stationDescCreatedAt.Default.(func() time.Time) // stationDescID is the schema descriptor for id field. @@ -1363,6 +1295,20 @@ func init() { stepdataDescID := stepdataFields[0].Descriptor() // stepdata.IDValidator is a validator for the "id" field. It is called by the builders before save. stepdata.IDValidator = stepdataDescID.Validators[0].(func(int) error) + sysconfigFields := schema.SysConfig{}.Fields() + _ = sysconfigFields + // sysconfigDescKey is the schema descriptor for key field. + sysconfigDescKey := sysconfigFields[0].Descriptor() + // sysconfig.KeyValidator is a validator for the "key" field. It is called by the builders before save. + sysconfig.KeyValidator = sysconfigDescKey.Validators[0].(func(string) error) + // sysconfigDescValue is the schema descriptor for value field. + sysconfigDescValue := sysconfigFields[1].Descriptor() + // sysconfig.ValueValidator is a validator for the "value" field. It is called by the builders before save. + sysconfig.ValueValidator = sysconfigDescValue.Validators[0].(func(string) error) + // sysconfigDescRemark is the schema descriptor for remark field. + sysconfigDescRemark := sysconfigFields[2].Descriptor() + // sysconfig.RemarkValidator is a validator for the "remark" field. It is called by the builders before save. + sysconfig.RemarkValidator = sysconfigDescRemark.Validators[0].(func(string) error) torqueauditlogFields := schema.TorqueAuditLog{}.Fields() _ = torqueauditlogFields // torqueauditlogDescAction is the schema descriptor for action field. diff --git a/bj_power_mes/ent/station.go b/bj_power_mes/ent/station.go index f0d5e1b..ba6bbda 100644 --- a/bj_power_mes/ent/station.go +++ b/bj_power_mes/ent/station.go @@ -4,6 +4,7 @@ package ent import ( "bj_power_mes/ent/station" + "encoding/json" "fmt" "strings" "time" @@ -33,6 +34,8 @@ type Station struct { HasDock bool `json:"hasDock,omitempty"` // 接驳台编码 DOCK01..21 DockCode string `json:"dockCode,omitempty"` + // VisibleTabs holds the value of the "visibleTabs" field. + VisibleTabs []string `json:"visibleTabs,omitempty"` // CreatedAt holds the value of the "createdAt" field. CreatedAt time.Time `json:"createdAt,omitempty"` selectValues sql.SelectValues @@ -43,6 +46,8 @@ func (*Station) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { + case station.FieldVisibleTabs: + values[i] = new([]byte) case station.FieldIsBuiltin, station.FieldHasDock: values[i] = new(sql.NullBool) case station.FieldID, station.FieldStationNo, station.FieldFlowId: @@ -120,6 +125,14 @@ func (_m *Station) assignValues(columns []string, values []any) error { } else if value.Valid { _m.DockCode = value.String } + case station.FieldVisibleTabs: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field visibleTabs", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.VisibleTabs); err != nil { + return fmt.Errorf("unmarshal field visibleTabs: %w", err) + } + } case station.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field createdAt", values[i]) @@ -186,6 +199,9 @@ func (_m *Station) String() string { builder.WriteString("dockCode=") builder.WriteString(_m.DockCode) builder.WriteString(", ") + builder.WriteString("visibleTabs=") + builder.WriteString(fmt.Sprintf("%v", _m.VisibleTabs)) + builder.WriteString(", ") builder.WriteString("createdAt=") builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) builder.WriteByte(')') diff --git a/bj_power_mes/ent/station/station.go b/bj_power_mes/ent/station/station.go index 5831769..26fa678 100644 --- a/bj_power_mes/ent/station/station.go +++ b/bj_power_mes/ent/station/station.go @@ -29,6 +29,8 @@ const ( FieldHasDock = "has_dock" // FieldDockCode holds the string denoting the dockcode field in the database. FieldDockCode = "dock_code" + // FieldVisibleTabs holds the string denoting the visibletabs field in the database. + FieldVisibleTabs = "visible_tabs" // FieldCreatedAt holds the string denoting the createdat field in the database. FieldCreatedAt = "created_at" // Table holds the table name of the station in the database. @@ -46,6 +48,7 @@ var Columns = []string{ FieldIsBuiltin, FieldHasDock, FieldDockCode, + FieldVisibleTabs, FieldCreatedAt, } diff --git a/bj_power_mes/ent/station/where.go b/bj_power_mes/ent/station/where.go index 3ee6088..0736346 100644 --- a/bj_power_mes/ent/station/where.go +++ b/bj_power_mes/ent/station/where.go @@ -469,6 +469,16 @@ func DockCodeContainsFold(v string) predicate.Station { return predicate.Station(sql.FieldContainsFold(FieldDockCode, v)) } +// VisibleTabsIsNil applies the IsNil predicate on the "visibleTabs" field. +func VisibleTabsIsNil() predicate.Station { + return predicate.Station(sql.FieldIsNull(FieldVisibleTabs)) +} + +// VisibleTabsNotNil applies the NotNil predicate on the "visibleTabs" field. +func VisibleTabsNotNil() predicate.Station { + return predicate.Station(sql.FieldNotNull(FieldVisibleTabs)) +} + // CreatedAtEQ applies the EQ predicate on the "createdAt" field. func CreatedAtEQ(v time.Time) predicate.Station { return predicate.Station(sql.FieldEQ(FieldCreatedAt, v)) diff --git a/bj_power_mes/ent/station_create.go b/bj_power_mes/ent/station_create.go index c57f010..45a45e6 100644 --- a/bj_power_mes/ent/station_create.go +++ b/bj_power_mes/ent/station_create.go @@ -124,6 +124,12 @@ func (_c *StationCreate) SetNillableDockCode(v *string) *StationCreate { return _c } +// SetVisibleTabs sets the "visibleTabs" field. +func (_c *StationCreate) SetVisibleTabs(v []string) *StationCreate { + _c.mutation.SetVisibleTabs(v) + return _c +} + // SetCreatedAt sets the "createdAt" field. func (_c *StationCreate) SetCreatedAt(v time.Time) *StationCreate { _c.mutation.SetCreatedAt(v) @@ -324,6 +330,10 @@ func (_c *StationCreate) createSpec() (*Station, *sqlgraph.CreateSpec) { _spec.SetField(station.FieldDockCode, field.TypeString, value) _node.DockCode = value } + if value, ok := _c.mutation.VisibleTabs(); ok { + _spec.SetField(station.FieldVisibleTabs, field.TypeJSON, value) + _node.VisibleTabs = value + } if value, ok := _c.mutation.CreatedAt(); ok { _spec.SetField(station.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value diff --git a/bj_power_mes/ent/station_update.go b/bj_power_mes/ent/station_update.go index e982fe5..8f28ce1 100644 --- a/bj_power_mes/ent/station_update.go +++ b/bj_power_mes/ent/station_update.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" "entgo.io/ent/schema/field" ) @@ -160,6 +161,24 @@ func (_u *StationUpdate) SetNillableDockCode(v *string) *StationUpdate { return _u } +// SetVisibleTabs sets the "visibleTabs" field. +func (_u *StationUpdate) SetVisibleTabs(v []string) *StationUpdate { + _u.mutation.SetVisibleTabs(v) + return _u +} + +// AppendVisibleTabs appends value to the "visibleTabs" field. +func (_u *StationUpdate) AppendVisibleTabs(v []string) *StationUpdate { + _u.mutation.AppendVisibleTabs(v) + return _u +} + +// ClearVisibleTabs clears the value of the "visibleTabs" field. +func (_u *StationUpdate) ClearVisibleTabs() *StationUpdate { + _u.mutation.ClearVisibleTabs() + return _u +} + // Mutation returns the StationMutation object of the builder. func (_u *StationUpdate) Mutation() *StationMutation { return _u.mutation @@ -268,6 +287,17 @@ func (_u *StationUpdate) sqlSave(ctx context.Context) (_node int, err error) { if value, ok := _u.mutation.DockCode(); ok { _spec.SetField(station.FieldDockCode, field.TypeString, value) } + if value, ok := _u.mutation.VisibleTabs(); ok { + _spec.SetField(station.FieldVisibleTabs, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedVisibleTabs(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, station.FieldVisibleTabs, value) + }) + } + if _u.mutation.VisibleTabsCleared() { + _spec.ClearField(station.FieldVisibleTabs, field.TypeJSON) + } _spec.AddModifiers(_u.modifiers...) if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -422,6 +452,24 @@ func (_u *StationUpdateOne) SetNillableDockCode(v *string) *StationUpdateOne { return _u } +// SetVisibleTabs sets the "visibleTabs" field. +func (_u *StationUpdateOne) SetVisibleTabs(v []string) *StationUpdateOne { + _u.mutation.SetVisibleTabs(v) + return _u +} + +// AppendVisibleTabs appends value to the "visibleTabs" field. +func (_u *StationUpdateOne) AppendVisibleTabs(v []string) *StationUpdateOne { + _u.mutation.AppendVisibleTabs(v) + return _u +} + +// ClearVisibleTabs clears the value of the "visibleTabs" field. +func (_u *StationUpdateOne) ClearVisibleTabs() *StationUpdateOne { + _u.mutation.ClearVisibleTabs() + return _u +} + // Mutation returns the StationMutation object of the builder. func (_u *StationUpdateOne) Mutation() *StationMutation { return _u.mutation @@ -560,6 +608,17 @@ func (_u *StationUpdateOne) sqlSave(ctx context.Context) (_node *Station, err er if value, ok := _u.mutation.DockCode(); ok { _spec.SetField(station.FieldDockCode, field.TypeString, value) } + if value, ok := _u.mutation.VisibleTabs(); ok { + _spec.SetField(station.FieldVisibleTabs, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedVisibleTabs(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, station.FieldVisibleTabs, value) + }) + } + if _u.mutation.VisibleTabsCleared() { + _spec.ClearField(station.FieldVisibleTabs, field.TypeJSON) + } _spec.AddModifiers(_u.modifiers...) _node = &Station{config: _u.config} _spec.Assign = _node.assignValues diff --git a/bj_power_mes/ent/sysconfig.go b/bj_power_mes/ent/sysconfig.go new file mode 100644 index 0000000..60d2bb5 --- /dev/null +++ b/bj_power_mes/ent/sysconfig.go @@ -0,0 +1,125 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/sysconfig" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// SysConfig is the model entity for the SysConfig schema. +type SysConfig struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 配置键,如 wms.base_url + Key string `json:"key,omitempty"` + // 配置值 + Value string `json:"value,omitempty"` + // 说明 + Remark string `json:"remark,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SysConfig) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case sysconfig.FieldID: + values[i] = new(sql.NullInt64) + case sysconfig.FieldKey, sysconfig.FieldValue, sysconfig.FieldRemark: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the SysConfig fields. +func (_m *SysConfig) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case sysconfig.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case sysconfig.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case sysconfig.FieldValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + _m.Value = value.String + } + case sysconfig.FieldRemark: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field remark", values[i]) + } else if value.Valid { + _m.Remark = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// GetValue returns the ent.Value that was dynamically selected and assigned to the SysConfig. +// This includes values selected through modifiers, order, etc. +func (_m *SysConfig) GetValue(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this SysConfig. +// Note that you need to call SysConfig.Unwrap() before calling this method if this SysConfig +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *SysConfig) Update() *SysConfigUpdateOne { + return NewSysConfigClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the SysConfig entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *SysConfig) Unwrap() *SysConfig { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: SysConfig is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *SysConfig) String() string { + var builder strings.Builder + builder.WriteString("SysConfig(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + builder.WriteString("value=") + builder.WriteString(_m.Value) + builder.WriteString(", ") + builder.WriteString("remark=") + builder.WriteString(_m.Remark) + builder.WriteByte(')') + return builder.String() +} + +// SysConfigs is a parsable slice of SysConfig. +type SysConfigs []*SysConfig diff --git a/bj_power_mes/ent/sysconfig/sysconfig.go b/bj_power_mes/ent/sysconfig/sysconfig.go new file mode 100644 index 0000000..da028ab --- /dev/null +++ b/bj_power_mes/ent/sysconfig/sysconfig.go @@ -0,0 +1,72 @@ +// Code generated by ent, DO NOT EDIT. + +package sysconfig + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the sysconfig type in the database. + Label = "sys_config" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldValue holds the string denoting the value field in the database. + FieldValue = "value" + // FieldRemark holds the string denoting the remark field in the database. + FieldRemark = "remark" + // Table holds the table name of the sysconfig in the database. + Table = "sys_config" +) + +// Columns holds all SQL columns for sysconfig fields. +var Columns = []string{ + FieldID, + FieldKey, + FieldValue, + FieldRemark, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // KeyValidator is a validator for the "key" field. It is called by the builders before save. + KeyValidator func(string) error + // ValueValidator is a validator for the "value" field. It is called by the builders before save. + ValueValidator func(string) error + // RemarkValidator is a validator for the "remark" field. It is called by the builders before save. + RemarkValidator func(string) error +) + +// OrderOption defines the ordering options for the SysConfig queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByValue orders the results by the value field. +func ByValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValue, opts...).ToFunc() +} + +// ByRemark orders the results by the remark field. +func ByRemark(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRemark, opts...).ToFunc() +} diff --git a/bj_power_mes/ent/sysconfig/where.go b/bj_power_mes/ent/sysconfig/where.go new file mode 100644 index 0000000..3767fba --- /dev/null +++ b/bj_power_mes/ent/sysconfig/where.go @@ -0,0 +1,289 @@ +// Code generated by ent, DO NOT EDIT. + +package sysconfig + +import ( + "bj_power_mes/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldID, id)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldKey, v)) +} + +// Value applies equality check predicate on the "value" field. It's identical to ValueEQ. +func Value(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldValue, v)) +} + +// Remark applies equality check predicate on the "remark" field. It's identical to RemarkEQ. +func Remark(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldRemark, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldKey, v)) +} + +// ValueEQ applies the EQ predicate on the "value" field. +func ValueEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldValue, v)) +} + +// ValueNEQ applies the NEQ predicate on the "value" field. +func ValueNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldValue, v)) +} + +// ValueIn applies the In predicate on the "value" field. +func ValueIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldValue, vs...)) +} + +// ValueNotIn applies the NotIn predicate on the "value" field. +func ValueNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldValue, vs...)) +} + +// ValueGT applies the GT predicate on the "value" field. +func ValueGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldValue, v)) +} + +// ValueGTE applies the GTE predicate on the "value" field. +func ValueGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldValue, v)) +} + +// ValueLT applies the LT predicate on the "value" field. +func ValueLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldValue, v)) +} + +// ValueLTE applies the LTE predicate on the "value" field. +func ValueLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldValue, v)) +} + +// ValueContains applies the Contains predicate on the "value" field. +func ValueContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldValue, v)) +} + +// ValueHasPrefix applies the HasPrefix predicate on the "value" field. +func ValueHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldValue, v)) +} + +// ValueHasSuffix applies the HasSuffix predicate on the "value" field. +func ValueHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldValue, v)) +} + +// ValueEqualFold applies the EqualFold predicate on the "value" field. +func ValueEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldValue, v)) +} + +// ValueContainsFold applies the ContainsFold predicate on the "value" field. +func ValueContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldValue, v)) +} + +// RemarkEQ applies the EQ predicate on the "remark" field. +func RemarkEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldRemark, v)) +} + +// RemarkNEQ applies the NEQ predicate on the "remark" field. +func RemarkNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldRemark, v)) +} + +// RemarkIn applies the In predicate on the "remark" field. +func RemarkIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldRemark, vs...)) +} + +// RemarkNotIn applies the NotIn predicate on the "remark" field. +func RemarkNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldRemark, vs...)) +} + +// RemarkGT applies the GT predicate on the "remark" field. +func RemarkGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldRemark, v)) +} + +// RemarkGTE applies the GTE predicate on the "remark" field. +func RemarkGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldRemark, v)) +} + +// RemarkLT applies the LT predicate on the "remark" field. +func RemarkLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldRemark, v)) +} + +// RemarkLTE applies the LTE predicate on the "remark" field. +func RemarkLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldRemark, v)) +} + +// RemarkContains applies the Contains predicate on the "remark" field. +func RemarkContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldRemark, v)) +} + +// RemarkHasPrefix applies the HasPrefix predicate on the "remark" field. +func RemarkHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldRemark, v)) +} + +// RemarkHasSuffix applies the HasSuffix predicate on the "remark" field. +func RemarkHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldRemark, v)) +} + +// RemarkIsNil applies the IsNil predicate on the "remark" field. +func RemarkIsNil() predicate.SysConfig { + return predicate.SysConfig(sql.FieldIsNull(FieldRemark)) +} + +// RemarkNotNil applies the NotNil predicate on the "remark" field. +func RemarkNotNil() predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotNull(FieldRemark)) +} + +// RemarkEqualFold applies the EqualFold predicate on the "remark" field. +func RemarkEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldRemark, v)) +} + +// RemarkContainsFold applies the ContainsFold predicate on the "remark" field. +func RemarkContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldRemark, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.NotPredicates(p)) +} diff --git a/bj_power_mes/ent/sysconfig_create.go b/bj_power_mes/ent/sysconfig_create.go new file mode 100644 index 0000000..c6e75ce --- /dev/null +++ b/bj_power_mes/ent/sysconfig_create.go @@ -0,0 +1,229 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/sysconfig" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigCreate is the builder for creating a SysConfig entity. +type SysConfigCreate struct { + config + mutation *SysConfigMutation + hooks []Hook +} + +// SetKey sets the "key" field. +func (_c *SysConfigCreate) SetKey(v string) *SysConfigCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetValue sets the "value" field. +func (_c *SysConfigCreate) SetValue(v string) *SysConfigCreate { + _c.mutation.SetValue(v) + return _c +} + +// SetRemark sets the "remark" field. +func (_c *SysConfigCreate) SetRemark(v string) *SysConfigCreate { + _c.mutation.SetRemark(v) + return _c +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_c *SysConfigCreate) SetNillableRemark(v *string) *SysConfigCreate { + if v != nil { + _c.SetRemark(*v) + } + return _c +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_c *SysConfigCreate) Mutation() *SysConfigMutation { + return _c.mutation +} + +// Save creates the SysConfig in the database. +func (_c *SysConfigCreate) Save(ctx context.Context) (*SysConfig, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SysConfigCreate) SaveX(ctx context.Context) *SysConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SysConfigCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SysConfigCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SysConfigCreate) check() error { + if _, ok := _c.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "SysConfig.key"`)} + } + if v, ok := _c.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if _, ok := _c.mutation.Value(); !ok { + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "SysConfig.value"`)} + } + if v, ok := _c.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _c.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +func (_c *SysConfigCreate) sqlSave(ctx context.Context) (*SysConfig, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SysConfigCreate) createSpec() (*SysConfig, *sqlgraph.CreateSpec) { + var ( + _node = &SysConfig{config: _c.config} + _spec = sqlgraph.NewCreateSpec(sysconfig.Table, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + _node.Value = value + } + if value, ok := _c.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + _node.Remark = value + } + return _node, _spec +} + +// SysConfigCreateBulk is the builder for creating many SysConfig entities in bulk. +type SysConfigCreateBulk struct { + config + err error + builders []*SysConfigCreate +} + +// Save creates the SysConfig entities in the database. +func (_c *SysConfigCreateBulk) Save(ctx context.Context) ([]*SysConfig, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*SysConfig, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SysConfigMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SysConfigCreateBulk) SaveX(ctx context.Context) []*SysConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SysConfigCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SysConfigCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_mes/ent/bomitem_delete.go b/bj_power_mes/ent/sysconfig_delete.go similarity index 53% rename from bj_power_mes/ent/bomitem_delete.go rename to bj_power_mes/ent/sysconfig_delete.go index a61e14c..cb98f19 100644 --- a/bj_power_mes/ent/bomitem_delete.go +++ b/bj_power_mes/ent/sysconfig_delete.go @@ -3,8 +3,8 @@ package ent import ( - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/predicate" + "bj_power_mes/ent/sysconfig" "context" "entgo.io/ent/dialect/sql" @@ -12,26 +12,26 @@ import ( "entgo.io/ent/schema/field" ) -// BomItemDelete is the builder for deleting a BomItem entity. -type BomItemDelete struct { +// SysConfigDelete is the builder for deleting a SysConfig entity. +type SysConfigDelete struct { config hooks []Hook - mutation *BomItemMutation + mutation *SysConfigMutation } -// Where appends a list predicates to the BomItemDelete builder. -func (_d *BomItemDelete) Where(ps ...predicate.BomItem) *BomItemDelete { +// Where appends a list predicates to the SysConfigDelete builder. +func (_d *SysConfigDelete) Where(ps ...predicate.SysConfig) *SysConfigDelete { _d.mutation.Where(ps...) return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (_d *BomItemDelete) Exec(ctx context.Context) (int, error) { +func (_d *SysConfigDelete) Exec(ctx context.Context) (int, error) { return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (_d *BomItemDelete) ExecX(ctx context.Context) int { +func (_d *SysConfigDelete) ExecX(ctx context.Context) int { n, err := _d.Exec(ctx) if err != nil { panic(err) @@ -39,8 +39,8 @@ func (_d *BomItemDelete) ExecX(ctx context.Context) int { return n } -func (_d *BomItemDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(bomitem.Table, sqlgraph.NewFieldSpec(bomitem.FieldID, field.TypeInt)) +func (_d *SysConfigDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(sysconfig.Table, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { @@ -56,32 +56,32 @@ func (_d *BomItemDelete) sqlExec(ctx context.Context) (int, error) { return affected, err } -// BomItemDeleteOne is the builder for deleting a single BomItem entity. -type BomItemDeleteOne struct { - _d *BomItemDelete +// SysConfigDeleteOne is the builder for deleting a single SysConfig entity. +type SysConfigDeleteOne struct { + _d *SysConfigDelete } -// Where appends a list predicates to the BomItemDelete builder. -func (_d *BomItemDeleteOne) Where(ps ...predicate.BomItem) *BomItemDeleteOne { +// Where appends a list predicates to the SysConfigDelete builder. +func (_d *SysConfigDeleteOne) Where(ps ...predicate.SysConfig) *SysConfigDeleteOne { _d._d.mutation.Where(ps...) return _d } // Exec executes the deletion query. -func (_d *BomItemDeleteOne) Exec(ctx context.Context) error { +func (_d *SysConfigDeleteOne) Exec(ctx context.Context) error { n, err := _d._d.Exec(ctx) switch { case err != nil: return err case n == 0: - return &NotFoundError{bomitem.Label} + return &NotFoundError{sysconfig.Label} default: return nil } } // ExecX is like Exec, but panics if an error occurs. -func (_d *BomItemDeleteOne) ExecX(ctx context.Context) { +func (_d *SysConfigDeleteOne) ExecX(ctx context.Context) { if err := _d.Exec(ctx); err != nil { panic(err) } diff --git a/bj_power_mes/ent/bomitem_query.go b/bj_power_mes/ent/sysconfig_query.go similarity index 63% rename from bj_power_mes/ent/bomitem_query.go rename to bj_power_mes/ent/sysconfig_query.go index 521b798..1f7e6fb 100644 --- a/bj_power_mes/ent/bomitem_query.go +++ b/bj_power_mes/ent/sysconfig_query.go @@ -3,8 +3,8 @@ package ent import ( - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/predicate" + "bj_power_mes/ent/sysconfig" "context" "fmt" "math" @@ -16,65 +16,65 @@ import ( "entgo.io/ent/schema/field" ) -// BomItemQuery is the builder for querying BomItem entities. -type BomItemQuery struct { +// SysConfigQuery is the builder for querying SysConfig entities. +type SysConfigQuery struct { config ctx *QueryContext - order []bomitem.OrderOption + order []sysconfig.OrderOption inters []Interceptor - predicates []predicate.BomItem + predicates []predicate.SysConfig modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the BomItemQuery builder. -func (_q *BomItemQuery) Where(ps ...predicate.BomItem) *BomItemQuery { +// Where adds a new predicate for the SysConfigQuery builder. +func (_q *SysConfigQuery) Where(ps ...predicate.SysConfig) *SysConfigQuery { _q.predicates = append(_q.predicates, ps...) return _q } // Limit the number of records to be returned by this query. -func (_q *BomItemQuery) Limit(limit int) *BomItemQuery { +func (_q *SysConfigQuery) Limit(limit int) *SysConfigQuery { _q.ctx.Limit = &limit return _q } // Offset to start from. -func (_q *BomItemQuery) Offset(offset int) *BomItemQuery { +func (_q *SysConfigQuery) Offset(offset int) *SysConfigQuery { _q.ctx.Offset = &offset return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (_q *BomItemQuery) Unique(unique bool) *BomItemQuery { +func (_q *SysConfigQuery) Unique(unique bool) *SysConfigQuery { _q.ctx.Unique = &unique return _q } // Order specifies how the records should be ordered. -func (_q *BomItemQuery) Order(o ...bomitem.OrderOption) *BomItemQuery { +func (_q *SysConfigQuery) Order(o ...sysconfig.OrderOption) *SysConfigQuery { _q.order = append(_q.order, o...) return _q } -// First returns the first BomItem entity from the query. -// Returns a *NotFoundError when no BomItem was found. -func (_q *BomItemQuery) First(ctx context.Context) (*BomItem, error) { +// First returns the first SysConfig entity from the query. +// Returns a *NotFoundError when no SysConfig was found. +func (_q *SysConfigQuery) First(ctx context.Context) (*SysConfig, error) { nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } if len(nodes) == 0 { - return nil, &NotFoundError{bomitem.Label} + return nil, &NotFoundError{sysconfig.Label} } return nodes[0], nil } // FirstX is like First, but panics if an error occurs. -func (_q *BomItemQuery) FirstX(ctx context.Context) *BomItem { +func (_q *SysConfigQuery) FirstX(ctx context.Context) *SysConfig { node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -82,22 +82,22 @@ func (_q *BomItemQuery) FirstX(ctx context.Context) *BomItem { return node } -// FirstID returns the first BomItem ID from the query. -// Returns a *NotFoundError when no BomItem ID was found. -func (_q *BomItemQuery) FirstID(ctx context.Context) (id int, err error) { +// FirstID returns the first SysConfig ID from the query. +// Returns a *NotFoundError when no SysConfig ID was found. +func (_q *SysConfigQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { - err = &NotFoundError{bomitem.Label} + err = &NotFoundError{sysconfig.Label} return } return ids[0], nil } // FirstIDX is like FirstID, but panics if an error occurs. -func (_q *BomItemQuery) FirstIDX(ctx context.Context) int { +func (_q *SysConfigQuery) FirstIDX(ctx context.Context) int { id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -105,10 +105,10 @@ func (_q *BomItemQuery) FirstIDX(ctx context.Context) int { return id } -// Only returns a single BomItem entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one BomItem entity is found. -// Returns a *NotFoundError when no BomItem entities are found. -func (_q *BomItemQuery) Only(ctx context.Context) (*BomItem, error) { +// Only returns a single SysConfig entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SysConfig entity is found. +// Returns a *NotFoundError when no SysConfig entities are found. +func (_q *SysConfigQuery) Only(ctx context.Context) (*SysConfig, error) { nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err @@ -117,14 +117,14 @@ func (_q *BomItemQuery) Only(ctx context.Context) (*BomItem, error) { case 1: return nodes[0], nil case 0: - return nil, &NotFoundError{bomitem.Label} + return nil, &NotFoundError{sysconfig.Label} default: - return nil, &NotSingularError{bomitem.Label} + return nil, &NotSingularError{sysconfig.Label} } } // OnlyX is like Only, but panics if an error occurs. -func (_q *BomItemQuery) OnlyX(ctx context.Context) *BomItem { +func (_q *SysConfigQuery) OnlyX(ctx context.Context) *SysConfig { node, err := _q.Only(ctx) if err != nil { panic(err) @@ -132,10 +132,10 @@ func (_q *BomItemQuery) OnlyX(ctx context.Context) *BomItem { return node } -// OnlyID is like Only, but returns the only BomItem ID in the query. -// Returns a *NotSingularError when more than one BomItem ID is found. +// OnlyID is like Only, but returns the only SysConfig ID in the query. +// Returns a *NotSingularError when more than one SysConfig ID is found. // Returns a *NotFoundError when no entities are found. -func (_q *BomItemQuery) OnlyID(ctx context.Context) (id int, err error) { +func (_q *SysConfigQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return @@ -144,15 +144,15 @@ func (_q *BomItemQuery) OnlyID(ctx context.Context) (id int, err error) { case 1: id = ids[0] case 0: - err = &NotFoundError{bomitem.Label} + err = &NotFoundError{sysconfig.Label} default: - err = &NotSingularError{bomitem.Label} + err = &NotSingularError{sysconfig.Label} } return } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *BomItemQuery) OnlyIDX(ctx context.Context) int { +func (_q *SysConfigQuery) OnlyIDX(ctx context.Context) int { id, err := _q.OnlyID(ctx) if err != nil { panic(err) @@ -160,18 +160,18 @@ func (_q *BomItemQuery) OnlyIDX(ctx context.Context) int { return id } -// All executes the query and returns a list of BomItems. -func (_q *BomItemQuery) All(ctx context.Context) ([]*BomItem, error) { +// All executes the query and returns a list of SysConfigs. +func (_q *SysConfigQuery) All(ctx context.Context) ([]*SysConfig, error) { ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) if err := _q.prepareQuery(ctx); err != nil { return nil, err } - qr := querierAll[[]*BomItem, *BomItemQuery]() - return withInterceptors[[]*BomItem](ctx, _q, qr, _q.inters) + qr := querierAll[[]*SysConfig, *SysConfigQuery]() + return withInterceptors[[]*SysConfig](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (_q *BomItemQuery) AllX(ctx context.Context) []*BomItem { +func (_q *SysConfigQuery) AllX(ctx context.Context) []*SysConfig { nodes, err := _q.All(ctx) if err != nil { panic(err) @@ -179,20 +179,20 @@ func (_q *BomItemQuery) AllX(ctx context.Context) []*BomItem { return nodes } -// IDs executes the query and returns a list of BomItem IDs. -func (_q *BomItemQuery) IDs(ctx context.Context) (ids []int, err error) { +// IDs executes the query and returns a list of SysConfig IDs. +func (_q *SysConfigQuery) IDs(ctx context.Context) (ids []int, err error) { if _q.ctx.Unique == nil && _q.path != nil { _q.Unique(true) } ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(bomitem.FieldID).Scan(ctx, &ids); err != nil { + if err = _q.Select(sysconfig.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (_q *BomItemQuery) IDsX(ctx context.Context) []int { +func (_q *SysConfigQuery) IDsX(ctx context.Context) []int { ids, err := _q.IDs(ctx) if err != nil { panic(err) @@ -201,16 +201,16 @@ func (_q *BomItemQuery) IDsX(ctx context.Context) []int { } // Count returns the count of the given query. -func (_q *BomItemQuery) Count(ctx context.Context) (int, error) { +func (_q *SysConfigQuery) Count(ctx context.Context) (int, error) { ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, _q, querierCount[*BomItemQuery](), _q.inters) + return withInterceptors[int](ctx, _q, querierCount[*SysConfigQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (_q *BomItemQuery) CountX(ctx context.Context) int { +func (_q *SysConfigQuery) CountX(ctx context.Context) int { count, err := _q.Count(ctx) if err != nil { panic(err) @@ -219,7 +219,7 @@ func (_q *BomItemQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (_q *BomItemQuery) Exist(ctx context.Context) (bool, error) { +func (_q *SysConfigQuery) Exist(ctx context.Context) (bool, error) { ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) switch _, err := _q.FirstID(ctx); { case IsNotFound(err): @@ -232,7 +232,7 @@ func (_q *BomItemQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (_q *BomItemQuery) ExistX(ctx context.Context) bool { +func (_q *SysConfigQuery) ExistX(ctx context.Context) bool { exist, err := _q.Exist(ctx) if err != nil { panic(err) @@ -240,18 +240,18 @@ func (_q *BomItemQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the BomItemQuery builder, including all associated steps. It can be +// Clone returns a duplicate of the SysConfigQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (_q *BomItemQuery) Clone() *BomItemQuery { +func (_q *SysConfigQuery) Clone() *SysConfigQuery { if _q == nil { return nil } - return &BomItemQuery{ + return &SysConfigQuery{ config: _q.config, ctx: _q.ctx.Clone(), - order: append([]bomitem.OrderOption{}, _q.order...), + order: append([]sysconfig.OrderOption{}, _q.order...), inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.BomItem{}, _q.predicates...), + predicates: append([]predicate.SysConfig{}, _q.predicates...), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -265,19 +265,19 @@ func (_q *BomItemQuery) Clone() *BomItemQuery { // Example: // // var v []struct { -// ProductCode string `json:"productCode,omitempty"` +// Key string `json:"key,omitempty"` // Count int `json:"count,omitempty"` // } // -// client.BomItem.Query(). -// GroupBy(bomitem.FieldProductCode). +// client.SysConfig.Query(). +// GroupBy(sysconfig.FieldKey). // Aggregate(ent.Count()). // Scan(ctx, &v) -func (_q *BomItemQuery) GroupBy(field string, fields ...string) *BomItemGroupBy { +func (_q *SysConfigQuery) GroupBy(field string, fields ...string) *SysConfigGroupBy { _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &BomItemGroupBy{build: _q} + grbuild := &SysConfigGroupBy{build: _q} grbuild.flds = &_q.ctx.Fields - grbuild.label = bomitem.Label + grbuild.label = sysconfig.Label grbuild.scan = grbuild.Scan return grbuild } @@ -288,26 +288,26 @@ func (_q *BomItemQuery) GroupBy(field string, fields ...string) *BomItemGroupBy // Example: // // var v []struct { -// ProductCode string `json:"productCode,omitempty"` +// Key string `json:"key,omitempty"` // } // -// client.BomItem.Query(). -// Select(bomitem.FieldProductCode). +// client.SysConfig.Query(). +// Select(sysconfig.FieldKey). // Scan(ctx, &v) -func (_q *BomItemQuery) Select(fields ...string) *BomItemSelect { +func (_q *SysConfigQuery) Select(fields ...string) *SysConfigSelect { _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &BomItemSelect{BomItemQuery: _q} - sbuild.label = bomitem.Label + sbuild := &SysConfigSelect{SysConfigQuery: _q} + sbuild.label = sysconfig.Label sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } -// Aggregate returns a BomItemSelect configured with the given aggregations. -func (_q *BomItemQuery) Aggregate(fns ...AggregateFunc) *BomItemSelect { +// Aggregate returns a SysConfigSelect configured with the given aggregations. +func (_q *SysConfigQuery) Aggregate(fns ...AggregateFunc) *SysConfigSelect { return _q.Select().Aggregate(fns...) } -func (_q *BomItemQuery) prepareQuery(ctx context.Context) error { +func (_q *SysConfigQuery) prepareQuery(ctx context.Context) error { for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") @@ -319,7 +319,7 @@ func (_q *BomItemQuery) prepareQuery(ctx context.Context) error { } } for _, f := range _q.ctx.Fields { - if !bomitem.ValidColumn(f) { + if !sysconfig.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} } } @@ -333,16 +333,16 @@ func (_q *BomItemQuery) prepareQuery(ctx context.Context) error { return nil } -func (_q *BomItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BomItem, error) { +func (_q *SysConfigQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SysConfig, error) { var ( - nodes = []*BomItem{} + nodes = []*SysConfig{} _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { - return (*BomItem).scanValues(nil, columns) + return (*SysConfig).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &BomItem{config: _q.config} + node := &SysConfig{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } @@ -361,7 +361,7 @@ func (_q *BomItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BomI return nodes, nil } -func (_q *BomItemQuery) sqlCount(ctx context.Context) (int, error) { +func (_q *SysConfigQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() if len(_q.modifiers) > 0 { _spec.Modifiers = _q.modifiers @@ -373,8 +373,8 @@ func (_q *BomItemQuery) sqlCount(ctx context.Context) (int, error) { return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (_q *BomItemQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(bomitem.Table, bomitem.Columns, sqlgraph.NewFieldSpec(bomitem.FieldID, field.TypeInt)) +func (_q *SysConfigQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) _spec.From = _q.sql if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique @@ -383,9 +383,9 @@ func (_q *BomItemQuery) querySpec() *sqlgraph.QuerySpec { } if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, bomitem.FieldID) + _spec.Node.Columns = append(_spec.Node.Columns, sysconfig.FieldID) for i := range fields { - if fields[i] != bomitem.FieldID { + if fields[i] != sysconfig.FieldID { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } } @@ -413,12 +413,12 @@ func (_q *BomItemQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (_q *BomItemQuery) sqlQuery(ctx context.Context) *sql.Selector { +func (_q *SysConfigQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(bomitem.Table) + t1 := builder.Table(sysconfig.Table) columns := _q.ctx.Fields if len(columns) == 0 { - columns = bomitem.Columns + columns = sysconfig.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) if _q.sql != nil { @@ -451,7 +451,7 @@ func (_q *BomItemQuery) sqlQuery(ctx context.Context) *sql.Selector { // ForUpdate locks the selected rows against concurrent updates, and prevent them from being // updated, deleted or "selected ... for update" by other sessions, until the transaction is // either committed or rolled-back. -func (_q *BomItemQuery) ForUpdate(opts ...sql.LockOption) *BomItemQuery { +func (_q *SysConfigQuery) ForUpdate(opts ...sql.LockOption) *SysConfigQuery { if _q.driver.Dialect() == dialect.Postgres { _q.Unique(false) } @@ -464,7 +464,7 @@ func (_q *BomItemQuery) ForUpdate(opts ...sql.LockOption) *BomItemQuery { // ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock // on any rows that are read. Other sessions can read the rows, but cannot modify them // until your transaction commits. -func (_q *BomItemQuery) ForShare(opts ...sql.LockOption) *BomItemQuery { +func (_q *SysConfigQuery) ForShare(opts ...sql.LockOption) *SysConfigQuery { if _q.driver.Dialect() == dialect.Postgres { _q.Unique(false) } @@ -475,33 +475,33 @@ func (_q *BomItemQuery) ForShare(opts ...sql.LockOption) *BomItemQuery { } // Modify adds a query modifier for attaching custom logic to queries. -func (_q *BomItemQuery) Modify(modifiers ...func(s *sql.Selector)) *BomItemSelect { +func (_q *SysConfigQuery) Modify(modifiers ...func(s *sql.Selector)) *SysConfigSelect { _q.modifiers = append(_q.modifiers, modifiers...) return _q.Select() } -// BomItemGroupBy is the group-by builder for BomItem entities. -type BomItemGroupBy struct { +// SysConfigGroupBy is the group-by builder for SysConfig entities. +type SysConfigGroupBy struct { selector - build *BomItemQuery + build *SysConfigQuery } // Aggregate adds the given aggregation functions to the group-by query. -func (_g *BomItemGroupBy) Aggregate(fns ...AggregateFunc) *BomItemGroupBy { +func (_g *SysConfigGroupBy) Aggregate(fns ...AggregateFunc) *SysConfigGroupBy { _g.fns = append(_g.fns, fns...) return _g } // Scan applies the selector query and scans the result into the given value. -func (_g *BomItemGroupBy) Scan(ctx context.Context, v any) error { +func (_g *SysConfigGroupBy) Scan(ctx context.Context, v any) error { ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*BomItemQuery, *BomItemGroupBy](ctx, _g.build, _g, _g.build.inters, v) + return scanWithInterceptors[*SysConfigQuery, *SysConfigGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (_g *BomItemGroupBy) sqlScan(ctx context.Context, root *BomItemQuery, v any) error { +func (_g *SysConfigGroupBy) sqlScan(ctx context.Context, root *SysConfigQuery, v any) error { selector := root.sqlQuery(ctx).Select() aggregation := make([]string, 0, len(_g.fns)) for _, fn := range _g.fns { @@ -528,28 +528,28 @@ func (_g *BomItemGroupBy) sqlScan(ctx context.Context, root *BomItemQuery, v any return sql.ScanSlice(rows, v) } -// BomItemSelect is the builder for selecting fields of BomItem entities. -type BomItemSelect struct { - *BomItemQuery +// SysConfigSelect is the builder for selecting fields of SysConfig entities. +type SysConfigSelect struct { + *SysConfigQuery selector } // Aggregate adds the given aggregation functions to the selector query. -func (_s *BomItemSelect) Aggregate(fns ...AggregateFunc) *BomItemSelect { +func (_s *SysConfigSelect) Aggregate(fns ...AggregateFunc) *SysConfigSelect { _s.fns = append(_s.fns, fns...) return _s } // Scan applies the selector query and scans the result into the given value. -func (_s *BomItemSelect) Scan(ctx context.Context, v any) error { +func (_s *SysConfigSelect) Scan(ctx context.Context, v any) error { ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*BomItemQuery, *BomItemSelect](ctx, _s.BomItemQuery, _s, _s.inters, v) + return scanWithInterceptors[*SysConfigQuery, *SysConfigSelect](ctx, _s.SysConfigQuery, _s, _s.inters, v) } -func (_s *BomItemSelect) sqlScan(ctx context.Context, root *BomItemQuery, v any) error { +func (_s *SysConfigSelect) sqlScan(ctx context.Context, root *SysConfigQuery, v any) error { selector := root.sqlQuery(ctx) aggregation := make([]string, 0, len(_s.fns)) for _, fn := range _s.fns { @@ -571,7 +571,7 @@ func (_s *BomItemSelect) sqlScan(ctx context.Context, root *BomItemQuery, v any) } // Modify adds a query modifier for attaching custom logic to queries. -func (_s *BomItemSelect) Modify(modifiers ...func(s *sql.Selector)) *BomItemSelect { +func (_s *SysConfigSelect) Modify(modifiers ...func(s *sql.Selector)) *SysConfigSelect { _s.modifiers = append(_s.modifiers, modifiers...) return _s } diff --git a/bj_power_mes/ent/sysconfig_update.go b/bj_power_mes/ent/sysconfig_update.go new file mode 100644 index 0000000..4a65711 --- /dev/null +++ b/bj_power_mes/ent/sysconfig_update.go @@ -0,0 +1,357 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/predicate" + "bj_power_mes/ent/sysconfig" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigUpdate is the builder for updating SysConfig entities. +type SysConfigUpdate struct { + config + hooks []Hook + mutation *SysConfigMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the SysConfigUpdate builder. +func (_u *SysConfigUpdate) Where(ps ...predicate.SysConfig) *SysConfigUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetKey sets the "key" field. +func (_u *SysConfigUpdate) SetKey(v string) *SysConfigUpdate { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableKey(v *string) *SysConfigUpdate { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// SetValue sets the "value" field. +func (_u *SysConfigUpdate) SetValue(v string) *SysConfigUpdate { + _u.mutation.SetValue(v) + return _u +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableValue(v *string) *SysConfigUpdate { + if v != nil { + _u.SetValue(*v) + } + return _u +} + +// SetRemark sets the "remark" field. +func (_u *SysConfigUpdate) SetRemark(v string) *SysConfigUpdate { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableRemark(v *string) *SysConfigUpdate { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *SysConfigUpdate) ClearRemark() *SysConfigUpdate { + _u.mutation.ClearRemark() + return _u +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_u *SysConfigUpdate) Mutation() *SysConfigMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SysConfigUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SysConfigUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SysConfigUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SysConfigUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SysConfigUpdate) check() error { + if v, ok := _u.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if v, ok := _u.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _u.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *SysConfigUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SysConfigUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *SysConfigUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + } + if value, ok := _u.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(sysconfig.FieldRemark, field.TypeString) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sysconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SysConfigUpdateOne is the builder for updating a single SysConfig entity. +type SysConfigUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SysConfigMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetKey sets the "key" field. +func (_u *SysConfigUpdateOne) SetKey(v string) *SysConfigUpdateOne { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableKey(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// SetValue sets the "value" field. +func (_u *SysConfigUpdateOne) SetValue(v string) *SysConfigUpdateOne { + _u.mutation.SetValue(v) + return _u +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableValue(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetValue(*v) + } + return _u +} + +// SetRemark sets the "remark" field. +func (_u *SysConfigUpdateOne) SetRemark(v string) *SysConfigUpdateOne { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableRemark(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *SysConfigUpdateOne) ClearRemark() *SysConfigUpdateOne { + _u.mutation.ClearRemark() + return _u +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_u *SysConfigUpdateOne) Mutation() *SysConfigMutation { + return _u.mutation +} + +// Where appends a list predicates to the SysConfigUpdate builder. +func (_u *SysConfigUpdateOne) Where(ps ...predicate.SysConfig) *SysConfigUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SysConfigUpdateOne) Select(field string, fields ...string) *SysConfigUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated SysConfig entity. +func (_u *SysConfigUpdateOne) Save(ctx context.Context) (*SysConfig, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SysConfigUpdateOne) SaveX(ctx context.Context) *SysConfig { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SysConfigUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SysConfigUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SysConfigUpdateOne) check() error { + if v, ok := _u.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if v, ok := _u.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _u.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *SysConfigUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *SysConfigUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *SysConfigUpdateOne) sqlSave(ctx context.Context) (_node *SysConfig, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SysConfig.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, sysconfig.FieldID) + for _, f := range fields { + if !sysconfig.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != sysconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + } + if value, ok := _u.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(sysconfig.FieldRemark, field.TypeString) + } + _spec.AddModifiers(_u.modifiers...) + _node = &SysConfig{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sysconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/bj_power_mes/ent/tx.go b/bj_power_mes/ent/tx.go index 0b25123..3aff1b4 100644 --- a/bj_power_mes/ent/tx.go +++ b/bj_power_mes/ent/tx.go @@ -20,8 +20,6 @@ type Tx struct { AssociationTrace *AssociationTraceClient // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient - // BomItem is the client for interacting with the BomItem builders. - BomItem *BomItemClient // DailyPlan is the client for interacting with the DailyPlan builders. DailyPlan *DailyPlanClient // Dock is the client for interacting with the Dock builders. @@ -60,6 +58,8 @@ type Tx struct { StepCriterion *StepCriterionClient // StepData is the client for interacting with the StepData builders. StepData *StepDataClient + // SysConfig is the client for interacting with the SysConfig builders. + SysConfig *SysConfigClient // TorqueAuditLog is the client for interacting with the TorqueAuditLog builders. TorqueAuditLog *TorqueAuditLogClient // TorqueRecord is the client for interacting with the TorqueRecord builders. @@ -211,7 +211,6 @@ func (tx *Tx) init() { tx.AlertRule = NewAlertRuleClient(tx.config) tx.AssociationTrace = NewAssociationTraceClient(tx.config) tx.Attachment = NewAttachmentClient(tx.config) - tx.BomItem = NewBomItemClient(tx.config) tx.DailyPlan = NewDailyPlanClient(tx.config) tx.Dock = NewDockClient(tx.config) tx.EventLog = NewEventLogClient(tx.config) @@ -231,6 +230,7 @@ func (tx *Tx) init() { tx.StationState = NewStationStateClient(tx.config) tx.StepCriterion = NewStepCriterionClient(tx.config) tx.StepData = NewStepDataClient(tx.config) + tx.SysConfig = NewSysConfigClient(tx.config) tx.TorqueAuditLog = NewTorqueAuditLogClient(tx.config) tx.TorqueRecord = NewTorqueRecordClient(tx.config) tx.User = NewUserClient(tx.config) diff --git a/bj_power_mes/frontend/src/help.js b/bj_power_mes/frontend/src/help.js index cf4f3e5..c1afedf 100644 --- a/bj_power_mes/frontend/src/help.js +++ b/bj_power_mes/frontend/src/help.js @@ -81,26 +81,6 @@ export const helpDailyPlan = { ] } -export const helpBom = { - title: '产品物料清单', - overview: - '物料清单 = 生产 1 台该产品需要哪些物料、各用多少。\n按「产品编号 + 物料清单名称」维护:同一产品编号可并存多份物料清单(选用制)——不同厂家供货、含半成品的结构差异,都用不同的物料清单名称区分(缺省叫「默认」,不用 V1/V2 版本号)。\n工单建单时选定其中一份,之后该工单的备料算料、装机绑定校验都锁定这份物料清单,不同厂家的料单互不串。\n\n与 WMS 的关系:本页(MES)只维护「产品由哪几种料、各用几个」;每种物料叫什么、规格、按序列号还是按批次管理、库存有多少,统一在 WMS(库房)的「物料档案」里维护,两套系统互相解耦、通过图号对齐。\n\n编码对应规则:本页的「图号」必须与 WMS 物料档案里的「图号」完全一致;「管理方式」也要对应(电气件=SN 逐件,结构件=批次)。编码对不上,WMS 将无法为对应工单备料/出库。\n\n保护规则:某份物料清单一旦被工单选用过,就不允许再从中移除物料(防止历史工单追溯断链);新建/改名的物料清单名称在本页「物料清单名称」下拉直接输入即可创建。\n\n数据链路:先建「物料档案」→ 到本页选产品编号 + 命名物料清单,逐条添加物料 → 建工单时选定物料清单 → 仓库才能为对应工单领料。', - fields: [ - { name: '物料清单名称', source: '下拉选择/输入(可搜索,输入新名即创建)。缺省「默认」。', purpose: '同一产品编号下多份物料清单的区分名,工单建单时按此选定', fill: '如「默认」「A厂料单」「含半成品」;同一型号下名称唯一' }, - { name: '产品编号', source: '下拉选择。来自「物料档案」里建的编码。', purpose: '要为哪个产品配置物料清单', fill: '在查询区或「添加物料」弹窗里选择产品编号' }, - { name: '图号', source: '手工填写。必须与 WMS(库房) 物料档案的图号一致。', purpose: '该物料在库房的全库唯一编码,两系统靠它关联', fill: '如 螺丝=GJ-LUOSI-M16;图号对不上 WMS 将无法备料' }, - { name: '物料名称', source: '手工填写。', purpose: '物料中文名,便于识别', fill: '如 十字螺丝、主控芯片' }, - { name: '规格', source: '手工填写。', purpose: '物料规格型号', fill: '如 M16×80 / SMT-48脚' }, - { name: '单位', source: '手工填写。', purpose: '计量单位,用于算量', fill: '个 / 件 / 套 / kg' }, - { name: '管理方式', source: '单选。按物料类型决定,与 WMS 一致。', purpose: '电气件=逐件按SN管理;结构件=按批次管理', fill: '电气件/电子件选"序列号";螺丝等标准件选"批次"' }, - { name: '单台用量', source: '手工填写。', purpose: '生产 1 台产品用的该物料数量', fill: '如每台 8 颗螺丝 → 填 8' }, - { name: '损耗率%', source: '手工填写。', purpose: '考虑报废/损耗的加放比例', fill: '如 2% 填 2;0=不计算损耗' }, - { name: '需求量', source: '自动计算 = 数量×单台用量×(1+损耗率),可覆盖。', purpose: '该物料总需求,出库不能超它', fill: '一般自动算,不必改' }, - { name: '相关标准', source: '手工填写/导入带入。', purpose: '该物料对应的检验/工艺标准(如国标、图号标准),供质量检验与流程卡引用', fill: '如 GB/T xxx;可在导入模板中一列填入' }, - { name: '导入', source: 'Excel 模板导入(列表页「导入」按钮)。', purpose: '批量维护物料清单,减少逐条录入', fill: '下载模板→填写→上传,系统预检(编码/管理方式/数值)并提示错误行,确认后入库' } - ] -} - export const helpMaterial = { title: '备料单(按日排产自动算料)', overview: @@ -222,11 +202,39 @@ export const helpStation = { { name: '接驳台', source: '内置数据给定(对应实体位置),不可手动更改。', purpose: '该工位位置是否有接驳台', fill: '只读' }, { name: '接驳台编码', source: '系统预置(种子初始化),与工位 1:1。', purpose: '该工位绑定的接驳台唯一标识', fill: '只读;由种子初始化,页面不可更改' }, { name: '绑定工艺', source: '本页下拉选择「启用」的工艺即完成绑定。', purpose: '该工位执行的工艺(决定工艺步骤/考核标准/PDF/物料清单);一个工位只能绑定一个工艺', fill: '在本页下拉为该工位选择启用工艺;工单执行路线由工单工艺组合决定' }, + { name: '终端可见页签', source: '本页「页签」按钮配置(station.visibleTabs)。', purpose: '该工位终端允许显示哪些功能页签(上线建档/作业/物料/移料/工艺文件/巡检/下线完工),按工位差异化界面', fill: '点「页签」勾选;全部不勾 = 显示全部页签,保存后终端下次拉取任务生效' }, { name: '删除', source: '本页操作。', purpose: '删除自定义工位', fill: '仅自定义工位可删除;内置工位不允许删除' }, { name: '虚拟工位 0 / 13', source: '系统预置。工位号 0=上线位、13=下线位。', purpose: '产线进线口建档上线、出料口完工入库,由 PAD 操作,不连 PLC/拧紧枪', fill: '只读;上线位/下线位在工位终端(PAD)用「上线建档」「下线完工」面板操作' } ] } +export const helpVirtualStation = { + title: '虚拟工位作业(MES 后台人工报工)', + overview: + '虚拟工位 = 没有终端硬件(无屏、无 PLC、无拧紧枪)的工位(如包装等辅助工序,线下位类型)。这类工位无法用工位终端,由操作人用自己的手机/电脑登录 MES 后台,在本页完成作业:选择自己的虚拟工位 → 选工单、扫/输工件SN → 查看当前工艺步骤与应绑配料 → 逐项录入 → 点「完成报工」。\n\n与工位终端走同一套接口与校验(/station/task、/station/report):齐套校验、检测确认校验、不可倒序报工等规则完全一致;拧紧步骤因无硬件不在本页采集(由物理工位拧紧枪采集)。\n\n权限:菜单「虚拟工位作业」按账号开通(角色管理勾选 produce.virtualstation),不给普通账号开「工位绑定」等管理菜单即可。', + fields: [ + { name: '选择虚拟工位', source: '下拉来自「工位绑定」页维护的工位(建议给虚拟工序建线下位类型工位)。', purpose: '报工落在哪个工位(报工校验工位必须在工单工艺组合中)', fill: '选择自己负责的虚拟工位' }, + { name: '工单', source: '今日已启用日排产且工单已下发/在制(与终端口径一致)。', purpose: '本工位今天该干哪些工单', fill: '选择当前作业的工单' }, + { name: '工件SN', source: '上线建档时系统生成的工件唯一码(标签/二维码)。', purpose: '定位工件与所属工单,报工/绑定都挂在 SN 下', fill: '扫码或手输后回车载入' }, + { name: '工艺步骤', source: '工位绑定工艺的步骤模板(工艺页维护)。', purpose: '本工位要做什么、考核标准是什么', fill: '手填步骤逐项录入数值/结果;「检测确认」步骤需勾选;拧紧步骤由物理工位采集,本页只读' }, + { name: '配料', source: '工艺物料清单(flow_material)中该工艺要求装配的物料 + 已绑记录(bind-panel 接口)。', purpose: '装机绑定强校验:电气件需绑满单台用量 SN、结构件至少绑一个批次号,缺料不允许报工', fill: '在录入框填批次号/SN(多个用逗号分隔),随报工一次性提交' }, + { name: '完成报工', source: 'POST /station/report(与终端同一接口)。', purpose: '写实绩 + 步骤考核 + 装机绑定,原子提交', fill: '全部录入后点「完成报工」;报错按提示补齐' } + ] +} + +export const helpSettings = { + title: '基础设置(系统管理员)', + overview: + '运行参数集中配置页,保存即生效(无需重启服务)。库存查询、缺料补货、可生产套数、排产支撑均为实时计算:库存实时来自 WMS,需求按「日排产 × 工单工艺组合」现场汇总,MES 不落库存/需求表,所以改配置立刻影响下一次计算。\n\n可配置项:\n· WMS 地址(IP:端口):保存后热切换,所有库存查询/扣账/台账同步即刻走新地址;「测试连通」只试测不保存,失败不影响当前配置。\n· 需求窗口天数:缺料补货/未来需求按日排产取未来 N 天(默认 5),WMS 备料四态「预警」数据源。\n· 外推均值窗口 / 外推封顶:排产支撑在排产日耗尽仍有余量时,按近 N 天平均日需求外推,封顶防死循环。\n· 事件日志保留天数:超过保留期的操作日志每小时自动清理,0=不清理。\n\n本机基础信息(只读):主机名/内网 IP、服务监听地址、数据库、当前生效 WMS 地址、Go 版本、启动时间。\n\n安全边界:JWT 密钥、WMS Token、数据库密码等敏感信息一律留在 etc/bj_power_mes-api.yaml,不进本页(不在库里明文存密)。', + fields: [ + { name: 'WMS 地址', source: '手工填写(sys_config: wms.base_url),留空=用 YAML 配置/默认 127.0.0.1:9091。', purpose: '库存查询/扣账/半成品流转/台账同步的 WMS 服务地址,保存即热切换', fill: '如 http://192.168.1.100:9091;先用「测试连通」验证再保存' }, + { name: '需求窗口天数', source: '数字(sys_config: demand.days,默认 5)。', purpose: '缺料补货/未来需求 = 未来 N 天日排产 × 工单单台含损耗用量', fill: '1~60 天;改大可提前看到更远期备料需求' }, + { name: '外推均值窗口', source: '数字(sys_config: producible.extrap.window,默认 3)。', purpose: '排产支撑外推取最近 N 天平均日需求', fill: '1~30 天' }, + { name: '外推封顶', source: '数字(sys_config: producible.extrap.cap,默认 365)。', purpose: '排产支撑外推最多算 N 天,防死循环', fill: '30~3650 天' }, + { name: '事件日志保留天数', source: '数字(sys_config: eventlog.retention.days,默认 0=不清理)。', purpose: '操作日志超期自动清理(每小时检查一次)', fill: '如 180 = 保留半年;0 = 永不清理' } + ] +} + export const helpDock = { title: '接驳台维护(只读主数据)', overview: @@ -456,9 +464,9 @@ export const helpProcessCard = { export const helpQuality = { title: '质量检验(过程检 / 完工检)', overview: - '质量检验 = 对物料/产品做检验判定并留痕,分「过程检」与「完工检」两个 Tab。来料检在 WMS 库房侧完成,本页不重复。\n\n录入流程:选图号(输入图号或名称远程检索物料清单,自动带出物料名称)→ 填报检单号/生产厂家/检验单号 → 上传附件 → 判定合格/不合格 → 保存。\n\n不合格闭环:结论为「不合格」时可当场选择处置方式(退货/返修/退换)并写处置说明;也可在列表操作列「处置」补录,或点「不合格单」一键导出《不合格单.xlsx》(预填本次检验数据)。\n\n查询:图号 / 物料名称 / 报检单号 / 记录日期范围组合筛选,每个框内模糊匹配、多框取交集;记录按时间倒序,后端真分页。', + '质量检验 = 对物料/产品做检验判定并留痕,分「过程检」与「完工检」两个 Tab。来料检在 WMS 库房侧完成,本页不重复。\n\n录入流程:选图号(输入图号或名称远程检索 WMS 物料档案,自动带出物料名称)→ 填报检单号/生产厂家/检验单号 → 上传附件 → 判定合格/不合格 → 保存。\n\n不合格闭环:结论为「不合格」时可当场选择处置方式(退货/返修/退换)并写处置说明;也可在列表操作列「处置」补录,或点「不合格单」一键导出《不合格单.xlsx》(预填本次检验数据)。\n\n查询:图号 / 物料名称 / 报检单号 / 记录日期范围组合筛选,每个框内模糊匹配、多框取交集;记录按时间倒序,后端真分页。', fields: [ - { name: '图号', source: '远程检索物料清单(/quality/bom-material),也可手填。', purpose: '被检物料的图号(即 WMS 物料档案的图号)', fill: '输入图号或名称关键字选择' }, + { name: '图号', source: '远程检索 WMS 物料档案(/materials 代理接口,WMS 是物料主数据源),也可手填。', purpose: '被检物料的图号(即 WMS 物料档案的图号)', fill: '输入图号或名称关键字选择' }, { name: '物料名称', source: '选图号后自动带出,可手改。', purpose: '被检物料名称', fill: '一般无需手填' }, { name: '报检单号', source: '系统自动生成(RQ+时间戳),可改。', purpose: '本次报检的唯一编号,也是附件挂靠键', fill: '一般无需改,须唯一' }, { name: '生产厂家', source: '手工填写。', purpose: '该物料的生产/供货厂家', fill: '如 XX电气有限公司' }, @@ -523,12 +531,12 @@ export const helpAttachment = { export const helpProducible = { title: '排产支撑', overview: - '把「库存还能撑多久」算清楚,给计划员排产/叫料决策用。数据来源:日排产(daily_plan)× 工单(work_order)× BOM(产品物料清单)得到需求量,库存可用量实时来自 WMS(/api/internal/stock/check)。\n\n本页两块:\n· 各成品可生产套数:只统计启用产品(停用产品不再展示产能,列表分页展示);按每个成品的 BOM 单台用量 ÷ 对应物料 WMS 可用量取最小值,即当前库存最多还能装出多少台该成品;短板说明列出限制它的物料(可用量 ÷ 单台用量 = 套数)。\n· 整体支撑:用 WMS 可用量对日排产做逐日消耗模拟,直到某物料不足,得出「还能满产多少天」「库存可支撑到哪天」「最先告罄的短板物料」;排产只排到 N 天时,第 N+1 天起用近3天平均日需求外推(封顶365天防死循环)。\n\n无排产计划时短板物料栏显示「无排产计划」;排产日全部满足且外推无有效需求时显示「充足」。本页只读,不落库。', + '把「库存还能撑多久」算清楚,给计划员排产/叫料决策用。数据来源:日排产(daily_plan,按排产日期窗口、剔除已取消排产)× 工单(work_order)× 工单工艺组合 × 工艺物料清单(flow_material)得到需求量,库存可用量实时来自 WMS(/api/internal/stock/check)。注意:物料需求跟着工单走(同成品不同工单可用不同工艺),且一律按日排产口径计算,工单起止日期仅作参考。\n\n本页两块:\n· 各成品可生产套数:只统计有未取消日排产的工单;按该工单工艺组合的物料单台含损耗用量 ÷ 对应物料 WMS 可用量取最小值,即当前库存最多还能装出多少台;短板说明列出限制它的物料(可用量 ÷ 单台用量 = 套数)。\n· 整体支撑:用 WMS 可用量对日排产做逐日消耗模拟,直到某物料不足,得出「还能满产多少天」「库存可支撑到哪天」「最先告罄的短板物料」;排产只排到 N 天时,第 N+1 天起用近3天平均日需求外推(封顶365天防死循环)。\n\n无排产计划时短板物料栏显示「无排产计划」;排产日全部满足且外推无有效需求时显示「充足」。本页只读,不落库。', fields: [ { name: '还能满产(天)', source: '逐日消耗模拟算得(/api/v1/production/producible-support)。', purpose: '一眼看出按当前排产节奏库存能撑几天', fill: '=0 表示今天/近期排产即缺料,需立即补料' }, { name: '库存可支撑到', source: '支撑天数 + 今日日期推算。', purpose: '给出最晚需要到货的日期', fill: '只读;格式 YYYY-MM-DD' }, { name: '最先告罄短板物料', source: '模拟中第一个被耗尽的物料(名称+编码)。', purpose: '指出最该优先补货的物料', fill: '「无排产计划」/「充足」表示暂无瓶颈' }, - { name: '可生产套数', source: '逐成品计算(只算启用产品,停用产品不展示):min(各物料可用量 ÷ 单台用量)。', purpose: '该成品当前库存能装出的最多台数', fill: '=0 表示关键物料已缺,无法开线' }, + { name: '可生产套数', source: '逐工单计算(只算有未取消日排产的工单):min(各物料可用量 ÷ 单台含损耗用量)。', purpose: '该工单当前库存能装出的最多台数', fill: '=0 表示关键物料已缺,无法开线' }, { name: '短板说明', source: '限制该成品可生产套数的物料明细(可用量÷单台用量=套数)。', purpose: '定位缺哪料、缺多少', fill: '只读;多短板时最多列前3个' } ] } diff --git a/bj_power_mes/frontend/src/layouts/MainLayout.vue b/bj_power_mes/frontend/src/layouts/MainLayout.vue index 4cd901d..934ff65 100644 --- a/bj_power_mes/frontend/src/layouts/MainLayout.vue +++ b/bj_power_mes/frontend/src/layouts/MainLayout.vue @@ -70,7 +70,7 @@ import { useRouter } from 'vue-router' import { Document, Calendar, Box, Goods, ShoppingCart, Monitor, Tools, Operation, Link, DataLine, Search, CircleCheck, Clock, User, - Key, Fold, Expand, Warning, Paperclip, Tickets, Bell, Aim + Key, Fold, Expand, Warning, Paperclip, Tickets, Bell, Aim, Setting } from '@element-plus/icons-vue' import { ElNotification } from 'element-plus' import { getUser, logout } from '../utils/auth' @@ -130,7 +130,6 @@ const menuGroups = [ title: '生产管理', icon: Document, children: [ { code: 'produce.workorder', name: '工单管理', path: '/work-order', icon: Document }, { code: 'produce.dailyplan', name: '日排产', path: '/daily-plan', icon: Calendar }, - { code: 'produce.bom', name: '产品物料清单', path: '/bom', icon: Goods }, { code: 'produce.producible', name: '排产支撑', path: '/producible-support', icon: DataLine }, { code: 'produce.material', name: '备料单', path: '/material-request', icon: ShoppingCart }, { code: 'produce.qty', name: '数量不符处理', path: '/qty-report', icon: Warning }, @@ -143,6 +142,7 @@ const menuGroups = [ { code: 'produce.plc', name: '工位组合下发', path: '/plc-send', icon: Monitor }, { code: 'produce.wip', name: '在制品', path: '/wip', icon: Clock }, { code: 'produce.trace', name: '工件追溯', path: '/trace', icon: Search }, + { code: 'produce.virtualstation', name: '虚拟工位作业', path: '/virtual-station', icon: Goods }, { code: 'produce.processcard', name: '生产流程卡', path: '/process-card', icon: Tickets }, { code: 'produce.torque', name: '拧紧查询', path: '/torque', icon: Tools }, { code: 'sys.inspect', name: '巡检终端', path: '/inspect', icon: CircleCheck } @@ -162,7 +162,8 @@ const menuGroups = [ { code: 'sys.role', name: '角色管理', path: '/role', icon: Key }, { code: 'sys.eventlog', name: '操作日志', path: '/event-log', icon: Clock }, { code: 'sys.alert', name: '预警中心', path: '/alert-center', icon: Warning }, - { code: 'sys.attachment', name: '附件中心', path: '/attachment', icon: Paperclip } + { code: 'sys.attachment', name: '附件中心', path: '/attachment', icon: Paperclip }, + { code: 'sys.settings', name: '基础设置', path: '/settings', icon: Setting } ] } ] diff --git a/bj_power_mes/frontend/src/pages/Bom.vue b/bj_power_mes/frontend/src/pages/Bom.vue deleted file mode 100644 index 0e2d387..0000000 --- a/bj_power_mes/frontend/src/pages/Bom.vue +++ /dev/null @@ -1,165 +0,0 @@ - - - diff --git a/bj_power_mes/frontend/src/pages/EventLog.vue b/bj_power_mes/frontend/src/pages/EventLog.vue index 131877a..8b46d54 100644 --- a/bj_power_mes/frontend/src/pages/EventLog.vue +++ b/bj_power_mes/frontend/src/pages/EventLog.vue @@ -69,7 +69,6 @@ import { helpEventLog } from '../help' const EVENT_FAMILIES = [ { label: '工单', value: 'work.order.' }, { label: '日排产', value: 'daily.plan.' }, - { label: '物料清单', value: 'bom.' }, { label: '备料单', value: 'material.request.' }, { label: '工艺', value: 'process.flow.' }, { label: '关联工位', value: 'station.' }, @@ -82,13 +81,13 @@ const EVENT_FAMILIES = [ ] const FAMILY_LABEL = Object.fromEntries(EVENT_FAMILIES.map((f) => [f.value, f.label])) const FAMILY_TAG = { - 'work.order.': 'primary', 'daily.plan.': 'success', 'bom.': 'warning', + 'work.order.': 'primary', 'daily.plan.': 'success', 'material.request.': 'warning', 'process.flow.': 'info', 'station.': 'info', 'plc.': 'danger', 'torque.': 'info', 'scan.': 'success', 'workpiece.': 'success', 'inspection.': 'warning', 'semi.': 'info' } const ENTITY_LABEL = { - work_order: '工单', product_bom: '物料清单', material_request: '备料单', + work_order: '工单', material_request: '备料单', process_flow: '工艺', station: '工位', workpiece: '工件', torque: '拧紧', inspection: '检验', scan: '报工', daily_plan: '日排产', plc: '下发', semi: '半成品' } diff --git a/bj_power_mes/frontend/src/pages/ProcessCard.vue b/bj_power_mes/frontend/src/pages/ProcessCard.vue index 569a852..fb52426 100644 --- a/bj_power_mes/frontend/src/pages/ProcessCard.vue +++ b/bj_power_mes/frontend/src/pages/ProcessCard.vue @@ -103,11 +103,11 @@ - + - +
-
物料清单:{{ g.bomName }}
+
工艺物料清单:{{ g.bomName }}
diff --git a/bj_power_mes/frontend/src/pages/ProducibleSupport.vue b/bj_power_mes/frontend/src/pages/ProducibleSupport.vue index 4064703..4b94c01 100644 --- a/bj_power_mes/frontend/src/pages/ProducibleSupport.vue +++ b/bj_power_mes/frontend/src/pages/ProducibleSupport.vue @@ -51,7 +51,7 @@ onMounted(load) - + + + + @@ -83,6 +92,18 @@ 保存 + + + + + {{ t.l }} + + + @@ -98,14 +119,43 @@ import { helpStation } from '../help' const stations = ref([]) const flows = ref([]) +// 终端页签固定集合(与工位终端 Main.vue 页签一一对应) +const TAB_OPTIONS = [ + { v: 'online', l: '上线建档' }, + { v: 'work', l: '作业' }, + { v: 'material', l: '物料' }, + { v: 'move', l: '移料' }, + { v: 'pdf', l: '工艺文件' }, + { v: 'inspect', l: '巡检' }, + { v: 'offline', l: '下线完工' } +] +const tabLabel = (v) => (TAB_OPTIONS.find((t) => t.v === v) || {}).l || v + const rows = computed(() => { return [...stations.value] .sort((a, b) => (a.stationNo || 0) - (b.stationNo || 0)) - .map((s) => ({ id: s.id, stationNo: s.stationNo, name: s.name, flowId: s.flowId, flowName: s.flowName, stationType: s.stationType, isBuiltin: !!s.isBuiltin, hasDock: !!s.hasDock, dockCode: s.dockCode || '' })) + .map((s) => ({ id: s.id, stationNo: s.stationNo, name: s.name, flowId: s.flowId, flowName: s.flowName, stationType: s.stationType, isBuiltin: !!s.isBuiltin, hasDock: !!s.hasDock, dockCode: s.dockCode || '', visibleTabs: Array.isArray(s.visibleTabs) ? s.visibleTabs : [] })) }) const dlg = reactive({ show: false, isAdd: false, title: '', id: 0, stationNo: 1, name: '', stationType: 'LINE', isBuiltin: false, hasDock: false }) +// 终端可见页签编辑(空数组 = 显示全部) +const tabDlg = reactive({ show: false, id: 0, stationNo: 0, name: '', stationType: 'LINE', tabs: [] }) + +function openTabs(row) { + Object.assign(tabDlg, { show: true, id: row.id, stationNo: row.stationNo, name: row.name, stationType: row.stationType || 'LINE', tabs: [...row.visibleTabs] }) +} + +async function saveTabs() { + await request.post('/stations', { + id: tabDlg.id, stationNo: tabDlg.stationNo, name: tabDlg.name, + stationType: tabDlg.stationType, visibleTabs: tabDlg.tabs + }) + ElMessage.success('页签配置已保存') + tabDlg.show = false + load() +} + async function load() { stations.value = (await request.get('/stations')) || [] } diff --git a/bj_power_mes/frontend/src/pages/VirtualStation.vue b/bj_power_mes/frontend/src/pages/VirtualStation.vue new file mode 100644 index 0000000..41e5e3b --- /dev/null +++ b/bj_power_mes/frontend/src/pages/VirtualStation.vue @@ -0,0 +1,247 @@ + + + diff --git a/bj_power_mes/frontend/src/pages/WorkOrder.vue b/bj_power_mes/frontend/src/pages/WorkOrder.vue index 7c09304..3a1f398 100644 --- a/bj_power_mes/frontend/src/pages/WorkOrder.vue +++ b/bj_power_mes/frontend/src/pages/WorkOrder.vue @@ -57,8 +57,9 @@ - + + + + + + + + + + + + + + + + + +
@@ -286,6 +308,17 @@ async function loadComboData() { } catch { flows.value = [] } } +// ---------- 工单单台用料汇总(只读) ---------- +const usage = reactive({ show: false, orderNo: '', rows: [], loading: false }) +async function openUsage(row) { + Object.assign(usage, { show: true, orderNo: row.workOrderNo, rows: [], loading: true }) + try { + usage.rows = (await request.get('/order-usage', { params: { orderNo: row.workOrderNo } })) || [] + } finally { + usage.loading = false + } +} + const dialog = reactive({ show: false, id: 0, workOrderNo: '', productTypeId: 0, productCode: '', productName: '', contractNo: '', projectNo: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', status: 'CREATED' }) async function load() { diff --git a/bj_power_mes/frontend/src/router/index.js b/bj_power_mes/frontend/src/router/index.js index 498544c..8e9a75c 100644 --- a/bj_power_mes/frontend/src/router/index.js +++ b/bj_power_mes/frontend/src/router/index.js @@ -10,7 +10,6 @@ const routes = [ { path: '', redirect: '/work-order' }, { path: 'work-order', name: 'WorkOrder', component: () => import('../pages/WorkOrder.vue'), meta: { title: '工单管理' } }, { path: 'daily-plan', name: 'DailyPlan', component: () => import('../pages/DailyPlan.vue'), meta: { title: '日排产' } }, - { path: 'bom', name: 'Bom', component: () => import('../pages/Bom.vue'), meta: { title: '产品物料清单' } }, { path: 'producible-support', name: 'ProducibleSupport', component: () => import('../pages/ProducibleSupport.vue'), meta: { title: '排产支撑' } }, { path: 'material-request', name: 'MaterialRequest', component: () => import('../pages/MaterialRequest.vue'), meta: { title: '备料单' } }, { path: 'qty-report', name: 'QtyReport', component: () => import('../pages/QtyReport.vue'), meta: { title: '数量不符处理' } }, @@ -24,6 +23,8 @@ const routes = [ { path: 'quality', name: 'QualityInspection', component: () => import('../pages/QualityInspection.vue'), meta: { title: '质量检验' } }, { path: 'wip', name: 'Wip', component: () => import('../pages/Wip.vue'), meta: { title: '在制品' } }, { path: 'trace', name: 'Trace', component: () => import('../pages/Trace.vue'), meta: { title: '工件追溯' } }, + { path: 'virtual-station', name: 'VirtualStation', component: () => import('../pages/VirtualStation.vue'), meta: { title: '虚拟工位作业' } }, + { path: 'settings', name: 'Settings', component: () => import('../pages/Settings.vue'), meta: { title: '基础设置' } }, { path: 'process-card', name: 'ProcessCard', component: () => import('../pages/ProcessCard.vue'), meta: { title: '生产流程卡' } }, { path: 'product-type', name: 'ProductType', component: () => import('../pages/ProductType.vue'), meta: { title: '物料档案' } }, { path: 'event-log', name: 'EventLog', component: () => import('../pages/EventLog.vue'), meta: { title: '操作日志' } }, diff --git a/bj_power_mes/internal/db/db.go b/bj_power_mes/internal/db/db.go index 81beca8..c094ce1 100644 --- a/bj_power_mes/internal/db/db.go +++ b/bj_power_mes/internal/db/db.go @@ -188,6 +188,9 @@ var schemaPatchSQL = []string{ // 路线唯一源头 = 工单工艺组合 flow_combination([{flowId,stationNo}],工位号即顺序号); // 装配绑定/备料/齐套全部改走工艺物料清单 flow_material,bom_item/material_request/process_code 退役。 `DROP TABLE IF EXISTS station_process`, + // ---- BOM 删除(2026-09-23 定稿):用料唯一来源=工单工艺组合×工艺物料清单,产品物料清单表退役 ---- + `DROP TABLE IF EXISTS bom_item`, + `DROP TABLE IF EXISTS work_order_bom`, `ALTER TABLE workpiece_process DROP COLUMN IF EXISTS process_code`, `ALTER TABLE workpiece_bind DROP COLUMN IF EXISTS process_code`, `ALTER TABLE material_request DROP COLUMN IF EXISTS process_code`, diff --git a/bj_power_mes/internal/eventlog/eventlog.go b/bj_power_mes/internal/eventlog/eventlog.go index eed209d..546282c 100644 --- a/bj_power_mes/internal/eventlog/eventlog.go +++ b/bj_power_mes/internal/eventlog/eventlog.go @@ -73,4 +73,10 @@ func (w *Writer) Query(ctx context.Context, eventType, workOrderNo string, opera return nil, 0, err } return list, total, nil +} + +// CleanupBefore 删除早于 cutoff 的操作日志(基础设置「事件日志保留天数」用),返回删除条数。 +func (w *Writer) CleanupBefore(ctx context.Context, cutoff time.Time) (int, error) { + n, err := w.client.EventLog.Delete().Where(eventlog.CreatedAtLT(cutoff)).Exec(ctx) + return int(n), err } \ No newline at end of file diff --git a/bj_power_mes/internal/handler/inspection.go b/bj_power_mes/internal/handler/inspection.go index beaf9ed..6074ab2 100644 --- a/bj_power_mes/internal/handler/inspection.go +++ b/bj_power_mes/internal/handler/inspection.go @@ -89,18 +89,6 @@ func UploadPhotoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } -// QueryBomMaterialHandler GET /quality/bom-material?keyword= 按物料编码或名称/图号检索 BOM 料 -func QueryBomMaterialHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - data, err := logic.New(svcCtx).QueryBomMaterial(r.Context(), r.URL.Query().Get("keyword")) - if err != nil { - httpx.Fail(w, 2304, err.Error()) - return - } - httpx.Ok(w, data) - } -} - // InspectionDisposalHandler POST /quality/disposal 质量检验处置(退货/返修/退换) func InspectionDisposalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { diff --git a/bj_power_mes/internal/handler/perm.go b/bj_power_mes/internal/handler/perm.go index db966b8..c9cd008 100644 --- a/bj_power_mes/internal/handler/perm.go +++ b/bj_power_mes/internal/handler/perm.go @@ -11,30 +11,29 @@ import ( // pathPermMap 请求方法+路径 → 所需按钮级权限码(块2:后端接口兜底校验)。 // 路径中的 :id 统一以 * 结尾匹配。 var pathPermMap = map[string]string{ - "POST:/api/v1/product-types": "produce.product:add", - "PUT:/api/v1/product-types": "produce.product:edit", - "DELETE:/api/v1/product-types/*": "produce.product:delete", - "POST:/api/v1/work-orders": "produce.workorder:add", - "PUT:/api/v1/work-orders": "produce.workorder:edit", - "POST:/api/v1/work-orders/status": "produce.workorder:edit", - "POST:/api/v1/work-orders/auto-schedule": "produce.workorder:dailyplan", - "DELETE:/api/v1/work-orders/*": "produce.workorder:delete", - "POST:/api/v1/daily-plans": "produce.workorder:dailyplan", - "PUT:/api/v1/bom": "produce.bom:edit", - "POST:/api/v1/bom/item/delete": "produce.bom:edit", - "POST:/api/v1/bom/import": "produce.bom:edit", - "POST:/api/v1/material-requests/generate": "produce.material:generate", + "POST:/api/v1/product-types": "produce.product:add", + "PUT:/api/v1/product-types": "produce.product:edit", + "DELETE:/api/v1/product-types/*": "produce.product:delete", + "POST:/api/v1/work-orders": "produce.workorder:add", + "PUT:/api/v1/work-orders": "produce.workorder:edit", + "POST:/api/v1/work-orders/status": "produce.workorder:edit", + "POST:/api/v1/work-orders/auto-schedule": "produce.workorder:dailyplan", + "DELETE:/api/v1/work-orders/*": "produce.workorder:delete", + "POST:/api/v1/daily-plans": "produce.workorder:dailyplan", + "POST:/api/v1/material-requests/generate": "produce.material:generate", "POST:/api/v1/material-requests/auto-outbound": "produce.material:outbound", // 数量不符处理(produce.qty 菜单下:补发/退库/调整关闭) - "POST:/api/v1/qty-reports/handle": "produce.qty:handle", - "POST:/api/v1/plc/send-process": "produce.plc:send", - "POST:/api/v1/process-flows": "produce.processflow:add", - "POST:/api/v1/process-flows/status": "produce.processflow:edit", - "DELETE:/api/v1/process-flows/*": "produce.processflow:delete", - "POST:/api/v1/process-flows/upload": "produce.processflow:upload", - "POST:/api/v1/process-steps": "produce.processflow:edit", - "POST:/api/v1/stations": "produce.station:edit", - "DELETE:/api/v1/stations/*": "produce.station:delete", + "POST:/api/v1/qty-reports/handle": "produce.qty:handle", + "POST:/api/v1/plc/send-process": "produce.plc:send", + "POST:/api/v1/process-flows": "produce.processflow:add", + "POST:/api/v1/process-flows/status": "produce.processflow:edit", + "DELETE:/api/v1/process-flows/*": "produce.processflow:delete", + "POST:/api/v1/process-flows/upload": "produce.processflow:upload", + "POST:/api/v1/process-steps": "produce.processflow:edit", + "POST:/api/v1/stations": "produce.station:edit", + "DELETE:/api/v1/stations/*": "produce.station:delete", + // 基础设置(WMS 地址/需求窗口/外推参数/日志保留) + "PUT:/api/v1/settings": "sys.settings:edit", // 过程巡检汇总生成《工序间检验记录》(巡检终端操作域) "POST:/api/v1/inspections/generate-inter-process": "sys.inspect:process", // 质量检验处置(过程检/完工检不合格处置 退货/返修/退换) @@ -44,16 +43,16 @@ var pathPermMap = map[string]string{ "POST:/api/v1/attachment/delete": "sys.attachment:manage", "POST:/api/v1/attachment/archive": "sys.attachment:manage", // 账号管理(拆分自原 sys.rbac:user;sys.account 菜单下增/改/删) - "POST:/api/v1/users": "sys.account:add", - "PUT:/api/v1/users": "sys.account:edit", - "DELETE:/api/v1/users/*": "sys.account:delete", + "POST:/api/v1/users": "sys.account:add", + "PUT:/api/v1/users": "sys.account:edit", + "DELETE:/api/v1/users/*": "sys.account:delete", // 角色管理(拆分自原 sys.rbac:role/perm;sys.role 菜单下增/改/删) - "POST:/api/v1/roles": "sys.role:add", - "PUT:/api/v1/roles": "sys.role:edit", - "DELETE:/api/v1/roles/*": "sys.role:delete", - "POST:/api/v1/permissions": "sys.role:perm", - "PUT:/api/v1/permissions": "sys.role:perm", - "DELETE:/api/v1/permissions/*": "sys.role:perm", + "POST:/api/v1/roles": "sys.role:add", + "PUT:/api/v1/roles": "sys.role:edit", + "DELETE:/api/v1/roles/*": "sys.role:delete", + "POST:/api/v1/permissions": "sys.role:perm", + "PUT:/api/v1/permissions": "sys.role:perm", + "DELETE:/api/v1/permissions/*": "sys.role:perm", } // userHasPerm 校验当前登录用户是否拥有某权限码(SUPER_ADMIN 或 * 放行)。 diff --git a/bj_power_mes/internal/handler/processcard_model.go b/bj_power_mes/internal/handler/processcard_model.go index 84aa3a5..7c4e342 100644 --- a/bj_power_mes/internal/handler/processcard_model.go +++ b/bj_power_mes/internal/handler/processcard_model.go @@ -13,7 +13,6 @@ import ( "bj_power_mes/common/httpx" "bj_power_mes/ent" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/processflow" "bj_power_mes/ent/processstep" "bj_power_mes/ent/station" @@ -267,56 +266,43 @@ func buildModelCard(ctx context.Context, svcCtx *svc.ServiceContext, productType card.Stations = append(card.Stations, ms) } - // 5) 物料清单(按 BOM 名称分组;工艺清单经 flow_material + process_flow 映射) + // 5) 物料清单(按工艺分组的工艺物料清单——唯一用料来源) if productCode != "" { - // 物料编码 → 使用该物料的工艺名列表(工艺物料清单是装配绑定的唯一依据) - flowNames := map[string][]string{} - if fms, e := client.FlowMaterial.Query().All(ctx); e == nil { - flowAll, _ := client.ProcessFlow.Query().All(ctx) - nameById := map[int]string{} - for _, f := range flowAll { - nameById[f.ID] = f.Name - } - for _, fm := range fms { - if n := nameById[fm.FlowId]; n != "" { - flowNames[fm.MaterialCode] = append(flowNames[fm.MaterialCode], n) - } - } + // 物料分组:按工艺分组的工艺物料清单(BOM 已删除,工艺物料清单是唯一用料来源) + flowAll, _ := client.ProcessFlow.Query().All(ctx) + nameById := map[int]string{} + for _, f := range flowAll { + nameById[f.ID] = f.Name } - items, _ := client.BomItem.Query(). - Where(bomitem.ProductCode(productCode)). - Order(ent.Asc(bomitem.FieldBomName), ent.Asc(bomitem.FieldMaterialCode)).All(ctx) - groupIdx := map[string]int{} - for _, it := range items { - name := it.BomName - if name == "" { - name = "默认" + if fms, e := client.FlowMaterial.Query().All(ctx); e == nil { + groupIdx := map[int]int{} + for _, fm := range fms { + name := nameById[fm.FlowId] + if name == "" { + name = "未命名工艺" + } + gi, ok := groupIdx[fm.FlowId] + if !ok { + card.BomGroups = append(card.BomGroups, modelBomGroup{BomName: name}) + gi = len(card.BomGroups) - 1 + groupIdx[fm.FlowId] = gi + } + card.BomGroups[gi].Items = append(card.BomGroups[gi].Items, modelBomItem{ + MaterialCode: fm.MaterialCode, + MaterialName: fm.MaterialName, + Spec: fm.Spec, + Unit: fm.Unit, + ManageMode: manageModeCN(fm.ManageMode), + FlowNames: name, + UnitQty: f2s(fm.UnitQty), + LossRate: f2s(fm.LossRate), + RequiredQty: "-", + }) } - gi, ok := groupIdx[name] - if !ok { - card.BomGroups = append(card.BomGroups, modelBomGroup{BomName: name}) - gi = len(card.BomGroups) - 1 - groupIdx[name] = gi - } - fnames := "-" - if ns := flowNames[it.MaterialCode]; len(ns) > 0 { - fnames = strings.Join(ns, "、") - } - card.BomGroups[gi].Items = append(card.BomGroups[gi].Items, modelBomItem{ - MaterialCode: it.MaterialCode, - MaterialName: it.MaterialName, - Spec: it.Spec, - Unit: it.Unit, - ManageMode: manageModeCN(it.ManageMode), - FlowNames: fnames, - UnitQty: f2s(it.UnitQty), - LossRate: f2s(it.LossRate), - RequiredQty: f2s(it.RequiredQty), - }) } } - card.Summary = fmt.Sprintf("共 %d 个工位、%d 项检验卡项、%d 份物料清单", + card.Summary = fmt.Sprintf("共 %d 个工位、%d 项检验卡项、%d 个工艺物料分组", card.StationCount, len(card.CheckItems), len(card.BomGroups)) return card, nil } diff --git a/bj_power_mes/internal/handler/production/bind.go b/bj_power_mes/internal/handler/production/bind.go index eb04a89..f785e55 100644 --- a/bj_power_mes/internal/handler/production/bind.go +++ b/bj_power_mes/internal/handler/production/bind.go @@ -106,3 +106,9 @@ func BindPanelInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.Ok(w, data) } } + +// BindPanelAdminHandler GET /api/v1/workpiece/bind-panel?sn=&flowId= +// MES 管理后台「虚拟工位作业」页拉取绑定面板(与终端同逻辑,JWT 保护) +func BindPanelAdminHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return BindPanelInternalHandler(svcCtx) +} diff --git a/bj_power_mes/internal/handler/production/bom_material.go b/bj_power_mes/internal/handler/production/bom_material.go deleted file mode 100644 index bed7831..0000000 --- a/bj_power_mes/internal/handler/production/bom_material.go +++ /dev/null @@ -1,341 +0,0 @@ -package production - -import ( - "net/http" - "strconv" - - "bj_power_mes/common/httpx" - "bj_power_mes/internal/logic" - "bj_power_mes/internal/svc" - - "github.com/xuri/excelize/v2" -) - -// ---------- BOM ---------- - -// ImportBomHandler POST /bom/import 产品物料清单(BOM) Excel 导入。 -// 模板列:产品编号|物料清单名称|物料编码|名称|规格|单位|单台用量|损耗率|相关标准|备注(原「装配工位」列忽略) -func ImportBomHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if err := r.ParseMultipartForm(svcCtx.Config.Upload.MaxMB << 20); err != nil { - httpx.BadRequest(w, "上传文件过大或格式错误") - return - } - f, _, err := r.FormFile("file") - if err != nil { - httpx.BadRequest(w, "请选择 Excel 文件") - return - } - defer f.Close() - xlsx, err := excelize.OpenReader(f) - if err != nil { - httpx.Fail(w, 3109, "Excel 解析失败:"+err.Error()) - return - } - sheet := xlsx.GetSheetName(0) - rows, err := xlsx.GetRows(sheet) - if err != nil { - httpx.Fail(w, 3110, "读取 Excel 失败:"+err.Error()) - return - } - // 按 (产品编号, 物料清单名称) 分组,每组一次 SaveBom(覆盖式 upsert) - type key struct{ pc, bn string } - groups := map[key][]logic.BomItemReq{} - order := []key{} - count := 0 - for i, row := range rows { - if i == 0 { - continue // 跳过表头 - } - if len(row) < 3 { - continue - } - productCode := trimCell(row, 0) - bomName := trimCell(row, 1) - materialCode := trimCell(row, 2) - if productCode == "" || materialCode == "" { - continue - } - if bomName == "" { - bomName = "默认" - } - item := logic.BomItemReq{ - ProductCode: productCode, - BomName: bomName, - MaterialCode: materialCode, - MaterialName: trimCell(row, 3), - Spec: trimCell(row, 4), - Unit: trimCell(row, 5), - ManageMode: "2", - UnitQty: parseFloat(trimCell(row, 6)), - LossRate: parseFloat(trimCell(row, 7)), - RelatedStandard: trimCell(row, 9), - } - k := key{productCode, bomName} - if _, ok := groups[k]; !ok { - order = append(order, k) - } - groups[k] = append(groups[k], item) - count++ - } - if count == 0 { - httpx.Fail(w, 3111, "未解析到有效物料清单行(至少需产品编号与图号)") - return - } - for _, k := range order { - if err := logic.New(svcCtx).SaveBom(r.Context(), k.pc, k.bn, groups[k], operator(r, "")); err != nil { - httpx.Fail(w, 3112, "导入失败:"+err.Error()) - return - } - } - httpx.OkMessage(w, "导入成功", map[string]any{"count": count}) - } -} - -func trimCell(row []string, i int) string { - if i >= len(row) { - return "" - } - return strconvTrimSpace(row[i]) -} - -func strconvTrimSpace(s string) string { - out := []rune{} - for _, c := range s { - if c == ' ' || c == '\t' || c == '\n' || c == '\r' { - continue - } - out = append(out, c) - } - return string(out) -} - -func parseFloat(s string) float64 { - if s == "" { - return 0 - } - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0 - } - return v -} - -func SaveBomHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - ProductCode string `json:"productCode"` - BomName string `json:"bomName"` // 同型号多份 BOM 并存时的名称(空=「默认」) - Items []logic.BomItemReq `json:"items"` - } - if err := httpx.ParseJSON(r, &req); err != nil { - httpx.BadRequest(w, "请求体解析失败") - return - } - if req.ProductCode == "" { - httpx.BadRequest(w, "请选择产品编码") - return - } - if err := logic.New(svcCtx).SaveBom(r.Context(), req.ProductCode, req.BomName, req.Items, operator(r, "")); err != nil { - httpx.Fail(w, 3101, err.Error()) - return - } - httpx.OkMessage(w, "保存成功", nil) - } -} - -func ListBomHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - data, err := logic.New(svcCtx).ListBom(r.Context(), r.URL.Query().Get("productCode"), r.URL.Query().Get("bomName")) - if err != nil { - httpx.Fail(w, 3102, err.Error()) - return - } - httpx.Ok(w, data) - } -} - -// ListBomNamesHandler GET /bom/names?productCode= — 型号下并存的 BOM 名称列表(工单建单选 BOM 用) -func ListBomNamesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - data, err := logic.New(svcCtx).ListBomNames(r.Context(), r.URL.Query().Get("productCode")) - if err != nil { - httpx.Fail(w, 3107, err.Error()) - return - } - httpx.Ok(w, data) - } -} - -// DeleteBomItemHandler POST /bom/item/delete {id} — 移除 BOM 中一条物料(按行主键) -func DeleteBomItemHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - Id int `json:"id"` - } - if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 { - httpx.BadRequest(w, "缺少 id") - return - } - if err := logic.New(svcCtx).DeleteBomItem(r.Context(), req.Id, operator(r, "")); err != nil { - httpx.Fail(w, 3108, err.Error()) - return - } - httpx.OkMessage(w, "已移除", nil) - } -} - -// ---------- 备料单 ---------- - -// GenerateMaterialHandler 按日排产生成备料单(生成前校验 BOM 物料在 WMS 档案存在) -func GenerateMaterialHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - PlanDate string `json:"planDate"` - } - if err := httpx.ParseJSON(r, &req); err != nil { - httpx.BadRequest(w, "请求体解析失败") - return - } - count, missing, err := logic.New(svcCtx).GenerateMaterialRequest(r.Context(), req.PlanDate, operator(r, "")) - if err != nil { - httpx.Fail(w, 3103, err.Error()) - return - } - if len(missing) > 0 { - // 有物料在 WMS 档案不存在:不生成,把缺失列表返回给前端弹窗 - httpx.Ok(w, map[string]any{"count": 0, "missing": missing, "blocked": true}) - return - } - httpx.OkMessage(w, "生成完成", map[string]any{"count": count, "blocked": false}) - } -} - -// AutoOutboundHandler POST /material-requests/auto-outbound 备料自动出库(一键补出)。 -// 日常由「生成备料单」自动触发(客户第1条:平时无需操作);库存补齐后库管可在此一键补出。 -func AutoOutboundHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - PlanDate string `json:"planDate"` - OrderNo string `json:"orderNo"` - } - if err := httpx.ParseJSON(r, &req); err != nil { - httpx.BadRequest(w, "请求体解析失败") - return - } - if req.PlanDate == "" && req.OrderNo == "" { - httpx.BadRequest(w, "planDate 与 orderNo 至少填一个") - return - } - done, short := logic.New(svcCtx).AutoOutboundRequests(r.Context(), req.PlanDate, req.OrderNo, operator(r, "")) - httpx.OkMessage(w, "自动出库完成", map[string]any{"done": done, "short": short}) - } -} - -func ListMaterialRequestsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - q := r.URL.Query() - data, err := logic.New(svcCtx).ListMaterialRequests(r.Context(), logic.MaterialRequestQuery{ - OrderNo: q.Get("orderNo"), - PlanDate: q.Get("planDate"), - Status: q.Get("status"), - MaterialCode: q.Get("materialCode"), - MaterialName: q.Get("materialName"), - TargetDock: q.Get("targetDock"), - StationNo: q.Get("stationNo"), - Source: q.Get("source"), - RequestNo: q.Get("requestNo"), - }) - if err != nil { - httpx.Fail(w, 3104, err.Error()) - return - } - httpx.Ok(w, data) - } -} - -// ListMaterialRequestsInternalHandler 内部接口:供 WMS 拉取备料单(含 target_dock),X-API-TOKEN 保护。 -// WMS AGV 配送页据此展示待发料行,仓管确认 target_dock 后调用 WMS AGV 下发。 -func ListMaterialRequestsInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - q := r.URL.Query() - data, err := logic.New(svcCtx).ListMaterialRequests(r.Context(), logic.MaterialRequestQuery{ - OrderNo: q.Get("orderNo"), - PlanDate: q.Get("planDate"), - Status: q.Get("status"), - StationNo: q.Get("stationNo"), - }) - if err != nil { - httpx.Fail(w, 3105, err.Error()) - return - } - httpx.Ok(w, data) - } -} - -// MarkMaterialRequestStatusInternalHandler 内部接口:WMS 下发 AGV 后回写备料单状态(DELIVERING/DONE)。 -// 供 WMS AGV 任务推进状态时联动 MES 备料单,保持一致。 -func MarkMaterialRequestStatusInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - RequestNo string `json:"requestNo"` - Status string `json:"status"` - } - if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { - httpx.BadRequest(w, "请求体缺失") - return - } - if req.Status != "DELIVERING" && req.Status != "DONE" { - httpx.Fail(w, 3106, "非法状态") - return - } - if err := logic.New(svcCtx).SetMaterialRequestStatus(r.Context(), req.RequestNo, req.Status); err != nil { - httpx.Fail(w, 3106, err.Error()) - return - } - httpx.Ok(w, nil) - } -} - -// ---------- 接驳台 / 接料确认 ---------- -// 接驳台查询/维护接口见 dock.go(真源已迁 MES 本地 dock 表)。 - -// ReceiveMaterialRequestHandler POST /material-requests/receive 接料确认(MES 备料页人工点「已接料」)。 -// qty 可空(≤0 表示确认本批全部剩余);累加 receivedQty(已接料),上限为已发出量。 -func ReceiveMaterialRequestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - RequestNo string `json:"requestNo"` - Qty int `json:"qty"` - } - if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { - httpx.BadRequest(w, "缺少备料单号") - return - } - if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil { - httpx.Fail(w, 3114, err.Error()) - return - } - httpx.OkMessage(w, "已接料", nil) - } -} - -// StationReceiveMaterialInternalHandler POST /api/internal/station/receive-material 接料确认内部接口。 -// 供工位终端代理调用(工人扫码接料主入口),X-API-TOKEN 保护。逻辑同 ReceiveMaterialRequestHandler。 -func StationReceiveMaterialInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - RequestNo string `json:"requestNo"` - Qty int `json:"qty"` - } - if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { - httpx.BadRequest(w, "缺少备料单号") - return - } - if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil { - httpx.Fail(w, 3114, err.Error()) - return - } - httpx.Ok(w, nil) - } -} diff --git a/bj_power_mes/internal/handler/production/material.go b/bj_power_mes/internal/handler/production/material.go index 0d7d2e2..b10c1d2 100644 --- a/bj_power_mes/internal/handler/production/material.go +++ b/bj_power_mes/internal/handler/production/material.go @@ -1,10 +1,11 @@ -package production +package production import ( "net/http" "strconv" "bj_power_mes/common/httpx" + "bj_power_mes/internal/logic" "bj_power_mes/internal/svc" ) @@ -31,3 +32,158 @@ func ListMaterialsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { httpx.Ok(w, list) } } + +// ---------- 备料单 ---------- + +// GenerateMaterialHandler 按日排产生成备料单(生成前校验 BOM 物料在 WMS 档案存在) +func GenerateMaterialHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + PlanDate string `json:"planDate"` + } + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + count, missing, err := logic.New(svcCtx).GenerateMaterialRequest(r.Context(), req.PlanDate, operator(r, "")) + if err != nil { + httpx.Fail(w, 3103, err.Error()) + return + } + if len(missing) > 0 { + // 有物料在 WMS 档案不存在:不生成,把缺失列表返回给前端弹窗 + httpx.Ok(w, map[string]any{"count": 0, "missing": missing, "blocked": true}) + return + } + httpx.OkMessage(w, "生成完成", map[string]any{"count": count, "blocked": false}) + } +} + +// AutoOutboundHandler POST /material-requests/auto-outbound 备料自动出库(一键补出)。 +// 日常由「生成备料单」自动触发(客户第1条:平时无需操作);库存补齐后库管可在此一键补出。 +func AutoOutboundHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + PlanDate string `json:"planDate"` + OrderNo string `json:"orderNo"` + } + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + if req.PlanDate == "" && req.OrderNo == "" { + httpx.BadRequest(w, "planDate 与 orderNo 至少填一个") + return + } + done, short := logic.New(svcCtx).AutoOutboundRequests(r.Context(), req.PlanDate, req.OrderNo, operator(r, "")) + httpx.OkMessage(w, "自动出库完成", map[string]any{"done": done, "short": short}) + } +} + +func ListMaterialRequestsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + data, err := logic.New(svcCtx).ListMaterialRequests(r.Context(), logic.MaterialRequestQuery{ + OrderNo: q.Get("orderNo"), + PlanDate: q.Get("planDate"), + Status: q.Get("status"), + MaterialCode: q.Get("materialCode"), + MaterialName: q.Get("materialName"), + TargetDock: q.Get("targetDock"), + StationNo: q.Get("stationNo"), + Source: q.Get("source"), + RequestNo: q.Get("requestNo"), + }) + if err != nil { + httpx.Fail(w, 3104, err.Error()) + return + } + httpx.Ok(w, data) + } +} + +// ListMaterialRequestsInternalHandler 内部接口:供 WMS 拉取备料单(含 target_dock),X-API-TOKEN 保护。 +// WMS AGV 配送页据此展示待发料行,仓管确认 target_dock 后调用 WMS AGV 下发。 +func ListMaterialRequestsInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + data, err := logic.New(svcCtx).ListMaterialRequests(r.Context(), logic.MaterialRequestQuery{ + OrderNo: q.Get("orderNo"), + PlanDate: q.Get("planDate"), + Status: q.Get("status"), + StationNo: q.Get("stationNo"), + }) + if err != nil { + httpx.Fail(w, 3105, err.Error()) + return + } + httpx.Ok(w, data) + } +} + +// MarkMaterialRequestStatusInternalHandler 内部接口:WMS 下发 AGV 后回写备料单状态(DELIVERING/DONE)。 +// 供 WMS AGV 任务推进状态时联动 MES 备料单,保持一致。 +func MarkMaterialRequestStatusInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + RequestNo string `json:"requestNo"` + Status string `json:"status"` + } + if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { + httpx.BadRequest(w, "请求体缺失") + return + } + if req.Status != "DELIVERING" && req.Status != "DONE" { + httpx.Fail(w, 3106, "非法状态") + return + } + if err := logic.New(svcCtx).SetMaterialRequestStatus(r.Context(), req.RequestNo, req.Status); err != nil { + httpx.Fail(w, 3106, err.Error()) + return + } + httpx.Ok(w, nil) + } +} + +// ---------- 接驳台 / 接料确认 ---------- +// 接驳台查询/维护接口见 dock.go(真源已迁 MES 本地 dock 表)。 + +// ReceiveMaterialRequestHandler POST /material-requests/receive 接料确认(MES 备料页人工点「已接料」)。 +// qty 可空(≤0 表示确认本批全部剩余);累加 receivedQty(已接料),上限为已发出量。 +func ReceiveMaterialRequestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + RequestNo string `json:"requestNo"` + Qty int `json:"qty"` + } + if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { + httpx.BadRequest(w, "缺少备料单号") + return + } + if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil { + httpx.Fail(w, 3114, err.Error()) + return + } + httpx.OkMessage(w, "已接料", nil) + } +} + +// StationReceiveMaterialInternalHandler POST /api/internal/station/receive-material 接料确认内部接口。 +// 供工位终端代理调用(工人扫码接料主入口),X-API-TOKEN 保护。逻辑同 ReceiveMaterialRequestHandler。 +func StationReceiveMaterialInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + RequestNo string `json:"requestNo"` + Qty int `json:"qty"` + } + if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" { + httpx.BadRequest(w, "缺少备料单号") + return + } + if err := logic.New(svcCtx).ReceiveMaterialRequest(r.Context(), req.RequestNo, req.Qty, operator(r, "")); err != nil { + httpx.Fail(w, 3114, err.Error()) + return + } + httpx.Ok(w, nil) + } +} diff --git a/bj_power_mes/internal/handler/production/production.go b/bj_power_mes/internal/handler/production/production.go index 5e8cbd0..1eb17f0 100644 --- a/bj_power_mes/internal/handler/production/production.go +++ b/bj_power_mes/internal/handler/production/production.go @@ -154,11 +154,11 @@ func DoneWorkpieceInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } -// BomInternalHandler BOM 物料清单(工位终端上线位「领料确认」按物料清单展示应领料)。 -// GET ?productCode=&bomName=,返回 []*ent.BomItem。 -func BomInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { +// OrderUsageInternalHandler 工单单台用料(工位终端上线位「领料确认」按工单工艺组合的物料清单展示应领料)。 +// GET ?orderNo=,返回 []logic.UsageRow。BOM 已删除:用料唯一来源 = 工单工艺组合×工艺物料清单。 +func OrderUsageInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - data, err := logic.New(svcCtx).ListBom(r.Context(), r.URL.Query().Get("productCode"), r.URL.Query().Get("bomName")) + data, err := logic.New(svcCtx).GetOrderUsage(r.Context(), r.URL.Query().Get("orderNo")) if err != nil { httpx.Fail(w, 2009, err.Error()) return @@ -167,6 +167,11 @@ func BomInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } +// OrderUsageHandler GET /order-usage?orderNo= 工单单台用料(管理后台工单详情只读汇总展示) +func OrderUsageHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return OrderUsageInternalHandler(svcCtx) +} + // ---------- 看板内部接口 ---------- // DashboardSnapshotInternalHandler 看板全量快照。 diff --git a/bj_power_mes/internal/handler/routes_production.go b/bj_power_mes/internal/handler/routes_production.go index cd1e317..31b6966 100644 --- a/bj_power_mes/internal/handler/routes_production.go +++ b/bj_power_mes/internal/handler/routes_production.go @@ -95,7 +95,7 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext Method: http.MethodPost, Path: "/api/internal/workpiece/done", Handler: internal(production.DoneWorkpieceInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ - Method: http.MethodGet, Path: "/api/internal/bom", Handler: internal(production.BomInternalHandler(serverCtx)), + Method: http.MethodGet, Path: "/api/internal/order-usage", Handler: internal(production.OrderUsageInternalHandler(serverCtx)), }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/material-requests", Handler: internal(production.ListMaterialRequestsInternalHandler(serverCtx)), @@ -177,16 +177,12 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext {Method: http.MethodPost, Path: "/daily-plans/:id/status", Handler: production.DailyPlanStatusHandler(serverCtx)}, {Method: http.MethodGet, Path: "/daily-plans/suggest-docks", Handler: production.SuggestedDockCodesHandler(serverCtx)}, - {Method: http.MethodPut, Path: "/bom", Handler: production.SaveBomHandler(serverCtx)}, - {Method: http.MethodGet, Path: "/bom", Handler: production.ListBomHandler(serverCtx)}, - {Method: http.MethodGet, Path: "/bom/names", Handler: production.ListBomNamesHandler(serverCtx)}, - {Method: http.MethodPost, Path: "/bom/item/delete", Handler: production.DeleteBomItemHandler(serverCtx)}, - {Method: http.MethodPost, Path: "/bom/import", Handler: production.ImportBomHandler(serverCtx)}, - {Method: http.MethodPost, Path: "/material-requests/generate", Handler: production.GenerateMaterialHandler(serverCtx)}, {Method: http.MethodGet, Path: "/material-requests", Handler: production.ListMaterialRequestsHandler(serverCtx)}, // 物料档案(代理 WMS /api/internal/materials,WMS 是物料主数据源;WMS 不可达返回空列表) {Method: http.MethodGet, Path: "/materials", Handler: production.ListMaterialsHandler(serverCtx)}, + // 工单单台用料(BOM 已删除:工单详情页只读汇总 = 工单工艺组合×工艺物料清单) + {Method: http.MethodGet, Path: "/order-usage", Handler: production.OrderUsageHandler(serverCtx)}, {Method: http.MethodPost, Path: "/material-requests/receive", Handler: production.ReceiveMaterialRequestHandler(serverCtx)}, {Method: http.MethodPost, Path: "/material-requests/auto-outbound", Handler: production.AutoOutboundHandler(serverCtx)}, // 配送进度(只读聚合:WMS 台账四段量 + MES 已接料 → 在途/线边) @@ -263,11 +259,21 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext {Method: http.MethodPost, Path: "/inspections/upload", Handler: UploadPhotoHandler(serverCtx)}, // P0-4:一键生成《工序间检验记录》(汇总该工单 PROCESS 类巡检,按步骤维度) // ---------- MES 质量检验(过程检/完工检,来料检在 WMS 已做仍落本表) ---------- - {Method: http.MethodGet, Path: "/quality/bom-material", Handler: QueryBomMaterialHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/quality/disposal", Handler: InspectionDisposalHandler(serverCtx)}, {Method: http.MethodGet, Path: "/quality/unqualified-report", Handler: UnqualifiedReportHandler(serverCtx)}, {Method: http.MethodPost, Path: "/inspections/generate-inter-process", Handler: GenerateInterProcessInspectionHandler(serverCtx)}, + // ---------- 虚拟工位作业(管理后台,与终端同逻辑;虚拟工位无实体屏,手机/电脑登录操作) ---------- + {Method: http.MethodGet, Path: "/station/task", Handler: StationTaskAdminHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/station/report", Handler: StationReportAdminHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/workpiece/bind-panel", Handler: production.BindPanelAdminHandler(serverCtx)}, + + // ---------- 系统基础设置(系统管理员;保存即生效无需重启) ---------- + {Method: http.MethodGet, Path: "/settings", Handler: SettingsHandler(serverCtx)}, + {Method: http.MethodPut, Path: "/settings", Handler: SaveSettingsHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/settings/wms-test", Handler: WmsTestHandler(serverCtx)}, + // ---------- 应急呼叫(D3,MES 前端亦可发起) ---------- {Method: http.MethodPost, Path: "/alert/emergency", Handler: EmergencyCallHandler(serverCtx)}, diff --git a/bj_power_mes/internal/handler/settings.go b/bj_power_mes/internal/handler/settings.go new file mode 100644 index 0000000..4479422 --- /dev/null +++ b/bj_power_mes/internal/handler/settings.go @@ -0,0 +1,76 @@ +package handler + +import ( + "context" + "net/http" + "time" + + "bj_power_mes/common/httpx" + "bj_power_mes/internal/logic" + "bj_power_mes/internal/svc" + + "github.com/zeromicro/go-zero/core/logx" +) + +// SettingsHandler GET /api/v1/settings 基础设置 + 本机基础信息(只读) +func SettingsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + data, err := logic.New(svcCtx).GetSettings(r.Context()) + if err != nil { + httpx.Fail(w, 2501, err.Error()) + return + } + httpx.Ok(w, data) + } +} + +// SaveSettingsHandler PUT /api/v1/settings 保存基础设置(WMS 地址热切换;sys.settings:edit 权限) +func SaveSettingsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req logic.SettingsReq + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + if err := logic.New(svcCtx).SaveSettings(r.Context(), req, operator(r, "")); err != nil { + httpx.Fail(w, 2502, err.Error()) + return + } + httpx.OkMessage(w, "已保存并生效", nil) + } +} + +// WmsTestHandler GET /api/v1/settings/wms-test?url= 测试 WMS 连通性(url 为空测当前生效地址) +func WmsTestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + msg, err := logic.New(svcCtx).TestWms(r.Context(), r.URL.Query().Get("url")) + if err != nil { + httpx.Fail(w, 2503, err.Error()) + return + } + httpx.OkMessage(w, msg, nil) + } +} + +// StartEventLogRetention 事件日志保留期清理:每小时检查一次(保留天数在「基础设置」页 +// 配置 eventlog.retention.days,0=不清理),删除超过保留期的操作日志。 +func StartEventLogRetention(ctx *svc.ServiceContext) { + go func() { + ticker := time.NewTicker(time.Hour) + defer ticker.Stop() + for range ticker.C { + days := logic.New(ctx).CfgInt(context.Background(), logic.CfgLogRetention, 0) + if days <= 0 { + continue + } + n, err := ctx.EventLog.CleanupBefore(context.Background(), time.Now().AddDate(0, 0, -days)) + if err != nil { + logx.Errorf("事件日志清理失败: %v", err) + continue + } + if n > 0 { + logx.Infof("事件日志保留 %d 天:已清理 %d 条过期记录", days, n) + } + } + }() +} diff --git a/bj_power_mes/internal/handler/station.go b/bj_power_mes/internal/handler/station.go index e3506ec..1563bec 100644 --- a/bj_power_mes/internal/handler/station.go +++ b/bj_power_mes/internal/handler/station.go @@ -105,7 +105,8 @@ func StationChangePasswordInternalHandler(svcCtx *svc.ServiceContext) http.Handl func StationTaskInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { stationNo := atoiDefault(r.URL.Query().Get("stationNo"), 0) - if stationNo <= 0 { + // 0=上线位为合法虚拟工位,仅负数视为未配置 + if stationNo < 0 { httpx.BadRequest(w, "缺少 stationNo 参数") return } @@ -118,6 +119,16 @@ func StationTaskInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } +// StationTaskAdminHandler GET /station/task?stationNo= 管理后台「虚拟工位作业」页拉取任务(与终端同逻辑) +func StationTaskAdminHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return StationTaskInternalHandler(svcCtx) +} + +// StationReportAdminHandler POST /station/report 管理后台「虚拟工位作业」报工(与终端同逻辑,operator=登录账号) +func StationReportAdminHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return StationReportInternalHandler(svcCtx) +} + // StationReportInternalHandler 工位终端工艺报工(写工位实绩 + 步骤考核) func StationReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { diff --git a/bj_power_mes/internal/logic/bom.go b/bj_power_mes/internal/logic/bom.go deleted file mode 100644 index a2bc80d..0000000 --- a/bj_power_mes/internal/logic/bom.go +++ /dev/null @@ -1,142 +0,0 @@ -package logic - -import ( - "context" - "errors" - "fmt" - - "bj_power_mes/ent" - "bj_power_mes/ent/bomitem" - "bj_power_mes/ent/workorder" -) - -// 默认BOMName 同一型号多份 BOM 并存时的缺省名称(历史数据/未指定时统一回填此值) -const DefaultBOMName = "默认" - -type BomItemReq struct { - ProductCode string `json:"productCode"` - BomName string `json:"bomName"` - MaterialCode string `json:"materialCode"` - MaterialName string `json:"materialName"` - Spec string `json:"spec"` - Unit string `json:"unit"` - ManageMode string `json:"manageMode"` - RelatedStandard string `json:"relatedStandard"` // 相关标准(检验细则) - UnitQty float64 `json:"unitQty"` - LossRate float64 `json:"lossRate"` - RequiredQty float64 `json:"requiredQty"` - SerialSns []string `json:"serialSns"` -} - -// bomNameOrDefault 空 BOM 名回退为「默认」(兼容旧前端/旧数据) -func bomNameOrDefault(name string) string { - if name == "" { - return DefaultBOMName - } - return name -} - -// SaveBom 保存产品 BOM(覆盖式 upsert:唯一键 = 产品编码+BOM名称+物料编码)。 -// 同一产品型号可并存多份 BOM(不同厂家供货/含半成品等不同料单结构),按 bomName 区分, -// 工单建单时选定一份;备料/装机绑定均按工单锁定的 bomName 计算。 -func (s *Service) SaveBom(ctx context.Context, productCode, bomName string, items []BomItemReq, operator string) error { - bomName = bomNameOrDefault(bomName) - for _, it := range items { - if it.ManageMode == "" { - it.ManageMode = "2" - } - exist, err := s.ctx.EntClient.BomItem.Query(). - Where(bomitem.ProductCode(productCode), bomitem.BomName(bomName), bomitem.MaterialCode(it.MaterialCode)).First(ctx) - if err == nil && exist != nil { - u := s.ctx.EntClient.BomItem.UpdateOneID(exist.ID). - SetMaterialName(it.MaterialName).SetSpec(it.Spec).SetUnit(it.Unit). - SetManageMode(it.ManageMode).SetUnitQty(it.UnitQty).SetLossRate(it.LossRate). - SetRelatedStandard(it.RelatedStandard) - if len(it.SerialSns) > 0 { - u.SetSerialSns(it.SerialSns) - } - if _, err := u.Save(ctx); err != nil { - return fmt.Errorf("更新BOM物料 %s 失败: %w", it.MaterialCode, err) - } - } else { - b := s.ctx.EntClient.BomItem.Create(). - SetProductCode(productCode).SetBomName(bomName).SetMaterialCode(it.MaterialCode). - SetMaterialName(it.MaterialName).SetSpec(it.Spec).SetUnit(it.Unit). - SetManageMode(it.ManageMode). - SetUnitQty(it.UnitQty).SetLossRate(it.LossRate). - SetRelatedStandard(it.RelatedStandard) - if len(it.SerialSns) > 0 { - b.SetSerialSns(it.SerialSns) - } - if _, err := b.Save(ctx); err != nil { - return fmt.Errorf("保存BOM物料 %s 失败: %w", it.MaterialCode, err) - } - } - } - s.ctx.EventLog.Write(ctx, "bom.save", "", operator, "product_bom", productCode, "保存产品BOM", map[string]any{"bomName": bomName, "count": len(items)}) - return nil -} - -// DeleteBomItem 移除 BOM 中的一条物料(按行主键)。 -// 安全校验:该 (产品编码+BOM名称) 下任一工单已生成备料单时禁止移除,避免已锁定料单被改动。 -func (s *Service) DeleteBomItem(ctx context.Context, id int, operator string) error { - item, err := s.ctx.EntClient.BomItem.Get(ctx, id) - if err != nil { - return errors.New("BOM 物料不存在") - } - used, err := s.ctx.EntClient.WorkOrder.Query(). - Where(workorder.ProductCode(item.ProductCode)).Exist(ctx) - if err == nil && used { - // 该型号已有工单,谨慎起见禁止直接移除 - return fmt.Errorf("该物料清单已被「%s」型号的工单选用,移除物料会影响备料/追溯,请先评估相关工单", item.ProductCode) - } - if err := s.ctx.EntClient.BomItem.DeleteOneID(id).Exec(ctx); err != nil { - return err - } - s.ctx.EventLog.Write(ctx, "bom.item.delete", "", operator, "product_bom", item.ProductCode, - "移除BOM物料 "+item.MaterialCode, map[string]any{"bomName": item.BomName}) - return nil -} - -// ListBom 查询 BOM(可按产品编码 + BOM 名称过滤;bomName 传 "ALL" 或空且指定了产品时返回全部) -func (s *Service) ListBom(ctx context.Context, productCode, bomName string) ([]*ent.BomItem, error) { - q := s.ctx.EntClient.BomItem.Query() - if productCode != "" { - q = q.Where(bomitem.ProductCode(productCode)) - } - if bomName != "" && bomName != "ALL" { - q = q.Where(bomitem.BomName(bomName)) - } - return q.Order(ent.Asc(bomitem.FieldProductCode), ent.Asc(bomitem.FieldBomName), ent.Asc(bomitem.FieldID)).All(ctx) -} - -// BomNameInfo 型号下的一份 BOM 概要(名称 + 物料数) -type BomNameInfo struct { - BomName string `json:"bomName"` - ItemCount int `json:"itemCount"` -} - -// ListBomNames 列出某产品型号下并存的所有 BOM 名称(工单建单选 BOM 下拉数据源) -func (s *Service) ListBomNames(ctx context.Context, productCode string) ([]*BomNameInfo, error) { - if productCode == "" { - return []*BomNameInfo{}, nil - } - items, err := s.ctx.EntClient.BomItem.Query(). - Where(bomitem.ProductCode(productCode)).All(ctx) - if err != nil { - return nil, err - } - order := []string{} - count := map[string]int{} - for _, it := range items { - if _, ok := count[it.BomName]; !ok { - order = append(order, it.BomName) - } - count[it.BomName]++ - } - out := make([]*BomNameInfo, 0, len(order)) - for _, name := range order { - out = append(out, &BomNameInfo{BomName: name, ItemCount: count[name]}) - } - return out, nil -} diff --git a/bj_power_mes/internal/logic/bom_expand.go b/bj_power_mes/internal/logic/bom_expand.go deleted file mode 100644 index 196fe63..0000000 --- a/bj_power_mes/internal/logic/bom_expand.go +++ /dev/null @@ -1,176 +0,0 @@ -package logic - -import ( - "context" - - "bj_power_mes/ent/bomitem" -) - -// ============================================================ -// BOM 展开统一核心(R1 工程债,2026-09-19) -// ============================================================ -// -// 背景:备料算料(expandBomToLeaf)与追溯物料组成(expandBindBom)原先各自实现了一套 -// 递归展开,两套的"是否继续下钻"判定不同—— -// - 备料:子项在 WMS 的品类为成品(3) 才继续展开; -// - 追溯:本地存在该编码的下级物料清单才继续展开。 -// 结果是同一产品在"备料料单"和"追溯物料组成"里可能呈现不同结构,追溯断链。 -// -// 此处抽出唯一递归骨架,两处共用同一份实现:深度上限、防环、用量倍率相乘、日志口径 -// 完全一致;下钻判定与 BOM 名称策略由调用方以 resolver/参数注入,保证业务口径不变。 - -// bomNode BOM 展开的中间态树节点(备料拍平为叶子、追溯直接展示层级)。 -type bomNode struct { - MaterialCode string - MaterialName string - Spec string - Unit string - ManageMode string - UnitQty float64 // 已按路径倍率折算的单台用量 - LossRate float64 - Level int // 1=顶层物料,2+=下级 - Children []bomNode -} - -// bomMaxDepth 展开深度上限(防配置错误导致的无界递归)。 -const bomMaxDepth = 10 - -// bomCompositeResolver 批量判定本层哪些子项属于"组合件"(需继续下钻展开其自身清单)。 -// 每层只调用一次,避免逐条查 WMS/库造成 N+1。 -type bomCompositeResolver func(ctx context.Context, productCode string, codes []string) map[string]bool - -// expandBomTree 统一递归展开核心。 -// - productCode: 当前层产品/组合件编码; -// - bomName: 物料清单名称("" 由 ListBom 决定不过滤,具体策略由调用方传入); -// - mult: 父级累计倍率; -// - path: 当前展开路径(防环,同路径重复编码视为配置错误并记日志)。 -func (s *Service) expandBomTree(ctx context.Context, productCode, bomName string, mult float64, depth int, - path map[string]bool, resolve bomCompositeResolver) []bomNode { - if depth > bomMaxDepth || productCode == "" { - return nil - } - bom, err := s.ListBom(ctx, productCode, bomName) - if err != nil || len(bom) == 0 { - return nil - } - codes := make([]string, 0, len(bom)) - for _, b := range bom { - if b.MaterialCode != "" { - codes = append(codes, b.MaterialCode) - } - } - var composite map[string]bool - if resolve != nil { - composite = resolve(ctx, productCode, codes) - } - - out := make([]bomNode, 0, len(bom)) - for _, b := range bom { - if b.MaterialCode == "" { - continue - } - if path[b.MaterialCode] { - s.ctx.EventLog.Write(ctx, "bom.expand.cycle", "", "", "product_bom", productCode, - "产品物料清单存在循环引用,已跳过", - map[string]any{"materialCode": b.MaterialCode, "depth": depth}) - continue - } - unitQty := b.UnitQty * mult - node := bomNode{ - MaterialCode: b.MaterialCode, - MaterialName: b.MaterialName, - Spec: b.Spec, - Unit: b.Unit, - ManageMode: b.ManageMode, - UnitQty: unitQty, - LossRate: b.LossRate, - Level: depth, - } - if composite[b.MaterialCode] { - path[b.MaterialCode] = true - node.Children = s.expandBomTree(ctx, b.MaterialCode, bomName, unitQty, depth+1, path, resolve) - delete(path, b.MaterialCode) - // 组合件没有自身清单(或展开为空):按叶子处理,避免漏料 - if len(node.Children) == 0 { - node.Children = nil - } - } - out = append(out, node) - } - return out -} - -// bomTreeToLeaf 把展开树拍平为叶子清单(备料算料用):组合件递归下沉,叶子原样输出。 -func bomTreeToLeaf(nodes []bomNode) []bomLeaf { - out := make([]bomLeaf, 0, len(nodes)) - for _, n := range nodes { - if len(n.Children) > 0 { - out = append(out, bomTreeToLeaf(n.Children)...) - continue - } - out = append(out, bomLeaf{ - materialCode: n.MaterialCode, - materialName: n.MaterialName, - unit: n.Unit, - manageMode: n.ManageMode, - unitQty: n.UnitQty, - lossRate: n.LossRate, - }) - } - return out -} - -// bomTreeToBindNodes 把展开树转为追溯展示节点(保留层级与用量)。 -func bomTreeToBindNodes(nodes []bomNode) []BindNode { - out := make([]BindNode, 0, len(nodes)) - for _, n := range nodes { - node := BindNode{ - MaterialCode: n.MaterialCode, - MaterialName: n.MaterialName, - Spec: n.Spec, - Unit: n.Unit, - ManageMode: n.ManageMode, - Qty: n.UnitQty, - Level: n.Level, - } - if len(n.Children) > 0 { - node.Children = bomTreeToBindNodes(n.Children) - } - out = append(out, node) - } - return out -} - -// wmsFinishedResolver 备料侧下钻判定:子项在 WMS 的品类为成品(3) 时继续展开。 -// 客户口径:成品可作为零部件被再次加工,备料必须展开到原材料,否则产线缺料。 -// WMS 不可达时返回空集(全部按叶子处理),不阻塞备料生成,并记日志。 -func (s *Service) wmsFinishedResolver(ctx context.Context, productCode string, codes []string) map[string]bool { - out := map[string]bool{} - if s.ctx.Wms == nil || len(codes) == 0 { - return out - } - types, err := s.ctx.Wms.MaterialTypes(ctx, codes) - if err != nil { - s.ctx.EventLog.Write(ctx, "bom.expand.wms_skip", "", "", "product_bom", productCode, - "WMS 物料品类查询不可达,本次按叶子物料展开", map[string]any{"error": err.Error()}) - return out - } - for _, c := range codes { - if types[c] == 3 { - out[c] = true - } - } - return out -} - -// localBomExistsResolver 追溯侧下钻判定:本地存在该编码的下级物料清单时继续展开。 -// 不依赖 WMS(追溯页在 WMS 不可达时也必须能展示完整物料组成)。 -func (s *Service) localBomExistsResolver(ctx context.Context, _ string, codes []string) map[string]bool { - out := map[string]bool{} - for _, c := range codes { - if has, _ := s.ctx.EntClient.BomItem.Query().Where(bomitem.ProductCode(c)).Exist(ctx); has { - out[c] = true - } - } - return out -} diff --git a/bj_power_mes/internal/logic/inspection.go b/bj_power_mes/internal/logic/inspection.go index 833cec1..b0d21a4 100644 --- a/bj_power_mes/internal/logic/inspection.go +++ b/bj_power_mes/internal/logic/inspection.go @@ -8,7 +8,6 @@ import ( "time" "bj_power_mes/ent" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/inspectionrecord" ) @@ -44,14 +43,14 @@ type InspectionReq struct { StepName string `json:"stepName"` // 工艺步骤名称 MeasuredValue string `json:"measuredValue"` // 实测值 // 质量检验(过程检/完工检/来料检)扩展字段 - ReportNo string `json:"reportNo"` // 报检单号 - MaterialCode string `json:"materialCode"` // 物料编码(图号) - MaterialName string `json:"materialName"` // 物料名称 - Manufacturer string `json:"manufacturer"` // 生产厂家 - InspectionNo string `json:"inspectionNo"` // 检验单号 - AttachmentIds string `json:"attachmentIds"` // 附件ID,逗号分隔 - DisposalType string `json:"disposalType"` // 处置类型 退货/返修/退换 - DisposalRemark string `json:"disposalRemark"` // 处置说明 + ReportNo string `json:"reportNo"` // 报检单号 + MaterialCode string `json:"materialCode"` // 物料编码(图号) + MaterialName string `json:"materialName"` // 物料名称 + Manufacturer string `json:"manufacturer"` // 生产厂家 + InspectionNo string `json:"inspectionNo"` // 检验单号 + AttachmentIds string `json:"attachmentIds"` // 附件ID,逗号分隔 + DisposalType string `json:"disposalType"` // 处置类型 退货/返修/退换 + DisposalRemark string `json:"disposalRemark"` // 处置说明 } // CreateInspection 提交巡检记录;ALARM 类型同时触发看板报警(SSE + 清缓存) @@ -231,18 +230,3 @@ func (s *Service) SetInspectionDisposal(ctx context.Context, id int, disposalTyp "质量检验处置 "+disposalType, map[string]any{"id": id, "remark": disposalRemark}) return nil } - -// QueryBomMaterial 按物料编码或名称/图号模糊检索 BOM 料信息(质量检验"选物料自动带出 BOM"用) -func (s *Service) QueryBomMaterial(ctx context.Context, keyword string) ([]*ent.BomItem, error) { - if keyword == "" { - return []*ent.BomItem{}, nil - } - q := s.ctx.EntClient.BomItem.Query() - q = q.Where( - bomitem.Or( - bomitem.MaterialCodeContainsFold(keyword), - bomitem.MaterialNameContainsFold(keyword), - ), - ) - return q.Order(ent.Asc(bomitem.FieldProductCode), ent.Asc(bomitem.FieldBomName), ent.Asc(bomitem.FieldID)).Limit(200).All(ctx) -} diff --git a/bj_power_mes/internal/logic/material.go b/bj_power_mes/internal/logic/material.go index 9752cfb..d003283 100644 --- a/bj_power_mes/internal/logic/material.go +++ b/bj_power_mes/internal/logic/material.go @@ -79,26 +79,6 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string, } } } - // BOM 物料未被任何涉及工艺引用 → 告警不阻断(工艺物料清单 ⊆ 产品 BOM 的兜底提醒) - if bom, e := s.ListBom(ctx, wo.ProductCode, bomNameOrDefault("")); e == nil { - covered := map[string]bool{} - for _, fms := range g.fmByFlow { - for _, fm := range fms { - covered[fm.MaterialCode] = true - } - } - un := []string{} - for _, b := range bom { - if b.MaterialCode != "" && !covered[b.MaterialCode] { - un = append(un, b.MaterialCode) - } - } - if len(un) > 0 { - s.ctx.EventLog.Write(ctx, "bom.unassigned", plan.OrderNo, operator, "product_bom", wo.ProductCode, - "BOM 物料未配置在任何涉及工艺的物料清单,本次备料未覆盖", - map[string]any{"materials": un}) - } - } groups = append(groups, g) } if len(groups) == 0 { @@ -200,9 +180,9 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string, // SyncOrderLedger 计算并向 WMS 下发某工单的「工单级物料需求总量」(需求10)。 // -// 需求量口径(临时.md §四 工单域):需求量 = 工单数量 × 单台用量 × (1+损耗率),向上取整。 +// 需求量口径(临时.md §四 工单域):需求量 = 工单数量 × 单台含损耗用量,向上取整。 // 工单级而非日级——用日级会误卡跨天生产(临时.md L283-285)。 -// 多级 BOM 展开到叶子后按物料编码聚合(同编码合并),一个物料一行下发。 +// 用料唯一来源 = 工单工艺组合×工艺物料清单(BOM 已删除),同物料合并,一个物料一行下发。 // WMS 侧按 orderNo+materialCode 幂等 upsert total_qty,可重复调用。 func (s *Service) SyncOrderLedger(ctx context.Context, orderNo, operator string) error { wo, err := s.ctx.EntClient.WorkOrder.Query(). @@ -210,38 +190,20 @@ func (s *Service) SyncOrderLedger(ctx context.Context, orderNo, operator string) if err != nil { return err } - leaves := s.expandBomToLeaf(ctx, wo.ProductCode, bomNameOrDefault(""), 1, 0, map[string]bool{}) - if len(leaves) == 0 { + usage := s.WorkOrderUnitUsage(ctx, wo) + if len(usage) == 0 { return nil } - type agg struct { - name string - qty float64 - } - m := map[string]*agg{} - order := make([]string, 0, len(leaves)) - for _, it := range leaves { - if it.materialCode == "" { - continue - } - need := float64(wo.Quantity) * it.unitQty * (1 + it.lossRate/100) + items := make([]wmsclient.LedgerSyncItem, 0, len(usage)) + for _, it := range usage { + need := float64(wo.Quantity) * it.EffQty if need <= 0 { continue } - if a, ok := m[it.materialCode]; ok { - a.qty += need - } else { - m[it.materialCode] = &agg{name: it.materialName, qty: need} - order = append(order, it.materialCode) - } - } - items := make([]wmsclient.LedgerSyncItem, 0, len(order)) - for _, code := range order { - a := m[code] items = append(items, wmsclient.LedgerSyncItem{ - MaterialCode: code, - MaterialName: a.name, - TotalQty: int(math.Ceil(a.qty - 1e-9)), + MaterialCode: it.MaterialCode, + MaterialName: it.MaterialName, + TotalQty: int(math.Ceil(need - 1e-9)), }) } if len(items) == 0 { @@ -362,29 +324,6 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o return done, short } -// bomLeaf 递归展开后的叶子物料行(原材料/外购件) -type bomLeaf struct { - materialCode string - materialName string - unit string - manageMode string - unitQty float64 // 已折算父级倍率的单台用量 - lossRate float64 -} - -// expandBomToLeaf 递归展开产品物料清单到叶子(原材料/外购件),供备料算料。 -// -// 业务口径:成品可以作为零部件被另一个成品再次加工(多级嵌套)。备料算料时必须把 -// 成品子项按其自身的物料清单继续展开,直到原材料/外购件,否则产线会缺料。 -// 用量按倍率相乘(父级单台用量 × 子级单台用量)。 -// -// R1(2026-09-19):递归骨架统一到 bom_expand.go 的 expandBomTree,与追溯侧 -// (expandBindBom)共用同一份实现;下钻判定由 wmsFinishedResolver 注入, -// WMS 不可达时按叶子处理,不阻塞备料生成。 -func (s *Service) expandBomToLeaf(ctx context.Context, productCode, bomName string, mult float64, depth int, path map[string]bool) []bomLeaf { - return bomTreeToLeaf(s.expandBomTree(ctx, productCode, bomName, mult, depth, path, s.wmsFinishedResolver)) -} - // splitQtyToStations 把日总量 dayQty 拆分到 stations 各工位: // 优先使用 stationQty 显式分配(其和>0 时直接采用);否则平均分配(余数补到前面工位)。 func splitQtyToStations(stations []int, dayQty int, stationQty map[int]int) []int { diff --git a/bj_power_mes/internal/logic/processflow.go b/bj_power_mes/internal/logic/processflow.go index 887c968..5465af8 100644 --- a/bj_power_mes/internal/logic/processflow.go +++ b/bj_power_mes/internal/logic/processflow.go @@ -9,6 +9,7 @@ import ( "time" "bj_power_mes/ent" + "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/flowmaterial" "bj_power_mes/ent/processflow" "bj_power_mes/ent/processstep" @@ -242,24 +243,26 @@ func (s *Service) flowSteps(ctx context.Context, flowId int) []*ProcessStepTempl // ---------- 工位主数据(块3) ---------- type StationReq struct { - Id int `json:"id"` - StationNo int `json:"stationNo"` - Name string `json:"name"` - StationType *string `json:"stationType"` - FlowId *int `json:"flowId"` + Id int `json:"id"` + StationNo int `json:"stationNo"` + Name string `json:"name"` + StationType *string `json:"stationType"` + FlowId *int `json:"flowId"` + VisibleTabs []string `json:"visibleTabs"` // 终端可见页签(空=全部显示) } type StationVO struct { - Id int `json:"id"` - StationNo int `json:"stationNo"` - Name string `json:"name"` - FlowId int `json:"flowId"` - FlowName string `json:"flowName"` - StationType string `json:"stationType"` - Status string `json:"status"` - IsBuiltin bool `json:"isBuiltin"` - HasDock bool `json:"hasDock"` - DockCode string `json:"dockCode"` + Id int `json:"id"` + StationNo int `json:"stationNo"` + Name string `json:"name"` + FlowId int `json:"flowId"` + FlowName string `json:"flowName"` + StationType string `json:"stationType"` + Status string `json:"status"` + IsBuiltin bool `json:"isBuiltin"` + HasDock bool `json:"hasDock"` + DockCode string `json:"dockCode"` + VisibleTabs []string `json:"visibleTabs"` } func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) { @@ -274,7 +277,7 @@ func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) { } out := make([]*StationVO, 0, len(stas)) for _, st := range stas { - vo := &StationVO{Id: st.ID, StationNo: st.StationNo, Name: st.Name, FlowId: st.FlowId, StationType: st.StationType, Status: st.Status, IsBuiltin: st.IsBuiltin, HasDock: st.HasDock, DockCode: st.DockCode} + vo := &StationVO{Id: st.ID, StationNo: st.StationNo, Name: st.Name, FlowId: st.FlowId, StationType: st.StationType, Status: st.Status, IsBuiltin: st.IsBuiltin, HasDock: st.HasDock, DockCode: st.DockCode, VisibleTabs: st.VisibleTabs} if f, ok := flowMap[st.FlowId]; ok { vo.FlowName = f.Name } @@ -317,6 +320,9 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri // 页面「新增工位」创建的是非内置工位(可改类型、可删除);内置工位只能由种子/初始化数据产生。 // 是否有接驳台对应实体位置,由内置数据给定,页面新增时一律为 false 且不可手改。 SetIsBuiltin(false).SetHasDock(false) + if len(req.VisibleTabs) > 0 { + cr.SetVisibleTabs(req.VisibleTabs) + } if req.FlowId != nil && *req.FlowId > 0 { flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, *req.FlowId) if fErr != nil { @@ -365,6 +371,10 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri upd.SetFlowId(0) } } + // 终端可见页签:传 nil=不改;传空数组=清空(全部显示);传列表=按配置显示 + if req.VisibleTabs != nil { + upd.SetVisibleTabs(req.VisibleTabs) + } if _, err := upd.Save(ctx); err != nil { return err } @@ -430,12 +440,28 @@ func (s *Service) StationTask(ctx context.Context, stationNo int) (map[string]an if err != nil { return nil, errors.New("工位不存在或未配置") } + // 工位终端可见工单 = 今日已启用排产(CONFIRMED/执行中)且工单已下发/在制(RELEASED/IN_PROGRESS)。 + // 与状态机对齐:工单下发=批准生产、排产启用=排进某一天;未下发或未排进今天的工单,终端一律不显示。 orderNos := []string{} - wos, _ := s.ctx.EntClient.WorkOrder.Query(). - Where(workorder.StatusIn("CREATED", "RELEASED", "IN_PROGRESS")). - Order(ent.Asc(workorder.FieldID)).Limit(10).All(ctx) - for _, w := range wos { - orderNos = append(orderNos, w.WorkOrderNo) + today := time.Now().Format("2006-01-02") + plans, _ := s.ctx.EntClient.DailyPlan.Query(). + Where(dailyplan.PlanDate(today), dailyplan.StatusIn("CONFIRMED", "PROCESSING")). + Order(ent.Asc(dailyplan.FieldID)).All(ctx) + nos := make([]string, 0, len(plans)) + seen := map[string]bool{} + for _, p := range plans { + if !seen[p.OrderNo] { + seen[p.OrderNo] = true + nos = append(nos, p.OrderNo) + } + } + if len(nos) > 0 { + wos, _ := s.ctx.EntClient.WorkOrder.Query(). + Where(workorder.WorkOrderNoIn(nos...), workorder.StatusIn("RELEASED", "IN_PROGRESS")). + Order(ent.Asc(workorder.FieldID)).All(ctx) + for _, w := range wos { + orderNos = append(orderNos, w.WorkOrderNo) + } } // M4:工位终端按「本工位绑定的工艺流程」驱动。 // 产线定义 = 关联工位(station.flow_id)+ 工位号 1→12 顺序,已无独立"工艺路线/路线段"对象。 @@ -457,6 +483,8 @@ func (s *Service) StationTask(ctx context.Context, stationNo int) (map[string]an "flowActive": flow != nil && flow.Status == "ACTIVE", "steps": steps, "orderNos": orderNos, + // 终端可见页签(按工位配置;空=全部显示) + "tabs": st.VisibleTabs, }, nil } diff --git a/bj_power_mes/internal/logic/producible.go b/bj_power_mes/internal/logic/producible.go index ccc64a2..045e61f 100644 --- a/bj_power_mes/internal/logic/producible.go +++ b/bj_power_mes/internal/logic/producible.go @@ -15,14 +15,6 @@ import ( "bj_power_mes/internal/wmsclient" ) -// producibleBomItem 可生产数量计算用的精简 BOM 行 -type producibleBomItem struct { - materialCode string - materialName string - unit string // 计量单位(来自 BOM,与物料档案单位一致) - unitQty float64 // 单台用量 -} - // ProducibleResult 可生产数量计算结果(供 WMS 按需实时拉取) type ProducibleResult struct { Items []wmsclient.ProducibleItem `json:"items"` @@ -37,20 +29,21 @@ type MaterialDemandRow struct { MaterialCode string `json:"materialCode"` MaterialName string `json:"materialName"` Unit string `json:"unit"` - DemandQty int `json:"demandQty"` // 未来 N 天排产总需求(台数×单台用量,向上取整) + DemandQty int `json:"demandQty"` // 未来 N 天排产总需求(台数×单台含损耗用量,向上取整) StartDate string `json:"startDate"` // 需求窗口起(YYYY-MM-DD) EndDate string `json:"endDate"` // 需求窗口止(YYYY-MM-DD) } -// ProducibleSupportItem 排产支撑:单个成品的可生产套数与短板物料说明 +// ProducibleSupportItem 排产支撑:单张工单的可生产套数与短板物料说明 type ProducibleSupportItem struct { + OrderNo string `json:"orderNo"` ProductCode string `json:"productCode"` ProductName string `json:"productName"` ProducibleQty int `json:"producibleQty"` ShortText string `json:"shortText"` } -// ProducibleSupportResult 排产支撑总览:逐成品可生产套数 + 整体还能满产多少天/支撑到哪天/最先告罄短板物料 +// ProducibleSupportResult 排产支撑总览:逐工单可生产套数 + 整体还能满产多少天/支撑到哪天/最先告罄短板物料 type ProducibleSupportResult struct { Items []ProducibleSupportItem `json:"items"` SupportDays int `json:"supportDays"` @@ -59,36 +52,88 @@ type ProducibleSupportResult struct { ComputedAt int64 `json:"computedAt"` } +// planOrdersBetween 取 [start,end] 窗口内(按排产日期 PlanDate,非工单起止日期)未取消日排产: +// 返回 工单号→排产台数 合并映射(同工单多日排产累加)。 +func (s *Service) planOrdersBetween(ctx context.Context, start, end string) (map[string]int, error) { + plans, err := s.ctx.EntClient.DailyPlan.Query(). + Where(dailyplan.PlanDateGTE(start), dailyplan.PlanDateLTE(end)).All(ctx) + if err != nil { + return nil, err + } + qty := map[string]int{} + for _, p := range plans { + if p.Status == "CANCELLED" { + continue + } + qty[p.OrderNo] += p.PlanQty + } + for no, q := range qty { + if q <= 0 { + delete(qty, no) + } + } + return qty, nil +} + +// loadOrderUsage 批量加载工单(工单号→单台用料行)。工单号不存在或组合无物料的不进映射。 +func (s *Service) loadOrderUsage(ctx context.Context, orderNos []string) map[string][]UsageRow { + usageByOrder := map[string][]UsageRow{} + if len(orderNos) == 0 { + return usageByOrder + } + wos, err := s.ctx.EntClient.WorkOrder.Query(). + Where(workorder.WorkOrderNoIn(orderNos...)).All(ctx) + if err != nil { + return usageByOrder + } + for _, wo := range wos { + if u := s.WorkOrderUnitUsage(ctx, wo); len(u) > 0 { + usageByOrder[wo.WorkOrderNo] = u + } + } + return usageByOrder +} + // ComputeProducible 计算「可生产数量」+「未来5天物料需求」,结果直接返回(不做定时推送)。 // -// 业务口径(问题记录 L470-474 + L256): -// - 可生产套数 = min(各物料可用量 ÷ 单台用量)。BOM 单台用量在 MES、库存可用量在 WMS, -// 故由 MES 拉取 WMS 可用量(/api/internal/stock/check)后本地计算,WMS 打开页面时实时来拉。 -// - 未来5天需求量 = 近5天(含今日)日排产台数 × 单台用量,按物料汇总,供 WMS 备料四态「预警」判定。 +// 业务口径(BOM 已删除,物料跟着工单走): +// - 可生产套数 = 按"有未取消日排产的工单"逐单计算:min(各物料可用量 ÷ 该工单单台含损耗用量)。 +// 单台用量来自该工单工艺组合×工艺物料清单;库存可用量在 WMS,由 MES 拉取后本地计算。 +// - 未来5天需求量 = 近5天(含今日)日排产台数 × 工单单台含损耗用量,按物料汇总(按排产日期算), +// 供 WMS 备料四态「预警」判定(客户诉求 问题记录 L256)。 // // 两系统独立运行约束:未配置 WMS 或不可达时返回错误,由调用方(WMS)提示,绝不阻塞 MES。 func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, error) { if s.ctx.Wms == nil || s.ctx.EntClient == nil { return nil, errors.New("未配置 WMS 地址,无法计算可生产数量") } - chosen, materialSet, err := s.buildChosenBom(ctx) + today := time.Now().Format("2006-01-02") + planQty, err := s.planOrdersBetween(ctx, today, addDays(today, 59)) if err != nil { return nil, err } - if len(chosen) == 0 { + if len(planQty) == 0 { return &ProducibleResult{ Items: []wmsclient.ProducibleItem{}, Demands: []wmsclient.ProducibleDemand{}, Avail: map[string]int{}, ComputedAt: time.Now().Unix(), }, nil } + orderNos := make([]string, 0, len(planQty)) + for no := range planQty { + orderNos = append(orderNos, no) + } + sort.Strings(orderNos) + usageByOrder := s.loadOrderUsage(ctx, orderNos) - // §A2:可生产套数只算启用成品(停用产品不再展示产能)。 - // materialSet 保持完整——排产消耗模拟(simulateSupport)按真实排产消耗全部 BOM 物料。 - s.dropInactiveProducts(ctx, chosen) - - // 3) 拉取 WMS 各物料可用量 - codes := make([]string, 0, len(materialSet)) - for c := range materialSet { + // 拉取 WMS 各物料可用量(仅工单用料涉及的物料) + codeSet := map[string]bool{} + for _, usage := range usageByOrder { + for _, it := range usage { + codeSet[it.MaterialCode] = true + } + } + codes := make([]string, 0, len(codeSet)) + for c := range codeSet { codes = append(codes, c) } sort.Strings(codes) @@ -97,62 +142,58 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err return nil, errors.New("拉取 WMS 可用量失败: " + err.Error()) } - // 4) 产品名称映射(product_type 优先,work_order 兜底) + // 产品名称映射(product_type 优先,工单快照兜底) nameMap := map[string]string{} if rows, e := s.ctx.Wms.ProductTypes(ctx, ""); e == nil { for _, p := range rows { nameMap[p.Code] = p.Name } } - if wos, e := s.ctx.EntClient.WorkOrder.Query().All(ctx); e == nil { + prodCodeByOrder := map[string]string{} + if wos, e := s.ctx.EntClient.WorkOrder.Query(). + Where(workorder.WorkOrderNoIn(orderNos...)).All(ctx); e == nil { for _, wo := range wos { - if wo.ProductCode != "" && wo.ProductName != "" { - if _, has := nameMap[wo.ProductCode]; !has { - nameMap[wo.ProductCode] = wo.ProductName - } - } + prodCodeByOrder[wo.WorkOrderNo] = wo.ProductCode } } - // 5) 逐产品计算可生产套数 = min(floor(可用量 ÷ 单台用量)),短板物料取达最小值的前3 + // 逐工单计算可生产套数 = min(floor(可用量 ÷ 单台含损耗用量)),短板物料取最小值前3 now := time.Now().Unix() - prodCodes := make([]string, 0, len(chosen)) - for pc := range chosen { - prodCodes = append(prodCodes, pc) - } - sort.Strings(prodCodes) - items := make([]wmsclient.ProducibleItem, 0, len(prodCodes)) - for _, pc := range prodCodes { - bom := chosen[pc] + items := make([]wmsclient.ProducibleItem, 0, len(orderNos)) + for _, no := range orderNos { + usage, ok := usageByOrder[no] + if !ok { + continue // 工单组合无物料清单,无法评估 + } minSets := -1 type shortRow struct { text string set int } - shorts := make([]shortRow, 0, len(bom)) - for _, it := range bom { - if it.unitQty <= 0 { + shorts := make([]shortRow, 0, len(usage)) + for _, it := range usage { + if it.EffQty <= 0 { continue } - a := avail[it.materialCode] - sets := int(math.Floor(float64(a) / it.unitQty)) + a := avail[it.MaterialCode] + sets := int(math.Floor(float64(a) / it.EffQty)) if sets < 0 { sets = 0 } if minSets < 0 || sets < minSets { minSets = sets } - name := it.materialName + name := it.MaterialName if name == "" { - name = it.materialCode + name = it.MaterialCode } shorts = append(shorts, shortRow{ - text: fmt.Sprintf("%s(%s) 可用%d÷单台%s=%d套", name, it.materialCode, a, trimNum(it.unitQty), sets), + text: fmt.Sprintf("%s(%s) 可用%d÷单台%s=%d套", name, it.MaterialCode, a, trimNum(it.EffQty), sets), set: sets, }) } if minSets < 0 { - minSets = 0 // BOM 全无有效单台用量 + minSets = 0 } sort.SliceStable(shorts, func(i, j int) bool { return shorts[i].set < shorts[j].set }) pick := make([]string, 0, 3) @@ -161,7 +202,9 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err pick = append(pick, sr.text) } } + pc := prodCodeByOrder[no] items = append(items, wmsclient.ProducibleItem{ + OrderNo: no, ProductCode: pc, ProductName: nameMap[pc], ProducibleQty: minSets, @@ -170,98 +213,57 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err }) } - // 6) 未来5天物料需求(备料四态「预警」数据源) - demands := s.computeFuture5Demand(ctx, chosen) - - return &ProducibleResult{Items: items, Demands: demands, Avail: avail, ComputedAt: now}, nil + // 未来 N 天物料需求(备料四态「预警」数据源;窗口天数在「基础设置」页配置,默认 5) + demands := s.computeFutureDemand(ctx, s.CfgInt(ctx, CfgDemandDays, 5)) + return &ProducibleResult{ + Items: items, Demands: demands, + Avail: avail, ComputedAt: time.Now().Unix(), + }, nil } -// dropInactiveProducts 剔除停用产品(product_type.isActive=false)的 BOM 条目, -// 使「可生产套数」(排产支撑视图 Items)只统计启用成品(§A2:只算启用成品)。 -// 注意:只影响可生产套数计算;逐日消耗模拟(simulateSupport)仍用完整 BOM—— -// 停用产品若有遗留排产,物料消耗是真实的,不能漏算。 -func (s *Service) dropInactiveProducts(ctx context.Context, chosen map[string][]producibleBomItem) { - if len(chosen) == 0 { - return - } - rows, err := s.ctx.Wms.ProductTypes(ctx, "false") - if err != nil { - return - } - for _, p := range rows { - delete(chosen, p.Code) - } -} - -// buildChosenBom 按产品编码分组 BOM 明细,并为每个产品选定一份 BOM(优先“默认”,否则按名排序取第一份)。 -// 返回 chosen(产品编码→明细行) 与 materialSet(BOM 涉及的全部物料编码)。 -func (s *Service) buildChosenBom(ctx context.Context) (map[string][]producibleBomItem, map[string]bool, error) { - all, err := s.ctx.EntClient.BomItem.Query().All(ctx) - if err != nil { - return nil, nil, err - } - byProd := map[string]map[string][]producibleBomItem{} - for _, b := range all { - if b.ProductCode == "" || b.MaterialCode == "" { - continue - } - bn := b.BomName - if bn == "" { - bn = DefaultBOMName - } - if byProd[b.ProductCode] == nil { - byProd[b.ProductCode] = map[string][]producibleBomItem{} - } - byProd[b.ProductCode][bn] = append(byProd[b.ProductCode][bn], producibleBomItem{ - materialCode: b.MaterialCode, materialName: b.MaterialName, unit: b.Unit, unitQty: b.UnitQty, - }) - } - chosen := map[string][]producibleBomItem{} - materialSet := map[string]bool{} - for pc, boms := range byProd { - var bn string - if _, has := boms[DefaultBOMName]; has { - bn = DefaultBOMName - } else { - names := make([]string, 0, len(boms)) - for n := range boms { - names = append(names, n) - } - sort.Strings(names) - bn = names[0] - } - chosen[pc] = boms[bn] - for _, it := range boms[bn] { - materialSet[it.materialCode] = true - } - } - return chosen, materialSet, nil -} - -// ComputeMaterialDemand 按物料汇总未来 N 天(含今日)排产需求量,供 WMS 缺料补货视图实时拉取。 -// 需求 = Σ(逐日排产台数 × 单台用量),向上取整,按物料汇总;返回需求窗口起止日期。 -// 与 ComputeProducible 共享 BOM 选定逻辑,各自只算自己视角:MES 只产出"需求量",可用量由 WMS 自己比。 +// ComputeMaterialDemand WMS 缺料补货数据源:未来 N 天(按排产日期)排产物料需求,按物料汇总。 +// 与 ComputeProducible 共享工单用料汇总:MES 只产出"需求量",可用量由 WMS 自己比。 func (s *Service) ComputeMaterialDemand(ctx context.Context, days int) ([]MaterialDemandRow, error) { if s.ctx.EntClient == nil { return nil, errors.New("未配置数据库连接") } if days <= 0 { - days = 5 - } - chosen, _, err := s.buildChosenBom(ctx) - if err != nil { - return nil, err - } - if len(chosen) == 0 { - return []MaterialDemandRow{}, nil + days = s.CfgInt(ctx, CfgDemandDays, 5) // 未传窗口 → 基础设置需求窗口天数 } today := time.Now() start := today.Format("2006-01-02") end := today.AddDate(0, 0, days-1).Format("2006-01-02") - demand, err := s.dailyMaterialDemand(ctx, chosen, start, end) + planQty, err := s.planOrdersBetween(ctx, start, end) if err != nil { return nil, err } + if len(planQty) == 0 { + return []MaterialDemandRow{}, nil + } + orderNos := make([]string, 0, len(planQty)) + for no := range planQty { + orderNos = append(orderNos, no) + } + usageByOrder := s.loadOrderUsage(ctx, orderNos) + if len(usageByOrder) == 0 { + return []MaterialDemandRow{}, nil + } + // 需求 = Σ 排产台数 × 单台含损耗用量(向上取整);名称/单位取自工艺物料快照 + demand := map[string]int{} + nameUnit := map[string]struct{ name, unit string }{} + for no, qty := range planQty { + usage, ok := usageByOrder[no] + if !ok || qty <= 0 { + continue + } + for _, it := range usage { + if it.EffQty <= 0 { + continue + } + demand[it.MaterialCode] += int(math.Ceil(float64(qty) * it.EffQty)) + nameUnit[it.MaterialCode] = struct{ name, unit string }{it.MaterialName, it.Unit} + } + } if len(demand) == 0 { return []MaterialDemandRow{}, nil } @@ -270,13 +272,6 @@ func (s *Service) ComputeMaterialDemand(ctx context.Context, days int) ([]Materi mcodes = append(mcodes, c) } sort.Strings(mcodes) - // 物料名称/单位取自选定 BOM - nameUnit := map[string]struct{ name, unit string }{} - for _, bom := range chosen { - for _, it := range bom { - nameUnit[it.materialCode] = struct{ name, unit string }{it.materialName, it.unit} - } - } out := make([]MaterialDemandRow, 0, len(mcodes)) for _, c := range mcodes { nu := nameUnit[c] @@ -288,83 +283,22 @@ func (s *Service) ComputeMaterialDemand(ctx context.Context, days int) ([]Materi return out, nil } -// dailyMaterialDemand 累计 [start,end] 窗口内各物料排产需求量(向上取整)。 -// 数据链路:daily_plan(工单号→台数) → work_order(工单号→产品编码) → BOM(产品编码→物料单台用量)。 -func (s *Service) dailyMaterialDemand(ctx context.Context, chosen map[string][]producibleBomItem, start, end string) (map[string]int, error) { - plans, err := s.ctx.EntClient.DailyPlan.Query(). - Where(dailyplan.PlanDateGTE(start), dailyplan.PlanDateLTE(end)).All(ctx) - if err != nil { - return nil, err - } - if len(plans) == 0 { - return nil, nil - } - orderByNo := map[string]int{} - for _, p := range plans { - if p.Status == "CANCELLED" { - continue - } - orderByNo[p.OrderNo] += p.PlanQty - } - if len(orderByNo) == 0 { - return nil, nil - } - nos := make([]string, 0, len(orderByNo)) - for no := range orderByNo { - nos = append(nos, no) - } - wos, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNoIn(nos...)).All(ctx) - if err != nil { - return nil, err - } - // 产品编码 → 窗口内总台数 - prodQty := map[string]int{} - for _, wo := range wos { - if wo.ProductCode == "" { - continue - } - prodQty[wo.ProductCode] += orderByNo[wo.WorkOrderNo] - } - matQty := map[string]int{} - for pc, qty := range prodQty { - bom := chosen[pc] - if qty <= 0 || len(bom) == 0 { - continue - } - for _, it := range bom { - if it.unitQty <= 0 { - continue - } - matQty[it.materialCode] += int(math.Ceil(float64(qty) * it.unitQty)) - } - } - return matQty, nil -} - -// computeFuture5Demand 近5天(含今日)日排产台数 × 单台用量,按物料汇总为未来5天需求量。 -// 数据链路:daily_plan(工单号→台数) → work_order(工单号→产品编码) → BOM(产品编码→物料单台用量)。 -func (s *Service) computeFuture5Demand(ctx context.Context, chosen map[string][]producibleBomItem) []wmsclient.ProducibleDemand { - today := time.Now() - start := today.Format("2006-01-02") - end := today.AddDate(0, 0, 4).Format("2006-01-02") - matQty, err := s.dailyMaterialDemand(ctx, chosen, start, end) - if err != nil || len(matQty) == 0 { +// computeFutureDemand 近 N 天(含今日)日排产台数 × 工单单台含损耗用量,按物料汇总为未来需求量。 +// 窗口按排产日期算(工单起止日期≠排产日期,一律以排产日期为准);N 在「基础设置」页配置(默认 5)。 +func (s *Service) computeFutureDemand(ctx context.Context, days int) []wmsclient.ProducibleDemand { + rows, err := s.ComputeMaterialDemand(ctx, days) + if err != nil || len(rows) == 0 { return nil } - mcodes := make([]string, 0, len(matQty)) - for c := range matQty { - mcodes = append(mcodes, c) - } - sort.Strings(mcodes) - out := make([]wmsclient.ProducibleDemand, 0, len(mcodes)) - for _, c := range mcodes { - out = append(out, wmsclient.ProducibleDemand{MaterialCode: c, Future5Qty: matQty[c]}) + out := make([]wmsclient.ProducibleDemand, 0, len(rows)) + for _, r := range rows { + out = append(out, wmsclient.ProducibleDemand{MaterialCode: r.MaterialCode, Future5Qty: r.DemandQty}) } return out } // ComputeProducibleSupport 计算排产支撑视图(§A2 / §D1)。 -// 复用 ComputeProducible 得到逐成品可生产套数,再用 WMS 可用量对日排产做逐日消耗模拟, +// 复用 ComputeProducible 得到逐工单可生产套数,再用 WMS 可用量对日排产做逐日消耗模拟, // 得出整体还能满产多少天、支撑到哪天、最先告罄的短板物料;排产只排 N 天时,第 N+1 天起用近3天平均日需求外推。 func (s *Service) ComputeProducibleSupport(ctx context.Context) (*ProducibleSupportResult, error) { base, err := s.ComputeProducible(ctx) @@ -378,24 +312,32 @@ func (s *Service) ComputeProducibleSupport(ctx context.Context) (*ProducibleSupp } for _, it := range base.Items { res.Items = append(res.Items, ProducibleSupportItem{ - ProductCode: it.ProductCode, ProductName: it.ProductName, + OrderNo: it.OrderNo, ProductCode: it.ProductCode, ProductName: it.ProductName, ProducibleQty: it.ProducibleQty, ShortText: it.ShortText, }) } - chosen, _, err := s.buildChosenBom(ctx) - if err != nil { - return nil, err - } - days, until, shortBoard := s.simulateSupport(ctx, chosen, base.Avail) + usageByOrder := s.loadOrderUsage(ctx, orderNosOf(base.Items)) + days, until, shortBoard := s.simulateSupport(ctx, usageByOrder, base.Avail) res.SupportDays = days res.SupportUntil = until res.ShortBoardMaterial = shortBoard return res, nil } +// orderNosOf 从可生产结果提取工单号(保持顺序) +func orderNosOf(items []wmsclient.ProducibleItem) []string { + out := make([]string, 0, len(items)) + for _, it := range items { + if it.OrderNo != "" { + out = append(out, it.OrderNo) + } + } + return out +} + // simulateSupport 逐日消耗模拟:用 WMS 可用量 avail 对日排产做逐日扣减,直到某物料不足。 // 返回 支撑满产天数、支撑到哪天、最先告罄短板物料(名称+编码,无排产返回"无排产计划")。 -func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]producibleBomItem, avail map[string]int) (int, string, string) { +func (s *Service) simulateSupport(ctx context.Context, usageByOrder map[string][]UsageRow, avail map[string]int) (int, string, string) { today := time.Now() start := today.Format("2006-01-02") end := today.AddDate(0, 0, 59).Format("2006-01-02") @@ -404,42 +346,27 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ if err != nil { return 0, start, "无排产计划" } - // 工单号 → 产品编码 - orderNoSet := map[string]bool{} planByDate := map[string]map[string]int{} // date -> orderNo -> qty for _, p := range plans { if p.Status == "CANCELLED" || p.PlanQty <= 0 { continue } + if _, has := usageByOrder[p.OrderNo]; !has { + continue // 工单组合无物料清单,不参与消耗模拟 + } if planByDate[p.PlanDate] == nil { planByDate[p.PlanDate] = map[string]int{} } planByDate[p.PlanDate][p.OrderNo] += p.PlanQty - orderNoSet[p.OrderNo] = true } if len(planByDate) == 0 { return 0, start, "无排产计划" } - // 拉工单产品编码 - orderNos := make([]string, 0, len(orderNoSet)) - for no := range orderNoSet { - orderNos = append(orderNos, no) - } - wos, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNoIn(orderNos...)).All(ctx) - if err != nil { - return 0, start, "无排产计划" - } - orderProduct := map[string]string{} - for _, wo := range wos { - if wo.ProductCode != "" { - orderProduct[wo.WorkOrderNo] = wo.ProductCode - } - } // 物料名称 matName := map[string]string{} - for _, bom := range chosen { - for _, it := range bom { - matName[it.materialCode] = it.materialName + for _, usage := range usageByOrder { + for _, it := range usage { + matName[it.MaterialCode] = it.MaterialName } } // 排序排产日 @@ -460,7 +387,7 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ supportDays := 0 shortBoard := "" for _, d := range dates { - dayDemand := dayMaterialDemand(planByDate[d], orderProduct, chosen) + dayDemand := dayMaterialDemand(planByDate[d], usageByOrder) history = append(history, dayDemand) // 扣减 fail := false @@ -481,16 +408,17 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ supportDays++ } - // 排产日已耗尽仍有余量 → 用近3天平均日需求外推 + // 排产日已耗尽仍有余量 → 用近 N 天平均日需求外推(N 在「基础设置」页配置,默认 3) if shortBoard == "" { - // 计算均值(取最近 min(3,len) 天) + // 计算均值(取最近 min(N,len) 天) n := len(history) if n == 0 { return supportDays, addDays(start, supportDays), "" } + window := s.CfgInt(ctx, CfgExtrapWindow, 3) lo := 0 - if n > 3 { - lo = n - 3 + if n > window { + lo = n - window } avg := map[string]float64{} cnt := float64(n - lo) @@ -502,7 +430,7 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ for mat := range avg { avg[mat] /= cnt } - // 近3天平均日需求全为0(无有效 BOM 用量)→ 无更多需求,不再外推 + // 近 N 天平均日需求全为0(无有效单台用量)→ 无更多需求,不再外推 totalAvg := 0.0 for _, q := range avg { totalAvg += q @@ -510,8 +438,8 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ if totalAvg <= 0 { return supportDays, addDays(start, supportDays), "" } - // 外推:每日按 avg 扣减,直到某物料不足(封顶 365 天防死循环) - capDays := 365 + // 外推:每日按 avg 扣减,直到某物料不足(封顶天数在「基础设置」页配置,防死循环) + capDays := s.CfgInt(ctx, CfgExtrapCap, 365) for supportDays < capDays { fail := false for mat, q := range avg { @@ -537,23 +465,19 @@ func (s *Service) simulateSupport(ctx context.Context, chosen map[string][]produ return supportDays, addDays(start, supportDays), shortBoard } -// dayMaterialDemand 计算某日各物料需求(逐工单台数 × 单台用量,向上取整) -func dayMaterialDemand(planOfDay map[string]int, orderProduct map[string]string, chosen map[string][]producibleBomItem) map[string]int { +// dayMaterialDemand 计算某日各物料需求(逐工单台数 × 工单单台含损耗用量,向上取整) +func dayMaterialDemand(planOfDay map[string]int, usageByOrder map[string][]UsageRow) map[string]int { demand := map[string]int{} for orderNo, qty := range planOfDay { - pc := orderProduct[orderNo] - if pc == "" || qty <= 0 { + usage := usageByOrder[orderNo] + if len(usage) == 0 || qty <= 0 { continue } - bom := chosen[pc] - if len(bom) == 0 { - continue - } - for _, it := range bom { - if it.unitQty <= 0 { + for _, it := range usage { + if it.EffQty <= 0 { continue } - demand[it.materialCode] += int(math.Ceil(float64(qty) * it.unitQty)) + demand[it.MaterialCode] += int(math.Ceil(float64(qty) * it.EffQty)) } } return demand diff --git a/bj_power_mes/internal/logic/product.go b/bj_power_mes/internal/logic/product.go index 9278d58..f93b87e 100644 --- a/bj_power_mes/internal/logic/product.go +++ b/bj_power_mes/internal/logic/product.go @@ -6,7 +6,6 @@ import ( "fmt" "strings" - "bj_power_mes/ent/bomitem" "bj_power_mes/ent/workorder" "bj_power_mes/internal/wmsclient" ) @@ -16,11 +15,11 @@ import ( // 不降级读本地缓存,避免给界面喂空/陈旧数据)。 type ProductTypeReq struct { - Id int `json:"id"` - Name string `json:"name"` - Code string `json:"code"` - Spec string `json:"spec"` - Unit string `json:"unit"` + Id int `json:"id"` + Name string `json:"name"` + Code string `json:"code"` + Spec string `json:"spec"` + Unit string `json:"unit"` Category string `json:"category"` ManageMode int `json:"manageMode"` // 1结构件(批次)/2电气件(SN);MES 成品只列这两个 IsActive bool `json:"isActive"` @@ -76,10 +75,6 @@ func (s *Service) DeleteProductType(ctx context.Context, id int) error { if woCnt > 0 { return fmt.Errorf("该物料档案已被 %d 张工单引用,不可删除;建议停用(下架)", woCnt) } - bomCnt, _ := s.ctx.EntClient.BomItem.Query().Where(bomitem.ProductCode(row.Code)).Count(ctx) - if bomCnt > 0 { - return fmt.Errorf("该物料档案在物料清单中有 %d 条配置,不可删除;建议停用(下架)", bomCnt) - } if err := s.ctx.Wms.DeleteProductType(ctx, id); err != nil { return errors.New("WMS 不可达或拒绝删除:" + err.Error()) } diff --git a/bj_power_mes/internal/logic/seed.go b/bj_power_mes/internal/logic/seed.go index 78803b4..d8a5807 100644 --- a/bj_power_mes/internal/logic/seed.go +++ b/bj_power_mes/internal/logic/seed.go @@ -25,12 +25,12 @@ func (s *Service) Seed(ctx context.Context) error { codes := []string{"*"} if r.code == "OPERATOR" { codes = []string{ - "produce.workorder", "produce.dailyplan", "produce.bom", "produce.material", "produce.producible", + "produce.workorder", "produce.dailyplan", "produce.material", "produce.producible", "produce.trace", "produce.wip", "produce.torque", "produce.plc", "produce.product", "produce.processflow", "produce.station", "produce.performance", "produce.processcard", // 按钮级权限(块2) "produce.workorder:add", "produce.workorder:edit", "produce.workorder:delete", - "produce.workorder:dailyplan", "produce.bom:edit", "produce.material:generate", "produce.material:outbound", + "produce.workorder:dailyplan", "produce.material:generate", "produce.material:outbound", "produce.quality", "produce.quality:edit", "produce.plc:send", "produce.product:add", "produce.product:edit", "produce.product:delete", "produce.processflow:add", "produce.processflow:edit", "produce.processflow:delete", @@ -74,7 +74,6 @@ func (s *Service) Seed(ctx context.Context) error { menus := []struct{ code, name, typ, path string }{ {"produce.workorder", "工单管理", "MENU", "/work-order"}, {"produce.dailyplan", "日排产", "MENU", "/daily-plan"}, - {"produce.bom", "产品物料清单", "MENU", "/bom"}, {"produce.producible", "排产支撑", "MENU", "/producible-support"}, {"produce.material", "备料单", "MENU", "/material-request"}, {"produce.qty", "数量不符处理", "MENU", "/qty-report"}, @@ -84,6 +83,9 @@ func (s *Service) Seed(ctx context.Context) error { {"produce.station", "关联工位", "MENU", "/station"}, {"produce.performance", "绩效报表", "MENU", "/performance"}, {"produce.dock", "接驳台维护", "MENU", "/dock"}, {"produce.trace", "工件追溯", "MENU", "/trace"}, + // 虚拟工位作业:虚拟工位(如包装等无终端硬件的工位)由人工在 MES 后台(手机/电脑)完成报工, + // 给对应账号开通本菜单权限即可使用 + {"produce.virtualstation", "虚拟工位作业", "MENU", "/virtual-station"}, {"produce.wip", "在制品", "MENU", "/wip"}, {"produce.processcard", "生产流程卡", "MENU", "/process-card"}, {"produce.product", "物料档案", "MENU", "/product-type"}, @@ -93,6 +95,8 @@ func (s *Service) Seed(ctx context.Context) error { // sys.rbac(角色权限管理) 已拆分:账号管理 + 角色管理(对齐 WMS 系统管理菜单) {"sys.account", "账号管理", "MENU", "/account"}, {"sys.role", "角色管理", "MENU", "/role"}, + // 基础设置:WMS 地址(热切换)/需求窗口天数/外推参数/事件日志保留天数 + 本机信息展示 + {"sys.settings", "基础设置", "MENU", "/settings"}, // 预警中心 / 附件中心此前只有前端菜单码(MainLayout menuGroups)、权限表未登记, // 导致这两个菜单无法授权给任何角色(只有 SUPER_ADMIN 靠 roleCode 旁路可见),2026-09-19 补齐。 {"sys.alert", "预警中心", "MENU", "/alert-center"}, @@ -106,6 +110,11 @@ func (s *Service) Seed(ctx context.Context) error { SetCode(m.code).SetName(m.name).SetType(m.typ).SetPath(m.path).Exec(ctx) } + // BOM 已删除(物料跟着工单走):清理历史「产品物料清单」菜单与按钮权限 + for _, dead := range []string{"produce.bom", "produce.bom:edit"} { + _, _ = s.ctx.EntClient.Permission.Delete().Where(permission.Code(dead)).Exec(ctx) + } + // 3.1 按钮级权限(块2):前端按钮 + 后端接口 双重校验 // parent = 所属菜单权限码:每个按钮显式声明挂在哪个菜单下,前端据此组装权限树, // 不再用 code.startsWith(菜单+':') 这类前缀通配推断。 @@ -114,7 +123,6 @@ func (s *Service) Seed(ctx context.Context) error { {"produce.workorder:edit", "工单-编辑", "BUTTON", "", "produce.workorder"}, {"produce.workorder:delete", "工单-删除", "BUTTON", "", "produce.workorder"}, {"produce.workorder:dailyplan", "工单-日排产", "BUTTON", "", "produce.workorder"}, - {"produce.bom:edit", "物料清单-维护", "BUTTON", "", "produce.bom"}, {"produce.material:generate", "备料单-生成", "BUTTON", "", "produce.material"}, {"produce.material:outbound", "备料单-自动出库", "BUTTON", "", "produce.material"}, {"produce.qty:handle", "数量不符-处理", "BUTTON", "", "produce.qty"}, @@ -145,6 +153,7 @@ func (s *Service) Seed(ctx context.Context) error { {"produce.quality:edit", "质量检验-录入/处置", "BUTTON", "", "produce.quality"}, // 附件中心(对齐 WMS attachment:manage 口径):删除 + 归档清理 {"sys.attachment:manage", "附件-删除/归档清理", "BUTTON", "", "sys.attachment"}, + {"sys.settings:edit", "基础设置-修改", "BUTTON", "", "sys.settings"}, } for _, b := range buttons { exist, err := s.ctx.EntClient.Permission.Query().Where(permission.Code(b.code)).Only(ctx) diff --git a/bj_power_mes/internal/logic/settings.go b/bj_power_mes/internal/logic/settings.go new file mode 100644 index 0000000..1b093c1 --- /dev/null +++ b/bj_power_mes/internal/logic/settings.go @@ -0,0 +1,213 @@ +package logic + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "runtime" + "strconv" + "strings" + "time" + + "bj_power_mes/ent/sysconfig" + "bj_power_mes/internal/wmsclient" +) + +// 系统基础设置配置键(sys_config 表,系统管理员「基础设置」页维护,保存即生效) +const ( + // CfgWmsBaseURL WMS 地址(IP:端口),保存即热切换 wmsclient;空=用 YAML 配置/默认地址 + CfgWmsBaseURL = "wms.base_url" + // CfgDemandDays 需求窗口天数:缺料补货/未来需求按日排产取未来 N 天(默认 5) + CfgDemandDays = "demand.days" + // CfgExtrapWindow 排产支撑外推均值窗口(近 N 天平均日需求,默认 3) + CfgExtrapWindow = "producible.extrap.window" + // CfgExtrapCap 排产支撑外推封顶天数(防死循环,默认 365) + CfgExtrapCap = "producible.extrap.cap" + // CfgLogRetention 事件日志保留天数,超过自动清理(0=不清理) + CfgLogRetention = "eventlog.retention.days" +) + +// startedAt 服务启动时刻(本机信息展示用) +var startedAt = time.Now() + +// SettingsVO 基础设置视图:可配置项 + 本机基础信息(只读展示) +type SettingsVO struct { + // 可配置项 + WmsBaseURL string `json:"wmsBaseURL"` // WMS 地址(空=未自定义,走 YAML/默认) + DemandDays int `json:"demandDays"` // 需求窗口天数 + ExtrapWindow int `json:"extrapWindow"` // 外推均值窗口天数 + ExtrapCap int `json:"extrapCap"` // 外推封顶天数 + LogRetentionDays int `json:"logRetentionDays"` // 事件日志保留天数(0=不清理) + + // 本机基础信息(只读) + LocalIPs []string `json:"localIPs"` // 本机内网 IPv4 列表 + ListenAddr string `json:"listenAddr"` // 服务监听地址 + DBInfo string `json:"dbInfo"` // 数据库 host:port/db(不含密码) + EffectiveWms string `json:"effectiveWms"` // 当前生效的 WMS 地址 + GoVersion string `json:"goVersion"` // Go 运行时版本 + StartedAt string `json:"startedAt"` // 服务启动时间 +} + +// SettingsReq 基础设置保存请求(nil 字段不改,便于部分保存) +type SettingsReq struct { + WmsBaseURL *string `json:"wmsBaseURL"` + DemandDays *int `json:"demandDays"` + ExtrapWindow *int `json:"extrapWindow"` + ExtrapCap *int `json:"extrapCap"` + LogRetentionDays *int `json:"logRetentionDays"` +} + +// defaults 建议默认值(未配置时生效) +var settingsDefaults = map[string]int{ + CfgDemandDays: 5, + CfgExtrapWindow: 3, + CfgExtrapCap: 365, + CfgLogRetention: 0, +} + +// GetSettings 读取基础设置 + 本机信息。DB 读失败时按默认值返回(设置页必须能打开)。 +func (s *Service) GetSettings(ctx context.Context) (*SettingsVO, error) { + kv := map[string]string{} + if rows, err := s.ctx.EntClient.SysConfig.Query().All(ctx); err == nil { + for _, r := range rows { + kv[r.Key] = r.Value + } + } + vo := &SettingsVO{ + WmsBaseURL: kv[CfgWmsBaseURL], + DemandDays: cfgIntFrom(kv, CfgDemandDays), + ExtrapWindow: cfgIntFrom(kv, CfgExtrapWindow), + ExtrapCap: cfgIntFrom(kv, CfgExtrapCap), + LogRetentionDays: cfgIntFrom(kv, CfgLogRetention), + LocalIPs: localIPv4s(), + ListenAddr: fmt.Sprintf("%s:%d", s.ctx.Config.Host, s.ctx.Config.Port), + DBInfo: fmt.Sprintf("%s:%d/%s", s.ctx.Config.Database.Host, s.ctx.Config.Database.Port, s.ctx.Config.Database.Dbname), + EffectiveWms: strings.TrimSuffix(s.ctx.Wms.BaseURL(), "/"), + GoVersion: runtime.Version(), + StartedAt: startedAt.Format("2006-01-02 15:04:05"), + } + return vo, nil +} + +// SaveSettings 保存基础设置(幂等 upsert,nil 字段不改);WMS 地址变化即热切换。 +func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator string) error { + // 校验 + if req.WmsBaseURL != nil { + u := strings.TrimSpace(*req.WmsBaseURL) + if u != "" && !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") { + return errors.New("WMS 地址需以 http:// 或 https:// 开头,如 http://192.168.1.100:9091") + } + } + type item struct { + key string + val *int + lo int + hi int + remark string + } + items := []item{ + {CfgDemandDays, req.DemandDays, 1, 60, "需求窗口天数(缺料补货/未来需求)"}, + {CfgExtrapWindow, req.ExtrapWindow, 1, 30, "排产支撑外推均值窗口天数"}, + {CfgExtrapCap, req.ExtrapCap, 30, 3650, "排产支撑外推封顶天数"}, + {CfgLogRetention, req.LogRetentionDays, 0, 3650, "事件日志保留天数(0=不清理)"}, + } + for _, it := range items { + if it.val == nil { + continue + } + if *it.val < it.lo || *it.val > it.hi { + return fmt.Errorf("%s 取值范围 %d~%d", it.remark, it.lo, it.hi) + } + if err := s.upsertConfig(ctx, it.key, strconv.Itoa(*it.val), it.remark); err != nil { + return err + } + } + if req.WmsBaseURL != nil { + u := strings.TrimSpace(*req.WmsBaseURL) + if err := s.upsertConfig(ctx, CfgWmsBaseURL, u, "WMS 服务地址(保存即生效)"); err != nil { + return err + } + // 热切换:保存即生效,无需重启 + s.ctx.Wms.SetBaseURL(u) + } + payload := map[string]any{"req": req} + s.ctx.EventLog.Write(ctx, "sys.settings.save", "", operator, "sys_config", "", "保存基础设置", payload) + return nil +} + +// TestWms 测试 WMS 连通性:调免登录看板总览接口,返回耗时/错误。 +// candidate 非空时测试该地址(保存前试测用),为空测当前生效地址。 +func (s *Service) TestWms(ctx context.Context, candidate string) (string, error) { + client := s.ctx.Wms + if u := strings.TrimSpace(candidate); u != "" { + if !strings.HasPrefix(u, "http://") && !strings.HasPrefix(u, "https://") { + return "", errors.New("WMS 地址需以 http:// 或 https:// 开头") + } + client = wmsclient.New(u, s.ctx.Config.Wms.Token) + } + c2, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + start := time.Now() + if _, err := client.DisplayOverview(c2); err != nil { + return "", fmt.Errorf("连接失败: %v", err) + } + return fmt.Sprintf("连接成功(%d ms)", time.Since(start).Milliseconds()), nil +} + +// CfgInt 读取整型配置(未配置/非法值回退 def)。供业务模块读取可配置参数。 +func (s *Service) CfgInt(ctx context.Context, key string, def int) int { + v, err := s.ctx.EntClient.SysConfig.Query().Where(sysconfig.Key(key)).Only(ctx) + if err != nil || v == nil { + return def + } + n, err := strconv.Atoi(strings.TrimSpace(v.Value)) + if err != nil { + return def + } + return n +} + +// upsertConfig 幂等写入配置 +func (s *Service) upsertConfig(ctx context.Context, key, value, remark string) error { + exist, err := s.ctx.EntClient.SysConfig.Query().Where(sysconfig.Key(key)).Only(ctx) + if err == nil && exist != nil { + return exist.Update().SetValue(value).SetRemark(remark).Exec(ctx) + } + return s.ctx.EntClient.SysConfig.Create().SetKey(key).SetValue(value).SetRemark(remark).Exec(ctx) +} + +// cfgIntFrom 从已加载的 kv map 解析整型(非法/未配置回退默认值) +func cfgIntFrom(kv map[string]string, key string) int { + v, ok := kv[key] + if !ok || strings.TrimSpace(v) == "" { + return settingsDefaults[key] + } + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil { + return settingsDefaults[key] + } + return n +} + +// localIPv4s 枚举本机非环回 IPv4(内网 IP 展示) +func localIPv4s() []string { + hostname, _ := os.Hostname() + out := []string{} + if hostname != "" { + out = append(out, hostname) + } + addrs, err := net.InterfaceAddrs() + if err != nil { + return out + } + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok || ipnet.IP.IsLoopback() || ipnet.IP.To4() == nil { + continue + } + out = append(out, ipnet.IP.String()) + } + return out +} diff --git a/bj_power_mes/internal/logic/usage.go b/bj_power_mes/internal/logic/usage.go new file mode 100644 index 0000000..ac72c8f --- /dev/null +++ b/bj_power_mes/internal/logic/usage.go @@ -0,0 +1,98 @@ +package logic + +import ( + "context" + "errors" + "sort" + + "bj_power_mes/ent" + "bj_power_mes/ent/flowmaterial" + "bj_power_mes/ent/workorder" +) + +// UsageRow 工单的单台用料行(BOM 已删除:用料唯一来源 = 工单工艺组合条目 × 工艺物料清单)。 +// 同一物料出现在组合中多个工艺时合并累加;同一成品不同工单可用不同工艺,物料跟着工单走。 +type UsageRow struct { + MaterialCode string `json:"materialCode"` + MaterialName string `json:"materialName"` + Spec string `json:"spec"` + Unit string `json:"unit"` + ManageMode string `json:"manageMode"` + UnitQty float64 `json:"unitQty"` // 单台净用量(跨工艺累加) + LossRate float64 `json:"lossRate"` // 综合损耗率%(按各行损耗加权折算,仅供展示) + EffQty float64 `json:"effQty"` // 单台含损耗用量 = Σ 行单台用量×(1+损耗率/100),参与计算 +} + +// GetOrderUsage 按工单号查询单台用料(工位终端上线位领料确认 / 管理后台展示用) +func (s *Service) GetOrderUsage(ctx context.Context, orderNo string) ([]UsageRow, error) { + if orderNo == "" { + return []UsageRow{}, nil + } + wo, err := s.ctx.EntClient.WorkOrder.Query(). + Where(workorder.WorkOrderNo(orderNo)).First(ctx) + if err != nil { + return nil, errors.New("工单不存在: " + orderNo) + } + return s.WorkOrderUnitUsage(ctx, wo), nil +} + +// WorkOrderUnitUsage 汇总工单的单台用料:工艺组合条目×flow_material,同物料合并。 +// 组合为空或工艺均无物料时返回空切片。 +func (s *Service) WorkOrderUnitUsage(ctx context.Context, wo *ent.WorkOrder) []UsageRow { + if wo == nil { + return nil + } + items, _ := RouteStationsFromWO(ctx, s.ctx.EntClient, wo) + if len(items) == 0 { + return nil + } + idSet := map[int]bool{} + for _, it := range items { + idSet[it.FlowId] = true + } + ids := make([]int, 0, len(idSet)) + for id := range idSet { + ids = append(ids, id) + } + fms, err := s.ctx.EntClient.FlowMaterial.Query(). + Where(flowmaterial.FlowIdIn(ids...)).All(ctx) + if err != nil { + return nil + } + byCode := map[string]*UsageRow{} + for _, fm := range fms { + if fm.MaterialCode == "" { + continue + } + r, ok := byCode[fm.MaterialCode] + if !ok { + r = &UsageRow{ + MaterialCode: fm.MaterialCode, MaterialName: fm.MaterialName, + Spec: fm.Spec, Unit: fm.Unit, ManageMode: fm.ManageMode, + } + byCode[fm.MaterialCode] = r + } + if r.MaterialName == "" { + r.MaterialName = fm.MaterialName + } + if r.Unit == "" { + r.Unit = fm.Unit + } + r.UnitQty += fm.UnitQty + r.EffQty += fm.UnitQty * (1 + fm.LossRate/100) + } + codes := make([]string, 0, len(byCode)) + for c := range byCode { + codes = append(codes, c) + } + sort.Strings(codes) + out := make([]UsageRow, 0, len(codes)) + for _, c := range codes { + r := byCode[c] + if r.UnitQty > 0 { + r.LossRate = (r.EffQty/r.UnitQty - 1) * 100 + } + out = append(out, *r) + } + return out +} diff --git a/bj_power_mes/internal/logic/workpiece.go b/bj_power_mes/internal/logic/workpiece.go index e32d7c7..5248fa0 100644 --- a/bj_power_mes/internal/logic/workpiece.go +++ b/bj_power_mes/internal/logic/workpiece.go @@ -446,9 +446,9 @@ func (s *Service) DoneWorkpiece(ctx context.Context, req DoneReq, operator strin return nil } -// backflushWorkpiece 反冲扣账:按工单产品整份 BOM 算「单件消耗(含损耗)」, +// backflushWorkpiece 反冲扣账:按工单工艺组合的单台用料(工艺物料清单汇总,含损耗)算「单件消耗」, // 调 WMS 内部反冲接口 FIFO 扣库存 + 生成 backflush 出库单。 -// 整份 BOM 一次性下发(完工即全部物料已消耗),WMS 不可达/校验失败仅记日志。 +// 用料唯一来源=工单组合×flow_material(BOM 已删除);WMS 不可达/校验失败仅记日志。 func (s *Service) backflushWorkpiece(ctx context.Context, wp *ent.Workpiece, operator string) { wo, err := s.ctx.EntClient.WorkOrder.Get(ctx, wp.WorkOrderId) if err != nil || wo == nil { @@ -456,19 +456,16 @@ func (s *Service) backflushWorkpiece(ctx context.Context, wp *ent.Workpiece, ope "反冲失败:工单不存在", map[string]any{"workOrderId": wp.WorkOrderId}) return } - bom, err := s.ListBom(ctx, wo.ProductCode, bomNameOrDefault("")) - if err != nil || len(bom) == 0 { + usage := s.WorkOrderUnitUsage(ctx, wo) + if len(usage) == 0 { s.ctx.EventLog.Write(ctx, "wms.backflush.skip", wp.OrderNo, operator, "workpiece", wp.Sn, - "无BOM物料,跳过反冲", map[string]any{"productCode": wo.ProductCode}) + "工单工艺组合无物料清单,跳过反冲", map[string]any{"orderNo": wp.OrderNo}) return } - items := make([]wmsclient.BackflushItem, 0, len(bom)) - for _, it := range bom { - if it.MaterialCode == "" { - continue - } - // 单件消耗 = 单台用量 ×(1+损耗率),四舍五入;≤0 跳过 - qty := int(math.Round(it.UnitQty * (1 + it.LossRate/100))) + items := make([]wmsclient.BackflushItem, 0, len(usage)) + for _, it := range usage { + // 单件消耗 = 单台含损耗用量,四舍五入;≤0 跳过 + qty := int(math.Round(it.EffQty)) if qty <= 0 { continue } @@ -479,11 +476,11 @@ func (s *Service) backflushWorkpiece(ctx context.Context, wp *ent.Workpiece, ope } if wmsErr := s.ctx.Wms.Backflush(ctx, wp.OrderNo, 0, 0, operator, items); wmsErr != nil { s.ctx.EventLog.Write(ctx, "wms.backflush.failed", wp.OrderNo, operator, "workpiece", wp.Sn, - "反冲扣账WMS失败(库存未扣,请人工核查)", map[string]any{"error": wmsErr.Error(), "productCode": wo.ProductCode}) + "反冲扣账WMS失败(库存未扣,请人工核查)", map[string]any{"error": wmsErr.Error(), "orderNo": wp.OrderNo}) return } s.ctx.EventLog.Write(ctx, "wms.backflush", wp.OrderNo, operator, "workpiece", wp.Sn, - "反冲扣账已下发WMS", map[string]any{"productCode": wo.ProductCode, "items": len(items)}) + "反冲扣账已下发WMS", map[string]any{"orderNo": wp.OrderNo, "items": len(items)}) } // retainFinishedToWms 完工品回流 WMS 库存。失败仅记日志(wms.finished.retain_failed), diff --git a/bj_power_mes/internal/logic/workpiece_bind.go b/bj_power_mes/internal/logic/workpiece_bind.go index 198818f..1c32213 100644 --- a/bj_power_mes/internal/logic/workpiece_bind.go +++ b/bj_power_mes/internal/logic/workpiece_bind.go @@ -309,22 +309,18 @@ func (s *Service) BuildBindTrace(ctx context.Context, sn string) (*BindTraceVO, if err != nil { return nil, err } - // 物料组成树:递归展开成品零部件到叶子(不依赖 WMS),让追溯页能展示完整物料组成, - // 避免成品作零部件被引用时只显示上层成品而漏下层料、追溯断链。 + // 物料组成:按工单工艺组合×工艺物料清单平铺一层(BOM 已删除,无多级树) var tree []BindNode - tree = s.expandBindBom(ctx, wo.ProductCode, "", 1, 0, map[string]bool{}) + for _, it := range s.WorkOrderUnitUsage(ctx, wo) { + tree = append(tree, BindNode{ + MaterialCode: it.MaterialCode, MaterialName: it.MaterialName, + Spec: it.Spec, Unit: it.Unit, ManageMode: it.ManageMode, + Qty: it.UnitQty, Level: 0, + }) + } return &BindTraceVO{Binds: binds, Complete: missing == "", Missing: missing, BomTree: tree}, nil } -// expandBindBom 递归展开某产品的物料组成树(供追溯页/成品档案展示完整物料构成)。 -// -// R1(2026-09-19):递归骨架统一到 bom_expand.go 的 expandBomTree,与备料算料共用同一份实现; -// 下钻判定由 localBomExistsResolver 注入(本地存在下级清单才继续展开)——不依赖 WMS, -// 保证 WMS 不可达时追溯仍能展示完整物料组成、不断链。 -func (s *Service) expandBindBom(ctx context.Context, productCode, bomName string, qty float64, depth int, path map[string]bool) []BindNode { - return bomTreeToBindNodes(s.expandBomTree(ctx, productCode, bomNameOrDefault(bomName), qty, depth, path, s.localBomExistsResolver)) -} - // BindRequiredItem 应绑清单条目(工位终端展示引导 + 前端齐套计算) type BindRequiredItem struct { MaterialCode string `json:"materialCode"` diff --git a/bj_power_mes/internal/wmsclient/client.go b/bj_power_mes/internal/wmsclient/client.go index 64b9908..626403c 100644 --- a/bj_power_mes/internal/wmsclient/client.go +++ b/bj_power_mes/internal/wmsclient/client.go @@ -10,25 +10,47 @@ import ( "net/http" "net/url" "strconv" + "strings" + "sync/atomic" "time" ) // Client WMS 内部接口客户端(半成品流转等) +// baseURL 支持运行时热切换(系统管理员「基础设置」页保存 WMS 地址后 SetBaseURL 即生效), +// 因此用 atomic.Value 存储,读侧无需加锁。 type Client struct { - baseURL string + baseURL atomic.Value // string token string hc *http.Client } +// defaultBaseURL 未配置 WMS 地址时的兜底值 +const defaultBaseURL = "http://127.0.0.1:9091" + func New(baseURL, token string) *Client { - if baseURL == "" { - baseURL = "http://127.0.0.1:9091" + c := &Client{ + token: token, + hc: &http.Client{Timeout: 5 * time.Second}, } - return &Client{ - baseURL: baseURL, - token: token, - hc: &http.Client{Timeout: 5 * time.Second}, + c.SetBaseURL(baseURL) + return c +} + +// SetBaseURL 热切换 WMS 地址;空串回退默认地址 +func (c *Client) SetBaseURL(u string) { + u = strings.TrimSpace(u) + if u == "" { + u = defaultBaseURL } + if !strings.HasSuffix(u, "/") { + u += "/" + } + c.baseURL.Store(u) +} + +// BaseURL 当前生效的 WMS 地址(带尾斜杠) +func (c *Client) BaseURL() string { + return c.baseURL.Load().(string) } // SemiInbound 调 WMS /api/internal/semi/inbound 半成品入库。 @@ -55,7 +77,7 @@ func (c *Client) postSemi(ctx context.Context, path string, body any) error { if err != nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+path, bytes.NewReader(b)) if err != nil { return err } @@ -98,7 +120,7 @@ func (c *Client) MaterialExists(ctx context.Context, codes []string) ([]string, if err != nil { return nil, err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/internal/material/exists", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/material/exists", bytes.NewReader(b)) if err != nil { return nil, err } @@ -128,11 +150,11 @@ func (c *Client) MaterialExists(ctx context.Context, codes []string) ([]string, // 注:原「备注」随 WMS 物料档案「简称」一并删除(2026-09-19), // 改为与 WMS 必填口径一致的「规格 / 单位」。 type ProductTypeRow struct { - ID int `json:"id"` - Code string `json:"code"` - Name string `json:"name"` - Spec string `json:"spec"` - Unit string `json:"unit"` + ID int `json:"id"` + Code string `json:"code"` + Name string `json:"name"` + Spec string `json:"spec"` + Unit string `json:"unit"` Category string `json:"category"` ManageMode int `json:"manageMode"` // 1结构件(批次)/2电气件(SN) IsActive bool `json:"isActive"` @@ -142,7 +164,7 @@ type ProductTypeRow struct { // get 调 WMS GET 接口并解出 {code,data} func (c *Client) get(ctx context.Context, path string, out any) error { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+path, nil) if err != nil { return err } @@ -178,7 +200,7 @@ func (c *Client) putJSON(ctx context.Context, path string, body any) error { if err != nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.baseURL+path, bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.BaseURL()+path, bytes.NewReader(b)) if err != nil { return err } @@ -271,7 +293,7 @@ func (c *Client) ExportProductTypes(ctx context.Context, code, name, category, i q += "isActive=" + isActive + "&" } q += "startDate=" + startDate + "&endDate=" + endDate - req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+q, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+q, nil) if err != nil { return nil, err } @@ -302,7 +324,7 @@ func (c *Client) CreateReturnOrder(ctx context.Context, orderNo, sn, materialCod // DisplayOverview 拉取 WMS 免登录看板总览 /api/display/overview。 // 用于看板「仓储动态」屏。WMS 不可达时返回 err,由调用方降级为空对象(看板其余屏不受影响)。 func (c *Client) DisplayOverview(ctx context.Context) (map[string]any, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/display/overview", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL()+"/api/display/overview", nil) if err != nil { return nil, err } @@ -339,7 +361,7 @@ func (c *Client) StockAvailable(ctx context.Context, codes []string) (map[string if err != nil { return nil, err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/internal/stock/check", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/stock/check", bytes.NewReader(b)) if err != nil { return nil, err } @@ -372,8 +394,9 @@ func (c *Client) StockAvailable(ctx context.Context, codes []string) (map[string return out, nil } -// ProducibleItem 可生产数量快照行(MES 计算后推送 WMS 只读展示) +// ProducibleItem 可生产数量行(按工单维度,MES 实时计算;原定时推送/快照已下线) type ProducibleItem struct { + OrderNo string `json:"orderNo"` ProductCode string `json:"productCode"` ProductName string `json:"productName"` ProducibleQty int `json:"producibleQty"` @@ -395,7 +418,7 @@ func (c *Client) MaterialTypes(ctx context.Context, codes []string) (map[string] if err != nil { return nil, err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/internal/material/types", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/material/types", bytes.NewReader(b)) if err != nil { return nil, err } @@ -460,7 +483,7 @@ type StockBatch struct { // StockBatches 调 WMS /api/internal/stock/batches 取该物料可出库的批次(FIFO 升序)与可用 SN 列表。 // 供「工单备料自动出库」分配用;WMS 只返回「合格」且在库的库存。 func (c *Client) StockBatches(ctx context.Context, materialCode string) ([]StockBatch, []string, error) { - u := c.baseURL + "/api/internal/stock/batches?materialCode=" + url.QueryEscape(materialCode) + u := c.BaseURL() + "/api/internal/stock/batches?materialCode=" + url.QueryEscape(materialCode) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return nil, nil, err @@ -529,7 +552,7 @@ func (c *Client) StockDeduct(ctx context.Context, orderNo, materialCode string, if err != nil { return "", "", err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/internal/stock/deduct", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/stock/deduct", bytes.NewReader(b)) if err != nil { return "", "", err } @@ -615,7 +638,7 @@ func (c *Client) LedgerSync(ctx context.Context, orderNo, productCode, operator if err != nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/api/internal/ledger/sync", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/ledger/sync", bytes.NewReader(b)) if err != nil { return err } @@ -645,7 +668,7 @@ func (c *Client) post(ctx context.Context, path string, body any) error { if err != nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+path, bytes.NewReader(b)) if err != nil { return err } @@ -729,7 +752,7 @@ func (c *Client) UpdateMaterial(ctx context.Context, id int, name, spec, unit, d "id": id, "name": name, "spec": spec, "unit": unit, "description": description, "itemType": itemType, "manageMode": manageMode, "templateCode": templateCode, "safetyStock": safetyStock, }) - req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.baseURL+"/api/internal/materials", bytes.NewReader(b)) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, c.BaseURL()+"/api/internal/materials", bytes.NewReader(b)) if err != nil { return err } diff --git a/bj_power_mes/public/index.html b/bj_power_mes/public/index.html index ef7233d..53985ec 100644 --- a/bj_power_mes/public/index.html +++ b/bj_power_mes/public/index.html @@ -6,8 +6,8 @@ MES 产线控制 - - + +
diff --git a/bj_power_mes/schema/bom_item.go b/bj_power_mes/schema/bom_item.go deleted file mode 100644 index 4851ecc..0000000 --- a/bj_power_mes/schema/bom_item.go +++ /dev/null @@ -1,50 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/entsql" - "entgo.io/ent/schema" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" -) - -// BomItem 产品物料清单明细(一个产品型号可并存多份:不同厂家供货/含半成品等不同料单结构,工单建单时选定一份) -type BomItem struct { - ent.Schema -} - -func (BomItem) Annotations() []schema.Annotation { - return []schema.Annotation{entsql.Annotation{Table: "work_order_bom"}} -} - -func (BomItem) Fields() []ent.Field { - return []ent.Field{ - field.Int("id").Positive(), - field.String("productCode").Default("").MaxLen(64).Comment("产品编码"), - field.String("bomName").Default("默认").MaxLen(64).Comment("物料清单名称:同一型号多份并存(如 厂家A/厂家B/含半成品),工单按名选用"), - field.String("materialCode").MaxLen(64).Comment("物料编码"), - field.String("materialName").Default("").MaxLen(128), - field.String("spec").Default("").MaxLen(128), - field.String("unit").Default("").MaxLen(16), - // 1 批次(结构件) / 2 序列号(电气件) - field.String("manageMode").Default("2").MaxLen(10), - field.Float("unitQty").Default(0).Comment("单台用量"), - field.Float("lossRate").Default(0).Comment("损耗率%"), - field.String("relatedStandard").Default("").MaxLen(255).Comment("相关标准(检验细则)"), - field.Float("requiredQty").Default(0).Comment("需求总量=总台数*单台*(1+损耗)"), - field.JSON("serialSns", []string{}).Optional().SchemaType(map[string]string{ - dialect.Postgres: "jsonb", - }).Comment("电气件SN下发列表(可选)"), - field.Time("createdAt").Default(time.Now).Immutable(), - } -} - -func (BomItem) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("productCode"), - index.Fields("productCode", "bomName", "materialCode").Unique(), - } -} diff --git a/bj_power_mes/schema/station.go b/bj_power_mes/schema/station.go index 316be97..32c3ef2 100644 --- a/bj_power_mes/schema/station.go +++ b/bj_power_mes/schema/station.go @@ -38,6 +38,9 @@ func (Station) Fields() []ent.Field { field.Bool("hasDock").Default(false).Comment("是否有接驳台(实体位置,内置不可改)"), // 引用接驳台编码(与 WMS dock.dock_code 对应,1:1):产线工位 DOCKn↔工位n,无接驳台则空 field.String("dockCode").Default("").MaxLen(20).Comment("接驳台编码 DOCK01..21"), + // 终端可见页签(按工位配置,2026-09-23):空=全部显示(兼容存量工位); + // 可选值 online(上线建档)/work(作业)/material(物料叫料)/move(移料)/pdf(工艺文件)/inspect(巡检异常)/offline(下线完工) + field.JSON("visibleTabs", []string{}).Optional(), field.Time("createdAt").Default(time.Now).Immutable(), } } diff --git a/bj_power_mes/schema/sys_config.go b/bj_power_mes/schema/sys_config.go new file mode 100644 index 0000000..182a99d --- /dev/null +++ b/bj_power_mes/schema/sys_config.go @@ -0,0 +1,27 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// SysConfig 系统基础设置(key/value)。 +// 系统管理员「基础设置」页维护,保存即生效(无需重启);敏感信息(JWT secret、 +// WMS token、数据库密码)仍留在 etc/*.yaml,不进本表。 +type SysConfig struct { + ent.Schema +} + +func (SysConfig) Annotations() []schema.Annotation { + return []schema.Annotation{entsql.Annotation{Table: "sys_config"}} +} + +func (SysConfig) Fields() []ent.Field { + return []ent.Field{ + field.String("key").Unique().MaxLen(64).Comment("配置键,如 wms.base_url"), + field.String("value").MaxLen(512).Comment("配置值"), + field.String("remark").Optional().MaxLen(255).Comment("说明"), + } +} diff --git a/bj_power_workstation/etc/bj_power_workstation.yaml b/bj_power_workstation/etc/bj_power_workstation.yaml index 09418f5..60fa5e9 100644 --- a/bj_power_workstation/etc/bj_power_workstation.yaml +++ b/bj_power_workstation/etc/bj_power_workstation.yaml @@ -24,7 +24,7 @@ Internal: # 工位配置:StationNo 固定本终端工位号(仅允许运维改配置后重启生效,工人无法在前端修改)。 # 应拧颗数不再由工位固定配置,而是取自工件工艺流程中「拧紧工艺步骤」的数量。 Station: - StationNo: 1 + StationNo: 0 # 工艺文件 PDF 本地预缓存目录(留空关闭缓存) PdfCache: diff --git a/bj_power_workstation/frontend/src/store/station.js b/bj_power_workstation/frontend/src/store/station.js index b073161..9d7a250 100644 --- a/bj_power_workstation/frontend/src/store/station.js +++ b/bj_power_workstation/frontend/src/store/station.js @@ -90,6 +90,10 @@ export const missingTorqueSteps = computed( () => torqueSteps.value.filter((s) => !torqueRowOfStep(s.id)) ) export const orderNos = computed(() => (Array.isArray(state.task?.orderNos) ? state.task.orderNos : [])) +// 终端可见页签(按工位配置;空=全部显示)。可选值 online/work/material/move/pdf/inspect/offline +export const visibleTabs = computed(() => (Array.isArray(state.task?.tabs) ? state.task.tabs : [])) +// 页签是否显示:未配置(空数组)一律显示 +export const hasTab = (name) => !visibleTabs.value.length || visibleTabs.value.includes(name) export const flowName = computed(() => state.task?.flow?.name || '-') export const flowActive = computed(() => !!state.task?.flowActive) // 本工位绑定的工艺 ID(station.flowId,随任务下发):装机绑定/报工一律按 flowId 查询与上报 @@ -202,7 +206,8 @@ export async function loadConfig() { } export async function loadTask() { - if (!state.stationNo) return + // 0=上线位是合法工位,不能用 falsy 判断,否则上线位永远不拉任务 + if (state.stationNo == null || state.stationNo === '') return try { state.task = await getTaskCurrent(state.stationNo) if (orderNos.value.length && !orderNos.value.includes(state.orderNo)) { @@ -311,7 +316,7 @@ export function refreshAll() { // loadStationState 拉取本工位当天的停单状态(MES /api/internal/station/state),刷新横幅与按钮。 // 拉取失败保持现状,避免网络抖动误清停单横幅。 export async function loadStationState() { - if (!state.stationNo) return + if (state.stationNo == null || state.stationNo === '') return try { const list = await getStationState() const rows = Array.isArray(list) ? list : (list?.list || []) diff --git a/bj_power_workstation/frontend/src/views/Login.vue b/bj_power_workstation/frontend/src/views/Login.vue index 1857603..043ba74 100644 --- a/bj_power_workstation/frontend/src/views/Login.vue +++ b/bj_power_workstation/frontend/src/views/Login.vue @@ -27,7 +27,7 @@
工位 - {{ fixedStation ? '工位 ' + fixedStation : '工位加载中…' }} + {{ fixedStation != null ? '工位 ' + fixedStation : '工位加载中…' }}