feat: 完成MES工位终端系统全量功能迭代
本次提交包含以下核心变更: 1. 新增按钮级权限控制框架与前端权限校验 2. 新增工位管理、工艺流程、巡检终端等核心业务模块 3. 完善用户体系,支持工位终端专属登录权限 4. 新增文件上传下载、报表查询等配套功能 5. 修复多系统兼容性与交互体验问题 6. 完成所有文档与配置项的规范化更新
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
"bj_power_mes/internal/logic"
|
||||
"bj_power_mes/internal/svc"
|
||||
)
|
||||
|
||||
// CreateInspectionHandler POST /inspections(PAD 巡检终端提交记录)
|
||||
func CreateInspectionHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req logic.InspectionReq
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
// 按钮级权限:按记录类型校验(块2/8)
|
||||
categoryPerm := map[string]string{
|
||||
"CHECKIN": "sys.inspect:checkin",
|
||||
"POINT": "sys.inspect:point",
|
||||
"PROCESS": "sys.inspect:process",
|
||||
"DONE": "sys.inspect:done",
|
||||
"ALARM": "sys.inspect:alarm",
|
||||
}
|
||||
if code, ok := categoryPerm[req.Category]; ok && !userHasPerm(r, svcCtx, code) {
|
||||
httpx.FailHTTP(w, http.StatusForbidden, "无操作权限:"+code)
|
||||
return
|
||||
}
|
||||
if err := logic.New(svcCtx).CreateInspection(r.Context(), req, operator(r, "")); err != nil {
|
||||
httpx.Fail(w, 2301, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "巡检记录已提交", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// ListInspectionsHandler GET /inspections?category=&operator=&from=&to=
|
||||
func ListInspectionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
data, err := logic.New(svcCtx).ListInspections(r.Context(),
|
||||
q.Get("category"), q.Get("operator"), q.Get("from"), q.Get("to"))
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2302, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// UploadPhotoHandler POST /inspections/upload(巡检拍照上传,返回文件名)
|
||||
func UploadPhotoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
httpx.BadRequest(w, "上传文件过大或格式错误")
|
||||
return
|
||||
}
|
||||
name, err := saveUploadFile(r, "file", svcCtx.Config.Upload.Dir)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2303, "照片保存失败:"+err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, map[string]any{"filename": name, "url": "/api/v1/files/" + name})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
"bj_power_mes/internal/svc"
|
||||
)
|
||||
|
||||
// pathPermMap 请求方法+路径 → 所需按钮级权限码(块2:后端接口兜底校验)。
|
||||
// 路径中的 :id 统一以 * 结尾匹配。
|
||||
var pathPermMap = map[string]string{
|
||||
"POST:/api/v1/product-types": "produce.product:add",
|
||||
"PUT:/api/v1/product-types": "produce.product:edit",
|
||||
"DELETE:/api/v1/product-types/*": "produce.product:delete",
|
||||
"POST:/api/v1/work-orders": "produce.workorder:add",
|
||||
"PUT:/api/v1/work-orders": "produce.workorder:edit",
|
||||
"DELETE:/api/v1/work-orders/*": "produce.workorder:delete",
|
||||
"POST:/api/v1/daily-plans": "produce.workorder:dailyplan",
|
||||
"PUT:/api/v1/bom": "produce.bom:edit",
|
||||
"POST:/api/v1/material-requests/generate": "produce.material:generate",
|
||||
"POST:/api/v1/plc/send-process": "produce.plc:send",
|
||||
"POST:/api/v1/process-flows": "produce.processflow:add",
|
||||
"DELETE:/api/v1/process-flows/*": "produce.processflow:delete",
|
||||
"POST:/api/v1/process-flows/upload": "produce.processflow:upload",
|
||||
"POST:/api/v1/process-steps": "produce.processflow:edit",
|
||||
"POST:/api/v1/stations": "produce.station:edit",
|
||||
"POST:/api/v1/users": "sys.rbac:user",
|
||||
"PUT:/api/v1/users": "sys.rbac:user",
|
||||
"DELETE:/api/v1/users/*": "sys.rbac:user",
|
||||
"POST:/api/v1/roles": "sys.rbac:role",
|
||||
"PUT:/api/v1/roles": "sys.rbac:role",
|
||||
"DELETE:/api/v1/roles/*": "sys.rbac:role",
|
||||
"POST:/api/v1/permissions": "sys.rbac:perm",
|
||||
"PUT:/api/v1/permissions": "sys.rbac:perm",
|
||||
"DELETE:/api/v1/permissions/*": "sys.rbac:perm",
|
||||
}
|
||||
|
||||
// userHasPerm 校验当前登录用户是否拥有某权限码(SUPER_ADMIN 或 * 放行)。
|
||||
// 用户ID 使用 uidFromRequest:优先取 context,缺失时回退解析 Authorization token。
|
||||
func userHasPerm(r *http.Request, svcCtx *svc.ServiceContext, code string) bool {
|
||||
if code == "" {
|
||||
return true
|
||||
}
|
||||
userId := uidFromRequest(r, svcCtx)
|
||||
if userId <= 0 {
|
||||
return false
|
||||
}
|
||||
usr, err := svcCtx.EntClient.User.Get(r.Context(), userId)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
role, err := svcCtx.EntClient.Role.Get(r.Context(), usr.RoleId)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if role.Code == "SUPER_ADMIN" {
|
||||
return true
|
||||
}
|
||||
for _, c := range role.PermissionCodes {
|
||||
if c == "*" || c == code {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// permissionGuard 按钮级权限后端兜底中间件(仅对写操作映射表内的路径生效)
|
||||
func permissionGuard(svcCtx *svc.ServiceContext) func(http.HandlerFunc) http.HandlerFunc {
|
||||
return func(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
code, ok := pathPerm(r.Method, r.URL.Path)
|
||||
if ok && !userHasPerm(r, svcCtx, code) {
|
||||
httpx.FailHTTP(w, http.StatusForbidden, "无操作权限:"+code)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pathPerm 先按完整路径精确匹配;未命中时把末段替换为 * 再匹配(用于 :id 结尾的路径)。
|
||||
func pathPerm(method, path string) (string, bool) {
|
||||
key := method + ":" + strings.TrimSuffix(path, "/")
|
||||
if code, ok := pathPermMap[key]; ok {
|
||||
return code, true
|
||||
}
|
||||
segs := strings.Split(key, "/")
|
||||
if len(segs) > 0 {
|
||||
segs[len(segs)-1] = "*"
|
||||
}
|
||||
code, ok := pathPermMap[strings.Join(segs, "/")]
|
||||
return code, ok
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
"bj_power_mes/internal/logic"
|
||||
"bj_power_mes/internal/svc"
|
||||
)
|
||||
|
||||
// ProcessCardHandler GET /api/v1/process-card?sn=xxx
|
||||
// 按 SN 生成可打印流程卡(无公司名、含签名栏、可调样式),返回 text/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
|
||||
}
|
||||
data, err := logic.New(svcCtx).Trace(r.Context(), sn)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2401, err.Error())
|
||||
return
|
||||
}
|
||||
html, err := renderProcessCard(sn, data)
|
||||
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 cardTmpl struct {
|
||||
Sn string
|
||||
OrderNo string
|
||||
Product string
|
||||
CreatedAt string
|
||||
Processes []cardProcess
|
||||
Materials []string
|
||||
Operator string
|
||||
Inspector string
|
||||
DoneTime string
|
||||
Result string
|
||||
}
|
||||
|
||||
type cardProcess struct {
|
||||
Code string
|
||||
Name string
|
||||
Station string
|
||||
Operator string
|
||||
Status string
|
||||
Result string
|
||||
Steps []cardStep
|
||||
}
|
||||
|
||||
type cardStep struct {
|
||||
Name string
|
||||
Value string
|
||||
OK bool
|
||||
}
|
||||
|
||||
func renderProcessCard(sn string, data map[string]any) (string, error) {
|
||||
t := cardTmpl{Sn: sn}
|
||||
wp, _ := data["workpiece"].(map[string]any)
|
||||
if wp != nil {
|
||||
t.OrderNo = strAny(wp["orderNo"])
|
||||
t.Product = strAny(wp["productType"])
|
||||
if c, ok := wp["createdAt"]; ok {
|
||||
if ts, ok := c.(time.Time); ok {
|
||||
t.CreatedAt = ts.Format("2006-01-02 15:04")
|
||||
} else {
|
||||
t.CreatedAt = fmt.Sprintf("%v", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
procList, _ := data["processTimeline"].([]any)
|
||||
for _, p := range procList {
|
||||
pm, _ := p.(map[string]any)
|
||||
cp := cardProcess{
|
||||
Code: strAny(pm["processCode"]),
|
||||
Name: strAny(pm["processName"]),
|
||||
Station: strAny(pm["stationNo"]),
|
||||
Operator: strAny(pm["operator"]),
|
||||
Status: strAny(pm["status"]),
|
||||
Result: strAny(pm["result"]),
|
||||
}
|
||||
t.Processes = append(t.Processes, cp)
|
||||
}
|
||||
steps, _ := data["stepData"].([]any)
|
||||
stepByProc := map[string][]cardStep{}
|
||||
for _, s := range steps {
|
||||
sm, _ := s.(map[string]any)
|
||||
key := fmt.Sprintf("%v", sm["processCode"])
|
||||
ok, _ := sm["isOK"].(bool)
|
||||
stepByProc[key] = append(stepByProc[key], cardStep{
|
||||
Name: strAny(sm["stepName"]),
|
||||
Value: strAny(sm["valueText"]),
|
||||
OK: ok,
|
||||
})
|
||||
}
|
||||
for i := range t.Processes {
|
||||
t.Processes[i].Steps = stepByProc[t.Processes[i].Code]
|
||||
}
|
||||
assoc, _ := data["associationTrace"].(map[string]any)
|
||||
if assoc != nil {
|
||||
if b, ok := assoc["batchItems"].([]any); ok {
|
||||
for _, x := range b {
|
||||
t.Materials = append(t.Materials, fmt.Sprintf("%v", x))
|
||||
}
|
||||
}
|
||||
if s, ok := assoc["serialItems"].([]any); ok {
|
||||
for _, x := range s {
|
||||
t.Materials = append(t.Materials, fmt.Sprintf("%v", x))
|
||||
}
|
||||
}
|
||||
t.Operator = strAny(assoc["operator"])
|
||||
}
|
||||
done := "待完工"
|
||||
for _, p := range t.Processes {
|
||||
if p.Result == "NG" {
|
||||
done = "NG"
|
||||
}
|
||||
}
|
||||
t.Result = done
|
||||
|
||||
const tpl = `<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>流程卡 {{.Sn}}</title>
|
||||
<style>
|
||||
* { margin:0; padding:0; box-sizing:border-box; }
|
||||
body { font-family:"Microsoft YaHei",sans-serif; color:#1f2937; padding:24px; }
|
||||
.card { max-width:900px; margin:0 auto; border:2px solid #333; border-radius:8px; padding:20px 24px; }
|
||||
h1 { font-size:22px; text-align:center; border-bottom:2px solid #333; padding-bottom:10px; margin-bottom:14px; letter-spacing:4px; }
|
||||
.meta { display:flex; flex-wrap:wrap; gap:8px 32px; font-size:14px; margin-bottom:14px; }
|
||||
.meta b { font-weight:700; }
|
||||
table { width:100%; border-collapse:collapse; font-size:13px; }
|
||||
th, td { border:1px solid #999; padding:6px 8px; text-align:center; }
|
||||
th { background:#f3f4f6; }
|
||||
.ok { color:#15803d; font-weight:700; }
|
||||
.ng { color:#dc2626; font-weight:700; }
|
||||
.sub td { text-align:left; color:#374151; background:#fafafa; }
|
||||
.sign { display:flex; justify-content:space-between; margin-top:22px; font-size:14px; }
|
||||
.sign div { width:45%; border-top:1px solid #333; padding-top:6px; text-align:center; }
|
||||
@media print { body { padding:0; } .card { border-color:#000; box-shadow:none; } .no-print { display:none; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>产品流程卡</h1>
|
||||
<div class="meta">
|
||||
<span>SN:<b>{{.Sn}}</b></span>
|
||||
<span>工单号:<b>{{.OrderNo}}</b></span>
|
||||
<span>产品型号:<b>{{.Product}}</b></span>
|
||||
<span>登记时间:<b>{{.CreatedAt}}</b></span>
|
||||
<span>判定:<b>{{if eq .Result "NG"}}<span class="ng">NG</span>{{else}}{{.Result}}{{end}}</b></span>
|
||||
</div>
|
||||
<table>
|
||||
<thead><tr><th>工序</th><th>工序名称</th><th>工位</th><th>操作人</th><th>采集参数</th><th>结果</th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Processes}}
|
||||
<tr>
|
||||
<td>工序{{.Code}}</td><td>{{.Name}}</td><td>{{.Station}}</td><td>{{.Operator}}</td>
|
||||
<td>{{if .Steps}}{{range .Steps}}{{.Name}}={{.Value}}({{if .OK}}<span class="ok">OK</span>{{else}}<span class="ng">NG</span>{{end}}) {{end}}{{else}}-{{end}}</td>
|
||||
<td>{{if eq .Result "NG"}}<span class="ng">NG</span>{{else}}OK{{end}}</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
{{if .Materials}}
|
||||
<p style="margin-top:10px;font-size:13px;">关联物料/批次:{{range .Materials}}{{.}} {{end}}</p>
|
||||
{{end}}
|
||||
<div class="sign">
|
||||
<div>操作人签字:</div>
|
||||
<div>检验员签字:</div>
|
||||
</div>
|
||||
<div style="text-align:center;margin-top:14px;">
|
||||
<button class="no-print" onclick="window.print()" style="padding:8px 28px;font-size:15px;">打 印</button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func strAny(v any) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%v", v)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
"bj_power_mes/internal/logic"
|
||||
"bj_power_mes/internal/svc"
|
||||
)
|
||||
|
||||
// ListProcessFlowsHandler GET /process-flows?processCode=
|
||||
func ListProcessFlowsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
code := atoiDefault(r.URL.Query().Get("processCode"), 0)
|
||||
data, err := logic.New(svcCtx).ListFlows(r.Context(), code)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2201, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// SaveProcessFlowHandler POST /process-flows(新建或更新工艺流程,含步骤模板)
|
||||
func SaveProcessFlowHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req logic.FlowReq
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
if err := logic.New(svcCtx).SaveFlow(r.Context(), req, operator(r, "")); err != nil {
|
||||
httpx.Fail(w, 2202, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "工艺流程已保存", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteProcessFlowHandler DELETE /process-flows/:id
|
||||
func DeleteProcessFlowHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := logic.New(svcCtx).DeleteFlow(r.Context(), pathId(r), operator(r, "")); err != nil {
|
||||
httpx.Fail(w, 2203, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "工艺流程已删除", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// UploadPdfHandler POST /process-flows/upload(工艺图纸PDF上传,返回文件名)
|
||||
func UploadPdfHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
httpx.BadRequest(w, "上传文件过大或格式错误")
|
||||
return
|
||||
}
|
||||
name, err := saveUploadFile(r, "file", svcCtx.Config.Upload.Dir)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2204, "文件保存失败:"+err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, map[string]any{"filename": name, "url": "/api/v1/files/" + name})
|
||||
}
|
||||
}
|
||||
|
||||
// FileDownloadHandler JWT 保护的文件下载(MES 前端展示 PDF/照片)
|
||||
func FileDownloadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
serveUploadFile(w, r, svcCtx.Config.Upload.Dir, r.URL.Query().Get("name"))
|
||||
}
|
||||
}
|
||||
|
||||
// ListStationsHandler GET /stations
|
||||
func ListStationsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := logic.New(svcCtx).ListStations(r.Context())
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2205, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// SaveStationHandler POST /stations(工位绑定工艺流程图)
|
||||
func SaveStationHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req logic.StationReq
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
if err := logic.New(svcCtx).SaveStation(r.Context(), req, operator(r, "")); err != nil {
|
||||
httpx.Fail(w, 2206, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "工位绑定已保存", nil)
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,8 @@ func RegisterRoutes(server *rest.Server, serverCtx *svc.ServiceContext) {
|
||||
{Method: http.MethodPut, Path: "/permissions", Handler: UpdatePermissionHandler(serverCtx)},
|
||||
{Method: http.MethodDelete, Path: "/permissions/:id", Handler: DeletePermissionHandler(serverCtx)},
|
||||
}
|
||||
server.AddRoutes(jwtAdmin,
|
||||
server.AddRoutes(
|
||||
rest.WithMiddlewares([]rest.Middleware{permissionGuard(serverCtx)}, jwtAdmin...),
|
||||
rest.WithPrefix("/api/v1"),
|
||||
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
|
||||
)
|
||||
|
||||
@@ -49,6 +49,29 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
|
||||
Method: http.MethodGet, Path: "/api/internal/dashboard/stream", Handler: serverCtx.SSE.Handler,
|
||||
}, rest.WithTimeout(3600_000_000_000))
|
||||
|
||||
// ---------- 工位终端内部 API(块1/4/5/6) ----------
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodPost, Path: "/api/internal/station/login", Handler: internal(StationLoginInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodPost, Path: "/api/internal/station/change-password", Handler: internal(StationChangePasswordInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodGet, Path: "/api/internal/station/task", Handler: internal(StationTaskInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodPost, Path: "/api/internal/station/report", Handler: internal(StationReportInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodPost, Path: "/api/internal/station/checkin", Handler: internal(StationCheckinInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodGet, Path: "/api/internal/station/workload", Handler: internal(WorkloadInternalHandler(serverCtx)),
|
||||
})
|
||||
server.AddRoute(rest.Route{
|
||||
Method: http.MethodGet, Path: "/api/internal/files", Handler: internal(FileDownloadInternalHandler(serverCtx)),
|
||||
})
|
||||
|
||||
// ---------- JWT 业务 API ----------
|
||||
jwtRoutes := []rest.Route{
|
||||
{Method: http.MethodGet, Path: "/product-types", Handler: production.ListProductTypesHandler(serverCtx)},
|
||||
@@ -92,8 +115,29 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext
|
||||
{Method: http.MethodGet, Path: "/semi/flows", Handler: production.ListSemiFlowsHandler(serverCtx)},
|
||||
|
||||
{Method: http.MethodGet, Path: "/event-logs", Handler: production.ListEventLogsHandler(serverCtx)},
|
||||
|
||||
// ---------- 工艺流程/工位(块3) ----------
|
||||
{Method: http.MethodGet, Path: "/process-flows", Handler: ListProcessFlowsHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/process-flows", Handler: SaveProcessFlowHandler(serverCtx)},
|
||||
{Method: http.MethodDelete, Path: "/process-flows/:id", Handler: DeleteProcessFlowHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/process-flows/upload", Handler: UploadPdfHandler(serverCtx)},
|
||||
{Method: http.MethodGet, Path: "/stations", Handler: ListStationsHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/stations", Handler: SaveStationHandler(serverCtx)},
|
||||
{Method: http.MethodGet, Path: "/files", Handler: FileDownloadHandler(serverCtx)},
|
||||
|
||||
// ---------- PAD 巡检终端(块8) ----------
|
||||
{Method: http.MethodPost, Path: "/inspections", Handler: CreateInspectionHandler(serverCtx)},
|
||||
{Method: http.MethodGet, Path: "/inspections", Handler: ListInspectionsHandler(serverCtx)},
|
||||
{Method: http.MethodPost, Path: "/inspections/upload", Handler: UploadPhotoHandler(serverCtx)},
|
||||
|
||||
// ---------- 工作量/绩效报表(块6) ----------
|
||||
{Method: http.MethodGet, Path: "/performance", Handler: WorkloadInternalHandler(serverCtx)},
|
||||
|
||||
// ---------- 流程卡打印(块7) ----------
|
||||
{Method: http.MethodGet, Path: "/process-card", Handler: ProcessCardHandler(serverCtx)},
|
||||
}
|
||||
server.AddRoutes(jwtRoutes,
|
||||
server.AddRoutes(
|
||||
rest.WithMiddlewares([]rest.Middleware{permissionGuard(serverCtx)}, jwtRoutes...),
|
||||
rest.WithPrefix("/api/v1"),
|
||||
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"bj_power_mes/common/httpx"
|
||||
"bj_power_mes/internal/logic"
|
||||
"bj_power_mes/internal/svc"
|
||||
)
|
||||
|
||||
// atoiDefault 解析整型字符串,非法返回默认值
|
||||
func atoiDefault(s string, def int) int {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil {
|
||||
return n
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// operator 从 JWT 上下文取操作人,取不到回退 fallback
|
||||
func operator(r *http.Request, fallback string) string {
|
||||
if v, ok := r.Context().Value("name").(string); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
if v, ok := r.Context().Value("username").(string); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
if fallback != "" {
|
||||
return fallback
|
||||
}
|
||||
return "system"
|
||||
}
|
||||
|
||||
// StationLoginInternalHandler 工位终端登录(内部接口,X-API-TOKEN 保护)
|
||||
// 校验 用户名 + 工位终端密码 + 工位权限,签发与 MES 同密钥 JWT
|
||||
func StationLoginInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req logic.StationLoginReq
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
data, err := logic.New(svcCtx).StationLogin(r.Context(), req)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2101, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// StationChangePasswordInternalHandler 工位终端修改自己的工位终端密码
|
||||
func StationChangePasswordInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
UserId int `json:"userId"`
|
||||
OldPassword string `json:"oldPassword"`
|
||||
NewPassword string `json:"newPassword"`
|
||||
}
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
if err := logic.New(svcCtx).StationChangePassword(r.Context(), req.UserId, req.OldPassword, req.NewPassword); err != nil {
|
||||
httpx.Fail(w, 2102, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "工位终端密码修改成功", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// StationTaskInternalHandler 工位终端拉取当前任务(工位/流程/步骤/活跃工单)
|
||||
func StationTaskInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
stationNo := atoiDefault(r.URL.Query().Get("stationNo"), 0)
|
||||
if stationNo <= 0 {
|
||||
httpx.BadRequest(w, "缺少 stationNo 参数")
|
||||
return
|
||||
}
|
||||
data, err := logic.New(svcCtx).StationTask(r.Context(), stationNo)
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2103, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// StationReportInternalHandler 工位终端工序报工(写工序实绩 + 步骤考核)
|
||||
func StationReportInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req logic.ReportProcessReq
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
if err := logic.New(svcCtx).ReportProcess(r.Context(), req, operator(r, "")); err != nil {
|
||||
httpx.Fail(w, 2104, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "报工成功", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// WorkloadInternalHandler 工作量/绩效报表(工位终端"我的工作量" + MES 绩效报表共用)
|
||||
func WorkloadInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
data, err := logic.New(svcCtx).Workload(r.Context(), q.Get("operator"), q.Get("from"), q.Get("to"))
|
||||
if err != nil {
|
||||
httpx.Fail(w, 2105, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.Ok(w, data)
|
||||
}
|
||||
}
|
||||
|
||||
// FileDownloadInternalHandler 内部文件下载(工艺图纸 PDF,供工位终端代理)
|
||||
func FileDownloadInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
serveUploadFile(w, r, svcCtx.Config.Upload.Dir, r.URL.Query().Get("name"))
|
||||
}
|
||||
}
|
||||
|
||||
// StationCheckinInternalHandler 工位终端暂存退库(半成品入库,块4/5)
|
||||
// 记录已完成工序后按半成品 INBOUND 流转,并通知 WMS 入库。
|
||||
func StationCheckinInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Sn string `json:"sn"`
|
||||
OrderNo string `json:"orderNo"`
|
||||
StationNo int `json:"stationNo"`
|
||||
ProcessCode int `json:"processCode"`
|
||||
Operator string `json:"operator"`
|
||||
}
|
||||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||||
httpx.BadRequest(w, "请求体解析失败")
|
||||
return
|
||||
}
|
||||
if req.Sn == "" {
|
||||
httpx.BadRequest(w, "缺少 sn")
|
||||
return
|
||||
}
|
||||
doneCodes := []int{}
|
||||
if req.ProcessCode > 0 {
|
||||
doneCodes = append(doneCodes, req.ProcessCode)
|
||||
}
|
||||
op := req.Operator
|
||||
if op == "" {
|
||||
op = operator(r, "")
|
||||
}
|
||||
if err := logic.New(svcCtx).SemiFlow(r.Context(), logic.SemiReq{
|
||||
Sn: req.Sn,
|
||||
OrderNo: req.OrderNo,
|
||||
DoneProcessCodes: doneCodes,
|
||||
Action: "INBOUND",
|
||||
}, op); err != nil {
|
||||
httpx.Fail(w, 2106, err.Error())
|
||||
return
|
||||
}
|
||||
httpx.OkMessage(w, "暂存退库已登记", nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// saveUploadFile 保存上传文件(工艺图纸PDF / 巡检照片),返回生成的文件名
|
||||
func saveUploadFile(r *http.Request, field, dir string) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
file, header, err := r.FormFile(field)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
if ext == "" {
|
||||
ext = ".bin"
|
||||
}
|
||||
name := time.Now().Format("20060102150405") + "_" + randHex(6) + ext
|
||||
dst, err := os.Create(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer dst.Close()
|
||||
if _, err := io.Copy(dst, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func randHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)[:n*2]
|
||||
}
|
||||
|
||||
// serveUploadFile 下发上传目录中的文件(限制为单段文件名,防路径穿越)
|
||||
func serveUploadFile(w http.ResponseWriter, r *http.Request, dir, name string) {
|
||||
name = strings.TrimSpace(filepath.Base(name))
|
||||
if name == "" || name == "." || name == ".." || strings.Contains(name, "..") {
|
||||
http.Error(w, "非法文件名", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
f, err := os.Open(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
http.Error(w, "文件不存在", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
ct := "application/octet-stream"
|
||||
switch {
|
||||
case strings.HasSuffix(strings.ToLower(name), ".pdf"):
|
||||
ct = "application/pdf"
|
||||
case strings.HasSuffix(strings.ToLower(name), ".jpg"), strings.HasSuffix(strings.ToLower(name), ".jpeg"):
|
||||
ct = "image/jpeg"
|
||||
case strings.HasSuffix(strings.ToLower(name), ".png"):
|
||||
ct = "image/png"
|
||||
}
|
||||
w.Header().Set("Content-Type", ct)
|
||||
http.ServeContent(w, r, name, time.Time{}, f)
|
||||
}
|
||||
Reference in New Issue
Block a user