This commit is contained in:
SunYF
2026-10-26 16:32:35 +08:00
parent 4b14f9540a
commit f86feb2271
99 changed files with 1652 additions and 521 deletions
+5 -1
View File
@@ -43,7 +43,7 @@ func (w *Writer) Write(ctx context.Context, eventType, workOrderNo, operator, en
// from/to 传时间戳毫秒(0 表示不限)。
// operators:操作人候选列表(任一命中即算),历史数据里 operator 中文名/用户名混杂,调用方应同时传两者;
// admin 精确筛选单人时传单元素即可,传空切片=不过滤。
func (w *Writer) Query(ctx context.Context, eventType, workOrderNo string, operators []string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
func (w *Writer) Query(ctx context.Context, eventType, workOrderNo string, operators []string, entityType string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
q := w.client.EventLog.Query()
// 操作日志只收录业务操作,登录/退出(auth.*)不属于操作日志范畴,一律不展示。
q = q.Where(eventlog.Not(eventlog.EventTypeHasPrefix("auth.")))
@@ -57,6 +57,10 @@ func (w *Writer) Query(ctx context.Context, eventType, workOrderNo string, opera
if len(operators) > 0 {
q = q.Where(eventlog.OperatorIn(operators...))
}
if entityType != "" {
// B3.4 对象类型筛选(如 workpiece / material / alert_rule)
q = q.Where(eventlog.EntityTypeEQ(entityType))
}
if fromMs > 0 {
q = q.Where(eventlog.CreatedAtGTE(time.UnixMilli(fromMs)))
}
+28 -2
View File
@@ -199,8 +199,13 @@ func AttachmentFileHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
http.NotFound(w, r)
return
}
// 中文文件名走 RFC 5987;下载(dl=1)才强制 attachment,否则内联预览
disp := "inline"
// 中文文件名走 RFC 5987;图片/PDF 内联预览,其他类型强制下载;
// 显式 dl=1 一律强制下载(对齐 WMS /uploads/ 行为)。
ext := strings.ToLower(filepath.Ext(abs))
disp := "attachment"
if isInlineExt(ext) {
disp = "inline"
}
if r.URL.Query().Get("dl") == "1" {
disp = "attachment"
}
@@ -219,6 +224,27 @@ func AttachmentDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.BadRequest(w, "参数错误:id 必填")
return
}
// 删除保护(对齐 WMS):关键工艺文件 / 保留期内检验件禁止删除,避免质量/工艺记录丢失。
rec, gerr := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
if gerr != nil {
http.NotFound(w, r)
return
}
switch rec.FileType {
case FileTypeProcessPDF, FileTypeProcessCard:
httpx.Fail(w, 3315, "工艺流程 / 流程卡为关键工艺文件,禁止删除")
return
case FileTypeInspectionPhoto, FileTypeInspectionPDF:
years := svcCtx.Config.Upload.LocalRetentionYears
if years <= 0 {
years = 1
}
cutYear := time.Now().Year() - years
if rec.CreatedAt.Year() >= cutYear {
httpx.Fail(w, 3315, fmt.Sprintf("检验记录在质量追溯保留期(%d 年)内,禁止删除", years))
return
}
}
att, err := logic.New(svcCtx).DeleteAttachment(r.Context(), req.Id, operator(r, ""))
if err != nil {
httpx.Fail(w, 3313, "删除附件失败:"+err.Error())
+11 -1
View File
@@ -170,6 +170,7 @@ func CreateUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1006, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "user.create", "", ctxOperator(r), "user", req.Username, "创建用户 "+req.Username, nil)
httpx.OkMessage(w, "创建成功", nil)
}
}
@@ -185,6 +186,7 @@ func UpdateUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1007, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "user.update", "", ctxOperator(r), "user", req.Username, "更新用户 "+req.Username, nil)
httpx.OkMessage(w, "更新成功", nil)
}
}
@@ -195,6 +197,7 @@ func DeleteUserHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1008, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "user.delete", "", ctxOperator(r), "user", strconv.Itoa(pathId(r)), "删除用户 id="+strconv.Itoa(pathId(r)), nil)
httpx.OkMessage(w, "删除成功", nil)
}
}
@@ -220,7 +223,8 @@ func ChangePasswordHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
func ListRolesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data, err := logic.New(svcCtx).ListRoles(r.Context())
keyword := strings.TrimSpace(r.URL.Query().Get("keyword"))
data, err := logic.New(svcCtx).ListRoles(r.Context(), keyword)
if err != nil {
httpx.Fail(w, 1009, err.Error())
return
@@ -240,6 +244,7 @@ func CreateRoleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1010, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "role.create", "", ctxOperator(r), "role", req.Code, "创建角色 "+req.Name, nil)
httpx.OkMessage(w, "创建成功", nil)
}
}
@@ -255,6 +260,7 @@ func UpdateRoleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1011, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "role.update", "", ctxOperator(r), "role", req.Code, "更新角色 "+req.Name, nil)
httpx.OkMessage(w, "更新成功", nil)
}
}
@@ -265,6 +271,7 @@ func DeleteRoleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1012, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "role.delete", "", ctxOperator(r), "role", strconv.Itoa(pathId(r)), "删除角色 id="+strconv.Itoa(pathId(r)), nil)
httpx.OkMessage(w, "删除成功", nil)
}
}
@@ -293,6 +300,7 @@ func CreatePermissionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1014, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "rbac.permission.create", "", ctxOperator(r), "permission", req.Code, "创建权限 "+req.Name, nil)
httpx.OkMessage(w, "创建成功", nil)
}
}
@@ -308,6 +316,7 @@ func UpdatePermissionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1015, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "rbac.permission.update", "", ctxOperator(r), "permission", req.Code, "更新权限 "+req.Name, nil)
httpx.OkMessage(w, "更新成功", nil)
}
}
@@ -318,6 +327,7 @@ func DeletePermissionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 1016, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "rbac.permission.delete", "", ctxOperator(r), "permission", strconv.Itoa(pathId(r)), "删除权限 id="+strconv.Itoa(pathId(r)), nil)
httpx.OkMessage(w, "删除成功", nil)
}
}
+1
View File
@@ -13,6 +13,7 @@ import (
var pathPermMap = map[string]string{
"POST:/api/v1/product-types": "produce.product:add",
"PUT:/api/v1/product-types": "produce.product:edit",
"POST:/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",
+2 -1
View File
@@ -17,7 +17,8 @@ func ListProcessFlowsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
stationNo := atoiDefault(r.URL.Query().Get("stationNo"), 0)
page := atoiDefault(r.URL.Query().Get("page"), 0)
pageSize := atoiDefault(r.URL.Query().Get("pageSize"), 20)
data, err := logic.New(svcCtx).ListFlows(r.Context(), stationNo, r.URL.Query().Get("pp"), page, pageSize)
data, err := logic.New(svcCtx).ListFlows(r.Context(), stationNo, r.URL.Query().Get("pp"),
r.URL.Query().Get("name"), r.URL.Query().Get("status"), atoiDefault(r.URL.Query().Get("stepMin"), 0), page, pageSize)
if err != nil {
httpx.Fail(w, 2201, err.Error())
return
@@ -2,6 +2,7 @@ package production
import (
"net/http"
"strconv"
"bj_power_mes/common/httpx"
"bj_power_mes/internal/logic"
@@ -26,6 +27,7 @@ func CreateAlertRuleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 3301, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "alert.rule.create", "", operator(r, ""), "alert_rule", req.Name, "新增预警规则 "+req.Name, nil)
httpx.OkMessage(w, "保存成功", nil)
}
}
@@ -49,6 +51,7 @@ func UpdateAlertRuleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 3302, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "alert.rule.update", "", operator(r, ""), "alert_rule", strconv.Itoa(req.Id), "修改预警规则 "+req.Name, nil)
httpx.OkMessage(w, "保存成功", nil)
}
}
@@ -65,6 +68,7 @@ func DeleteAlertRuleHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 3303, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "alert.rule.delete", "", operator(r, ""), "alert_rule", strconv.Itoa(id), "删除预警规则 id="+strconv.Itoa(id), nil)
httpx.OkMessage(w, "删除成功", nil)
}
}
@@ -23,6 +23,7 @@ func UpsertMaterialInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc
httpx.Fail(w, 3120, err.Error())
return
}
svcCtx.EventLog.Write(r.Context(), "material.upsert", "", operator(r, ""), "material", req.Code, "物料档案 upsert "+req.Code, nil)
httpx.Ok(w, map[string]any{"created": created})
}
}
@@ -96,6 +96,17 @@ func DeleteProductTypeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
}
}
// RetryProductTypeSyncHandler POST /product-types/:id/sync-retry 手动重推单行物料到 WMS(替代原列表自动重推)
func RetryProductTypeSyncHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := logic.New(svcCtx).RetryProductTypeSync(r.Context(), pathID(r)); err != nil {
httpx.Fail(w, 3015, "重推失败:"+err.Error())
return
}
httpx.OkMessage(w, "重推成功", nil)
}
}
// SetProductTypeStatusHandler POST /product-types/status 物料档案启用/停用专用通道(body {id,isActive})
func SetProductTypeStatusHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
@@ -154,8 +154,21 @@ func ListEventLogsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
isAdmin := false
if me != nil {
candidates = []string{me.Username, me.Name}
if rl, err := svcCtx.EntClient.Role.Get(context.Background(), me.RoleId); err == nil && rl.Code == "SUPER_ADMIN" {
isAdmin = true
}
// B3.3 isAdmin 优先取 JWT 中的 roleCode(上下文注入 / 解析 token),缺失时回退 DB Role 查 code,避免每次查库
if rc, ok := r.Context().Value("roleCode").(string); ok && rc != "" {
isAdmin = rc == "SUPER_ADMIN"
} else {
auth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if auth != "" {
if claims, err := tokenx.Parse(svcCtx.Config.Auth.AccessSecret, auth); err == nil && claims.RoleCode == "SUPER_ADMIN" {
isAdmin = true
}
}
if !isAdmin && me != nil {
if rl, err := svcCtx.EntClient.Role.Get(context.Background(), me.RoleId); err == nil && rl.Code == "SUPER_ADMIN" {
isAdmin = true
}
}
}
explicitFilter := q.Get("operator")
@@ -165,7 +178,7 @@ func ListEventLogsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
}
list, total, err := logic.New(svcCtx).ListEventLogs(r.Context(),
q.Get("orderNo"), operatorCandidates(explicitFilter, candidates), q.Get("eventType"), fromMs, toMs, page, pageSize)
q.Get("orderNo"), operatorCandidates(explicitFilter, candidates), q.Get("eventType"), q.Get("entityType"), fromMs, toMs, page, pageSize)
if err != nil {
httpx.Fail(w, 3308, err.Error())
return
@@ -18,7 +18,8 @@ func ListProductProcessesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
page := atoiDefault(q.Get("page"), 0)
pageSize := atoiDefault(q.Get("pageSize"), 20)
data, err := logic.New(svcCtx).ListProductProcesses(r.Context(),
q.Get("productCode"), q.Get("status"), atoiDefault(q.Get("flowId"), 0), q.Get("keyword"), page, pageSize)
q.Get("productCode"), q.Get("status"), atoiDefault(q.Get("flowId"), 0), q.Get("keyword"),
q.Get("name"), atoiDefault(q.Get("stepMin"), 0), atoiDefault(q.Get("stepMax"), 0), page, pageSize)
if err != nil {
httpx.Fail(w, 2231, err.Error())
return
@@ -222,6 +222,7 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
{Method: http.MethodPut, Path: "/product-types", Handler: production.UpdateProductTypeHandler(serverCtx)},
// 物料档案启用/停用专用通道(body {id,isActive}):本地置 isActive 并同步 WMS,停用=退出新建下拉
{Method: http.MethodPost, Path: "/product-types/status", Handler: production.SetProductTypeStatusHandler(serverCtx)},
{Method: http.MethodPost, Path: "/product-types/:id/sync-retry", Handler: production.RetryProductTypeSyncHandler(serverCtx)},
{Method: http.MethodDelete, Path: "/product-types/:id", Handler: production.DeleteProductTypeHandler(serverCtx)},
{Method: http.MethodGet, Path: "/work-orders", Handler: production.ListWorkOrdersHandler(serverCtx)},
+43 -13
View File
@@ -32,13 +32,14 @@ const (
FileTypeProcessCard = "PROCESS_CARD" // 流程卡
FileTypePackagePhoto = "PACKAGE_PHOTO" // 包装照片
FileTypeExcelImport = "EXCEL_IMPORT" // Excel 导入
FileTypeImage = "IMAGE" // 图片(通用,不细分业务:png/jpg/jpeg/gif/webp)
FileTypeOther = "OTHER" // 其他
)
var validFileTypes = map[string]bool{
FileTypeProcessPDF: true, FileTypeInspectionPhoto: true, FileTypeInspectionPDF: true,
FileTypeDrawing: true, FileTypeProcessCard: true, FileTypePackagePhoto: true,
FileTypeExcelImport: true, FileTypeOther: true,
FileTypeExcelImport: true, FileTypeImage: true, FileTypeOther: true,
}
// allowedExt 允许的扩展名白名单(图纸/报告/图片/表格/压缩包)。白名单而非黑名单,避免上传可执行文件。
@@ -48,27 +49,45 @@ var allowedExt = map[string]bool{
".dwg": true, ".dxf": true, ".zip": true, ".txt": true, ".csv": true,
}
// deriveFileType 未显式指定文件类型时,按业务类型 + 扩展名推断,兜底 OTHER。
// deriveFileType 未显式指定文件类型时,按「扩展名优先」推断:
// 1) 图片类(png/jpg/jpeg/gif/webp)→ 按业务类型细分(检验/来料→检验照片,包裹/出库→包裹照片),无更细业务类型归「图片(IMAGE)」;
// 2) 非图片按业务类型 + 扩展名细分(PDF/DWG 等);
// 3) 兜底 OTHER。
// 扩展名优先可避免「material 的 png 照片被误判为其他」等问题。
func deriveFileType(bizType, ext string) string {
ext = strings.ToLower(ext)
switch {
case ext == ".xlsx" || ext == ".xls" || ext == ".csv":
return FileTypeExcelImport
case bizType == "inspection":
// 扩展名优先:图片类
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".webp" {
switch bizType {
case "inspection", "inbound":
return FileTypeInspectionPhoto
case "outbound", "package":
return FileTypePackagePhoto
default:
return FileTypeImage
}
}
// 非图片:按业务类型 + 扩展名细分
switch bizType {
case "inspection":
if ext == ".pdf" {
return FileTypeInspectionPDF
}
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
return FileTypeInspectionPhoto
case "material":
if ext == ".pdf" || ext == ".dwg" || ext == ".dxf" {
return FileTypeDrawing
}
case bizType == "material" && (ext == ".pdf" || ext == ".dwg" || ext == ".dxf"):
return FileTypeDrawing
case bizType == "work_order":
case "work_order":
if ext == ".pdf" {
return FileTypeProcessCard
}
case bizType == "process_flow" && ext == ".pdf":
return FileTypeProcessPDF
case "process_flow":
if ext == ".pdf" {
return FileTypeProcessPDF
}
}
if ext == ".xlsx" || ext == ".xls" || ext == ".csv" {
return FileTypeExcelImport
}
return FileTypeOther
}
@@ -267,6 +286,17 @@ func serveUploadFile(w http.ResponseWriter, r *http.Request, dir, name string) {
http.ServeContent(w, r, filepath.Base(abs), time.Time{}, f)
}
// isInlineExt 判断扩展名是否可在浏览器内联预览(图片 / PDF)。
// 与 WMS attachment 包的判定保持一致:只有这类文件才允许 inline,其余一律强制下载,
// 避免 docx/xlsx/zip 等被当垃圾数据内联打开(B1.1 对齐两端行为)。
func isInlineExt(ext string) bool {
switch strings.ToLower(ext) {
case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".pdf":
return true
}
return false
}
// randHex 随机十六进制串(保留给其他场景的短随机名使用)。
func randHex(n int) string {
b := make([]byte, n)
+8 -2
View File
@@ -231,9 +231,15 @@ func (s *Service) Evaluate(ctx context.Context, typ string, value float64, title
if err != nil || len(rules) == 0 {
return
}
dir := alertDirection(typ)
// 事件触发型(torque_ng / inspection_ng):enabled 即命中,忽略阈值比较(B2.3)。
// 阈值比较型(inventory_low / task_overdue 等)仍按方向 + 阈值判定。
eventType := typ == "torque_ng" || typ == "inspection_ng"
for _, r := range rules {
hit := (dir == 1 && value >= r.Threshold) || (dir == -1 && value <= r.Threshold)
hit := true
if !eventType {
dir := alertDirection(typ)
hit = (dir == 1 && value >= r.Threshold) || (dir == -1 && value <= r.Threshold)
}
if !hit {
continue
}
+7 -2
View File
@@ -535,8 +535,13 @@ func (s *Service) DeleteRole(ctx context.Context, id int) error {
return s.ctx.EntClient.Role.DeleteOneID(id).Exec(ctx)
}
func (s *Service) ListRoles(ctx context.Context) ([]*ent.Role, error) {
return s.ctx.EntClient.Role.Query().Order(ent.Asc(role.FieldID)).All(ctx)
func (s *Service) ListRoles(ctx context.Context, keyword string) ([]*ent.Role, error) {
q := s.ctx.EntClient.Role.Query().Order(ent.Asc(role.FieldID))
if keyword != "" {
kw := keyword
q = q.Where(role.Or(role.NameContainsFold(kw), role.CodeContainsFold(kw)))
}
return q.All(ctx)
}
type PermissionReq struct {
@@ -109,6 +109,9 @@ type FrontDashboard struct {
Trends FrontTrends `json:"trends"`
// Alarms 仅用于前端语音播报(D2),不渲染到屏幕(报喜不报忧)。
Alarms []AlarmItem `json:"alarms"`
// RefreshSeconds 看板轮询兜底刷新间隔(秒,1~10),由 dashboard.refresh.seconds 配置驱动;
// 仅影响 SSE 实时通道不可用时的 HTTP 轮询周期,SSE 可用时不依赖此值。
RefreshSeconds int `json:"refreshSeconds"`
}
// DashboardFrontSnapshot 看板前端快照:富聚合 → 前端契约映射,走同一缓存(60s + 防击穿)。
@@ -118,7 +121,9 @@ func (s *Service) DashboardFrontSnapshot(ctx context.Context) (*FrontDashboard,
if err != nil {
return nil, err
}
return mapFrontDashboard(rich), nil
f := mapFrontDashboard(rich)
f.RefreshSeconds = s.CfgInt(ctx, CfgDashboardRefreshSeconds, 5)
return f, nil
})
}
@@ -193,6 +193,14 @@ func (s *Service) CreateInspection(ctx context.Context, req InspectionReq, opera
}
}
// B2.3 检验不合格 → 触发 inspection_ng 预警(事件触发型,enabled 即命中,忽略阈值):
// 仅结论 NG 时触发;走 Evaluate 经 alert_rule(enabled) 门控,与拧紧/库存/超期预警同一框架。
if result == "NG" {
s.Evaluate(ctx, "inspection_ng", 1, "检验不合格",
"检验记录不合格:类型="+category+" SN="+req.Sn+" 工位"+string(req.StationNo),
"inspection_record", req.Sn, req.OrderNo)
}
// 完工检(FINAL)结论触发成品回流入库(方案A:完工检合格才入库,完工确认仅代表生产完成):
// 已通过→入库(合格)、部分通过→入库(合格)、不合格/报废→不入库待返修;
// WMS 调用结果以提示透出,不阻断检验留痕(与上方库存联动同降级策略)。
+15 -5
View File
@@ -147,10 +147,12 @@ func materialUpsertOf(m *ent.Material) wmsclient.MaterialUpsert {
}
}
// pushMaterialToWMS 推单行到 WMS(同步调用):成功清 sync_pending,失败置位等待重推(不 panic)。
// pushMaterialToWMS 推单行到 WMS(同步调用):成功清 sync_pending,失败置位并记入事件日志(不再自动重推,改为页面手动推送)。
func (s *Service) pushMaterialToWMS(ctx context.Context, m *ent.Material) error {
if err := s.ctx.Wms.UpsertMaterialToWMS(ctx, materialUpsertOf(m)); err != nil {
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(true).Exec(ctx)
payload := map[string]any{"code": m.Code, "error": err.Error()}
s.ctx.EventLog.Write(ctx, "material.sync.failed", "", "", "material", m.Code, "推送物料到 WMS 失败", payload)
return err
}
_ = s.ctx.EntClient.Material.UpdateOneID(m.ID).SetSyncPending(false).Exec(ctx)
@@ -174,7 +176,7 @@ func (s *Service) RetryPendingMaterialPushes(ctx context.Context) int {
return okCnt
}
// RetryPendingMaterialPushesAsync 异步重推(列表请求顺带触发,不阻塞响应,失败静默)。
// RetryPendingMaterialPushesAsync 异步重推(保留供管理员「重推全部」使用;列表请求不再自动触发)。
func (s *Service) RetryPendingMaterialPushesAsync() {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
@@ -185,6 +187,15 @@ func (s *Service) RetryPendingMaterialPushesAsync() {
}()
}
// RetryProductTypeSync 手动重推单行物料到 WMS(页面「手动推送」按钮触发,替代原列表自动重推)。
func (s *Service) RetryProductTypeSync(ctx context.Context, id int) error {
m, err := s.ctx.EntClient.Material.Get(ctx, id)
if err != nil {
return err
}
return s.pushMaterialToWMS(ctx, m)
}
// PullMaterialsFromWMSAsync 从 WMS 全量分页拉取物料 upsert 到本地(M7 冷启动补齐)。
// 仅在本地为空时调用——若本地已有 pending 行,说明本地存在未推 WMS 的改动,禁止被 WMS 旧值覆盖。
// 失败静默记日志,不阻塞用户。
@@ -219,8 +230,8 @@ func (s *Service) PullMaterialsFromWMSAsync() {
}()
}
// EnsureMaterialCacheAsync 列表请求顺带的缓存维护(M3/M7):本地为空才异步全量拉取;重推 pending 行。
// 均为异步,不阻塞响应。
// EnsureMaterialCacheAsync 列表请求顺带的缓存维护(M7):本地为空才异步全量拉取补齐。
// 不再自动重推 sync_pending 行(改为页面「手动推送」按钮触发),避免静默重试掩盖同步故障。
func (s *Service) EnsureMaterialCacheAsync() {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -230,5 +241,4 @@ func (s *Service) EnsureMaterialCacheAsync() {
s.PullMaterialsFromWMSAsync()
}
}()
s.RetryPendingMaterialPushesAsync()
}
+15 -23
View File
@@ -52,7 +52,7 @@ type FlowVO struct {
// ListFlows 查询工艺流程(可按工位号过滤:只认「工位绑定」页的绑定关系 station.flow_id;
// pp 非空时按引用该工艺的产品工艺名称反查过滤)。page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page, pageSize int) (any, error) {
func (s *Service) ListFlows(ctx context.Context, stationNo int, pp, name, status string, stepMin, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProcessFlow.Query().
Order(ent.Asc(processflow.FieldID))
flows, err := q.All(ctx)
@@ -82,6 +82,14 @@ func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page,
continue
}
}
// 名称模糊过滤(大小写无关)
if name != "" && !strings.Contains(strings.ToLower(f.Name), strings.ToLower(name)) {
continue
}
// 状态过滤(ACTIVE/INACTIVE,空=全部)
if status != "" && f.Status != status {
continue
}
vo := &FlowVO{
Id: f.ID, Name: f.Name,
PdfFile: f.PdfFile, Status: f.Status, Remark: f.Remark,
@@ -93,6 +101,10 @@ func (s *Service) ListFlows(ctx context.Context, stationNo int, pp string, page,
if vo.ProductProcesses = ppNames[f.ID]; vo.ProductProcesses == nil {
vo.ProductProcesses = []string{}
}
// 工序数下限过滤(stepMin>0 时只保留工序数≥阈值者)
if stepMin > 0 && len(vo.Steps) < stepMin {
continue
}
// 产品工艺反查过滤(模糊,大小写无关)
if pp != "" && !ppContainsFold(vo.ProductProcesses, pp) {
continue
@@ -331,12 +343,6 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri
ve.Add("name", "请填写工位名称", "在「工位名称」输入框填写名称后保存")
}
stype := "LINE"
if req.StationType != nil {
stype = *req.StationType
if stype != "LINE" && stype != "OFFLINE" {
ve.Add("stationType", "工位类型仅支持 线上位(LINE)/线下位(OFFLINE)", "类型改为 LINE(连 PLC)或 OFFLINE(不连 PLC)")
}
}
if req.FlowId != nil && *req.FlowId > 0 {
flow, fErr := s.ctx.EntClient.ProcessFlow.Get(ctx, *req.FlowId)
if fErr != nil {
@@ -368,14 +374,6 @@ func (s *Service) SaveStation(ctx context.Context, req StationReq, operator stri
}
// 更新分支:字段错误 + 规则3守卫(托盘在位/在途指令)全部收集,一次性返回
ve := verr.New()
if req.StationType != nil {
t := *req.StationType
if t != "LINE" && t != "OFFLINE" {
ve.Add("stationType", "工位类型仅支持 线上位(LINE)/线下位(OFFLINE)", "类型改为 LINE(连 PLC)或 OFFLINE(不连 PLC)")
} else if st.IsBuiltin && t != st.StationType {
ve.Add("stationType", "内置工位不允许修改工位类型", "内置工位对应实体产线固定位置(连 PLC、按顺序流转),只能改名称/绑定/终端页签")
}
}
// 仅改名称:flowId 不传(nil)保留原绑定;0=解绑;>0=绑定指定启用流程。
// 规则3(2026-10-20 拍板,2026-10-20 下午改 fail-closed→fail-open):改绑定关系(含解绑)前,
// 过「在途指令/托盘在位」双检(两条同时收集,不串行)。
@@ -420,14 +418,8 @@ if req.FlowId != nil {
if err := ve.OrNil(); err != nil {
return err
}
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
if req.StationType != nil {
t := *req.StationType
if !st.IsBuiltin {
upd.SetStationType(t)
}
}
if req.FlowId != nil {
upd := s.ctx.EntClient.Station.UpdateOneID(st.ID).SetName(req.Name)
if req.FlowId != nil {
upd.SetFlowId(bindFlow) // 0=解绑
}
// 终端可见页签:传 nil=不改;传空数组=清空(全部显示);传列表=按配置显示
+19 -1
View File
@@ -70,7 +70,7 @@ type ProductProcessVO struct {
// ListProductProcesses 产品工艺列表(分页;筛选:产品编码/状态/工艺反查/关键字)。
// page>0 真分页返回 map{total,list,page,pageSize};page=0 返回全量数组(工单页下拉用)。
func (s *Service) ListProductProcesses(ctx context.Context, productCode, status string, flowId int, keyword string, page, pageSize int) (any, error) {
func (s *Service) ListProductProcesses(ctx context.Context, productCode, status string, flowId int, keyword, name string, stepMin, stepMax int, page, pageSize int) (any, error) {
q := s.ctx.EntClient.ProductProcess.Query()
if productCode != "" {
q = q.Where(productprocess.ProductCodeContainsFold(productCode))
@@ -86,6 +86,9 @@ func (s *Service) ListProductProcesses(ctx context.Context, productCode, status
)
q = q.Where(kw)
}
if name != "" {
q = q.Where(productprocess.NameContainsFold(name))
}
// 工艺反查:只要包含该工艺的产品工艺
if flowId > 0 {
items, err := s.ctx.EntClient.ProductProcessItem.Query().
@@ -161,6 +164,21 @@ func (s *Service) ListProductProcesses(ctx context.Context, productCode, status
vo.Executable, vo.NotReady = ppExecutable(vo)
out = append(out, vo)
}
// 工序数范围过滤:按产品工艺的工艺顺序/工序条目数(vo.Flows 长度)
if stepMin > 0 || stepMax > 0 {
kept := make([]*ProductProcessVO, 0, len(out))
for _, vo := range out {
n := len(vo.Flows)
if stepMin > 0 && n < stepMin {
continue
}
if stepMax > 0 && n > stepMax {
continue
}
kept = append(kept, vo)
}
out = kept
}
if page > 0 {
total := len(out)
start := (page - 1) * pageSize
+24 -7
View File
@@ -291,21 +291,38 @@ func (s *Service) Seed(ctx context.Context) error {
}
// seedAlertRules 预警规则占位(幂等):按 type 幂等插入,已有行(含人工改过的阈值/启用态)一律不动。
// 常用类型:torque_ng=拧紧扭矩不合格 / inspection_ng=检验不合格 / inventory_low=库存低于阈值 / task_overdue=任务超期。
// 常用类型:inspection_ng=检验不合格 / inventory_low=库存低于阈值 / task_overdue=任务超期。
func seedAlertRules(ctx context.Context, s *Service) {
placeholders := []struct{ typ, name string }{
{"torque_ng", "拧紧扭矩不合格预警"},
{"inspection_ng", "检验不合格预警"},
{"inventory_low", "库存低于阈值预警"},
{"task_overdue", "任务超期预警"},
// 存量 torque_ng 规则保留历史但置为禁用:拧紧报警已改由基础配置 torque.ng.alert.enabled 开关控制(B2.2),
// 不再走预警规则表;不删除,便于追溯。
if _, err := s.ctx.EntClient.AlertRule.Update().
Where(alertrule.Type("torque_ng")).SetEnabled(false).Save(ctx); err != nil {
_ = err // 表为空时影响 0 行属正常,非致命
}
// inspection_ng 默认启用(事件触发型,出现检验不合格即报警,阈值不使用);
// inventory_low / task_overdue 默认停用(占位,由实施按需启用)。
placeholders := []struct {
typ string
name string
enabled bool
}{
{"inspection_ng", "检验不合格预警", true},
{"inventory_low", "库存低于阈值预警", false},
{"task_overdue", "任务超期预警", false},
}
for _, p := range placeholders {
// B2.3 幂等对齐:占位规则以 seed 定义的启用态为准(inspection_ng 强制启用,inventory_low/task_overdue 默认停用)。
// 既有行一并校正——避免"已存在却被历史 seed 置为禁用"导致检验不合格预警不触发(这正是 B2.3 要修的 bug)。
if ok, _ := s.ctx.EntClient.AlertRule.Query().Where(alertrule.Type(p.typ)).Exist(ctx); ok {
if _, e := s.ctx.EntClient.AlertRule.Update().
Where(alertrule.Type(p.typ)).SetEnabled(p.enabled).Save(ctx); e != nil {
_ = e
}
continue
}
if _, err := s.ctx.EntClient.AlertRule.Create().
SetName(p.name).SetType(p.typ).SetThreshold(0).
SetEnabled(false).SetCreatedBy("seed").Save(ctx); err != nil {
SetEnabled(p.enabled).SetCreatedBy("seed").Save(ctx); err != nil {
continue // 单条失败不阻断其余占位
}
}
+2 -2
View File
@@ -102,6 +102,6 @@ func (s *Service) CountSemiIn(ctx context.Context, sn string) int {
}
// ListEventLogs 操作日志查询(按工单号/操作人;operators 为候选列表,任一命中即算)
func (s *Service) ListEventLogs(ctx context.Context, orderNo string, operators []string, eventType string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
return s.ctx.EventLog.Query(ctx, eventType, orderNo, operators, fromMs, toMs, page, pageSize)
func (s *Service) ListEventLogs(ctx context.Context, orderNo string, operators []string, eventType, entityType string, fromMs, toMs int64, page, pageSize int) ([]*ent.EventLog, int, error) {
return s.ctx.EventLog.Query(ctx, eventType, orderNo, operators, entityType, fromMs, toMs, page, pageSize)
}
+22
View File
@@ -31,6 +31,10 @@ const (
CfgPipelineCache = "pipeline_cache"
// CfgAllowCrossDay 允许叫非今日排产的料(B5 跨日:1=允许(默认,工位端预警提示),0=禁止)
CfgAllowCrossDay = "call.allow_cross_day"
// CfgTorqueNgAlert 拧紧不合格报警开关(B2.1):1=开启(默认,拧紧扭矩不合格立即落预警),0=关闭(只写 step_data + 置待处置标记,不落预警)
CfgTorqueNgAlert = "torque.ng.alert.enabled"
// CfgDashboardRefreshSeconds 看板大屏轮询兜底刷新间隔(秒,1~10):仅影响 SSE 实时通道不可用时的 HTTP 轮询周期(默认 5)
CfgDashboardRefreshSeconds = "dashboard.refresh.seconds"
)
// startedAt 服务启动时刻(本机信息展示用)
@@ -46,6 +50,8 @@ type SettingsVO struct {
LogRetentionDays int `json:"logRetentionDays"` // 事件日志保留天数(0=不清理)
PipelineCache int `json:"pipelineCache"` // 滚筒线缓存模式(1=缓存并行,0=串行;预留,PLC 真机接入时生效)
AllowCrossDay int `json:"allowCrossDay"` // 允许叫非今日排产的料(1=允许(默认),0=禁止)
TorqueNgAlert bool `json:"torqueNgAlert"` // 拧紧不合格报警开关(1=开启,0=关闭)
DashboardRefreshSeconds int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,1~10)
// 本机基础信息(只读)
LocalIPs []string `json:"localIPs"` // 本机内网 IPv4 列表
@@ -65,6 +71,8 @@ type SettingsReq struct {
LogRetentionDays *int `json:"logRetentionDays"`
PipelineCache *int `json:"pipelineCache"`
AllowCrossDay *int `json:"allowCrossDay"`
TorqueNgAlert *bool `json:"torqueNgAlert"` // B2.1 拧紧不合格报警开关(nil=不改)
DashboardRefreshSeconds *int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,nil=不改)
}
// defaults 建议默认值(未配置时生效)
@@ -75,6 +83,8 @@ var settingsDefaults = map[string]int{
CfgLogRetention: 0,
CfgPipelineCache: 0,
CfgAllowCrossDay: 1,
CfgTorqueNgAlert: 1, // B2.1 默认开启拧紧不合格报警
CfgDashboardRefreshSeconds: 5, // 看板轮询兜底刷新间隔(秒)
}
// GetSettings 读取基础设置 + 本机信息。DB 读失败时按默认值返回(设置页必须能打开)。
@@ -93,6 +103,8 @@ func (s *Service) GetSettings(ctx context.Context) (*SettingsVO, error) {
LogRetentionDays: cfgIntFrom(kv, CfgLogRetention),
PipelineCache: cfgIntFrom(kv, CfgPipelineCache),
AllowCrossDay: cfgIntFrom(kv, CfgAllowCrossDay),
TorqueNgAlert: s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1, // B2.1 默认开启
DashboardRefreshSeconds: cfgIntFrom(kv, CfgDashboardRefreshSeconds),
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),
@@ -126,6 +138,7 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st
{CfgLogRetention, req.LogRetentionDays, 0, 3650, "事件日志保留天数(0=不清理)"},
{CfgPipelineCache, req.PipelineCache, 0, 1, "滚筒线缓存模式(1=启用缓存位并行流转,0=串行不缓存);预留配置,PLC 真机接入时生效"},
{CfgAllowCrossDay, req.AllowCrossDay, 0, 1, "允许叫非今日排产的料(1=允许,工位端预警提示;0=禁止)"},
{CfgDashboardRefreshSeconds, req.DashboardRefreshSeconds, 1, 10, "看板轮询兜底刷新间隔(秒,1~10,仅 SSE 不可用时的 HTTP 轮询周期)"},
}
for _, it := range items {
if it.val == nil {
@@ -138,6 +151,15 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st
return err
}
}
if req.TorqueNgAlert != nil {
v := 0
if *req.TorqueNgAlert {
v = 1
}
if err := s.upsertConfig(ctx, CfgTorqueNgAlert, strconv.Itoa(v), "拧紧不合格报警开关(1=开启,0=关闭)"); err != nil {
return err
}
}
if req.WmsBaseURL != nil {
u := strings.TrimSpace(*req.WmsBaseURL)
if err := s.upsertConfig(ctx, CfgWmsBaseURL, u, "WMS 服务地址(保存即生效)"); err != nil {
+13 -1
View File
@@ -102,7 +102,19 @@ func (s *Service) evaluateTorqueCriterion(ctx context.Context, sn, stationNo str
SetTorqueNgPending(true).SetTorqueNgAt(time.Now()).SetTorqueNgBy(operator).Save(ctx); e != nil {
log.Printf("[torque] 置拧紧不合格标记失败 sn=%s: %v", sn, e)
}
s.Evaluate(ctx, "torque_ng", 1, "拧紧扭矩不合格", "SN="+sn+" 工位"+stationNo, "torque_record", sn, orderNo)
// B2.1 拧紧报警改由基础配置 torque.ng.alert.enabled 开关控制(不再走预警规则表):
// 开关开启(默认) → 直接 CreateAlert 落预警(绕过 Evaluate 的阈值比较);
// 开关关闭 → 只写 step_data + 置 torque_ng_pending(已在上面完成),不落 alert。
if s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1 {
// 直写预警(绕过 Evaluate 阈值比较);target 含「工位N」供终端按工位过滤,message 带工单号便于中心检索
msg := "拧紧扭矩不合格:SN=" + sn + " 工位" + stationNo
if orderNo != "" {
msg += " 工单" + orderNo
}
if err := s.CreateAlert(ctx, "torque_ng", "critical", "SN="+sn+" 工位"+stationNo, msg); err != nil {
log.Printf("[torque] 写拧紧不合格预警失败 sn=%s: %v", sn, err)
}
}
}
}
+1 -1
View File
@@ -427,7 +427,7 @@ func (c *Client) MaterialQuery(ctx context.Context, code, batch string) (map[str
}
// StockAvailable 批量查询物料可用量(调 WMS /api/internal/stock/check,qty 传 0 只取可用量)。
// 返回 materialCode → availQty。用于 MES 侧计算可生产数量(BOM 单台用量在 MES、库存可用量在 WMS)。
// 返回 materialCode → availQty。用于 MES 侧计算可生产数量(物料清单单台用量在 MES、库存可用量在 WMS)。
func (c *Client) StockAvailable(ctx context.Context, codes []string) (map[string]int, error) {
items := make([]map[string]any, 0, len(codes))
for _, code := range codes {