- MES 新增实体:混产模板、产品BOM、产品工艺物料、试制记录(schema + ent 生成码 + logic/handler/前端页) - WMS 实体增强:检验记录、库存、半成品重构;新增序列号库存与短缺代报 - AGV 与产能:AGV 手动点位与链路、物料守卫、短缺预测、原因字典 - 前端通用能力:新增下一步引导组件 NextStepBar,统一帮助文档/布局/请求拦截与操作列 - 工位终端:界面与各 handler 调整(api/store/绑定/PLC/拧紧/上报等) - 配置与文档:更新 mes-api.yaml、WMS README 及案例/产线API/问题记录/项目说明/流程说明
577 lines
21 KiB
Go
577 lines
21 KiB
Go
package handler
|
||
|
||
// 附件生命周期(2026-10-28 重构,与 WMS 对称):
|
||
// - 附件中心转纯查阅;删除/恢复/彻底清除唯一入口 = 数据归档页「磁盘空间回收」(sys.attachment:manage)。
|
||
// - 删除前提示清楚(delete-precheck):保护期、禁删保护、引用校验、备份覆盖情况,全部透明列出。
|
||
// - 两道闸:① 时间保护期(仅允许删除 N 天前数据,sys_config: archive.protect.days,默认 180);
|
||
// ② 确认弹窗完整提示 + 实名(姓名/手机号)留痕。不建补救层、不承诺备份介质可读。
|
||
// - 引用校验器:bizType+bizId 反查业务表;引用=0 视为孤儿,>0 拒删并列出引用方;
|
||
// 未注册业务类型按"有引用"处理(fail-safe)。
|
||
// - 业务面板「移除」:上传人本人撤回误传附件,禁删保护生效,不受保护期约束。
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"net/http"
|
||
"os"
|
||
"regexp"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"bj_power_mes/common/httpx"
|
||
"bj_power_mes/ent"
|
||
"bj_power_mes/ent/attachment"
|
||
"bj_power_mes/ent/backuprecord"
|
||
"bj_power_mes/ent/inspectionrecord"
|
||
"bj_power_mes/ent/material"
|
||
"bj_power_mes/ent/processflow"
|
||
"bj_power_mes/ent/semiflow"
|
||
"bj_power_mes/ent/workorder"
|
||
"bj_power_mes/internal/logic"
|
||
"bj_power_mes/internal/svc"
|
||
)
|
||
|
||
// ackPhoneRe 实名留痕手机号校验。
|
||
var ackPhoneRe = regexp.MustCompile(`^1\d{10}$`)
|
||
|
||
func checkAckNamePhone(name, phone string) error {
|
||
if strings.TrimSpace(name) == "" {
|
||
return fmt.Errorf("须填写确认人姓名(警示留痕)")
|
||
}
|
||
if !ackPhoneRe.MatchString(strings.TrimSpace(phone)) {
|
||
return fmt.Errorf("须填写有效的 11 位手机号(警示留痕)")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// attachmentProtectCheck 保护期校验:createdAt 须早于保护期。返回非空即拦截原因。
|
||
func attachmentProtectCheck(svcCtx *svc.ServiceContext, r *http.Request, createdAt time.Time) string {
|
||
days := logic.New(svcCtx).CfgInt(r.Context(), logic.CfgArchiveProtectDays, 180)
|
||
if days <= 0 {
|
||
return ""
|
||
}
|
||
cutoff := time.Now().AddDate(0, 0, -days)
|
||
if createdAt.After(cutoff) {
|
||
return fmt.Sprintf("该数据在保护期内(仅允许删除 %d 天前的数据,即 %s 之前上传的)",
|
||
days, cutoff.Format("2006-01-02"))
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// attachmentFileTypeProtect 禁删保护(关键业务附件):返回非空即拦截原因。
|
||
func attachmentFileTypeProtect(svcCtx *svc.ServiceContext, rec *ent.Attachment) string {
|
||
switch rec.FileType {
|
||
case FileTypeProcessPDF, FileTypeProcessCard:
|
||
return "工艺流程 / 流程卡为关键工艺文件,禁止删除"
|
||
case FileTypeInspectionPhoto, FileTypeInspectionPDF:
|
||
years := svcCtx.Config.Upload.LocalRetentionYears
|
||
if years <= 0 {
|
||
years = 1
|
||
}
|
||
cutYear := time.Now().Year() - years
|
||
if rec.CreatedAt.Year() >= cutYear {
|
||
return fmt.Sprintf("检验记录在质量追溯保留期(%d 年)内,禁止删除", years)
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func refResult(err error, n int, label string) (int, []string) {
|
||
if err != nil {
|
||
return 1, []string{"引用校验查询失败:" + err.Error()}
|
||
}
|
||
if n > 0 {
|
||
return n, []string{label}
|
||
}
|
||
return 0, nil
|
||
}
|
||
|
||
// attachmentRefs 引用校验器:返回(引用数, 引用方描述列表)。
|
||
// 未注册的业务类型(quality/inbound/outbound 等 MES 无对应单据表)一律按有引用处理(fail-safe)。
|
||
func attachmentRefs(svcCtx *svc.ServiceContext, bizType, bizId string) (int, []string) {
|
||
bizId = strings.TrimSpace(bizId)
|
||
if bizId == "" {
|
||
return 0, nil
|
||
}
|
||
c := svcCtx.EntClient
|
||
ctx := context.Background()
|
||
switch bizType {
|
||
case "work_order":
|
||
n, err := c.WorkOrder.Query().Where(workorder.WorkOrderNoEQ(bizId)).Count(ctx)
|
||
return refResult(err, n, fmt.Sprintf("工单 %s", bizId))
|
||
case "material":
|
||
n, err := c.Material.Query().Where(material.CodeEQ(bizId)).Count(ctx)
|
||
return refResult(err, n, fmt.Sprintf("物料 %s", bizId))
|
||
case "process_flow":
|
||
id, perr := strconv.Atoi(bizId)
|
||
if perr != nil {
|
||
return 1, []string{"工艺流程 ID 非法,按有引用处理"}
|
||
}
|
||
n, err := c.ProcessFlow.Query().Where(processflow.IDEQ(id)).Count(ctx)
|
||
return refResult(err, n, fmt.Sprintf("工艺流程 #%s", bizId))
|
||
case "inspection":
|
||
id, perr := strconv.Atoi(bizId)
|
||
if perr != nil {
|
||
return 1, []string{"检验记录 ID 非法,按有引用处理"}
|
||
}
|
||
n, err := c.InspectionRecord.Query().Where(inspectionrecord.IDEQ(id)).Count(ctx)
|
||
return refResult(err, n, fmt.Sprintf("检验记录 #%s", bizId))
|
||
case "semi":
|
||
n, err := c.SemiFlow.Query().Where(semiflow.SnEQ(bizId)).Count(ctx)
|
||
return refResult(err, n, fmt.Sprintf("在制品 %s", bizId))
|
||
case "attachment":
|
||
// 系统级附件(说明书等):无业务单据,视为无引用,由管理员在孤儿扫描中自行判断清理
|
||
return 0, nil
|
||
default:
|
||
return 1, []string{fmt.Sprintf("业务类型 %s 未注册引用校验,按有引用处理", bizType)}
|
||
}
|
||
}
|
||
|
||
// attachmentBackupInfo 透明信息:上传时间是否落在某次成功备份的时间窗内(不承诺介质可读)。
|
||
func attachmentBackupInfo(svcCtx *svc.ServiceContext, createdAt time.Time) string {
|
||
recs, err := svcCtx.EntClient.BackupRecord.Query().
|
||
Where(backuprecord.StatusEQ("success"),
|
||
backuprecord.RangeStartLTE(createdAt.Unix()), backuprecord.RangeEndGTE(createdAt.Unix())).
|
||
All(context.Background())
|
||
if err != nil {
|
||
return "备份覆盖情况查询失败"
|
||
}
|
||
if len(recs) == 0 {
|
||
return "无备份记录覆盖该文件的上传时间"
|
||
}
|
||
parts := make([]string, 0, len(recs))
|
||
for _, r := range recs {
|
||
parts = append(parts, fmt.Sprintf("#%d(%s ~ %s)", r.ID,
|
||
time.Unix(r.RangeStart, 0).Format("2006-01-02"), time.Unix(r.RangeEnd, 0).Format("2006-01-02")))
|
||
}
|
||
return "该文件上传时间在备份记录覆盖范围内:" + strings.Join(parts, "、")
|
||
}
|
||
|
||
// deletePrecheckVO 删除前提示清楚所需的全部信息。
|
||
type deletePrecheckVO struct {
|
||
ID int64 `json:"id"`
|
||
FileName string `json:"fileName"`
|
||
FileSize int64 `json:"fileSize"`
|
||
CreatedAt int64 `json:"createdAt"`
|
||
BizType string `json:"bizType"`
|
||
BizID string `json:"bizId"`
|
||
ProtectDays int `json:"protectDays"`
|
||
ProtectBlocked string `json:"protectBlocked"`
|
||
RefCount int `json:"refCount"`
|
||
Refs []string `json:"refs"`
|
||
BackupInfo string `json:"backupInfo"`
|
||
}
|
||
|
||
// AttachmentDeletePrecheckHandler POST /attachment/delete-precheck {id}
|
||
func AttachmentDeletePrecheckHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Id int `json:"id"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 {
|
||
httpx.BadRequest(w, "参数错误:id 必填")
|
||
return
|
||
}
|
||
rec, err := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
|
||
if err != nil {
|
||
httpx.Fail(w, 3316, "附件不存在")
|
||
return
|
||
}
|
||
refCount, refs := attachmentRefs(svcCtx, rec.BizType, rec.BizId)
|
||
protectDays := logic.New(svcCtx).CfgInt(r.Context(), logic.CfgArchiveProtectDays, 180)
|
||
httpx.Ok(w, deletePrecheckVO{
|
||
ID: int64(rec.ID), FileName: rec.FileName, FileSize: int64(rec.FileSize),
|
||
CreatedAt: rec.CreatedAt.Unix(), BizType: rec.BizType, BizID: rec.BizId,
|
||
ProtectDays: protectDays,
|
||
ProtectBlocked: attachmentProtectCheck(svcCtx, r, rec.CreatedAt) + attachmentFileTypeProtect(svcCtx, rec),
|
||
RefCount: refCount, Refs: refs,
|
||
BackupInfo: attachmentBackupInfo(svcCtx, rec.CreatedAt),
|
||
})
|
||
}
|
||
}
|
||
|
||
// AttachmentDeleteHandler 重构:逻辑删除(数据归档页入口)。
|
||
// POST /attachment/delete body: { id, reason, ackName, ackPhone }
|
||
func AttachmentDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Id int `json:"id"`
|
||
Reason string `json:"reason"`
|
||
AckName string `json:"ackName"`
|
||
AckPhone string `json:"ackPhone"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 {
|
||
httpx.BadRequest(w, "参数错误:id 必填")
|
||
return
|
||
}
|
||
rec, gerr := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
|
||
if gerr != nil {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
if rec.Deleted {
|
||
httpx.Fail(w, 3313, "该附件已是删除状态")
|
||
return
|
||
}
|
||
if blocked := attachmentProtectCheck(svcCtx, r, rec.CreatedAt) + attachmentFileTypeProtect(svcCtx, rec); blocked != "" {
|
||
httpx.Fail(w, 3315, blocked)
|
||
return
|
||
}
|
||
refCount, refs := attachmentRefs(svcCtx, rec.BizType, rec.BizId)
|
||
if refCount > 0 {
|
||
httpx.Fail(w, 3315, "该附件仍被业务数据引用,禁止删除:"+strings.Join(refs, "、"))
|
||
return
|
||
}
|
||
if err := checkAckNamePhone(req.AckName, req.AckPhone); err != nil {
|
||
httpx.Fail(w, 3313, err.Error())
|
||
return
|
||
}
|
||
user := operator(r, "")
|
||
if _, err := svcCtx.EntClient.Attachment.UpdateOneID(req.Id).
|
||
SetDeleted(true).SetDeletedAt(time.Now().Unix()).
|
||
SetDeletedBy(user).SetDeletedReason(strings.TrimSpace(req.Reason)).
|
||
Save(r.Context()); err != nil {
|
||
httpx.Fail(w, 3313, "删除附件失败:"+err.Error())
|
||
return
|
||
}
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.delete", "", user, "attachment", rec.BizId,
|
||
fmt.Sprintf("删除附件 %s(%.2f MB;确认人:%s %s;说明:%s)",
|
||
rec.FileName, float64(rec.FileSize)/1024/1024,
|
||
strings.TrimSpace(req.AckName), strings.TrimSpace(req.AckPhone), ornull(req.Reason)), nil)
|
||
httpx.OkMessage(w, "删除成功", nil)
|
||
}
|
||
}
|
||
|
||
// AttachmentRestoreHandler POST /attachment/restore {id} 恢复逻辑删除(未彻底清除前可反悔)。
|
||
func AttachmentRestoreHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Id int `json:"id"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 {
|
||
httpx.BadRequest(w, "参数错误:id 必填")
|
||
return
|
||
}
|
||
rec, err := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
|
||
if err != nil {
|
||
httpx.Fail(w, 3316, "附件不存在")
|
||
return
|
||
}
|
||
if !rec.Deleted {
|
||
httpx.Fail(w, 3313, "该附件不是删除状态,无需恢复")
|
||
return
|
||
}
|
||
if rec.PurgedAt != 0 {
|
||
httpx.Fail(w, 3313, "该附件已彻底清除(磁盘文件已删除),无法恢复;如需找回请使用对应备份包")
|
||
return
|
||
}
|
||
if _, err := svcCtx.EntClient.Attachment.UpdateOneID(req.Id).SetDeleted(false).Save(r.Context()); err != nil {
|
||
httpx.Fail(w, 3313, "恢复附件失败:"+err.Error())
|
||
return
|
||
}
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.restore", "", operator(r, ""), "attachment", rec.BizId,
|
||
"恢复附件 "+rec.FileName, nil)
|
||
httpx.OkMessage(w, "恢复成功", nil)
|
||
}
|
||
}
|
||
|
||
// AttachmentPurgeHandler 彻底清除单个已删除附件:物理删除磁盘文件,索引保留(purgedAt/by 留痕)。
|
||
// POST /attachment/purge body: { id, ackName, ackPhone }
|
||
func AttachmentPurgeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Id int `json:"id"`
|
||
AckName string `json:"ackName"`
|
||
AckPhone string `json:"ackPhone"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 {
|
||
httpx.BadRequest(w, "参数错误:id 必填")
|
||
return
|
||
}
|
||
rec, err := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
|
||
if err != nil {
|
||
httpx.Fail(w, 3316, "附件不存在")
|
||
return
|
||
}
|
||
if !rec.Deleted {
|
||
httpx.Fail(w, 3313, "请先删除(逻辑删除)后再彻底清除")
|
||
return
|
||
}
|
||
if rec.PurgedAt != 0 {
|
||
httpx.Fail(w, 3313, "该附件已彻底清除")
|
||
return
|
||
}
|
||
if blocked := attachmentProtectCheck(svcCtx, r, rec.CreatedAt) + attachmentFileTypeProtect(svcCtx, rec); blocked != "" {
|
||
httpx.Fail(w, 3315, blocked)
|
||
return
|
||
}
|
||
if err := checkAckNamePhone(req.AckName, req.AckPhone); err != nil {
|
||
httpx.Fail(w, 3313, err.Error())
|
||
return
|
||
}
|
||
user := operator(r, "")
|
||
removed := false
|
||
if abs, okp := safeAbsPath(svcCtx.Config.Upload.Dir, rec.FilePath); okp {
|
||
if rerr := osRemoveIfExist(abs); rerr == "" {
|
||
removed = true
|
||
}
|
||
}
|
||
if _, uerr := svcCtx.EntClient.Attachment.UpdateOneID(req.Id).
|
||
SetPurgedAt(time.Now().Unix()).SetPurgedBy(user).Save(r.Context()); uerr != nil {
|
||
httpx.Fail(w, 3313, "清除标记失败:"+uerr.Error())
|
||
return
|
||
}
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.purge", "", user, "attachment", rec.BizId,
|
||
fmt.Sprintf("彻底清除附件 %s(%.2f MB,文件已删除%s;确认人:%s %s)",
|
||
rec.FileName, float64(rec.FileSize)/1024/1024,
|
||
map[bool]string{true: "", false: ",文件本已缺失"}[removed],
|
||
strings.TrimSpace(req.AckName), strings.TrimSpace(req.AckPhone)), nil)
|
||
httpx.Ok(w, map[string]any{"id": req.Id, "removed": removed})
|
||
}
|
||
}
|
||
|
||
// AttachmentRemoveHandler 业务面板「移除」:上传人本人撤回误传附件(物理删除文件+记录)。
|
||
// POST /attachment/remove body: { id, reason }
|
||
func AttachmentRemoveHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
Id int `json:"id"`
|
||
Reason string `json:"reason"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil || req.Id <= 0 {
|
||
httpx.BadRequest(w, "参数错误:id 必填")
|
||
return
|
||
}
|
||
rec, err := logic.New(svcCtx).GetAttachment(r.Context(), req.Id)
|
||
if err != nil {
|
||
httpx.Fail(w, 3316, "附件不存在")
|
||
return
|
||
}
|
||
if rec.Deleted {
|
||
httpx.Fail(w, 3313, "该附件已是删除状态")
|
||
return
|
||
}
|
||
user := operator(r, "")
|
||
if rec.Uploader != user {
|
||
httpx.Fail(w, 3315, "仅上传人本人可移除附件;其他情况请管理员在「数据归档」页处理")
|
||
return
|
||
}
|
||
if blocked := attachmentFileTypeProtect(svcCtx, rec); blocked != "" {
|
||
httpx.Fail(w, 3315, blocked)
|
||
return
|
||
}
|
||
if abs, okp := safeAbsPath(svcCtx.Config.Upload.Dir, rec.FilePath); okp {
|
||
_ = osRemoveIfExist(abs)
|
||
}
|
||
if _, derr := svcCtx.EntClient.Attachment.Delete().Where(attachment.ID(rec.ID)).Exec(r.Context()); derr != nil {
|
||
httpx.Fail(w, 3313, "移除附件失败:"+derr.Error())
|
||
return
|
||
}
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.remove", "", user, "attachment", rec.BizId,
|
||
fmt.Sprintf("移除附件 %s(上传人本人撤回,物理删除;说明:%s)", rec.FileName, ornull(req.Reason)), nil)
|
||
httpx.OkMessage(w, "移除成功", nil)
|
||
}
|
||
}
|
||
|
||
// AttachmentOrphanScanHandler GET /attachment/orphans 扫描无引用附件(孤儿)。
|
||
func AttachmentOrphanScanHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
recs, err := svcCtx.EntClient.Attachment.Query().
|
||
Where(attachment.DeletedEQ(false)).Order(ent.Desc(attachment.FieldCreatedAt)).All(r.Context())
|
||
if err != nil {
|
||
httpx.Fail(w, 3312, err.Error())
|
||
return
|
||
}
|
||
type orphanVO struct {
|
||
ID int64 `json:"id"`
|
||
FileName string `json:"fileName"`
|
||
FileSize int64 `json:"fileSize"`
|
||
BizType string `json:"bizType"`
|
||
BizID string `json:"bizId"`
|
||
CreatedAt int64 `json:"createdAt"`
|
||
Reason string `json:"reason"`
|
||
}
|
||
var total int64
|
||
list := make([]orphanVO, 0, 16)
|
||
const capN = 500
|
||
for _, rec := range recs {
|
||
if rec.PurgedAt != 0 {
|
||
continue
|
||
}
|
||
n, refs := attachmentRefs(svcCtx, rec.BizType, rec.BizId)
|
||
if n > 0 {
|
||
continue
|
||
}
|
||
total += int64(rec.FileSize)
|
||
if len(list) < capN {
|
||
reason := "业务单据不存在(可能未保存即取消,或单据已删除)"
|
||
if len(refs) > 0 {
|
||
reason = refs[0]
|
||
}
|
||
list = append(list, orphanVO{
|
||
ID: int64(rec.ID), FileName: rec.FileName, FileSize: int64(rec.FileSize),
|
||
BizType: rec.BizType, BizID: rec.BizId, CreatedAt: rec.CreatedAt.Unix(), Reason: reason,
|
||
})
|
||
}
|
||
}
|
||
httpx.Ok(w, map[string]any{"count": len(list), "truncated": len(recs) > capN, "totalSize": total, "list": list})
|
||
}
|
||
}
|
||
|
||
// AttachmentOrphanPurgeHandler POST /attachment/orphans/purge 批量清除孤儿附件(文件+记录)。
|
||
// body: { ids: [], ackName, ackPhone }(ids 空=全部扫描到的)
|
||
func AttachmentOrphanPurgeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
IDs []int `json:"ids"`
|
||
AckName string `json:"ackName"`
|
||
AckPhone string `json:"ackPhone"`
|
||
}
|
||
if err := httpx.ParseJSON(r, &req); err != nil {
|
||
httpx.BadRequest(w, "请求体解析失败")
|
||
return
|
||
}
|
||
if err := checkAckNamePhone(req.AckName, req.AckPhone); err != nil {
|
||
httpx.Fail(w, 3313, err.Error())
|
||
return
|
||
}
|
||
if len(req.IDs) == 0 {
|
||
recs, err := svcCtx.EntClient.Attachment.Query().Where(attachment.DeletedEQ(false)).All(r.Context())
|
||
if err != nil {
|
||
httpx.Fail(w, 3312, err.Error())
|
||
return
|
||
}
|
||
for _, rec := range recs {
|
||
if rec.PurgedAt != 0 {
|
||
continue
|
||
}
|
||
if n, _ := attachmentRefs(svcCtx, rec.BizType, rec.BizId); n == 0 {
|
||
req.IDs = append(req.IDs, rec.ID)
|
||
}
|
||
}
|
||
}
|
||
user := operator(r, "")
|
||
removed, failed, freed := 0, 0, int64(0)
|
||
for _, id := range req.IDs {
|
||
rec, err := logic.New(svcCtx).GetAttachment(r.Context(), id)
|
||
if err != nil {
|
||
failed++
|
||
continue
|
||
}
|
||
if rec.Deleted || rec.PurgedAt != 0 {
|
||
continue
|
||
}
|
||
if n, _ := attachmentRefs(svcCtx, rec.BizType, rec.BizId); n > 0 {
|
||
failed++ // 执行时引用出现(如单据刚保存),跳过
|
||
continue
|
||
}
|
||
if abs, okp := safeAbsPath(svcCtx.Config.Upload.Dir, rec.FilePath); okp {
|
||
if info, serr := os.Stat(abs); serr == nil {
|
||
freed += info.Size()
|
||
}
|
||
_ = osRemoveIfExist(abs)
|
||
}
|
||
if _, derr := svcCtx.EntClient.Attachment.Delete().Where(attachment.ID(rec.ID)).Exec(r.Context()); derr != nil {
|
||
failed++
|
||
continue
|
||
}
|
||
removed++
|
||
}
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.orphan.purge", "", user, "attachment", "orphan",
|
||
fmt.Sprintf("清除无引用附件:删除%d 释放%.2fMB 失败%d(确认人:%s %s)",
|
||
removed, float64(freed)/1024/1024, failed,
|
||
strings.TrimSpace(req.AckName), strings.TrimSpace(req.AckPhone)), nil)
|
||
httpx.Ok(w, map[string]any{"removed": removed, "failed": failed, "freed": freed})
|
||
}
|
||
}
|
||
|
||
// AttachmentPurgeDeletedHandler POST /attachment/purge-deleted 批量物理清理已逻辑删除的附件
|
||
// (数据归档页「磁盘空间回收」批量入口):dryRun 预检返回将清理数量与释放字节;
|
||
// 执行须实名留痕;保护期/禁删保护的附件跳过(计入 protected);索引保留(purgedAt/by 留痕)。
|
||
func AttachmentPurgeDeletedHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
var req struct {
|
||
DryRun bool `json:"dryRun"`
|
||
AckName string `json:"ackName"`
|
||
AckPhone string `json:"ackPhone"`
|
||
}
|
||
_ = httpx.ParseJSON(r, &req)
|
||
if !req.DryRun {
|
||
if err := checkAckNamePhone(req.AckName, req.AckPhone); err != nil {
|
||
httpx.Fail(w, 3313, err.Error())
|
||
return
|
||
}
|
||
}
|
||
recs, err := svcCtx.EntClient.Attachment.Query().
|
||
Where(attachment.DeletedEQ(true)).All(r.Context())
|
||
if err != nil {
|
||
httpx.Fail(w, 3312, err.Error())
|
||
return
|
||
}
|
||
removed, freed, missing, failed, protected := 0, int64(0), 0, 0, 0
|
||
user := operator(r, "")
|
||
for _, rec := range recs {
|
||
if rec.PurgedAt != 0 {
|
||
missing++ // 已清除过(文件已删),仅计数
|
||
continue
|
||
}
|
||
if blocked := attachmentProtectCheck(svcCtx, r, rec.CreatedAt) + attachmentFileTypeProtect(svcCtx, rec); blocked != "" {
|
||
protected++
|
||
continue
|
||
}
|
||
abs, okp := safeAbsPath(svcCtx.Config.Upload.Dir, rec.FilePath)
|
||
if !okp {
|
||
failed++
|
||
continue
|
||
}
|
||
info, statErr := os.Stat(abs)
|
||
if statErr != nil {
|
||
missing++ // 文件已不存在(已清理或丢失),仅计数
|
||
now := time.Now().Unix()
|
||
_, _ = svcCtx.EntClient.Attachment.UpdateOneID(rec.ID).
|
||
SetPurgedAt(now).SetPurgedBy(user).Save(r.Context())
|
||
continue
|
||
}
|
||
if req.DryRun {
|
||
removed++
|
||
freed += int64(info.Size())
|
||
continue
|
||
}
|
||
if err := os.Remove(abs); err != nil {
|
||
failed++
|
||
continue
|
||
}
|
||
now := time.Now().Unix()
|
||
_, _ = svcCtx.EntClient.Attachment.UpdateOneID(rec.ID).
|
||
SetPurgedAt(now).SetPurgedBy(user).Save(r.Context())
|
||
removed++
|
||
freed += int64(info.Size())
|
||
}
|
||
if !req.DryRun {
|
||
svcCtx.EventLog.Write(r.Context(), "attachment.purge", "", user, "attachment", "purge",
|
||
fmt.Sprintf("批量物理清理已删附件:删除%d 释放%.2fMB 缺失%d 失败%d 保护期跳过%d(确认人:%s %s)",
|
||
removed, float64(freed)/1024/1024, missing, failed, protected,
|
||
strings.TrimSpace(req.AckName), strings.TrimSpace(req.AckPhone)),
|
||
map[string]any{"removed": removed, "freed": freed, "missing": missing, "failed": failed, "protected": protected})
|
||
}
|
||
httpx.Ok(w, map[string]any{"removed": removed, "freed": freed, "missing": missing, "failed": failed,
|
||
"protected": protected, "dryRun": req.DryRun})
|
||
}
|
||
}
|
||
|
||
// osRemoveIfExist 物理删除文件(不存在视为成功)。返回空串=成功。
|
||
func osRemoveIfExist(abs string) string {
|
||
if err := os.Remove(abs); err != nil && !os.IsNotExist(err) {
|
||
return err.Error()
|
||
}
|
||
return ""
|
||
}
|
||
|
||
func ornull(s string) string {
|
||
if strings.TrimSpace(s) == "" {
|
||
return "无"
|
||
}
|
||
return strings.TrimSpace(s)
|
||
}
|