Files
bj_power/bj_power_mes/internal/handler/processcard_pdf.go
T
SunYF f930a1325f feat(mes/wms): 接驳台编码统一为GW点位码 + 签字模型改报检呼叫 + 台账续流修复 + 末级库位强校验(2026-12-01 终版整改)
【全系统 · 接驳台编码终版统一(12-01 用户拍板)】
- 新增 dockcode 包作为唯一真源:工位接驳台 = GW{工位号}{Z|Y}(Z=左/Y=右,工位1~10同一规则,废除左右互换),库房 = JBT21 不变
- 编码即海康 RCS 地图点位码:落库/界面/下发 RCS/读 PLC 传感器全用同一套;旧 DOCK01~20 全量废弃,系统内无第二套编号、无换算层
- dock 表去 side 字段;agv_task.target_dock、line_point、看板点位态与中文名、dockLabel 工具全部改 GW 规则
- 产线布局说明.md 同步终版(图纸名 GxZ/GxY 与 AGV 码 GWxZ/GWxY 一一对应;注明 RCS 图与主线流向图相差 180°,读图一律以 GW 码为准)

【MES · 签字模型二次重构(11-30 实测后定稿)】
- _OPERATOR 签字整体废除:工艺步骤删 needOperatorSign / needAudit / auditRole 字段,签字角色改 CALL(工人报检呼叫)+ INSPECTOR(检验员审核签)
- 呼叫时落步骤录入快照(stepValue/stepText/stepChecked/processId),供检验员查看与指纹比对;「待签任务」只认检验员签名步骤
- 「签字复核」(AuditPending 页面 + produce.audit 菜单 + 路由)整套删除

【MES · 台账续流根因修复(11-30 对账发现)】
- 流转目标「G6」与 line_point.point_no「6」对不上导致到位落账查不到、却先释放源位→工件从调度消失;新增 ledgerPointByTarget 归一
- settleDirect/settleInTransit 改为先占目标位、成功才释放源位;目标被占原样保留,工件进缓存位排队(实测 C2 排队不再丢件)

【WMS · 末级库位强校验与上架移库】
- 新增 LocationCascade 四级联动选择器(区/架/层/号,只从启用 level=4 节点派生);手工入库、半成品/成品入库、隔离库位一律四级必填且命中启用节点
- 新增上架/移库 relocate:只改四级库位与 updated_at,不动质量状态/数量/锁定量;不合格与锁定行同样允许移库;支持 ids 逐行指定或 scope 按物料+原库位整组搬
- MES 新增 WMS 自动回流库位配置(半成品/成品各一组末级库位,默认值 1区/1架/1层/1号,存 sys_config 可改)

【MES · 统一口径与工程整改】
- 新增 workpiece_location:工单详情工件列表/WIP/追溯三处共用位置判定(SCRAPPED→DONE→SEMI_STORED→在 StationNo→在途→待流转)
- 新增 workorder_close_warn:工单完工/取消时汇总各工位实物余料出一条预警,不阻断关单
- 分页下沉:新增 pagination 工具,同步失败台账(两端)改 Count+LIMIT/OFFSET 真分页,列表不再全量切片
- 全网对账/孤儿扫描(问题临时.md 第25/26节):10 类关系边断言实测,给出 8 条可重复巡检项

【文档】
- 产线布局说明.md 按 GW 编码终版重写;问题临时.md 新增 24.7 闭环实测、25 全网对账、26 补料→配送→报工人库闭环
2026-12-01 22:15:28 +08:00

399 lines
13 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package handler
import (
"bytes"
"context"
"fmt"
"net/http"
"strconv"
"strings"
"bj_power_mes/common/httpx"
"bj_power_mes/internal/svc"
"github.com/jung-kurt/gofpdf"
)
const (
pdfMargin = 12.0
pdfLineH = 5.0
pdfPageW = 210.0
pdfPageH = 297.0
pdfBottom = pdfPageH - pdfMargin
)
// WorkOrderCardPdfHandler GET /api/v1/process-card/pdf?no=WO-1&no=WO-2&sn=FIN-1
// 服务端生成真正的 PDF 文件(不再依赖浏览器「打印→另存为」),支持多张卡合并到一个 PDF。
func WorkOrderCardPdfHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
nos := q["no"]
sns := q["sn"]
if len(nos) == 0 && len(sns) == 0 {
httpx.BadRequest(w, "缺少 no 或 sn 参数")
return
}
pdf, err := buildCardsPdf(r.Context(), svcCtx, nos, sns)
if err != nil {
httpx.Fail(w, 2410, err.Error())
return
}
var buf bytes.Buffer
if err := pdf.Output(&buf); err != nil {
httpx.Fail(w, 2411, "PDF 生成失败:"+err.Error())
return
}
filename := "流程卡批量导出"
if len(nos) == 1 && len(sns) == 0 {
filename = "生产流程卡_" + nos[0]
} else if len(sns) == 1 && len(nos) == 0 {
filename = "成品追溯卡_" + sns[0]
}
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition",
`attachment; filename="process_card.pdf"; filename*=UTF-8''`+urlEncode(filename+".pdf"))
_, _ = w.Write(buf.Bytes())
}
}
func urlEncode(s string) string {
var b strings.Builder
for _, r := range s {
if (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == '~' {
b.WriteRune(r)
} else {
b.WriteString("%" + strings.ToUpper(strconv.FormatInt(int64(r), 16)))
}
}
return b.String()
}
// buildCardsPdf 生成包含若干工单主卡 / 成品 SN 追溯卡的 PDF 文档。
func buildCardsPdf(ctx context.Context, svcCtx *svc.ServiceContext, nos, sns []string) (*gofpdf.Fpdf, error) {
pdf := gofpdf.New("P", "mm", "A4", "")
fontBytes, err := simheiFontFS.ReadFile("fonts/simhei.ttf")
if err != nil {
return nil, fmt.Errorf("字体读取失败:%w", err)
}
pdf.AddUTF8FontFromBytes("simhei", "", fontBytes)
if pdf.Err() {
return nil, fmt.Errorf("中文字体加载失败")
}
pdf.SetFooterFunc(func() {
pdf.SetFont("simhei", "", 8)
pdf.SetTextColor(120, 120, 120)
pdf.SetY(pdfPageH - 8)
pdfCell(pdf, pdfPageW, 6, strconv.Itoa(pdf.PageNo()), "", "C", false, 0)
pdf.SetTextColor(0, 0, 0)
})
pdf.SetMargins(pdfMargin, pdfMargin, pdfMargin)
first := true
for _, no := range nos {
card, err := buildWorkOrderCard(ctx, svcCtx, no)
if err != nil {
return nil, err
}
if !first {
pdf.AddPage()
}
first = false
renderWorkOrderCardPdf(pdf, card)
}
for _, sn := range sns {
card, err := buildSnTraceCard(ctx, svcCtx, sn)
if err != nil {
return nil, err
}
if !first {
pdf.AddPage()
}
first = false
renderSnTraceCardPdf(pdf, card)
}
if first {
pdf.AddPage()
}
return pdf, nil
}
// pdfCell 封装 gofpdf.CellFormat(统一 link 参数)。
func pdfCell(pdf *gofpdf.Fpdf, w, h float64, txt, border, align string, fill bool, ln int) {
pdf.CellFormat(w, h, txt, border, ln, align, fill, 0, "")
}
// ---------- 通用绘制助手 ----------
func pdfSetFont(pdf *gofpdf.Fpdf, size float64) {
pdf.SetFont("simhei", "", size)
}
// wrap 按字符宽度折行(兼容中文逐字与西文按空格)。
func wrap(pdf *gofpdf.Fpdf, text string, maxW float64) []string {
if text == "" {
return []string{""}
}
lines := []string{}
cur := strings.Builder{}
curW := 0.0
for _, r := range text {
s := string(r)
w := pdf.GetStringWidth(s)
if curW+w > maxW && cur.Len() > 0 {
lines = append(lines, cur.String())
cur.Reset()
curW = 0
}
cur.WriteString(s)
curW += w
}
if cur.Len() > 0 {
lines = append(lines, cur.String())
}
if len(lines) == 0 {
lines = []string{""}
}
return lines
}
func pdfTitle(pdf *gofpdf.Fpdf, y float64, txt string) float64 {
pdfSetFont(pdf, 17)
pdf.SetXY(pdfMargin, y)
pdfCell(pdf, pdfPageW-2*pdfMargin, 10, txt, "", "C", false, 0)
return y + 12
}
func pdfHeading(pdf *gofpdf.Fpdf, y float64, txt string) float64 {
if y > pdfBottom-10 {
pdf.AddPage()
y = pdfMargin
}
pdfSetFont(pdf, 12)
pdf.SetXY(pdfMargin, y)
pdfCell(pdf, pdfPageW-2*pdfMargin, 8, txt, "", "L", false, 0)
pdf.Line(pdfMargin, y+8.5, pdfPageW-pdfMargin, y+8.5)
return y + 12
}
// metaKV 打印「标签:值」键值对,每行 perRow 组,自动换行。
func metaKV(pdf *gofpdf.Fpdf, y float64, pairs [][2]string, perRow int) float64 {
pdfSetFont(pdf, 10)
gap := (pdfPageW - 2*pdfMargin) / float64(perRow)
for i := 0; i < len(pairs); i += perRow {
if y > pdfBottom-pdfLineH {
pdf.AddPage()
y = pdfMargin
}
x := pdfMargin
for j := 0; j < perRow && i+j < len(pairs); j++ {
p := pairs[i+j]
pdf.SetXY(x, y)
pdfCell(pdf, gap-2, pdfLineH, p[0]+":"+p[1], "", "L", false, 0)
x += gap
}
y += pdfLineH
}
return y + 2
}
// drawTable 绘制表格(含表头),自动处理分页与多行单元格。
func drawTable(pdf *gofpdf.Fpdf, y float64, widths []float64, headers []string, rows [][]string) float64 {
y = drawRow(pdf, y, widths, headers, true, headers)
for _, row := range rows {
y = drawRow(pdf, y, widths, row, false, headers)
}
return y + 2
}
func drawRow(pdf *gofpdf.Fpdf, y float64, widths []float64, cells []string, isHeader bool, headers []string) float64 {
allLines := make([][]string, len(cells))
maxLines := 1
for i := range cells {
w := widths[i] - 2
if w < 3 {
w = 3
}
ls := wrap(pdf, cells[i], w)
allLines[i] = ls
if len(ls) > maxLines {
maxLines = len(ls)
}
}
rowH := float64(maxLines) * pdfLineH
if y+rowH > pdfBottom {
pdf.AddPage()
y = pdfMargin
y = drawRow(pdf, y, widths, headers, true, headers)
}
xi := pdfMargin
if isHeader {
pdf.SetFillColor(243, 244, 246)
} else {
pdf.SetFillColor(255, 255, 255)
}
for i := range cells {
pdf.SetXY(xi, y)
pdfCell(pdf, widths[i], rowH, "", "1", "L", isHeader, 0)
pdfSetFont(pdf, 9)
ty := y
lines := allLines[i]
if len(lines) == 0 {
lines = []string{""}
}
for _, line := range lines {
pdf.SetXY(xi+1, ty+0.5)
pdfCell(pdf, widths[i]-2, pdfLineH, line, "", "L", false, 0)
ty += pdfLineH
}
xi += widths[i]
}
pdf.SetFillColor(255, 255, 255)
return y + rowH
}
// pdfBlockFlags 四张子表的显示开关(2026-12-01 用户拍板):工艺没配置的块不绘制。
// 判断依据是「工艺里配没配」(工单级),不是「当前有没有数据」;单台追溯卡全开。
type pdfBlockFlags struct {
Torque bool
Sign bool
Material bool
}
var pdfAllBlocks = pdfBlockFlags{Torque: true, Sign: true, Material: true}
// drawProductTables 绘制一台成品的四张子表;工单主卡与单台追溯卡共用,保证导出结构一致。
func drawProductTables(pdf *gofpdf.Fpdf, y float64, p *woProduct, flags pdfBlockFlags) float64 {
// ① 工序实绩
y = pdfHeading(pdf, y, "1. 工序实绩")
stepRows := make([][]string, 0, len(p.Steps))
for _, s := range p.Steps {
stepRows = append(stepRows, []string{
strconv.Itoa(s.Seq), s.ProcessName, s.StationNo, s.StartAt, s.EndAt, s.Operator,
s.SelfCheck, s.Inspector, s.Conclusion, s.Remark, s.InspectedAt, s.Status,
})
}
y = drawTable(pdf, y, []float64{8, 26, 10, 20, 20, 18, 12, 14, 10, 20, 20, 8},
[]string{"序号", "工艺", "工位", "开始", "结束", "操作人", "工人自检", "检验员", "结论", "检验意见", "检验时间", "状态"}, stepRows)
// ② 用料清单(工艺没配物料分账 → 不绘制)
if flags.Material {
y = pdfHeading(pdf, y, "2. 用料清单")
matRows := make([][]string, 0, len(p.Materials))
for _, m := range p.Materials {
matRows = append(matRows, []string{
m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit,
m.SnOrBatch, strconv.Itoa(m.Qty), m.StationNo, m.Operator, m.BindAt,
})
}
y = drawTable(pdf, y, []float64{24, 26, 14, 22, 10, 30, 8, 14, 20, 18},
[]string{"图号", "名称", "类型", "规格", "单位", "物料SN或批次号", "数量", "装配工位", "装配人", "装配时间"}, matRows)
}
// ③ 拧紧数据(工艺没配拧紧步骤 → 不绘制)
if flags.Torque {
y = pdfHeading(pdf, y, "3. 拧紧数据")
torqueRows := make([][]string, 0, len(p.Torques))
for _, t := range p.Torques {
torqueRows = append(torqueRows, []string{t.ScrewNo, t.Torque, t.Angle, "设备判 " + t.Result, t.Operator, t.Time})
}
y = drawTable(pdf, y, []float64{22, 26, 22, 26, 24, 66},
[]string{"螺丝点", "扭矩", "角度", "设备判定", "操作人", "时间"}, torqueRows)
}
// ④ 签字明细(未撤销;工艺没配签字步骤 → 不绘制)
if flags.Sign {
y = pdfHeading(pdf, y, "4. 签字明细(未撤销)")
signRows := make([][]string, 0, len(p.Signs))
for _, s := range p.Signs {
signRows = append(signRows, []string{
s.ProcessName, s.StepName, s.SelfCheck, s.SelfCheckAt, s.Inspector,
s.Conclusion, s.Remark, s.SignedAt, strconv.Itoa(s.Round),
})
}
y = drawTable(pdf, y, []float64{24, 20, 12, 22, 18, 12, 28, 34, 16},
[]string{"工艺", "步骤", "工人自检", "自检时间", "检验员", "结论", "意见", "签字时间", "轮次"}, signRows)
}
return y
}
// ---------- 工单主卡 PDF ----------
func renderWorkOrderCardPdf(pdf *gofpdf.Fpdf, c *workOrderCard) {
y := pdfMargin
y = pdfTitle(pdf, y, "生产流程卡 · 工件明细")
y = pdfHeading(pdf, y, "一、工单汇总")
y = metaKV(pdf, y, [][2]string{
{"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode}, {"产品名称", c.ProductName},
{"图号", c.DrawingNo}, {"计划数", strconv.Itoa(c.PlanQty)}, {"完成数", strconv.Itoa(c.FinishedNum)},
{"不良数", strconv.Itoa(c.FailNum)}, {"用料合计", strconv.Itoa(c.MaterialTotal)},
{"状态", c.Status}, {"实际开始", c.ActualStart}, {"实际完成", c.ActualFinish},
{"生成时间", c.GeneratedAt},
}, 3)
// 签字汇总:已排除撤销记录、按人去重,不再把返工重签算成次数。
sign := [][2]string{}
if c.Signs.Operator != nil {
sign = append(sign, [2]string{"操作工", c.Signs.Operator.Names + "(" + strconv.Itoa(c.Signs.Operator.Count) + "人,最近 " + c.Signs.Operator.LatestTime + ")"})
} else {
sign = append(sign, [2]string{"操作工", "待签"})
}
if c.Signs.Inspector != nil {
sign = append(sign, [2]string{"检验员", c.Signs.Inspector.Names + "(" + strconv.Itoa(c.Signs.Inspector.Count) + "人,最近 " + c.Signs.Inspector.LatestTime + ")"})
} else {
sign = append(sign, [2]string{"检验员", "待签"})
}
y = metaKV(pdf, y, sign, 1)
y = pdfHeading(pdf, y, "二、工件明细(按成品 SN 逐台)")
if len(c.Products) == 0 {
y = metaKV(pdf, y, [][2]string{{"提示", "暂无成品记录"}}, 1)
}
// 每台强制分页:一台一页,四张子表在页内按需续页。
for i := range c.Products {
p := &c.Products[i]
pdf.AddPage()
y = pdfMargin
y = pdfTitle(pdf, y, "成品 SN:"+p.Sn)
y = metaKV(pdf, y, [][2]string{
{"状态", p.Status}, {"当前工序", p.CurrentProcess},
{"已完成工序", strconv.Itoa(p.DoneCount) + "/" + strconv.Itoa(p.TotalCount)},
{"用料条数", strconv.Itoa(p.MaterialCount)}, {"检验结论", p.InspectionResult},
{"完工时间", p.DoneAt},
}, 3)
y = drawProductTables(pdf, y, p, pdfBlockFlags{
Torque: c.HasTorqueConfig, Sign: c.HasSignConfig, Material: c.HasMaterialConfig,
})
_ = y
}
}
// ---------- 成品 SN 追溯卡 PDF ----------
func renderSnTraceCardPdf(pdf *gofpdf.Fpdf, c *snTraceCard) {
y := pdfMargin
y = pdfTitle(pdf, y, "成品追溯卡 · 工件明细")
y = metaKV(pdf, y, [][2]string{
{"SN", c.Sn}, {"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode},
{"状态", c.Status}, {"完工时间", c.DoneAt}, {"生成时间", c.GeneratedAt},
{"当前工序", c.CurrentProcess}, {"已完成工序", strconv.Itoa(c.DoneCount) + "/" + strconv.Itoa(c.TotalCount)},
{"用料条数", strconv.Itoa(c.MaterialCount)}, {"检验结论", c.InspectionResult},
}, 3)
// 单台卡与工单主卡 products[] 使用同一套四张子表;单台卡不受工艺配置标志约束,四块全开。
p := &woProduct{Steps: c.Steps, Materials: c.Materials, Torques: c.Torques, Signs: c.SignRows}
y = drawProductTables(pdf, y, p, pdfAllBlocks)
if len(c.SkipRows) > 0 {
y = pdfHeading(pdf, y, "5. 人工跳过(设备未连接)")
srows := make([][]string, 0, len(c.SkipRows))
for _, s := range c.SkipRows {
srows = append(srows, []string{s.StepName, s.Reason, s.Operator, s.Time})
}
y = drawTable(pdf, y, []float64{40, 76, 24, 46}, []string{"拧紧步骤", "跳过原因", "操作人", "时间"}, srows)
}
_ = y
}