Files
bj_power/bj_power_mes/internal/logic/auth.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

692 lines
24 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 logic
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"time"
tokenx "bj_power_mes/common/token"
"bj_power_mes/ent"
"bj_power_mes/ent/permission"
"bj_power_mes/ent/role"
"bj_power_mes/ent/station"
"bj_power_mes/ent/user"
"bj_power_mes/ent/userstation"
"github.com/zeromicro/go-zero/core/logx"
"golang.org/x/crypto/bcrypt"
)
// ------ 请求/返回 DTO ------
type LoginReq struct {
Username string `json:"username"`
Password string `json:"password"`
}
type LoginResp struct {
AccessToken string `json:"accessToken"`
AccessExpire int64 `json:"accessExpire"`
}
// sessionExpire 会话闲置窗口(秒),默认 1 小时
func (s *Service) sessionExpire() int64 {
if s.ctx.Config.Auth.AccessExpire > 0 {
return s.ctx.Config.Auth.AccessExpire
}
return 3600
}
// newSessionID 生成后台登录会话标识(32 位 hex,随机 16 字节)
func newSessionID() string {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
return hex.EncodeToString(b)
}
// currentToken 签发 access token(滑动续签模式,无 refresh);sid=后台登录会话标识(互踢用,工位终端登录传空)
func (s *Service) issueTokens(usr *ent.User, roleEntity *ent.Role, sid string) (LoginResp, error) {
claims := tokenx.Claims{UserId: usr.ID, Username: usr.Username, Name: usr.Name, RoleId: usr.RoleId, Sid: sid}
if roleEntity != nil {
claims.RoleCode = roleEntity.Code
claims.RoleName = roleEntity.Name
}
expire := s.sessionExpire()
access, err := tokenx.Issue(s.ctx.Config.Auth.AccessSecret, time.Duration(expire)*time.Second, claims)
if err != nil {
return LoginResp{}, err
}
return LoginResp{AccessToken: access, AccessExpire: expire}, nil
}
type UserInfoResp struct {
UserId int `json:"userId"`
Username string `json:"username"`
Name string `json:"name"`
RoleId int `json:"roleId"`
RoleCode string `json:"roleCode"`
RoleName string `json:"roleName"`
Menus []permissionItem `json:"menus"`
PermissionCodes []string `json:"permissionCodes"`
}
type ChangePasswordReq struct {
OldPassword string `json:"oldPassword"`
NewPassword string `json:"newPassword"`
}
type permissionItem struct {
Code string `json:"code"`
Name string `json:"name"`
Path string `json:"path"`
Icon string `json:"icon"`
}
// Login 登录
func (s *Service) Login(ctx context.Context, req LoginReq) (LoginResp, error) {
var resp LoginResp
usr, err := s.ctx.EntClient.User.Query().Where(user.Username(req.Username)).First(ctx)
if err != nil {
return resp, errors.New("用户名或密码错误")
}
if usr.Status != "ENABLED" {
return resp, errors.New("账号已禁用")
}
if bcrypt.CompareHashAndPassword([]byte(usr.Password), []byte(req.Password)) != nil {
return resp, errors.New("用户名或密码错误")
}
// 记录最近登录时间 + 写入新会话标识 activeToken=SID(同账号互踢:新登录顶掉旧后台会话;
// 工位终端登录走 StationLogin,不写本字段,互不影响。写失败不阻塞登录)
now := time.Now().Unix()
sid := newSessionID()
if err := s.ctx.EntClient.User.UpdateOneID(usr.ID).SetLastLoginAt(now).SetActiveToken(sid).Exec(ctx); err != nil {
// 不阻塞登录,仅记日志
}
usr.LastLoginAt = &now
roleEntity, _ := s.ctx.EntClient.Role.Get(ctx, usr.RoleId)
return s.issueTokens(usr, roleEntity, sid)
}
// UserInfo 当前用户信息 + 菜单权限
func (s *Service) UserInfo(ctx context.Context, userId int) (UserInfoResp, error) {
var out UserInfoResp
usr, err := s.ctx.EntClient.User.Get(ctx, userId)
if err != nil {
return out, err
}
out.UserId = usr.ID
out.Username = usr.Username
out.Name = usr.Name
out.RoleId = usr.RoleId
roleEntity, err := s.ctx.EntClient.Role.Get(ctx, usr.RoleId)
if err != nil {
roleEntity = nil
}
if roleEntity != nil {
out.RoleCode = roleEntity.Code
out.RoleName = roleEntity.Name
out.PermissionCodes = roleEntity.PermissionCodes
}
// 取所拥有权限对应的菜单
perms, err := s.ctx.EntClient.Permission.Query().
Where(permission.Type("MENU")).
Order(ent.Asc(permission.FieldSort)).All(ctx)
if err != nil {
return out, nil
}
owned := map[string]bool{}
for _, c := range out.PermissionCodes {
owned[c] = true
}
for _, p := range perms {
if roleEntity == nil {
continue
}
if roleEntity.Code == "SUPER_ADMIN" || owned[p.Code] || owned["*"] {
out.Menus = append(out.Menus, permissionItem{Code: p.Code, Name: p.Name, Path: p.Path, Icon: p.Icon})
}
}
return out, nil
}
// ChangePassword 当前登录用户修改自己的密码
func (s *Service) ChangePassword(ctx context.Context, userId int, req ChangePasswordReq) error {
if userId <= 0 {
return errors.New("未登录")
}
if req.OldPassword == "" || req.NewPassword == "" {
return errors.New("请输入旧密码与新密码")
}
if len(req.NewPassword) < 6 {
return errors.New("新密码长度至少 6 位")
}
if err := checkPasswordStrong(req.NewPassword); err != nil {
return err
}
usr, err := s.ctx.EntClient.User.Get(ctx, userId)
if err != nil {
return errors.New("用户不存在")
}
if bcrypt.CompareHashAndPassword([]byte(usr.Password), []byte(req.OldPassword)) != nil {
return errors.New("旧密码不正确")
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
return s.ctx.EntClient.User.UpdateOneID(userId).SetPassword(string(hash)).Exec(ctx)
}
// ------ 工位终端登录(块1:用户体系来源于 MES,终端登录改调本接口) ------
type StationLoginReq struct {
Username string `json:"username"`
Password string `json:"password"`
StationNo int `json:"stationNo"`
}
type StationLoginResp struct {
AccessToken string `json:"accessToken"`
ExpireAt int64 `json:"expireAt"`
User UserInfoResp `json:"user"`
Stations []int `json:"stations"`
StationNo int `json:"stationNo"`
// 2026-11-24 时钟偏差自检(第 2 层防御):携带 MES 服务器当前 unix 秒。终端/前端拿它
// 与本机时间比对,偏差超阈值即告警——token 有效期按签发方时钟写入、验签方本地时间判定,
// 两机时钟漂移过大会导致 token 一签出来就"过期"(现场表现为登录成功后立刻 401)。
ServerTime int64 `json:"serverTime"`
}
// StationOption 登录页工位选项(2026-11-09 拍板:未配置工位的终端登录页可选实体+虚拟工位)。
type StationOption struct {
StationNo int `json:"stationNo"`
Name string `json:"name"`
StationType string `json:"stationType"` // LINE 实体工位 / OFFLINE 虚拟工位(0 上线位、13 下线位)
}
// StationOptions 登录页可选工位清单:全部启用工位(实体+虚拟),按工位号升序。
// 未配置固定工位的终端在登录前调用(免用户态,X-API-TOKEN 保护)。
func (s *Service) StationOptions(ctx context.Context) ([]StationOption, error) {
sts, err := s.ctx.EntClient.Station.Query().
Where(station.Status("ENABLED")).Order(station.ByStationNo()).All(ctx)
if err != nil {
return nil, err
}
out := make([]StationOption, 0, len(sts))
for _, st := range sts {
out = append(out, StationOption{
StationNo: st.StationNo, Name: st.Name, StationType: st.StationType,
})
}
return out, nil
}
// StationLogin 工位终端登录:校验 用户名 + 工位终端密码 + 工位权限
func (s *Service) StationLogin(ctx context.Context, req StationLoginReq) (StationLoginResp, error) {
var resp StationLoginResp
if req.Username == "" || req.Password == "" {
return resp, errors.New("用户名和密码必填")
}
usr, err := s.ctx.EntClient.User.Query().Where(user.Username(req.Username)).First(ctx)
if err != nil {
return resp, errors.New("用户名或密码错误")
}
if usr.Status != "ENABLED" {
return resp, errors.New("账号已禁用")
}
if !usr.CanLoginWorkstation {
return resp, errors.New("该账号未开通工位终端登录权限")
}
if usr.WorkstationPassword == "" || bcrypt.CompareHashAndPassword([]byte(usr.WorkstationPassword), []byte(req.Password)) != nil {
return resp, errors.New("用户名或密码错误")
}
stations := s.UserStations(ctx, usr.ID)
if len(stations) == 0 {
// 未配置工位权限时兜底授权全部启用的非线下位工位(OFFLINE 类型不参与)
if dbStations, e := s.ctx.EntClient.Station.Query().
Where(station.StationTypeNEQ("OFFLINE"), station.Status("ENABLED")).All(ctx); e == nil {
for _, st := range dbStations {
stations = append(stations, st.StationNo)
}
}
if len(stations) == 0 {
for i := 1; i <= 12; i++ {
stations = append(stations, i)
}
}
}
if req.StationNo != 0 {
// 虚拟工位(线下位 OFFLINE)免工位权限校验(2026-11-11 多会话拍板):虚拟工位不连 PLC、
// 不占产线点位、仅记录作业,权限体系面向实体工位——任何已开通工位终端登录的账号均可登录。
// 存在性仍以 station 表为准(存在且 ENABLED 的 OFFLINE 才放行);实体工位保持原权限校验。
// 2026-11-24:负数前段虚拟工位同走此校验(!=0 而非 >0),不存在的负数工位同样拒绝,杜绝越权登录任意负数。
if st, gerr := s.ctx.EntClient.Station.Query().
Where(station.StationNo(req.StationNo)).First(ctx); gerr == nil && st.Status == "ENABLED" && st.StationType == "OFFLINE" {
// 放行
} else {
allowed := false
for _, no := range stations {
if no == req.StationNo {
allowed = true
break
}
}
if !allowed {
return resp, errors.New("该账号无此工位的操作权限")
}
}
}
roleEntity, _ := s.ctx.EntClient.Role.Get(ctx, usr.RoleId)
claims := tokenx.Claims{UserId: usr.ID, Username: usr.Username, Name: usr.Name, RoleId: usr.RoleId, StationNo: req.StationNo}
if roleEntity != nil {
claims.RoleCode = roleEntity.Code
claims.RoleName = roleEntity.Name
}
access, err := tokenx.Issue(s.ctx.Config.Auth.AccessSecret, time.Duration(s.ctx.Config.Auth.AccessExpire)*time.Second, claims)
if err != nil {
return resp, err
}
// 2026-11-24 修复:工位终端登录此前不写最近登录时间,账号管理「最近登录」恒显示"从未登录"。
// 只补 LastLoginAt,不写 activeToken——工位登录与后台登录的互踢体系互不影响(见 Login 内注释)。
// 写失败不阻塞登录(与 Login 同口径)。
now := time.Now().Unix()
if err := s.ctx.EntClient.User.UpdateOneID(usr.ID).SetLastLoginAt(now).Exec(ctx); err != nil {
// 不阻塞登录,仅记日志
}
resp.AccessToken = access
resp.ExpireAt = time.Now().Add(time.Duration(s.ctx.Config.Auth.AccessExpire) * time.Second).Unix()
resp.ServerTime = now
// 2026-11-24 登录诊断:工位登录全量留痕(密钥指纹/有效期/签发到期/token 指纹)。现场把这条与
// 终端 401 时的 [鉴权诊断] 指纹比对:指纹不同=两端密钥不统一(401 根因);时间对不上=时钟漂移。
tp := access
if len(tp) > 24 {
tp = tp[:24]
}
logx.WithContext(ctx).Infof("[工位登录诊断] 登录成功 user=%s(id=%d) 工位=%d 密钥指纹=%s 有效期=%ds 签发=%s 到期unix=%d token前24=%s",
req.Username, usr.ID, req.StationNo, tokenx.Fingerprint(s.ctx.Config.Auth.AccessSecret),
s.ctx.Config.Auth.AccessExpire, time.Now().Format("2006-01-02 15:04:05"), resp.ExpireAt, tp)
resp.User = UserInfoResp{UserId: usr.ID, Username: usr.Username, Name: usr.Name, RoleId: usr.RoleId}
if roleEntity != nil {
resp.User.RoleCode = roleEntity.Code
resp.User.RoleName = roleEntity.Name
}
resp.Stations = stations
resp.StationNo = req.StationNo
return resp, nil
}
// StationRefreshTokenResp 工位终端滑动续签响应
type StationRefreshTokenResp struct {
AccessToken string `json:"accessToken"`
ExpireAt int64 `json:"expireAt"`
}
// StationRefreshToken 工位终端滑动续签:校验当前登录态 JWT 有效后,原样重签新 JWT(延长有效期)。
// 终端任何人工触屏经前端 30 秒节流后调用,作业中令牌不再因固定有效期过期而被登出。
// 工位终端与 MES 同密钥,claims(含 StationNo)原样保留。
func (s *Service) StationRefreshToken(tokenStr string) (StationRefreshTokenResp, error) {
var resp StationRefreshTokenResp
claims, err := tokenx.Parse(s.ctx.Config.Auth.AccessSecret, tokenStr)
if err != nil || claims == nil {
return resp, errors.New("登录凭证无效或已过期,请重新登录")
}
expire := s.sessionExpire()
access, err := tokenx.Issue(s.ctx.Config.Auth.AccessSecret, time.Duration(expire)*time.Second, *claims)
if err != nil {
return resp, err
}
resp.AccessToken = access
resp.ExpireAt = time.Now().Add(time.Duration(expire) * time.Second).Unix()
return resp, nil
}
// StationChangePassword 工位终端修改自己的工位终端密码
func (s *Service) StationChangePassword(ctx context.Context, userId int, oldPwd, newPwd string) error {
if userId <= 0 {
return errors.New("未登录")
}
if oldPwd == "" || newPwd == "" {
return errors.New("请输入原密码与新密码")
}
if err := checkPasswordStrong(newPwd); err != nil {
return err
}
usr, err := s.ctx.EntClient.User.Get(ctx, userId)
if err != nil {
return errors.New("用户不存在")
}
if !usr.CanLoginWorkstation {
return errors.New("该账号未开通工位终端登录权限")
}
if bcrypt.CompareHashAndPassword([]byte(usr.WorkstationPassword), []byte(oldPwd)) != nil {
return errors.New("原工位终端密码不正确")
}
// 2026-11-23 吞错修复:此前 hash,_ 吞掉生成错误 → 把空密码写库,账号从此密码校验恒过(安全洞)
hash, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
if err != nil {
return errors.New("密码加密失败:" + err.Error())
}
return s.ctx.EntClient.User.UpdateOneID(userId).SetWorkstationPassword(string(hash)).Exec(ctx)
}
// ------ 用户 / 角色 / 权限 管理 ------
type UserReq struct {
Id int `json:"id"`
Username string `json:"username"`
Password string `json:"password"`
Name string `json:"name"`
RoleId int `json:"roleId"`
Status string `json:"status"`
CanLoginWorkstation bool `json:"canLoginWorkstation"`
WorkstationPassword string `json:"workstationPassword"`
Stations []int `json:"stations"` // 允许操作的工位号列表
}
// checkPasswordStrong 校验密码:长度>=6 且不能是纯数字
func checkPasswordStrong(pwd string) error {
if len(pwd) < 6 {
return errors.New("密码长度至少 6 位")
}
allDigit := true
for _, r := range pwd {
if r < '0' || r > '9' {
allDigit = false
break
}
}
if allDigit {
return errors.New("密码不能是纯数字")
}
return nil
}
func (s *Service) CreateUser(ctx context.Context, req UserReq) error {
if err := checkPasswordStrong(req.Password); err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
status := req.Status
if status == "" {
status = "ENABLED"
}
create := s.ctx.EntClient.User.Create().
SetUsername(req.Username).
SetPassword(string(hash)).
SetName(req.Name).
SetRoleId(req.RoleId).
SetStatus(status).
SetCanLoginWorkstation(req.CanLoginWorkstation)
if req.CanLoginWorkstation {
wsPwd := req.WorkstationPassword
if wsPwd == "" {
wsPwd = req.Password // 默认复用登录密码
}
if err := checkPasswordStrong(wsPwd); err != nil {
return errors.New("工位终端密码" + err.Error())
}
wsHash, err := bcrypt.GenerateFromPassword([]byte(wsPwd), bcrypt.DefaultCost)
if err != nil {
return err
}
create.SetWorkstationPassword(string(wsHash))
}
usr, err := create.Save(ctx)
if err != nil {
return err
}
return s.replaceUserStations(ctx, usr.ID, req.Stations)
}
func (s *Service) UpdateUser(ctx context.Context, req UserReq) error {
// 仅内置管理员账号(username=admin)不允许通过管理接口修改;其余账号(含 SUPER_ADMIN 角色的用户)均可修改。
// 2026-09-28 修正:原按角色码 SUPER_ADMIN 锁定的规则过宽,导致普通新建账号被误锁、无法编辑/删除/改状态。
if usr, e := s.ctx.EntClient.User.Get(ctx, req.Id); e == nil {
if usr.Username == "admin" {
return errors.New("系统内置管理员账号不允许修改")
}
}
u := s.ctx.EntClient.User.UpdateOneID(req.Id).SetRoleId(req.RoleId).SetName(req.Name).
SetCanLoginWorkstation(req.CanLoginWorkstation)
if req.Password != "" {
if err := checkPasswordStrong(req.Password); err != nil {
return err
}
// 2026-11-23 吞错修复:此前 hash,_ 吞错会把空密码写库(安全洞)
hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
if err != nil {
return errors.New("密码加密失败:" + err.Error())
}
u.SetPassword(string(hash))
}
if req.CanLoginWorkstation {
if req.WorkstationPassword != "" {
if err := checkPasswordStrong(req.WorkstationPassword); err != nil {
return errors.New("工位终端密码" + err.Error())
}
wsHash, err := bcrypt.GenerateFromPassword([]byte(req.WorkstationPassword), bcrypt.DefaultCost)
if err != nil {
return errors.New("工位终端密码加密失败:" + err.Error())
}
u.SetWorkstationPassword(string(wsHash))
}
} else {
u.SetWorkstationPassword("")
}
if req.Status != "" {
u.SetStatus(req.Status)
}
if err := u.Exec(ctx); err != nil {
return err
}
return s.replaceUserStations(ctx, req.Id, req.Stations)
}
// replaceUserStations 全量替换用户-工位关联
func (s *Service) replaceUserStations(ctx context.Context, userId int, stations []int) error {
if _, err := s.ctx.EntClient.UserStation.Delete().Where(userstation.UserId(userId)).Exec(ctx); err != nil {
return err
}
for _, no := range stations {
if no <= 0 {
continue
}
if err := s.ctx.EntClient.UserStation.Create().
SetUserId(userId).SetStationNo(no).Exec(ctx); err != nil {
return err
}
}
return nil
}
// UserStations 查询用户绑定的工位号
func (s *Service) UserStations(ctx context.Context, userId int) []int {
rows, _ := s.ctx.EntClient.UserStation.Query().
Where(userstation.UserId(userId)).All(ctx)
out := make([]int, 0, len(rows))
for _, r := range rows {
out = append(out, r.StationNo)
}
return out
}
func (s *Service) DeleteUser(ctx context.Context, id int) error {
usr, err := s.ctx.EntClient.User.Get(ctx, id)
if err != nil {
return errors.New("用户不存在")
}
// 仅内置管理员账号(username=admin)不允许删除;其余账号(含 SUPER_ADMIN 角色的用户)均可删除。
// 2026-09-28 修正:原按角色码 SUPER_ADMIN 锁定的规则过宽,导致普通新建账号被误锁、无法删除。
if usr.Username == "admin" {
return errors.New("系统内置管理员账号不允许删除")
}
// 先清工位绑定,避免 user_station 残留孤儿行(引用已删用户 id)
if _, err := s.ctx.EntClient.UserStation.Delete().Where(userstation.UserId(id)).Exec(ctx); err != nil {
return err
}
return s.ctx.EntClient.User.DeleteOneID(id).Exec(ctx)
}
// UserVO 用户列表返回体(含工位终端属性与允许操作工位)
type UserVO struct {
Id int `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
RoleId int `json:"roleId"`
Status string `json:"status"`
CanLoginWorkstation bool `json:"canLoginWorkstation"`
Stations []int `json:"stations"` // 允许登录/操作的工位号(空=全部工位)
LastLoginAt *int64 `json:"lastLoginAt"` // 最近登录时间(unix秒),null=从未登录
CreatedAt *time.Time `json:"createdAt"` // 创建时间
UpdatedAt *time.Time `json:"updatedAt"` // 更新时间
}
// ListUsers 账号列表:page>0 时按 Count+Offset/Limit 真分页,否则保持旧的全量返回。
func (s *Service) ListUsers(ctx context.Context, page, pageSize int) ([]UserVO, int, error) {
q := s.ctx.EntClient.User.Query().Order(ent.Desc(user.FieldCreatedAt))
total, err := q.Count(ctx)
if err != nil {
return nil, 0, err
}
if page > 0 {
if pageSize <= 0 {
pageSize = 20
}
q = q.Offset((page - 1) * pageSize).Limit(pageSize)
}
usrs, err := q.All(ctx)
if err != nil {
return nil, 0, err
}
out := make([]UserVO, 0, len(usrs))
for _, u := range usrs {
out = append(out, UserVO{
Id: u.ID,
Username: u.Username,
Name: u.Name,
RoleId: u.RoleId,
Status: u.Status,
CanLoginWorkstation: u.CanLoginWorkstation,
Stations: s.UserStations(ctx, u.ID),
LastLoginAt: u.LastLoginAt,
CreatedAt: &u.CreatedAt,
UpdatedAt: u.UpdatedAt,
})
}
return out, total, nil
}
type RoleReq struct {
Id int `json:"id"`
Name string `json:"name"`
Code string `json:"code"`
Remark string `json:"remark"`
PermissionCodes []string `json:"permissionCodes"`
}
func (s *Service) CreateRole(ctx context.Context, req RoleReq) error {
return s.ctx.EntClient.Role.Create().
SetName(req.Name).SetCode(req.Code).SetRemark(req.Remark).
SetPermissionCodes(req.PermissionCodes).Exec(ctx)
}
func (s *Service) UpdateRole(ctx context.Context, req RoleReq) error {
// 内置管理员角色(SUPER_ADMIN)不允许修改其权限(admin 拥有所有权限,且不可被缩减)
rl, err := s.ctx.EntClient.Role.Get(ctx, req.Id)
if err != nil {
return errors.New("角色不存在")
}
if rl.Code == "SUPER_ADMIN" {
return errors.New("内置管理员角色不允许修改其权限")
}
// 角色编码创建后不可修改(对齐 WMS 语义;内置角色 code 变更会破坏权限体系)
if req.Code != "" && req.Code != rl.Code {
return errors.New("角色编码创建后不可修改")
}
return s.ctx.EntClient.Role.UpdateOneID(req.Id).
SetName(req.Name).SetCode(rl.Code).SetRemark(req.Remark).
SetPermissionCodes(req.PermissionCodes).Exec(ctx)
}
func (s *Service) DeleteRole(ctx context.Context, id int) error {
// 保护:不可删除内置角色(超级管理员/生产操作员/质检员)
r, err := s.ctx.EntClient.Role.Get(ctx, id)
if err != nil {
return errors.New("角色不存在")
}
if r.Code == "SUPER_ADMIN" || r.Code == "OPERATOR" || r.Code == "INSPECTOR" {
return errors.New("内置角色不允许删除")
}
// 保护:仍有关联用户的角色不可删除(避免产生无主用户/失去全部管理员)
cnt, err := s.ctx.EntClient.User.Query().
Where(user.RoleId(id)).Count(ctx)
if err == nil && cnt > 0 {
return errors.New("该角色下仍有用户,请先移除相关用户")
}
return s.ctx.EntClient.Role.DeleteOneID(id).Exec(ctx)
}
// ListRoles 角色列表:page>0 时按 Count+Offset/Limit 真分页,否则保持旧的全量返回。
func (s *Service) ListRoles(ctx context.Context, keyword string, page, pageSize int) ([]*ent.Role, int, error) {
q := s.ctx.EntClient.Role.Query().Order(ent.Asc(role.FieldID))
if keyword != "" {
kw := keyword
q = q.Where(role.Or(role.NameContainsFold(kw), role.CodeContainsFold(kw)))
}
total, err := q.Count(ctx)
if err != nil {
return nil, 0, err
}
if page > 0 {
if pageSize <= 0 {
pageSize = 20
}
q = q.Offset((page - 1) * pageSize).Limit(pageSize)
}
list, err := q.All(ctx)
if err != nil {
return nil, 0, err
}
return list, total, nil
}
type PermissionReq struct {
Id int `json:"id"`
Code string `json:"code"`
Name string `json:"name"`
Type string `json:"type"`
Path string `json:"path"`
Icon string `json:"icon"`
Sort int `json:"sort"`
Remark string `json:"remark"`
}
func (s *Service) CreatePermission(ctx context.Context, req PermissionReq) error {
return s.ctx.EntClient.Permission.Create().
SetCode(req.Code).SetName(req.Name).SetType(req.Type).
SetPath(req.Path).SetIcon(req.Icon).SetSort(req.Sort).SetRemark(req.Remark).Exec(ctx)
}
func (s *Service) UpdatePermission(ctx context.Context, req PermissionReq) error {
return s.ctx.EntClient.Permission.UpdateOneID(req.Id).
SetCode(req.Code).SetName(req.Name).SetType(req.Type).
SetPath(req.Path).SetIcon(req.Icon).SetSort(req.Sort).SetRemark(req.Remark).Exec(ctx)
}
func (s *Service) DeletePermission(ctx context.Context, id int) error {
return s.ctx.EntClient.Permission.DeleteOneID(id).Exec(ctx)
}
func (s *Service) ListPermissions(ctx context.Context) ([]*ent.Permission, error) {
return s.ctx.EntClient.Permission.Query().Order(ent.Asc(permission.FieldSort), ent.Asc(permission.FieldID)).All(ctx)
}