import { ref, reactive, computed, onMounted } from 'vue'
+import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'
import { can } from '../utils/perm'
@@ -432,7 +446,51 @@ async function openDetail(row) {
}
}
-const dialog = reactive({ show: false, id: 0, workOrderNo: '', productTypeId: 0, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', status: 'CREATED' })
+const dialog = reactive({ show: false, id: 0, workOrderNo: '', productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', status: 'CREATED', productProcessId: 0 })
+
+// ---------- 产品工艺(2026-10-09):建单选产品自动带出默认产品工艺,自动填工艺组合(快捷选择+偏差提示) ----------
+const productProcesses = ref([])
+const ppWarnings = ref([])
+const router = useRouter()
+// 工单不嵌路线卡(客户裁定):想看定义层就跳「产品工艺」页查看/打印路线卡
+function goProductProcess() {
+ router.push('/product-process')
+}
+
+async function loadProductProcesses() {
+ productProcesses.value = []
+ dialog.productProcessId = 0
+ ppWarnings.value = []
+ if (!dialog.productCode) return
+ try {
+ productProcesses.value = (await request.get('/product-processes', { params: { productCode: dialog.productCode, status: 'ACTIVE' } })) || []
+ } catch {
+ productProcesses.value = []
+ }
+ if (productProcesses.value.length) {
+ const d = productProcesses.value.find((x) => x.isDefault) || productProcesses.value[0]
+ dialog.productProcessId = d.id
+ await applyProductProcess(d.id)
+ } else {
+ ppWarnings.value = ['该产品尚未配置产品工艺(可在「产品工艺」页创建),工艺组合需手动勾选']
+ }
+}
+
+// 选产品工艺 → 自动推导:每道工艺的全部启用工位填入组合(与既有勾选模型一致,可手改)
+async function applyProductProcess(id) {
+ ppWarnings.value = []
+ if (!id) return
+ try {
+ const d = await request.get('/product-processes/derive', { params: { id } })
+ if (!d) return
+ ppWarnings.value = d.warnings || []
+ const enabled = new Set(stations.value.filter((s) => s.flowId > 0 && s.status === 'ENABLED').map((s) => s.stationNo))
+ const nos = (d.combination || []).map((c) => c.stationNo).filter((n) => enabled.has(n))
+ selStations.value = [...new Set(nos)].sort((a, b) => a - b)
+ } catch {
+ // 拦截器已提示
+ }
+}
async function load() {
const [dueFrom, dueTo] = query.dueRange || []
@@ -453,6 +511,7 @@ function genOrderNo() {
return `WO-${ymd}-001`
}
// Q1=A:选产品型号后自动带出图号/名称(只读,避免手填错位;图号=产品编码,同值)
+// 2026-10-09:同时带出该产品的产品工艺(默认优先),自动填工艺组合
function onProductTypeChange(id) {
const p = productTypes.value.find((x) => x.id === id)
if (p) {
@@ -462,16 +521,29 @@ function onProductTypeChange(id) {
dialog.productCode = ''
dialog.productName = ''
}
+ loadProductProcesses()
}
function openCreate() {
- Object.assign(dialog, { show: true, id: 0, workOrderNo: genOrderNo(), productTypeId: 0, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', status: 'CREATED' })
+ Object.assign(dialog, { show: true, id: 0, workOrderNo: genOrderNo(), productTypeId: null, productCode: '', productName: '', contractNo: '', ownershipType: '', productSerial: '', quantity: 1, dueDate: '', planStart: '', status: 'CREATED', productProcessId: 0 })
+ productProcesses.value = []
+ ppWarnings.value = []
selStations.value = defaultSelStations()
}
-function openEdit(row) {
- Object.assign(dialog, { show: true, id: row.id, workOrderNo: row.workOrderNo, productTypeId: row.productTypeId, productCode: row.productCode, productName: row.productName, contractNo: row.contractNo || '', ownershipType: row.ownershipType || '', productSerial: row.productSerial || '', quantity: row.quantity, dueDate: row.dueDate ? String(row.dueDate).slice(0, 10) : '', planStart: row.planStart ? String(row.planStart).slice(0, 10) : '', status: row.status })
+async function openEdit(row) {
+ Object.assign(dialog, { show: true, id: row.id, workOrderNo: row.workOrderNo, productTypeId: row.productTypeId, productCode: row.productCode, productName: row.productName, contractNo: row.contractNo || '', ownershipType: row.ownershipType || '', productSerial: row.productSerial || '', quantity: row.quantity, dueDate: row.dueDate ? String(row.dueDate).slice(0, 10) : '', planStart: row.planStart ? String(row.planStart).slice(0, 10) : '', status: row.status, productProcessId: row.productProcessId || 0 })
selStations.value = hasCombination(row)
? [...new Set(row.flowCombination.map((c) => c.stationNo))].sort((a, b) => a - b)
: defaultSelStations()
+ // 编辑:只带出该产品可选的产品工艺(不自动重填组合,保留已保存的组合)
+ productProcesses.value = []
+ ppWarnings.value = []
+ if (row.productCode) {
+ try {
+ productProcesses.value = (await request.get('/product-processes', { params: { productCode: row.productCode, status: 'ACTIVE' } })) || []
+ } catch {
+ productProcesses.value = []
+ }
+ }
}
async function save() {
if (!dialog.dueDate) return ElMessage.warning('请选择完成日期(必填)')
@@ -482,10 +554,18 @@ async function save() {
}
// 建单不强制工艺组合(工单≠开工):排产/开工时由后端校验组合非空
if (!flowCombination.value.length) ElMessage.warning('未选择工艺组合:排产/开工前须配置')
- const body = { id: dialog.id, workOrderNo: dialog.workOrderNo, productTypeId: dialog.productTypeId, productCode: dialog.productCode, productName: dialog.productName, contractNo: dialog.contractNo, ownershipType: dialog.ownershipType, productSerial: dialog.productSerial, quantity: dialog.quantity, dueDate: dialog.dueDate, planStart: dialog.planStart, flowCombination: flowCombination.value }
- if (dialog.id) await request.put('/work-orders', body)
- else await request.post('/work-orders', body)
+ const body = { id: dialog.id, workOrderNo: dialog.workOrderNo, productTypeId: dialog.productTypeId, productCode: dialog.productCode, productName: dialog.productName, contractNo: dialog.contractNo, ownershipType: dialog.ownershipType, productSerial: dialog.productSerial, quantity: dialog.quantity, dueDate: dialog.dueDate, planStart: dialog.planStart, flowCombination: flowCombination.value, productProcessId: dialog.productProcessId || 0 }
+ let resp = null
+ if (dialog.id) resp = await request.put('/work-orders', body)
+ else resp = await request.post('/work-orders', body)
ElMessage.success('保存成功')
+ // 产品工艺偏差警告(仅提示不阻断,2026-10-09 定稿:覆盖/顺序/个数不符时警告提示)
+ const ws = (resp && resp.warnings) || []
+ if (ws.length) {
+ ElMessageBox.alert(ws.map((w, i) => (i + 1) + '. ' + w).join('\n'), '与产品工艺存在偏差(已保存)', {
+ type: 'warning', confirmButtonText: '知道了'
+ }).catch(() => {})
+ }
dialog.show = false
load()
}
diff --git a/bj_power_mes/frontend/src/router/index.js b/bj_power_mes/frontend/src/router/index.js
index f2316e4..182fdd8 100644
--- a/bj_power_mes/frontend/src/router/index.js
+++ b/bj_power_mes/frontend/src/router/index.js
@@ -15,6 +15,7 @@ const routes = [
{ path: 'qty-report', name: 'QtyReport', component: () => import('../pages/QtyReport.vue'), meta: { title: '数量不符处理' } },
{ path: 'plc-send', name: 'PlcSend', component: () => import('../pages/PlcSend.vue'), meta: { title: '工位组合下发' } },
{ path: 'process-flow', name: 'ProcessFlow', component: () => import('../pages/ProcessFlow.vue'), meta: { title: '工艺' } },
+ { path: 'product-process', name: 'ProductProcess', component: () => import('../pages/ProductProcess.vue'), meta: { title: '产品工艺' } },
{ path: 'station', name: 'Station', component: () => import('../pages/Station.vue'), meta: { title: '工位绑定' } },
{ path: 'dock', name: 'Dock', component: () => import('../pages/Dock.vue'), meta: { title: '接驳台维护' } },
{ path: 'performance', name: 'Performance', component: () => import('../pages/Performance.vue'), meta: { title: '绩效报表' } },
@@ -25,6 +26,7 @@ const routes = [
{ 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: 'audit-pending', name: 'AuditPending', component: () => import('../pages/AuditPending.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: '操作日志' } },
{ path: 'change-password', name: 'ChangePassword', component: () => import('../pages/ChangePassword.vue'), meta: { title: '修改密码' } },
diff --git a/bj_power_mes/frontend/src/utils/request.js b/bj_power_mes/frontend/src/utils/request.js
index 46fe6f9..02f6586 100644
--- a/bj_power_mes/frontend/src/utils/request.js
+++ b/bj_power_mes/frontend/src/utils/request.js
@@ -4,6 +4,19 @@ import { getToken, setSession, getUser, logout } from './auth'
const request = axios.create({ baseURL: '/api/v1', timeout: 30000 })
+// 业务化报错:把底层网络/连接/服务不可达等技术错误翻译成业务人员能看懂的提示;
+// 详细技术信息由后端 EventLog 与框架日志记录,不暴露给前端用户。
+function friendlyMsg(raw) {
+ if (!raw || typeof raw !== 'string') return '操作失败,请稍后重试'
+ if (/dial tcp|connectex|connection could be made|refused|ECONNREFUSED|ETIMEDOUT|127\.0\.0\.1|Post "http|Get "http|WMS 未配置|拉取 WMS|无法获取 WMS/i.test(raw)) {
+ return '无法连接 WMS 服务(服务未启动或网络不可达),相关功能暂不可用;请检查 WMS 服务状态或联系管理员'
+ }
+ if (/Network Error|Failed to fetch|ERR_NETWORK|ERR_CONNECTION|网络异常|网络连接/i.test(raw)) {
+ return '网络连接异常,请检查网络后重试或联系管理员'
+ }
+ return raw
+}
+
request.interceptors.request.use((config) => {
const token = getToken()
if (token) config.headers.Authorization = `Bearer ${token}`
@@ -18,8 +31,9 @@ request.interceptors.response.use(
const body = resp.data
if (body && typeof body === 'object' && 'code' in body) {
if (body.code !== 0) {
- ElMessage.error(body.message || '操作失败')
- return Promise.reject(new Error(body.message || '操作失败'))
+ const msg = friendlyMsg(body.message || '操作失败')
+ ElMessage.error(msg)
+ return Promise.reject(new Error(msg))
}
return body.data !== undefined ? body.data : body
}
@@ -32,7 +46,7 @@ request.interceptors.response.use(
ElMessage.error('登录已失效,请重新登录')
if (!window.location.pathname.startsWith('/login')) window.location.href = '/login'
} else {
- const msg = error.response?.data?.message || error.message || '网络错误'
+ const msg = friendlyMsg(error.response?.data?.message || error.message || '网络错误')
ElMessage.error(msg)
}
return Promise.reject(error)
diff --git a/bj_power_mes/internal/db/db.go b/bj_power_mes/internal/db/db.go
index 1218387..2fd9994 100644
--- a/bj_power_mes/internal/db/db.go
+++ b/bj_power_mes/internal/db/db.go
@@ -263,6 +263,15 @@ var schemaPatchSQL = []string{
// 历史库若已存在 delegate_id 列则删除,保持无遗留字段。
`ALTER TABLE workpiece_process DROP COLUMN IF EXISTS delegate_id`,
`ALTER TABLE torque_record DROP COLUMN IF EXISTS delegate_id`,
+
+ // ---- 工艺步骤审核(2026-10-08 定稿):need_audit 开关 + audit_role 审核角色(既有库补列,
+ // 上轮经 migrateonce 落库但漏挂本补丁清单,此处补齐防新装库遗漏)----
+ `ALTER TABLE process_step ADD COLUMN IF NOT EXISTS need_audit boolean NOT NULL DEFAULT false`,
+ `ALTER TABLE process_step ADD COLUMN IF NOT EXISTS audit_role varchar(64) NOT NULL DEFAULT ''`,
+
+ // ---- 产品工艺(2026-10-09 定稿):产品级工艺定义(有序工艺集合,不绑工位)----
+ // 两张新表由 ent Schema.Create 建出;此处只补既有表 work_order 的来源列。
+ `ALTER TABLE work_order ADD COLUMN IF NOT EXISTS product_process_id integer NOT NULL DEFAULT 0`,
}
// EnsureSchema ent 建表 + 幂等列补丁(只增,不删数据)
diff --git a/bj_power_mes/internal/handler/processcard.go b/bj_power_mes/internal/handler/processcard.go
deleted file mode 100644
index b1ebb89..0000000
--- a/bj_power_mes/internal/handler/processcard.go
+++ /dev/null
@@ -1,339 +0,0 @@
-package handler
-
-import (
- "bytes"
- "context"
- "fmt"
- "html/template"
- "net/http"
- "strings"
-
- "bj_power_mes/common/httpx"
- "bj_power_mes/ent"
- "bj_power_mes/ent/associationtrace"
- "bj_power_mes/ent/processstep"
- "bj_power_mes/ent/station"
- "bj_power_mes/ent/stepdata"
- "bj_power_mes/ent/torquerecord"
- "bj_power_mes/ent/workorder"
- "bj_power_mes/ent/workpiece"
- "bj_power_mes/ent/workpieceprocess"
- "bj_power_mes/internal/logic"
- "bj_power_mes/internal/svc"
-)
-
-// ProcessCardHandler GET /api/v1/process-card?sn=xxx
-// 按 SN 生成可打印流程卡。数据经工单联查(产品名称/数量),工序时间线补全操作人与完成时间,
-// 拧紧数据(如有拧紧步骤)渲染到卡尾。
-// 带 ?check=1 时返回 JSON {missing:[缺失项…]} 供前端"打印前预检"弹窗,不渲染 HTML。
-func ProcessCardHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- sn := strings.TrimSpace(r.URL.Query().Get("sn"))
- if sn == "" {
- httpx.BadRequest(w, "缺少 sn 参数")
- return
- }
- card, missing, err := buildCard(r.Context(), svcCtx, sn)
- if err != nil {
- httpx.Fail(w, 2401, err.Error())
- return
- }
- if r.URL.Query().Get("check") == "1" {
- httpx.Ok(w, map[string]any{"sn": sn, "missing": missing})
- return
- }
- html, err := renderProcessCard(card)
- if err != nil {
- httpx.Fail(w, 2402, "流程卡生成失败:"+err.Error())
- return
- }
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- _, _ = w.Write([]byte(html))
- }
-}
-
-type cardProcess struct {
- ID int
- Code string
- Name string
- Station string
- Operator string
- Status string
- Result string
- DoneTime string
- Steps []cardStep
-}
-
-type cardStep struct {
- Name string
- Value string
- OK bool
-}
-
-type cardTorque struct {
- ScrewNo string
- Torque string
- Angle string
- Result string
- Operator string
- Time string
-}
-
-type cardTmpl struct {
- Sn string
- OrderNo string
- Product string
- Quantity int
- CreatedAt string
- Processes []cardProcess
- Materials []string
- Operator string
- Inspector string
- DoneTime string
- Result string
- NeedTorque bool
- TorqueRows []cardTorque
-}
-
-// buildCard 汇总流程卡所需全部数据(ent 实体直查),并计算缺失项。
-// missing 非空时表示存在数据不完整,前端应提示"是否继续打印"。
-func buildCard(ctx context.Context, svcCtx *svc.ServiceContext, sn string) (*cardTmpl, []string, error) {
- client := svcCtx.EntClient
- wp, err := client.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx)
- if err != nil {
- return nil, nil, fmt.Errorf("该SN无追溯数据")
- }
- t := &cardTmpl{Sn: sn, Result: "待完工", NeedTorque: false}
- missing := []string{}
-
- if wp.OrderNo == "" {
- missing = append(missing, "工单号")
- } else {
- t.OrderNo = wp.OrderNo
- }
- t.CreatedAt = wp.CreatedAt.Format("2006-01-02 15:04")
-
- // 产品信息:工件 → 工单 联查(修复 wp.productType 恒空 bug)
- var wo *ent.WorkOrder
- if t.OrderNo != "" {
- wo, _ = client.WorkOrder.Query().Where(workorder.WorkOrderNo(t.OrderNo)).First(ctx)
- }
- if wo != nil {
- t.Product = wo.ProductName
- if wo.ProductName == "" {
- t.Product = wo.ProductCode
- }
- t.Quantity = wo.Quantity
- }
- if t.Product == "" {
- missing = append(missing, "产品名称")
- }
- if wo == nil || t.Quantity <= 0 {
- missing = append(missing, "产品数量")
- }
-
- // 工艺时间线(操作人 + 完成时间)
- procs, _ := client.WorkpieceProcess.Query().
- Where(workpieceprocess.Sn(sn)).Order(ent.Asc(workpieceprocess.FieldFlowId), ent.Asc(workpieceprocess.FieldID)).All(ctx)
- for _, p := range procs {
- doneAt := ""
- if p.EndedAt != nil {
- doneAt = p.EndedAt.Format("2006-01-02 15:04")
- }
- flowLabel := p.ProcessName
- if flowLabel == "" {
- flowLabel = "工艺" + itoaCard(p.FlowId)
- }
- if p.Operator == "" {
- missing = append(missing, fmt.Sprintf("工艺「%s」报工记录(缺操作人)", flowLabel))
- }
- if p.EndedAt == nil {
- missing = append(missing, fmt.Sprintf("工艺「%s」报工记录(缺完成时间)", flowLabel))
- }
- cp := cardProcess{
- ID: p.ID,
- Code: p.StationNo,
- Name: p.ProcessName,
- Station: p.StationNo,
- Operator: p.Operator,
- Status: p.Status,
- Result: p.Result,
- DoneTime: doneAt,
- }
- if p.Result == "NG" {
- t.Result = "NG"
- }
- t.Processes = append(t.Processes, cp)
- }
- if len(procs) == 0 {
- missing = append(missing, "报工记录")
- }
-
- // 步骤考核数据按工序实绩 ID 归组,回填到对应工序行的"采集参数"
- steps, _ := client.StepData.Query().Where(stepdata.Sn(sn)).All(ctx)
- stepByProc := map[int][]cardStep{}
- for _, s := range steps {
- stepByProc[s.ProcessId] = append(stepByProc[s.ProcessId], cardStep{Name: s.StepName, Value: s.ValueText, OK: s.IsOK})
- }
- for i := range t.Processes {
- t.Processes[i].Steps = stepByProc[t.Processes[i].ID]
- }
-
- // 拧紧数据:工件所属流程含 isTorque 步骤时判定"需要拧紧数据"
- needTorque := hasTorqueStep(ctx, client, sn, wp)
- t.NeedTorque = needTorque
- torque, _ := client.TorqueRecord.Query().
- Where(torquerecord.Sn(sn)).Order(ent.Desc(torquerecord.FieldTime)).Limit(200).All(ctx)
- for _, q := range torque {
- t.TorqueRows = append(t.TorqueRows, cardTorque{
- ScrewNo: q.ScrewNo, Torque: fmt.Sprintf("%.2f", q.Torque),
- Angle: fmt.Sprintf("%.2f", q.Angle), Result: q.Result,
- Operator: q.Operator, Time: q.Time.Format("2006-01-02 15:04:05"),
- })
- }
- if needTorque && len(t.TorqueRows) == 0 {
- missing = append(missing, "拧紧数据")
- }
-
- // 关联物料(批次/电气件SN)
- assoc, _ := client.AssociationTrace.Query().
- Where(associationtrace.FinishedSn(sn)).First(ctx)
- if assoc != nil {
- t.Operator = assoc.Operator
- for _, b := range assoc.BatchItems {
- t.Materials = append(t.Materials, b)
- }
- for _, s := range assoc.SerialItems {
- t.Materials = append(t.Materials, s)
- }
- }
- return t, missing, nil
-}
-
-// hasTorqueStep 判断该工件加工路径上是否存在"拧紧采集"步骤(经 工单工艺组合→工位→流程→步骤 链)
-// 路线 = 工单工艺组合(唯一路线源头)
-func hasTorqueStep(ctx context.Context, client *ent.Client, sn string, wp *ent.Workpiece) bool {
- if wp.WorkOrderId <= 0 {
- return false
- }
- wo, err := client.WorkOrder.Get(ctx, wp.WorkOrderId)
- if err != nil {
- return false
- }
- items, _ := logic.RouteStationsFromWO(ctx, client, wo)
- if len(items) == 0 {
- return false
- }
- stations, err := client.Station.Query().
- Where(station.StationNoIn(logic.RouteStationsOfWO(items)...), station.FlowIdGT(0)).All(ctx)
- if err != nil || len(stations) == 0 {
- return false
- }
- flowIds := make([]int, 0, len(stations))
- for _, st := range stations {
- flowIds = append(flowIds, st.FlowId)
- }
- n, err := client.ProcessStep.Query().
- Where(processstep.FlowIdIn(flowIds...), processstep.IsTorque(true)).Count(ctx)
- if err != nil {
- return false
- }
- return n > 0
-}
-
-func itoaCard(n int) string { return fmt.Sprintf("%d", n) }
-
-func renderProcessCard(t *cardTmpl) (string, error) {
- const tpl = `
-
-
-
-流程卡 {{.Sn}}
-
-
-
-
-
产品流程卡
-
- SN:{{.Sn}}
- 工单号:{{.OrderNo}}
- 产品型号:{{.Product}}
- 数量:{{.Quantity}}
- 登记时间:{{.CreatedAt}}
- 判定:{{if eq .Result "NG"}}NG{{else}}{{.Result}}{{end}}
-
- {{if .Processes}}
-
工艺流转记录
-
- | 工位号 | 工艺名称 | 工位 | 操作人 | 完成时间 | 采集参数 | 结果 |
-
- {{range .Processes}}
-
- | {{.Code}} | {{.Name}} | {{.Station}} | {{.Operator}} | {{.DoneTime}} |
- {{if .Steps}}{{range .Steps}}{{.Name}}={{.Value}}({{if .OK}}OK{{else}}NG{{end}}) {{end}}{{else}}-{{end}} |
- {{if eq .Result "NG"}}NG{{else}}OK{{end}} |
-
- {{end}}
-
-
- {{else}}
-
暂无报工记录。
- {{end}}
- {{if .NeedTorque}}
-
拧紧数据{{if not .TorqueRows}}(无数据){{end}}
- {{if .TorqueRows}}
-
- | 螺丝编号 | 扭矩(N·m) | 角度(°) | 结果 | 操作人 | 时间 |
-
- {{range .TorqueRows}}
-
- | {{.ScrewNo}} | {{.Torque}} | {{.Angle}} |
- {{if eq .Result "NG"}}NG{{else}}OK{{end}} |
- {{.Operator}} | {{.Time}} |
-
- {{end}}
-
-
- {{end}}
- {{end}}
- {{if .Materials}}
-
关联物料/批次:{{range .Materials}}{{.}} {{end}}
- {{end}}
-
-
-
-
-
-
-`
-
- tmpl, err := template.New("card").Parse(tpl)
- if err != nil {
- return "", err
- }
- var buf bytes.Buffer
- if err := tmpl.Execute(&buf, t); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
diff --git a/bj_power_mes/internal/handler/processcard_model.go b/bj_power_mes/internal/handler/processcard_model.go
deleted file mode 100644
index 470cb99..0000000
--- a/bj_power_mes/internal/handler/processcard_model.go
+++ /dev/null
@@ -1,593 +0,0 @@
-package handler
-
-import (
- "bytes"
- "context"
- "fmt"
- "html/template"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "bj_power_mes/common/httpx"
- "bj_power_mes/ent"
- "bj_power_mes/ent/processflow"
- "bj_power_mes/ent/processstep"
- "bj_power_mes/ent/station"
- "bj_power_mes/ent/stepcriterion"
- "bj_power_mes/ent/workorder"
- "bj_power_mes/ent/workpieceprocess"
- "bj_power_mes/internal/logic"
- "bj_power_mes/internal/svc"
- "bj_power_mes/internal/wmsclient"
-)
-
-// ModelProcessCardHandler GET /api/v1/process-card/model?productTypeId=&productCode=[&format=json]
-//
-// 产品型号级「全景流程卡」:与 SN 级流程卡(按单个工件打印实绩)互补,本卡按**产品型号**聚合
-// 该型号的完整制造定义,用于工艺交底/审核/客户查阅:
-//
-// 产品型号 → 工位组合 → 每工位工艺流程与步骤(含采集方式/检测点/拧紧/考核标准/工艺图纸)
-// → 物料清单(按 BOM 分组,含工艺清单/单台用量/损耗/需求总量)
-// → 检验卡项(所有"检测确认"步骤汇总为检验项清单)
-// → 各环节时间(工单计划时间 + 该型号历史实绩的首末作业时间)
-//
-// 默认返回可打印 HTML(浏览器直接打印/另存 PDF);?format=json 返回结构化数据供页面预览。
-func ModelProcessCardHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- q := r.URL.Query()
- productTypeId := atoiDefault(q.Get("productTypeId"), 0)
- productCode := strings.TrimSpace(q.Get("productCode"))
- if productTypeId <= 0 && productCode == "" {
- httpx.BadRequest(w, "请指定产品型号(productTypeId 或 productCode)")
- return
- }
- card, err := buildModelCard(r.Context(), svcCtx, productTypeId, productCode)
- if err != nil {
- httpx.Fail(w, 2403, err.Error())
- return
- }
- if q.Get("format") == "json" {
- httpx.Ok(w, card)
- return
- }
- html, err := renderModelCard(card)
- if err != nil {
- httpx.Fail(w, 2404, "全景流程卡生成失败:"+err.Error())
- return
- }
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- _, _ = w.Write([]byte(html))
- }
-}
-
-// ---------- 视图数据结构 ----------
-
-type modelCard struct {
- ProductName string
- ProductCode string
- Category string
- ProcessSeq string
- SeqSource string
- StationCount int
- OrderNo string
- PlanStart string
- PlanEnd string
- GeneratedAt string
- Stations []modelStation
- BomGroups []modelBomGroup
- CheckItems []modelCheckItem
- Summary string
-}
-
-type modelStation struct {
- StationNo int
- StationName string
- FlowName string
- FlowStatus string
- PdfFile string
- StepCount int
- CheckCount int
- TorqueCount int
- RefTime string
- Steps []modelStep
-}
-
-type modelStep struct {
- Seq int
- Name string
- CollectType string
- NeedCheck bool
- IsTorque bool
- Criteria string
-}
-
-type modelBomGroup struct {
- BomName string
- Items []modelBomItem
-}
-
-type modelBomItem struct {
- MaterialCode string
- MaterialName string
- Spec string
- Unit string
- SnMode int // 是否逐件SN管理 1序列号件/2批次件
- FlowNames string // 使用该物料的工艺清单(经 flow_material 映射)
- UnitQty string
- LossRate string
- RequiredQty string
-}
-
-type modelCheckItem struct {
- StationNo int
- StationName string
- StepName string
- Criteria string
-}
-
-// ---------- 数据聚合 ----------
-
-func buildModelCard(ctx context.Context, svcCtx *svc.ServiceContext, productTypeId int, productCode string) (*modelCard, error) {
- client := svcCtx.EntClient
- card := &modelCard{GeneratedAt: nowText()}
-
- // 1) 定位产品型号(实时代理 WMS,成品档案 item_type=3;WMS 不可达时降级用 code 兜底)
- var pt *wmsclient.ProductTypeRow
- if productTypeId > 0 {
- pt, _ = logic.New(svcCtx).ProductTypeByID(ctx, productTypeId)
- }
- if pt == nil && productCode != "" {
- pt, _ = logic.New(svcCtx).ProductTypeByCode(ctx, productCode)
- }
- switch {
- case pt != nil:
- card.ProductName = pt.Name
- card.ProductCode = pt.Code
- card.Category = pt.Category
- if productCode == "" {
- productCode = pt.Code
- }
- case productCode != "":
- card.ProductCode = productCode
- card.ProductName = productCode
- default:
- return nil, fmt.Errorf("产品型号不存在")
- }
-
- // 2) 产品最近工单(卡头展示 + 工艺组合路线唯一来源)
- var refWO *ent.WorkOrder
- if productCode != "" {
- refWO, _ = client.WorkOrder.Query().
- Where(workorder.ProductCode(productCode)).
- Order(ent.Desc(workorder.FieldID)).First(ctx)
- }
- if refWO != nil {
- card.OrderNo = refWO.WorkOrderNo
- if refWO.PlanStart != nil {
- card.PlanStart = refWO.PlanStart.Format("2006-01-02 15:04")
- }
- if refWO.PlanEnd != nil {
- card.PlanEnd = refWO.PlanEnd.Format("2006-01-02 15:04")
- }
- }
-
- // 3) 工位组合:唯一路线源头 = 最近工单的工艺组合;未配置则展示全产线已配置工艺的工位
- var seq []int
- if items, _ := logic.RouteStationsFromWO(ctx, client, refWO); len(items) > 0 {
- seq = logic.RouteStationsOfWO(items)
- card.SeqSource = "取自最近工单的工艺组合(工单 " + refWO.WorkOrderNo + ")"
- } else {
- sts, _ := client.Station.Query().Where(station.FlowIdGT(0)).Order(ent.Asc(station.FieldStationNo)).All(ctx)
- for _, st := range sts {
- seq = append(seq, st.StationNo)
- }
- card.SeqSource = "未配置工艺组合,按全产线已配置工位顺序展示"
- }
- sort.Ints(seq)
- card.ProcessSeq = joinInts(seq)
- card.StationCount = len(seq)
-
- // 4) 工位 + 工艺流程 + 步骤 + 考核标准
- sts, _ := client.Station.Query().Where(station.StationNoIn(seq...)).All(ctx)
- stationByName := map[int]*ent.Station{}
- flowIds := []int{}
- for _, st := range sts {
- stationByName[st.StationNo] = st
- if st.FlowId > 0 {
- flowIds = append(flowIds, st.FlowId)
- }
- }
- flows := map[int]*ent.ProcessFlow{}
- if len(flowIds) > 0 {
- fl, _ := client.ProcessFlow.Query().Where(processflow.IDIn(flowIds...)).All(ctx)
- for _, f := range fl {
- flows[f.ID] = f
- }
- }
- stepsByFlow := map[int][]*ent.ProcessStep{}
- if len(flowIds) > 0 {
- allSteps, _ := client.ProcessStep.Query().
- Where(processstep.FlowIdIn(flowIds...)).
- Order(ent.Asc(processstep.FieldFlowId), ent.Asc(processstep.FieldSeq)).All(ctx)
- for _, s := range allSteps {
- stepsByFlow[s.FlowId] = append(stepsByFlow[s.FlowId], s)
- }
- }
- critByStep := map[int][]*ent.StepCriterion{}
- if n, _ := client.StepCriterion.Query().Count(ctx); n > 0 {
- allCrit, _ := client.StepCriterion.Query().Order(ent.Asc(stepcriterion.FieldStepId)).All(ctx)
- for _, c := range allCrit {
- critByStep[c.StepId] = append(critByStep[c.StepId], c)
- }
- }
-
- // 该型号历史实绩时间(按工位聚合首末作业时间),供"各环节时间"列
- refTimes := stationRefTimes(ctx, client, productCode)
-
- for _, no := range seq {
- st := stationByName[no]
- ms := modelStation{StationNo: no, StationName: fmt.Sprintf("工位%d", no)}
- if st != nil {
- ms.RefTime = refTimes[st.FlowId]
- if st.Name != "" {
- ms.StationName = st.Name
- }
- if f := flows[st.FlowId]; f != nil {
- ms.FlowName = f.Name
- ms.FlowStatus = flowStatusCN(f.Status)
- ms.PdfFile = f.PdfFile
- }
- for _, s := range stepsByFlow[st.FlowId] {
- crit := criteriaText(critByStep[s.ID])
- ms.Steps = append(ms.Steps, modelStep{
- Seq: s.Seq,
- Name: s.Name,
- CollectType: collectTypeCN(s.CollectType),
- NeedCheck: s.NeedCheck,
- IsTorque: s.IsTorque,
- Criteria: crit,
- })
- if s.NeedCheck {
- ms.CheckCount++
- card.CheckItems = append(card.CheckItems, modelCheckItem{
- StationNo: no, StationName: ms.StationName,
- StepName: s.Name, Criteria: crit,
- })
- }
- if s.IsTorque {
- ms.TorqueCount++
- }
- }
- ms.StepCount = len(ms.Steps)
- }
- card.Stations = append(card.Stations, ms)
- }
-
- // 5) 物料清单(按工艺分组的工艺物料清单——唯一用料来源)
- if productCode != "" {
- // 物料分组:按工艺分组的工艺物料清单(BOM 已删除,工艺物料清单是唯一用料来源)
- flowAll, _ := client.ProcessFlow.Query().All(ctx)
- nameById := map[int]string{}
- for _, f := range flowAll {
- nameById[f.ID] = f.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,
- SnMode: fm.SnMode,
- FlowNames: name,
- UnitQty: f2s(fm.UnitQty),
- LossRate: f2s(fm.LossRate),
- RequiredQty: "-",
- })
- }
- }
- }
-
- card.Summary = fmt.Sprintf("共 %d 个工位、%d 项检验卡项、%d 个工艺物料分组",
- card.StationCount, len(card.CheckItems), len(card.BomGroups))
- return card, nil
-}
-
-// stationRefTimes 该产品型号历史实绩按工艺聚合的首末作业时间(无实绩则返回空 map,键=工艺ID)
-func stationRefTimes(ctx context.Context, client *ent.Client, productCode string) map[int]string {
- out := map[int]string{}
- if productCode == "" {
- return out
- }
- wos, _ := client.WorkOrder.Query().Where(workorder.ProductCode(productCode)).
- Order(ent.Desc(workorder.FieldID)).Limit(50).All(ctx)
- if len(wos) == 0 {
- return out
- }
- orderNos := make([]string, 0, len(wos))
- for _, wo := range wos {
- orderNos = append(orderNos, wo.WorkOrderNo)
- }
- procs, _ := client.WorkpieceProcess.Query().
- Where(workpieceprocess.OrderNoIn(orderNos...)).All(ctx)
- type span struct {
- first, last int64
- seen bool
- }
- m := map[int]*span{}
- for _, p := range procs {
- s := m[p.FlowId]
- if s == nil {
- s = &span{}
- m[p.FlowId] = s
- }
- if p.StartedAt != nil {
- t := p.StartedAt.Unix()
- if !s.seen || t < s.first {
- s.first = t
- }
- s.seen = true
- }
- if p.EndedAt != nil {
- t := p.EndedAt.Unix()
- if t > s.last {
- s.last = t
- }
- s.seen = true
- }
- }
- for flowId, s := range m {
- if !s.seen {
- continue
- }
- if s.last == 0 {
- out[flowId] = tsText(s.first) + " 起(未完成)"
- continue
- }
- out[flowId] = tsText(s.first) + " → " + tsText(s.last)
- }
- return out
-}
-
-// ---------- 文案/格式化助手 ----------
-
-func nowText() string { return time.Now().Format("2006-01-02 15:04:05") }
-
-func tsText(unix int64) string { return time.Unix(unix, 0).Format("2006-01-02 15:04") }
-
-func collectTypeCN(v string) string {
- switch v {
- case "MANUAL":
- return "手工录入"
- case "AUTO":
- return "自动采集"
- case "NONE", "":
- return "无需采集"
- }
- return v
-}
-
-func flowStatusCN(v string) string {
- switch v {
- case "ACTIVE":
- return "启用"
- case "INACTIVE":
- return "停用"
- }
- return v
-}
-
-func snModeCN(v int) string {
- switch v {
- case 1:
- return "序列号件"
- case 2:
- return "批次件"
- }
- return "-"
-}
-
-func criteriaText(cs []*ent.StepCriterion) string {
- if len(cs) == 0 {
- return "-"
- }
- parts := make([]string, 0, len(cs))
- for _, c := range cs {
- unit := c.Unit
- switch c.Logic {
- case "RANGE":
- lo, hi := "", ""
- if c.Min != nil {
- lo = f2s(*c.Min)
- }
- if c.Max != nil {
- hi = f2s(*c.Max)
- }
- parts = append(parts, fmt.Sprintf("%s ∈ [%s, %s]%s", c.Name, lo, hi, unit))
- case "GE":
- parts = append(parts, fmt.Sprintf("%s ≥ %s%s", c.Name, f2s(c.Target), unit))
- case "LE":
- parts = append(parts, fmt.Sprintf("%s ≤ %s%s", c.Name, f2s(c.Target), unit))
- case "GT":
- parts = append(parts, fmt.Sprintf("%s > %s%s", c.Name, f2s(c.Target), unit))
- case "LT":
- parts = append(parts, fmt.Sprintf("%s < %s%s", c.Name, f2s(c.Target), unit))
- case "EQUAL":
- parts = append(parts, fmt.Sprintf("%s = %s%s", c.Name, f2s(c.Target), unit))
- default:
- parts = append(parts, c.Name)
- }
- }
- return strings.Join(parts, ";")
-}
-
-func f2s(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
-
-func joinInts(a []int) string {
- p := make([]string, 0, len(a))
- for _, v := range a {
- p = append(p, strconv.Itoa(v))
- }
- return strings.Join(p, ",")
-}
-
-// ---------- HTML 渲染 ----------
-
-func renderModelCard(c *modelCard) (string, error) {
- const tpl = `
-
-
-
-产品型号全景流程卡 {{.ProductCode}}
-
-
-
-
-
产品型号全景流程卡
-
- 产品名称:{{.ProductName}}
- 产品编号:{{.ProductCode}}
- {{if .Category}}产品分类:{{.Category}}{{end}}
- 工位组合:{{.ProcessSeq}}
- 工位数:{{.StationCount}}
-
-
工位组合来源:{{.SeqSource}};{{.Summary}};生成时间 {{.GeneratedAt}}
- {{if .OrderNo}}
参考工单:{{.OrderNo}}{{if .PlanStart}} 计划开始 {{.PlanStart}}{{end}}{{if .PlanEnd}} 计划结束 {{.PlanEnd}}{{end}}
{{end}}
-
-
一、工位流程总览
-
- | 工位号 | 工位名称 | 工艺流程 | 流程状态 | 步骤数 | 检验点 | 拧紧步骤 | 工艺图纸 | 作业时间(本型号实绩) |
-
- {{range .Stations}}
-
- | {{.StationNo}} | {{.StationName}} |
- {{if .FlowName}}{{.FlowName}}{{else}}未绑定流程{{end}} |
- {{if .FlowStatus}}{{.FlowStatus}}{{else}}-{{end}} |
- {{.StepCount}} |
- {{if .CheckCount}}{{.CheckCount}}{{else}}0{{end}} |
- {{.TorqueCount}} |
- {{if .PdfFile}}{{.PdfFile}}{{else}}-{{end}} |
- {{if .RefTime}}{{.RefTime}}{{else}}暂无实绩{{end}} |
-
- {{end}}
-
-
-
-
二、各工位工艺流程与步骤明细
- {{range .Stations}}
- {{if .Steps}}
-
-
- | 工位{{.StationNo}} {{.StationName}} · {{if .FlowName}}{{.FlowName}}{{else}}未绑定工艺{{end}} |
- | 步骤号 | 步骤名称 | 采集方式 | 检测确认 | 拧紧采集 | 考核标准 |
-
-
- {{range .Steps}}
-
- | {{.Seq}} | {{.Name}} | {{.CollectType}} |
- {{if .NeedCheck}}需检验{{else}}否{{end}} |
- {{if .IsTorque}}是{{else}}否{{end}} |
- {{.Criteria}} |
-
- {{end}}
-
-
- {{end}}
- {{end}}
-
-
三、物料清单
- {{if .BomGroups}}
- {{range .BomGroups}}
-
-
- | BOM:{{.BomName}} |
- | 图号 | 物料名称 | 规格 | 单位 | 管理方式 | 工艺清单 | 单台用量 | 损耗率(%) | 需求总量 |
-
-
- {{range .Items}}
-
- | {{.MaterialCode}} | {{.MaterialName}} | {{.Spec}} |
- {{.Unit}} | {{snModeCN .SnMode}} | {{.FlowNames}} |
- {{.UnitQty}} | {{.LossRate}} | {{.RequiredQty}} |
-
- {{end}}
-
-
- {{end}}
- {{else}}
-
该产品型号暂无物料清单。
- {{end}}
-
-
四、检验卡项(所有「检测确认」步骤)
- {{if .CheckItems}}
-
- | 工位号 | 工位名称 | 检验步骤 | 判定标准 |
-
- {{range .CheckItems}}
- | {{.StationNo}} | {{.StationName}} | {{.StepName}} | {{.Criteria}} |
- {{end}}
-
-
- {{else}}
-
该产品型号暂无检验卡项(工艺流程未设置「需要检测确认」的步骤)。
- {{end}}
-
-
-
-
-
-
-
-`
-
- tmpl, err := template.New("modelcard").Parse(tpl)
- if err != nil {
- return "", err
- }
- var buf bytes.Buffer
- if err := tmpl.Execute(&buf, c); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
diff --git a/bj_power_mes/internal/handler/processcard_workorder.go b/bj_power_mes/internal/handler/processcard_workorder.go
new file mode 100644
index 0000000..44f3ce4
--- /dev/null
+++ b/bj_power_mes/internal/handler/processcard_workorder.go
@@ -0,0 +1,1004 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "html/template"
+ "net/http"
+ "sort"
+ "strings"
+ "time"
+
+ "bj_power_mes/common/httpx"
+ "bj_power_mes/ent"
+ "bj_power_mes/ent/processflow"
+ "bj_power_mes/ent/processstep"
+ "bj_power_mes/ent/station"
+ "bj_power_mes/ent/stepsignrecord"
+ "bj_power_mes/ent/torquerecord"
+ "bj_power_mes/ent/workorder"
+ "bj_power_mes/ent/workpiece"
+ "bj_power_mes/ent/workpiecebind"
+ "bj_power_mes/ent/workpieceprocess"
+ "bj_power_mes/internal/logic"
+ "bj_power_mes/internal/svc"
+)
+
+// ============================================================================
+// 生产流程卡(工单维度主卡 + 成品 SN 追溯卡 + 型号筛选)
+//
+// 业务定位(客户裁定):
+// - 客户要的是「生产实绩 / 追溯卡」,工单维度为主卡,成品 SN 维度为追溯子视图,两者都保留。
+// - 产品型号只是筛选入口(/process-card/by-model 返回该型号下的工单列表),不是独立卡片。
+// - 定义层(工艺怎么规定)仅用于给出工序清单;实绩层(谁在何时做了什么、用了什么料)才是主内容。
+//
+// 三端点:
+// GET /api/v1/process-card/workorder?no=WO-xxx 工单生产流程卡(主卡)
+// GET /api/v1/process-card/by-sn?sn=FIN-xxx 成品 SN 追溯卡(追溯子视图)
+// GET /api/v1/process-card/by-model?code=DX100 型号→工单列表(筛选,仅 JSON)
+// 默认返回可打印 HTML;?format=json 返回结构化数据供页面渲染。
+// ============================================================================
+
+// ---------- 工单主卡 ----------
+
+type workOrderCard struct {
+ WorkOrderNo string `json:"workOrderNo"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ DrawingNo string `json:"drawingNo"`
+ PlanQty int `json:"planQty"`
+ FinishedNum int `json:"finishedNum"`
+ FailNum int `json:"failNum"`
+ Status string `json:"status"`
+ PlanStart string `json:"planStart"`
+ PlanEnd string `json:"planEnd"`
+ ActualStart string `json:"actualStart"`
+ ActualFinish string `json:"actualFinish"`
+ ProcessSeqNote string `json:"processSeqNote"`
+ GeneratedAt string `json:"generatedAt"`
+ ProcessSteps []woProcessStep `json:"processSteps"`
+ SerialMaterials []woMaterialSerial `json:"serialMaterials"`
+ BatchMaterials []woMaterialBatch `json:"batchMaterials"`
+ Signs woSignSummary `json:"signs"`
+ Products []woProduct `json:"products"`
+}
+
+type woProcessStep struct {
+ Seq int `json:"seq"`
+ ProcessName string `json:"processName"`
+ StationNo int `json:"stationNo"`
+ PlanHours string `json:"planHours"`
+ ActualStart string `json:"actualStart"`
+ ActualEnd string `json:"actualEnd"`
+ Operators string `json:"operators"`
+ Status string `json:"status"`
+ NeedCheck bool `json:"needCheck"`
+ NeedAudit bool `json:"needAudit"`
+ AuditRole string `json:"auditRole"`
+ Auditor string `json:"auditor"`
+ AuditedAt string `json:"auditedAt"`
+}
+
+type woMaterialSerial struct {
+ MaterialCode string `json:"materialCode"`
+ MaterialName string `json:"materialName"`
+ MaterialType string `json:"materialType"` // 类型:结构件/电气件/其他(WMS manage_mode)
+ Spec string `json:"spec"`
+ Unit string `json:"unit"`
+ SnList []string `json:"snList"` // 物料 SN 列表(逐件)
+ Qty int `json:"qty"`
+ StationNo string `json:"stationNo"`
+ Operator string `json:"operator"`
+}
+
+type woMaterialBatch struct {
+ MaterialCode string `json:"materialCode"`
+ MaterialName string `json:"materialName"`
+ MaterialType string `json:"materialType"`
+ Spec string `json:"spec"`
+ Unit string `json:"unit"`
+ BatchNo string `json:"batchNo"`
+ Qty int `json:"qty"`
+ StationNo string `json:"stationNo"`
+ Operator string `json:"operator"`
+}
+
+type woSignSummary struct {
+ Operator *woSignRole `json:"operator"`
+ Inspector *woSignRole `json:"inspector"`
+ Auditor *woSignRole `json:"auditor"`
+ Reviewer string `json:"reviewer"` // 单据级审核人(本轮留手签空位,不造假)
+ Approver string `json:"approver"` // 单据级批准人(本轮留手签空位,不造假)
+}
+
+type woSignRole struct {
+ Names string `json:"names"`
+ Count int `json:"count"`
+ LatestTime string `json:"latestTime"`
+ names string // 累积用(未序列化)
+}
+
+type woProduct struct {
+ Sn string `json:"sn"`
+ Status string `json:"status"`
+ DoneAt string `json:"doneAt"`
+}
+
+// ---------- 成品 SN 追溯卡 ----------
+
+type snTraceCard struct {
+ Sn string `json:"sn"`
+ WorkOrderNo string `json:"workOrderNo"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ Status string `json:"status"`
+ DoneAt string `json:"doneAt"`
+ GeneratedAt string `json:"generatedAt"`
+ Processes []snTraceStep `json:"processes"`
+ SerialMaterials []woMaterialSerial `json:"serialMaterials"`
+ BatchMaterials []woMaterialBatch `json:"batchMaterials"`
+ Signs woSignSummary `json:"signs"`
+ TorqueRows []snTraceTorque `json:"torqueRows"`
+}
+
+type snTraceStep struct {
+ FlowId int `json:"flowId"`
+ StationNo string `json:"stationNo"`
+ ProcessName string `json:"processName"`
+ StartAt string `json:"startAt"`
+ EndAt string `json:"endAt"`
+ Operator string `json:"operator"`
+ Status string `json:"status"`
+ Result string `json:"result"`
+}
+
+type snTraceTorque struct {
+ ScrewNo string `json:"screwNo"`
+ Torque string `json:"torque"`
+ Angle string `json:"angle"`
+ Result string `json:"result"`
+ Operator string `json:"operator"`
+ Time string `json:"time"`
+}
+
+// ---------- 型号→工单列表(筛选) ----------
+
+type modelWorkOrders struct {
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ TotalOrders int `json:"totalOrders"`
+ TotalPlanQty int `json:"totalPlanQty"`
+ TotalFinished int `json:"totalFinished"`
+ WorkOrders []modelOrderRow `json:"workOrders"`
+}
+
+type modelOrderRow struct {
+ No string `json:"no"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ Status string `json:"status"`
+ PlanStart string `json:"planStart"`
+ PlanEnd string `json:"planEnd"`
+ Quantity int `json:"quantity"`
+ FinishedNum int `json:"finishedNum"`
+ CreatedAt string `json:"createdAt"`
+}
+
+// ============================================================================
+// 路由处理器
+// ============================================================================
+
+// WorkOrderCardHandler GET /api/v1/process-card/workorder?no=WO-xxx
+func WorkOrderCardHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ no := strings.TrimSpace(r.URL.Query().Get("no"))
+ if no == "" {
+ httpx.BadRequest(w, "缺少工单号 no 参数")
+ return
+ }
+ card, err := buildWorkOrderCard(r.Context(), svcCtx, no)
+ if err != nil {
+ httpx.Fail(w, 2403, err.Error())
+ return
+ }
+ if r.URL.Query().Get("format") == "json" {
+ httpx.Ok(w, card)
+ return
+ }
+ html, err := renderWorkOrderCard(card)
+ if err != nil {
+ httpx.Fail(w, 2405, "工单流程卡生成失败:"+err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = w.Write([]byte(html))
+ }
+}
+
+// SnTraceCardHandler GET /api/v1/process-card/by-sn?sn=FIN-xxx
+func SnTraceCardHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ sn := strings.TrimSpace(r.URL.Query().Get("sn"))
+ if sn == "" {
+ httpx.BadRequest(w, "缺少成品 SN 参数")
+ return
+ }
+ card, err := buildSnTraceCard(r.Context(), svcCtx, sn)
+ if err != nil {
+ httpx.Fail(w, 2406, err.Error())
+ return
+ }
+ if r.URL.Query().Get("format") == "json" {
+ httpx.Ok(w, card)
+ return
+ }
+ html, err := renderSnTraceCard(card)
+ if err != nil {
+ httpx.Fail(w, 2407, "成品追溯卡生成失败:"+err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = w.Write([]byte(html))
+ }
+}
+
+// ModelWorkOrdersHandler GET /api/v1/process-card/by-model?code=DX100
+// 型号只是筛选入口:返回该型号下的工单列表 + 汇总数字(不渲染独立卡片)。
+func ModelWorkOrdersHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ code := strings.TrimSpace(r.URL.Query().Get("code"))
+ if code == "" {
+ httpx.BadRequest(w, "缺少产品型号 code 参数")
+ return
+ }
+ data, err := buildModelWorkOrders(r.Context(), svcCtx, code)
+ if err != nil {
+ httpx.Fail(w, 2408, err.Error())
+ return
+ }
+ httpx.Ok(w, data)
+ }
+}
+
+// ============================================================================
+// 数据聚合
+// ============================================================================
+
+func buildWorkOrderCard(ctx context.Context, svcCtx *svc.ServiceContext, workOrderNo string) (*workOrderCard, error) {
+ client := svcCtx.EntClient
+ wo, err := client.WorkOrder.Query().Where(workorder.WorkOrderNo(workOrderNo)).First(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("工单 %s 不存在", workOrderNo)
+ }
+ card := &workOrderCard{
+ WorkOrderNo: wo.WorkOrderNo,
+ ProductCode: wo.ProductCode,
+ ProductName: wo.ProductName,
+ DrawingNo: wo.ProductCode,
+ PlanQty: wo.Quantity,
+ FinishedNum: wo.FinishedNum,
+ FailNum: wo.FailNum,
+ Status: wo.Status,
+ GeneratedAt: nowText(),
+ }
+ if card.ProductName == "" {
+ card.ProductName = wo.ProductCode
+ }
+ if wo.PlanStart != nil {
+ card.PlanStart = wo.PlanStart.Format("2006-01-02 15:04")
+ }
+ if wo.PlanEnd != nil {
+ card.PlanEnd = wo.PlanEnd.Format("2006-01-02 15:04")
+ }
+
+ // 路线:工单工艺组合 → 工位顺序;未配置则全产线已配置工位
+ seq := []int{}
+ if items, _ := logic.RouteStationsFromWO(ctx, client, wo); len(items) > 0 {
+ seq = logic.RouteStationsOfWO(items)
+ } else {
+ sts, _ := client.Station.Query().Where(station.FlowIdGT(0)).Order(ent.Asc(station.FieldStationNo)).All(ctx)
+ for _, s := range sts {
+ seq = append(seq, s.StationNo)
+ }
+ }
+ sort.Ints(seq)
+ card.ProcessSeqNote = joinInts(seq)
+
+ sts, _ := client.Station.Query().Where(station.StationNoIn(seq...)).All(ctx)
+ stationByNo := map[int]*ent.Station{}
+ flowIds := []int{}
+ for _, s := range sts {
+ stationByNo[s.StationNo] = s
+ if s.FlowId > 0 {
+ flowIds = append(flowIds, s.FlowId)
+ }
+ }
+ flows := map[int]*ent.ProcessFlow{}
+ if len(flowIds) > 0 {
+ fl, _ := client.ProcessFlow.Query().Where(processflow.IDIn(flowIds...)).All(ctx)
+ for _, f := range fl {
+ flows[f.ID] = f
+ }
+ }
+ stepsByFlow := map[int][]*ent.ProcessStep{}
+ if len(flowIds) > 0 {
+ allSteps, _ := client.ProcessStep.Query().
+ Where(processstep.FlowIdIn(flowIds...)).
+ Order(ent.Asc(processstep.FieldFlowId), ent.Asc(processstep.FieldSeq)).All(ctx)
+ for _, s := range allSteps {
+ stepsByFlow[s.FlowId] = append(stepsByFlow[s.FlowId], s)
+ }
+ }
+
+ // 实绩:该工单全部 SN 的 workpiece_process,按 (flow_id, 工序名) 聚合
+ procs, _ := client.WorkpieceProcess.Query().Where(workpieceprocess.OrderNo(wo.WorkOrderNo)).All(ctx)
+ type agg struct {
+ started *time.Time
+ ended *time.Time
+ ops map[string]bool
+ allEnded bool
+ hasRecord bool
+ }
+ actByKey := map[string]*agg{}
+ var firstStart, lastEnd *time.Time
+ for _, p := range procs {
+ key := fmt.Sprintf("%d|%s", p.FlowId, p.ProcessName)
+ a := actByKey[key]
+ if a == nil {
+ a = &agg{ops: map[string]bool{}}
+ actByKey[key] = a
+ }
+ a.hasRecord = true
+ if p.StartedAt != nil {
+ a.started = minTime(a.started, p.StartedAt)
+ firstStart = minTime(firstStart, p.StartedAt)
+ }
+ if p.EndedAt != nil {
+ a.ended = maxTime(a.ended, p.EndedAt)
+ lastEnd = maxTime(lastEnd, p.EndedAt)
+ }
+ if p.Operator != "" {
+ a.ops[p.Operator] = true
+ }
+ if p.Status != "DONE" && p.Status != "OK" && p.Status != "完成" {
+ a.allEnded = false
+ } else if p.EndedAt != nil {
+ a.allEnded = true
+ }
+ }
+ if firstStart != nil {
+ card.ActualStart = firstStart.Format("2006-01-02 15:04")
+ }
+ if lastEnd != nil {
+ card.ActualFinish = lastEnd.Format("2006-01-02 15:04")
+ }
+
+ // 工序签字(工序级):一次加载工单全部签字,按 step_id / role 索引
+ signs, _ := client.StepSignRecord.Query().Where(stepsignrecord.OrderNo(wo.WorkOrderNo)).All(ctx)
+ signByStep := map[int]map[string][]*ent.StepSignRecord{}
+ for _, s := range signs {
+ if s.StepId <= 0 {
+ continue
+ }
+ if signByStep[s.StepId] == nil {
+ signByStep[s.StepId] = map[string][]*ent.StepSignRecord{}
+ }
+ signByStep[s.StepId][s.SignRole] = append(signByStep[s.StepId][s.SignRole], s)
+ }
+
+ // 组装工序实绩行
+ for _, no := range seq {
+ st := stationByNo[no]
+ if st == nil {
+ continue
+ }
+ for _, s := range stepsByFlow[st.FlowId] {
+ key := fmt.Sprintf("%d|%s", st.FlowId, s.Name)
+ ps := woProcessStep{Seq: s.Seq, ProcessName: s.Name, StationNo: no, PlanHours: "-",
+ NeedCheck: s.NeedCheck, NeedAudit: s.NeedAudit, AuditRole: s.AuditRole}
+ a := actByKey[key]
+ if a != nil && a.hasRecord {
+ if a.started != nil {
+ ps.ActualStart = a.started.Format("2006-01-02 15:04")
+ }
+ if a.ended != nil {
+ ps.ActualEnd = a.ended.Format("2006-01-02 15:04")
+ }
+ ops := []string{}
+ for o := range a.ops {
+ ops = append(ops, o)
+ }
+ sort.Strings(ops)
+ ps.Operators = strings.Join(ops, "、")
+ if a.allEnded {
+ ps.Status = "完成"
+ } else {
+ ps.Status = "进行中"
+ }
+ } else {
+ ps.Status = "待开工"
+ }
+ // 该工序的审核人(AUDITOR 最新一条)
+ if recs := signByStep[s.ID]["AUDITOR"]; len(recs) > 0 {
+ latest := recs[0]
+ for _, r := range recs {
+ if r.SignedAt.After(latest.SignedAt) {
+ latest = r
+ }
+ }
+ ps.Auditor = latest.SignedBy
+ ps.AuditedAt = latest.SignedAt.Format("2006-01-02 15:04")
+ }
+ card.ProcessSteps = append(card.ProcessSteps, ps)
+ }
+ }
+
+ // 用料实绩:工单全部 SN 的 workpiece_bind,按 序列号件 / 批次件 分组
+ wps, _ := client.Workpiece.Query().Where(workpiece.OrderNo(wo.WorkOrderNo)).All(ctx)
+ sns := make([]string, 0, len(wps))
+ for _, w := range wps {
+ sns = append(sns, w.Sn)
+ card.Products = append(card.Products, woProduct{
+ Sn: w.Sn, Status: w.Status,
+ DoneAt: orEmptyTime(w.DoneAt),
+ })
+ }
+ if len(sns) > 0 {
+ binds, _ := client.WorkpieceBind.Query().Where(workpiecebind.SnIn(sns...)).All(ctx)
+ card.SerialMaterials, card.BatchMaterials = buildMaterialGroups(ctx, svcCtx, binds)
+ }
+
+ // 签字汇总(单据级展示):操作工 / 检验员 / 审核人(单据级审核/批准本轮留手签空位)
+ card.Signs = summarizeSigns(signs)
+ return card, nil
+}
+
+// buildSnTraceCard 成品 SN 追溯卡(SN 维度)。
+func buildSnTraceCard(ctx context.Context, svcCtx *svc.ServiceContext, sn string) (*snTraceCard, error) {
+ client := svcCtx.EntClient
+ wp, err := client.Workpiece.Query().Where(workpiece.Sn(sn)).First(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("该 SN %s 无追溯数据", sn)
+ }
+ card := &snTraceCard{Sn: sn, Status: wp.Status, DoneAt: orEmptyTime(wp.DoneAt), GeneratedAt: nowText()}
+ if wp.OrderNo != "" {
+ if wo, e := client.WorkOrder.Query().Where(workorder.WorkOrderNo(wp.OrderNo)).First(ctx); e == nil {
+ card.WorkOrderNo = wo.WorkOrderNo
+ card.ProductCode = wo.ProductCode
+ card.ProductName = wo.ProductName
+ if card.ProductName == "" {
+ card.ProductName = wo.ProductCode
+ }
+ }
+ }
+
+ // 工序实绩(逐条)
+ procs, _ := client.WorkpieceProcess.Query().
+ Where(workpieceprocess.Sn(sn)).Order(ent.Asc(workpieceprocess.FieldFlowId), ent.Asc(workpieceprocess.FieldID)).All(ctx)
+ for _, p := range procs {
+ card.Processes = append(card.Processes, snTraceStep{
+ FlowId: p.FlowId, StationNo: p.StationNo, ProcessName: p.ProcessName,
+ StartAt: orEmptyTime(p.StartedAt), EndAt: orEmptyTime(p.EndedAt),
+ Operator: p.Operator, Status: p.Status, Result: p.Result,
+ })
+ }
+
+ // 用料实绩(该 SN 的绑定)
+ binds, _ := client.WorkpieceBind.Query().Where(workpiecebind.Sn(sn)).All(ctx)
+ card.SerialMaterials, card.BatchMaterials = buildMaterialGroups(ctx, svcCtx, binds)
+
+ // 签字(该 SN)
+ signs, _ := client.StepSignRecord.Query().Where(stepsignrecord.Sn(sn)).All(ctx)
+ card.Signs = summarizeSigns(signs)
+
+ // 拧紧(如有)
+ torque, _ := client.TorqueRecord.Query().
+ Where(torquerecord.Sn(sn)).Order(ent.Desc(torquerecord.FieldTime)).Limit(200).All(ctx)
+ for _, q := range torque {
+ card.TorqueRows = append(card.TorqueRows, snTraceTorque{
+ ScrewNo: q.ScrewNo, Torque: fmt.Sprintf("%.2f", q.Torque), Angle: fmt.Sprintf("%.2f", q.Angle),
+ Result: q.Result, Operator: q.Operator, Time: q.Time.Format("2006-01-02 15:04:05"),
+ })
+ }
+ return card, nil
+}
+
+// buildModelWorkOrders 型号→工单列表(筛选入口)。
+func buildModelWorkOrders(ctx context.Context, svcCtx *svc.ServiceContext, code string) (*modelWorkOrders, error) {
+ client := svcCtx.EntClient
+ data := &modelWorkOrders{ProductCode: code}
+ wos, err := client.WorkOrder.Query().Where(workorder.ProductCode(code)).
+ Order(ent.Desc(workorder.FieldID)).All(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("查询工单失败")
+ }
+ for _, w := range wos {
+ data.WorkOrders = append(data.WorkOrders, modelOrderRow{
+ No: w.WorkOrderNo, ProductCode: w.ProductCode, ProductName: w.ProductName,
+ Status: w.Status, PlanStart: orEmptyTime(w.PlanStart), PlanEnd: orEmptyTime(w.PlanEnd),
+ Quantity: w.Quantity, FinishedNum: w.FinishedNum, CreatedAt: orEmptyTimeValue(w.CreatedAt),
+ })
+ data.TotalOrders++
+ data.TotalPlanQty += w.Quantity
+ data.TotalFinished += w.FinishedNum
+ }
+ if data.ProductName == "" && len(wos) > 0 {
+ data.ProductName = wos[0].ProductName
+ }
+ return data, nil
+}
+
+// ============================================================================
+// 物料分组(实绩):序列号件 / 批次件 分离,类型经 WMS manage_mode 补全
+// ============================================================================
+
+func buildMaterialGroups(ctx context.Context, svcCtx *svc.ServiceContext, binds []*ent.WorkpieceBind) ([]woMaterialSerial, []woMaterialBatch) {
+ serialMap := map[string]*woMaterialSerial{}
+ batchMap := map[string]*woMaterialBatch{}
+ codes := []string{}
+ for _, b := range binds {
+ if b.MaterialCode == "" {
+ continue
+ }
+ codes = append(codes, b.MaterialCode)
+ if b.BindType == "SN" {
+ r, ok := serialMap[b.MaterialCode]
+ if !ok {
+ r = &woMaterialSerial{MaterialCode: b.MaterialCode, MaterialName: b.MaterialName, Spec: b.Spec, Unit: b.Unit}
+ serialMap[b.MaterialCode] = r
+ }
+ r.Qty++
+ r.SnList = append(r.SnList, b.BindValue)
+ if r.StationNo == "" {
+ r.StationNo = b.StationNo
+ }
+ if r.Operator == "" {
+ r.Operator = b.Operator
+ }
+ } else { // BATCH
+ k := b.MaterialCode + "|" + b.BindValue
+ r, ok := batchMap[k]
+ if !ok {
+ r = &woMaterialBatch{MaterialCode: b.MaterialCode, MaterialName: b.MaterialName, Spec: b.Spec, Unit: b.Unit, BatchNo: b.BindValue}
+ batchMap[k] = r
+ }
+ r.Qty++
+ r.StationNo = b.StationNo
+ r.Operator = b.Operator
+ }
+ }
+ if len(codes) > 0 && svcCtx.Wms != nil {
+ if mm, e := svcCtx.Wms.MaterialManageModes(ctx, dedupeStrings(codes)); e == nil {
+ for _, r := range serialMap {
+ r.MaterialType = manageModeCN(mm[r.MaterialCode])
+ }
+ for _, r := range batchMap {
+ r.MaterialType = manageModeCN(mm[r.MaterialCode])
+ }
+ }
+ }
+ serials := make([]woMaterialSerial, 0, len(serialMap))
+ for _, r := range serialMap {
+ sort.Strings(r.SnList)
+ serials = append(serials, *r)
+ }
+ batches := make([]woMaterialBatch, 0, len(batchMap))
+ for _, r := range batchMap {
+ batches = append(batches, *r)
+ }
+ return serials, batches
+}
+
+// summarizeSigns 工序级签字汇总(操作工/检验员/审核人);单据级审核/批准留手签空位。
+func summarizeSigns(signs []*ent.StepSignRecord) woSignSummary {
+ sum := woSignSummary{}
+ roles := map[string]*woSignRole{}
+ for _, s := range signs {
+ if s.SignedBy == "" {
+ continue
+ }
+ switch s.SignRole {
+ case "OPERATOR", "INSPECTOR", "AUDITOR":
+ r := roles[s.SignRole]
+ if r == nil {
+ r = &woSignRole{}
+ roles[s.SignRole] = r
+ }
+ if !containsStr(r.nameList(), s.SignedBy) {
+ r.names += s.SignedBy + "、"
+ }
+ r.Count++
+ t := s.SignedAt.Format("2006-01-02 15:04")
+ if t > r.LatestTime {
+ r.LatestTime = t
+ }
+ }
+ }
+ if r := roles["OPERATOR"]; r != nil {
+ sum.Operator = trimRole(r)
+ }
+ if r := roles["INSPECTOR"]; r != nil {
+ sum.Inspector = trimRole(r)
+ }
+ if r := roles["AUDITOR"]; r != nil {
+ sum.Auditor = trimRole(r)
+ }
+ return sum
+}
+
+// ============================================================================
+// 文案 / 格式化助手
+// ============================================================================
+
+func nowText() string { return time.Now().Format("2006-01-02 15:04:05") }
+func orEmptyTime(t *time.Time) string {
+ if t == nil {
+ return ""
+ }
+ return t.Format("2006-01-02 15:04")
+}
+
+func orEmptyTimeValue(t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ return t.Format("2006-01-02 15:04")
+}
+
+func minTime(a, b *time.Time) *time.Time {
+ if a == nil {
+ return b
+ }
+ if b.Before(*a) {
+ return b
+ }
+ return a
+}
+
+func maxTime(a, b *time.Time) *time.Time {
+ if a == nil {
+ return b
+ }
+ if b.After(*a) {
+ return b
+ }
+ return a
+}
+
+func dedupeStrings(in []string) []string {
+ seen := map[string]bool{}
+ out := []string{}
+ for _, s := range in {
+ if s != "" && !seen[s] {
+ seen[s] = true
+ out = append(out, s)
+ }
+ }
+ return out
+}
+
+func containsStr(list string, s string) bool {
+ return strings.Contains(list, s)
+}
+
+// woSignRole 临时辅助:累计 names 字符串
+func (r *woSignRole) nameList() string { return r.names }
+
+func trimRole(r *woSignRole) *woSignRole {
+ r.names = strings.TrimRight(r.names, "、")
+ return r
+}
+
+// manageModeCN 物料「类型」(WMS manage_mode):1结构件/2电气件/3其他。
+func manageModeCN(v int) string {
+ switch v {
+ case 1:
+ return "结构件"
+ case 2:
+ return "电气件"
+ case 3:
+ return "其他"
+ }
+ return "-"
+}
+
+// snModeCN 物料「序列号」(sn_mode):1序列号件/2批次件(仅作模板函数注册,避免未注册 panic)。
+func snModeCN(v int) string {
+ switch v {
+ case 1:
+ return "序列号件"
+ case 2:
+ return "批次件"
+ }
+ return "-"
+}
+
+func joinInts(a []int) string {
+ p := make([]string, 0, len(a))
+ for _, v := range a {
+ p = append(p, fmt.Sprintf("%d", v))
+ }
+ return strings.Join(p, ",")
+}
+
+// ============================================================================
+// HTML 渲染(必须 Funcs 注册,否则未注册函数会 2404 panic)
+// ============================================================================
+
+func renderWorkOrderCard(c *workOrderCard) (string, error) {
+ const tpl = `
+
+
+
+生产流程卡 {{.WorkOrderNo}}
+
+
+
+
+
生产流程卡(工单维度)
+
+ 工单号:{{.WorkOrderNo}}
+ 产品型号:{{.ProductCode}}
+ 产品名称:{{.ProductName}}
+ 图号:{{.DrawingNo}}
+ 计划数:{{.PlanQty}}
+ 完成数:{{.FinishedNum}}
+ 状态:{{.Status}}
+
+
+ 计划开始:{{.PlanStart}}
+ 计划结束:{{.PlanEnd}}
+ 实际开始:{{.ActualStart}}
+ 实际结束:{{.ActualFinish}}
+ 生成时间:{{.GeneratedAt}}
+
+
+
一、工序实绩
+ {{if .ProcessSteps}}
+
+ | 序号 | 工序 | 工位 | 计划工时 | 实绩开始 | 实绩结束 | 操作人 | 状态 | 审核人 | 审核时间 |
+
+ {{range .ProcessSteps}}
+
+ | {{.Seq}} | {{.ProcessName}} | {{.StationNo}} | {{.PlanHours}} |
+ {{.ActualStart}} | {{.ActualEnd}} | {{.Operators}} |
+ {{if eq .Status "完成"}}完成{{else}}{{.Status}}{{end}} |
+ {{if .Auditor}}{{.Auditor}}{{if .AuditRole}}({{.AuditRole}}){{end}}{{else}}-{{end}} |
+ {{.AuditedAt}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无工序实绩。
+ {{end}}
+
+
二、用料清单 · 序列号件(逐件追溯)
+ {{if .SerialMaterials}}
+
+ | 图号 | 名称 | 类型 | 规格 | 单位 | 物料SN | 数量 | 装配工位 | 装配人 |
+
+ {{range .SerialMaterials}}
+
+ | {{.MaterialCode}} | {{.MaterialName}} | {{.MaterialType}} | {{.Spec}} | {{.Unit}} |
+ {{range .SnList}}{{.}} {{end}} | {{.Qty}} | {{.StationNo}} | {{.Operator}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无序列号件实绩。
+ {{end}}
+
+
三、用料清单 · 批次件(按批追溯)
+ {{if .BatchMaterials}}
+
+ | 图号 | 名称 | 类型 | 规格 | 单位 | 批次号 | 数量 | 供应商 | 装配工位 | 装配人 |
+
+ {{range .BatchMaterials}}
+
+ | {{.MaterialCode}} | {{.MaterialName}} | {{.MaterialType}} | {{.Spec}} | {{.Unit}} |
+ {{.BatchNo}} | {{.Qty}} | - | {{.StationNo}} | {{.Operator}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无批次件实绩。
+ {{end}}
+
+
四、成品明细
+ {{if .Products}}
+
+ | SN | 状态 | 完工时间 |
+
+ {{range .Products}}
+ | {{.Sn}} | {{.Status}} | {{.DoneAt}} |
+ {{end}}
+
+
+ {{else}}
+
暂无成品记录。
+ {{end}}
+
+
五、签字确认
+
+
操作工:{{if .Signs.Operator}}{{.Signs.Operator.Names}}
({{.Signs.Operator.Count}}次,最近 {{.Signs.Operator.LatestTime}}){{else}}待签{{end}}
+
检验员:{{if .Signs.Inspector}}{{.Signs.Inspector.Names}}
({{.Signs.Inspector.Count}}次,最近 {{.Signs.Inspector.LatestTime}}){{else}}待签{{end}}
+
审核人:{{if .Signs.Auditor}}{{.Signs.Auditor.Names}}
({{.Signs.Auditor.Count}}次,最近 {{.Signs.Auditor.LatestTime}}){{else}}待签{{end}}
+
批准人:手签
+
+
+
+
+
+
+
+`
+
+ tmpl, err := template.New("workordercard").
+ Funcs(template.FuncMap{"manageModeCN": manageModeCN, "snModeCN": snModeCN}).
+ Parse(tpl)
+ if err != nil {
+ return "", err
+ }
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, c); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+func renderSnTraceCard(c *snTraceCard) (string, error) {
+ const tpl = `
+
+
+
+成品追溯卡 {{.Sn}}
+
+
+
+
+
成品追溯卡(SN 维度)
+
+ SN:{{.Sn}}
+ 工单号:{{.WorkOrderNo}}
+ 产品型号:{{.ProductCode}}
+ 状态:{{.Status}}
+ 完工时间:{{.DoneAt}}
+ 生成时间:{{.GeneratedAt}}
+
+
+
一、工序实绩
+ {{if .Processes}}
+
+ | 工位 | 工序 | 开始 | 结束 | 操作人 | 状态 | 结果 |
+
+ {{range .Processes}}
+
+ | {{.StationNo}} | {{.ProcessName}} | {{.StartAt}} | {{.EndAt}} |
+ {{.Operator}} | {{.Status}} |
+ {{if eq .Result "NG"}}NG{{else}}{{.Result}}{{end}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无工序实绩。
+ {{end}}
+
+
二、用料清单 · 序列号件
+ {{if .SerialMaterials}}
+
+ | 图号 | 名称 | 类型 | 规格 | 单位 | 物料SN | 数量 | 装配工位 | 装配人 |
+
+ {{range .SerialMaterials}}
+
+ | {{.MaterialCode}} | {{.MaterialName}} | {{.MaterialType}} | {{.Spec}} | {{.Unit}} |
+ {{range .SnList}}{{.}} {{end}} | {{.Qty}} | {{.StationNo}} | {{.Operator}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无序列号件实绩。
+ {{end}}
+
+
三、用料清单 · 批次件
+ {{if .BatchMaterials}}
+
+ | 图号 | 名称 | 类型 | 规格 | 单位 | 批次号 | 数量 | 装配工位 | 装配人 |
+
+ {{range .BatchMaterials}}
+
+ | {{.MaterialCode}} | {{.MaterialName}} | {{.MaterialType}} | {{.Spec}} | {{.Unit}} |
+ {{.BatchNo}} | {{.Qty}} | {{.StationNo}} | {{.Operator}} |
+
+ {{end}}
+
+
+ {{else}}
+
暂无批次件实绩。
+ {{end}}
+
+ {{if .TorqueRows}}
+
四、拧紧数据
+
+ | 螺丝编号 | 扭矩(N·m) | 角度(°) | 结果 | 操作人 | 时间 |
+
+ {{range .TorqueRows}}
+ | {{.ScrewNo}} | {{.Torque}} | {{.Angle}} |
+ {{if eq .Result "NG"}}NG{{else}}OK{{end}} |
+ {{.Operator}} | {{.Time}} |
+ {{end}}
+
+
+ {{end}}
+
+
五、签字确认
+
+
操作工:{{if .Signs.Operator}}{{.Signs.Operator.Names}}{{else}}待签{{end}}
+
检验员:{{if .Signs.Inspector}}{{.Signs.Inspector.Names}}{{else}}待签{{end}}
+
审核人:{{if .Signs.Auditor}}{{.Signs.Auditor.Names}}{{else}}待签{{end}}
+
批准人:手签
+
+
+
+
+
+
+
+`
+
+ tmpl, err := template.New("sntracecard").
+ Funcs(template.FuncMap{"manageModeCN": manageModeCN, "snModeCN": snModeCN}).
+ Parse(tpl)
+ if err != nil {
+ return "", err
+ }
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, c); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
diff --git a/bj_power_mes/internal/handler/processflow.go b/bj_power_mes/internal/handler/processflow.go
index 40387b4..e393b68 100644
--- a/bj_power_mes/internal/handler/processflow.go
+++ b/bj_power_mes/internal/handler/processflow.go
@@ -10,13 +10,13 @@ import (
"github.com/zeromicro/go-zero/rest/pathvar"
)
-// ListProcessFlowsHandler GET /process-flows?stationNo=
+// ListProcessFlowsHandler GET /process-flows?stationNo=&pp=(pp=按产品工艺名称反查过滤)
func ListProcessFlowsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
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, page, pageSize)
+ data, err := logic.New(svcCtx).ListFlows(r.Context(), stationNo, r.URL.Query().Get("pp"), page, pageSize)
if err != nil {
httpx.Fail(w, 2201, err.Error())
return
diff --git a/bj_power_mes/internal/handler/production/material.go b/bj_power_mes/internal/handler/production/material.go
index 63bff3f..3471cec 100644
--- a/bj_power_mes/internal/handler/production/material.go
+++ b/bj_power_mes/internal/handler/production/material.go
@@ -2,9 +2,12 @@ package production
import (
"net/http"
+ "strconv"
+ "strings"
"bj_power_mes/common/httpx"
"bj_power_mes/ent"
+ material "bj_power_mes/ent/material"
"bj_power_mes/internal/logic"
"bj_power_mes/internal/svc"
)
@@ -13,16 +16,31 @@ import (
// 两库对等的核心收益:WMS 宕机时本接口照常可用。
// 响应 [{code,name,spec,unit,manageMode,snMode}]:manageMode=类型 1结构件/2电气件/3其他(仅分类);
// snMode=是否逐件SN管理 0未选择/1序列号件(录SN)/2批次件(不录SN),行为唯一依据。
+// 大数据量治理:支持 keyword(图号/名称 模糊,ILIKE)过滤 + limit(默认100、封顶200),
+// 避免一次性全量返回造成数据炸弹;下拉框按需远程搜索。
// 本地为空(冷启动)时异步自 WMS 全量拉取补齐(M7),并顺带异步重推 sync_pending 行(M3);
// 均不阻塞响应、失败静默。
func ListMaterialsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logic.New(svcCtx).EnsureMaterialCacheAsync()
+ q := r.URL.Query()
+ keyword := strings.TrimSpace(q.Get("keyword"))
+ limit := 100
+ if l, err := strconv.Atoi(q.Get("limit")); err == nil && l > 0 {
+ if l > 200 {
+ l = 200
+ }
+ limit = l
+ }
+ query := svcCtx.EntClient.Material.Query()
+ if keyword != "" {
+ query = query.Where(material.Or(
+ material.CodeContains(keyword),
+ material.NameContains(keyword),
+ ))
+ }
+ rows, err := query.Order(ent.Desc("id")).Limit(limit).All(r.Context())
list := []map[string]any{}
- rows, err := svcCtx.EntClient.Material.Query().
- Order(ent.Desc("id")).
- Limit(1000).
- All(r.Context())
if err == nil {
for _, m := range rows {
list = append(list, map[string]any{
@@ -164,7 +182,12 @@ func ReceiveMaterialRequestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc
RequestNo string `json:"requestNo"`
Qty int `json:"qty"`
}
- if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" {
+ // ParseJSON 失败与 requestNo 为空分开报,避免误导入参正确却看不到真实原因(AITEST 闭环实测)
+ if err := httpx.ParseJSON(r, &req); err != nil {
+ httpx.BadRequest(w, "请求体解析失败")
+ return
+ }
+ if req.RequestNo == "" {
httpx.BadRequest(w, "缺少备料单号")
return
}
@@ -184,7 +207,11 @@ func StationReceiveMaterialInternalHandler(svcCtx *svc.ServiceContext) http.Hand
RequestNo string `json:"requestNo"`
Qty int `json:"qty"`
}
- if err := httpx.ParseJSON(r, &req); err != nil || req.RequestNo == "" {
+ if err := httpx.ParseJSON(r, &req); err != nil {
+ httpx.BadRequest(w, "请求体解析失败")
+ return
+ }
+ if req.RequestNo == "" {
httpx.BadRequest(w, "缺少备料单号")
return
}
diff --git a/bj_power_mes/internal/handler/production/production.go b/bj_power_mes/internal/handler/production/production.go
index 91b4145..45762fa 100644
--- a/bj_power_mes/internal/handler/production/production.go
+++ b/bj_power_mes/internal/handler/production/production.go
@@ -220,7 +220,7 @@ type orderRow struct {
func OrderQueryInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
orderNo := r.URL.Query().Get("orderNo")
- list, err := logic.New(svcCtx).ListWorkOrders(r.Context(), orderNo, "", "", "", "", "", "", "")
+ list, err := logic.New(svcCtx).ListWorkOrders(r.Context(), orderNo, "", "", "", "", "", "", "", "", 0)
if err != nil {
httpx.Fail(w, 2004, err.Error())
return
diff --git a/bj_power_mes/internal/handler/production/sign.go b/bj_power_mes/internal/handler/production/sign.go
index 8909b65..67e164f 100644
--- a/bj_power_mes/internal/handler/production/sign.go
+++ b/bj_power_mes/internal/handler/production/sign.go
@@ -35,11 +35,48 @@ func SignPendingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
Page: atoiDefault(q.Get("page"), 1),
PageSize: atoiDefault(q.Get("pageSize"), 50),
}
- data, total, err := logic.New(svcCtx).PendingSigns(r.Context(), f)
+ data, total, err := logic.New(svcCtx).PendingSigns(r.Context(), f)
+ if err != nil {
+ httpx.Fail(w, 3302, err.Error())
+ return
+ }
+ httpx.Ok(w, map[string]any{"list": data, "total": total})
+ }
+}
+
+// AuditorSignHandler 审核人复核签字(工序级审核 gate,工艺配置 needAudit 决定)。
+func AuditorSignHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ var req logic.AuditorSignReq
+ if err := httpx.ParseJSON(r, &req); err != nil {
+ httpx.BadRequest(w, "请求体解析失败")
+ return
+ }
+ if err := logic.New(svcCtx).AuditorSign(r.Context(), req, operator(r, "")); err != nil {
+ httpx.Fail(w, 3303, err.Error())
+ return
+ }
+ httpx.OkMessage(w, "审核成功", nil)
+ }
+}
+
+// AuditPendingHandler 待审核列表(审核人「待审任务」数据源)。
+func AuditPendingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ f := logic.PendingAuditFilter{
+ Sn: q.Get("sn"),
+ OrderNo: q.Get("orderNo"),
+ StationNo: q.Get("stationNo"),
+ Page: atoiDefault(q.Get("page"), 1),
+ PageSize: atoiDefault(q.Get("pageSize"), 50),
+ }
+ data, total, err := logic.New(svcCtx).PendingAudits(r.Context(), f)
if err != nil {
- httpx.Fail(w, 3302, err.Error())
+ httpx.Fail(w, 3304, err.Error())
return
}
httpx.Ok(w, map[string]any{"list": data, "total": total})
}
}
+
diff --git a/bj_power_mes/internal/handler/production/workorder.go b/bj_power_mes/internal/handler/production/workorder.go
index 5a66ab1..b3442ef 100644
--- a/bj_power_mes/internal/handler/production/workorder.go
+++ b/bj_power_mes/internal/handler/production/workorder.go
@@ -113,9 +113,17 @@ func ExportProductTypesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
func ListWorkOrdersHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
+ // keyword+limit:下拉远程搜索(limit>0 才截断,封顶 200);列表页不传=全量,行为不变
+ limit := 0
+ if v := q.Get("limit"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ limit = n
+ }
+ }
data, err := logic.New(svcCtx).ListWorkOrders(r.Context(),
q.Get("orderNo"), q.Get("status"), q.Get("productCode"), q.Get("productName"),
- q.Get("contractNo"), q.Get("ownershipType"), q.Get("dueFrom"), q.Get("dueTo"))
+ q.Get("contractNo"), q.Get("ownershipType"), q.Get("dueFrom"), q.Get("dueTo"),
+ q.Get("keyword"), limit)
if err != nil {
httpx.Fail(w, 3004, err.Error())
return
@@ -135,7 +143,8 @@ func CreateWorkOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 3005, err.Error())
return
}
- httpx.OkMessage(w, "创建成功", nil)
+ // 产品工艺偏差警告(仅提示不阻断):覆盖/顺序/个数与来源产品工艺不一致时返回 warnings
+ httpx.Ok(w, map[string]any{"warnings": logic.New(svcCtx).ComboDeviationWarnings(r.Context(), req.ProductProcessId, req.FlowCombination)})
}
}
@@ -150,7 +159,8 @@ func UpdateWorkOrderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
httpx.Fail(w, 3006, err.Error())
return
}
- httpx.OkMessage(w, "更新成功", nil)
+ // 产品工艺偏差警告(仅提示不阻断)
+ httpx.Ok(w, map[string]any{"warnings": logic.New(svcCtx).ComboDeviationWarnings(r.Context(), req.ProductProcessId, req.FlowCombination)})
}
}
diff --git a/bj_power_mes/internal/handler/production/workpiece_semi.go b/bj_power_mes/internal/handler/production/workpiece_semi.go
index 654b302..edaf8f7 100644
--- a/bj_power_mes/internal/handler/production/workpiece_semi.go
+++ b/bj_power_mes/internal/handler/production/workpiece_semi.go
@@ -50,7 +50,14 @@ func DoneWorkpieceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
func ListWorkpiecesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
- data, err := logic.New(svcCtx).ListWorkpieces(r.Context(), q.Get("sn"), q.Get("orderNo"))
+ // limit:下拉远程搜索场景传参(封顶 200);不传默认 500,行为向后兼容
+ limit := 0
+ if v := q.Get("limit"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ limit = n
+ }
+ }
+ data, err := logic.New(svcCtx).ListWorkpieces(r.Context(), q.Get("sn"), q.Get("orderNo"), limit)
if err != nil {
httpx.Fail(w, 3304, err.Error())
return
diff --git a/bj_power_mes/internal/handler/productprocess.go b/bj_power_mes/internal/handler/productprocess.go
new file mode 100644
index 0000000..619082f
--- /dev/null
+++ b/bj_power_mes/internal/handler/productprocess.go
@@ -0,0 +1,88 @@
+package handler
+
+import (
+ "net/http"
+
+ "bj_power_mes/common/httpx"
+ "bj_power_mes/internal/logic"
+ "bj_power_mes/internal/svc"
+)
+
+// ---------- 产品工艺(2026-10-09 定稿:产品级工艺定义,有序工艺集合不绑工位) ----------
+
+// ListProductProcessesHandler GET /product-processes?productCode=&status=&flowId=&keyword=&page=&pageSize=
+// page=0 返回全量数组(工单页下拉用);page>0 返回 {total,list,page,pageSize}
+func ListProductProcessesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ 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)
+ if err != nil {
+ httpx.Fail(w, 2231, err.Error())
+ return
+ }
+ httpx.Ok(w, data)
+ }
+}
+
+// DeriveProductProcessHandler GET /product-processes/derive?productCode=&id=
+// 建单自动推导:每道工艺带出全部启用的绑定工位,返回 {productProcessId,name,items,combination,warnings}
+func DeriveProductProcessHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ data, err := logic.New(svcCtx).DeriveProductProcess(r.Context(), q.Get("productCode"), atoiDefault(q.Get("id"), 0))
+ if err != nil {
+ httpx.Fail(w, 2232, err.Error())
+ return
+ }
+ httpx.Ok(w, data)
+ }
+}
+
+// SaveProductProcessHandler POST/PUT /product-processes(新建或更新,明细整表覆盖)
+func SaveProductProcessHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ var req logic.ProductProcessReq
+ if err := httpx.ParseJSON(r, &req); err != nil {
+ httpx.BadRequest(w, "请求体解析失败")
+ return
+ }
+ if err := logic.New(svcCtx).SaveProductProcess(r.Context(), req, operator(r, "")); err != nil {
+ httpx.Fail(w, 2233, err.Error())
+ return
+ }
+ httpx.OkMessage(w, "产品工艺已保存", nil)
+ }
+}
+
+// SetProductProcessStatusHandler POST /product-processes/status(启用/停用,停用不删)
+func SetProductProcessStatusHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Id int `json:"id"`
+ Status string `json:"status"`
+ }
+ if err := httpx.ParseJSON(r, &req); err != nil {
+ httpx.BadRequest(w, "请求体解析失败")
+ return
+ }
+ if err := logic.New(svcCtx).SetProductProcessStatus(r.Context(), req.Id, req.Status, operator(r, "")); err != nil {
+ httpx.Fail(w, 2234, err.Error())
+ return
+ }
+ httpx.OkMessage(w, "操作成功", nil)
+ }
+}
+
+// DeleteProductProcessHandler DELETE /product-processes/:id(被工单引用过禁止删除)
+func DeleteProductProcessHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if err := logic.New(svcCtx).DeleteProductProcess(r.Context(), pathId(r), operator(r, "")); err != nil {
+ httpx.Fail(w, 2235, err.Error())
+ return
+ }
+ httpx.OkMessage(w, "产品工艺已删除", nil)
+ }
+}
diff --git a/bj_power_mes/internal/handler/productprocess_card.go b/bj_power_mes/internal/handler/productprocess_card.go
new file mode 100644
index 0000000..31e7d3f
--- /dev/null
+++ b/bj_power_mes/internal/handler/productprocess_card.go
@@ -0,0 +1,334 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "html/template"
+ "net/http"
+ "strings"
+
+ "bj_power_mes/common/httpx"
+ "bj_power_mes/ent"
+ "bj_power_mes/ent/flowmaterial"
+ "bj_power_mes/ent/processstep"
+ "bj_power_mes/ent/productprocess"
+ "bj_power_mes/ent/productprocessitem"
+ "bj_power_mes/ent/stepcriterion"
+ "bj_power_mes/ent/station"
+ "bj_power_mes/internal/svc"
+)
+
+// ============================================================================
+// 工艺路线卡(产品级定义层卡片,2026-10-09 客户裁定恢复)
+//
+// 定位:回答「这个产品应该怎么做」——产品工艺的路线 + 每道工艺的步骤配置 + BOM + 检验卡项。
+// 与「生产流程卡」(工单实绩层)分离:本卡只读定义、不复制不落表;工单页不嵌入本卡,
+// 工单想看定义层时跳转到「产品工艺」页查看/打印(客户裁定)。
+// 端点:GET /api/v1/product-processes/card?id=N 默认可打印 HTML;?format=json 返回结构化数据。
+// ============================================================================
+
+type ppCardData struct {
+ Name string `json:"name"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ StatusCN string `json:"statusCN"`
+ IsDefault bool `json:"isDefault"`
+ Remark string `json:"remark"`
+ GeneratedAt string `json:"generatedAt"`
+ Items []ppCardItem `json:"items"`
+ Checks []ppCardCheck `json:"checks"`
+}
+
+type ppCardItem struct {
+ Seq int `json:"seq"`
+ FlowName string `json:"flowName"`
+ StationNos string `json:"stationNos"`
+ CheckCnt int `json:"checkCnt"` // 本工艺内需检测确认的步骤数(模板汇总用)
+ Steps []ppCardStep `json:"steps"`
+ Bom []ppCardBom `json:"bom"`
+}
+
+type ppCardStep struct {
+ Seq int `json:"seq"`
+ Name string `json:"name"`
+ CollectCN string `json:"collectCN"`
+ IsTorque bool `json:"isTorque"`
+ NeedCheck bool `json:"needCheck"`
+ NeedOperatorSign bool `json:"needOperatorSign"`
+ NeedInspectorSign bool `json:"needInspectorSign"`
+ NeedAudit bool `json:"needAudit"`
+ AuditRole string `json:"auditRole"`
+ Remark string `json:"remark"`
+}
+
+type ppCardBom struct {
+ MaterialCode string `json:"materialCode"`
+ MaterialName string `json:"materialName"`
+ Spec string `json:"spec"`
+ Unit string `json:"unit"`
+ SnModeCN string `json:"snModeCN"`
+ UnitQty float64 `json:"unitQty"`
+ LossRate float64 `json:"lossRate"`
+}
+
+type ppCardCheck struct {
+ FlowName string `json:"flowName"`
+ StepName string `json:"stepName"`
+ Criteria string `json:"criteria"`
+}
+
+func ppCollectCN(v string) string {
+ switch v {
+ case "AUTO":
+ return "拧紧枪自动"
+ case "MANUAL":
+ return "手填"
+ case "NONE":
+ return "仅记录"
+ }
+ return v
+}
+
+func buildProductProcessCard(ctx context.Context, svcCtx *svc.ServiceContext, id int) (*ppCardData, error) {
+ client := svcCtx.EntClient
+ pp, err := client.ProductProcess.Query().Where(productprocess.ID(id)).First(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("产品工艺 %d 不存在", id)
+ }
+ card := &ppCardData{
+ Name: pp.Name, ProductCode: pp.ProductCode, ProductName: pp.ProductName,
+ StatusCN: map[bool]string{true: "启用", false: "停用"}[pp.Status == "ACTIVE"],
+ IsDefault: pp.IsDefault, Remark: pp.Remark, GeneratedAt: nowText(),
+ Items: []ppCardItem{}, Checks: []ppCardCheck{},
+ }
+ items, err := client.ProductProcessItem.Query().
+ Where(productprocessitem.ProductProcessId(id)).
+ Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ flows, _ := client.ProcessFlow.Query().All(ctx)
+ flowName := map[int]string{}
+ for _, f := range flows {
+ flowName[f.ID] = f.Name
+ }
+ sts, _ := client.Station.Query().Where(station.Status("ENABLED"), station.FlowIdGT(0)).All(ctx)
+ byFlow := map[int][]int{}
+ for _, st := range sts {
+ byFlow[st.FlowId] = append(byFlow[st.FlowId], st.StationNo)
+ }
+ for _, it := range items {
+ row := ppCardItem{
+ Seq: it.Seq, FlowName: flowName[it.FlowId],
+ StationNos: joinInts(byFlow[it.FlowId]),
+ Steps: []ppCardStep{}, Bom: []ppCardBom{},
+ } // 工艺步骤(定义层配置,含签字/审核开关)
+ steps, _ := client.ProcessStep.Query().
+ Where(processstep.FlowId(it.FlowId)).
+ Order(ent.Asc(processstep.FieldSeq)).All(ctx)
+ for _, st := range steps {
+ row.Steps = append(row.Steps, ppCardStep{
+ Seq: st.Seq, Name: st.Name, CollectCN: ppCollectCN(st.CollectType),
+ IsTorque: st.IsTorque, NeedCheck: st.NeedCheck,
+ NeedOperatorSign: st.NeedOperatorSign, NeedInspectorSign: st.NeedInspectorSign,
+ NeedAudit: st.NeedAudit, AuditRole: st.AuditRole, Remark: st.Remark,
+ })
+ if st.NeedCheck {
+ row.CheckCnt++
+ // 检验卡项:汇总判定标准
+ crits, _ := client.StepCriterion.Query().
+ Where(stepcriterion.StepId(st.ID)).All(ctx)
+ parts := []string{}
+ for _, c := range crits {
+ one := c.Name
+ switch c.Logic {
+ case "BETWEEN":
+ one += fmt.Sprintf(" %g~%g", c.Min, c.Max)
+ case "GT":
+ one += fmt.Sprintf(" >%g", c.Target)
+ case "LT":
+ one += fmt.Sprintf(" <%g", c.Target)
+ case "EQ":
+ one += fmt.Sprintf(" =%g", c.Target)
+ }
+ if c.Unit != "" {
+ one += c.Unit
+ }
+ parts = append(parts, one)
+ }
+ if len(parts) == 0 {
+ parts = []string{"按作业要求检验确认"}
+ }
+ card.Checks = append(card.Checks, ppCardCheck{
+ FlowName: flowName[it.FlowId], StepName: st.Name,
+ Criteria: strings.Join(parts, ";"),
+ })
+ }
+ }
+ // 物料清单(BOM 定义挂在工艺上)
+ fms, _ := client.FlowMaterial.Query().
+ Where(flowmaterial.FlowId(it.FlowId)).All(ctx)
+ for _, m := range fms {
+ row.Bom = append(row.Bom, ppCardBom{
+ MaterialCode: m.MaterialCode, MaterialName: m.MaterialName,
+ Spec: m.Spec, Unit: m.Unit, SnModeCN: snModeCN(m.SnMode),
+ UnitQty: m.UnitQty, LossRate: m.LossRate,
+ })
+ }
+ card.Items = append(card.Items, row)
+ }
+ return card, nil
+}
+
+// ProductProcessCardHandler GET /api/v1/product-processes/card?id=N
+func ProductProcessCardHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ id := atoiDefault(r.URL.Query().Get("id"), 0)
+ if id <= 0 {
+ httpx.BadRequest(w, "缺少产品工艺 id 参数")
+ return
+ }
+ card, err := buildProductProcessCard(r.Context(), svcCtx, id)
+ if err != nil {
+ httpx.Fail(w, 2236, err.Error())
+ return
+ }
+ if r.URL.Query().Get("format") == "json" {
+ httpx.Ok(w, card)
+ return
+ }
+ html, err := renderProductProcessCard(card)
+ if err != nil {
+ httpx.Fail(w, 2237, "工艺路线卡生成失败:"+err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = w.Write([]byte(html))
+ }
+}
+
+func renderProductProcessCard(c *ppCardData) (string, error) {
+ const tpl = `
+
+
+
+工艺路线卡 {{.ProductCode}}
+
+
+
+
+
工艺路线卡(产品级 · 定义层)
+
+ 产品工艺:{{.Name}}
+ 产品编码:{{.ProductCode}}
+ 产品名称:{{.ProductName}}
+ 状态:{{.StatusCN}}
+ {{if .IsDefault}}默认路线{{end}}
+ 生成时间:{{.GeneratedAt}}
+
+ {{if .Remark}}
备注:{{.Remark}}
{{end}}
+
+
一、工艺路线(按顺序执行)
+
+ | 道次 | 工艺 | 绑定工位 | 步骤数 | 检验点数 | BOM 条目 |
+
+ {{range .Items}}
+
+ | 第{{.Seq}}道 | {{.FlowName}} | {{if .StationNos}}{{.StationNos}}{{else}}暂无绑定{{end}} |
+ {{len .Steps}} | {{.CheckCnt}} | {{len .Bom}} |
+
+ {{end}}
+
+
+
+
二、工艺步骤配置(定义层)
+ {{range .Items}}
+
第{{.Seq}}道 · {{.FlowName}}
+ {{if .Steps}}
+
+ | 序号 | 步骤 | 采集方式 | 拧紧 | 检测确认 | 操作工签 | 检验员签 | 审核 | 备注 |
+
+ {{range .Steps}}
+
+ | {{.Seq}} | {{.Name}} | {{.CollectCN}} |
+ {{if .IsTorque}}是{{else}}-{{end}} |
+ {{if .NeedCheck}}需检验{{else}}-{{end}} |
+ {{if .NeedOperatorSign}}需签{{else}}-{{end}} |
+ {{if .NeedInspectorSign}}需签{{else}}-{{end}} |
+ {{if .NeedAudit}}需审核{{if .AuditRole}}({{.AuditRole}}){{end}}{{else}}-{{end}} |
+ {{.Remark}} |
+
+ {{end}}
+
+
+ {{else}}
该工艺暂无步骤配置。
{{end}}
+ {{end}}
+
+
三、物料清单(BOM 定义)
+ {{$hasBom := false}}{{range .Items}}{{if .Bom}}{{$hasBom = true}}{{end}}{{end}}
+ {{if $hasBom}}
+
+ | 所属工艺 | 图号 | 名称 | 规格 | 单位 | 序列号管理 | 单台用量 | 损耗率% |
+
+ {{range $it := .Items}}{{range $b := $it.Bom}}
+
+ | {{$it.FlowName}} | {{$b.MaterialCode}} | {{$b.MaterialName}} |
+ {{$b.Spec}} | {{$b.Unit}} | {{$b.SnModeCN}} | {{$b.UnitQty}} | {{$b.LossRate}} |
+
+ {{end}}{{end}}
+
+
+ {{else}}
+
各工艺暂无物料清单(BOM 定义在「工艺」页维护)。
+ {{end}}
+
+
四、检验卡项(需检测确认的步骤汇总)
+ {{if .Checks}}
+
+ | 工艺 | 步骤 | 判定标准 |
+
+ {{range .Checks}}
+ | {{.FlowName}} | {{.StepName}} | {{.Criteria}} |
+ {{end}}
+
+
+ {{else}}
+
该产品工艺的各步骤均未开启「检测确认」。
+ {{end}}
+
+
+
+
+
+
+`
+
+ tmpl, err := template.New("ppcard").Parse(tpl)
+ if err != nil {
+ return "", err
+ }
+ var buf bytes.Buffer
+ if err := tmpl.Execute(&buf, c); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
diff --git a/bj_power_mes/internal/handler/routes_production.go b/bj_power_mes/internal/handler/routes_production.go
index db9b018..912cc5e 100644
--- a/bj_power_mes/internal/handler/routes_production.go
+++ b/bj_power_mes/internal/handler/routes_production.go
@@ -209,6 +209,8 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
// ---------- 签字机制(需求B):操作工报工签字随 /workpiece/report 落库;检验员签字为独立动作 ----------
{Method: http.MethodPost, Path: "/signs/inspector", Handler: production.InspectorSignHandler(serverCtx)},
{Method: http.MethodGet, Path: "/signs/pending", Handler: production.SignPendingHandler(serverCtx)},
+ {Method: http.MethodPost, Path: "/signs/auditor", Handler: production.AuditorSignHandler(serverCtx)},
+ {Method: http.MethodGet, Path: "/signs/audit-pending", Handler: production.AuditPendingHandler(serverCtx)},
{Method: http.MethodGet, Path: "/process-steps", Handler: production.ProcessStepsHandler(serverCtx)},
@@ -252,6 +254,16 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
{Method: http.MethodGet, Path: "/stations", Handler: ListStationsHandler(serverCtx)},
{Method: http.MethodPost, Path: "/stations", Handler: SaveStationHandler(serverCtx)},
{Method: http.MethodDelete, Path: "/stations/:id", Handler: DeleteStationHandler(serverCtx)},
+
+ // ---------- 产品工艺(2026-10-09 定稿:产品级工艺定义,有序工艺集合不绑工位;建单时推导工位) ----------
+ // derive 需注册在 :id 语义之外(无 GET /:id 路由,无冲突)
+ {Method: http.MethodGet, Path: "/product-processes", Handler: ListProductProcessesHandler(serverCtx)},
+ {Method: http.MethodGet, Path: "/product-processes/derive", Handler: DeriveProductProcessHandler(serverCtx)},
+ {Method: http.MethodGet, Path: "/product-processes/card", Handler: ProductProcessCardHandler(serverCtx)},
+ {Method: http.MethodPost, Path: "/product-processes", Handler: SaveProductProcessHandler(serverCtx)},
+ {Method: http.MethodPut, Path: "/product-processes", Handler: SaveProductProcessHandler(serverCtx)},
+ {Method: http.MethodPost, Path: "/product-processes/status", Handler: SetProductProcessStatusHandler(serverCtx)},
+ {Method: http.MethodDelete, Path: "/product-processes/:id", Handler: DeleteProductProcessHandler(serverCtx)},
{Method: http.MethodGet, Path: "/line/points", Handler: ListPointsHandler(serverCtx)},
{Method: http.MethodPost, Path: "/line/call-material", Handler: CallMaterialHandler(serverCtx)},
@@ -285,10 +297,10 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
{Method: http.MethodGet, Path: "/performance", Handler: WorkloadInternalHandler(serverCtx)},
{Method: http.MethodGet, Path: "/performance/export", Handler: PerformanceExportHandler(serverCtx)},
- // ---------- 流程卡打印(块7) ----------
- {Method: http.MethodGet, Path: "/process-card", Handler: ProcessCardHandler(serverCtx)},
- // 产品型号级全景流程卡(D2):按型号聚合 工位组合→工艺流程/步骤→物料清单→检验卡项
- {Method: http.MethodGet, Path: "/process-card/model", Handler: ModelProcessCardHandler(serverCtx)},
+ // ---------- 生产流程卡(工单维度主卡 + 成品 SN 追溯卡 + 型号筛选) ----------
+ {Method: http.MethodGet, Path: "/process-card/workorder", Handler: WorkOrderCardHandler(serverCtx)},
+ {Method: http.MethodGet, Path: "/process-card/by-sn", Handler: SnTraceCardHandler(serverCtx)},
+ {Method: http.MethodGet, Path: "/process-card/by-model", Handler: ModelWorkOrdersHandler(serverCtx)},
// ---------- 工艺物料清单(flow_material,一份工艺定义一份清单) ----------
{Method: http.MethodGet, Path: "/process-flows/:id/materials", Handler: production.ListFlowMaterialsHandler(serverCtx)},
diff --git a/bj_power_mes/internal/logic/material.go b/bj_power_mes/internal/logic/material.go
index f57200d..364014a 100644
--- a/bj_power_mes/internal/logic/material.go
+++ b/bj_power_mes/internal/logic/material.go
@@ -98,6 +98,14 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
return 0, missing, nil
}
// 阶段2:全部存在 → 按 组合条目 × flow_material × 分产量 拆料生成
+ // 幂等查重(AITEST 闭环实测缺陷):同 工单+排产日+物料+工位+工艺 已有备料单则跳过,
+ // 否则每次调用 generate 都翻倍生成重复单据(重复出库/重复备料,生产级事故源)。
+ existing, _ := s.ctx.EntClient.MaterialRequest.Query().
+ Where(materialrequest.PlanDateEQ(planDate)).All(ctx)
+ existKey := make(map[string]bool, len(existing))
+ for _, mr := range existing {
+ existKey[mr.OrderNo+"|"+mr.MaterialCode+"|"+strconv.Itoa(mr.StationNo)+"|"+strconv.Itoa(mr.FlowId)] = true
+ }
created := 0
tsBase := time.Now().Format("20060102150405")
seq := 1
@@ -137,16 +145,23 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
if fm.MaterialCode == "" {
continue
}
- for i, stNo := range stations {
- q := qtys[i]
- if q <= 0 {
- continue
- }
- reqQty := float64(q) * fm.UnitQty * (1 + fm.LossRate/100)
- if reqQty <= 0 {
- continue
- }
- reqNo := fmt.Sprintf("MR%s%03d", tsBase, seq)
+ for i, stNo := range stations {
+ q := qtys[i]
+ if q <= 0 {
+ continue
+ }
+ // 损耗向上取整:备料单需求数量必须为整数(接料/出库按整数收发),
+ // 小数 reqQty 会使接料接口(int)永远无法收满、备料单永远无法完结(AITEST 闭环实测缺陷)
+ reqQty := math.Ceil(float64(q) * fm.UnitQty * (1 + fm.LossRate/100))
+ if reqQty <= 0 {
+ continue
+ }
+ // 幂等:该 工单+物料+工位+工艺 当日已有单则跳过(重复调用不翻倍)
+ dedupKey := g.plan.OrderNo + "|" + fm.MaterialCode + "|" + strconv.Itoa(stNo) + "|" + strconv.Itoa(flowId)
+ if existKey[dedupKey] {
+ continue
+ }
+ reqNo := fmt.Sprintf("MR%s%03d", tsBase, seq)
seq++
_ = s.ctx.EntClient.MaterialRequest.Create().
SetRequestNo(reqNo).SetOrderNo(g.plan.OrderNo).SetPlanDate(g.plan.PlanDate).
@@ -184,30 +199,41 @@ func (s *Service) GenerateMaterialRequest(ctx context.Context, planDate string,
// SyncOrderLedger 计算并向 WMS 下发某工单的「工单级物料需求总量」(需求10)。
//
-// 需求量口径(临时.md §四 工单域):需求量 = 工单数量 × 单台含损耗用量,向上取整。
-// 工单级而非日级——用日级会误卡跨天生产(临时.md L283-285)。
-// 用料唯一来源 = 工单工艺组合×工艺物料清单(BOM 已删除),同物料合并,一个物料一行下发。
-// WMS 侧按 orderNo+materialCode 幂等 upsert total_qty,可重复调用。
+// 需求量口径(AITEST 闭环实测修正):= 该工单全部备料单 reqQty 之和(损耗按工位拆单逐单向上取整)。
+// 原按「工单数量×单台用量」整体取整的算法与工位级拆单逐单取整必然不一致(拆单合计 ≥ 整体取整),
+// 会导致自动出库合计触发 WMS 台账超量拦截、备料单永远无法出齐(如 拆单合计 8 > 整体取整 7)。
+// 改为聚合备料单:total 与单据精确自洽,generate 幂等生成新单后重复调用自动增长,WMS 侧按
+// orderNo+materialCode 幂等 upsert total_qty。
+// 工单尚无备料单时不下发(保持 WMS 既有 total 不变,避免误清零)。
func (s *Service) SyncOrderLedger(ctx context.Context, orderNo, operator string) error {
wo, err := s.ctx.EntClient.WorkOrder.Query().
Where(workorder.WorkOrderNo(orderNo)).Only(ctx)
if err != nil {
return err
}
- usage := s.WorkOrderUnitUsage(ctx, wo)
- if len(usage) == 0 {
+ mrs, err := s.ctx.EntClient.MaterialRequest.Query().
+ Where(materialrequest.OrderNoEQ(orderNo)).All(ctx)
+ if err != nil {
+ return err
+ }
+ if len(mrs) == 0 {
return nil
}
- items := make([]wmsclient.LedgerSyncItem, 0, len(usage))
- for _, it := range usage {
- need := float64(wo.Quantity) * it.EffQty
- if need <= 0 {
+ agg := map[string]int{} // materialCode → ΣreqQty(逐单向上取整后求和)
+ names := map[string]string{}
+ for _, mr := range mrs {
+ agg[mr.MaterialCode] += int(math.Ceil(mr.ReqQty))
+ names[mr.MaterialCode] = mr.MaterialName
+ }
+ items := make([]wmsclient.LedgerSyncItem, 0, len(agg))
+ for code, total := range agg {
+ if total <= 0 {
continue
}
items = append(items, wmsclient.LedgerSyncItem{
- MaterialCode: it.MaterialCode,
- MaterialName: it.MaterialName,
- TotalQty: int(math.Ceil(need - 1e-9)),
+ MaterialCode: code,
+ MaterialName: names[code],
+ TotalQty: total,
})
}
if len(items) == 0 {
@@ -275,7 +301,10 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o
opts.SnList = []string{sn}
opts.BatchNo = ""
opts.Qty = 1
- opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, sn, round)
+ // 幂等键必须含备料单号:同工单+同物料会按工位拆成多张备料单,
+ // 若只用 orderNo+物料做键,各单 round=1 必然撞键——WMS 幂等复用吞掉
+ // 第二张单的扣减,MES 却虚增 sent_qty 并置 LOCKED(账实不符,AITEST 闭环实测)。
+ opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%d", mr.RequestNo, sn, round)
no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts)
if e != nil {
break
@@ -300,7 +329,8 @@ func (s *Service) AutoOutboundRequests(ctx context.Context, planDate, orderNo, o
opts.BatchNo = b.BatchNo
opts.Qty = take
opts.ZoneCode = b.ZoneCode
- opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%s-%d", mr.OrderNo, mr.MaterialCode, b.BatchNo, round)
+ // 同上:幂等键含备料单号,杜绝工位级拆单跨单撞键(AITEST 闭环实测缺陷)
+ opts.IdempotencyKey = fmt.Sprintf("IDEM-%s-%s-%d", mr.RequestNo, b.BatchNo, round)
no, _, _, e := s.ctx.Wms.StockDeduct(ctx, mr.OrderNo, mr.MaterialCode, opts)
if e != nil {
break
diff --git a/bj_power_mes/internal/logic/processflow.go b/bj_power_mes/internal/logic/processflow.go
index 85970f3..bed28b5 100644
--- a/bj_power_mes/internal/logic/processflow.go
+++ b/bj_power_mes/internal/logic/processflow.go
@@ -43,12 +43,14 @@ type FlowVO struct {
Remark string `json:"remark"`
Stations []int `json:"stations"`
Steps []*ProcessStepTemplate `json:"steps"`
- CreatedAt time.Time `json:"createdAt"`
+ // 只读反查:引用本工艺的产品工艺名称列表(产品工艺明细实时反查)
+ ProductProcesses []string `json:"productProcesses"`
+ CreatedAt time.Time `json:"createdAt"`
}
-// ListFlows 查询工艺流程(可按工位号过滤:只认「关联工位」页的绑定关系 station.flow_id)
-// page>0 时真分页返回 map{total,list,page,pageSize}(管理页用);page=0 全量数组(工位终端兼容)
-func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int) (any, error) {
+// 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) {
q := s.ctx.EntClient.ProcessFlow.Query().
Order(ent.Asc(processflow.FieldID))
flows, err := q.All(ctx)
@@ -62,6 +64,7 @@ func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int)
flowToStations[st.FlowId] = append(flowToStations[st.FlowId], st.StationNo)
}
}
+ ppNames := s.productProcessNamesByFlow(ctx)
out := make([]*FlowVO, 0, len(flows))
for _, f := range flows {
// 过滤:指定工位号时,只返回绑定了该工位的流程
@@ -85,6 +88,13 @@ func (s *Service) ListFlows(ctx context.Context, stationNo, page, pageSize int)
if list, ok := flowToStations[f.ID]; ok {
vo.Stations = list
}
+ if vo.ProductProcesses = ppNames[f.ID]; vo.ProductProcesses == nil {
+ vo.ProductProcesses = []string{}
+ }
+ // 产品工艺反查过滤(模糊,大小写无关)
+ if pp != "" && !ppContainsFold(vo.ProductProcesses, pp) {
+ continue
+ }
out = append(out, vo)
}
if page > 0 {
@@ -264,6 +274,8 @@ type StationVO struct {
Status string `json:"status"`
IsBuiltin bool `json:"isBuiltin"`
VisibleTabs []string `json:"visibleTabs"`
+ // 只读反查:本工位绑定工艺被哪些产品工艺引用(名称列表)
+ ProductProcesses []string `json:"productProcesses"`
}
func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) {
@@ -276,12 +288,16 @@ func (s *Service) ListStations(ctx context.Context) ([]*StationVO, error) {
for _, f := range flows {
flowMap[f.ID] = f
}
+ ppNames := s.productProcessNamesByFlow(ctx)
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, VisibleTabs: st.VisibleTabs}
if f, ok := flowMap[st.FlowId]; ok {
vo.FlowName = f.Name
}
+ if vo.ProductProcesses = ppNames[st.FlowId]; vo.ProductProcesses == nil {
+ vo.ProductProcesses = []string{}
+ }
out = append(out, vo)
}
return out, nil
diff --git a/bj_power_mes/internal/logic/producible.go b/bj_power_mes/internal/logic/producible.go
index 0c59763..45062c6 100644
--- a/bj_power_mes/internal/logic/producible.go
+++ b/bj_power_mes/internal/logic/producible.go
@@ -105,7 +105,7 @@ func (s *Service) loadOrderUsage(ctx context.Context, orderNos []string) map[str
// 两系统独立运行约束:未配置 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 地址,无法计算可生产数量")
+ return nil, errors.New("未配置 WMS 服务地址,无法计算可生产数量;请在系统设置中填写 WMS 地址后重试")
}
today := time.Now().Format("2006-01-02")
planQty, err := s.planOrdersBetween(ctx, today, addDays(today, 59))
@@ -139,7 +139,8 @@ func (s *Service) ComputeProducible(ctx context.Context) (*ProducibleResult, err
sort.Strings(codes)
avail, err := s.ctx.Wms.StockAvailable(ctx, codes)
if err != nil {
- return nil, errors.New("拉取 WMS 可用量失败: " + err.Error())
+ // 业务友好提示:不把底层网络/连接技术细节返回给前端;详细错误由 EventLog 与框架日志捕获
+ return nil, errors.New("无法获取 WMS 库存可用量(WMS 服务未启动或网络不可达),排产支撑暂不可用;请检查 WMS 服务状态或稍后重试")
}
// 产品名称映射(本地成品档案优先=M6,工单快照兜底)
diff --git a/bj_power_mes/internal/logic/productprocess.go b/bj_power_mes/internal/logic/productprocess.go
new file mode 100644
index 0000000..9e6d24a
--- /dev/null
+++ b/bj_power_mes/internal/logic/productprocess.go
@@ -0,0 +1,497 @@
+package logic
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "bj_power_mes/ent"
+ "bj_power_mes/ent/productprocess"
+ "bj_power_mes/ent/productprocessitem"
+ "bj_power_mes/ent/workorder"
+)
+
+// ---------- 产品工艺(2026-10-09 定稿) ----------
+//
+// 产品工艺 = 产品级的工艺定义:只选工艺+顺序(seq 严格递增=串行),不绑工位。
+// 工位在建工单时按「工位绑定」(station.flow_id) 自动推导(同工艺的全部启用工位),
+// 并复制为工单工艺组合 flow_combination 快照;产品工艺是模板,工单组合是实例快照。
+// 校验口径(客户裁决):覆盖/顺序校验仅作保存时警告提示,不阻断保存(允许手改组合偏离)。
+
+// ProductProcessItemReq 产品工艺明细项(flows 数组顺序即 seq 顺序)
+type ProductProcessItemReq struct {
+ FlowId int `json:"flowId"`
+}
+
+// ProductProcessReq 产品工艺保存请求
+type ProductProcessReq struct {
+ Id int `json:"id"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ Name string `json:"name"`
+ IsDefault bool `json:"isDefault"`
+ Status string `json:"status"`
+ Remark string `json:"remark"`
+ Flows []ProductProcessItemReq `json:"flows"`
+}
+
+// ProductProcessItemVO 明细行(含实时反查的绑定工位号)
+type ProductProcessItemVO struct {
+ Seq int `json:"seq"`
+ FlowId int `json:"flowId"`
+ FlowName string `json:"flowName"`
+ StationNos []int `json:"stationNos"` // 该工艺当前绑定的启用工位号(升序,实时反查)
+}
+
+// ProductProcessVO 列表/详情视图
+type ProductProcessVO struct {
+ Id int `json:"id"`
+ ProductCode string `json:"productCode"`
+ ProductName string `json:"productName"`
+ Name string `json:"name"`
+ IsDefault bool `json:"isDefault"`
+ Status string `json:"status"`
+ Remark string `json:"remark"`
+ Flows []ProductProcessItemVO `json:"flows"`
+ // 只读:被工单引用次数(>0 时只读:禁编辑禁删,只能停用+新建)
+ UsedByWorkOrders int `json:"usedByWorkOrders"`
+ // 只读:可执行状态(所有工艺都有启用工位绑定且顺序可满足)
+ Executable bool `json:"executable"`
+ NotReady string `json:"notReady"` // 不可执行原因(可执行时为空)
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// 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) {
+ q := s.ctx.EntClient.ProductProcess.Query()
+ if productCode != "" {
+ q = q.Where(productprocess.ProductCodeContains(productCode))
+ }
+ if status != "" {
+ q = q.Where(productprocess.Status(status))
+ }
+ if keyword != "" {
+ kw := productprocess.Or(
+ productprocess.NameContains(keyword),
+ productprocess.ProductCodeContains(keyword),
+ productprocess.ProductNameContains(keyword),
+ )
+ q = q.Where(kw)
+ }
+ // 工艺反查:只要包含该工艺的产品工艺
+ if flowId > 0 {
+ items, err := s.ctx.EntClient.ProductProcessItem.Query().
+ Where(productprocessitem.FlowId(flowId)).All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ ids := make([]int, 0, len(items))
+ for _, it := range items {
+ ids = append(ids, it.ProductProcessId)
+ }
+ if len(ids) == 0 {
+ ids = []int{-1} // 无命中:返回空集
+ }
+ q = q.Where(productprocess.IDIn(ids...))
+ }
+ pps, err := q.Order(ent.Desc(productprocess.FieldCreatedAt), ent.Desc(productprocess.FieldID)).All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ // 名字映射(工艺/工位)
+ flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
+ flowName := map[int]string{}
+ for _, f := range flows {
+ flowName[f.ID] = f.Name
+ }
+ sts, _ := s.ctx.EntClient.Station.Query().All(ctx)
+ byFlow := map[int][]int{}
+ for _, st := range sts {
+ if st.Status == "ENABLED" && st.FlowId > 0 {
+ byFlow[st.FlowId] = append(byFlow[st.FlowId], st.StationNo)
+ }
+ }
+ for k := range byFlow {
+ sort.Ints(byFlow[k])
+ }
+ // 明细按产品工艺分组
+ items, _ := s.ctx.EntClient.ProductProcessItem.Query().
+ Order(ent.Asc(productprocessitem.FieldProductProcessId), ent.Asc(productprocessitem.FieldSeq)).All(ctx)
+ itemsOf := map[int][]*ent.ProductProcessItem{}
+ for _, it := range items {
+ itemsOf[it.ProductProcessId] = append(itemsOf[it.ProductProcessId], it)
+ }
+ // 工单引用计数
+ used := map[int]int{}
+ wos, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessIdGT(0)).All(ctx)
+ for _, w := range wos {
+ used[w.ProductProcessId]++
+ }
+ out := make([]*ProductProcessVO, 0, len(pps))
+ for _, p := range pps {
+ vo := &ProductProcessVO{
+ Id: p.ID, ProductCode: p.ProductCode, ProductName: p.ProductName, Name: p.Name,
+ IsDefault: p.IsDefault, Status: p.Status, Remark: p.Remark,
+ UsedByWorkOrders: used[p.ID], CreatedAt: p.CreatedAt,
+ Flows: []ProductProcessItemVO{},
+ }
+ for _, it := range itemsOf[p.ID] {
+ vo.Flows = append(vo.Flows, ProductProcessItemVO{
+ Seq: it.Seq, FlowId: it.FlowId, FlowName: flowName[it.FlowId],
+ StationNos: byFlow[it.FlowId],
+ })
+ }
+ vo.Executable, vo.NotReady = ppExecutable(vo)
+ out = append(out, vo)
+ }
+ if page > 0 {
+ total := len(out)
+ start := (page - 1) * pageSize
+ if start > total {
+ start = total
+ }
+ end := start + pageSize
+ if end > total {
+ end = total
+ }
+ return map[string]any{"total": total, "list": out[start:end], "page": page, "pageSize": pageSize}, nil
+ }
+ return out, nil
+}
+
+// ppExecutable 可执行判定:每道工艺都有启用的绑定工位,且按 seq 排列后工位号可满足递增
+func ppExecutable(vo *ProductProcessVO) (bool, string) {
+ prev := 0
+ for _, it := range vo.Flows {
+ if len(it.StationNos) == 0 {
+ return false, fmt.Sprintf("第%d道工艺「%s」暂无启用的绑定工位", it.Seq, it.FlowName)
+ }
+ if prev > 0 && it.StationNos[0] <= prev {
+ return false, fmt.Sprintf("第%d道工艺「%s」(工位%d) 与上一道工位顺序冲突", it.Seq, it.FlowName, it.StationNos[0])
+ }
+ prev = it.StationNos[len(it.StationNos)-1]
+ }
+ return true, ""
+}
+
+// SaveProductProcess 保存产品工艺(新建或整表覆盖明细)。
+// 约束:① 名称/产品必填,明细非空;② 同一工艺不能在同一产品工艺内出现两次(客户裁决);
+// ③ is_default 每产品至多一条(设新自动取消旧);④ 被工单引用过的只读,禁编辑。
+func (s *Service) SaveProductProcess(ctx context.Context, req ProductProcessReq, operator string) error {
+ if strings.TrimSpace(req.Name) == "" {
+ return errors.New("请填写产品工艺名称")
+ }
+ if strings.TrimSpace(req.ProductCode) == "" {
+ return errors.New("请选择产品")
+ }
+ if len(req.Flows) == 0 {
+ return errors.New("请至少选择一道工艺")
+ }
+ seen := map[int]bool{}
+ for _, f := range req.Flows {
+ if f.FlowId <= 0 {
+ return errors.New("工艺选择无效")
+ }
+ if seen[f.FlowId] {
+ return errors.New("同一工艺不能在同一产品工艺内出现两次")
+ }
+ seen[f.FlowId] = true
+ if _, err := s.ctx.EntClient.ProcessFlow.Get(ctx, f.FlowId); err != nil {
+ return errors.New("所选工艺不存在(ID=" + fmt.Sprint(f.FlowId) + ")")
+ }
+ }
+ status := req.Status
+ if status == "" {
+ status = "ACTIVE"
+ }
+ if status != "ACTIVE" && status != "INACTIVE" {
+ return errors.New("非法状态")
+ }
+ // is_default 唯一性:设为默认时取消同产品旧默认
+ clearDefault := func(code string) {
+ _, _ = s.ctx.EntClient.ProductProcess.Update().
+ Where(productprocess.ProductCode(code), productprocess.IsDefault(true)).
+ SetIsDefault(false).Save(ctx)
+ }
+ var ppID int
+ if req.Id > 0 {
+ old, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.Id)
+ if err != nil {
+ return errors.New("产品工艺不存在")
+ }
+ if n, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessId(req.Id)).Count(ctx); n > 0 {
+ return errors.New(fmt.Sprintf("该产品工艺已被 %d 张工单引用,只读不可编辑(如需调整请停用后新建)", n))
+ }
+ if _, err := s.ctx.EntClient.ProductProcess.UpdateOneID(req.Id).
+ SetProductCode(req.ProductCode).SetProductName(req.ProductName).
+ SetName(req.Name).SetIsDefault(req.IsDefault).SetStatus(status).SetRemark(req.Remark).
+ Save(ctx); err != nil {
+ return err
+ }
+ ppID = req.Id
+ // 产品编码可能被改:新旧两个编码下的默认都要校正
+ clearDefault(old.ProductCode)
+ if old.ProductCode != req.ProductCode {
+ clearDefault(req.ProductCode)
+ }
+ } else {
+ p, err := s.ctx.EntClient.ProductProcess.Create().
+ SetProductCode(req.ProductCode).SetProductName(req.ProductName).
+ SetName(req.Name).SetIsDefault(req.IsDefault).SetStatus(status).SetRemark(req.Remark).
+ Save(ctx)
+ if err != nil {
+ return err
+ }
+ ppID = p.ID
+ }
+ if req.IsDefault {
+ clearDefault(req.ProductCode)
+ _, _ = s.ctx.EntClient.ProductProcess.UpdateOneID(ppID).SetIsDefault(true).Save(ctx)
+ }
+ // 明细整表覆盖(seq = 数组顺序,从 1 严格递增)
+ _, _ = s.ctx.EntClient.ProductProcessItem.Delete().
+ Where(productprocessitem.ProductProcessId(ppID)).Exec(ctx)
+ for i, f := range req.Flows {
+ if err := s.ctx.EntClient.ProductProcessItem.Create().
+ SetProductProcessId(ppID).SetSeq(i + 1).SetFlowId(f.FlowId).
+ Exec(ctx); err != nil {
+ return err
+ }
+ }
+ s.ctx.EventLog.Write(ctx, "product.process.save", "", operator, "product_process", fmt.Sprint(ppID),
+ "保存产品工艺", map[string]any{"id": ppID, "name": req.Name, "productCode": req.ProductCode, "flows": len(req.Flows)})
+ return nil
+}
+
+// DeleteProductProcess 删除产品工艺(被工单引用过禁止删除,只能停用)
+func (s *Service) DeleteProductProcess(ctx context.Context, id int, operator string) error {
+ if id <= 0 {
+ return errors.New("缺少 id")
+ }
+ if n, _ := s.ctx.EntClient.WorkOrder.Query().Where(workorder.ProductProcessId(id)).Count(ctx); n > 0 {
+ return fmt.Errorf("该产品工艺已被 %d 张工单引用,不能删除(只能停用)", n)
+ }
+ p, err := s.ctx.EntClient.ProductProcess.Get(ctx, id)
+ if err != nil {
+ return errors.New("产品工艺不存在")
+ }
+ _, _ = s.ctx.EntClient.ProductProcessItem.Delete().Where(productprocessitem.ProductProcessId(id)).Exec(ctx)
+ if err := s.ctx.EntClient.ProductProcess.DeleteOneID(id).Exec(ctx); err != nil {
+ return err
+ }
+ s.ctx.EventLog.Write(ctx, "product.process.delete", "", operator, "product_process", fmt.Sprint(id),
+ "删除产品工艺", map[string]any{"id": id, "name": p.Name})
+ return nil
+}
+
+// SetProductProcessStatus 启用/停用(停用不删:历史工单按 product_process_id 反查当时定义)
+func (s *Service) SetProductProcessStatus(ctx context.Context, id int, status, operator string) error {
+ if id <= 0 {
+ return errors.New("缺少 id")
+ }
+ if status != "ACTIVE" && status != "INACTIVE" {
+ return errors.New("非法状态")
+ }
+ p, err := s.ctx.EntClient.ProductProcess.Get(ctx, id)
+ if err != nil {
+ return errors.New("产品工艺不存在")
+ }
+ if p.Status == status {
+ return nil
+ }
+ if err := s.ctx.EntClient.ProductProcess.UpdateOneID(id).SetStatus(status).Exec(ctx); err != nil {
+ return err
+ }
+ action := "停用产品工艺"
+ if status == "ACTIVE" {
+ action = "启用产品工艺"
+ }
+ s.ctx.EventLog.Write(ctx, "product.process.status", "", operator, "product_process", fmt.Sprint(id),
+ action, map[string]any{"id": id, "name": p.Name, "status": status})
+ return nil
+}
+
+// DeriveProductProcess 建单自动推导:按产品取默认(或指定)产品工艺,
+// 每道工艺带出其全部启用的绑定工位(升序),拼成工艺组合与实时警告。
+// 返回 map{productProcessId,name,items,combination,warnings};无产品工艺时 combination 为空并给提示。
+func (s *Service) DeriveProductProcess(ctx context.Context, productCode string, id int) (map[string]any, error) {
+ q := s.ctx.EntClient.ProductProcess.Query()
+ if id > 0 {
+ q = q.Where(productprocess.ID(id))
+ } else if productCode != "" {
+ q = q.Where(productprocess.ProductCode(productCode), productprocess.Status("ACTIVE"))
+ } else {
+ return nil, errors.New("缺少产品编码或产品工艺ID")
+ }
+ pps, err := q.Order(ent.Desc(productprocess.FieldIsDefault), ent.Desc(productprocess.FieldID)).All(ctx)
+ if err != nil {
+ return nil, err
+ }
+ res := map[string]any{
+ "productProcessId": 0, "name": "", "productCode": productCode,
+ "items": []map[string]any{}, "combination": []map[string]int{}, "warnings": []string{},
+ }
+ if len(pps) == 0 {
+ res["warnings"] = []string{"该产品尚未配置产品工艺(可在「产品工艺」页创建)"}
+ return res, nil
+ }
+ pp := pps[0]
+ res["productProcessId"] = pp.ID
+ res["name"] = pp.Name
+ res["productCode"] = pp.ProductCode
+ items, _ := s.ctx.EntClient.ProductProcessItem.Query().
+ Where(productprocessitem.ProductProcessId(pp.ID)).
+ Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
+ flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
+ flowName := map[int]string{}
+ for _, f := range flows {
+ flowName[f.ID] = f.Name
+ }
+ sts, _ := s.ctx.EntClient.Station.Query().All(ctx)
+ byFlow := map[int][]int{}
+ for _, st := range sts {
+ if st.Status == "ENABLED" && st.FlowId > 0 {
+ byFlow[st.FlowId] = append(byFlow[st.FlowId], st.StationNo)
+ }
+ }
+ for k := range byFlow {
+ sort.Ints(byFlow[k])
+ }
+ warns := []string{}
+ itemsVO := []map[string]any{}
+ combination := []map[string]int{}
+ prevMax := 0
+ for _, it := range items {
+ stsOfFlow := byFlow[it.FlowId]
+ itemsVO = append(itemsVO, map[string]any{
+ "seq": it.Seq, "flowId": it.FlowId, "flowName": flowName[it.FlowId], "stationNos": stsOfFlow,
+ })
+ if len(stsOfFlow) == 0 {
+ warns = append(warns, fmt.Sprintf("第%d道工艺「%s」暂无启用的绑定工位,请先在「工位绑定」中绑定", it.Seq, flowName[it.FlowId]))
+ continue
+ }
+ if prevMax > 0 && stsOfFlow[0] <= prevMax {
+ warns = append(warns, fmt.Sprintf("第%d道工艺「%s」(工位%d) 与上一道工位顺序冲突(工位号需按顺序递增)", it.Seq, flowName[it.FlowId], stsOfFlow[0]))
+ }
+ if stsOfFlow[len(stsOfFlow)-1] > prevMax {
+ prevMax = stsOfFlow[len(stsOfFlow)-1]
+ }
+ for _, no := range stsOfFlow {
+ combination = append(combination, map[string]int{"flowId": it.FlowId, "stationNo": no})
+ }
+ }
+ sort.Slice(combination, func(i, j int) bool { return combination[i]["stationNo"] < combination[j]["stationNo"] })
+ res["items"] = itemsVO
+ res["combination"] = combination
+ res["warnings"] = warns
+ return res, nil
+}
+
+// ComboDeviationWarnings 工单工艺组合与产品工艺的偏差警告(仅提示,不阻断保存):
+// ① 覆盖/个数——产品工艺的每道工艺都须出现在组合中,组合不得包含产品工艺之外的工艺;
+// ② 顺序——各道工艺在组合中的首个工位号须按 seq 递增。
+func (s *Service) ComboDeviationWarnings(ctx context.Context, ppId int, combo []map[string]int) []string {
+ if ppId <= 0 {
+ return nil
+ }
+ pp, err := s.ctx.EntClient.ProductProcess.Get(ctx, ppId)
+ if err != nil {
+ return []string{"来源产品工艺已删除,无法比对"}
+ }
+ items, _ := s.ctx.EntClient.ProductProcessItem.Query().
+ Where(productprocessitem.ProductProcessId(ppId)).
+ Order(ent.Asc(productprocessitem.FieldSeq)).All(ctx)
+ if len(items) == 0 {
+ return nil
+ }
+ flows, _ := s.ctx.EntClient.ProcessFlow.Query().All(ctx)
+ flowName := map[int]string{}
+ for _, f := range flows {
+ flowName[f.ID] = f.Name
+ }
+ if len(combo) == 0 {
+ return []string{fmt.Sprintf("未选择工艺组合:产品工艺「%s」共 %d 道工艺均未包含", pp.Name, len(items))}
+ }
+ inCombo := map[int][]int{}
+ for _, c := range combo {
+ fid, no := c["flowId"], c["stationNo"]
+ if fid > 0 && no > 0 {
+ inCombo[fid] = append(inCombo[fid], no)
+ }
+ }
+ for k := range inCombo {
+ sort.Ints(inCombo[k])
+ }
+ ppFlowSet := map[int]bool{}
+ for _, it := range items {
+ ppFlowSet[it.FlowId] = true
+ }
+ // 个数汇总(客户裁决:顺序 或 个数 不符都要提示)——先给一条总数对不上的汇总,明细警告跟在后面
+ have, missingCnt, extraCnt := 0, 0, 0
+ for fid := range inCombo {
+ if ppFlowSet[fid] {
+ have++
+ } else {
+ extraCnt++
+ }
+ }
+ missingCnt = len(items) - have
+ warns := []string{}
+ if missingCnt > 0 || extraCnt > 0 {
+ warns = append(warns, fmt.Sprintf("工艺组合道数与产品工艺不符:产品工艺共 %d 道,组合包含 %d 道(缺 %d 道、多 %d 道)",
+ len(items), have, missingCnt, extraCnt))
+ }
+ prevFirst := 0
+ for _, it := range items {
+ name := flowName[it.FlowId]
+ sts := inCombo[it.FlowId]
+ if len(sts) == 0 {
+ warns = append(warns, fmt.Sprintf("工艺组合缺少第%d道工艺「%s」", it.Seq, name))
+ continue
+ }
+ if prevFirst > 0 && sts[0] <= prevFirst {
+ warns = append(warns, fmt.Sprintf("工艺组合顺序与产品工艺不一致:第%d道「%s」(工位%d) 不在上一道工艺之后", it.Seq, name, sts[0]))
+ }
+ prevFirst = sts[0]
+ }
+ for fid, sts := range inCombo {
+ if !ppFlowSet[fid] {
+ warns = append(warns, fmt.Sprintf("工艺组合包含产品工艺之外的工艺「%s」(%d 个工位)", flowName[fid], len(sts)))
+ }
+ }
+ return warns
+}
+
+// productProcessNamesByFlow 反查:工艺ID → 引用它的产品工艺名称列表(工位绑定/工艺列表只读展示用)
+func (s *Service) productProcessNamesByFlow(ctx context.Context) map[int][]string {
+ items, _ := s.ctx.EntClient.ProductProcessItem.Query().All(ctx)
+ out := map[int][]string{}
+ if len(items) == 0 {
+ return out
+ }
+ pps, _ := s.ctx.EntClient.ProductProcess.Query().All(ctx)
+ name := map[int]string{}
+ for _, p := range pps {
+ name[p.ID] = p.Name
+ }
+ for _, it := range items {
+ if n := name[it.ProductProcessId]; n != "" {
+ out[it.FlowId] = append(out[it.FlowId], n)
+ }
+ }
+ return out
+}
+
+// ppContainsFold 大小写无关包含(工艺列表按产品工艺名筛选用)
+func ppContainsFold(list []string, kw string) bool {
+ for _, v := range list {
+ if strings.Contains(strings.ToLower(v), strings.ToLower(kw)) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/bj_power_mes/internal/logic/seed.go b/bj_power_mes/internal/logic/seed.go
index b12415b..6cae193 100644
--- a/bj_power_mes/internal/logic/seed.go
+++ b/bj_power_mes/internal/logic/seed.go
@@ -27,12 +27,15 @@ func (s *Service) Seed(ctx context.Context) error {
"produce.workorder", "produce.dailyplan", "produce.material", "produce.producible",
"produce.trace", "produce.wip", "produce.plc", "produce.product",
"produce.processflow", "produce.station", "produce.performance", "produce.processcard",
+ // 产品工艺(产品级工艺定义,2026-10-09)+ 待审核签字
+ "produce.productprocess", "produce.audit",
// 按钮级权限(块2)
"produce.workorder:add", "produce.workorder:edit", "produce.workorder:delete",
"produce.workorder:dailyplan", "produce.material:generate", "produce.material:outbound",
"produce.plc:send", "produce.product:add", "produce.product:edit", "produce.product:delete",
"produce.processflow:add", "produce.processflow:edit", "produce.processflow:delete",
"produce.processflow:upload", "produce.station:edit", "produce.station:add", "produce.station:delete",
+ "produce.productprocess:add", "produce.productprocess:edit", "produce.productprocess:delete",
// 预警中心 / 附件中心(含归档清理按钮)
"sys.alert", "sys.attachment", "sys.attachment:manage",
// 数量不符处理(上报在工位终端,处理在本页)
@@ -85,6 +88,7 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.qty", "数量不符处理", "MENU", "/qty-report"},
{"produce.plc", "工位组合下发", "MENU", "/plc-send"},
{"produce.processflow", "工艺流程", "MENU", "/process-flow"},
+ {"produce.productprocess", "产品工艺", "MENU", "/product-process"},
{"produce.station", "关联工位", "MENU", "/station"}, {"produce.performance", "绩效报表", "MENU", "/performance"},
{"produce.dock", "接驳台维护", "MENU", "/dock"},
{"produce.trace", "工件追溯", "MENU", "/trace"},
@@ -93,6 +97,7 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.virtualstation", "虚拟工位作业", "MENU", "/virtual-station"},
{"produce.wip", "在制品", "MENU", "/wip"},
{"produce.processcard", "生产流程卡", "MENU", "/process-card"},
+ {"produce.audit", "待审核签字", "MENU", "/audit-pending"},
{"produce.product", "物料档案", "MENU", "/product-type"},
{"produce.quality", "质量检验", "MENU", "/quality"},
{"sys.inspect", "巡检终端", "MENU", "/inspect"},
@@ -139,6 +144,9 @@ func (s *Service) Seed(ctx context.Context) error {
{"produce.processflow:edit", "工艺流程-编辑", "BUTTON", "", "produce.processflow"},
{"produce.processflow:delete", "工艺流程-删除", "BUTTON", "", "produce.processflow"},
{"produce.processflow:upload", "工艺流程-上传图纸", "BUTTON", "", "produce.processflow"},
+ {"produce.productprocess:add", "产品工艺-新增", "BUTTON", "", "produce.productprocess"},
+ {"produce.productprocess:edit", "产品工艺-编辑", "BUTTON", "", "produce.productprocess"},
+ {"produce.productprocess:delete", "产品工艺-删除", "BUTTON", "", "produce.productprocess"},
{"produce.station:edit", "工位-绑定与改名", "BUTTON", "", "produce.station"},
{"produce.station:add", "工位-新增", "BUTTON", "", "produce.station"},
{"produce.station:delete", "工位-删除", "BUTTON", "", "produce.station"},
diff --git a/bj_power_mes/internal/logic/sign.go b/bj_power_mes/internal/logic/sign.go
index d884f2d..8c85503 100644
--- a/bj_power_mes/internal/logic/sign.go
+++ b/bj_power_mes/internal/logic/sign.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"strings"
+ "time"
"bj_power_mes/ent"
"bj_power_mes/ent/stepsignrecord"
@@ -105,6 +106,102 @@ func (s *Service) InspectorSign(ctx context.Context, req InspectorSignReq, opera
return nil
}
+// AuditorSignReq 审核人复核签字请求(工序级审核 gate,工艺配置 needAudit 决定)。
+type AuditorSignReq struct {
+ Sn string `json:"sn"`
+ OrderNo string `json:"orderNo"`
+ StationNo string `json:"stationNo"`
+ StepId int `json:"stepId"`
+ Result string `json:"result"` // OK / NG(NG=审核不通过,退回操作工重做)
+ Remark string `json:"remark"`
+}
+
+// AuditorSign 落审核人复核签字(signRole=AUDITOR);前置:步骤须 needAudit=true,且前置签字
+// (若 needInspectorSign 则检验员须 OK,否则操作工已签)已存在。
+// result=NG 表示审核不通过,撤销该步骤已有的操作工/检验员签字,退回操作工重做(新一轮轮次)。
+func (s *Service) AuditorSign(ctx context.Context, req AuditorSignReq, operator string) error {
+ req.Sn = strings.TrimSpace(req.Sn)
+ req.StationNo = strings.TrimSpace(req.StationNo)
+ req.OrderNo = strings.TrimSpace(req.OrderNo)
+ if req.Sn == "" || req.StationNo == "" || req.StepId <= 0 {
+ return errors.New("审核参数不完整:缺少 SN / 工位号 / 步骤")
+ }
+ if operator == "" {
+ return errors.New("未获取到审核人身份,请重新登录")
+ }
+ client := s.ctx.EntClient
+ ps, err := client.ProcessStep.Get(ctx, req.StepId)
+ if err != nil {
+ return errors.New("工艺步骤不存在:" + itoa(req.StepId))
+ }
+ if !ps.NeedAudit {
+ return errors.New("该步骤未配置「需审核人复核」,无需审核")
+ }
+ result := strings.ToUpper(strings.TrimSpace(req.Result))
+ if result != "OK" && result != "NG" {
+ result = "OK"
+ }
+ // 前置签字校验(审核在签字链末端)
+ if ps.NeedInspectorSign {
+ inspOK, e := client.StepSignRecord.Query().
+ Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
+ stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("INSPECTOR"),
+ stepsignrecord.Revoked(false), stepsignrecord.Result("OK"), stepsignrecord.SignedByNEQ("")).Exist(ctx)
+ if e != nil {
+ return e
+ }
+ if !inspOK {
+ return errors.New("检验员尚未 OK 签字,审核人不能先于检验员复核")
+ }
+ } else {
+ opSigned, e := client.StepSignRecord.Query().
+ Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
+ stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("OPERATOR"),
+ stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ("")).Exist(ctx)
+ if e != nil {
+ return e
+ }
+ if !opSigned {
+ return errors.New("操作工尚未签字,审核人不能复核")
+ }
+ }
+ // 计算轮次(每轮审核递增)
+ recs, e := client.StepSignRecord.Query().
+ Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
+ stepsignrecord.StepId(req.StepId), stepsignrecord.SignRole("AUDITOR")).All(ctx)
+ if e != nil {
+ return e
+ }
+ round := 1
+ for _, r := range recs {
+ if r.Round >= round {
+ round = r.Round + 1
+ }
+ }
+ if result == "NG" {
+ // 退回操作工重做:撤销该步骤已有的操作工/检验员签字
+ _, _ = client.StepSignRecord.Update().
+ Where(stepsignrecord.Sn(req.Sn), stepsignrecord.StationNo(req.StationNo),
+ stepsignrecord.StepId(req.StepId),
+ stepsignrecord.SignRoleIn("OPERATOR", "INSPECTOR"), stepsignrecord.Revoked(false)).
+ SetRevoked(true).SetRevokedBy(operator).
+ SetRevokedAt(time.Now()).SetRevokeReason("审核不通过,退回重做").Save(ctx)
+ }
+ _, err = client.StepSignRecord.Create().
+ SetSn(req.Sn).SetOrderNo(req.OrderNo).SetFlowId(ps.FlowId).
+ SetStationNo(req.StationNo).SetStepId(req.StepId).SetStepName(ps.Name).
+ SetSignRole("AUDITOR").SetResult(result).
+ SetSignedBy(operator).SetRound(round).
+ SetSource("audit").SetRemark(req.Remark).Save(ctx)
+ if err != nil {
+ if isUniqueSignViolation(err) {
+ return errors.New("该步骤已审核,请勿重复提交")
+ }
+ return err
+ }
+ return nil
+}
+
// isUniqueSignViolation 判定是否为签字唯一索引冲突(并发签字竞态)
func isUniqueSignViolation(err error) bool {
if err == nil {
@@ -204,3 +301,95 @@ func (s *Service) PendingSigns(ctx context.Context, f PendingSignFilter) ([]Step
}
return list[start:end], total, nil
}
+
+// PendingAuditFilter 待审核查询过滤(审核人「待审任务」数据源)。
+type PendingAuditFilter struct {
+ Sn string `json:"sn"`
+ OrderNo string `json:"orderNo"`
+ StationNo string `json:"stationNo"`
+ Page int `json:"page"`
+ PageSize int `json:"pageSize"`
+}
+
+// PendingAudits 聚合「前置签字已满足、待审核人复核」的工艺步骤。
+// 基数=操作工已签字(未撤销)的步骤;排除:已有审核 OK 的步骤;以及检验未通过(存在检验员签字记录但未 OK)的步骤。
+func (s *Service) PendingAudits(ctx context.Context, f PendingAuditFilter) ([]StepSignVO, int, error) {
+ client := s.ctx.EntClient
+ q := client.StepSignRecord.Query().
+ Where(stepsignrecord.SignRole("OPERATOR"), stepsignrecord.Revoked(false), stepsignrecord.SignedByNEQ(""))
+ if f.Sn != "" {
+ q = q.Where(stepsignrecord.Sn(f.Sn))
+ }
+ if f.OrderNo != "" {
+ q = q.Where(stepsignrecord.OrderNo(f.OrderNo))
+ }
+ if f.StationNo != "" {
+ q = q.Where(stepsignrecord.StationNo(f.StationNo))
+ }
+ ops, err := q.Order(ent.Desc(stepsignrecord.FieldID)).All(ctx)
+ if err != nil {
+ return nil, 0, err
+ }
+ type signKey struct {
+ sn, stationNo string
+ stepId int
+ }
+ inspectorAny := map[signKey]bool{}
+ inspectorOK := map[signKey]bool{}
+ auditOK := map[signKey]bool{}
+ insp, e := client.StepSignRecord.Query().
+ Where(stepsignrecord.SignRoleIn("INSPECTOR", "AUDITOR"), stepsignrecord.Revoked(false),
+ stepsignrecord.SignedByNEQ("")).All(ctx)
+ if e != nil {
+ return nil, 0, e
+ }
+ for _, r := range insp {
+ k := signKey{r.Sn, r.StationNo, r.StepId}
+ if r.SignRole == "INSPECTOR" {
+ inspectorAny[k] = true
+ if r.Result == "OK" {
+ inspectorOK[k] = true
+ }
+ }
+ if r.SignRole == "AUDITOR" && r.Result == "OK" {
+ auditOK[k] = true
+ }
+ }
+ list := make([]StepSignVO, 0, len(ops))
+ for _, r := range ops {
+ k := signKey{r.Sn, r.StationNo, r.StepId}
+ if auditOK[k] {
+ continue
+ }
+ if inspectorAny[k] && !inspectorOK[k] {
+ // 检验环节未通过,未到审核阶段
+ continue
+ }
+ signedAt := r.SignedAt.Format("2006-01-02 15:04:05")
+ list = append(list, StepSignVO{
+ ID: r.ID, Sn: r.Sn, OrderNo: r.OrderNo, FlowId: r.FlowId,
+ StationNo: r.StationNo, StepId: r.StepId, StepName: r.StepName,
+ SignRole: r.SignRole, Result: r.Result, SignedBy: r.SignedBy,
+ SignedAt: signedAt, Round: r.Round, Source: r.Source,
+ OperatorSigner: r.SignedBy, OperatorSignedAt: signedAt,
+ })
+ }
+ total := len(list)
+ ps := f.PageSize
+ if ps <= 0 {
+ ps = 50
+ }
+ pg := f.Page
+ if pg <= 0 {
+ pg = 1
+ }
+ start := (pg - 1) * ps
+ if start >= total {
+ return []StepSignVO{}, total, nil
+ }
+ end := start + ps
+ if end > total {
+ end = total
+ }
+ return list[start:end], total, nil
+}
diff --git a/bj_power_mes/internal/logic/workorder.go b/bj_power_mes/internal/logic/workorder.go
index d1ed252..b5cfda6 100644
--- a/bj_power_mes/internal/logic/workorder.go
+++ b/bj_power_mes/internal/logic/workorder.go
@@ -34,6 +34,9 @@ type WorkOrderReq struct {
DueDate string `json:"dueDate"`
// 工艺组合(唯一路线源头):[{flowId,stationNo}],工位号即顺序号,按工位号升序执行、可跳过未选工位
FlowCombination []map[string]int `json:"flowCombination"`
+ // 来源产品工艺(2026-10-09):建单选产品时带出默认产品工艺并自动填组合;
+ // 组合是快照可手改,本字段恒保留=来源定义(0=无来源,历史工单),供追溯与偏差提示。
+ ProductProcessId int `json:"productProcessId"`
}
// CreateWorkOrder 创建工单(状态恒 CREATED,后续用状态流转按钮推进)
@@ -102,6 +105,13 @@ func (s *Service) CreateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
b.SetFlowCombination(flowItemsToMaps(items))
}
+ // 来源产品工艺:传了必须存在( ACTIVE/停用均可落——前端只列启用的,此处宽松校验存在性)
+ if req.ProductProcessId > 0 {
+ if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.ProductProcessId); err != nil {
+ return errors.New("所选产品工艺不存在")
+ }
+ b.SetProductProcessId(req.ProductProcessId)
+ }
// 创建人(Item M):取当前登录用户
b.SetCreatedBy(operator)
if _, err := b.Save(ctx); err != nil {
@@ -227,6 +237,13 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
u.SetFlowCombination(flowItemsToMaps(items))
}
+ // 来源产品工艺:传了必须存在(恒保留=来源定义,不随组合手改清空)
+ if req.ProductProcessId > 0 {
+ if _, err := s.ctx.EntClient.ProductProcess.Get(ctx, req.ProductProcessId); err != nil {
+ return errors.New("所选产品工艺不存在")
+ }
+ u.SetProductProcessId(req.ProductProcessId)
+ }
if req.Quantity > 0 {
u.SetQuantity(req.Quantity)
}
@@ -263,8 +280,10 @@ func (s *Service) UpdateWorkOrder(ctx context.Context, req WorkOrderReq, operato
}
// ListWorkOrders 查询工单(支持工单号/状态/产品编码/产品名称/归属类型/归属编号 过滤;
-// 工程编号查询已随编号体系改造移除,字段保留仅防历史迁移)
-func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, dueFrom, dueTo string) ([]*ent.WorkOrder, error) {
+// 工程编号查询已随编号体系改造移除,字段保留仅防历史迁移)。
+// keyword:跨字段模糊(工单号/产品编码/产品名称/合同号 任一命中),供下拉远程搜索用;
+// limit:>0 时启用截断(封顶 200),仅下拉搜索场景传参,列表页不传=全量,行为向后兼容。
+func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCode, productName, contractNo, ownershipType, dueFrom, dueTo, keyword string, limit int) ([]*ent.WorkOrder, error) {
q := s.ctx.EntClient.WorkOrder.Query()
if orderNo != "" {
q = q.Where(workorder.WorkOrderNoContains(orderNo))
@@ -295,6 +314,23 @@ func (s *Service) ListWorkOrders(ctx context.Context, orderNo, status, productCo
q = q.Where(workorder.DueDateLTE(t))
}
}
+ // keyword 跨字段模糊(下拉远程搜索):工单号/产品编码/产品名称/合同号 任一命中
+ if keyword != "" {
+ kw := workorder.Or(
+ workorder.WorkOrderNoContains(keyword),
+ workorder.ProductCodeContains(keyword),
+ workorder.ProductNameContains(keyword),
+ workorder.ContractNoContains(keyword),
+ )
+ q = q.Where(kw)
+ }
+ // limit 截断(封顶 200):仅下拉搜索场景启用,防数据炸弹
+ if limit > 0 {
+ if limit > 200 {
+ limit = 200
+ }
+ q = q.Limit(limit)
+ }
return q.Order(ent.Desc(workorder.FieldCreatedAt), ent.Desc(workorder.FieldID)).All(ctx)
}
diff --git a/bj_power_mes/internal/logic/workpiece.go b/bj_power_mes/internal/logic/workpiece.go
index 3a039d2..45c6c49 100644
--- a/bj_power_mes/internal/logic/workpiece.go
+++ b/bj_power_mes/internal/logic/workpiece.go
@@ -322,16 +322,20 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
return errors.New(miss)
}
// 阶段2:检测确认(needCheck)强校验——服务端为准,前端勾选只是辅助提示。
- // 本工位绑定工艺流程中标记“需要检测确认”的步骤,报工数据里必须逐条带 checked=true,否则拒绝报工。
- if err := s.validateNeedCheck(ctx, client, req); err != nil {
+ // 本工位在本工艺组合中的出现序号 k 对应步骤 seq=k,标记“需要检测确认”的步骤须带 checked=true。
+ // k 由组合派生(第 k 次出现 ↔ 步骤 seq=k),与签字校验同源,避免跨工位误拦。
+ k := stationSeqInFlow(items, flowId, req.StationNo)
+ if err := s.validateNeedCheck(ctx, client, req, flowId, k); err != nil {
return err
}
// 阶段2.5:签字机制(需求B)强校验 + 落操作工签字(needOperatorSign 步骤)。
// needInspectorSign 步骤要求检验员已在巡检终端「待签任务」页签签字,否则拒流转。
- if err := s.validateNeedSign(ctx, client, req, flowId); err != nil {
+ // 校验同时返回 k(同 stationSeqInFlow),供落签字时同范围使用。
+ k, err = s.validateNeedSign(ctx, client, req, flowId, k)
+ if err != nil {
return err
}
- if err := s.writeOperatorSigns(ctx, client, req, flowId, wp.OrderNo, operator); err != nil {
+ if err := s.writeOperatorSigns(ctx, client, req, flowId, k, wp.OrderNo, operator); err != nil {
return err
}
now := time.Now()
@@ -398,19 +402,16 @@ func (s *Service) ReportProcess(ctx context.Context, req ReportProcessReq, opera
}
// validateNeedCheck 检测确认(needCheck)服务端强校验。
-// 规则:本工位绑定的工艺流程中,凡标记 needCheck=true 的工艺步骤,
+// 规则:本工位在本工艺组合中的出现序号 k 对应的步骤(seq=k),凡标记 needCheck=true,
// 报工请求里必须存在对应 stepId 且 checked=true 的步骤数据;缺失则拒绝报工。
-// 工位未绑定流程、或流程内没有 needCheck 步骤时不拦截(与现场配置保持一致)。
-func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req ReportProcessReq) error {
- if req.StationNo <= 0 {
- return nil
- }
- st, err := client.Station.Query().Where(station.StationNo(req.StationNo)).First(ctx)
- if err != nil || st.FlowId <= 0 {
+// 与 validateNeedSign 同源:跨工位的检测确认步骤不应在本工位报工时被要求(2026-10-08 审核修正)。
+// 工位不在组合中、或本步骤非 needCheck 时不拦截(与现场配置保持一致)。
+func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId, k int) error {
+ if req.StationNo <= 0 || flowId <= 0 || k <= 0 {
return nil
}
steps, err := client.ProcessStep.Query().
- Where(processstep.FlowId(st.FlowId), processstep.NeedCheck(true)).All(ctx)
+ Where(processstep.FlowId(flowId), processstep.NeedCheck(true), processstep.Seq(k)).All(ctx)
if err != nil || len(steps) == 0 {
return nil
}
@@ -436,19 +437,39 @@ func (s *Service) validateNeedCheck(ctx context.Context, client *ent.Client, req
return nil
}
-// validateNeedSign 签字机制(需求B)服务端强校验,镜像 validateNeedCheck:
-// 本工位绑定工艺流程中,凡标记 needOperatorSign=true 的工艺步骤,报工请求必须携带对应签字
-// (Signs 中存在 stepId 匹配且 signer 非空);凡标记 needInspectorSign=true 的步骤,必须已存在
-// 检验员签字记录(step_sign_record, signRole=INSPECTOR, 未撤销, signedBy 非空)方可流转。
-// 工位未绑定流程、或流程内无签字步骤时不拦截(与现场配置保持一致)。
-func (s *Service) validateNeedSign(ctx context.Context, client *ent.Client, req ReportProcessReq, flowId int) error {
- if req.StationNo <= 0 || flowId <= 0 {
- return nil
+// stationSeqInFlow 返回工位在指定工艺组合中的出现序号 k(按工位号升序的第 k 次出现,从 1 起)。
+// 语义:组合条目 ↔ 工艺步骤 seq 一一对应(第 k 次出现 ↔ 步骤 seq=k)。不在组合中返回 0。
+func stationSeqInFlow(items []FlowItem, flowId, stationNo int) int {
+ k, cur := 0, 0
+ for _, it := range items {
+ if it.FlowId != flowId {
+ continue
+ }
+ cur++
+ if it.StationNo == stationNo {
+ k = cur
+ break
+ }
+ }
+ return k
+}
+
+// validateNeedSign 签字机制(需求B)服务端强校验,返回本工位在本工艺组合中的出现序号 k:
+// 组合条目(按工位号升序)与工艺步骤 seq 一一对应——本工艺在组合中第 k 次出现 ↔ 步骤 seq=k。
+// - needOperatorSign:仅校验「本次报工步骤」(seq=k),报工请求必须携带对应操作工签字;
+// 随报工事务落 step_sign_record(signRole=OPERATOR)(writeOperatorSigns,同样限 seq=k)。
+// - needInspectorSign:仅校验「历史步骤」(seq0 时截断封顶 200,默认 500)
+func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string, limit int) ([]*ent.Workpiece, error) {
q := s.ctx.EntClient.Workpiece.Query()
if sn != "" {
q = q.Where(workpiece.SnContains(sn))
@@ -798,7 +823,15 @@ func (s *Service) ListWorkpieces(ctx context.Context, sn, orderNo string) ([]*en
if orderNo != "" {
q = q.Where(workpiece.OrderNo(orderNo))
}
- return q.Order(ent.Desc(workpiece.FieldID)).Limit(500).All(ctx)
+ if limit > 0 {
+ if limit > 200 {
+ limit = 200
+ }
+ q = q.Limit(limit)
+ } else {
+ q = q.Limit(500)
+ }
+ return q.Order(ent.Desc(workpiece.FieldID)).All(ctx)
}
// InProcessItem 在制品(已进线未完工)视图项。跨天工件继续停留,日排产不重复排。
diff --git a/bj_power_mes/internal/wmsclient/client.go b/bj_power_mes/internal/wmsclient/client.go
index dcb8915..056cd0e 100644
--- a/bj_power_mes/internal/wmsclient/client.go
+++ b/bj_power_mes/internal/wmsclient/client.go
@@ -487,6 +487,47 @@ func (c *Client) MaterialTypes(ctx context.Context, codes []string) (map[string]
return body.Data.Types, nil
}
+// MaterialManageModes 批量查询物料在 WMS 的「类型」(manage_mode: 1结构件/2电气件/3其他)。
+// 与 MaterialTypes(品类 item_type)相互独立:品类=成品/组件类,类型=结构件/电气件/其他。
+// WMS 不可达返回 err,由调用方降级(不阻塞产线)。
+func (c *Client) MaterialManageModes(ctx context.Context, codes []string) (map[string]int, error) {
+ b, err := json.Marshal(map[string]any{"codes": codes})
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL()+"/api/internal/material/manage-modes", bytes.NewReader(b))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-API-TOKEN", c.token)
+ resp, err := c.hc.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ var body struct {
+ Code int `json:"code"`
+ Data struct {
+ ManageModes map[string]int `json:"manageModes"`
+ } `json:"data"`
+ Msg string `json:"message"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
+ return nil, err
+ }
+ if body.Code != 0 {
+ if body.Msg != "" {
+ return nil, errors.New(body.Msg)
+ }
+ return nil, errors.New("WMS 查询物料类型失败")
+ }
+ if body.Data.ManageModes == nil {
+ return map[string]int{}, nil
+ }
+ return body.Data.ManageModes, nil
+}
+
// BackflushItem 反冲单条物料(已含损耗的单件消耗 * 完成件数)
type BackflushItem struct {
MaterialCode string `json:"materialCode"`
diff --git a/bj_power_mes/public/index.html b/bj_power_mes/public/index.html
index cbae33f..df9ec23 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/process_step.go b/bj_power_mes/schema/process_step.go
index 2891ae9..8605e2f 100644
--- a/bj_power_mes/schema/process_step.go
+++ b/bj_power_mes/schema/process_step.go
@@ -31,6 +31,8 @@ func (ProcessStep) Fields() []ent.Field {
field.Bool("needCheck").Default(false).Comment("是否需要检测确认(报工前须检验通过)"),
field.Bool("needOperatorSign").Default(false).Comment("是否需要操作工签字(报工前须签字确认)"),
field.Bool("needInspectorSign").Default(false).Comment("是否需要检验员签字(审核通过并签字后放行)"),
+ field.Bool("needAudit").Default(false).Comment("是否需要审核人复核签字(审核通过后放行)"),
+ field.String("auditRole").Default("").MaxLen(64).Optional().Comment("审核角色(如班组长/工艺员),具该角色的人员可签"),
// 本步骤图纸/附件(按工序分发到工位终端),多份,存 {name,url} 列表
field.JSON("attachment", []map[string]string{}).Optional().SchemaType(map[string]string{
dialect.Postgres: "jsonb",
diff --git a/bj_power_mes/schema/product_process.go b/bj_power_mes/schema/product_process.go
new file mode 100644
index 0000000..2eb3da9
--- /dev/null
+++ b/bj_power_mes/schema/product_process.go
@@ -0,0 +1,46 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+ "entgo.io/ent/schema/index"
+)
+
+// ProductProcess 产品工艺:产品级的工艺定义("这个产品该按什么顺序经过哪些工艺")。
+// 只选工艺+顺序(seq 严格递增=串行),不绑工位——工位在建工单时按「工位绑定」(station.flow_id)
+// 自动推导(同工艺的全部启用工位),并复制为工单工艺组合 flow_combination 快照。
+// 约束:① 同一工艺在同一产品工艺内不重复(明细表唯一索引);② 每产品至多一条默认(is_default);
+// ③ 被工单引用过(work_order.product_process_id)后只读,只能停用+新建,历史工单可反查当时定义。
+type ProductProcess struct {
+ ent.Schema
+}
+
+func (ProductProcess) Annotations() []schema.Annotation {
+ return []schema.Annotation{entsql.Annotation{Table: "product_process"}, entsql.WithComments(true), schema.Comment("ProductProcess 产品工艺:产品级工艺定义(有序工艺集合,不绑工位;建工单时推导工位并复制为工艺组合快照)")}
+}
+
+func (ProductProcess) Fields() []ent.Field {
+ return []ent.Field{
+ field.Int("id").Positive(),
+ field.String("productCode").MaxLen(64).Comment("产品编码(WMS 物料档案 item_type=3 图号)"),
+ field.String("productName").Default("").MaxLen(128).Comment("产品名称(快照,WMS 改名不回写)"),
+ field.String("name").MaxLen(128).Comment("产品工艺名称,如 DX100常规"),
+ // 每产品至多一条默认:建工单选完产品自动带出默认产品工艺(设新自动取消旧默认)
+ field.Bool("isDefault").Default(false).Comment("是否该产品的默认产品工艺(每产品至多一条)"),
+ // ACTIVE / INACTIVE(停用不删:历史工单按 product_process_id 反查当时定义)
+ field.String("status").Default("ACTIVE").MaxLen(20),
+ field.String("remark").Default("").MaxLen(255),
+ field.Time("createdAt").Default(time.Now).Immutable(),
+ }
+}
+
+func (ProductProcess) Indexes() []ent.Index {
+ return []ent.Index{
+ index.Fields("productCode"),
+ index.Fields("productCode", "isDefault"),
+ }
+}
diff --git a/bj_power_mes/schema/product_process_item.go b/bj_power_mes/schema/product_process_item.go
new file mode 100644
index 0000000..8fc4e02
--- /dev/null
+++ b/bj_power_mes/schema/product_process_item.go
@@ -0,0 +1,40 @@
+package schema
+
+import (
+ "time"
+
+ "entgo.io/ent"
+ "entgo.io/ent/dialect/entsql"
+ "entgo.io/ent/schema"
+ "entgo.io/ent/schema/field"
+ "entgo.io/ent/schema/index"
+)
+
+// ProductProcessItem 产品工艺明细:有序工艺执行点(seq 从 1 严格递增=串行执行顺序)。
+// 同一工艺在同一产品工艺内不重复(唯一索引兜底);不存工位——工位在建工单时
+// 按 station.flow_id 自动推导(同工艺的全部启用工位),产品工艺只定义"经过哪些工艺、什么顺序"。
+type ProductProcessItem struct {
+ ent.Schema
+}
+
+func (ProductProcessItem) Annotations() []schema.Annotation {
+ return []schema.Annotation{entsql.Annotation{Table: "product_process_item"}, entsql.WithComments(true), schema.Comment("ProductProcessItem 产品工艺明细:有序工艺执行点(seq 严格递增=串行;工位建单时推导,不落本表)")}
+}
+
+func (ProductProcessItem) Fields() []ent.Field {
+ return []ent.Field{
+ field.Int("id").Positive(),
+ field.Int("productProcessId").Comment("所属产品工艺ID"),
+ field.Int("seq").Comment("顺序号(从1严格递增,即执行顺序)"),
+ field.Int("flowId").Comment("工艺ID(process_flow)"),
+ field.Time("createdAt").Default(time.Now).Immutable(),
+ }
+}
+
+func (ProductProcessItem) Indexes() []ent.Index {
+ return []ent.Index{
+ index.Fields("productProcessId"),
+ // 同一产品工艺内同一工艺不重复(客户裁决:不能出现两次)
+ index.Fields("productProcessId", "flowId").Unique(),
+ }
+}
diff --git a/bj_power_mes/schema/work_order.go b/bj_power_mes/schema/work_order.go
index df487d2..1c2c241 100644
--- a/bj_power_mes/schema/work_order.go
+++ b/bj_power_mes/schema/work_order.go
@@ -46,6 +46,9 @@ func (WorkOrder) Fields() []ent.Field {
field.JSON("flowCombination", []map[string]int{}).Optional().SchemaType(map[string]string{
dialect.Postgres: "jsonb",
}).Comment("工艺组合 [{flowId,stationNo}] 按工位号升序"),
+ // 产品工艺来源(2026-10-09):建单选产品时带出默认产品工艺并自动填组合;组合是快照、可手改,
+ // 本字段恒保留=来源定义(0=无来源,历史工单),供追溯与偏差提示,不随组合编辑清空。
+ field.Int("productProcessId").Default(0).Comment("来源产品工艺ID(0=无来源)"),
// CREATED / RELEASED / IN_PROGRESS / COMPLETED / CLOSED
field.String("status").Default("CREATED").MaxLen(20),
field.Time("planStart").Optional().Nillable().Comment("计划开始"),
diff --git a/bj_power_wms/etc/aitest_wms.yaml b/bj_power_wms/etc/aitest_wms.yaml
new file mode 100644
index 0000000..d5a5181
--- /dev/null
+++ b/bj_power_wms/etc/aitest_wms.yaml
@@ -0,0 +1,69 @@
+Name: bj_power_wms
+Host: 0.0.0.0
+Port: 8890
+Timeout: 10000
+# 请求体上限:go-zero 默认仅 1MB,会拦住照片/PDF/Excel 上传;取各文件类型上限的最大值(50MB)
+MaxBytes: 52428800
+
+# PostgreSQL
+Postgres:
+ Host: 127.0.0.1
+ Port: 5432
+ User: postgres
+ Password: postgres
+ DBName: bj_power_wms
+ SSLMode: disable
+
+# JWT(短有效期 + 滑动续签)
+Auth:
+ AccessSecret: Hardman_2026
+ AccessExpire: 3600
+
+# 项目间内部 API 写死 token
+Internal:
+ Token: Hardman_2026
+
+# MES 服务对接(备料单拉取/状态回写,AGV 配送用)
+Mes:
+ BaseURL: http://127.0.0.1:8888
+ Token: Hardman_2026
+
+Log:
+ Mode: file
+ Path: logs
+ Level: info
+
+Redis:
+ Host: 127.0.0.1:6379
+ Type: node
+
+# 海康 AGV(RCS-2000) 对接:未接真实 RCS 前保持 mock(模拟下发成功/到位)
+# 现场对接时填 EnableMock: false + RCS 服务地址 + appKey/appSecret
+Agv:
+ EnableMock: true
+ BaseURL: ""
+ AppKey: ""
+ AppSecret: ""
+
+# 前端页面托管(原库房客户端 8891 已合并进主服务)
+Web:
+ OpenBrowser: false
+
+# 命令行敏感操作门禁密码(migrate/reset-all/seed 需输入,独立于后台登录账号密码)
+Cli:
+ AdminPassword: "Hardman_2026"
+
+# 附件存储(年/月/日/文件类型/uuid.ext,库内只存相对路径,不存绝对路径)
+# 生产环境改 RootDir: /data/bj_power/attachments
+Attachment:
+ RootDir: "D:/hardman/bj_power/attachments"
+ DefaultMaxSize: 20971520 # 默认单文件 20MB
+ MaxSize:
+ PROCESS_PDF: 52428800 # 工艺流程作业指导书 50MB
+ INSPECTION_PHOTO: 20971520 # 检验照片 20MB
+ EXCEL_IMPORT: 10485760 # Excel 导入 10MB
+ LocalRetentionYears: 1 # 本地保留最近 1 年
+ DiskWarnPercent: 20 # 剩余空间 <20% 告警
+ DiskCriticalPercent: 10 # 剩余空间 <10% 提示清理/归档
+ DiskCheckHour: 7 # 每天 07:00 检测
+ ArchiveDir: "" # 外部备份目录(NAS/移动硬盘),留空则归档仅标记
diff --git a/bj_power_wms/frontend/src/pages/Agv.vue b/bj_power_wms/frontend/src/pages/Agv.vue
index 64c41ed..f1713b3 100644
--- a/bj_power_wms/frontend/src/pages/Agv.vue
+++ b/bj_power_wms/frontend/src/pages/Agv.vue
@@ -241,7 +241,7 @@ onMounted(() => { loadDocks(); loadTasks(); loadMode() })
-
+
@@ -251,7 +251,7 @@ onMounted(() => { loadDocks(); loadTasks(); loadMode() })
勾选待发料行 → 行内可改目标接驳台 → 下发