Files
bj_power/bj_power_mes/internal/handler/processcard_pdf.go
T

410 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"
"github.com/jung-kurt/gofpdf"
"bj_power_mes/common/httpx"
"bj_power_mes/internal/svc"
)
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
pdf.AddPage()
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
pdf.AddPage()
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
}
// ---------- 工单主卡 PDF ----------
func renderWorkOrderCardPdf(pdf *gofpdf.Fpdf, c *workOrderCard) {
y := pdfMargin
y = pdfTitle(pdf, y, "生产流程卡(工单维度)")
y = metaKV(pdf, y, [][2]string{
{"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode}, {"产品名称", c.ProductName},
{"图号", c.DrawingNo}, {"计划数", strconv.Itoa(c.PlanQty)}, {"完成数", strconv.Itoa(c.FinishedNum)},
{"状态", c.Status}, {"不合格数", strconv.Itoa(c.FailNum)},
}, 4)
y = metaKV(pdf, y, [][2]string{
{"计划开始", c.PlanStart}, {"计划完成", c.PlanEnd}, {"实际开始", c.ActualStart},
{"实际完成", c.CompletedAt}, {"实际结束", c.ActualFinish}, {"生成时间", c.GeneratedAt},
}, 3)
y = pdfHeading(pdf, y, "一、工序实绩")
widths := []float64{12, 34, 14, 16, 28, 28, 24, 16, 18}
rows := [][]string{}
for _, s := range c.ProcessSteps {
rows = append(rows, []string{
strconv.Itoa(s.Seq), s.ProcessName, s.StationNo, s.CollectCN,
s.ActualStart, s.ActualEnd, s.Operators, s.Status, s.Auditor,
})
}
y = drawTable(pdf, y, widths, []string{"序号", "工序", "工位", "采集", "实绩开始", "实绩结束", "操作人", "状态", "审核人"}, rows)
y = pdfHeading(pdf, y, "二、用料清单 · 序列号=是(逐件追溯)")
swidths := []float64{28, 38, 16, 28, 12, 28, 10, 14, 16}
srows := [][]string{}
for _, m := range c.SerialMaterials {
srows = append(srows, []string{
m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit,
strings.Join(m.SnList, " "), strconv.Itoa(m.Qty), m.StationNo, m.Operator,
})
}
y = drawTable(pdf, y, swidths, []string{"图号", "名称", "类型", "规格", "单位", "物料SN", "数量", "装配工位", "装配人"}, srows)
y = pdfHeading(pdf, y, "三、用料清单 · 序列号=否(按批追溯)")
bwidths := []float64{28, 38, 16, 28, 12, 20, 10, 14, 16}
brows := [][]string{}
for _, m := range c.BatchMaterials {
brows = append(brows, []string{
m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit,
m.BatchNo, strconv.Itoa(m.Qty), m.StationNo, m.Operator,
})
}
y = drawTable(pdf, y, bwidths, []string{"图号", "名称", "类型", "规格", "单位", "批次号", "数量", "装配工位", "装配人"}, brows)
y = pdfHeading(pdf, y, "四、成品明细")
pwidths := []float64{60, 30, 88}
prows := [][]string{}
for _, p := range c.Products {
prows = append(prows, []string{p.Sn, p.Status, p.DoneAt})
}
y = drawTable(pdf, y, pwidths, []string{"SN", "状态", "完工时间"}, prows)
y = pdfHeading(pdf, y, "五、签字确认")
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{"检验员", "待签"})
}
if c.Signs.Auditor != nil {
sign = append(sign, [2]string{"审核人", c.Signs.Auditor.Names + "(" + strconv.Itoa(c.Signs.Auditor.Count) + "次,最近 " + c.Signs.Auditor.LatestTime + ")"})
} else {
sign = append(sign, [2]string{"审核人", "待签"})
}
sign = append(sign, [2]string{"批准人", "手签"})
y = metaKV(pdf, y, sign, 1)
}
// ---------- 成品 SN 追溯卡 PDF ----------
func renderSnTraceCardPdf(pdf *gofpdf.Fpdf, c *snTraceCard) {
y := pdfMargin
y = pdfTitle(pdf, y, "成品追溯卡(SN 维度)")
y = metaKV(pdf, y, [][2]string{
{"SN", c.Sn}, {"工单号", c.WorkOrderNo}, {"产品型号", c.ProductCode},
{"状态", c.Status}, {"完工时间", c.DoneAt}, {"生成时间", c.GeneratedAt},
}, 3)
y = pdfHeading(pdf, y, "一、工序实绩")
widths := []float64{14, 14, 38, 28, 28, 22, 16, 16}
rows := [][]string{}
for _, s := range c.Processes {
rows = append(rows, []string{
strconv.Itoa(s.FlowId), s.StationNo, s.ProcessName, s.StartAt, s.EndAt,
s.Operator, s.Status, s.Result,
})
}
y = drawTable(pdf, y, widths, []string{"产线", "工位", "工序", "开始", "结束", "操作人", "状态", "结果"}, rows)
y = pdfHeading(pdf, y, "二、用料清单 · 序列号=是")
swidths := []float64{28, 38, 16, 28, 12, 28, 10, 14, 16}
srows := [][]string{}
for _, m := range c.SerialMaterials {
srows = append(srows, []string{
m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit,
strings.Join(m.SnList, " "), strconv.Itoa(m.Qty), m.StationNo, m.Operator,
})
}
y = drawTable(pdf, y, swidths, []string{"图号", "名称", "类型", "规格", "单位", "物料SN", "数量", "装配工位", "装配人"}, srows)
y = pdfHeading(pdf, y, "三、用料清单 · 序列号=否")
bwidths := []float64{28, 38, 16, 28, 12, 20, 10, 14, 16}
brows := [][]string{}
for _, m := range c.BatchMaterials {
brows = append(brows, []string{
m.MaterialCode, m.MaterialName, m.MaterialType, m.Spec, m.Unit,
m.BatchNo, strconv.Itoa(m.Qty), m.StationNo, m.Operator,
})
}
y = drawTable(pdf, y, bwidths, []string{"图号", "名称", "类型", "规格", "单位", "批次号", "数量", "装配工位", "装配人"}, brows)
if len(c.TorqueRows) > 0 {
y = pdfHeading(pdf, y, "四、拧紧数据")
twidths := []float64{24, 28, 24, 18, 24, 48}
trows := [][]string{}
for _, t := range c.TorqueRows {
trows = append(trows, []string{t.ScrewNo, t.Torque, t.Angle, t.Result, t.Operator, t.Time})
}
y = drawTable(pdf, y, twidths, []string{"螺丝编号", "扭矩(N·m)", "角度(°)", "结果", "操作人", "时间"}, trows)
}
y = pdfHeading(pdf, y, "五、签字确认")
sign := [][2]string{}
if c.Signs.Operator != nil {
sign = append(sign, [2]string{"操作工", c.Signs.Operator.Names})
} else {
sign = append(sign, [2]string{"操作工", "待签"})
}
if c.Signs.Inspector != nil {
sign = append(sign, [2]string{"检验员", c.Signs.Inspector.Names})
} else {
sign = append(sign, [2]string{"检验员", "待签"})
}
if c.Signs.Auditor != nil {
sign = append(sign, [2]string{"审核人", c.Signs.Auditor.Names})
} else {
sign = append(sign, [2]string{"审核人", "待签"})
}
sign = append(sign, [2]string{"批准人", "手签"})
y = metaKV(pdf, y, sign, 1)
}