From 4d3c4e2c3a6df490d49c6c90755331801235b30e Mon Sep 17 00:00:00 2001 From: SunYF <123@hard_man.com> Date: Wed, 28 Oct 2026 10:10:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A4=A7=E5=B1=8F=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E7=BA=AF=E6=B5=81=E5=BC=8F=E8=87=AA=E9=80=82=E5=BA=94=E5=B8=83?= =?UTF-8?q?=E5=B1=80=EF=BC=8C=E6=96=B0=E5=A2=9EKPI=E5=B8=A6=E4=B8=8E?= =?UTF-8?q?=E4=BA=A7=E7=BA=BF=E5=8A=A8=E6=80=81=E6=8B=93=E6=89=91=E5=9C=B0?= =?UTF-8?q?=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bj_power_dashboard/src/App.tsx | 133 +- bj_power_dashboard/src/components/EChart.tsx | 23 +- .../src/components/ErrorRetry.tsx | 23 +- .../src/components/KpiStrip.tsx | 68 + .../src/components/ScrollList.tsx | 48 + bj_power_dashboard/src/index.css | 259 ++- bj_power_dashboard/src/mock.ts | 47 + bj_power_dashboard/src/pages/LineModel.css | 100 +- bj_power_dashboard/src/pages/LineModel.tsx | 881 ++++------- .../src/pages/ProductionBoard.tsx | 358 +---- bj_power_dashboard/src/pages/SideBoard.tsx | 131 ++ .../src/pages/WarehouseBoard.tsx | 208 +-- .../src/services/dashboardService.ts | 37 +- bj_power_dashboard/src/types.ts | 50 + bj_power_dashboard/tsconfig.tsbuildinfo | 2 +- ....timestamp-1793096244782-28cd3727204d5.mjs | 31 + bj_power_mes/ent/backuprecord.go | 202 +++ bj_power_mes/ent/backuprecord/backuprecord.go | 144 ++ bj_power_mes/ent/backuprecord/where.go | 669 ++++++++ bj_power_mes/ent/backuprecord_create.go | 415 +++++ bj_power_mes/ent/backuprecord_delete.go | 88 ++ bj_power_mes/ent/backuprecord_query.go | 577 +++++++ bj_power_mes/ent/backuprecord_update.go | 667 ++++++++ bj_power_mes/ent/client.go | 181 ++- bj_power_mes/ent/ent.go | 2 + bj_power_mes/ent/hook/hook.go | 12 + bj_power_mes/ent/migrate/schema.go | 42 + bj_power_mes/ent/mutation.go | 955 +++++++++++ bj_power_mes/ent/predicate/predicate.go | 3 + bj_power_mes/ent/runtime.go | 39 + bj_power_mes/ent/tx.go | 3 + bj_power_mes/etc/bj_power_mes-api.yaml | 1 - bj_power_mes/frontend/src/help.js | 6 +- .../frontend/src/layouts/MainLayout.vue | 43 +- .../frontend/src/pages/Attachment.vue | 42 +- bj_power_mes/frontend/src/pages/DailyPlan.vue | 4 +- .../frontend/src/pages/DataArchive.vue | 375 +++++ .../frontend/src/pages/ProcessCard.vue | 149 +- bj_power_mes/frontend/src/pages/Settings.vue | 20 +- bj_power_mes/frontend/src/pages/Station.vue | 2 +- bj_power_mes/frontend/src/router/index.js | 1 + bj_power_mes/internal/backup/backup.go | 731 +++++++++ bj_power_mes/internal/backup/browse.go | 78 + bj_power_mes/internal/backup/records.go | 178 +++ bj_power_mes/internal/backup/util.go | 131 ++ bj_power_mes/internal/backup/zip.go | 79 + bj_power_mes/internal/config/config.go | 4 +- bj_power_mes/internal/db/db.go | 4 +- bj_power_mes/internal/handler/attachment.go | 87 - bj_power_mes/internal/handler/backup.go | 181 +++ bj_power_mes/internal/handler/perm.go | 5 +- .../internal/handler/production/production.go | 13 + bj_power_mes/internal/handler/routes.go | 14 + .../internal/handler/routes_production.go | 4 +- bj_power_mes/internal/logic/attachment.go | 12 - bj_power_mes/internal/logic/call.go | 2 +- bj_power_mes/internal/logic/dailyplan.go | 2 +- bj_power_mes/internal/logic/dashboard.go | 77 + .../internal/logic/dashboard_front.go | 45 +- .../internal/logic/dashboard_types.go | 34 + bj_power_mes/internal/logic/line.go | 2 +- bj_power_mes/internal/logic/seed.go | 4 +- bj_power_mes/internal/logic/settings.go | 35 + bj_power_mes/internal/plc/mock.go | 14 + bj_power_mes/internal/plc/plc.go | 11 + bj_power_mes/internal/plc/tcp.go | 41 +- bj_power_mes/internal/svc/service_context.go | 3 + bj_power_mes/public/index.html | 4 +- bj_power_mes/schema/backup_record.go | 56 + bj_power_mes/schema/line_point.go | 2 +- bj_power_wms/ent/backuprecord.go | 202 +++ bj_power_wms/ent/backuprecord/backuprecord.go | 142 ++ bj_power_wms/ent/backuprecord/where.go | 669 ++++++++ bj_power_wms/ent/backuprecord_create.go | 1109 +++++++++++++ bj_power_wms/ent/backuprecord_delete.go | 88 ++ bj_power_wms/ent/backuprecord_query.go | 527 ++++++ bj_power_wms/ent/backuprecord_update.go | 651 ++++++++ bj_power_wms/ent/client.go | 312 +++- bj_power_wms/ent/ent.go | 4 + bj_power_wms/ent/hook/hook.go | 24 + bj_power_wms/ent/migrate/schema.go | 60 + bj_power_wms/ent/mutation.go | 1407 +++++++++++++++++ bj_power_wms/ent/predicate/predicate.go | 6 + bj_power_wms/ent/runtime.go | 50 + bj_power_wms/ent/sysconfig.go | 125 ++ bj_power_wms/ent/sysconfig/sysconfig.go | 72 + bj_power_wms/ent/sysconfig/where.go | 289 ++++ bj_power_wms/ent/sysconfig_create.go | 600 +++++++ bj_power_wms/ent/sysconfig_delete.go | 88 ++ bj_power_wms/ent/sysconfig_query.go | 527 ++++++ bj_power_wms/ent/sysconfig_update.go | 341 ++++ bj_power_wms/ent/tx.go | 6 + bj_power_wms/etc/aitest_wms.yaml | 1 - bj_power_wms/etc/bj_power_wms-api.yaml | 1 - bj_power_wms/etc/test-8899.yaml | 1 - bj_power_wms/frontend/package-lock.json | 26 + bj_power_wms/frontend/package.json | 3 +- .../frontend/src/components/AnimNumber.vue | 38 + .../frontend/src/components/VChart.vue | 43 + bj_power_wms/frontend/src/help.js | 7 +- .../frontend/src/layouts/MainLayout.vue | 57 +- .../frontend/src/pages/AttachmentCenter.vue | 103 +- bj_power_wms/frontend/src/pages/BaseData.vue | 26 +- .../frontend/src/pages/DataArchive.vue | 375 +++++ bj_power_wms/frontend/src/pages/Display.vue | 620 +++++++- bj_power_wms/frontend/src/pages/Settings.vue | 112 ++ bj_power_wms/frontend/src/router/index.js | 4 +- bj_power_wms/internal/backup/backup.go | 637 ++++++++ bj_power_wms/internal/backup/browse.go | 76 + bj_power_wms/internal/backup/records.go | 187 +++ bj_power_wms/internal/backup/util.go | 130 ++ bj_power_wms/internal/backup/zip.go | 79 + bj_power_wms/internal/config/config.go | 1 - bj_power_wms/internal/handler/attachment.go | 167 +- bj_power_wms/internal/handler/backup.go | 197 +++ bj_power_wms/internal/handler/internalapi.go | 204 ++- bj_power_wms/internal/handler/rbac_admin.go | 3 + bj_power_wms/internal/handler/routes.go | 42 +- bj_power_wms/internal/handler/settings.go | 231 +++ bj_power_wms/internal/handler/zone.go | 109 +- bj_power_wms/internal/mesclient/client.go | 1 + bj_power_wms/internal/svc/service_context.go | 5 + bj_power_wms/schema/backup_record.go | 49 + bj_power_wms/schema/sys_config.go | 27 + bj_power_wms/web/static/index.html | 4 +- .../frontend/src/api/index.js | 2 +- .../frontend/src/store/station.js | 2 +- .../internal/config/config.go | 2 +- bj_power_workstation/internal/handler/line.go | 4 +- 产线布局说明.md | 65 +- 问题临时.md | 12 +- 131 files changed, 18118 insertions(+), 1728 deletions(-) create mode 100644 bj_power_dashboard/src/components/KpiStrip.tsx create mode 100644 bj_power_dashboard/src/components/ScrollList.tsx create mode 100644 bj_power_dashboard/src/pages/SideBoard.tsx create mode 100644 bj_power_dashboard/vite.config.ts.timestamp-1793096244782-28cd3727204d5.mjs create mode 100644 bj_power_mes/ent/backuprecord.go create mode 100644 bj_power_mes/ent/backuprecord/backuprecord.go create mode 100644 bj_power_mes/ent/backuprecord/where.go create mode 100644 bj_power_mes/ent/backuprecord_create.go create mode 100644 bj_power_mes/ent/backuprecord_delete.go create mode 100644 bj_power_mes/ent/backuprecord_query.go create mode 100644 bj_power_mes/ent/backuprecord_update.go create mode 100644 bj_power_mes/frontend/src/pages/DataArchive.vue create mode 100644 bj_power_mes/internal/backup/backup.go create mode 100644 bj_power_mes/internal/backup/browse.go create mode 100644 bj_power_mes/internal/backup/records.go create mode 100644 bj_power_mes/internal/backup/util.go create mode 100644 bj_power_mes/internal/backup/zip.go create mode 100644 bj_power_mes/internal/handler/backup.go create mode 100644 bj_power_mes/schema/backup_record.go create mode 100644 bj_power_wms/ent/backuprecord.go create mode 100644 bj_power_wms/ent/backuprecord/backuprecord.go create mode 100644 bj_power_wms/ent/backuprecord/where.go create mode 100644 bj_power_wms/ent/backuprecord_create.go create mode 100644 bj_power_wms/ent/backuprecord_delete.go create mode 100644 bj_power_wms/ent/backuprecord_query.go create mode 100644 bj_power_wms/ent/backuprecord_update.go create mode 100644 bj_power_wms/ent/sysconfig.go create mode 100644 bj_power_wms/ent/sysconfig/sysconfig.go create mode 100644 bj_power_wms/ent/sysconfig/where.go create mode 100644 bj_power_wms/ent/sysconfig_create.go create mode 100644 bj_power_wms/ent/sysconfig_delete.go create mode 100644 bj_power_wms/ent/sysconfig_query.go create mode 100644 bj_power_wms/ent/sysconfig_update.go create mode 100644 bj_power_wms/frontend/src/components/AnimNumber.vue create mode 100644 bj_power_wms/frontend/src/components/VChart.vue create mode 100644 bj_power_wms/frontend/src/pages/DataArchive.vue create mode 100644 bj_power_wms/frontend/src/pages/Settings.vue create mode 100644 bj_power_wms/internal/backup/backup.go create mode 100644 bj_power_wms/internal/backup/browse.go create mode 100644 bj_power_wms/internal/backup/records.go create mode 100644 bj_power_wms/internal/backup/util.go create mode 100644 bj_power_wms/internal/backup/zip.go create mode 100644 bj_power_wms/internal/handler/backup.go create mode 100644 bj_power_wms/internal/handler/settings.go create mode 100644 bj_power_wms/schema/backup_record.go create mode 100644 bj_power_wms/schema/sys_config.go diff --git a/bj_power_dashboard/src/App.tsx b/bj_power_dashboard/src/App.tsx index a48d6f5..1c93c4c 100644 --- a/bj_power_dashboard/src/App.tsx +++ b/bj_power_dashboard/src/App.tsx @@ -1,69 +1,104 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { Layout, Tag, Spin } from '@douyinfe/semi-ui'; import { useDashboardData } from './hooks/useDashboardData'; import { useSpeechAlarm } from './hooks/useSpeechAlarm'; +import { KpiStrip } from './components/KpiStrip'; import { ProductionBoard } from './pages/ProductionBoard'; -import { WarehouseBoard } from './pages/WarehouseBoard'; import { LineModel } from './pages/LineModel'; +import { SideBoard } from './pages/SideBoard'; +import { WarehouseBoard } from './pages/WarehouseBoard'; import { ErrorRetry } from './components/ErrorRetry'; import { MaterialQuery } from './components/MaterialQuery'; +import { fetchBoardConfig } from './services/dashboardService'; +/** + * 大屏骨架(100 寸 · 无鼠标 · 纯流式自适应,禁写死尺寸): + * 顶栏 → KPI 带(全宽七格)→ 产线地图主视觉(全宽,接近真实横长比)→ 底部三块细节。 + */ export function App() { const { data: dashboard, mode, error, retry } = useDashboardData(); const loading = !dashboard && !error; + + // 门口看板运行配置(MES 基础设置页维护,保存即生效;每 60 秒跟随): + // dashboard.board.title 标题文字(空=默认「总装产线实时看板」)、dashboard.board.voice 语音播报开关 + const [boardTitle, setBoardTitle] = useState(''); + const [voiceOn, setVoiceOn] = useState(true); + useEffect(() => { + let alive = true; + const apply = () => + fetchBoardConfig() + .then((c) => { + if (!alive) return; + setBoardTitle(c.title); + setVoiceOn(c.voiceOn); + document.title = c.title || '生产看板'; + }) + .catch(() => { + /* MES 未起时沿用当前配置 */ + }); + apply(); + const t = window.setInterval(apply, 60_000); + return () => { + alive = false; + window.clearInterval(t); + }; + }, []); + + // D2 语音播报:监听报警事件(无播音设备静默降级;MES 基础设置可关) + useSpeechAlarm(voiceOn ? dashboard?.alarms ?? [] : []); + const [now, setNow] = useState(() => new Date()); - - // D2 语音播报:监听报警事件(无播音设备静默降级) - useSpeechAlarm(dashboard?.alarms ?? []); - - // 时钟 - setTimeout(() => setNow(new Date()), 1000); + useEffect(() => { + const t = window.setInterval(() => setNow(new Date()), 1000); + return () => window.clearInterval(t); + }, []); return ( - - -
- {mode === 'sse' && 实时推送} - {mode === 'polling' && 轮询刷新} - {mode === 'demo' && 演示数据} - {mode === 'init' && 连接中} - - {now.toLocaleTimeString('zh-CN')} - {now.toLocaleDateString('zh-CN', { weekday: 'long' })} -
-
+
+
+ + +
{boardTitle || '总装产线实时看板'}
+
+ {mode === 'sse' && 实时推送} + {mode === 'polling' && 轮询刷新} + {mode === 'demo' && 演示数据} + {mode === 'init' && 连接中} + + {now.toLocaleTimeString('zh-CN')} + {now.toLocaleDateString('zh-CN', { weekday: 'long' })} +
+
- - {loading ? ( -
- -
- ) : ( - - {dashboard ? ( -
-
-
- -
-
-
-
- -
-
-
- -
+ + {loading ? ( +
+
) : ( -
- 等待产线数据… -
+ + {dashboard ? ( + <> + +
+
+ +
+
+ + + +
+
+ + ) : ( +
等待产线数据…
+ )} +
)} - - )} -
- + + +
+
); } diff --git a/bj_power_dashboard/src/components/EChart.tsx b/bj_power_dashboard/src/components/EChart.tsx index 99a843d..e0dc3c1 100644 --- a/bj_power_dashboard/src/components/EChart.tsx +++ b/bj_power_dashboard/src/components/EChart.tsx @@ -7,22 +7,35 @@ interface EChartProps { height?: number | string; } -/** 简易 ECharts 容器,option 变化时自动更新,卸载时销毁实例。 */ +/** + * 简易 ECharts 容器: + * - option 变化只 setOption,不重建实例; + * - 用 ResizeObserver 跟随容器尺寸(大屏流式布局下容器随视口变化,不能只靠 window.resize); + * - 卸载时销毁实例。 + */ export function EChart({ option, height = 260 }: EChartProps) { const ref = useRef(null); + const chartRef = useRef(null); useEffect(() => { const el = ref.current; if (!el) return; const chart = echarts.init(el); + chartRef.current = chart; chart.setOption(option); - const onResize = () => chart.resize(); - window.addEventListener('resize', onResize); + + const ro = new ResizeObserver(() => chart.resize()); + ro.observe(el); return () => { - window.removeEventListener('resize', onResize); + ro.disconnect(); chart.dispose(); + chartRef.current = null; }; + }, []); + + useEffect(() => { + chartRef.current?.setOption(option); }, [option]); return
; -} \ No newline at end of file +} diff --git a/bj_power_dashboard/src/components/ErrorRetry.tsx b/bj_power_dashboard/src/components/ErrorRetry.tsx index f45dda3..88601d3 100644 --- a/bj_power_dashboard/src/components/ErrorRetry.tsx +++ b/bj_power_dashboard/src/components/ErrorRetry.tsx @@ -27,28 +27,7 @@ export function ErrorRetry({ error, mode, loading, onRetry, children }: ErrorRet ); } return ( -
- {error && mode === 'demo' && ( -
- 演示数据 · 真实业务数据到位后自动切换 -
- )} +
{children}
); diff --git a/bj_power_dashboard/src/components/KpiStrip.tsx b/bj_power_dashboard/src/components/KpiStrip.tsx new file mode 100644 index 0000000..5f0f4f7 --- /dev/null +++ b/bj_power_dashboard/src/components/KpiStrip.tsx @@ -0,0 +1,68 @@ +import type { DashboardData } from '../types'; + +/** 顶部 KPI 带:七格全宽,指标优先、数字最大(100 寸屏 3 米外可读) */ +export function KpiStrip({ data }: { data: DashboardData }) { + const p = data.production; + const w = data.warehouse; + + const output = p.outputToday ?? 0; + const target = p.targetToday ?? 0; + const pct = target > 0 ? Math.min(100, Math.round((output / target) * 100)) : null; + + const locPct = w.locationTotal > 0 ? Math.round((w.locationUsed / w.locationTotal) * 100) : null; + + return ( +
+ 0 ? `目标 ${target} 件` : '目标未下达'} /> + + + 0 ? p.cycleTime.toFixed(1) : '—'} + unit={p.cycleTime > 0 ? '分钟' : ''} + sub="相邻完工间隔均值" + color="#fbbf24" + /> + + 0 ? `${p.deviceOnline}/${p.deviceTotal}` : '—'} + unit="" + sub="扫码枪 + 拧紧枪" + color="#22d3ee" + /> + 0 ? `已用 ${w.locationUsed} / 共 ${w.locationTotal}` : '库位未维护'} + color="#a78bfa" + /> +
+ ); +} + +function Cell({ + label, + value, + unit, + sub, + color = '#22d3ee', +}: { + label: string; + value: string | number; + unit: string; + sub: string; + color?: string; +}) { + return ( +
+
{label}
+
+ {value} + {unit && {unit}} +
+
{sub}
+
+ ); +} diff --git a/bj_power_dashboard/src/components/ScrollList.tsx b/bj_power_dashboard/src/components/ScrollList.tsx new file mode 100644 index 0000000..b6324ef --- /dev/null +++ b/bj_power_dashboard/src/components/ScrollList.tsx @@ -0,0 +1,48 @@ +import { ReactNode, useMemo } from 'react'; + +/** + * 无缝向上滚动列表(车次信息大屏式)。 + * 内容渲染两份,CSS translateY(-50%) 循环,数据不足一屏时静止。 + * 无鼠标交互:hover 暂停仅为运维调试兜底。 + */ +export function ScrollList({ + children, + duration, + style, +}: { + children: ReactNode; + /** 滚动一轮秒数;缺省按行数自适应(每行 1.6s,最少 12s) */ + duration?: number; + style?: React.CSSProperties; +}) { + const items = Array.isArray(children) ? children : [children]; + const count = items.length; + const dur = useMemo(() => { + if (duration) return duration; + return Math.max(12, count * 1.6); + }, [duration, count]); + + if (count === 0) { + return ( +
+
暂无数据
+
+ ); + } + if (count <= 3) { + // 不足一屏:静止展示,不做无意义滚动 + return ( +
+
{items}
+
+ ); + } + return ( +
+
+
{items}
+
{items}
+
+
+ ); +} diff --git a/bj_power_dashboard/src/index.css b/bj_power_dashboard/src/index.css index 5f7334f..9b65619 100644 --- a/bj_power_dashboard/src/index.css +++ b/bj_power_dashboard/src/index.css @@ -1,61 +1,84 @@ :root { color-scheme: dark; + --gap: clamp(8px, 0.75vw, 35px); } +/* ============ 基座:纯流式(Grid/Flex + clamp),无固定容器尺寸、无滚动条 ============ */ html, body, #root { height: 100%; margin: 0; + overflow: hidden; } body { font-family: 'PingFang SC', 'Microsoft YaHei', 'Segoe UI', system-ui, sans-serif; - background: radial-gradient(1200px 600px at 20% -10%, #13203a 0%, #0b1220 60%); + background: #04070f; color: #e7eef8; - overflow: hidden; } -.app-shell { +#stage-wrap, +#stage { + width: 100%; height: 100%; + overflow: hidden; + background: radial-gradient(120vmax 70vmax at 50% -12%, #0e1a2e 0%, #04070f 62%); +} + +#stage { display: flex; flex-direction: column; } +/* ============ 顶栏 ============ */ .app-header { display: flex; align-items: center; - justify-content: flex-end; - padding: 8px 20px; - background: linear-gradient(90deg, #0f1a30, #14213d); - border-bottom: 1px solid #22304a; - height: 40px; + justify-content: space-between; + gap: var(--gap); + padding: 0 clamp(12px, 1.4vw, 66px); + height: clamp(40px, 4.6vh, 56px); flex-shrink: 0; + background: linear-gradient(90deg, #0a1424, #12203a 55%, #0a1424); + border-bottom: 1px solid #1e2c44; +} + +.app-title { + font-size: clamp(14px, 1.2vw, 48px); + font-weight: 600; + letter-spacing: 0.28em; + color: #d7ecff; + white-space: nowrap; + text-shadow: 0 0 18px rgba(56, 189, 248, 0.45); } .app-meta { display: flex; align-items: center; - gap: 12px; + gap: clamp(8px, 0.9vw, 40px); } .app-meta .clock { - font-size: 14px; - color: #8fa3bf; + font-size: clamp(13px, 1.05vw, 40px); + color: #cfe0f5; font-variant-numeric: tabular-nums; } .app-meta .date { - font-size: 12px; - color: #5d6f8f; + font-size: clamp(11px, 0.8vw, 31px); + color: #6d82a5; } +/* ============ 内容区:KPI 带 → 地图主视觉 → 底部三块 ============ */ .app-content { - padding: 12px; flex: 1; min-height: 0; - overflow: hidden; display: flex; + flex-direction: column; + gap: var(--gap); + padding: var(--gap); + overflow: hidden; } .app-content .semi-card { @@ -63,50 +86,198 @@ body { border-color: #22304a; } -/* ----- 主布局:左侧紧凑栏(生产+仓储)+ 右侧大块 LineModel ----- */ -.dashboard-grid { - display: grid; - grid-template-columns: minmax(360px, 34%) 1fr; - grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); - grid-template-areas: - 'production model' - 'warehouse model'; - gap: 10px; +/* 兜底容器必须延续 flex 高度链,否则内部 grid/flex 拿不到可用高度(曾导致地图撑破视口) */ +.error-retry-body { flex: 1; min-height: 0; - height: 100%; + display: flex; + flex-direction: column; + gap: var(--gap); } -.dash-section { +/* KPI 带:七格全宽 */ +.kpi-strip { + display: grid; + grid-template-columns: repeat(7, minmax(0, 1fr)); + gap: var(--gap); + flex-shrink: 0; +} + +.kpi-cell { + min-width: 0; + background: linear-gradient(180deg, rgba(17, 33, 60, 0.9), rgba(9, 19, 36, 0.92)); + border: 1px solid rgba(56, 189, 248, 0.18); + border-radius: 10px; + padding: clamp(6px, 0.8vh, 12px) clamp(8px, 0.8vw, 35px); + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + box-shadow: inset 0 0 22px rgba(35, 130, 255, 0.12); +} + +.kpi-label { + font-size: clamp(10px, 0.78vw, 33px); + color: #8aa4c8; + letter-spacing: 0.08em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.kpi-value { + font-size: clamp(20px, 2vw, 88px); + font-weight: 700; + line-height: 1.12; + color: #22d3ee; + font-variant-numeric: tabular-nums; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.kpi-value small { + font-size: 0.42em; + font-weight: 500; + color: #8aa4c8; + margin-left: 0.2em; +} + +.kpi-sub { + font-size: clamp(9px, 0.7vw, 29px); + color: #5f7a9e; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +/* 主区:上=地图(大),下=三块细节 */ +.board-main { + flex: 1; + min-height: 0; + display: grid; + grid-template-rows: minmax(0, 1.45fr) minmax(0, 1fr); + gap: var(--gap); +} + +.map-hero { + min-height: 0; + min-width: 0; + display: flex; +} + +.bottom-row { + min-height: 0; + display: grid; + grid-template-columns: 1.08fr 1fr 0.92fr; + gap: var(--gap); +} + +/* ============ 通用面板 ============ */ +.panel { min-height: 0; min-width: 0; display: flex; flex-direction: column; + background: rgba(13, 26, 51, 0.62); + border: 1px solid rgba(56, 189, 248, 0.18); + border-radius: 10px; overflow: hidden; + padding: clamp(6px, 0.7vw, 26px) clamp(8px, 0.8vw, 31px); } -/* Section 内的可滚动 card(统一暗色背板) */ -.dash-section .board-card { +.panel-head { + flex-shrink: 0; + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + font-size: clamp(12px, 0.95vw, 40px); + font-weight: 500; + color: #67e8f9; + letter-spacing: 0.1em; + padding-bottom: clamp(3px, 0.5vh, 8px); + border-bottom: 1px solid rgba(56, 189, 248, 0.12); + margin-bottom: clamp(4px, 0.6vh, 8px); + white-space: nowrap; +} + +.panel-head .note { + font-size: clamp(9px, 0.72vw, 29px); + font-weight: 400; + color: #64809f; + letter-spacing: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.panel-body { flex: 1; min-height: 0; - background: rgba(13, 26, 51, 0.55); - border: 1px solid rgba(56, 189, 248, 0.18); - border-radius: 6px; - overflow: auto; - padding: 8px 10px; + overflow: hidden; + display: flex; + flex-direction: column; } -.dash-section.production { grid-area: production; } -.dash-section.warehouse { grid-area: warehouse; } -.dash-section.model { grid-area: model; } +/* ============ 无缝滚动列表 ============ */ +.scroll-list { + overflow: hidden; + position: relative; + min-height: 0; +} -@media (max-width: 1100px) { - .dashboard-grid { - grid-template-columns: 1fr; - grid-template-rows: auto auto minmax(360px, 50vh); - grid-template-areas: - 'production' - 'warehouse' - 'model'; +.scroll-list .scroll-inner { + animation: scroll-up var(--scroll-dur, 18s) linear infinite; +} + +.scroll-list:hover .scroll-inner { + animation-play-state: paused; +} + +@keyframes scroll-up { + 0% { + transform: translateY(0); + } + 100% { + transform: translateY(-50%); + } +} + +/* ============ 环形进度(conic-gradient) ============ */ +.ring { + border-radius: 50%; + display: grid; + place-items: center; + position: relative; + flex-shrink: 0; +} + +.ring::before { + content: ''; + position: absolute; + inset: 8%; + border-radius: 50%; + background: #0d1a33; +} + +.ring .ring-value { + position: relative; + z-index: 1; + text-align: center; + line-height: 1.2; +} + +.num-pop { + animation: num-pop 0.5s ease-out 1; +} + +@keyframes num-pop { + 0% { + transform: scale(0.85); + opacity: 0.4; + } + 100% { + transform: scale(1); + opacity: 1; } } diff --git a/bj_power_dashboard/src/mock.ts b/bj_power_dashboard/src/mock.ts index 61fc089..ef485e6 100644 --- a/bj_power_dashboard/src/mock.ts +++ b/bj_power_dashboard/src/mock.ts @@ -75,6 +75,50 @@ function buildStations(): Station[] { tighteningGun: { status: tool, currentSn: sn, processedCount: 1080 + id * 96 }, currentSn: sn, currentOperator: operator, + currentProcess: busy ? PROCESS_NAMES[id - 1] : undefined, + doneCount: busy ? 26 + id * 3 : 0, + }; + }); +} + +/** 演示点位态:主线/接驳台预置部分占用,AGV 一台在途 */ +function buildDemoPoints() { + const mainHas = new Set(['C1', 'C3', 'C7', 'C9', 'C13']); + const dockHas = new Set(['G1L', 'G3R', 'G6L', 'JBT21']); + return { + mock: false, + main: Array.from({ length: 15 }, (_, i) => ({ code: `C${i + 1}`, has: mainHas.has(`C${i + 1}`) })), + dock: (() => { + const arr = Array.from({ length: 20 }, (_, i) => { + const g = Math.floor(i / 2) + 1; + const s = i % 2 === 0 ? 'L' : 'R'; // 奇数位=左侧L、偶数位=右侧R + return { code: `G${g}${s}`, has: dockHas.has(`G${g}${s}`) }; + }); + arr.push({ code: 'JBT21', has: dockHas.has('JBT21') }); + return arr; + })(), + transit: [{ src: 'G5', tgt: 'C7' }], + }; +} + +/** 演示 AGV:一台在途(G1L ← JBT21),一台待命 */ +function buildDemoAgv() { + return [ + { code: 'AGV-01', status: 'moving', from: 'JBT21', to: 'G1L', carrier: '装配螺丝 M6', taskNo: 'WO-20260825-007-01' }, + { code: 'AGV-02', status: 'idle', from: 'JBT21', to: '', carrier: '', taskNo: '' }, + ]; +} + +/** 演示事件流(已完成工序实绩,负面结果不进大屏) */ +function buildDemoEvents() { + const now2 = new Date(); + return Array.from({ length: 8 }, (_, i) => { + const t = new Date(now2.getTime() - (i + 1) * 7 * 60_000); + const st = 1 + (i % 10); + return { + time: `${pad2(t.getHours())}:${pad2(t.getMinutes())}`, + text: `工位${st} ${OPERATORS[i % OPERATORS.length]} 完成 SN26-${2580 - i * 3} ${PROCESS_NAMES[i % PROCESS_NAMES.length]} OK`, + level: 'info', }; }); } @@ -226,6 +270,9 @@ export function getDemoData(): DashboardData { }, traces, trends: { production: trends }, + points: buildDemoPoints(), + agv: buildDemoAgv(), + events: buildDemoEvents(), // 报警项仅用于语音播报、屏幕不渲染;演示数据不造报警(看板报喜不报忧) alarms: [], isDemo: true, diff --git a/bj_power_dashboard/src/pages/LineModel.css b/bj_power_dashboard/src/pages/LineModel.css index 176c35e..37aea53 100644 --- a/bj_power_dashboard/src/pages/LineModel.css +++ b/bj_power_dashboard/src/pages/LineModel.css @@ -2,11 +2,12 @@ flex: 1; width: 100%; min-height: 0; + min-width: 0; display: flex; flex-direction: column; - background: linear-gradient(180deg, #040912, #050b1a 60%); + background: linear-gradient(180deg, rgba(6, 14, 28, 0.9), rgba(5, 11, 24, 0.95) 70%); border: 1px solid rgba(125, 211, 252, 0.18); - border-radius: 6px; + border-radius: 10px; position: relative; overflow: hidden; } @@ -16,8 +17,8 @@ } @keyframes linemodel-pulse { - 0% { box-shadow: inset 0 0 0 0 rgba(125, 211, 252, 0.85); } - 35% { box-shadow: inset 0 0 0 6px rgba(125, 211, 252, 0.45); } + 0% { box-shadow: inset 0 0 0 0 rgba(125, 211, 252, 0.8); } + 35% { box-shadow: inset 0 0 0 6px rgba(125, 211, 252, 0.4); } 100% { box-shadow: inset 0 0 0 12px rgba(125, 211, 252, 0); } } @@ -25,53 +26,90 @@ display: flex; align-items: center; justify-content: space-between; - padding: 6px 12px; - border-bottom: 1px solid rgba(125, 211, 252, 0.18); - background: linear-gradient(90deg, rgba(13, 26, 51, 0.6), rgba(13, 26, 51, 0.0)); + gap: 12px; + padding: clamp(4px, 0.7vh, 10px) clamp(10px, 0.9vw, 40px); + border-bottom: 1px solid rgba(125, 211, 252, 0.16); + background: linear-gradient(90deg, rgba(13, 26, 51, 0.75), rgba(13, 26, 51, 0)); flex-shrink: 0; } -.linemodel-shell .lm-titlebar .lm-title { +.linemodel-shell .lm-title { color: #67e8f9; - font-size: 12px; - font-weight: 600; - letter-spacing: 2px; + font-size: clamp(13px, 1vw, 42px); + font-weight: 500; + letter-spacing: 0.16em; + white-space: nowrap; } -.linemodel-shell .lm-titlebar .lm-stat { +.linemodel-shell .lm-stat { color: #94a3b8; - font-size: 11px; + font-size: clamp(10px, 0.8vw, 31px); display: flex; - gap: 14px; + gap: clamp(8px, 1vw, 40px); + align-items: center; + white-space: nowrap; + overflow: hidden; } -.linemodel-shell .lm-titlebar .lm-stat b { - color: #f1f5f9; +.linemodel-shell .lm-stat b { + color: #e2f6ff; font-weight: 600; + font-variant-numeric: tabular-nums; } -.linemodel-svg { +.linemodel-shell .lm-stat .lm-note { + color: #5c718f; +} + +/* PLC 未接真实设备:点位为模拟数据,低调标注 */ +.linemodel-shell .lm-mock { + color: #fbbf24; + border: 1px solid rgba(251, 191, 36, 0.5); + border-radius: 10px; + font-size: clamp(9px, 0.72vw, 26px); + padding: 0 8px; +} + +/* 画布容器:占满标题栏以下全部空间;SVG 绝对定位,避免 viewBox 固有比例把容器撑高 */ +.lm-canvas { + position: relative; flex: 1; + min-height: 0; + min-width: 0; +} + +/* SVG 铺满画布:宽高绝对填充,配合 viewBox 等比缩放(不写死像素、不溢出) */ +.linemodel-svg { + position: absolute; + inset: 0; width: 100%; height: 100%; - min-height: 0; display: block; background: transparent; } -.linemodel-shell .lm-watermark { - position: absolute; - right: 10px; - bottom: 6px; - font-size: 10px; - color: rgba(148, 163, 184, 0.55); - letter-spacing: 1px; - pointer-events: none; +/* 在途流光:真实路径指令驱动(同一时刻至多一条) */ +.linemodel-svg .flow-line { + stroke-dasharray: 8 6; + animation: flow-dash 0.8s linear infinite; + opacity: 0.85; } -.linemodel-svg .legend-text { - font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif; - fill: #cbd5e1; - font-size: 3px; - dominant-baseline: middle; +@keyframes flow-dash { + to { stroke-dashoffset: -14; } +} + +/* AGV 平滑移动:transform 过渡 2.5s(数据事件驱动,非逐帧模拟) */ +.linemodel-svg .agv-car { + transition: transform 2.5s ease-in-out; +} + +/* 状态灯呼吸(工位运行 / AGV 作业灯) */ +.linemodel-svg .status-blink { + animation: status-blink 1.6s ease-in-out infinite; +} + +@keyframes status-blink { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.35; } } diff --git a/bj_power_dashboard/src/pages/LineModel.tsx b/bj_power_dashboard/src/pages/LineModel.tsx index a5ee019..d4f9920 100644 --- a/bj_power_dashboard/src/pages/LineModel.tsx +++ b/bj_power_dashboard/src/pages/LineModel.tsx @@ -1,217 +1,130 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; -import type { DashboardData, Station } from '../types'; +import { useEffect, useMemo, useState } from 'react'; +import type { AgvRobot, DashboardData, LinePoint, Station } from '../types'; import './LineModel.css'; // ============================================================ -// 产线 2D 顶视平面图(严格按甲方 CAD 图布局) +// 产线动态地图(拓扑严格按《产线布局说明》主线位置编址版) // -// 单位 = 100mm,画布对应 CAD 48000 × 27000 mm -// 世界坐标:中心 (0,0),y 上正下负 +// 上排工位(奇):G1 G3 G5 G7 G9,末端 G11(下料检测,无终端无接驳台) +// 下排工位(偶):G2 G4 G6 G8 G10,末端 G12 +// 主线:C1~C15 自左向右单向流动;停靠位 C1/C4/C7/C10/C13/C15(不缓存,到位即顶升进工位), +// 缓存位 C2C3 / C5C6 / C8C9 / C11C12 / C14 +// 接驳台:工位 1~10 各 2 个(L=左 / R=右,共 20 个 AGV 点位)+ 库房接驳台 JBT21 // -// 按图分区(CAD 1:1 严格布置): -// ┌────┬─────────────────────────────────────────┬──────┐ -// │ │ 上方红高货架区(密集 4 排) │ │ -// │控制│ ████ ████ ████ ████ ████ │ 独立 │ -// │室 │ ████ ████ ████ ████ ████ │ 房间 │ -// │ │ │ │ -// │ ├──────────────────────────────────────────┴──────┤ ← 黄跑道 -// │ │ 绿跑道(矩形环) │ -// │ │ ▢ ▢ ▢ ▢ ▢ ▢ (接驳台) │ -// │ │ S1 S2 S3 S4 S5 工位(上) │ -// │ │ ▔▔▔▔ 装配线+传送带 ▔▔▔▔ │ -// │ │ S6 S7 S8 S9 S10 工位(下) │ -// │ │ ▢ ▢ ▢ ▢ ▢ ▢ (接驳台) │ -// │ ├─────────────────────────────────────────┬──────┤ ← 黄跑道 -// │ │ 下方左红低货架(堆料) │ 右下独立 │ -// │ │ │ 房间+白盒 │ -// └────┴──────────────────────────────────────────┴──────┘ +// 画布比例 1900×540(≈ 全宽主视觉容器 3.5:1)——横长比例与真实产线一致,SVG 铺满不留黑边。 +// 纵向分区:上排接驳台(64~94) / 上排工位(100~204) / 主线带(240~288) / 下排工位(324~428) / 下排接驳台(438~468) +// 横向分区:主线+工位(x 40~1560) / 库房侧 JBT21+AGV+图例(x 1610~1810) +// +// 数据:工位状态/SN/操作人/完成数 ← equipment;点位亮灭 ← points(PLC 48 位); +// 在途流光 ← points.transit(MW 非 0 的真实路径指令,同一时刻至多一条); +// AGV ← agv(真实备料任务,事件驱动 + CSS 过渡移动,不造假坐标) +// 动效:全部 CSS 动画 / transition,无 JS 帧循环(4K 不掉帧) // ============================================================ -// 画布(中心 0,0;sx/sy 做世界→SVG 转换) -const VIEW_W = 480; -const VIEW_H = 270; -const cx = VIEW_W / 2; -const cy = VIEW_H / 2; -const sx = (x: number) => cx + x; -const sy = (y: number) => cy - y; +const VIEW_W = 1900; +const VIEW_H = 540; -// ============================================================ -// 分区坐标(按 CAD 图标注直接 hard-code) -// ============================================================ +// 主线 15 个位置:块宽 76、步长 96(C1 中心 140 → C15 中心 1484) +const C_STEP = 96; +const C_W = 76; +const C_Y = 240; +const C_H = 48; +const cx = (i: number) => 140 + (i - 1) * C_STEP; -// 上方红高货架区(密集多排) -const TOP_SHELF_AREA = { x: -230, y: -135, w: 410, h: 70 }; -// 上方货架每排位置(4 排,沿 x 均匀) -const TOP_SHELVES: Array<{ x: number; y: number }> = []; -for (let row = 0; row < 4; row++) { - for (let col = 0; col < 6; col++) { - TOP_SHELVES.push({ - x: -200 + col * 70, - y: -120 + row * 16, - }); - } -} - -// 左上控制室(独立小房间) -const TOP_LEFT_ROOM = { x: -230, y: -135, w: 25, h: 30 }; - -// 右上独立房间(库房 / 配电) -const TOP_RIGHT_ROOM = { x: 180, y: -135, w: 50, h: 30 }; - -// 中央通道:黄跑道(外圈矩形环,沿外墙) -const ASSEMBLY_TOP = -32; // 上黄跑道 y 中心 -const ASSEMBLY_BOTTOM = +32; // 下黄跑道 y 中心 -const ASSEMBLY_LEFT = -195; -const ASSEMBLY_RIGHT = +195; - -// 装配线(中央横向长条) -const ASSEMBLY = { - x: -180, y: -15, w: 360, h: 30, -}; - -// 工位(上下各 5) -const STATION_NAMES = [ - '上料扫码', '外壳组装', '端子排安装', '电路板装配', '线缆连接', - '面板固定', '功能初检', '绝缘耐压', '计量校准', '外观终检', -]; -const STATION_W = 56; -const STATION_H = 28; -const STATION_GAP_X = 12; // 工位之间间距 -// 5 个工位总宽 = 5*56 + 4*12 = 328,居中:startX = -164 -const STATION_START_X = -((5 * STATION_W + 4 * STATION_GAP_X) / 2); -const STATION_TOP_Y = -55; -const STATION_BOT_Y = +27; - -// 接驳台:每个工位上下各 1 个,夹住工位 -const DOCK_W = 20; -const DOCK_H = 14; -const DOCK_GAP_FROM_STATION = 4; // 接驳台到工位边距 - -// 下方左红低货架(堆料区) -const BOT_LEFT_SHELF_AREA = { x: -230, y: +65, w: 200, h: 70 }; -// 内部细分(4 排 x 6 列) -const BOT_LEFT_SHELVES: Array<{ x: number; y: number }> = []; -for (let row = 0; row < 4; row++) { - for (let col = 0; col < 6; col++) { - BOT_LEFT_SHELVES.push({ - x: -200 + col * 32, - y: +75 + row * 16, - }); - } -} - -// 下方右黄货架(成品/不同物料) -const BOT_RIGHT_SHELF_AREA = { x: -30, y: +65, w: 210, h: 70 }; -const BOT_RIGHT_SHELVES: Array<{ x: number; y: number }> = []; -for (let row = 0; row < 4; row++) { - for (let col = 0; col < 6; col++) { - BOT_RIGHT_SHELVES.push({ - x: +5 + col * 33, - y: +75 + row * 16, - }); - } -} - -// 右下独立房间(充电区)+ 2 个白盒(机器人待命) -const BOT_RIGHT_ROOM = { x: 180, y: +65, w: 50, h: 70 }; -const BOT_RIGHT_BOXES: Array<{ x: number; y: number }> = [ - { x: 195, y: 95 }, - { x: 220, y: 95 }, +// 停靠位(不缓存,正对工位对) +const STOP_C = [1, 4, 7, 10, 13, 15]; +// 工位对 → 停靠位 +const PAIR_STOP: Array<[number, number, number]> = [ + [1, 2, 1], + [3, 4, 4], + [5, 6, 7], + [7, 8, 10], + [9, 10, 13], + [11, 12, 15], ]; -// ============================================================ -// 颜色 -// ============================================================ -const COLOR = { - factory: '#0a1830', - walkwayBg: 'rgba(250, 204, 21, 0.22)', - walkway: '#facc15', - agvBg: 'rgba(34, 197, 94, 0.30)', - agv: '#22c55e', - dock: '#ef4444', - dockEdge: '#fca5a5', - pile: '#dc2626', - pileEdge: '#fca5a5', - station: '#3b82f6', - stationOn: '#22d3ee', - stationOff: '#64748b', - assembly: '#0f172a', - assemblyLine: '#06b6d4', - shelfRed: 'rgba(239, 68, 68, 0.55)', - shelfRedEdge: '#fca5a5', - shelfYel: 'rgba(234, 179, 8, 0.65)', - shelfYelEdge: '#fde047', - room: '#1e293b', - roomEdge: '#94a3b8', - whiteBox: '#e2e8f0', - text: '#cbd5e1', - textDim: '#64748b', - agvCar: '#fb923c', - agvCar2: '#38bdf8', -}; +const STATION_W = 140; +const STATION_H = 104; +const STATION_TOP_Y = 100; +const STATION_BOT_Y = 324; +const DOCK_W = 64; +const DOCK_H = 30; +const DOCK_TOP_Y = 64; +const DOCK_BOT_Y = 438; + +// 接驳台 左L/右R 相对工位中心:左块 / 右块合计恰好铺满工位卡宽度(r: 1=左L、2=右R,仅内部几何参数) +const dockX = (center: number, r: 1 | 2) => (r === 1 ? center - 70 : center + 6); + +// 库房侧(右端) +const WAREHOUSE_X = 1610; +const WAREHOUSE_W = 200; +const JBT_X = WAREHOUSE_X + WAREHOUSE_W / 2; +const JBT_Y = 120; +const AGV_LANE_Y = 190; // ============================================================ -// AGV 路径(沿矩形环顺时针,绿跑道中线) +// 点位坐标表(流光端点 / AGV 目标定位) // ============================================================ -const AGV_TRACK_TOP = +50; -const AGV_TRACK_BOTTOM = -50; -const AGV_TRACK_RIGHT = +195; -const AGV_TRACK_LEFT = -195; - -const agvPathPos = (t: number) => { - const p = (t % 1 + 1) % 1; - const seg = p * 4; - if (seg < 1) { - return { x: AGV_TRACK_RIGHT, y: AGV_TRACK_BOTTOM + seg * (AGV_TRACK_TOP - AGV_TRACK_BOTTOM) }; - } else if (seg < 2) { - const k = seg - 1; - return { x: AGV_TRACK_RIGHT - k * (AGV_TRACK_RIGHT - AGV_TRACK_LEFT), y: AGV_TRACK_TOP }; - } else if (seg < 3) { - const k = seg - 2; - return { x: AGV_TRACK_LEFT, y: AGV_TRACK_TOP - k * (AGV_TRACK_TOP - AGV_TRACK_BOTTOM) }; - } else { - const k = seg - 3; - return { x: AGV_TRACK_LEFT + k * (AGV_TRACK_RIGHT - AGV_TRACK_LEFT), y: AGV_TRACK_BOTTOM }; +function pointCenter(code: string): { x: number; y: number } | null { + const c = code.trim().toUpperCase(); + if (c === 'JBT21') return { x: JBT_X, y: JBT_Y }; + if (c.startsWith('C')) { + const n = parseInt(c.slice(1), 10); + if (n >= 1 && n <= 15) return { x: cx(n), y: C_Y + C_H / 2 }; + return null; } -}; - -const agvTangent = (t: number) => { - const p = (t % 1 + 1) % 1; - const seg = p * 4; - if (seg < 1) return { dx: 0, dy: 1 }; - if (seg < 2) return { dx: -1, dy: 0 }; - if (seg < 3) return { dx: 0, dy: -1 }; - return { dx: 1, dy: 0 }; -}; - -// ============================================================ -// 组件 -// ============================================================ -export function LineModel({ data }: { data: DashboardData }) { - const [tick, setTick] = useState(0); - const stationsRef = useRef(data.equipment); - stationsRef.current = data.equipment; - - // 60fps 动画 tick(AGV 流动 + 工位呼吸 + 物料光斑) - useEffect(() => { - let timer = 0; - const loop = () => { - setTick((t) => (t + 1) % 1_000_000); - timer = window.setTimeout(loop, 60); + if (c.startsWith('G')) { + // 接驳台 G{n}L / G{n}R(左L/右R)优先于工位 G{n};运行时纯字符串解析,不用正则 + const last = c.charAt(c.length - 1); + if (last === 'L' || last === 'R') { + const g = parseInt(c.slice(1, -1), 10); + if (Number.isNaN(g)) return null; + const pair = PAIR_STOP.find((p) => p[0] === g || p[1] === g); + if (!pair) return null; + const stopCenter = cx(pair[2]); + const top = g % 2 === 1; + return { x: dockX(stopCenter, last === 'L' ? 1 : 2) + DOCK_W / 2, y: top ? DOCK_TOP_Y + DOCK_H / 2 : DOCK_BOT_Y + DOCK_H / 2 }; + } + const n = parseInt(c.slice(1), 10); + const pair = PAIR_STOP.find((p) => p[0] === n || p[1] === n); + if (!pair) return null; + const stopCenter = cx(pair[2]); + const top = n % 2 === 1; + return { + x: stopCenter, + y: top ? STATION_TOP_Y + STATION_H / 2 : STATION_BOT_Y + STATION_H / 2, }; - timer = window.setTimeout(loop, 60); - return () => window.clearTimeout(timer); - }, []); + } + return null; +} - // 数据指纹变化触发 0.6s 高亮脉冲(直观告诉用户「数据更新了」) +const COLOR = { + stop: '#185FA5', + stopOn: '#378ADD', + cache: 'rgba(234, 179, 8, 0.28)', + cacheEdge: 'rgba(234, 179, 8, 0.55)', + dock: 'rgba(148, 163, 184, 0.25)', + dockEdge: '#64748b', + dockOn: '#f59e0b', + tray: '#22d3ee', + flow: '#f59e0b', + text: '#cbd5e1', + dim: '#64748b', + cyan: '#67e8f9', +}; + +export function LineModel({ data }: { data: DashboardData }) { + // 数据指纹变化触发一次脉冲(CSS 动画,非常驻帧循环) const fingerprint = useMemo(() => { const eq = data.equipment .slice() .sort((a, b) => a.id - b.id) .map((s) => `${s.id}:${s.status}:${s.doneCount ?? 0}`) .join('|'); - return `${data.production.outputToday}|${data.production.inLine}|${data.progress.orderNo}|${eq}`; + const pts = data.points.main.map((p) => (p.has ? 1 : 0)).join('') + data.points.transit.map((t) => t.src + t.tgt).join(','); + return `${data.production.outputToday}|${data.production.inLine}|${pts}|${eq}`; }, [data]); + const [pulsing, setPulsing] = useState(false); useEffect(() => { setPulsing(true); @@ -219,421 +132,265 @@ export function LineModel({ data }: { data: DashboardData }) { return () => window.clearTimeout(t); }, [fingerprint]); - const agv1T = (tick * 0.0014) % 1; // 跑得更快(约一圈 12s) - const agv2T = ((tick * 0.0011) + 0.5) % 1; - const agv1 = agvPathPos(agv1T); - const agv2 = agvPathPos(agv2T); - const agv1Tan = agvTangent(agv1T); - const agv2Tan = agvTangent(agv2T); - const agv1Angle = Math.atan2(agv1Tan.dy, agv1Tan.dx); - const agv2Angle = Math.atan2(agv2Tan.dy, agv2Tan.dx); - - // 工位状态(以 dashboard.equipment 为准) - const stations: Station[] = Array.from({ length: 10 }, (_, i) => - stationsRef.current[i] ?? { - id: i + 1, stationNo: `S${i + 1}`, name: STATION_NAMES[i], - status: i < 2 ? 'running' : 'idle', doneCount: 0, - scanGun: { connected: true }, tighteningGun: { connected: true }, + const stations: Station[] = Array.from({ length: 12 }, (_, i) => + data.equipment.find((s) => s.id === i + 1) ?? { + id: i + 1, + name: `工位${i + 1}`, + status: 'idle', + scanGun: { status: 'offline', processedCount: 0 }, + tighteningGun: { status: 'offline', processedCount: 0 }, }, ); + const byNo = new Map(stations.map((s) => [s.id, s])); - // 物料光点(沿装配线 x 方向跑,密度更高) - const flowDots = Array.from({ length: 28 }, (_, i) => ({ - x: -ASSEMBLY.w / 2 + ((tick * 1.0 + i * (ASSEMBLY.w / 28)) % ASSEMBLY.w), - })); + const mainMap = new Map(data.points.main.map((p) => [p.code, p])); + const dockMap = new Map(data.points.dock.map((p) => [p.code, p])); + const hasMain = (n: number) => mainMap.get(`C${n}`)?.has ?? false; + const hasDock = (g: number, r: 1 | 2) => dockMap.get(`G${g}${r === 1 ? 'L' : 'R'}`)?.has ?? false; + const hasJbt = dockMap.get('JBT21')?.has ?? false; - // 概览统计 - const runningCount = stations.filter((s) => s.status === 'running').length; - const idleCount = stations.filter((s) => s.status === 'idle').length; - const totalOutput = data.production.outputToday ?? 0; + const inStation = stations.filter((s) => !!s.currentSn).length; + const inMain = data.points.main.filter((p) => p.has).length; + const inDock = data.points.dock.filter((p) => p.has).length; + + const agv1 = data.agv.find((a) => a.code.endsWith('01')); + const agv2 = data.agv.find((a) => a.code.endsWith('02')); return (
- 数字孪生 · 产线 2D 顶视图 + 产线动态地图 - 在制 {data.production.inLine} - 今日产量 {totalOutput} - 运行 {runningCount}/待机 {idleCount}/10 - 数据指纹 {pulsing ? '更新' : '稳态'} + 在制 {data.production.inLine ?? 0} 件 + 工位 {inStation} · 主线 {inMain} · 接驳台 {inDock} + {data.points.mock && 点位模拟数据} + 上排 1/3/5/7/9 + 末端 11 · 下排 2/4/6/8/10 + 末端 12
- - - - - - - - - - - - - - - - - - - - - - +
+ + + + + + + + + - {/* 1. 厂区背景 + 网格点 */} - - + {/* 满幅底纹:铺满整个主视觉区,不留"黑洞" */} + - {/* 2. 上方红高货架区底色 */} - - - 上方库房(红高货架) - + {/* ---------- 主线流向(贯穿虚线,穿行于块间空隙,右端箭头) ---------- */} + - {/* 3. 上方密集红色高货架 */} - {TOP_SHELVES.map((p, i) => ( - - ))} + {/* ---------- 工位↔主线 竖向移载通道 ---------- */} + {PAIR_STOP.map(([up, , stop]) => { + const center = cx(stop); + return ( + + + + + ); + })} - {/* 4. 左上控制室(独立小房间) */} - + {/* ---------- 在途流光(真实路径指令:同一时刻至多一条) ---------- */} + {data.points.transit.map((t, i) => { + const a = pointCenter(t.src); + const b = pointCenter(t.tgt); + if (!a || !b) return null; + return ( + + + + + + + ); + })} - {/* 5. 右上独立房间 */} - + {/* ---------- 主线 C1~C15 ---------- */} + {Array.from({ length: 15 }, (_, i) => { + const n = i + 1; + const isStop = STOP_C.includes(n); + const has = hasMain(n); + const bx = cx(n) - C_W / 2; + return ( + + + {has && } + + C{n} + + + ); + })} - {/* 6. 黄跑道(上下两条横带) */} - - {/* 矩形环描边:上下两条横跑道 + 左右两条竖跑道 */} - - + {/* ---------- 工位 + 接驳台(上排奇 / 下排偶) ---------- */} + {PAIR_STOP.map(([up, down, stop]) => { + const center = cx(stop); + const isEnd = up >= 11; + return ( + + + + {!isEnd && ( + <> + + + + + + )} + + ); + })} - {/* 7. 绿跑道(矩形环,比黄跑道大一圈) */} - + {/* ---------- 库房侧:JBT21 + AGV 通道 + 图例 ---------- */} + 库房侧 - {/* 7.5 AGV 跑道流动光斑(沿环形循环,密度更高) */} - {Array.from({ length: 12 }, (_, i) => { - const t = (tick * 0.0016 + i / 12) % 1; - const p = agvPathPos(t); - return ( - + - ); - })} - - {/* 8. 下方左红低货架区底色 */} - - - 堆料区(红低货架) - - - {/* 9. 下方左红色低货架 */} - {BOT_LEFT_SHELVES.map((p, i) => ( - - ))} - - {/* 10. 下方右黄色货架区底色 */} - - - 成品区(黄货架) - - - {/* 11. 下方右黄色货架 */} - {BOT_RIGHT_SHELVES.map((p, i) => ( - - ))} - - {/* 12. 右下独立房间(充电区) */} - - - {/* 13. 右下独立房间内的 2 个白盒(机器人待命) */} - {BOT_RIGHT_BOXES.map((p, i) => ( - - - + {hasJbt && } + JBT21 + 库房接驳台 - ))} - {/* 14. 中央装配线 */} - - - - 中央装配线 + 传送带 - → 流向 - {flowDots.map((d, i) => ( - - ))} + + + + + AGV 搬运通道 · 任务驱动 + - {/* 15. 工位(上下各 5 个)+ 接驳台(每个工位上下各 1) */} - {stations.slice(0, 5).map((s, i) => { - const x = STATION_START_X + i * (STATION_W + STATION_GAP_X) + STATION_W / 2; - return ( - - - - - ); - })} - {stations.slice(5, 10).map((s, i) => { - const x = STATION_START_X + i * (STATION_W + STATION_GAP_X) + STATION_W / 2; - return ( - - - - - ); - })} + + + + + + - {/* 16. AGV 小车(两辆,沿跑道跑) */} - - - - {/* 17. 北方向标识 */} - - - N - - - - - 单位:100mm · 厂区 48000 × 27000 mm - - - {/* 18. 图例(左下角,避开右下房间) */} - - - 图例 - - - - - - - + + 虚线箭头 = 主线自左向右单向流动 · 布局依据:产线布局说明(停靠位 C1/C4/C7/C10/C13/C15;缓存位 C2C3 / C5C6 / C8C9 / C11C12 / C14) + - 更新指纹 {fingerprint.length} 位 · 内嵌 60fps 动画 +
); } -function LegendRow({ y, color, label }: { y: number; color: string; label: string }) { +/** 工位卡:编号 + 当前工序 + SN + 操作人·当日完成 + 停单图标 */ +function StationBox({ + x, y, station, no, +}: { + x: number; + y: number; + station?: Station; + no: number; +}) { + const W = STATION_W; + const running = station?.status === 'running'; + const offline = station?.status === 'offline'; + const paused = !!station?.paused; + const fill = offline ? 'rgba(51,65,85,0.5)' : running ? 'rgba(8,145,178,0.38)' : 'rgba(30,64,175,0.38)'; + const edge = offline ? '#475569' : running ? '#22d3ee' : '#3b82f6'; + const end = no >= 11; + return ( + + + {end ? `G${no} 下料` : `G${no}`} + + {paused && ( + + + + 该工位当天已停单 + + )} + {station?.currentProcess || '待排产'} + + {station?.currentSn ? station.currentSn : '无在制工件'} + + + {station?.currentOperator || '未登录'} + {station?.doneCount ? ` · 完成 ${station.doneCount}` : ''} + + + ); +} + +/** 接驳台:有料亮橙 + 托盘块;below=true 时标签在下方 */ +function DockBox({ x, y, has, label, below }: { x: number; y: number; has: boolean; label: string; below?: boolean }) { return ( - - {label} - - ); -} - -// ============================================================ -// 子组件 -// ============================================================ -function Shelf({ - x, y, w, h, fill, edge, layers = 2, -}: { - x: number; y: number; w: number; h: number; - fill: string; edge: string; layers?: number; -}) { - return ( - - - {Array.from({ length: layers - 1 }, (_, i) => ( - - ))} - - ); -} - -function RoomBox({ - x, y, w, h, label, -}: { - x: number; y: number; w: number; h: number; label: string; -}) { - return ( - - - {/* 门缝(右侧缺口表示门) */} - - + + {has && } + {label} ); } -function StationBox({ - x, y, idx, station, tick, -}: { - x: number; y: number; idx: number; station: Station; tick: number; -}) { - const W = STATION_W, H = STATION_H; - const running = station.status === 'running'; - const offline = station.status === 'offline'; - const fillCore = running ? '#0e7490' : offline ? '#334155' : '#1e40af'; - const strokeCore = running ? COLOR.stationOn : offline ? COLOR.stationOff : COLOR.station; - const pulsePhase = (idx * 0.18) % 1; - const pulse = 0.5 + 0.5 * Math.sin((tick / 9) + pulsePhase * Math.PI * 2); - const num = `${String(idx + 1).padStart(2, '0')}`; +/** 图例行 */ +function LegendRow({ y, color, label }: { y: number; color: string; label: string }) { return ( - - {/* 底座呼吸光晕 */} - - {/* 工位主体 */} - - {/* 工位编号 */} - {num} - {/* 工序名(在工位外侧:上边工位向上,下边工位向下) */} - - {STATION_NAMES[idx]} - - {/* 状态点(右上角) */} - - {/* 完成数(中央大字) */} - - {station.doneCount ?? 0} - + + + {label} ); } -function Dock({ - x, y, active, -}: { x: number; y: number; active?: boolean }) { +/** + * AGV 小车:真实备料任务驱动。 + * 无任务 → 待命区;loading → 停起点;moving → CSS transition 平滑滑向目标;到位 → 停目标。 + * 不做假坐标插值,位置只随数据事件变化。 + */ +function AgvCar({ robot, fallback }: { robot?: AgvRobot; fallback: { x: number; y: number } }) { + let pos = fallback; + if (robot && robot.to) { + const to = pointCenter(robot.to); + const from = pointCenter(robot.from) ?? fallback; + if (robot.status === 'moving') { + pos = to ?? from; + } else if (robot.status === 'loading' || robot.status === 'waiting') { + pos = from; + } else { + pos = to ?? from; + } + } + const label = robot?.code ?? 'AGV'; return ( - - - {active && ( - - )} - - ); -} - -function Agv({ - x, y, angle, body, lamp, -}: { - x: number; y: number; angle: number; body: string; lamp: string; -}) { - const W = 8, H = 4.5; - const rad = (angle * 180) / Math.PI; - return ( - - - - + + + + + {label.replace('AGV-', 'AGV ')} + ); } diff --git a/bj_power_dashboard/src/pages/ProductionBoard.tsx b/bj_power_dashboard/src/pages/ProductionBoard.tsx index d1a22f5..182b959 100644 --- a/bj_power_dashboard/src/pages/ProductionBoard.tsx +++ b/bj_power_dashboard/src/pages/ProductionBoard.tsx @@ -1,345 +1,109 @@ import type { EChartsOption } from 'echarts'; -import type { DashboardData, Station, ProgressGanttStep } from '../types'; +import type { DashboardData } from '../types'; import { EChart } from '../components/EChart'; +import { dash0 } from './WarehouseBoard'; const C = { cyan: '#22d3ee', green: '#34d399', - blue: '#60a5fa', - amber: '#fbbf24', - panel: '#0d1a33', - border: 'rgba(56,189,248,0.22)', text: '#e2e8f0', sub: '#94a3b8', dim: '#64748b', }; -const statusColor: Record = { - running: C.green, - idle: C.blue, - // 大屏「报喜不报忧」:不把异常状态渲染成负面色,统一按中性呈现 - alarm: C.blue, - offline: '#475569', -}; - -const gridLabel = { color: '#8fa3bf', fontSize: 13 }; - +/** 底部左块 · 当前订单(合同/工期/完成度)+ 近 7 日产量趋势 */ export function ProductionBoard({ data }: { data: DashboardData }) { - const { production, progress, trends, equipment } = data; + const { progress, trends } = data; const trendOption: EChartsOption = { - grid: { left: 48, right: 20, top: 28, bottom: 28 }, + grid: { left: 8, right: 12, top: 14, bottom: 4, containLabel: true }, tooltip: { trigger: 'axis' }, xAxis: { type: 'category', data: trends.production.map((t) => t.time), - axisLine: { lineStyle: { color: '#335' } }, - axisLabel: gridLabel, + axisTick: { show: false }, + axisLine: { lineStyle: { color: 'rgba(56,189,248,0.25)' } }, + axisLabel: { color: '#8fa3bf', fontSize: 11 }, }, yAxis: { type: 'value', - name: '产量', - splitLine: { lineStyle: { color: '#1f2a3f' } }, - axisLabel: gridLabel, + splitLine: { lineStyle: { color: 'rgba(56,189,248,0.1)' } }, + axisLabel: { color: '#8fa3bf', fontSize: 11 }, }, series: [ { name: '日产量', type: 'line', smooth: true, + symbol: 'circle', + symbolSize: 6, data: trends.production.map((t) => t.output), itemStyle: { color: C.cyan }, + lineStyle: { width: 2.5 }, areaStyle: { color: 'rgba(34,211,238,0.18)' }, }, ], }; return ( -
-
- - - - - 0 ? production.cycleTime.toFixed(1) : '—'} - label="生产节拍" - sub="相邻完工间隔均值(分)" - color={C.amber} - /> +
+
+ 当前订单 + 合同 · 工期 · 完成度
+
+ {/* 左:订单信息 */} +
+
+ {progress.contractNo || progress.orderNo || '暂无在产订单'} +
- - - +
+ {progress.productName || '—'} +
- -
- - {progress.contractNo || progress.orderNo} - - - {progress.productName} - - - {progress.owner || '—'} - - - - {progress.planStart || '—'} ~ {progress.planEnd || '—'} - = 0 ? C.green : C.amber }}> - 剩余 {progress.remainDays >= 0 ? progress.remainDays : 0} 天 +
+ + 交期 {progress.planEnd || '—'} - -
+ = 0 ? C.green : '#fbbf24' }}> + 剩余 {progress.planEnd ? Math.max(progress.remainDays, 0) : '—'} 天 + +
-
- - 完成度 {progress.progress}% · 工序 {progress.processDone}/{progress.processTotal} - - - {progress.doneQty} - {' / '}{progress.totalQty} 台 - -
- - -
- {progress.steps.length > 0 ? ( - - ) : ( -
- 暂无工序横道数据 +
+
+ 完成进度 + + {dash0(progress.doneQty)} + / {dash0(progress.totalQty)} 台 +
- )} -
- - - -
- {equipment.map((s, i) => ( -
-
- {s.name} - {i + 1} -
- {/* 报喜不报忧:不展示「异常/报警」等负面状态,异常位统一按「待料」中性展示 */} -
- {s.status === 'running' ? '作业中' : s.status === 'offline' ? '离线' : '待料'} -
+
+
- ))} +
+ 工序 {dash0(progress.processDone)}/{dash0(progress.processTotal)} + {progress.currentProcess ? ` · 当前 ${progress.currentProcess}` : ''} +
+
-
- 运行中 {production.stationSummary.running} · 待料 {production.stationSummary.idle} · 离线{' '} - {production.stationSummary.offline} + + {/* 右:近 7 日产量趋势(height:100% 跟随容器) */} +
+
近 7 日产量
+
+ +
- -
- ); -} - -function Field({ label }: { label: string }) { - return {label}; -} - -function Kpi({ value, label, sub, color }: { value: number | string; label: string; sub: string; color: string }) { - return ( -
-
{label}
-
{value}
-
{sub}
-
- ); -} - -function Panel({ - title, - children, - style, - accent, -}: { - title: string; - children: React.ReactNode; - style?: React.CSSProperties; - accent?: boolean; -}) { - return ( -
-
- {title}
- {children}
); } - -function Bar({ percent }: { percent: number }) { - const p = Math.max(0, Math.min(100, percent)); - return ( -
-
-
- ); -} - -function GanttChart({ steps }: { steps: ProgressGanttStep[] }) { - const names = steps.map((s) => s.name); - const now = new Date(); - - const planData = steps.map((s, i) => ({ - value: [i, new Date(s.planStart).getTime(), new Date(s.planEnd).getTime(), 'plan'], - itemStyle: { color: 'rgba(148, 163, 184, 0.12)' }, - })); - - const actualData = steps - .filter((s) => s.actualStart) - .map((s, i) => { - const start = new Date(s.actualStart!).getTime(); - const end = s.actualEnd ? new Date(s.actualEnd).getTime() : now.getTime(); - const color = s.status === 'done' ? C.green : C.cyan; - return { - value: [i, start, end, 'actual'], - itemStyle: { color }, - }; - }); - - const option: EChartsOption = { - tooltip: { - formatter: (params: any) => { - const s = steps[params.value[0] as number]; - const start = new Date(params.value[1] as number).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); - const end = new Date(params.value[2] as number).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); - return `
${s.name}
负责人:${s.owner}
状态:${s.status === 'done' ? '已完成' : s.status === 'running' ? '进行中' : '未开始'}
${start} ~ ${end}
`; - }, - }, - grid: { left: 96, right: 24, top: 10, bottom: 24 }, - xAxis: { - type: 'time', - axisLine: { lineStyle: { color: '#335' } }, - axisLabel: { color: '#8fa3bf', fontSize: 11, formatter: '{MM}-{dd}' }, - splitLine: { lineStyle: { color: '#1f2a3f' } }, - }, - yAxis: { - type: 'category', - data: names, - inverse: true, - axisLine: { lineStyle: { color: '#335' } }, - axisLabel: { color: '#94a3b8', fontSize: 11 }, - splitLine: { show: false }, - }, - series: [ - { - type: 'custom', - name: '计划工期', - renderItem: (_params: any, api: any) => { - const categoryIndex = api.value(0); - const start = api.coord([api.value(1), categoryIndex]); - const end = api.coord([api.value(2), categoryIndex]); - const height = api.size([0, 1])[1] * 0.55; - return { - type: 'rect', - shape: { - x: start[0], - y: start[1] - height / 2, - width: Math.max(end[0] - start[0], 2), - height, - }, - style: api.style(), - }; - }, - encode: { x: [1, 2], y: 0 }, - data: planData, - }, - { - type: 'custom', - name: '实际进度', - renderItem: (_params: any, api: any) => { - const categoryIndex = api.value(0); - const start = api.coord([api.value(1), categoryIndex]); - const end = api.coord([api.value(2), categoryIndex]); - const height = api.size([0, 1])[1] * 0.32; - return { - type: 'rect', - shape: { - x: start[0], - y: start[1] - height / 2, - width: Math.max(end[0] - start[0], 2), - height, - }, - style: api.style(), - }; - }, - encode: { x: [1, 2], y: 0 }, - data: actualData, - }, - ], - }; - - return ; -} diff --git a/bj_power_dashboard/src/pages/SideBoard.tsx b/bj_power_dashboard/src/pages/SideBoard.tsx new file mode 100644 index 0000000..aa9f301 --- /dev/null +++ b/bj_power_dashboard/src/pages/SideBoard.tsx @@ -0,0 +1,131 @@ +import type { DashboardData } from '../types'; +import { ScrollList } from '../components/ScrollList'; + +const C = { + cyan: '#22d3ee', + green: '#34d399', + text: '#e2e8f0', + sub: '#94a3b8', + dim: '#64748b', +}; + +/** 提取 时:分[:秒](后端可能下发完整 datetime);纯字符串解析,运行时不用正则 */ +function hms(t: string): string { + const s = String(t || ''); + const i = s.indexOf(':'); // 第一个冒号 = 小时之后(日期段无冒号) + if (i < 1) return '—'; + const start = i >= 2 ? i - 2 : 0; // 两位小时(08:05)从 i-2 起;一位小时(8:05)从 0 起 + const p = s.slice(start, start + 8).split(':'); + const digits = (x: string | undefined) => !!x && [...x].every((ch) => ch >= '0' && ch <= '9'); + if (!digits(p[0]) || p[0].length > 2 || !digits(p[1]) || p[1].length !== 2) return '—'; + const hh = p[0].length === 1 ? '0' + p[0] : p[0]; + return p[2] && digits(p[2]) ? hh + ':' + p[1] + ':' + p[2].slice(0, 2) : hh + ':' + p[1]; +} + +/** 底部右块 · 产线实时动态(事件流)+ 工件追溯(最近完工),均为后端已聚合数据 */ +export function SideBoard({ data }: { data: DashboardData }) { + const events = data.events ?? []; + const traces = data.traces ?? []; + + return ( +
+
+ 产线实时动态 + 自动滚动 +
+
+ + {events.map((e, i) => ( +
+ {hms(e.time)} + + {e.text} + +
+ ))} +
+ +
+ 工件追溯 · 最近完工 +
+ + + {traces.map((t) => ( +
+
+
+ {t.sn} +
+
+ {t.productName || '—'} · {t.stepCount} 道工序 · {Math.round(t.durationMin)} 分钟 +
+
+ {t.status === 'DONE' && ( + + 全程可追溯 + + )} +
+ ))} +
+
+
+ ); +} diff --git a/bj_power_dashboard/src/pages/WarehouseBoard.tsx b/bj_power_dashboard/src/pages/WarehouseBoard.tsx index 56ce0cb..c9764a9 100644 --- a/bj_power_dashboard/src/pages/WarehouseBoard.tsx +++ b/bj_power_dashboard/src/pages/WarehouseBoard.tsx @@ -1,111 +1,133 @@ -import { Card, Table, Tag, Typography } from '@douyinfe/semi-ui'; import type { DashboardData } from '../types'; +import { ScrollList } from '../components/ScrollList'; -interface MovementRow { - id: string; - time: string; - dir: string; - material: string; - qty: string; - operator: string; - batch: string; +const C = { + text: '#e2e8f0', + sub: '#94a3b8', + dim: '#64748b', + blue: '#36a3f7', + green: '#00d68f', + amber: '#fbbf24', + cyan: '#22d3ee', +}; + +/** 只显示 时:分[:秒](后端可能下发完整 datetime,避免时间列折行);纯字符串解析,运行时不用正则 */ +function hms(t: string): string { + const s = String(t || ''); + const i = s.indexOf(':'); // 第一个冒号 = 小时之后(日期段无冒号) + if (i < 1) return '—'; + const start = i >= 2 ? i - 2 : 0; // 两位小时(08:05)从 i-2 起;一位小时(8:05)从 0 起 + const p = s.slice(start, start + 8).split(':'); + const digits = (x: string | undefined) => !!x && [...x].every((ch) => ch >= '0' && ch <= '9'); + if (!digits(p[0]) || p[0].length > 2 || !digits(p[1]) || p[1].length !== 2) return '—'; + const hh = p[0].length === 1 ? '0' + p[0] : p[0]; + return p[2] && digits(p[2]) ? hh + ':' + p[1] + ':' + p[2].slice(0, 2) : hh + ':' + p[1]; } +/** 底部中块 · 仓储概览(四指标 + 出入库动态无缝滚动) */ export function WarehouseBoard({ data }: { data: DashboardData }) { - const { warehouse: w } = data; - const rows: MovementRow[] = w.movements.map((m) => ({ - id: m.id, - time: m.time, - dir: m.type === 'in' ? '入库' : '出库', - material: m.material, - qty: `${m.qty}`, - operator: m.operator, - batch: m.batch || '—', - })); - - const locationPct = - w.locationTotal > 0 ? `${Math.round((w.locationUsed / w.locationTotal) * 100)}%` : '—'; - - const columns = [ - { title: '时间', dataIndex: 'time' }, - { - title: '方向', - dataIndex: 'dir', - render: (dir: string) => ( - {dir} - ), - }, - { title: '物料名称', dataIndex: 'material' }, - { title: '数量', dataIndex: 'qty' }, - { title: '批次', dataIndex: 'batch', width: 140 }, - { title: '操作人', dataIndex: 'operator' }, - ]; + const w = data.warehouse; + const rows = w.movements ?? []; + const locPct = w.locationTotal > 0 ? `${Math.round((w.locationUsed / w.locationTotal) * 100)}%` : '—'; return ( -
-
- - - - - - - -
- - -
-
- - -
- 已用 {w.locationUsed} / 共 {w.locationTotal} -
-
+
+
+ 仓储概览 + 库位 · 今日出入库
- - -
- - +
+ {/* 四指标一行 */} +
+ + + +
- - - 暂无出入库记录} - /> - +
+ 出入库动态 + 待入库检 {dash0(w.pendingInbound)} · 待送达 {dash0(w.pendingOutbound)} +
+ + + {rows.map((m) => ( +
+ {hms(m.time)} + {m.type === 'in' ? '入库' : '出库'} + + {m.material || '—'} + + {dash0(m.qty)} + + {m.operator || '—'} + +
+ ))} +
+ ); } -function TextStat({ value, label, color }: { value: number; label: string; color: string }) { +/** 空指标显示 — 而非 0(大屏口径:没数据就是没数据,不显示一排 0) */ +export function dash0(v: number | undefined | null): string | number { + if (v === undefined || v === null || Number.isNaN(v)) return '—'; + return v; +} + +function Metric({ label, value, unit, color }: { label: string; value: string | number; unit: string; color: string }) { return ( -
-
{value}
-
{label}
+
+
+ {label} +
+
+ {value} +
+
+ {unit} +
); } - -function BigNumber({ - value, - unit, - color, -}: { - value: number | string; - unit: string; - color: string; -}) { - return ( -
- {value} - {unit} -
- ); -} \ No newline at end of file diff --git a/bj_power_dashboard/src/services/dashboardService.ts b/bj_power_dashboard/src/services/dashboardService.ts index cd0aa2d..a54aef9 100644 --- a/bj_power_dashboard/src/services/dashboardService.ts +++ b/bj_power_dashboard/src/services/dashboardService.ts @@ -179,7 +179,8 @@ export class DashboardDataService { const lines = block.split('\n'); const dataLine = lines.find((l) => l.startsWith('data:')); if (!dataLine) continue; - const payload = dataLine.replace(/^data:\s*/, '').trim(); + // 行 180 已确认 "data:" 前缀:切片剥掉固定 5 字符,trim 收掉前后空白(不用正则) + const payload = dataLine.slice(5).trim(); if (!payload) continue; // 事件驱动:业务数据落库后后端广播 dashboard.updated(空载荷), // 收到即拉一次最新快照,实时性优于轮询周期。 @@ -232,6 +233,32 @@ function isEmpty(d: DashboardData): boolean { return !d.progress?.orderNo && (d.production?.outputToday ?? 0) === 0; } +/** 门口看板启动配置(MES 基础设置页维护,保存即生效;看板端轮询跟随) */ +export interface BoardConfig { + /** 标题文字;空 = 不显示标题 */ + title: string; + /** 语音播报开关 */ + voiceOn: boolean; +} + +/** 拉取门口看板配置(GET /api/internal/dashboard/config,X-API-TOKEN) */ +export async function fetchBoardConfig(): Promise { + const res = await fetch(`${config.mesBaseUrl}/api/internal/dashboard/config`, { + headers: { 'X-API-TOKEN': config.internalToken }, + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const j = await res.json(); + const d = ( + j && typeof j === 'object' && 'data' in (j as Record) + ? (j as Record).data + : j + ) as Partial; + return { + title: typeof d.title === 'string' ? d.title : '', + voiceOn: d.voiceOn !== false, + }; +} + /** 后端响应统一为 {code,message,data},取 data 层;SSE 心跳推的是裸对象,两种都兼容 */ function unwrapPayload(j: unknown): unknown { if (j && typeof j === 'object' && !Array.isArray(j)) { @@ -299,6 +326,14 @@ function normalize(raw: Partial): DashboardData { }, traces: raw.traces ?? [], trends: raw.trends ?? { production: [] }, + points: { + mock: raw.points?.mock ?? false, + main: raw.points?.main ?? [], + dock: raw.points?.dock ?? [], + transit: raw.points?.transit ?? [], + }, + agv: raw.agv ?? [], + events: raw.events ?? [], alarms: raw.alarms ?? [], isDemo: false, }; diff --git a/bj_power_dashboard/src/types.ts b/bj_power_dashboard/src/types.ts index fa32d53..e5ab30d 100644 --- a/bj_power_dashboard/src/types.ts +++ b/bj_power_dashboard/src/types.ts @@ -33,6 +33,50 @@ export interface Station { currentSn?: string; /** 当前作业人(责任到人) */ currentOperator?: string; + /** 最近一道工序名 */ + currentProcess?: string; + /** 当天已停单(仅图标提示,不渲染刺眼文字) */ + paused?: boolean; + pauseReason?: string; +} + +/** 产线点位态(主线位置 / 接驳台) */ +export interface LinePoint { + code: string; + has: boolean; +} + +/** 在途路径指令(源→目标,如 G9→C13) */ +export interface InTransit { + src: string; + tgt: string; +} + +export interface PointsState { + /** PLC 未接真实设备时为 true,角落标「模拟数据」 */ + mock: boolean; + /** 15 个主线位置 C1..C15 */ + main: LinePoint[]; + /** 21 个接驳台 G1L..G10R + JBT21 */ + dock: LinePoint[]; + transit: InTransit[]; +} + +/** AGV 实时搬运任务(真实备料任务驱动,无假坐标) */ +export interface AgvRobot { + code: string; + status: 'idle' | 'loading' | 'moving' | 'done' | 'waiting' | string; + from: string; + to: string; + carrier: string; + taskNo: string; +} + +/** 实时事件流条目(后端已过滤负面结果项) */ +export interface EventItem { + time: string; + text: string; + level: string; } /** 生产 / 产能总览(屏1 KPI) */ @@ -207,6 +251,12 @@ export interface DashboardData { /** 追溯轮播数据(最近完工工件) */ traces: TraceItem[]; trends: TrendData; + /** 产线点位态(2D 地图真实亮灭 + 流光) */ + points: PointsState; + /** AGV 实时搬运任务 */ + agv: AgvRobot[]; + /** 实时事件流(无缝滚动) */ + events: EventItem[]; /** 报警项(仅用于语音播报,屏幕不渲染) */ alarms: AlarmItem[]; /** 是否演示数据:真实业务数据为空时自动降级,角落低调标注 */ diff --git a/bj_power_dashboard/tsconfig.tsbuildinfo b/bj_power_dashboard/tsconfig.tsbuildinfo index 9a1e856..63d605c 100644 --- a/bj_power_dashboard/tsconfig.tsbuildinfo +++ b/bj_power_dashboard/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/config.ts","./src/main.tsx","./src/mock.ts","./src/types.ts","./src/vite-env.d.ts","./src/components/echart.tsx","./src/components/errorretry.tsx","./src/components/materialquery.tsx","./src/hooks/usedashboarddata.ts","./src/hooks/usespeechalarm.ts","./src/pages/linemodel.tsx","./src/pages/productionboard.tsx","./src/pages/warehouseboard.tsx","./src/services/dashboardservice.ts","./vite.config.ts"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/config.ts","./src/main.tsx","./src/mock.ts","./src/types.ts","./src/vite-env.d.ts","./src/components/echart.tsx","./src/components/errorretry.tsx","./src/components/kpistrip.tsx","./src/components/materialquery.tsx","./src/components/scrolllist.tsx","./src/hooks/usedashboarddata.ts","./src/hooks/usespeechalarm.ts","./src/pages/linemodel.tsx","./src/pages/productionboard.tsx","./src/pages/sideboard.tsx","./src/pages/warehouseboard.tsx","./src/services/dashboardservice.ts","./vite.config.ts"],"version":"5.9.3"} \ No newline at end of file diff --git a/bj_power_dashboard/vite.config.ts.timestamp-1793096244782-28cd3727204d5.mjs b/bj_power_dashboard/vite.config.ts.timestamp-1793096244782-28cd3727204d5.mjs new file mode 100644 index 0000000..1b7e6bc --- /dev/null +++ b/bj_power_dashboard/vite.config.ts.timestamp-1793096244782-28cd3727204d5.mjs @@ -0,0 +1,31 @@ +// vite.config.ts +import { defineConfig } from "file:///D:/hardman/bj_power/bj_power_dashboard/node_modules/vite/dist/node/index.js"; +import react from "file:///D:/hardman/bj_power/bj_power_dashboard/node_modules/@vitejs/plugin-react/dist/index.js"; +import { fileURLToPath, URL } from "node:url"; +var __vite_injected_original_import_meta_url = "file:///D:/hardman/bj_power/bj_power_dashboard/vite.config.ts"; +var dashboardAlias = "@bj_power_dashboard"; +var vite_config_default = defineConfig({ + plugins: [react()], + resolve: { + alias: { + [dashboardAlias]: fileURLToPath(new URL("./src", __vite_injected_original_import_meta_url)) + } + }, + server: { + port: 5173, + // 大屏项目:启动后自动拉起浏览器,避免每次手动输地址 + open: true, + host: true, + proxy: { + // 开发环境代理到 MES(实际端口 8888,早期写 8000 导致连不上) + "/api": { + target: process.env.VITE_MES_BASE_URL || "http://127.0.0.1:8888", + changeOrigin: true + } + } + } +}); +export { + vite_config_default as default +}; +//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCJEOlxcXFxoYXJkbWFuXFxcXGJqX3Bvd2VyXFxcXGJqX3Bvd2VyX2Rhc2hib2FyZFwiO2NvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9maWxlbmFtZSA9IFwiRDpcXFxcaGFyZG1hblxcXFxial9wb3dlclxcXFxial9wb3dlcl9kYXNoYm9hcmRcXFxcdml0ZS5jb25maWcudHNcIjtjb25zdCBfX3ZpdGVfaW5qZWN0ZWRfb3JpZ2luYWxfaW1wb3J0X21ldGFfdXJsID0gXCJmaWxlOi8vL0Q6L2hhcmRtYW4vYmpfcG93ZXIvYmpfcG93ZXJfZGFzaGJvYXJkL3ZpdGUuY29uZmlnLnRzXCI7aW1wb3J0IHsgZGVmaW5lQ29uZmlnIH0gZnJvbSAndml0ZSc7XG5pbXBvcnQgcmVhY3QgZnJvbSAnQHZpdGVqcy9wbHVnaW4tcmVhY3QnO1xuaW1wb3J0IHsgZmlsZVVSTFRvUGF0aCwgVVJMIH0gZnJvbSAnbm9kZTp1cmwnO1xuXG4vLyBcdThCQTkgaW1wb3J0IFx1OERFRlx1NUY4NFx1NEUwRVx1OTg3OVx1NzZFRVx1NjU4N1x1NEVGNlx1NTkzOVx1NTQwRFx1RkYwOGJqX3Bvd2VyX2Rhc2hib2FyZFx1RkYwOVx1NUJGOVx1OUY1MFxuY29uc3QgZGFzaGJvYXJkQWxpYXMgPSAnQGJqX3Bvd2VyX2Rhc2hib2FyZCc7XG5cbmV4cG9ydCBkZWZhdWx0IGRlZmluZUNvbmZpZyh7XG4gIHBsdWdpbnM6IFtyZWFjdCgpXSxcbiAgcmVzb2x2ZToge1xuICAgIGFsaWFzOiB7XG4gICAgICBbZGFzaGJvYXJkQWxpYXNdOiBmaWxlVVJMVG9QYXRoKG5ldyBVUkwoJy4vc3JjJywgaW1wb3J0Lm1ldGEudXJsKSksXG4gICAgfSxcbiAgfSxcbiAgc2VydmVyOiB7XG4gICAgcG9ydDogNTE3MyxcbiAgICAvLyBcdTU5MjdcdTVDNEZcdTk4NzlcdTc2RUVcdUZGMUFcdTU0MkZcdTUyQThcdTU0MEVcdTgxRUFcdTUyQThcdTYyQzlcdThENzdcdTZENEZcdTg5QzhcdTU2NjhcdUZGMENcdTkwN0ZcdTUxNERcdTZCQ0ZcdTZCMjFcdTYyNEJcdTUyQThcdThGOTNcdTU3MzBcdTU3NDBcbiAgICBvcGVuOiB0cnVlLFxuICAgIGhvc3Q6IHRydWUsXG4gICAgcHJveHk6IHtcbiAgICAgIC8vIFx1NUYwMFx1NTNEMVx1NzNBRlx1NTg4M1x1NEVFM1x1NzQwNlx1NTIzMCBNRVNcdUZGMDhcdTVCOUVcdTk2NDVcdTdBRUZcdTUzRTMgODg4OFx1RkYwQ1x1NjVFOVx1NjcxRlx1NTE5OSA4MDAwIFx1NUJGQ1x1ODFGNFx1OEZERVx1NEUwRFx1NEUwQVx1RkYwOVxuICAgICAgJy9hcGknOiB7XG4gICAgICAgIHRhcmdldDogcHJvY2Vzcy5lbnYuVklURV9NRVNfQkFTRV9VUkwgfHwgJ2h0dHA6Ly8xMjcuMC4wLjE6ODg4OCcsXG4gICAgICAgIGNoYW5nZU9yaWdpbjogdHJ1ZSxcbiAgICAgIH0sXG4gICAgfSxcbiAgfSxcbn0pOyJdLAogICJtYXBwaW5ncyI6ICI7QUFBNFMsU0FBUyxvQkFBb0I7QUFDelUsT0FBTyxXQUFXO0FBQ2xCLFNBQVMsZUFBZSxXQUFXO0FBRndKLElBQU0sMkNBQTJDO0FBSzVPLElBQU0saUJBQWlCO0FBRXZCLElBQU8sc0JBQVEsYUFBYTtBQUFBLEVBQzFCLFNBQVMsQ0FBQyxNQUFNLENBQUM7QUFBQSxFQUNqQixTQUFTO0FBQUEsSUFDUCxPQUFPO0FBQUEsTUFDTCxDQUFDLGNBQWMsR0FBRyxjQUFjLElBQUksSUFBSSxTQUFTLHdDQUFlLENBQUM7QUFBQSxJQUNuRTtBQUFBLEVBQ0Y7QUFBQSxFQUNBLFFBQVE7QUFBQSxJQUNOLE1BQU07QUFBQTtBQUFBLElBRU4sTUFBTTtBQUFBLElBQ04sTUFBTTtBQUFBLElBQ04sT0FBTztBQUFBO0FBQUEsTUFFTCxRQUFRO0FBQUEsUUFDTixRQUFRLFFBQVEsSUFBSSxxQkFBcUI7QUFBQSxRQUN6QyxjQUFjO0FBQUEsTUFDaEI7QUFBQSxJQUNGO0FBQUEsRUFDRjtBQUNGLENBQUM7IiwKICAibmFtZXMiOiBbXQp9Cg== diff --git a/bj_power_mes/ent/backuprecord.go b/bj_power_mes/ent/backuprecord.go new file mode 100644 index 0000000..9b6252b --- /dev/null +++ b/bj_power_mes/ent/backuprecord.go @@ -0,0 +1,202 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/backuprecord" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖 +type BackupRecord struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 备份执行时刻(unix秒) + ExecutedAt int64 `json:"executedAt,omitempty"` + // 备份范围开始(unix秒,含) + RangeStart int64 `json:"rangeStart,omitempty"` + // 备份范围结束(unix秒,含) + RangeEnd int64 `json:"rangeEnd,omitempty"` + // 备份包(zip)在目标盘的完整路径 + BackupPath string `json:"backupPath,omitempty"` + // 备份包总字节数 + TotalSize int64 `json:"totalSize,omitempty"` + // 各数据项及大小(JSON数组:[{name,rows,bytes}]) + ItemsJSON string `json:"itemsJSON,omitempty"` + // success/failed/partial + Status string `json:"status,omitempty"` + // 操作人 + Operator string `json:"operator,omitempty"` + // 备份包校验和(sha256,基于 manifest) + Checksum string `json:"checksum,omitempty"` + // 写入方 mes/wms + Scope string `json:"scope,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BackupRecord) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case backuprecord.FieldID, backuprecord.FieldExecutedAt, backuprecord.FieldRangeStart, backuprecord.FieldRangeEnd, backuprecord.FieldTotalSize: + values[i] = new(sql.NullInt64) + case backuprecord.FieldBackupPath, backuprecord.FieldItemsJSON, backuprecord.FieldStatus, backuprecord.FieldOperator, backuprecord.FieldChecksum, backuprecord.FieldScope: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BackupRecord fields. +func (_m *BackupRecord) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case backuprecord.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case backuprecord.FieldExecutedAt: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field executedAt", values[i]) + } else if value.Valid { + _m.ExecutedAt = value.Int64 + } + case backuprecord.FieldRangeStart: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field rangeStart", values[i]) + } else if value.Valid { + _m.RangeStart = value.Int64 + } + case backuprecord.FieldRangeEnd: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field rangeEnd", values[i]) + } else if value.Valid { + _m.RangeEnd = value.Int64 + } + case backuprecord.FieldBackupPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field backupPath", values[i]) + } else if value.Valid { + _m.BackupPath = value.String + } + case backuprecord.FieldTotalSize: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field totalSize", values[i]) + } else if value.Valid { + _m.TotalSize = value.Int64 + } + case backuprecord.FieldItemsJSON: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field itemsJSON", values[i]) + } else if value.Valid { + _m.ItemsJSON = value.String + } + case backuprecord.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = value.String + } + case backuprecord.FieldOperator: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field operator", values[i]) + } else if value.Valid { + _m.Operator = value.String + } + case backuprecord.FieldChecksum: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field checksum", values[i]) + } else if value.Valid { + _m.Checksum = value.String + } + case backuprecord.FieldScope: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope", values[i]) + } else if value.Valid { + _m.Scope = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BackupRecord. +// This includes values selected through modifiers, order, etc. +func (_m *BackupRecord) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this BackupRecord. +// Note that you need to call BackupRecord.Unwrap() before calling this method if this BackupRecord +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BackupRecord) Update() *BackupRecordUpdateOne { + return NewBackupRecordClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BackupRecord entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *BackupRecord) Unwrap() *BackupRecord { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: BackupRecord is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BackupRecord) String() string { + var builder strings.Builder + builder.WriteString("BackupRecord(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("executedAt=") + builder.WriteString(fmt.Sprintf("%v", _m.ExecutedAt)) + builder.WriteString(", ") + builder.WriteString("rangeStart=") + builder.WriteString(fmt.Sprintf("%v", _m.RangeStart)) + builder.WriteString(", ") + builder.WriteString("rangeEnd=") + builder.WriteString(fmt.Sprintf("%v", _m.RangeEnd)) + builder.WriteString(", ") + builder.WriteString("backupPath=") + builder.WriteString(_m.BackupPath) + builder.WriteString(", ") + builder.WriteString("totalSize=") + builder.WriteString(fmt.Sprintf("%v", _m.TotalSize)) + builder.WriteString(", ") + builder.WriteString("itemsJSON=") + builder.WriteString(_m.ItemsJSON) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(_m.Status) + builder.WriteString(", ") + builder.WriteString("operator=") + builder.WriteString(_m.Operator) + builder.WriteString(", ") + builder.WriteString("checksum=") + builder.WriteString(_m.Checksum) + builder.WriteString(", ") + builder.WriteString("scope=") + builder.WriteString(_m.Scope) + builder.WriteByte(')') + return builder.String() +} + +// BackupRecords is a parsable slice of BackupRecord. +type BackupRecords []*BackupRecord diff --git a/bj_power_mes/ent/backuprecord/backuprecord.go b/bj_power_mes/ent/backuprecord/backuprecord.go new file mode 100644 index 0000000..7a4c7f2 --- /dev/null +++ b/bj_power_mes/ent/backuprecord/backuprecord.go @@ -0,0 +1,144 @@ +// Code generated by ent, DO NOT EDIT. + +package backuprecord + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the backuprecord type in the database. + Label = "backup_record" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldExecutedAt holds the string denoting the executedat field in the database. + FieldExecutedAt = "executed_at" + // FieldRangeStart holds the string denoting the rangestart field in the database. + FieldRangeStart = "range_start" + // FieldRangeEnd holds the string denoting the rangeend field in the database. + FieldRangeEnd = "range_end" + // FieldBackupPath holds the string denoting the backuppath field in the database. + FieldBackupPath = "backup_path" + // FieldTotalSize holds the string denoting the totalsize field in the database. + FieldTotalSize = "total_size" + // FieldItemsJSON holds the string denoting the itemsjson field in the database. + FieldItemsJSON = "items_json" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldOperator holds the string denoting the operator field in the database. + FieldOperator = "operator" + // FieldChecksum holds the string denoting the checksum field in the database. + FieldChecksum = "checksum" + // FieldScope holds the string denoting the scope field in the database. + FieldScope = "scope" + // Table holds the table name of the backuprecord in the database. + Table = "backup_record" +) + +// Columns holds all SQL columns for backuprecord fields. +var Columns = []string{ + FieldID, + FieldExecutedAt, + FieldRangeStart, + FieldRangeEnd, + FieldBackupPath, + FieldTotalSize, + FieldItemsJSON, + FieldStatus, + FieldOperator, + FieldChecksum, + FieldScope, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultExecutedAt holds the default value on creation for the "executedAt" field. + DefaultExecutedAt func() int64 + // DefaultTotalSize holds the default value on creation for the "totalSize" field. + DefaultTotalSize int64 + // DefaultStatus holds the default value on creation for the "status" field. + DefaultStatus string + // StatusValidator is a validator for the "status" field. It is called by the builders before save. + StatusValidator func(string) error + // DefaultOperator holds the default value on creation for the "operator" field. + DefaultOperator string + // OperatorValidator is a validator for the "operator" field. It is called by the builders before save. + OperatorValidator func(string) error + // DefaultChecksum holds the default value on creation for the "checksum" field. + DefaultChecksum string + // ChecksumValidator is a validator for the "checksum" field. It is called by the builders before save. + ChecksumValidator func(string) error + // DefaultScope holds the default value on creation for the "scope" field. + DefaultScope string + // ScopeValidator is a validator for the "scope" field. It is called by the builders before save. + ScopeValidator func(string) error + // IDValidator is a validator for the "id" field. It is called by the builders before save. + IDValidator func(int) error +) + +// OrderOption defines the ordering options for the BackupRecord queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByExecutedAt orders the results by the executedAt field. +func ByExecutedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExecutedAt, opts...).ToFunc() +} + +// ByRangeStart orders the results by the rangeStart field. +func ByRangeStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRangeStart, opts...).ToFunc() +} + +// ByRangeEnd orders the results by the rangeEnd field. +func ByRangeEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRangeEnd, opts...).ToFunc() +} + +// ByBackupPath orders the results by the backupPath field. +func ByBackupPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBackupPath, opts...).ToFunc() +} + +// ByTotalSize orders the results by the totalSize field. +func ByTotalSize(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalSize, opts...).ToFunc() +} + +// ByItemsJSON orders the results by the itemsJSON field. +func ByItemsJSON(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldItemsJSON, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByOperator orders the results by the operator field. +func ByOperator(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperator, opts...).ToFunc() +} + +// ByChecksum orders the results by the checksum field. +func ByChecksum(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChecksum, opts...).ToFunc() +} + +// ByScope orders the results by the scope field. +func ByScope(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScope, opts...).ToFunc() +} diff --git a/bj_power_mes/ent/backuprecord/where.go b/bj_power_mes/ent/backuprecord/where.go new file mode 100644 index 0000000..989194c --- /dev/null +++ b/bj_power_mes/ent/backuprecord/where.go @@ -0,0 +1,669 @@ +// Code generated by ent, DO NOT EDIT. + +package backuprecord + +import ( + "bj_power_mes/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldID, id)) +} + +// ExecutedAt applies equality check predicate on the "executedAt" field. It's identical to ExecutedAtEQ. +func ExecutedAt(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldExecutedAt, v)) +} + +// RangeStart applies equality check predicate on the "rangeStart" field. It's identical to RangeStartEQ. +func RangeStart(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeStart, v)) +} + +// RangeEnd applies equality check predicate on the "rangeEnd" field. It's identical to RangeEndEQ. +func RangeEnd(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeEnd, v)) +} + +// BackupPath applies equality check predicate on the "backupPath" field. It's identical to BackupPathEQ. +func BackupPath(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldBackupPath, v)) +} + +// TotalSize applies equality check predicate on the "totalSize" field. It's identical to TotalSizeEQ. +func TotalSize(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldTotalSize, v)) +} + +// ItemsJSON applies equality check predicate on the "itemsJSON" field. It's identical to ItemsJSONEQ. +func ItemsJSON(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldItemsJSON, v)) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldStatus, v)) +} + +// Operator applies equality check predicate on the "operator" field. It's identical to OperatorEQ. +func Operator(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldOperator, v)) +} + +// Checksum applies equality check predicate on the "checksum" field. It's identical to ChecksumEQ. +func Checksum(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldChecksum, v)) +} + +// Scope applies equality check predicate on the "scope" field. It's identical to ScopeEQ. +func Scope(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldScope, v)) +} + +// ExecutedAtEQ applies the EQ predicate on the "executedAt" field. +func ExecutedAtEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldExecutedAt, v)) +} + +// ExecutedAtNEQ applies the NEQ predicate on the "executedAt" field. +func ExecutedAtNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldExecutedAt, v)) +} + +// ExecutedAtIn applies the In predicate on the "executedAt" field. +func ExecutedAtIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldExecutedAt, vs...)) +} + +// ExecutedAtNotIn applies the NotIn predicate on the "executedAt" field. +func ExecutedAtNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldExecutedAt, vs...)) +} + +// ExecutedAtGT applies the GT predicate on the "executedAt" field. +func ExecutedAtGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldExecutedAt, v)) +} + +// ExecutedAtGTE applies the GTE predicate on the "executedAt" field. +func ExecutedAtGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldExecutedAt, v)) +} + +// ExecutedAtLT applies the LT predicate on the "executedAt" field. +func ExecutedAtLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldExecutedAt, v)) +} + +// ExecutedAtLTE applies the LTE predicate on the "executedAt" field. +func ExecutedAtLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldExecutedAt, v)) +} + +// RangeStartEQ applies the EQ predicate on the "rangeStart" field. +func RangeStartEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeStart, v)) +} + +// RangeStartNEQ applies the NEQ predicate on the "rangeStart" field. +func RangeStartNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldRangeStart, v)) +} + +// RangeStartIn applies the In predicate on the "rangeStart" field. +func RangeStartIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldRangeStart, vs...)) +} + +// RangeStartNotIn applies the NotIn predicate on the "rangeStart" field. +func RangeStartNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldRangeStart, vs...)) +} + +// RangeStartGT applies the GT predicate on the "rangeStart" field. +func RangeStartGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldRangeStart, v)) +} + +// RangeStartGTE applies the GTE predicate on the "rangeStart" field. +func RangeStartGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldRangeStart, v)) +} + +// RangeStartLT applies the LT predicate on the "rangeStart" field. +func RangeStartLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldRangeStart, v)) +} + +// RangeStartLTE applies the LTE predicate on the "rangeStart" field. +func RangeStartLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldRangeStart, v)) +} + +// RangeEndEQ applies the EQ predicate on the "rangeEnd" field. +func RangeEndEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeEnd, v)) +} + +// RangeEndNEQ applies the NEQ predicate on the "rangeEnd" field. +func RangeEndNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldRangeEnd, v)) +} + +// RangeEndIn applies the In predicate on the "rangeEnd" field. +func RangeEndIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldRangeEnd, vs...)) +} + +// RangeEndNotIn applies the NotIn predicate on the "rangeEnd" field. +func RangeEndNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldRangeEnd, vs...)) +} + +// RangeEndGT applies the GT predicate on the "rangeEnd" field. +func RangeEndGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldRangeEnd, v)) +} + +// RangeEndGTE applies the GTE predicate on the "rangeEnd" field. +func RangeEndGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldRangeEnd, v)) +} + +// RangeEndLT applies the LT predicate on the "rangeEnd" field. +func RangeEndLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldRangeEnd, v)) +} + +// RangeEndLTE applies the LTE predicate on the "rangeEnd" field. +func RangeEndLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldRangeEnd, v)) +} + +// BackupPathEQ applies the EQ predicate on the "backupPath" field. +func BackupPathEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldBackupPath, v)) +} + +// BackupPathNEQ applies the NEQ predicate on the "backupPath" field. +func BackupPathNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldBackupPath, v)) +} + +// BackupPathIn applies the In predicate on the "backupPath" field. +func BackupPathIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldBackupPath, vs...)) +} + +// BackupPathNotIn applies the NotIn predicate on the "backupPath" field. +func BackupPathNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldBackupPath, vs...)) +} + +// BackupPathGT applies the GT predicate on the "backupPath" field. +func BackupPathGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldBackupPath, v)) +} + +// BackupPathGTE applies the GTE predicate on the "backupPath" field. +func BackupPathGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldBackupPath, v)) +} + +// BackupPathLT applies the LT predicate on the "backupPath" field. +func BackupPathLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldBackupPath, v)) +} + +// BackupPathLTE applies the LTE predicate on the "backupPath" field. +func BackupPathLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldBackupPath, v)) +} + +// BackupPathContains applies the Contains predicate on the "backupPath" field. +func BackupPathContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldBackupPath, v)) +} + +// BackupPathHasPrefix applies the HasPrefix predicate on the "backupPath" field. +func BackupPathHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldBackupPath, v)) +} + +// BackupPathHasSuffix applies the HasSuffix predicate on the "backupPath" field. +func BackupPathHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldBackupPath, v)) +} + +// BackupPathEqualFold applies the EqualFold predicate on the "backupPath" field. +func BackupPathEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldBackupPath, v)) +} + +// BackupPathContainsFold applies the ContainsFold predicate on the "backupPath" field. +func BackupPathContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldBackupPath, v)) +} + +// TotalSizeEQ applies the EQ predicate on the "totalSize" field. +func TotalSizeEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldTotalSize, v)) +} + +// TotalSizeNEQ applies the NEQ predicate on the "totalSize" field. +func TotalSizeNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldTotalSize, v)) +} + +// TotalSizeIn applies the In predicate on the "totalSize" field. +func TotalSizeIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldTotalSize, vs...)) +} + +// TotalSizeNotIn applies the NotIn predicate on the "totalSize" field. +func TotalSizeNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldTotalSize, vs...)) +} + +// TotalSizeGT applies the GT predicate on the "totalSize" field. +func TotalSizeGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldTotalSize, v)) +} + +// TotalSizeGTE applies the GTE predicate on the "totalSize" field. +func TotalSizeGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldTotalSize, v)) +} + +// TotalSizeLT applies the LT predicate on the "totalSize" field. +func TotalSizeLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldTotalSize, v)) +} + +// TotalSizeLTE applies the LTE predicate on the "totalSize" field. +func TotalSizeLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldTotalSize, v)) +} + +// ItemsJSONEQ applies the EQ predicate on the "itemsJSON" field. +func ItemsJSONEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldItemsJSON, v)) +} + +// ItemsJSONNEQ applies the NEQ predicate on the "itemsJSON" field. +func ItemsJSONNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldItemsJSON, v)) +} + +// ItemsJSONIn applies the In predicate on the "itemsJSON" field. +func ItemsJSONIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldItemsJSON, vs...)) +} + +// ItemsJSONNotIn applies the NotIn predicate on the "itemsJSON" field. +func ItemsJSONNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldItemsJSON, vs...)) +} + +// ItemsJSONGT applies the GT predicate on the "itemsJSON" field. +func ItemsJSONGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldItemsJSON, v)) +} + +// ItemsJSONGTE applies the GTE predicate on the "itemsJSON" field. +func ItemsJSONGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldItemsJSON, v)) +} + +// ItemsJSONLT applies the LT predicate on the "itemsJSON" field. +func ItemsJSONLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldItemsJSON, v)) +} + +// ItemsJSONLTE applies the LTE predicate on the "itemsJSON" field. +func ItemsJSONLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldItemsJSON, v)) +} + +// ItemsJSONContains applies the Contains predicate on the "itemsJSON" field. +func ItemsJSONContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldItemsJSON, v)) +} + +// ItemsJSONHasPrefix applies the HasPrefix predicate on the "itemsJSON" field. +func ItemsJSONHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldItemsJSON, v)) +} + +// ItemsJSONHasSuffix applies the HasSuffix predicate on the "itemsJSON" field. +func ItemsJSONHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldItemsJSON, v)) +} + +// ItemsJSONEqualFold applies the EqualFold predicate on the "itemsJSON" field. +func ItemsJSONEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldItemsJSON, v)) +} + +// ItemsJSONContainsFold applies the ContainsFold predicate on the "itemsJSON" field. +func ItemsJSONContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldItemsJSON, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldStatus, vs...)) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldStatus, v)) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldStatus, v)) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldStatus, v)) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldStatus, v)) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldStatus, v)) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldStatus, v)) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldStatus, v)) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldStatus, v)) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldStatus, v)) +} + +// OperatorEQ applies the EQ predicate on the "operator" field. +func OperatorEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldOperator, v)) +} + +// OperatorNEQ applies the NEQ predicate on the "operator" field. +func OperatorNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldOperator, v)) +} + +// OperatorIn applies the In predicate on the "operator" field. +func OperatorIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldOperator, vs...)) +} + +// OperatorNotIn applies the NotIn predicate on the "operator" field. +func OperatorNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldOperator, vs...)) +} + +// OperatorGT applies the GT predicate on the "operator" field. +func OperatorGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldOperator, v)) +} + +// OperatorGTE applies the GTE predicate on the "operator" field. +func OperatorGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldOperator, v)) +} + +// OperatorLT applies the LT predicate on the "operator" field. +func OperatorLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldOperator, v)) +} + +// OperatorLTE applies the LTE predicate on the "operator" field. +func OperatorLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldOperator, v)) +} + +// OperatorContains applies the Contains predicate on the "operator" field. +func OperatorContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldOperator, v)) +} + +// OperatorHasPrefix applies the HasPrefix predicate on the "operator" field. +func OperatorHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldOperator, v)) +} + +// OperatorHasSuffix applies the HasSuffix predicate on the "operator" field. +func OperatorHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldOperator, v)) +} + +// OperatorEqualFold applies the EqualFold predicate on the "operator" field. +func OperatorEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldOperator, v)) +} + +// OperatorContainsFold applies the ContainsFold predicate on the "operator" field. +func OperatorContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldOperator, v)) +} + +// ChecksumEQ applies the EQ predicate on the "checksum" field. +func ChecksumEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldChecksum, v)) +} + +// ChecksumNEQ applies the NEQ predicate on the "checksum" field. +func ChecksumNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldChecksum, v)) +} + +// ChecksumIn applies the In predicate on the "checksum" field. +func ChecksumIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldChecksum, vs...)) +} + +// ChecksumNotIn applies the NotIn predicate on the "checksum" field. +func ChecksumNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldChecksum, vs...)) +} + +// ChecksumGT applies the GT predicate on the "checksum" field. +func ChecksumGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldChecksum, v)) +} + +// ChecksumGTE applies the GTE predicate on the "checksum" field. +func ChecksumGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldChecksum, v)) +} + +// ChecksumLT applies the LT predicate on the "checksum" field. +func ChecksumLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldChecksum, v)) +} + +// ChecksumLTE applies the LTE predicate on the "checksum" field. +func ChecksumLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldChecksum, v)) +} + +// ChecksumContains applies the Contains predicate on the "checksum" field. +func ChecksumContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldChecksum, v)) +} + +// ChecksumHasPrefix applies the HasPrefix predicate on the "checksum" field. +func ChecksumHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldChecksum, v)) +} + +// ChecksumHasSuffix applies the HasSuffix predicate on the "checksum" field. +func ChecksumHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldChecksum, v)) +} + +// ChecksumEqualFold applies the EqualFold predicate on the "checksum" field. +func ChecksumEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldChecksum, v)) +} + +// ChecksumContainsFold applies the ContainsFold predicate on the "checksum" field. +func ChecksumContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldChecksum, v)) +} + +// ScopeEQ applies the EQ predicate on the "scope" field. +func ScopeEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldScope, v)) +} + +// ScopeNEQ applies the NEQ predicate on the "scope" field. +func ScopeNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldScope, v)) +} + +// ScopeIn applies the In predicate on the "scope" field. +func ScopeIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldScope, vs...)) +} + +// ScopeNotIn applies the NotIn predicate on the "scope" field. +func ScopeNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldScope, vs...)) +} + +// ScopeGT applies the GT predicate on the "scope" field. +func ScopeGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldScope, v)) +} + +// ScopeGTE applies the GTE predicate on the "scope" field. +func ScopeGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldScope, v)) +} + +// ScopeLT applies the LT predicate on the "scope" field. +func ScopeLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldScope, v)) +} + +// ScopeLTE applies the LTE predicate on the "scope" field. +func ScopeLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldScope, v)) +} + +// ScopeContains applies the Contains predicate on the "scope" field. +func ScopeContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldScope, v)) +} + +// ScopeHasPrefix applies the HasPrefix predicate on the "scope" field. +func ScopeHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldScope, v)) +} + +// ScopeHasSuffix applies the HasSuffix predicate on the "scope" field. +func ScopeHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldScope, v)) +} + +// ScopeEqualFold applies the EqualFold predicate on the "scope" field. +func ScopeEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldScope, v)) +} + +// ScopeContainsFold applies the ContainsFold predicate on the "scope" field. +func ScopeContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldScope, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.NotPredicates(p)) +} diff --git a/bj_power_mes/ent/backuprecord_create.go b/bj_power_mes/ent/backuprecord_create.go new file mode 100644 index 0000000..3d45db6 --- /dev/null +++ b/bj_power_mes/ent/backuprecord_create.go @@ -0,0 +1,415 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/backuprecord" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordCreate is the builder for creating a BackupRecord entity. +type BackupRecordCreate struct { + config + mutation *BackupRecordMutation + hooks []Hook +} + +// SetExecutedAt sets the "executedAt" field. +func (_c *BackupRecordCreate) SetExecutedAt(v int64) *BackupRecordCreate { + _c.mutation.SetExecutedAt(v) + return _c +} + +// SetNillableExecutedAt sets the "executedAt" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableExecutedAt(v *int64) *BackupRecordCreate { + if v != nil { + _c.SetExecutedAt(*v) + } + return _c +} + +// SetRangeStart sets the "rangeStart" field. +func (_c *BackupRecordCreate) SetRangeStart(v int64) *BackupRecordCreate { + _c.mutation.SetRangeStart(v) + return _c +} + +// SetRangeEnd sets the "rangeEnd" field. +func (_c *BackupRecordCreate) SetRangeEnd(v int64) *BackupRecordCreate { + _c.mutation.SetRangeEnd(v) + return _c +} + +// SetBackupPath sets the "backupPath" field. +func (_c *BackupRecordCreate) SetBackupPath(v string) *BackupRecordCreate { + _c.mutation.SetBackupPath(v) + return _c +} + +// SetTotalSize sets the "totalSize" field. +func (_c *BackupRecordCreate) SetTotalSize(v int64) *BackupRecordCreate { + _c.mutation.SetTotalSize(v) + return _c +} + +// SetNillableTotalSize sets the "totalSize" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableTotalSize(v *int64) *BackupRecordCreate { + if v != nil { + _c.SetTotalSize(*v) + } + return _c +} + +// SetItemsJSON sets the "itemsJSON" field. +func (_c *BackupRecordCreate) SetItemsJSON(v string) *BackupRecordCreate { + _c.mutation.SetItemsJSON(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *BackupRecordCreate) SetStatus(v string) *BackupRecordCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableStatus(v *string) *BackupRecordCreate { + if v != nil { + _c.SetStatus(*v) + } + return _c +} + +// SetOperator sets the "operator" field. +func (_c *BackupRecordCreate) SetOperator(v string) *BackupRecordCreate { + _c.mutation.SetOperator(v) + return _c +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableOperator(v *string) *BackupRecordCreate { + if v != nil { + _c.SetOperator(*v) + } + return _c +} + +// SetChecksum sets the "checksum" field. +func (_c *BackupRecordCreate) SetChecksum(v string) *BackupRecordCreate { + _c.mutation.SetChecksum(v) + return _c +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableChecksum(v *string) *BackupRecordCreate { + if v != nil { + _c.SetChecksum(*v) + } + return _c +} + +// SetScope sets the "scope" field. +func (_c *BackupRecordCreate) SetScope(v string) *BackupRecordCreate { + _c.mutation.SetScope(v) + return _c +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableScope(v *string) *BackupRecordCreate { + if v != nil { + _c.SetScope(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *BackupRecordCreate) SetID(v int) *BackupRecordCreate { + _c.mutation.SetID(v) + return _c +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_c *BackupRecordCreate) Mutation() *BackupRecordMutation { + return _c.mutation +} + +// Save creates the BackupRecord in the database. +func (_c *BackupRecordCreate) Save(ctx context.Context) (*BackupRecord, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BackupRecordCreate) SaveX(ctx context.Context) *BackupRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BackupRecordCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BackupRecordCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *BackupRecordCreate) defaults() { + if _, ok := _c.mutation.ExecutedAt(); !ok { + v := backuprecord.DefaultExecutedAt() + _c.mutation.SetExecutedAt(v) + } + if _, ok := _c.mutation.TotalSize(); !ok { + v := backuprecord.DefaultTotalSize + _c.mutation.SetTotalSize(v) + } + if _, ok := _c.mutation.Status(); !ok { + v := backuprecord.DefaultStatus + _c.mutation.SetStatus(v) + } + if _, ok := _c.mutation.Operator(); !ok { + v := backuprecord.DefaultOperator + _c.mutation.SetOperator(v) + } + if _, ok := _c.mutation.Checksum(); !ok { + v := backuprecord.DefaultChecksum + _c.mutation.SetChecksum(v) + } + if _, ok := _c.mutation.Scope(); !ok { + v := backuprecord.DefaultScope + _c.mutation.SetScope(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BackupRecordCreate) check() error { + if _, ok := _c.mutation.ExecutedAt(); !ok { + return &ValidationError{Name: "executedAt", err: errors.New(`ent: missing required field "BackupRecord.executedAt"`)} + } + if _, ok := _c.mutation.RangeStart(); !ok { + return &ValidationError{Name: "rangeStart", err: errors.New(`ent: missing required field "BackupRecord.rangeStart"`)} + } + if _, ok := _c.mutation.RangeEnd(); !ok { + return &ValidationError{Name: "rangeEnd", err: errors.New(`ent: missing required field "BackupRecord.rangeEnd"`)} + } + if _, ok := _c.mutation.BackupPath(); !ok { + return &ValidationError{Name: "backupPath", err: errors.New(`ent: missing required field "BackupRecord.backupPath"`)} + } + if _, ok := _c.mutation.TotalSize(); !ok { + return &ValidationError{Name: "totalSize", err: errors.New(`ent: missing required field "BackupRecord.totalSize"`)} + } + if _, ok := _c.mutation.ItemsJSON(); !ok { + return &ValidationError{Name: "itemsJSON", err: errors.New(`ent: missing required field "BackupRecord.itemsJSON"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "BackupRecord.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if _, ok := _c.mutation.Operator(); !ok { + return &ValidationError{Name: "operator", err: errors.New(`ent: missing required field "BackupRecord.operator"`)} + } + if v, ok := _c.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if _, ok := _c.mutation.Checksum(); !ok { + return &ValidationError{Name: "checksum", err: errors.New(`ent: missing required field "BackupRecord.checksum"`)} + } + if v, ok := _c.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if _, ok := _c.mutation.Scope(); !ok { + return &ValidationError{Name: "scope", err: errors.New(`ent: missing required field "BackupRecord.scope"`)} + } + if v, ok := _c.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + if v, ok := _c.mutation.ID(); ok { + if err := backuprecord.IDValidator(v); err != nil { + return &ValidationError{Name: "id", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.id": %w`, err)} + } + } + return nil +} + +func (_c *BackupRecordCreate) sqlSave(ctx context.Context) (*BackupRecord, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BackupRecordCreate) createSpec() (*BackupRecord, *sqlgraph.CreateSpec) { + var ( + _node = &BackupRecord{config: _c.config} + _spec = sqlgraph.NewCreateSpec(backuprecord.Table, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + _node.ExecutedAt = value + } + if value, ok := _c.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + _node.RangeStart = value + } + if value, ok := _c.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + _node.RangeEnd = value + } + if value, ok := _c.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + _node.BackupPath = value + } + if value, ok := _c.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + _node.TotalSize = value + } + if value, ok := _c.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + _node.ItemsJSON = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + _node.Status = value + } + if value, ok := _c.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + _node.Operator = value + } + if value, ok := _c.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + _node.Checksum = value + } + if value, ok := _c.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + _node.Scope = value + } + return _node, _spec +} + +// BackupRecordCreateBulk is the builder for creating many BackupRecord entities in bulk. +type BackupRecordCreateBulk struct { + config + err error + builders []*BackupRecordCreate +} + +// Save creates the BackupRecord entities in the database. +func (_c *BackupRecordCreateBulk) Save(ctx context.Context) ([]*BackupRecord, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BackupRecord, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BackupRecordMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil && nodes[i].ID == 0 { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *BackupRecordCreateBulk) SaveX(ctx context.Context) []*BackupRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BackupRecordCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BackupRecordCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_mes/ent/backuprecord_delete.go b/bj_power_mes/ent/backuprecord_delete.go new file mode 100644 index 0000000..5cfe1c7 --- /dev/null +++ b/bj_power_mes/ent/backuprecord_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/backuprecord" + "bj_power_mes/ent/predicate" + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordDelete is the builder for deleting a BackupRecord entity. +type BackupRecordDelete struct { + config + hooks []Hook + mutation *BackupRecordMutation +} + +// Where appends a list predicates to the BackupRecordDelete builder. +func (_d *BackupRecordDelete) Where(ps ...predicate.BackupRecord) *BackupRecordDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BackupRecordDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BackupRecordDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BackupRecordDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(backuprecord.Table, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// BackupRecordDeleteOne is the builder for deleting a single BackupRecord entity. +type BackupRecordDeleteOne struct { + _d *BackupRecordDelete +} + +// Where appends a list predicates to the BackupRecordDelete builder. +func (_d *BackupRecordDeleteOne) Where(ps ...predicate.BackupRecord) *BackupRecordDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BackupRecordDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{backuprecord.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BackupRecordDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_mes/ent/backuprecord_query.go b/bj_power_mes/ent/backuprecord_query.go new file mode 100644 index 0000000..e59cd23 --- /dev/null +++ b/bj_power_mes/ent/backuprecord_query.go @@ -0,0 +1,577 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/backuprecord" + "bj_power_mes/ent/predicate" + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordQuery is the builder for querying BackupRecord entities. +type BackupRecordQuery struct { + config + ctx *QueryContext + order []backuprecord.OrderOption + inters []Interceptor + predicates []predicate.BackupRecord + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BackupRecordQuery builder. +func (_q *BackupRecordQuery) Where(ps ...predicate.BackupRecord) *BackupRecordQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BackupRecordQuery) Limit(limit int) *BackupRecordQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BackupRecordQuery) Offset(offset int) *BackupRecordQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *BackupRecordQuery) Unique(unique bool) *BackupRecordQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BackupRecordQuery) Order(o ...backuprecord.OrderOption) *BackupRecordQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first BackupRecord entity from the query. +// Returns a *NotFoundError when no BackupRecord was found. +func (_q *BackupRecordQuery) First(ctx context.Context) (*BackupRecord, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{backuprecord.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BackupRecordQuery) FirstX(ctx context.Context) *BackupRecord { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BackupRecord ID from the query. +// Returns a *NotFoundError when no BackupRecord ID was found. +func (_q *BackupRecordQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{backuprecord.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BackupRecordQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BackupRecord entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BackupRecord entity is found. +// Returns a *NotFoundError when no BackupRecord entities are found. +func (_q *BackupRecordQuery) Only(ctx context.Context) (*BackupRecord, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{backuprecord.Label} + default: + return nil, &NotSingularError{backuprecord.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BackupRecordQuery) OnlyX(ctx context.Context) *BackupRecord { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BackupRecord ID in the query. +// Returns a *NotSingularError when more than one BackupRecord ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BackupRecordQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{backuprecord.Label} + default: + err = &NotSingularError{backuprecord.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BackupRecordQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of BackupRecords. +func (_q *BackupRecordQuery) All(ctx context.Context) ([]*BackupRecord, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BackupRecord, *BackupRecordQuery]() + return withInterceptors[[]*BackupRecord](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BackupRecordQuery) AllX(ctx context.Context) []*BackupRecord { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BackupRecord IDs. +func (_q *BackupRecordQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(backuprecord.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BackupRecordQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *BackupRecordQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*BackupRecordQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BackupRecordQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *BackupRecordQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *BackupRecordQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BackupRecordQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *BackupRecordQuery) Clone() *BackupRecordQuery { + if _q == nil { + return nil + } + return &BackupRecordQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]backuprecord.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BackupRecord{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// ExecutedAt int64 `json:"executedAt,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.BackupRecord.Query(). +// GroupBy(backuprecord.FieldExecutedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *BackupRecordQuery) GroupBy(field string, fields ...string) *BackupRecordGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BackupRecordGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = backuprecord.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// ExecutedAt int64 `json:"executedAt,omitempty"` +// } +// +// client.BackupRecord.Query(). +// Select(backuprecord.FieldExecutedAt). +// Scan(ctx, &v) +func (_q *BackupRecordQuery) Select(fields ...string) *BackupRecordSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BackupRecordSelect{BackupRecordQuery: _q} + sbuild.label = backuprecord.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BackupRecordSelect configured with the given aggregations. +func (_q *BackupRecordQuery) Aggregate(fns ...AggregateFunc) *BackupRecordSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BackupRecordQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !backuprecord.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *BackupRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BackupRecord, error) { + var ( + nodes = []*BackupRecord{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BackupRecord).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BackupRecord{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *BackupRecordQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *BackupRecordQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, backuprecord.FieldID) + for i := range fields { + if fields[i] != backuprecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *BackupRecordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(backuprecord.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = backuprecord.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *BackupRecordQuery) ForUpdate(opts ...sql.LockOption) *BackupRecordQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *BackupRecordQuery) ForShare(opts ...sql.LockOption) *BackupRecordQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *BackupRecordQuery) Modify(modifiers ...func(s *sql.Selector)) *BackupRecordSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// BackupRecordGroupBy is the group-by builder for BackupRecord entities. +type BackupRecordGroupBy struct { + selector + build *BackupRecordQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BackupRecordGroupBy) Aggregate(fns ...AggregateFunc) *BackupRecordGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BackupRecordGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BackupRecordQuery, *BackupRecordGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BackupRecordGroupBy) sqlScan(ctx context.Context, root *BackupRecordQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// BackupRecordSelect is the builder for selecting fields of BackupRecord entities. +type BackupRecordSelect struct { + *BackupRecordQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BackupRecordSelect) Aggregate(fns ...AggregateFunc) *BackupRecordSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BackupRecordSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BackupRecordQuery, *BackupRecordSelect](ctx, _s.BackupRecordQuery, _s, _s.inters, v) +} + +func (_s *BackupRecordSelect) sqlScan(ctx context.Context, root *BackupRecordQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *BackupRecordSelect) Modify(modifiers ...func(s *sql.Selector)) *BackupRecordSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/bj_power_mes/ent/backuprecord_update.go b/bj_power_mes/ent/backuprecord_update.go new file mode 100644 index 0000000..0f8291a --- /dev/null +++ b/bj_power_mes/ent/backuprecord_update.go @@ -0,0 +1,667 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_mes/ent/backuprecord" + "bj_power_mes/ent/predicate" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordUpdate is the builder for updating BackupRecord entities. +type BackupRecordUpdate struct { + config + hooks []Hook + mutation *BackupRecordMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the BackupRecordUpdate builder. +func (_u *BackupRecordUpdate) Where(ps ...predicate.BackupRecord) *BackupRecordUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetExecutedAt sets the "executedAt" field. +func (_u *BackupRecordUpdate) SetExecutedAt(v int64) *BackupRecordUpdate { + _u.mutation.ResetExecutedAt() + _u.mutation.SetExecutedAt(v) + return _u +} + +// SetNillableExecutedAt sets the "executedAt" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableExecutedAt(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetExecutedAt(*v) + } + return _u +} + +// AddExecutedAt adds value to the "executedAt" field. +func (_u *BackupRecordUpdate) AddExecutedAt(v int64) *BackupRecordUpdate { + _u.mutation.AddExecutedAt(v) + return _u +} + +// SetRangeStart sets the "rangeStart" field. +func (_u *BackupRecordUpdate) SetRangeStart(v int64) *BackupRecordUpdate { + _u.mutation.ResetRangeStart() + _u.mutation.SetRangeStart(v) + return _u +} + +// SetNillableRangeStart sets the "rangeStart" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableRangeStart(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetRangeStart(*v) + } + return _u +} + +// AddRangeStart adds value to the "rangeStart" field. +func (_u *BackupRecordUpdate) AddRangeStart(v int64) *BackupRecordUpdate { + _u.mutation.AddRangeStart(v) + return _u +} + +// SetRangeEnd sets the "rangeEnd" field. +func (_u *BackupRecordUpdate) SetRangeEnd(v int64) *BackupRecordUpdate { + _u.mutation.ResetRangeEnd() + _u.mutation.SetRangeEnd(v) + return _u +} + +// SetNillableRangeEnd sets the "rangeEnd" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableRangeEnd(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetRangeEnd(*v) + } + return _u +} + +// AddRangeEnd adds value to the "rangeEnd" field. +func (_u *BackupRecordUpdate) AddRangeEnd(v int64) *BackupRecordUpdate { + _u.mutation.AddRangeEnd(v) + return _u +} + +// SetBackupPath sets the "backupPath" field. +func (_u *BackupRecordUpdate) SetBackupPath(v string) *BackupRecordUpdate { + _u.mutation.SetBackupPath(v) + return _u +} + +// SetNillableBackupPath sets the "backupPath" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableBackupPath(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetBackupPath(*v) + } + return _u +} + +// SetTotalSize sets the "totalSize" field. +func (_u *BackupRecordUpdate) SetTotalSize(v int64) *BackupRecordUpdate { + _u.mutation.ResetTotalSize() + _u.mutation.SetTotalSize(v) + return _u +} + +// SetNillableTotalSize sets the "totalSize" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableTotalSize(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetTotalSize(*v) + } + return _u +} + +// AddTotalSize adds value to the "totalSize" field. +func (_u *BackupRecordUpdate) AddTotalSize(v int64) *BackupRecordUpdate { + _u.mutation.AddTotalSize(v) + return _u +} + +// SetItemsJSON sets the "itemsJSON" field. +func (_u *BackupRecordUpdate) SetItemsJSON(v string) *BackupRecordUpdate { + _u.mutation.SetItemsJSON(v) + return _u +} + +// SetNillableItemsJSON sets the "itemsJSON" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableItemsJSON(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetItemsJSON(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *BackupRecordUpdate) SetStatus(v string) *BackupRecordUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableStatus(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetOperator sets the "operator" field. +func (_u *BackupRecordUpdate) SetOperator(v string) *BackupRecordUpdate { + _u.mutation.SetOperator(v) + return _u +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableOperator(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetOperator(*v) + } + return _u +} + +// SetChecksum sets the "checksum" field. +func (_u *BackupRecordUpdate) SetChecksum(v string) *BackupRecordUpdate { + _u.mutation.SetChecksum(v) + return _u +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableChecksum(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetChecksum(*v) + } + return _u +} + +// SetScope sets the "scope" field. +func (_u *BackupRecordUpdate) SetScope(v string) *BackupRecordUpdate { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableScope(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_u *BackupRecordUpdate) Mutation() *BackupRecordMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BackupRecordUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BackupRecordUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BackupRecordUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BackupRecordUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BackupRecordUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if v, ok := _u.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if v, ok := _u.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if v, ok := _u.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *BackupRecordUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BackupRecordUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *BackupRecordUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedExecutedAt(); ok { + _spec.AddField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeStart(); ok { + _spec.AddField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeEnd(); ok { + _spec.AddField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + } + if value, ok := _u.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTotalSize(); ok { + _spec.AddField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + } + if value, ok := _u.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + } + if value, ok := _u.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{backuprecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BackupRecordUpdateOne is the builder for updating a single BackupRecord entity. +type BackupRecordUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BackupRecordMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetExecutedAt sets the "executedAt" field. +func (_u *BackupRecordUpdateOne) SetExecutedAt(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetExecutedAt() + _u.mutation.SetExecutedAt(v) + return _u +} + +// SetNillableExecutedAt sets the "executedAt" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableExecutedAt(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetExecutedAt(*v) + } + return _u +} + +// AddExecutedAt adds value to the "executedAt" field. +func (_u *BackupRecordUpdateOne) AddExecutedAt(v int64) *BackupRecordUpdateOne { + _u.mutation.AddExecutedAt(v) + return _u +} + +// SetRangeStart sets the "rangeStart" field. +func (_u *BackupRecordUpdateOne) SetRangeStart(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetRangeStart() + _u.mutation.SetRangeStart(v) + return _u +} + +// SetNillableRangeStart sets the "rangeStart" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableRangeStart(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetRangeStart(*v) + } + return _u +} + +// AddRangeStart adds value to the "rangeStart" field. +func (_u *BackupRecordUpdateOne) AddRangeStart(v int64) *BackupRecordUpdateOne { + _u.mutation.AddRangeStart(v) + return _u +} + +// SetRangeEnd sets the "rangeEnd" field. +func (_u *BackupRecordUpdateOne) SetRangeEnd(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetRangeEnd() + _u.mutation.SetRangeEnd(v) + return _u +} + +// SetNillableRangeEnd sets the "rangeEnd" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableRangeEnd(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetRangeEnd(*v) + } + return _u +} + +// AddRangeEnd adds value to the "rangeEnd" field. +func (_u *BackupRecordUpdateOne) AddRangeEnd(v int64) *BackupRecordUpdateOne { + _u.mutation.AddRangeEnd(v) + return _u +} + +// SetBackupPath sets the "backupPath" field. +func (_u *BackupRecordUpdateOne) SetBackupPath(v string) *BackupRecordUpdateOne { + _u.mutation.SetBackupPath(v) + return _u +} + +// SetNillableBackupPath sets the "backupPath" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableBackupPath(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetBackupPath(*v) + } + return _u +} + +// SetTotalSize sets the "totalSize" field. +func (_u *BackupRecordUpdateOne) SetTotalSize(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetTotalSize() + _u.mutation.SetTotalSize(v) + return _u +} + +// SetNillableTotalSize sets the "totalSize" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableTotalSize(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetTotalSize(*v) + } + return _u +} + +// AddTotalSize adds value to the "totalSize" field. +func (_u *BackupRecordUpdateOne) AddTotalSize(v int64) *BackupRecordUpdateOne { + _u.mutation.AddTotalSize(v) + return _u +} + +// SetItemsJSON sets the "itemsJSON" field. +func (_u *BackupRecordUpdateOne) SetItemsJSON(v string) *BackupRecordUpdateOne { + _u.mutation.SetItemsJSON(v) + return _u +} + +// SetNillableItemsJSON sets the "itemsJSON" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableItemsJSON(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetItemsJSON(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *BackupRecordUpdateOne) SetStatus(v string) *BackupRecordUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableStatus(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetOperator sets the "operator" field. +func (_u *BackupRecordUpdateOne) SetOperator(v string) *BackupRecordUpdateOne { + _u.mutation.SetOperator(v) + return _u +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableOperator(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetOperator(*v) + } + return _u +} + +// SetChecksum sets the "checksum" field. +func (_u *BackupRecordUpdateOne) SetChecksum(v string) *BackupRecordUpdateOne { + _u.mutation.SetChecksum(v) + return _u +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableChecksum(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetChecksum(*v) + } + return _u +} + +// SetScope sets the "scope" field. +func (_u *BackupRecordUpdateOne) SetScope(v string) *BackupRecordUpdateOne { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableScope(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_u *BackupRecordUpdateOne) Mutation() *BackupRecordMutation { + return _u.mutation +} + +// Where appends a list predicates to the BackupRecordUpdate builder. +func (_u *BackupRecordUpdateOne) Where(ps ...predicate.BackupRecord) *BackupRecordUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *BackupRecordUpdateOne) Select(field string, fields ...string) *BackupRecordUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BackupRecord entity. +func (_u *BackupRecordUpdateOne) Save(ctx context.Context) (*BackupRecord, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BackupRecordUpdateOne) SaveX(ctx context.Context) *BackupRecord { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BackupRecordUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BackupRecordUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BackupRecordUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if v, ok := _u.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if v, ok := _u.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if v, ok := _u.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *BackupRecordUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BackupRecordUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *BackupRecordUpdateOne) sqlSave(ctx context.Context) (_node *BackupRecord, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "BackupRecord.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, backuprecord.FieldID) + for _, f := range fields { + if !backuprecord.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != backuprecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedExecutedAt(); ok { + _spec.AddField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeStart(); ok { + _spec.AddField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeEnd(); ok { + _spec.AddField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + } + if value, ok := _u.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTotalSize(); ok { + _spec.AddField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + } + if value, ok := _u.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + } + if value, ok := _u.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + } + _spec.AddModifiers(_u.modifiers...) + _node = &BackupRecord{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{backuprecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/bj_power_mes/ent/client.go b/bj_power_mes/ent/client.go index 9705be7..3a071cd 100644 --- a/bj_power_mes/ent/client.go +++ b/bj_power_mes/ent/client.go @@ -16,6 +16,7 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" + "bj_power_mes/ent/backuprecord" "bj_power_mes/ent/callpool" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" @@ -69,6 +70,8 @@ type Client struct { AssociationTrace *AssociationTraceClient // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient + // BackupRecord is the client for interacting with the BackupRecord builders. + BackupRecord *BackupRecordClient // CallPool is the client for interacting with the CallPool builders. CallPool *CallPoolClient // DailyPlan is the client for interacting with the DailyPlan builders. @@ -149,6 +152,7 @@ func (c *Client) init() { c.AlertRule = NewAlertRuleClient(c.config) c.AssociationTrace = NewAssociationTraceClient(c.config) c.Attachment = NewAttachmentClient(c.config) + c.BackupRecord = NewBackupRecordClient(c.config) c.CallPool = NewCallPoolClient(c.config) c.DailyPlan = NewDailyPlanClient(c.config) c.Dock = NewDockClient(c.config) @@ -278,6 +282,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { AlertRule: NewAlertRuleClient(cfg), AssociationTrace: NewAssociationTraceClient(cfg), Attachment: NewAttachmentClient(cfg), + BackupRecord: NewBackupRecordClient(cfg), CallPool: NewCallPoolClient(cfg), DailyPlan: NewDailyPlanClient(cfg), Dock: NewDockClient(cfg), @@ -334,6 +339,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) AlertRule: NewAlertRuleClient(cfg), AssociationTrace: NewAssociationTraceClient(cfg), Attachment: NewAttachmentClient(cfg), + BackupRecord: NewBackupRecordClient(cfg), CallPool: NewCallPoolClient(cfg), DailyPlan: NewDailyPlanClient(cfg), Dock: NewDockClient(cfg), @@ -395,14 +401,14 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.AgvTask, c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.CallPool, - c.DailyPlan, c.Dock, c.EventLog, c.FlowMaterial, c.InspectionRecord, - c.LinePoint, c.Material, c.MaterialQtyReport, c.MaterialRequest, c.Permission, - c.PlcSendLog, c.ProcessFlow, c.ProcessStep, c.ProductProcess, - c.ProductProcessItem, c.Role, c.SemiFlow, c.Station, c.StationState, - c.StepCriterion, c.StepData, c.StepSignRecord, c.SysConfig, c.TorqueRecord, - c.User, c.UserStation, c.WorkOrder, c.Workpiece, c.WorkpieceBind, - c.WorkpieceLifecycleLog, c.WorkpieceProcess, + c.AgvTask, c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, + c.BackupRecord, c.CallPool, c.DailyPlan, c.Dock, c.EventLog, c.FlowMaterial, + c.InspectionRecord, c.LinePoint, c.Material, c.MaterialQtyReport, + c.MaterialRequest, c.Permission, c.PlcSendLog, c.ProcessFlow, c.ProcessStep, + c.ProductProcess, c.ProductProcessItem, c.Role, c.SemiFlow, c.Station, + c.StationState, c.StepCriterion, c.StepData, c.StepSignRecord, c.SysConfig, + c.TorqueRecord, c.User, c.UserStation, c.WorkOrder, c.Workpiece, + c.WorkpieceBind, c.WorkpieceLifecycleLog, c.WorkpieceProcess, } { n.Use(hooks...) } @@ -412,14 +418,14 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.AgvTask, c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, c.CallPool, - c.DailyPlan, c.Dock, c.EventLog, c.FlowMaterial, c.InspectionRecord, - c.LinePoint, c.Material, c.MaterialQtyReport, c.MaterialRequest, c.Permission, - c.PlcSendLog, c.ProcessFlow, c.ProcessStep, c.ProductProcess, - c.ProductProcessItem, c.Role, c.SemiFlow, c.Station, c.StationState, - c.StepCriterion, c.StepData, c.StepSignRecord, c.SysConfig, c.TorqueRecord, - c.User, c.UserStation, c.WorkOrder, c.Workpiece, c.WorkpieceBind, - c.WorkpieceLifecycleLog, c.WorkpieceProcess, + c.AgvTask, c.Alert, c.AlertRule, c.AssociationTrace, c.Attachment, + c.BackupRecord, c.CallPool, c.DailyPlan, c.Dock, c.EventLog, c.FlowMaterial, + c.InspectionRecord, c.LinePoint, c.Material, c.MaterialQtyReport, + c.MaterialRequest, c.Permission, c.PlcSendLog, c.ProcessFlow, c.ProcessStep, + c.ProductProcess, c.ProductProcessItem, c.Role, c.SemiFlow, c.Station, + c.StationState, c.StepCriterion, c.StepData, c.StepSignRecord, c.SysConfig, + c.TorqueRecord, c.User, c.UserStation, c.WorkOrder, c.Workpiece, + c.WorkpieceBind, c.WorkpieceLifecycleLog, c.WorkpieceProcess, } { n.Intercept(interceptors...) } @@ -438,6 +444,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.AssociationTrace.mutate(ctx, m) case *AttachmentMutation: return c.Attachment.mutate(ctx, m) + case *BackupRecordMutation: + return c.BackupRecord.mutate(ctx, m) case *CallPoolMutation: return c.CallPool.mutate(ctx, m) case *DailyPlanMutation: @@ -1172,6 +1180,139 @@ func (c *AttachmentClient) mutate(ctx context.Context, m *AttachmentMutation) (V } } +// BackupRecordClient is a client for the BackupRecord schema. +type BackupRecordClient struct { + config +} + +// NewBackupRecordClient returns a client for the BackupRecord from the given config. +func NewBackupRecordClient(c config) *BackupRecordClient { + return &BackupRecordClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `backuprecord.Hooks(f(g(h())))`. +func (c *BackupRecordClient) Use(hooks ...Hook) { + c.hooks.BackupRecord = append(c.hooks.BackupRecord, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `backuprecord.Intercept(f(g(h())))`. +func (c *BackupRecordClient) Intercept(interceptors ...Interceptor) { + c.inters.BackupRecord = append(c.inters.BackupRecord, interceptors...) +} + +// Create returns a builder for creating a BackupRecord entity. +func (c *BackupRecordClient) Create() *BackupRecordCreate { + mutation := newBackupRecordMutation(c.config, OpCreate) + return &BackupRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BackupRecord entities. +func (c *BackupRecordClient) CreateBulk(builders ...*BackupRecordCreate) *BackupRecordCreateBulk { + return &BackupRecordCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *BackupRecordClient) MapCreateBulk(slice any, setFunc func(*BackupRecordCreate, int)) *BackupRecordCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BackupRecordCreateBulk{err: fmt.Errorf("calling to BackupRecordClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BackupRecordCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BackupRecordCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BackupRecord. +func (c *BackupRecordClient) Update() *BackupRecordUpdate { + mutation := newBackupRecordMutation(c.config, OpUpdate) + return &BackupRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BackupRecordClient) UpdateOne(_m *BackupRecord) *BackupRecordUpdateOne { + mutation := newBackupRecordMutation(c.config, OpUpdateOne, withBackupRecord(_m)) + return &BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BackupRecordClient) UpdateOneID(id int) *BackupRecordUpdateOne { + mutation := newBackupRecordMutation(c.config, OpUpdateOne, withBackupRecordID(id)) + return &BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BackupRecord. +func (c *BackupRecordClient) Delete() *BackupRecordDelete { + mutation := newBackupRecordMutation(c.config, OpDelete) + return &BackupRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BackupRecordClient) DeleteOne(_m *BackupRecord) *BackupRecordDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BackupRecordClient) DeleteOneID(id int) *BackupRecordDeleteOne { + builder := c.Delete().Where(backuprecord.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BackupRecordDeleteOne{builder} +} + +// Query returns a query builder for BackupRecord. +func (c *BackupRecordClient) Query() *BackupRecordQuery { + return &BackupRecordQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBackupRecord}, + inters: c.Interceptors(), + } +} + +// Get returns a BackupRecord entity by its id. +func (c *BackupRecordClient) Get(ctx context.Context, id int) (*BackupRecord, error) { + return c.Query().Where(backuprecord.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BackupRecordClient) GetX(ctx context.Context, id int) *BackupRecord { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BackupRecordClient) Hooks() []Hook { + return c.hooks.BackupRecord +} + +// Interceptors returns the client interceptors. +func (c *BackupRecordClient) Interceptors() []Interceptor { + return c.inters.BackupRecord +} + +func (c *BackupRecordClient) mutate(ctx context.Context, m *BackupRecordMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BackupRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BackupRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BackupRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown BackupRecord mutation op: %q", m.Op()) + } +} + // CallPoolClient is a client for the CallPool schema. type CallPoolClient struct { config @@ -5431,8 +5572,8 @@ func (c *WorkpieceProcessClient) mutate(ctx context.Context, m *WorkpieceProcess // hooks and interceptors per client, for fast access. type ( hooks struct { - AgvTask, Alert, AlertRule, AssociationTrace, Attachment, CallPool, DailyPlan, - Dock, EventLog, FlowMaterial, InspectionRecord, LinePoint, Material, + AgvTask, Alert, AlertRule, AssociationTrace, Attachment, BackupRecord, CallPool, + DailyPlan, Dock, EventLog, FlowMaterial, InspectionRecord, LinePoint, Material, MaterialQtyReport, MaterialRequest, Permission, PlcSendLog, ProcessFlow, ProcessStep, ProductProcess, ProductProcessItem, Role, SemiFlow, Station, StationState, StepCriterion, StepData, StepSignRecord, SysConfig, TorqueRecord, @@ -5440,8 +5581,8 @@ type ( WorkpieceProcess []ent.Hook } inters struct { - AgvTask, Alert, AlertRule, AssociationTrace, Attachment, CallPool, DailyPlan, - Dock, EventLog, FlowMaterial, InspectionRecord, LinePoint, Material, + AgvTask, Alert, AlertRule, AssociationTrace, Attachment, BackupRecord, CallPool, + DailyPlan, Dock, EventLog, FlowMaterial, InspectionRecord, LinePoint, Material, MaterialQtyReport, MaterialRequest, Permission, PlcSendLog, ProcessFlow, ProcessStep, ProductProcess, ProductProcessItem, Role, SemiFlow, Station, StationState, StepCriterion, StepData, StepSignRecord, SysConfig, TorqueRecord, diff --git a/bj_power_mes/ent/ent.go b/bj_power_mes/ent/ent.go index 07aa7e5..0478fe0 100644 --- a/bj_power_mes/ent/ent.go +++ b/bj_power_mes/ent/ent.go @@ -8,6 +8,7 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" + "bj_power_mes/ent/backuprecord" "bj_power_mes/ent/callpool" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" @@ -114,6 +115,7 @@ func checkColumn(t, c string) error { alertrule.Table: alertrule.ValidColumn, associationtrace.Table: associationtrace.ValidColumn, attachment.Table: attachment.ValidColumn, + backuprecord.Table: backuprecord.ValidColumn, callpool.Table: callpool.ValidColumn, dailyplan.Table: dailyplan.ValidColumn, dock.Table: dock.ValidColumn, diff --git a/bj_power_mes/ent/hook/hook.go b/bj_power_mes/ent/hook/hook.go index b4b8058..21506de 100644 --- a/bj_power_mes/ent/hook/hook.go +++ b/bj_power_mes/ent/hook/hook.go @@ -68,6 +68,18 @@ func (f AttachmentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AttachmentMutation", m) } +// The BackupRecordFunc type is an adapter to allow the use of ordinary +// function as BackupRecord mutator. +type BackupRecordFunc func(context.Context, *ent.BackupRecordMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f BackupRecordFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.BackupRecordMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.BackupRecordMutation", m) +} + // The CallPoolFunc type is an adapter to allow the use of ordinary // function as CallPool mutator. type CallPoolFunc func(context.Context, *ent.CallPoolMutation) (ent.Value, error) diff --git a/bj_power_mes/ent/migrate/schema.go b/bj_power_mes/ent/migrate/schema.go index f6be8b9..048a459 100644 --- a/bj_power_mes/ent/migrate/schema.go +++ b/bj_power_mes/ent/migrate/schema.go @@ -201,6 +201,44 @@ var ( }, }, } + // BackupRecordColumns holds the columns for the "backup_record" table. + BackupRecordColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "executed_at", Type: field.TypeInt64, Comment: "备份执行时刻(unix秒)"}, + {Name: "range_start", Type: field.TypeInt64, Comment: "备份范围开始(unix秒,含)"}, + {Name: "range_end", Type: field.TypeInt64, Comment: "备份范围结束(unix秒,含)"}, + {Name: "backup_path", Type: field.TypeString, Comment: "备份包(zip)在目标盘的完整路径"}, + {Name: "total_size", Type: field.TypeInt64, Comment: "备份包总字节数", Default: 0}, + {Name: "items_json", Type: field.TypeString, Comment: "各数据项及大小(JSON数组:[{name,rows,bytes}])"}, + {Name: "status", Type: field.TypeString, Size: 16, Comment: "success/failed/partial", Default: "success"}, + {Name: "operator", Type: field.TypeString, Size: 64, Comment: "操作人", Default: ""}, + {Name: "checksum", Type: field.TypeString, Size: 64, Comment: "备份包校验和(sha256,基于 manifest)", Default: ""}, + {Name: "scope", Type: field.TypeString, Size: 8, Comment: "写入方 mes/wms", Default: "mes"}, + } + // BackupRecordTable holds the schema information for the "backup_record" table. + BackupRecordTable = &schema.Table{ + Name: "backup_record", + Comment: "BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖", + Columns: BackupRecordColumns, + PrimaryKey: []*schema.Column{BackupRecordColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "backuprecord_range_start", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[2]}, + }, + { + Name: "backuprecord_range_end", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[3]}, + }, + { + Name: "backuprecord_status", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[7]}, + }, + }, + } // CallPoolColumns holds the columns for the "call_pool" table. CallPoolColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -1359,6 +1397,7 @@ var ( AlertRuleTable, AssociationTraceTable, AttachmentTable, + BackupRecordTable, CallPoolTable, DailyPlanTable, DockTable, @@ -1410,6 +1449,9 @@ func init() { AttachmentTable.Annotation = &entsql.Annotation{ Table: "attachment", } + BackupRecordTable.Annotation = &entsql.Annotation{ + Table: "backup_record", + } CallPoolTable.Annotation = &entsql.Annotation{ Table: "call_pool", } diff --git a/bj_power_mes/ent/mutation.go b/bj_power_mes/ent/mutation.go index ec0e2f4..f67fe0e 100644 --- a/bj_power_mes/ent/mutation.go +++ b/bj_power_mes/ent/mutation.go @@ -8,6 +8,7 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" + "bj_power_mes/ent/backuprecord" "bj_power_mes/ent/callpool" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" @@ -65,6 +66,7 @@ const ( TypeAlertRule = "AlertRule" TypeAssociationTrace = "AssociationTrace" TypeAttachment = "Attachment" + TypeBackupRecord = "BackupRecord" TypeCallPool = "CallPool" TypeDailyPlan = "DailyPlan" TypeDock = "Dock" @@ -4994,6 +4996,959 @@ func (m *AttachmentMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Attachment edge %s", name) } +// BackupRecordMutation represents an operation that mutates the BackupRecord nodes in the graph. +type BackupRecordMutation struct { + config + op Op + typ string + id *int + executedAt *int64 + addexecutedAt *int64 + rangeStart *int64 + addrangeStart *int64 + rangeEnd *int64 + addrangeEnd *int64 + backupPath *string + totalSize *int64 + addtotalSize *int64 + itemsJSON *string + status *string + operator *string + checksum *string + scope *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BackupRecord, error) + predicates []predicate.BackupRecord +} + +var _ ent.Mutation = (*BackupRecordMutation)(nil) + +// backuprecordOption allows management of the mutation configuration using functional options. +type backuprecordOption func(*BackupRecordMutation) + +// newBackupRecordMutation creates new mutation for the BackupRecord entity. +func newBackupRecordMutation(c config, op Op, opts ...backuprecordOption) *BackupRecordMutation { + m := &BackupRecordMutation{ + config: c, + op: op, + typ: TypeBackupRecord, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBackupRecordID sets the ID field of the mutation. +func withBackupRecordID(id int) backuprecordOption { + return func(m *BackupRecordMutation) { + var ( + err error + once sync.Once + value *BackupRecord + ) + m.oldValue = func(ctx context.Context) (*BackupRecord, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BackupRecord.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBackupRecord sets the old BackupRecord of the mutation. +func withBackupRecord(node *BackupRecord) backuprecordOption { + return func(m *BackupRecordMutation) { + m.oldValue = func(context.Context) (*BackupRecord, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m BackupRecordMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m BackupRecordMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of BackupRecord entities. +func (m *BackupRecordMutation) SetID(id int) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *BackupRecordMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *BackupRecordMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().BackupRecord.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetExecutedAt sets the "executedAt" field. +func (m *BackupRecordMutation) SetExecutedAt(i int64) { + m.executedAt = &i + m.addexecutedAt = nil +} + +// ExecutedAt returns the value of the "executedAt" field in the mutation. +func (m *BackupRecordMutation) ExecutedAt() (r int64, exists bool) { + v := m.executedAt + if v == nil { + return + } + return *v, true +} + +// OldExecutedAt returns the old "executedAt" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldExecutedAt(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExecutedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExecutedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExecutedAt: %w", err) + } + return oldValue.ExecutedAt, nil +} + +// AddExecutedAt adds i to the "executedAt" field. +func (m *BackupRecordMutation) AddExecutedAt(i int64) { + if m.addexecutedAt != nil { + *m.addexecutedAt += i + } else { + m.addexecutedAt = &i + } +} + +// AddedExecutedAt returns the value that was added to the "executedAt" field in this mutation. +func (m *BackupRecordMutation) AddedExecutedAt() (r int64, exists bool) { + v := m.addexecutedAt + if v == nil { + return + } + return *v, true +} + +// ResetExecutedAt resets all changes to the "executedAt" field. +func (m *BackupRecordMutation) ResetExecutedAt() { + m.executedAt = nil + m.addexecutedAt = nil +} + +// SetRangeStart sets the "rangeStart" field. +func (m *BackupRecordMutation) SetRangeStart(i int64) { + m.rangeStart = &i + m.addrangeStart = nil +} + +// RangeStart returns the value of the "rangeStart" field in the mutation. +func (m *BackupRecordMutation) RangeStart() (r int64, exists bool) { + v := m.rangeStart + if v == nil { + return + } + return *v, true +} + +// OldRangeStart returns the old "rangeStart" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldRangeStart(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRangeStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRangeStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRangeStart: %w", err) + } + return oldValue.RangeStart, nil +} + +// AddRangeStart adds i to the "rangeStart" field. +func (m *BackupRecordMutation) AddRangeStart(i int64) { + if m.addrangeStart != nil { + *m.addrangeStart += i + } else { + m.addrangeStart = &i + } +} + +// AddedRangeStart returns the value that was added to the "rangeStart" field in this mutation. +func (m *BackupRecordMutation) AddedRangeStart() (r int64, exists bool) { + v := m.addrangeStart + if v == nil { + return + } + return *v, true +} + +// ResetRangeStart resets all changes to the "rangeStart" field. +func (m *BackupRecordMutation) ResetRangeStart() { + m.rangeStart = nil + m.addrangeStart = nil +} + +// SetRangeEnd sets the "rangeEnd" field. +func (m *BackupRecordMutation) SetRangeEnd(i int64) { + m.rangeEnd = &i + m.addrangeEnd = nil +} + +// RangeEnd returns the value of the "rangeEnd" field in the mutation. +func (m *BackupRecordMutation) RangeEnd() (r int64, exists bool) { + v := m.rangeEnd + if v == nil { + return + } + return *v, true +} + +// OldRangeEnd returns the old "rangeEnd" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldRangeEnd(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRangeEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRangeEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRangeEnd: %w", err) + } + return oldValue.RangeEnd, nil +} + +// AddRangeEnd adds i to the "rangeEnd" field. +func (m *BackupRecordMutation) AddRangeEnd(i int64) { + if m.addrangeEnd != nil { + *m.addrangeEnd += i + } else { + m.addrangeEnd = &i + } +} + +// AddedRangeEnd returns the value that was added to the "rangeEnd" field in this mutation. +func (m *BackupRecordMutation) AddedRangeEnd() (r int64, exists bool) { + v := m.addrangeEnd + if v == nil { + return + } + return *v, true +} + +// ResetRangeEnd resets all changes to the "rangeEnd" field. +func (m *BackupRecordMutation) ResetRangeEnd() { + m.rangeEnd = nil + m.addrangeEnd = nil +} + +// SetBackupPath sets the "backupPath" field. +func (m *BackupRecordMutation) SetBackupPath(s string) { + m.backupPath = &s +} + +// BackupPath returns the value of the "backupPath" field in the mutation. +func (m *BackupRecordMutation) BackupPath() (r string, exists bool) { + v := m.backupPath + if v == nil { + return + } + return *v, true +} + +// OldBackupPath returns the old "backupPath" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldBackupPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBackupPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBackupPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBackupPath: %w", err) + } + return oldValue.BackupPath, nil +} + +// ResetBackupPath resets all changes to the "backupPath" field. +func (m *BackupRecordMutation) ResetBackupPath() { + m.backupPath = nil +} + +// SetTotalSize sets the "totalSize" field. +func (m *BackupRecordMutation) SetTotalSize(i int64) { + m.totalSize = &i + m.addtotalSize = nil +} + +// TotalSize returns the value of the "totalSize" field in the mutation. +func (m *BackupRecordMutation) TotalSize() (r int64, exists bool) { + v := m.totalSize + if v == nil { + return + } + return *v, true +} + +// OldTotalSize returns the old "totalSize" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldTotalSize(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalSize is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalSize requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalSize: %w", err) + } + return oldValue.TotalSize, nil +} + +// AddTotalSize adds i to the "totalSize" field. +func (m *BackupRecordMutation) AddTotalSize(i int64) { + if m.addtotalSize != nil { + *m.addtotalSize += i + } else { + m.addtotalSize = &i + } +} + +// AddedTotalSize returns the value that was added to the "totalSize" field in this mutation. +func (m *BackupRecordMutation) AddedTotalSize() (r int64, exists bool) { + v := m.addtotalSize + if v == nil { + return + } + return *v, true +} + +// ResetTotalSize resets all changes to the "totalSize" field. +func (m *BackupRecordMutation) ResetTotalSize() { + m.totalSize = nil + m.addtotalSize = nil +} + +// SetItemsJSON sets the "itemsJSON" field. +func (m *BackupRecordMutation) SetItemsJSON(s string) { + m.itemsJSON = &s +} + +// ItemsJSON returns the value of the "itemsJSON" field in the mutation. +func (m *BackupRecordMutation) ItemsJSON() (r string, exists bool) { + v := m.itemsJSON + if v == nil { + return + } + return *v, true +} + +// OldItemsJSON returns the old "itemsJSON" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldItemsJSON(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldItemsJSON is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldItemsJSON requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldItemsJSON: %w", err) + } + return oldValue.ItemsJSON, nil +} + +// ResetItemsJSON resets all changes to the "itemsJSON" field. +func (m *BackupRecordMutation) ResetItemsJSON() { + m.itemsJSON = nil +} + +// SetStatus sets the "status" field. +func (m *BackupRecordMutation) SetStatus(s string) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *BackupRecordMutation) Status() (r string, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *BackupRecordMutation) ResetStatus() { + m.status = nil +} + +// SetOperator sets the "operator" field. +func (m *BackupRecordMutation) SetOperator(s string) { + m.operator = &s +} + +// Operator returns the value of the "operator" field in the mutation. +func (m *BackupRecordMutation) Operator() (r string, exists bool) { + v := m.operator + if v == nil { + return + } + return *v, true +} + +// OldOperator returns the old "operator" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldOperator(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperator is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperator requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperator: %w", err) + } + return oldValue.Operator, nil +} + +// ResetOperator resets all changes to the "operator" field. +func (m *BackupRecordMutation) ResetOperator() { + m.operator = nil +} + +// SetChecksum sets the "checksum" field. +func (m *BackupRecordMutation) SetChecksum(s string) { + m.checksum = &s +} + +// Checksum returns the value of the "checksum" field in the mutation. +func (m *BackupRecordMutation) Checksum() (r string, exists bool) { + v := m.checksum + if v == nil { + return + } + return *v, true +} + +// OldChecksum returns the old "checksum" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldChecksum(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChecksum is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChecksum requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChecksum: %w", err) + } + return oldValue.Checksum, nil +} + +// ResetChecksum resets all changes to the "checksum" field. +func (m *BackupRecordMutation) ResetChecksum() { + m.checksum = nil +} + +// SetScope sets the "scope" field. +func (m *BackupRecordMutation) SetScope(s string) { + m.scope = &s +} + +// Scope returns the value of the "scope" field in the mutation. +func (m *BackupRecordMutation) Scope() (r string, exists bool) { + v := m.scope + if v == nil { + return + } + return *v, true +} + +// OldScope returns the old "scope" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldScope(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScope is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScope requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScope: %w", err) + } + return oldValue.Scope, nil +} + +// ResetScope resets all changes to the "scope" field. +func (m *BackupRecordMutation) ResetScope() { + m.scope = nil +} + +// Where appends a list predicates to the BackupRecordMutation builder. +func (m *BackupRecordMutation) Where(ps ...predicate.BackupRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BackupRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BackupRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BackupRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BackupRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BackupRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BackupRecord). +func (m *BackupRecordMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *BackupRecordMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.executedAt != nil { + fields = append(fields, backuprecord.FieldExecutedAt) + } + if m.rangeStart != nil { + fields = append(fields, backuprecord.FieldRangeStart) + } + if m.rangeEnd != nil { + fields = append(fields, backuprecord.FieldRangeEnd) + } + if m.backupPath != nil { + fields = append(fields, backuprecord.FieldBackupPath) + } + if m.totalSize != nil { + fields = append(fields, backuprecord.FieldTotalSize) + } + if m.itemsJSON != nil { + fields = append(fields, backuprecord.FieldItemsJSON) + } + if m.status != nil { + fields = append(fields, backuprecord.FieldStatus) + } + if m.operator != nil { + fields = append(fields, backuprecord.FieldOperator) + } + if m.checksum != nil { + fields = append(fields, backuprecord.FieldChecksum) + } + if m.scope != nil { + fields = append(fields, backuprecord.FieldScope) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *BackupRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case backuprecord.FieldExecutedAt: + return m.ExecutedAt() + case backuprecord.FieldRangeStart: + return m.RangeStart() + case backuprecord.FieldRangeEnd: + return m.RangeEnd() + case backuprecord.FieldBackupPath: + return m.BackupPath() + case backuprecord.FieldTotalSize: + return m.TotalSize() + case backuprecord.FieldItemsJSON: + return m.ItemsJSON() + case backuprecord.FieldStatus: + return m.Status() + case backuprecord.FieldOperator: + return m.Operator() + case backuprecord.FieldChecksum: + return m.Checksum() + case backuprecord.FieldScope: + return m.Scope() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *BackupRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case backuprecord.FieldExecutedAt: + return m.OldExecutedAt(ctx) + case backuprecord.FieldRangeStart: + return m.OldRangeStart(ctx) + case backuprecord.FieldRangeEnd: + return m.OldRangeEnd(ctx) + case backuprecord.FieldBackupPath: + return m.OldBackupPath(ctx) + case backuprecord.FieldTotalSize: + return m.OldTotalSize(ctx) + case backuprecord.FieldItemsJSON: + return m.OldItemsJSON(ctx) + case backuprecord.FieldStatus: + return m.OldStatus(ctx) + case backuprecord.FieldOperator: + return m.OldOperator(ctx) + case backuprecord.FieldChecksum: + return m.OldChecksum(ctx) + case backuprecord.FieldScope: + return m.OldScope(ctx) + } + return nil, fmt.Errorf("unknown BackupRecord field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *BackupRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case backuprecord.FieldExecutedAt: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExecutedAt(v) + return nil + case backuprecord.FieldRangeStart: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRangeStart(v) + return nil + case backuprecord.FieldRangeEnd: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRangeEnd(v) + return nil + case backuprecord.FieldBackupPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBackupPath(v) + return nil + case backuprecord.FieldTotalSize: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalSize(v) + return nil + case backuprecord.FieldItemsJSON: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetItemsJSON(v) + return nil + case backuprecord.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case backuprecord.FieldOperator: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperator(v) + return nil + case backuprecord.FieldChecksum: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChecksum(v) + return nil + case backuprecord.FieldScope: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScope(v) + return nil + } + return fmt.Errorf("unknown BackupRecord field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BackupRecordMutation) AddedFields() []string { + var fields []string + if m.addexecutedAt != nil { + fields = append(fields, backuprecord.FieldExecutedAt) + } + if m.addrangeStart != nil { + fields = append(fields, backuprecord.FieldRangeStart) + } + if m.addrangeEnd != nil { + fields = append(fields, backuprecord.FieldRangeEnd) + } + if m.addtotalSize != nil { + fields = append(fields, backuprecord.FieldTotalSize) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *BackupRecordMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case backuprecord.FieldExecutedAt: + return m.AddedExecutedAt() + case backuprecord.FieldRangeStart: + return m.AddedRangeStart() + case backuprecord.FieldRangeEnd: + return m.AddedRangeEnd() + case backuprecord.FieldTotalSize: + return m.AddedTotalSize() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *BackupRecordMutation) AddField(name string, value ent.Value) error { + switch name { + case backuprecord.FieldExecutedAt: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddExecutedAt(v) + return nil + case backuprecord.FieldRangeStart: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRangeStart(v) + return nil + case backuprecord.FieldRangeEnd: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRangeEnd(v) + return nil + case backuprecord.FieldTotalSize: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalSize(v) + return nil + } + return fmt.Errorf("unknown BackupRecord numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BackupRecordMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BackupRecordMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *BackupRecordMutation) ClearField(name string) error { + return fmt.Errorf("unknown BackupRecord nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *BackupRecordMutation) ResetField(name string) error { + switch name { + case backuprecord.FieldExecutedAt: + m.ResetExecutedAt() + return nil + case backuprecord.FieldRangeStart: + m.ResetRangeStart() + return nil + case backuprecord.FieldRangeEnd: + m.ResetRangeEnd() + return nil + case backuprecord.FieldBackupPath: + m.ResetBackupPath() + return nil + case backuprecord.FieldTotalSize: + m.ResetTotalSize() + return nil + case backuprecord.FieldItemsJSON: + m.ResetItemsJSON() + return nil + case backuprecord.FieldStatus: + m.ResetStatus() + return nil + case backuprecord.FieldOperator: + m.ResetOperator() + return nil + case backuprecord.FieldChecksum: + m.ResetChecksum() + return nil + case backuprecord.FieldScope: + m.ResetScope() + return nil + } + return fmt.Errorf("unknown BackupRecord field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BackupRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BackupRecordMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BackupRecordMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BackupRecordMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BackupRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BackupRecordMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *BackupRecordMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BackupRecord unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *BackupRecordMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BackupRecord edge %s", name) +} + // CallPoolMutation represents an operation that mutates the CallPool nodes in the graph. type CallPoolMutation struct { config diff --git a/bj_power_mes/ent/predicate/predicate.go b/bj_power_mes/ent/predicate/predicate.go index 27b955e..4aafdeb 100644 --- a/bj_power_mes/ent/predicate/predicate.go +++ b/bj_power_mes/ent/predicate/predicate.go @@ -21,6 +21,9 @@ type AssociationTrace func(*sql.Selector) // Attachment is the predicate function for attachment builders. type Attachment func(*sql.Selector) +// BackupRecord is the predicate function for backuprecord builders. +type BackupRecord func(*sql.Selector) + // CallPool is the predicate function for callpool builders. type CallPool func(*sql.Selector) diff --git a/bj_power_mes/ent/runtime.go b/bj_power_mes/ent/runtime.go index 4243785..b2457d6 100644 --- a/bj_power_mes/ent/runtime.go +++ b/bj_power_mes/ent/runtime.go @@ -8,6 +8,7 @@ import ( "bj_power_mes/ent/alertrule" "bj_power_mes/ent/associationtrace" "bj_power_mes/ent/attachment" + "bj_power_mes/ent/backuprecord" "bj_power_mes/ent/callpool" "bj_power_mes/ent/dailyplan" "bj_power_mes/ent/dock" @@ -348,6 +349,44 @@ func init() { attachmentDescID := attachmentFields[0].Descriptor() // attachment.IDValidator is a validator for the "id" field. It is called by the builders before save. attachment.IDValidator = attachmentDescID.Validators[0].(func(int) error) + backuprecordFields := schema.BackupRecord{}.Fields() + _ = backuprecordFields + // backuprecordDescExecutedAt is the schema descriptor for executedAt field. + backuprecordDescExecutedAt := backuprecordFields[1].Descriptor() + // backuprecord.DefaultExecutedAt holds the default value on creation for the executedAt field. + backuprecord.DefaultExecutedAt = backuprecordDescExecutedAt.Default.(func() int64) + // backuprecordDescTotalSize is the schema descriptor for totalSize field. + backuprecordDescTotalSize := backuprecordFields[5].Descriptor() + // backuprecord.DefaultTotalSize holds the default value on creation for the totalSize field. + backuprecord.DefaultTotalSize = backuprecordDescTotalSize.Default.(int64) + // backuprecordDescStatus is the schema descriptor for status field. + backuprecordDescStatus := backuprecordFields[7].Descriptor() + // backuprecord.DefaultStatus holds the default value on creation for the status field. + backuprecord.DefaultStatus = backuprecordDescStatus.Default.(string) + // backuprecord.StatusValidator is a validator for the "status" field. It is called by the builders before save. + backuprecord.StatusValidator = backuprecordDescStatus.Validators[0].(func(string) error) + // backuprecordDescOperator is the schema descriptor for operator field. + backuprecordDescOperator := backuprecordFields[8].Descriptor() + // backuprecord.DefaultOperator holds the default value on creation for the operator field. + backuprecord.DefaultOperator = backuprecordDescOperator.Default.(string) + // backuprecord.OperatorValidator is a validator for the "operator" field. It is called by the builders before save. + backuprecord.OperatorValidator = backuprecordDescOperator.Validators[0].(func(string) error) + // backuprecordDescChecksum is the schema descriptor for checksum field. + backuprecordDescChecksum := backuprecordFields[9].Descriptor() + // backuprecord.DefaultChecksum holds the default value on creation for the checksum field. + backuprecord.DefaultChecksum = backuprecordDescChecksum.Default.(string) + // backuprecord.ChecksumValidator is a validator for the "checksum" field. It is called by the builders before save. + backuprecord.ChecksumValidator = backuprecordDescChecksum.Validators[0].(func(string) error) + // backuprecordDescScope is the schema descriptor for scope field. + backuprecordDescScope := backuprecordFields[10].Descriptor() + // backuprecord.DefaultScope holds the default value on creation for the scope field. + backuprecord.DefaultScope = backuprecordDescScope.Default.(string) + // backuprecord.ScopeValidator is a validator for the "scope" field. It is called by the builders before save. + backuprecord.ScopeValidator = backuprecordDescScope.Validators[0].(func(string) error) + // backuprecordDescID is the schema descriptor for id field. + backuprecordDescID := backuprecordFields[0].Descriptor() + // backuprecord.IDValidator is a validator for the "id" field. It is called by the builders before save. + backuprecord.IDValidator = backuprecordDescID.Validators[0].(func(int) error) callpoolFields := schema.CallPool{}.Fields() _ = callpoolFields // callpoolDescMaterialCode is the schema descriptor for materialCode field. diff --git a/bj_power_mes/ent/tx.go b/bj_power_mes/ent/tx.go index be9f2ba..5f78b99 100644 --- a/bj_power_mes/ent/tx.go +++ b/bj_power_mes/ent/tx.go @@ -22,6 +22,8 @@ type Tx struct { AssociationTrace *AssociationTraceClient // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient + // BackupRecord is the client for interacting with the BackupRecord builders. + BackupRecord *BackupRecordClient // CallPool is the client for interacting with the CallPool builders. CallPool *CallPoolClient // DailyPlan is the client for interacting with the DailyPlan builders. @@ -222,6 +224,7 @@ func (tx *Tx) init() { tx.AlertRule = NewAlertRuleClient(tx.config) tx.AssociationTrace = NewAssociationTraceClient(tx.config) tx.Attachment = NewAttachmentClient(tx.config) + tx.BackupRecord = NewBackupRecordClient(tx.config) tx.CallPool = NewCallPoolClient(tx.config) tx.DailyPlan = NewDailyPlanClient(tx.config) tx.Dock = NewDockClient(tx.config) diff --git a/bj_power_mes/etc/bj_power_mes-api.yaml b/bj_power_mes/etc/bj_power_mes-api.yaml index fe69c8e..84a7af6 100644 --- a/bj_power_mes/etc/bj_power_mes-api.yaml +++ b/bj_power_mes/etc/bj_power_mes-api.yaml @@ -85,4 +85,3 @@ Upload: DiskWarnPercent: 20 # 剩余空间 <20% 告警 DiskCriticalPercent: 10 # 剩余空间 <10% 提示清理/归档 DiskCheckHour: 7 # 每天 07:00 检测 - ArchiveDir: "" # 外部备份目录(NAS/移动硬盘),留空则归档仅标记 \ No newline at end of file diff --git a/bj_power_mes/frontend/src/help.js b/bj_power_mes/frontend/src/help.js index bdd950c..db896ab 100644 --- a/bj_power_mes/frontend/src/help.js +++ b/bj_power_mes/frontend/src/help.js @@ -569,7 +569,7 @@ export const helpAlertRule = { export const helpAttachment = { title: '附件中心(统一存储与查阅)', overview: - '附件中心集中登记并查阅全系统附件(图纸、检验照片、检验报告、工艺、流程卡、包装照片、Excel 导入等),新增在各业务页面内完成,本页负责查阅、下载、删除与归档清理。\n\n统一存储规则:所有附件按「附件根目录/年/月/日/文件类型/文件」分层存放,文件类型目录全部大写(PROCESS_PDF、INSPECTION_PHOTO、INSPECTION_PDF、DRAWING、PROCESS_CARD、PACKAGE_PHOTO、EXCEL_IMPORT、OTHER);文件名统一用 UUID,扩展名小写,不含中文与特殊字符;数据库只存相对路径(如 2026/09/19/INSPECTION_PHOTO/xxx.jpg),不存绝对路径。附件根目录由配置文件 Upload.Dir 指定,不硬编码。\n\n上传为流式写入(边写边算 MD5),同业务对象同 MD5 自动秒传不重复占空间;单文件大小按文件类型配置上限(默认 20MB)。\n\n删除为逻辑删除:库内标记「已删除」并记录删除人/时间,物理文件保留,勾选「含已删除」可追溯。\n\n归档清理:本地只保留最近「配置的年数」(默认 1 年),更早的附件可一键归档到外部备份目录并标记「已归档」,释放本地磁盘。\n\n磁盘空间监控:系统每天早上 7 点自动检测磁盘剩余空间,剩余低于 20% 告警、低于 10% 提示执行备份归档清理(本页顶部同步横幅提示,critical 时可直接点「立即归档清理」)。', + '附件中心集中登记并查阅全系统附件(图纸、检验照片、检验报告、工艺、流程卡、包装照片、Excel 导入等),新增在各业务页面内完成,本页负责查阅、下载与删除。\n\n统一存储规则:所有附件按「附件根目录/年/月/日/文件类型/文件」分层存放,文件类型目录全部大写(PROCESS_PDF、INSPECTION_PHOTO、INSPECTION_PDF、DRAWING、PROCESS_CARD、PACKAGE_PHOTO、EXCEL_IMPORT、OTHER);文件名统一用 UUID,扩展名小写,不含中文与特殊字符;数据库只存相对路径(如 2026/09/19/INSPECTION_PHOTO/xxx.jpg),不存绝对路径。附件根目录由配置文件 Upload.Dir 指定,不硬编码。\n\n上传为流式写入(边写边算 MD5),同业务对象同 MD5 自动秒传不重复占空间;单文件大小按文件类型配置上限(默认 20MB)。\n\n删除为逻辑删除:库内标记「已删除」并记录删除人/时间,物理文件保留,勾选「含已删除」可追溯。\n\n历史数据的备份与清理统一在「数据归档」页面完成(按时间窗备份到 U 盘/移动硬盘,备份覆盖后才能物理清理释放空间)。\n\n磁盘空间监控:系统每天早上 7 点自动检测磁盘剩余空间,剩余低于 20% 告警、低于 10% 提示及时备份清理(本页顶部同步横幅提示;请到「数据归档」页处理)。', fields: [ { name: '文件类型', source: '上传时由业务场景指定或按扩展名推断(大写枚举)。', purpose: '决定存储目录分层,也是查阅时的主要筛选维度', fill: '下拉单选八类之一,留空=全部' }, { name: '业务类型', source: '上传时随附件记录写入(工单/物料/工艺/检验/入库 等)。', purpose: '区分附件挂在哪种业务单据上', fill: '下拉单选,留空=全部' }, @@ -577,12 +577,10 @@ export const helpAttachment = { { name: '文件名', source: '上传时的原始文件名。', purpose: '按名称模糊查找', fill: '支持模糊匹配' }, { name: '上传时间', source: '系统记录上传时刻。', purpose: '按时间区间缩小范围', fill: '可选起止日期,留空=不限' }, { name: '含已删除', source: '勾选后包含逻辑删除的记录。', purpose: '追溯已删除附件', fill: '默认不勾选' }, - { name: '相对路径', source: '系统按统一规则生成(年/月/日/类型/UUID.ext)。', purpose: '直观看到物理存放位置;点击即在线预览', fill: '只读' }, { name: '大小', source: '系统统计上传达字节数。', purpose: '评估占用空间', fill: '只读' }, - { name: '状态', source: '系统维护(有效/已归档/已删除)。', purpose: '区分当前可用的与已归档/已删除的附件', fill: '只读' }, { name: '预览 / 下载', source: '预览走免鉴权直链(PDF/图片浏览器内联打开);下载走鉴权路由并带回中文文件名。', purpose: '查看或另存附件', fill: '点击对应按钮' }, { name: '删除', source: '行末按钮(权限 sys.attachment:manage,需二次确认)。', purpose: '逻辑删除无效附件(保留可追溯索引)', fill: '点「删除」并确认;无权限时该按钮不显示' }, - { name: '归档清理', source: '按钮(权限 sys.attachment:manage;先预览数量再确认执行)。', purpose: '把早于本地保留年数的附件移到外部备份目录并标记已归档,释放磁盘', fill: '点「归档清理」→确认;无权限时该按钮不显示' } + { name: '预览 / 下载备用入口', source: '列表行「预览」「下载」按钮。', purpose: '查看或另存附件', fill: '点击对应按钮' } ] } diff --git a/bj_power_mes/frontend/src/layouts/MainLayout.vue b/bj_power_mes/frontend/src/layouts/MainLayout.vue index a83c2ff..8e511af 100644 --- a/bj_power_mes/frontend/src/layouts/MainLayout.vue +++ b/bj_power_mes/frontend/src/layouts/MainLayout.vue @@ -45,6 +45,13 @@ + + + + + + + 帮助 {{ userName }} ▾ @@ -70,9 +77,9 @@ import { useRouter } from 'vue-router' import { Document, Calendar, Box, Goods, ShoppingCart, Monitor, Tools, Operation, Link, DataLine, Search, CircleCheck, Clock, User, - Key, Fold, Expand, Warning, Paperclip, Tickets, Bell, Setting, Van + Key, Fold, Expand, Warning, Paperclip, Tickets, Bell, Setting, Van, AlarmClock } from '@element-plus/icons-vue' -import { ElNotification } from 'element-plus' +import { ElNotification, ElMessageBox } from 'element-plus' import { getUser, logout } from '../utils/auth' import request from '../utils/request' @@ -166,6 +173,7 @@ const menuGroups = [ { code: 'sys.alert', name: '预警中心', path: '/alert-center', icon: Warning }, { code: 'sys.alertrule', name: '预警规则', path: '/alert-rule', icon: Setting }, { code: 'sys.attachment', name: '附件中心', path: '/attachment', icon: Paperclip }, + { code: 'sys.backup', name: '数据归档', path: '/data-archive', icon: Tools }, { code: 'sys.settings', name: '基础设置', path: '/settings', icon: Setting } ] } @@ -201,8 +209,35 @@ onMounted(async () => { // 顶部预警铃铛:立即拉一次未读数,随后每 30s 轮询 pollAlerts() alertTimer = setInterval(pollAlerts, 30000) + + // 数据归档清理提醒:登录后拉取,超期则强提醒(每天一次) + checkArchiveReminder() }) +// ===== 数据归档清理提醒:登录后检查,超期弹强提醒 + 顶栏角标 ===== +// 仅依赖 backup_record 真实数据;localStorage 只记“当天已弹过”,每天最多一次。 +const archiveOverdue = ref(false) + +async function checkArchiveReminder() { + try { + const r = await request.get('/backup/reminder') + if (!r || !r.overdue) { + archiveOverdue.value = false + return + } + archiveOverdue.value = true + const todayKey = new Date().toISOString().slice(0, 10) + const shown = localStorage.getItem('mes_archive_remind_shown') || '' + if (shown === todayKey) return // 当天已弹过 + localStorage.setItem('mes_archive_remind_shown', todayKey) + ElMessageBox.alert( + `距上次成功备份已超过 ${r.remindDays} 天,建议清理旧数据以释放空间。\n请先在「数据归档」页确认 U 盘备份完整,再手动清理(仅提醒,不自动删除)。`, + '数据归档清理提醒', + { type: 'warning', confirmButtonText: '我知道了', showClose: false } + ).catch(() => {}) + } catch { /* ignore */ } +} + // ===== 顶部预警铃铛(plan 4.10):未读角标 + 30s 轮询 + 新增弹提示 ===== const unreadAlerts = ref(0) let alertTimer = null @@ -231,6 +266,10 @@ function goAlertCenter() { router.push('/alert-center') } +function goDataArchive() { + router.push('/data-archive') +} + function doLogout() { // 尽力通知后端记录"退出登录"操作日志,失败不阻塞本地退出 request.post('/logout').catch(() => {}) diff --git a/bj_power_mes/frontend/src/pages/Attachment.vue b/bj_power_mes/frontend/src/pages/Attachment.vue index e365bf4..1161fde 100644 --- a/bj_power_mes/frontend/src/pages/Attachment.vue +++ b/bj_power_mes/frontend/src/pages/Attachment.vue @@ -1,6 +1,6 @@ @@ -42,8 +40,6 @@ 查询 重置 - 归档清理 @@ -56,11 +52,6 @@ {{ fileTypeText(row.fileType) }} - - - @@ -77,7 +68,6 @@ @@ -141,7 +131,6 @@ const list = ref([]) const total = ref(0) const page = reactive({ current: 1, size: 20 }) const loading = ref(false) -const archiving = ref(false) const disk = reactive({ level: 'ok', message: '', rootDir: '', usedPercent: 0, freeBytes: 0, totalBytes: 0 }) const freePercent = computed(() => Math.max(0, 100 - (disk.usedPercent || 0))) @@ -204,12 +193,6 @@ function preview(row) { if (!row.previewUrl) return ElMessage.warning('无预览地址') window.open(row.previewUrl, '_blank') } -// 路径改完整 URL(绝对可访问地址,便于复制/对接) -function fullUrl(row) { - if (!row.url) return row.filePath || '-' - try { return location.origin + row.url } catch { return row.url } -} - // 下载:带鉴权走 id 路由,服务端给出中文文件名 async function download(row) { const token = getToken() @@ -235,27 +218,6 @@ async function remove(row) { await load() } -// 归档:先 dryRun 预览数量,确认后执行(早于本地保留年数的附件移动到外部备份目录并标记已归档) -async function doArchive() { - const pre = await request.post('/attachment/archive', { dryRun: true }) - if (!pre?.marked) return ElMessage.info('没有需要归档的附件(早于 ' + pre?.cutYear + ' 年的记录)') - const tip = pre.archiveDir - ? `将把 ${pre.marked} 个早于 ${pre.cutYear} 年的附件移动到备份目录:\n${pre.archiveDir}` - : `将把 ${pre.marked} 个早于 ${pre.cutYear} 年的附件标记为已归档(未配置备份目录,不移动物理文件)` - try { - await ElMessageBox.confirm(tip + '\n\n确认执行归档吗?', '归档确认', { - confirmButtonText: '确认归档', cancelButtonText: '取消', type: 'warning' - }) - } catch { return } - archiving.value = true - try { - const res = await request.post('/attachment/archive', { dryRun: false }) - ElMessage.success(`归档完成:移动 ${res?.moved || 0},标记 ${res?.marked || 0},失败 ${res?.failed || 0}`) - await load() - } finally { - archiving.value = false - } -} onMounted(load) diff --git a/bj_power_mes/frontend/src/pages/DailyPlan.vue b/bj_power_mes/frontend/src/pages/DailyPlan.vue index ed2aed7..4c06f20 100644 --- a/bj_power_mes/frontend/src/pages/DailyPlan.vue +++ b/bj_power_mes/frontend/src/pages/DailyPlan.vue @@ -384,7 +384,7 @@ async function loadStations() { const nm = {} sts.forEach((s) => { nm[s.stationNo] = s.name }) stationNameMap.value = nm - // 接驳台真源 = dock 表(一个工位可配 R1/R2 多个接驳台),按 station_no 聚合为 stationNo → [dockCode] + // 接驳台真源 = dock 表(一个工位可配 左L/右R 多个接驳台),按 station_no 聚合为 stationNo → [dockCode] const docks = (await request.get('/docks')) || [] const dm = {} docks.forEach((d) => { @@ -460,7 +460,7 @@ function onPageChange(p) { fetchPage() } -// 该行送达接驳台:由工单工艺组合的工位号 → dock 表接驳台编码去重派生(支持一工位 R1/R2 多个接驳台) +// 该行送达接驳台:由工单工艺组合的工位号 → dock 表接驳台编码去重派生(支持一工位 左L/右R 多个接驳台) function docksOf(row) { const comb = row.flowCombination || [] const seen = {}; const ds = [] diff --git a/bj_power_mes/frontend/src/pages/DataArchive.vue b/bj_power_mes/frontend/src/pages/DataArchive.vue new file mode 100644 index 0000000..84002a1 --- /dev/null +++ b/bj_power_mes/frontend/src/pages/DataArchive.vue @@ -0,0 +1,375 @@ + + + + + diff --git a/bj_power_mes/frontend/src/pages/ProcessCard.vue b/bj_power_mes/frontend/src/pages/ProcessCard.vue index 50ebfbd..2a45d96 100644 --- a/bj_power_mes/frontend/src/pages/ProcessCard.vue +++ b/bj_power_mes/frontend/src/pages/ProcessCard.vue @@ -65,7 +65,7 @@ 查询 - 打印 / 导出 PDF + 导出 重置 @@ -295,6 +295,25 @@ + + + + + + + PDF(打印版 / 浏览器另存为 PDF) + Excel(CSV,双击即用 Excel 打开) + + + + 当前查看的这张卡(单条) + + + +
@@ -464,6 +483,134 @@ const dateLabel = computed(() => { const canPrint = computed(() => (mode.value === 'workorder' && card.value) || (mode.value === 'sn' && snCard.value)) +// ---------- 导出(选择框 → 选完再生成文件) ---------- +const exportVisible = ref(false) +const exportFormat = ref('pdf') +const exporting = ref(false) + +function openExportDialog() { + exportFormat.value = 'pdf' + exportVisible.value = true +} + +async function doExport() { + if (exportFormat.value === 'pdf') { + // PDF(打印版):复用服务端渲染 HTML,新窗口内打印 / 另存为 PDF + exportVisible.value = false + printCurrent() + return + } + // Excel(CSV,Excel 可直接打开,零依赖) + exporting.value = true + try { + if (mode.value === 'workorder' && card.value) { + downloadCsv(buildWorkOrderCsv(card.value), `生产流程卡_${card.value.workOrderNo || 'workorder'}.csv`) + } else if (mode.value === 'sn' && snCard.value) { + downloadCsv(buildSnCsv(snCard.value), `成品追溯卡_${snCard.value.sn || 'sn'}.csv`) + } + } finally { + exporting.value = false + exportVisible.value = false + } +} + +// 客户端生成 CSV(与页面现有字段一致,UTF-8 BOM 保证 Excel 中文不乱码) +function csvCell(v) { + if (v === null || v === undefined) v = '' + const s = String(v) + if (s.includes(',') || s.includes('"') || s.includes('\n') || s.includes('\r')) { + return '"' + s.replace(/"/g, '""') + '"' + } + return s +} +function downloadCsv(content, filename) { + const blob = new Blob(['' + content], { type: 'text/csv;charset=utf-8' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = filename + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + URL.revokeObjectURL(url) +} +function buildWorkOrderCsv(c) { + const lines = [] + const push = (arr) => lines.push(arr.map(csvCell).join(',')) + push(['生产流程卡(工单维度)', c.workOrderNo || '']) + push(['产品工号', c.workOrderNo || '', '产品型号', c.productCode || '', '产品名称', c.productName || '', '图号', c.drawingNo || '']) + push(['计划数', c.planQty ?? '', '完成数', c.finishedNum ?? '', '不良数', c.failNum ?? '', '状态', c.status || '']) + push(['计划开始', c.planStart || '', '计划完成', c.planEnd || '', '实际开始', c.actualStart || '', '实际完成', c.completedAt || '']) + push(['实际结束', c.actualFinish || '', '生成时间', c.generatedAt || '']) + lines.push('') + push(['一、工序实绩']) + push(['序号', '工序', '采集方式', '工位', '计划工时', '实绩开始', '实绩结束', '操作人', '状态', '审核人', '审核时间']) + ;(c.processSteps || []).forEach((r) => + push([r.seq, r.processName, r.collectCN, r.stationNo, r.planHours, r.actualStart, r.actualEnd, r.operators, r.status, (r.auditor || '') + (r.auditRole ? '(' + r.auditRole + ')' : ''), r.auditedAt]) + ) + lines.push('') + push(['二、用料清单·序列号=是']) + push(['图号', '名称', '类型', '规格', '单位', '物料SN', '数量', '装配工位', '装配人']) + ;(c.serialMaterials || []).forEach((r) => + push([r.materialCode, r.materialName, r.materialType, r.spec, r.unit, (r.snList || []).join(' '), r.qty, r.stationNo, r.operator]) + ) + lines.push('') + push(['三、用料清单·序列号=否']) + push(['图号', '名称', '类型', '规格', '单位', '批次号', '数量', '装配工位', '装配人']) + ;(c.batchMaterials || []).forEach((r) => + push([r.materialCode, r.materialName, r.materialType, r.spec, r.unit, r.batchNo, r.qty, r.stationNo, r.operator]) + ) + lines.push('') + push(['四、成品明细']) + push(['SN', '状态', '完工时间']) + ;(c.products || []).forEach((r) => push([r.sn, r.status, r.doneAt])) + lines.push('') + push(['五、签字确认']) + const s = c.signs || {} + push(['操作工', s.operator ? s.operator.names + '(' + s.operator.count + '次,最近 ' + s.operator.latestTime + ')' : '待签']) + push(['检验员', s.inspector ? s.inspector.names + '(' + s.inspector.count + '次,最近 ' + s.inspector.latestTime + ')' : '待签']) + push(['审核人', s.auditor ? s.auditor.names + '(' + s.auditor.count + '次,最近 ' + s.auditor.latestTime + ')' : '待签']) + push(['批准人', '手签']) + return lines.join('\r\n') +} +function buildSnCsv(c) { + const lines = [] + const push = (arr) => lines.push(arr.map(csvCell).join(',')) + push(['成品追溯卡(SN 维度)', c.sn || '']) + push(['SN', c.sn || '', '产品工号', c.workOrderNo || '', '产品型号', c.productCode || '', '状态', c.status || '']) + push(['完工时间', c.doneAt || '', '生成时间', c.generatedAt || '']) + lines.push('') + push(['一、工序实绩']) + push(['工位', '工序', '开始', '结束', '操作人', '状态', '结果']) + ;(c.processes || []).forEach((r) => push([r.stationNo, r.processName, r.startAt, r.endAt, r.operator, r.status, r.result])) + lines.push('') + push(['二、用料清单·序列号=是']) + push(['图号', '名称', '类型', '规格', '单位', '物料SN', '数量', '装配工位', '装配人']) + ;(c.serialMaterials || []).forEach((r) => + push([r.materialCode, r.materialName, r.materialType, r.spec, r.unit, (r.snList || []).join(' '), r.qty, r.stationNo, r.operator]) + ) + lines.push('') + push(['三、用料清单·序列号=否']) + push(['图号', '名称', '类型', '规格', '单位', '批次号', '数量', '装配工位', '装配人']) + ;(c.batchMaterials || []).forEach((r) => + push([r.materialCode, r.materialName, r.materialType, r.spec, r.unit, r.batchNo, r.qty, r.stationNo, r.operator]) + ) + if ((c.torqueRows || []).length) { + lines.push('') + push(['四、拧紧数据']) + push(['螺丝编号', '扭矩(N·m)', '角度(°)', '结果', '操作人', '时间']) + ;(c.torqueRows || []).forEach((r) => push([r.screwNo, r.torque, r.angle, r.result, r.operator, r.time])) + } + lines.push('') + push([(c.torqueRows && c.torqueRows.length) ? '五、签字确认' : '四、签字确认']) + const s = c.signs || {} + push(['操作工', s.operator ? s.operator.names : '待签']) + push(['检验员', s.inspector ? s.inspector.names : '待签']) + push(['审核人', s.auditor ? s.auditor.names : '待签']) + push(['批准人', '手签']) + return lines.join('\r\n') +} + function printCurrent() { if (mode.value === 'workorder' && workOrderNo.value) { openPrintableHtml('/process-card/workorder', { no: workOrderNo.value }) diff --git a/bj_power_mes/frontend/src/pages/Settings.vue b/bj_power_mes/frontend/src/pages/Settings.vue index 2eb69d3..b57f78c 100644 --- a/bj_power_mes/frontend/src/pages/Settings.vue +++ b/bj_power_mes/frontend/src/pages/Settings.vue @@ -43,6 +43,19 @@
看板大屏轮询兜底刷新间隔(1~10 秒,默认 5);SSE 实时通道可用时由事件驱动刷新,本值仅作兜底间隔
+ + +
厂门口看板顶部标题文字(留空=保持默认「总装产线实时看板」);看板端每分钟自动拉取跟随
+
+ + +
开启(默认)后厂门口看板对新报警进行中文语音播报;关闭则只静默展示
+
+ + +
距上次成功备份超过该天数时,登录后弹出强提醒(每天一次,仅提醒不自动删除);0 = 关闭
+
保存 @@ -82,7 +95,7 @@ const loading = ref(false) const saving = ref(false) const testing = ref(false) const testMsg = ref('') -const form = reactive({ wmsBaseURL: '', demandDays: 5, extrapWindow: 3, extrapCap: 365, logRetentionDays: 0, pipelineCache: 0, allowCrossDay: 1, torqueNgAlert: true, dashboardRefreshSeconds: 5 }) +const form = reactive({ wmsBaseURL: '', demandDays: 5, extrapWindow: 3, extrapCap: 365, logRetentionDays: 0, pipelineCache: 0, allowCrossDay: 1, torqueNgAlert: true, dashboardRefreshSeconds: 5, archiveRemindDays: 7, dashboardTitle: '', dashboardVoice: true }) const info = ref({}) async function load() { @@ -98,7 +111,10 @@ async function load() { pipelineCache: data.pipelineCache ?? 0, allowCrossDay: data.allowCrossDay ?? 1, torqueNgAlert: data.torqueNgAlert ?? true, - dashboardRefreshSeconds: data.dashboardRefreshSeconds ?? 5 + dashboardRefreshSeconds: data.dashboardRefreshSeconds ?? 5, + archiveRemindDays: data.archiveRemindDays ?? 7, + dashboardTitle: data.dashboardTitle || '', + dashboardVoice: data.dashboardVoice ?? true }) info.value = data } finally { diff --git a/bj_power_mes/frontend/src/pages/Station.vue b/bj_power_mes/frontend/src/pages/Station.vue index f9bccdb..20c6aa5 100644 --- a/bj_power_mes/frontend/src/pages/Station.vue +++ b/bj_power_mes/frontend/src/pages/Station.vue @@ -154,7 +154,7 @@ import { helpStation } from '../help' const stations = ref([]) const flows = ref([]) -// 接驳台主数据(真源在 dock 表):一工位可绑多个接驳台(R1/R2),展示按 dock.station_no 聚合 +// 接驳台主数据(真源在 dock 表):一工位可绑多个接驳台(左L/右R),展示按 dock.station_no 聚合 const dockByStation = ref({}) async function loadDocks() { diff --git a/bj_power_mes/frontend/src/router/index.js b/bj_power_mes/frontend/src/router/index.js index d9c0d11..289fd1c 100644 --- a/bj_power_mes/frontend/src/router/index.js +++ b/bj_power_mes/frontend/src/router/index.js @@ -36,6 +36,7 @@ const routes = [ { path: 'alert-center', name: 'AlertCenter', component: () => import('../pages/AlertCenter.vue'), meta: { title: '预警中心' } }, { path: 'alert-rule', name: 'AlertRule', component: () => import('../pages/AlertRule.vue'), meta: { title: '预警规则' } }, { path: 'attachment', name: 'Attachment', component: () => import('../pages/Attachment.vue'), meta: { title: '附件中心' } }, + { path: 'data-archive', name: 'DataArchive', component: () => import('../pages/DataArchive.vue'), meta: { title: '数据归档' } }, ] }, { path: '/:pathMatch(.*)*', redirect: '/work-order' } diff --git a/bj_power_mes/internal/backup/backup.go b/bj_power_mes/internal/backup/backup.go new file mode 100644 index 0000000..534a8f2 --- /dev/null +++ b/bj_power_mes/internal/backup/backup.go @@ -0,0 +1,731 @@ +// Package backup 实现「备份到外部存储(U盘/移动硬盘)」与「按时间窗物理清理」两大能力。 +// +// 设计要点: +// - 备份:时间窗 [start,end](end ≤ 昨天);按各表 created_at 导出(MES 为 tz-time, +// 统一在窗口层转成 time.Time);附件按 DB 记录的 filePath 取磁盘文件;zip 流式直写 +// 目标路径(不落本地临时文件);包内含 manifest.json + index.html(不内嵌预览)。 +// - 清理:先校验 backup_record 对该时间窗的完整覆盖(部分/无覆盖一律拒绝并列出缺失段); +// 再物理 DELETE 日志表、物理删除附件文件 + DELETE 记录;各端附件文件由各端独占写入与引用 +// (UUID 文件名,物料同步不含附件),不存在跨系统共享文件,清理不依赖对端服务; +// 清理动作本身写一条 event_log。 +// - 不做软删、不引入 archived/deleted 标记。 +package backup + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "bj_power_mes/ent" + "bj_power_mes/ent/alert" + "bj_power_mes/ent/attachment" + backuprecord "bj_power_mes/ent/backuprecord" + "bj_power_mes/ent/eventlog" + "bj_power_mes/ent/plcsendlog" + "bj_power_mes/ent/workpiecelifecyclelog" + evlog "bj_power_mes/internal/eventlog" + + "golang.org/x/sys/windows" +) + +// ItemDef 可选备份/清理数据项(质量 4 表有意不出现)。 +type ItemDef struct { + Key string `json:"key"` + Name string `json:"name"` + Kind string `json:"kind"` // log | attachment +} + +// MESItems MES 端可选数据项(event_log/plc_send_log/workpiece_lifecycle_log/alert/attachment)。 +var MESItems = []ItemDef{ + {Key: "event_log", Name: "操作日志", Kind: "log"}, + {Key: "plc_send_log", Name: "PLC下发日志", Kind: "log"}, + {Key: "workpiece_lifecycle_log", Name: "工件生命周期日志", Kind: "log"}, + {Key: "alert", Name: "预警消息", Kind: "log"}, + {Key: "attachment", Name: "业务附件", Kind: "attachment"}, +} + +// BackupRequest 备份请求。 +type BackupRequest struct { + TargetPath string `json:"targetPath"` // 服务端绝对目录(U盘/移动硬盘挂载点) + Start int64 `json:"start"` // unix 秒(含) + End int64 `json:"end"` // unix 秒(含,≤ 昨天结束) + Items []string `json:"items"` // 数据项 key + Operator string `json:"operator"` +} + +// CleanupRequest 清理请求。 +type CleanupRequest struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + Operator string `json:"operator"` +} + +// ItemResult 单项导出结果。 +type ItemResult struct { + Name string `json:"name"` + Key string `json:"key"` + Rows int64 `json:"rows"` + Bytes int64 `json:"bytes"` +} + +// BackupResult 备份结果。 +type BackupResult struct { + BackupPath string `json:"backupPath"` + TotalSize int64 `json:"totalSize"` + Checksum string `json:"checksum"` + Items []ItemResult `json:"items"` +} + +// CleanupResult 清理结果。 +type CleanupResult struct { + RangeStart int64 `json:"rangeStart"` + RangeEnd int64 `json:"rangeEnd"` + Deleted []ItemResult `json:"deleted"` + Skipped []ItemResult `json:"skipped"` // 删除失败(文件被占用等)跳过的记录 +} + +// MissingSeg 缺失时间段。 +type MissingSeg struct { + Start int64 `json:"start"` + End int64 `json:"end"` +} + +// CoverageResult 覆盖校验结果。 +type CoverageResult struct { + OK bool `json:"ok"` + Missing []MissingSeg `json:"missing"` +} + +// Progress 任务进度。 +type Progress struct { + JobID string `json:"jobId"` + Phase string `json:"phase"` // backup | cleanup + Stage string `json:"stage"` + Percent int `json:"percent"` + Message string `json:"message"` + Done bool `json:"done"` + Failed bool `json:"failed"` + Result any `json:"result,omitempty"` +} + +// Service 备份/清理服务。 +type Service struct { + client *ent.Client + ev *evlog.Writer + attRoot string + + mu sync.Mutex + jobs map[string]*Progress +} + +// New 构造服务。 +func New(client *ent.Client, ev *evlog.Writer, attRoot string) *Service { + return &Service{ + client: client, + ev: ev, + attRoot: attRoot, + jobs: make(map[string]*Progress), + } +} + +// ListItems 返回可选数据项。 +func (s *Service) ListItems() []ItemDef { return MESItems } + +// ---------------- 备份 ---------------- + +// StartBackup 启动异步备份,返回 jobID。 +func (s *Service) StartBackup(req BackupRequest) (string, error) { + if strings.TrimSpace(req.TargetPath) == "" { + return "", fmt.Errorf("请选择备份目标路径") + } + if !filepath.IsAbs(req.TargetPath) { + return "", fmt.Errorf("备份目标路径必须为绝对路径") + } + if req.End <= req.Start { + return "", fmt.Errorf("时间窗不合法(结束须晚于开始)") + } + if len(req.Items) == 0 { + return "", fmt.Errorf("请至少选择一个数据项") + } + jobID := newJobID() + s.mu.Lock() + s.jobs[jobID] = &Progress{JobID: jobID, Phase: "backup", Stage: "preparing", Percent: 0} + s.mu.Unlock() + go s.runBackup(jobID, req) + return jobID, nil +} + +func (s *Service) runBackup(jobID string, req BackupRequest) { + ctx := context.Background() + tStart := time.Unix(req.Start, 0) + tEnd := time.Unix(req.End, 0) + setStage := func(stage string, pct int, msg string) { + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Stage, j.Percent, j.Message = stage, pct, msg + } + s.mu.Unlock() + } + + // 估算体积并检查目标盘剩余空间 + est, err := s.estimateBytes(ctx, req) + if err != nil { + s.failBackup(jobID, req, err) + return + } + free, derr := diskFree(req.TargetPath) + if derr == nil && free < uint64(est) { + need := est - int64(free) + s.failBackup(jobID, req, fmt.Errorf("目标盘空间不足:需要约 %s,当前剩余 %s(还差 %s)", + humanBytes(est), humanBytes(int64(free)), humanBytes(need))) + return + } + + setStage("writing", 5, "准备写入备份包…") + stamp := time.Now().Format("20060102_150405") + zipPath := filepath.Join(req.TargetPath, "backup_mes_"+stamp+".zip") + if err := os.MkdirAll(req.TargetPath, 0o755); err != nil { + s.failBackup(jobID, req, fmt.Errorf("无法创建目标目录:%w", err)) + return + } + f, err := os.Create(zipPath) + if err != nil { + s.failBackup(jobID, req, fmt.Errorf("无法创建备份文件(U盘是否已拔出/无写入权限):%w", err)) + return + } + + h := sha256.New() + zw := newZipWriter(f, h) + results := make([]ItemResult, 0, len(req.Items)) + total := int64(0) + itemNames := make(map[string]string, len(MESItems)) + for _, it := range MESItems { + itemNames[it.Key] = it.Name + } + + for i, key := range req.Items { + setStage("writing", 5+int(float64(i)/float64(len(req.Items))*80), "导出 "+itemName(itemNames, key)+" …") + var ir ItemResult + var e error + if key == "attachment" { + ir, e = s.exportAttachment(ctx, zw, h, tStart, tEnd) + } else { + ir, e = s.exportLog(ctx, zw, h, key, tStart, tEnd) + } + if e != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("导出 %s 失败(U盘是否已拔出):%w", itemName(itemNames, key), e)) + return + } + ir.Key = key + ir.Name = itemName(itemNames, key) + results = append(results, ir) + total += ir.Bytes + } + + // manifest.json(先哈希后写入,便于校验) + manifest := map[string]any{ + "generatedAt": time.Now().Format(time.RFC3339), + "scope": "mes", + "rangeStart": req.Start, + "rangeEnd": req.End, + "rangeStartText": tStart.Format("2006-01-02 15:04:05"), + "rangeEndText": tEnd.Format("2006-01-02 15:04:05"), + "operator": req.Operator, + "items": results, + "totalSize": total, + "checksum": "", + } + manifestBytes, _ := json.MarshalIndent(manifest, "", " ") + if err := zw.WriteFile("manifest.json", manifestBytes); err != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("写入 manifest 失败:%w", err)) + return + } + + // index.html(清单 + 校验,不内嵌预览) + indexHTML := buildIndexHTML("MES 备份清单", manifest, "") + if err := zw.WriteFile("index.html", []byte(indexHTML)); err != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("写入 index.html 失败:%w", err)) + return + } + + if err := zw.Close(); err != nil { + _ = f.Close() + _ = os.Remove(zipPath) + // 备份包已随 os.Remove 删除,无残留产物:状态=failed(非 partial) + s.failBackup(jobID, req, fmt.Errorf("备份写入中断(U盘是否已拔出):%w", err)) + return + } + if err := f.Close(); err != nil { + _ = os.Remove(zipPath) + // 备份包已随 os.Remove 删除,无残留产物:状态=failed(非 partial) + s.failBackup(jobID, req, fmt.Errorf("备份文件关闭失败:%w", err)) + return + } + + fi, _ := os.Stat(zipPath) + if fi != nil { + total = fi.Size() + } + s.finishBackup(jobID, req, zipPath, results, total, hex.EncodeToString(h.Sum(nil)), false, nil) +} + +func (s *Service) exportLog(ctx context.Context, zw *zipWriter, h io.Writer, key string, tStart, tEnd time.Time) (ItemResult, error) { + var rows []any + var err error + switch key { + case "event_log": + list, e := s.client.EventLog.Query(). + Where(eventlog.CreatedAtGTE(tStart), eventlog.CreatedAtLTE(tEnd)).All(ctx) + rows, err = sliceToAny(list), e + case "plc_send_log": + list, e := s.client.PlcSendLog.Query(). + Where(plcsendlog.CreatedAtGTE(tStart), plcsendlog.CreatedAtLTE(tEnd)).All(ctx) + rows, err = sliceToAny(list), e + case "workpiece_lifecycle_log": + list, e := s.client.WorkpieceLifecycleLog.Query(). + Where(workpiecelifecyclelog.CreatedAtGTE(tStart), workpiecelifecyclelog.CreatedAtLTE(tEnd)).All(ctx) + rows, err = sliceToAny(list), e + case "alert": + list, e := s.client.Alert.Query(). + Where(alert.CreatedAtGTE(tStart), alert.CreatedAtLTE(tEnd)).All(ctx) + rows, err = sliceToAny(list), e + default: + return ItemResult{}, fmt.Errorf("未知数据项 %s", key) + } + if err != nil { + return ItemResult{}, err + } + ir := ItemResult{Rows: int64(len(rows))} + if err := zw.WriteJSONL(key+"/data.jsonl", rows, &ir.Bytes); err != nil { + return ir, err + } + return ir, nil +} + +func (s *Service) exportAttachment(ctx context.Context, zw *zipWriter, h io.Writer, tStart, tEnd time.Time) (ItemResult, error) { + rows, err := s.client.Attachment.Query(). + Where(attachment.CreatedAtGTE(tStart), attachment.CreatedAtLTE(tEnd)).All(ctx) + if err != nil { + return ItemResult{}, err + } + ir := ItemResult{Rows: int64(len(rows))} + meta := make([]map[string]any, 0, len(rows)) + for _, r := range rows { + abs, ok := safeAbsPath(s.attRoot, r.FilePath) + if !ok { + continue + } + _, ferr := os.Stat(abs) + if ferr != nil { + // 文件不存在(可能已挪走):仅记录元数据 + meta = append(meta, map[string]any{ + "id": r.ID, "fileName": r.FileName, "filePath": r.FilePath, + "fileSize": r.FileSize, "missing": true, + }) + continue + } + src, oerr := os.Open(abs) + if oerr != nil { + return ir, oerr + } + entryName := "attachments/" + strings.ReplaceAll(r.FilePath, "\\", "/") + n, cerr := zw.CopyFrom(entryName, src) + _ = src.Close() + if cerr != nil { + return ir, cerr + } + ir.Bytes += n + meta = append(meta, map[string]any{ + "id": r.ID, "fileName": r.FileName, "filePath": r.FilePath, + "fileSize": r.FileSize, "bytes": n, + }) + } + mb, _ := json.MarshalIndent(meta, "", " ") + if err := zw.WriteFile("attachment/data.jsonl", mb); err != nil { + return ir, err + } + ir.Bytes += int64(len(mb)) + return ir, nil +} + +func (s *Service) finishBackup(jobID string, req BackupRequest, zipPath string, results []ItemResult, total int64, checksum string, partial bool, runErr error) { + status := "success" + if partial { + status = "partial" + } + itemsJSON, _ := json.Marshal(results) + rec := s.client.BackupRecord.Create(). + SetExecutedAt(time.Now().Unix()). + SetRangeStart(req.Start). + SetRangeEnd(req.End). + SetBackupPath(zipPath). + SetTotalSize(total). + SetItemsJSON(string(itemsJSON)). + SetStatus(status). + SetOperator(req.Operator). + SetChecksum(checksum). + SetScope("mes") + if _, e := rec.Save(context.Background()); e != nil { + // 记录写入失败不影响已生成的备份包,但需提示 + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Failed = true + j.Message = "备份包已生成,但写入 backup_record 失败:" + e.Error() + j.Done = true + } + s.mu.Unlock() + return + } + // 补写 index.html 的校验和(重新打开追加不便,写入 event_log 即可体现) + s.ev.Write(context.Background(), "backup.create", "", req.Operator, "backup", "", + fmt.Sprintf("备份到 %s(范围 %s ~ %s,共 %d 项,%s,校验和 %s)", + zipPath, time.Unix(req.Start, 0).Format("2006-01-02"), time.Unix(req.End, 0).Format("2006-01-02"), + len(results), humanBytes(total), checksum), nil) + + res := BackupResult{BackupPath: zipPath, TotalSize: total, Checksum: checksum, Items: results} + if runErr != nil { + res.Checksum = checksum + } + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + if partial { + j.Failed = true + j.Message = "备份部分成功(U盘可能已拔出):" + runErr.Error() + } else { + j.Message = "备份完成" + } + j.Result = res + j.Percent = 100 + } + s.mu.Unlock() +} + +func (s *Service) failBackup(jobID string, req BackupRequest, runErr error) { + // 备份失败:backup_record 记 failed,清理入口不出现(覆盖校验只看 success) + status := "failed" + if strings.Contains(runErr.Error(), "U盘") || strings.Contains(runErr.Error(), "空间不足") { + status = "failed" + } + rec := s.client.BackupRecord.Create(). + SetExecutedAt(time.Now().Unix()). + SetRangeStart(req.Start). + SetRangeEnd(req.End). + SetBackupPath(""). + SetTotalSize(0). + SetItemsJSON("[]"). + SetStatus(status). + SetOperator(req.Operator). + SetChecksum(""). + SetScope("mes") + _, _ = rec.Save(context.Background()) + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Failed = true + j.Message = runErr.Error() + j.Percent = 100 + } + s.mu.Unlock() +} + +func (s *Service) estimateBytes(ctx context.Context, req BackupRequest) (int64, error) { + var total int64 + tStart := time.Unix(req.Start, 0) + tEnd := time.Unix(req.End, 0) + for _, key := range req.Items { + switch key { + case "attachment": + rows, err := s.client.Attachment.Query(). + Where(attachment.CreatedAtGTE(tStart), attachment.CreatedAtLTE(tEnd)).All(ctx) + if err != nil { + return 0, err + } + for _, r := range rows { + total += int64(r.FileSize) + } + total += int64(len(rows)) * 256 // 元数据 + default: + // 日志类按行数粗略估算(每行上限 1KB,偏高以保证有足够空间) + n, err := s.countLog(ctx, key, tStart, tEnd) + if err != nil { + return 0, err + } + total += n * 1024 + } + } + total += 4096 // manifest + index + return total, nil +} + +func (s *Service) countLog(ctx context.Context, key string, tStart, tEnd time.Time) (int64, error) { + var q interface{ Count(context.Context) (int, error) } + switch key { + case "event_log": + q = s.client.EventLog.Query().Where(eventlog.CreatedAtGTE(tStart), eventlog.CreatedAtLTE(tEnd)) + case "plc_send_log": + q = s.client.PlcSendLog.Query().Where(plcsendlog.CreatedAtGTE(tStart), plcsendlog.CreatedAtLTE(tEnd)) + case "workpiece_lifecycle_log": + q = s.client.WorkpieceLifecycleLog.Query().Where(workpiecelifecyclelog.CreatedAtGTE(tStart), workpiecelifecyclelog.CreatedAtLTE(tEnd)) + case "alert": + q = s.client.Alert.Query().Where(alert.CreatedAtGTE(tStart), alert.CreatedAtLTE(tEnd)) + default: + return 0, nil + } + n, err := q.Count(ctx) + return int64(n), err +} + +// ---------------- 清理 ---------------- + +// StartCleanup 启动异步清理,返回 jobID。 +func (s *Service) StartCleanup(req CleanupRequest) (string, error) { + if req.End <= req.Start { + return "", fmt.Errorf("时间窗不合法") + } + if len(req.Items) == 0 { + return "", fmt.Errorf("请至少选择一个数据项") + } + jobID := newJobID() + s.mu.Lock() + s.jobs[jobID] = &Progress{JobID: jobID, Phase: "cleanup", Stage: "checking", Percent: 0} + s.mu.Unlock() + go s.runCleanup(jobID, req) + return jobID, nil +} + +// CheckCoverage 校验备份覆盖(供前端预检)。 +func (s *Service) CheckCoverage(start, end int64) (CoverageResult, error) { + recs, err := s.client.BackupRecord.Query().Where(backuprecord.StatusEQ("success")).All(context.Background()) + if err != nil { + return CoverageResult{}, err + } + ivs := make([][2]int64, 0, len(recs)) + for _, r := range recs { + ivs = append(ivs, [2]int64{r.RangeStart, r.RangeEnd}) + } + missing := complement(ivs, start, end) + return CoverageResult{OK: len(missing) == 0, Missing: missing}, nil +} + +func (s *Service) runCleanup(jobID string, req CleanupRequest) { + ctx := context.Background() + setStage := func(stage string, pct int, msg string) { + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Stage, j.Percent, j.Message = stage, pct, msg + } + s.mu.Unlock() + } + + // 1) 覆盖校验 + cov, err := s.CheckCoverage(req.Start, req.End) + if err != nil { + s.failCleanup(jobID, req, fmt.Errorf("覆盖校验失败:%w", err)) + return + } + if !cov.OK { + s.failCleanup(jobID, req, fmt.Errorf("该时间窗未被完整备份,禁止清理。缺失时间段:%s", + formatMissing(cov.Missing))) + return + } + + tStart := time.Unix(req.Start, 0) + tEnd := time.Unix(req.End, 0) + deleted := make([]ItemResult, 0, len(req.Items)) + skipped := make([]ItemResult, 0, len(req.Items)) + + itemNames := make(map[string]string, len(MESItems)) + for _, it := range MESItems { + itemNames[it.Key] = it.Name + } + + // 2) 逐表清理 + for i, key := range req.Items { + setStage("cleaning", int(float64(i)/float64(len(req.Items))*90), "清理 "+itemName(itemNames, key)+" …") + if key == "attachment" { + d, sk, e := s.cleanupAttachment(ctx, tStart, tEnd) + if e != nil { + s.failCleanup(jobID, req, fmt.Errorf("清理附件失败:%w", e)) + return + } + d.Key, d.Name = key, itemName(itemNames, key) + sk.Key, sk.Name = key, itemName(itemNames, key) + deleted = append(deleted, d) + if sk.Rows > 0 { + skipped = append(skipped, sk) + } + } else { + n, e := s.cleanupLog(ctx, key, tStart, tEnd) + if e != nil { + s.failCleanup(jobID, req, fmt.Errorf("清理 %s 失败:%w", itemName(itemNames, key), e)) + return + } + deleted = append(deleted, ItemResult{Key: key, Name: itemName(itemNames, key), Rows: n, Bytes: 0}) + } + } + + // 3) 清理动作本身写一条 event_log + s.ev.Write(ctx, "backup.cleanup", "", req.Operator, "backup", "", + fmt.Sprintf("按时间窗清理(%s ~ %s):%s", + time.Unix(req.Start, 0).Format("2006-01-02"), time.Unix(req.End, 0).Format("2006-01-02"), + summaryDeleted(deleted, skipped)), nil) + + setStage("done", 100, "清理完成") + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Result = CleanupResult{RangeStart: req.Start, RangeEnd: req.End, Deleted: deleted, Skipped: skipped} + } + s.mu.Unlock() +} + +func (s *Service) cleanupLog(ctx context.Context, key string, tStart, tEnd time.Time) (int64, error) { + var q interface{ Exec(context.Context) (int, error) } + switch key { + case "event_log": + q = s.client.EventLog.Delete().Where(eventlog.CreatedAtGTE(tStart), eventlog.CreatedAtLTE(tEnd)) + case "plc_send_log": + q = s.client.PlcSendLog.Delete().Where(plcsendlog.CreatedAtGTE(tStart), plcsendlog.CreatedAtLTE(tEnd)) + case "workpiece_lifecycle_log": + q = s.client.WorkpieceLifecycleLog.Delete().Where(workpiecelifecyclelog.CreatedAtGTE(tStart), workpiecelifecyclelog.CreatedAtLTE(tEnd)) + case "alert": + q = s.client.Alert.Delete().Where(alert.CreatedAtGTE(tStart), alert.CreatedAtLTE(tEnd)) + default: + return 0, nil + } + n, err := q.Exec(ctx) + return int64(n), err +} + +// cleanupAttachment 物理删除文件 + DELETE 记录(附件文件由本端独占写入与引用,无需跨库校验)。 +// 返回 (deleted 结果, skipped 结果, error)。skipped 为删除失败(文件被占用等)跳过的记录。 +func (s *Service) cleanupAttachment(ctx context.Context, tStart, tEnd time.Time) (ItemResult, ItemResult, error) { + rows, err := s.client.Attachment.Query(). + Where(attachment.CreatedAtGTE(tStart), attachment.CreatedAtLTE(tEnd)).All(ctx) + if err != nil { + return ItemResult{}, ItemResult{}, err + } + del := ItemResult{} + sk := ItemResult{} + for _, r := range rows { + abs, ok := safeAbsPath(s.attRoot, r.FilePath) + if ok { + if rerr := os.Remove(abs); rerr != nil && !os.IsNotExist(rerr) { + // 删除失败(如文件被占用):跳过该记录,避免 DB 与磁盘不一致 + sk.Rows++ + continue + } + } + if _, derr := s.client.Attachment.Delete().Where(attachment.ID(r.ID)).Exec(ctx); derr != nil { + sk.Rows++ + continue + } + del.Rows++ + del.Bytes += int64(r.FileSize) + } + return del, sk, nil +} + +func (s *Service) failCleanup(jobID string, req CleanupRequest, runErr error) { + s.ev.Write(context.Background(), "backup.cleanup.reject", "", req.Operator, "backup", "", + "清理被拒:"+runErr.Error(), nil) + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Failed = true + j.Message = runErr.Error() + j.Percent = 100 + } + s.mu.Unlock() +} + +// ---------------- 进度 ---------------- + +// Progress 返回任务进度。 +func (s *Service) Progress(jobID string) (Progress, bool) { + s.mu.Lock() + defer s.mu.Unlock() + j, ok := s.jobs[jobID] + if !ok { + return Progress{}, false + } + cp := *j + return cp, true +} + +// ---------------- 工具 ---------------- + +func itemName(m map[string]string, key string) string { + if n, ok := m[key]; ok { + return n + } + return key +} + +// safeAbsPath 把库内相对路径安全解析为根目录内的绝对路径(阻断 ../ 穿越)。 +func safeAbsPath(root, rel string) (string, bool) { + rel = strings.ReplaceAll(rel, "\\", "/") + clean := filepath.Clean(filepath.Join(root, rel)) + rootAbs, err := filepath.Abs(root) + if err != nil { + return "", false + } + abs, err := filepath.Abs(clean) + if err != nil { + return "", false + } + if abs != rootAbs && !strings.HasPrefix(abs, rootAbs+string(os.PathSeparator)) { + return "", false + } + return abs, true +} + +func diskFree(path string) (uint64, error) { + var free uint64 + p, err := windows.UTF16PtrFromString(path) + if err != nil { + return 0, err + } + if err := windows.GetDiskFreeSpaceEx(p, &free, nil, nil); err != nil { + return 0, err + } + return free, nil +} + +func humanBytes(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + div, exp := int64(unit), 0 + for x := n / unit; x >= unit; x /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.2f %cB", float64(n)/float64(div), "KMGTPE"[exp]) +} + +func newJobID() string { + b := make([]byte, 8) + _, _ = io.ReadFull(randReader(), b) + return hex.EncodeToString(b) + fmt.Sprintf("%d", time.Now().UnixNano()%100000) +} diff --git a/bj_power_mes/internal/backup/browse.go b/bj_power_mes/internal/backup/browse.go new file mode 100644 index 0000000..9bd4623 --- /dev/null +++ b/bj_power_mes/internal/backup/browse.go @@ -0,0 +1,78 @@ +package backup + +import ( + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/windows" +) + +// DriveInfo 盘符信息(Windows)。 +type DriveInfo struct { + Letter string `json:"letter"` + Path string `json:"path"` +} + +// ListDrives 列出本机所有盘符(Windows)。 +func ListDrives() ([]DriveInfo, error) { + mask, err := windows.GetLogicalDrives() + if err != nil { + return nil, err + } + out := make([]DriveInfo, 0) + for i := 0; i < 26; i++ { + if mask&(1< 0 { + last := recs[len(recs)-1] // 按 executedAt 升序,末位即最近 + res.LastBackupAt = last.ExecutedAt + res.LastBackupPath = last.BackupPath + } + if remindDays > 0 && res.LastBackupAt > 0 { + due := res.LastBackupAt + int64(remindDays)*86400 + res.Overdue = time.Now().Unix() >= due + } + return res, nil +} + +// PreviewItem 单项预览。 +type PreviewItem struct { + Key string `json:"key"` + Name string `json:"name"` + Rows int64 `json:"rows"` + Bytes int64 `json:"bytes"` +} + +// PreviewResult 清理预览结果。 +type PreviewResult struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []PreviewItem `json:"items"` + TotalRows int64 `json:"totalRows"` + TotalBytes int64 `json:"totalBytes"` +} + +// Preview 计算各数据项在 [start,end] 时间窗内「将删除」的行数与字节(仅估算,不落盘)。 +func (s *Service) Preview(start, end int64, keys []string) (PreviewResult, error) { + res := PreviewResult{Start: start, End: end} + tStart := time.Unix(start, 0) + tEnd := time.Unix(end, 0) + itemNames := make(map[string]string, len(MESItems)) + for _, it := range MESItems { + itemNames[it.Key] = it.Name + } + ctx := context.Background() + for _, key := range keys { + var pi PreviewItem + var e error + if key == "attachment" { + pi.Rows, pi.Bytes, e = s.previewAttachment(ctx, tStart, tEnd) + } else { + pi.Rows, e = s.countLog(ctx, key, tStart, tEnd) + pi.Bytes = pi.Rows * 1024 // 与 estimateBytes 同口径估算 + } + if e != nil { + return res, e + } + pi.Key = key + pi.Name = itemName(itemNames, key) + res.Items = append(res.Items, pi) + res.TotalRows += pi.Rows + res.TotalBytes += pi.Bytes + } + sort.Slice(res.Items, func(i, j int) bool { return res.Items[i].Key < res.Items[j].Key }) + return res, nil +} + +// previewAttachment 估算将删附件数量与字节(按 filePath 取 DB 记录,不实际删)。 +func (s *Service) previewAttachment(ctx context.Context, tStart, tEnd time.Time) (int64, int64, error) { + rows, err := s.client.Attachment.Query(). + Where(attachment.CreatedAtGTE(tStart), attachment.CreatedAtLTE(tEnd)).All(ctx) + if err != nil { + return 0, 0, err + } + var bytes int64 + for _, r := range rows { + bytes += int64(r.FileSize) + } + return int64(len(rows)), bytes, nil +} + +// RecordItem 单条备份/清理历史(对应 backup_record 表)。 +type RecordItem struct { + ID int `json:"id"` + ExecutedAt int64 `json:"executedAt"` + RangeStart int64 `json:"rangeStart"` + RangeEnd int64 `json:"rangeEnd"` + BackupPath string `json:"backupPath"` + TotalSize int64 `json:"totalSize"` + Status string `json:"status"` + Operator string `json:"operator"` + Scope string `json:"scope"` + ItemsJSON string `json:"itemsJson"` + Checksum string `json:"checksum"` +} + +// RecordsResult 历史列表(分页)。 +type RecordsResult struct { + Total int64 `json:"total"` + List []RecordItem `json:"list"` + Page int `json:"page"` + Size int `json:"size"` +} + +// ListRecords 分页查询 backup_record(按 executedAt 倒序);status/scope 可空过滤。 +// 历史永久保留,不清(覆盖校验仅认 success)。 +func (s *Service) ListRecords(page, size int, status, scope string) (RecordsResult, error) { + if size <= 0 { + size = 50 + } + if page <= 0 { + page = 1 + } + all, err := s.client.BackupRecord.Query(). + Order(backuprecord.ByExecutedAt()). + All(context.Background()) + if err != nil { + return RecordsResult{}, err + } + // 过滤 + filtered := make([]*ent.BackupRecord, 0, len(all)) + for _, r := range all { + if status != "" && r.Status != status { + continue + } + if scope != "" && r.Scope != scope { + continue + } + filtered = append(filtered, r) + } + // 倒序(最近在前) + for i, j := 0, len(filtered)-1; i < j; i, j = i+1, j-1 { + filtered[i], filtered[j] = filtered[j], filtered[i] + } + total := int64(len(filtered)) + start := (page - 1) * size + if start > len(filtered) { + start = len(filtered) + } + end := start + size + if end > len(filtered) { + end = len(filtered) + } + list := make([]RecordItem, 0, end-start) + for _, r := range filtered[start:end] { + list = append(list, RecordItem{ + ID: r.ID, ExecutedAt: r.ExecutedAt, RangeStart: r.RangeStart, RangeEnd: r.RangeEnd, + BackupPath: r.BackupPath, TotalSize: r.TotalSize, Status: r.Status, + Operator: r.Operator, Scope: r.Scope, ItemsJSON: r.ItemsJSON, Checksum: r.Checksum, + }) + } + return RecordsResult{Total: total, List: list, Page: page, Size: size}, nil +} diff --git a/bj_power_mes/internal/backup/util.go b/bj_power_mes/internal/backup/util.go new file mode 100644 index 0000000..b0021b3 --- /dev/null +++ b/bj_power_mes/internal/backup/util.go @@ -0,0 +1,131 @@ +package backup + +import ( + "crypto/rand" + "fmt" + "io" + "reflect" + "strings" + "time" +) + +// randReader 安全随机源。 +func randReader() io.Reader { return rand.Reader } + +// sliceToAny 把任意切片([]*ent.Xxx)转成 []any,便于统一 JSON 序列化。 +func sliceToAny(slice any) []any { + if slice == nil { + return nil + } + v := reflect.ValueOf(slice) + if v.Kind() != reflect.Slice { + return nil + } + out := make([]any, v.Len()) + for i := 0; i < v.Len(); i++ { + out[i] = v.Index(i).Interface() + } + return out +} + +// complement 计算 [start,end] 在被若干区间并集覆盖后的缺失段(闭区间,秒)。 +func complement(intervals [][2]int64, start, end int64) []MissingSeg { + if start > end { + return nil + } + // 归一化并排序 + ivs := make([][2]int64, 0, len(intervals)) + for _, iv := range intervals { + if iv[0] <= iv[1] && iv[1] >= start && iv[0] <= end { + ivs = append(ivs, [2]int64{maxInt64(iv[0], start), minInt64(iv[1], end)}) + } + } + sortIntervals(ivs) + missing := make([]MissingSeg, 0) + cur := start + for _, iv := range ivs { + if iv[0] > cur { + missing = append(missing, MissingSeg{Start: cur, End: iv[0] - 1}) + } + if iv[1] > cur { + cur = iv[1] + 1 + } + } + if cur <= end { + missing = append(missing, MissingSeg{Start: cur, End: end}) + } + return missing +} + +func sortIntervals(ivs [][2]int64) { + for i := 0; i < len(ivs); i++ { + for j := i + 1; j < len(ivs); j++ { + if ivs[j][0] < ivs[i][0] { + ivs[i], ivs[j] = ivs[j], ivs[i] + } + } + } +} + +func maxInt64(a, b int64) int64 { + if a > b { + return a + } + return b +} +func minInt64(a, b int64) int64 { + if a < b { + return a + } + return b +} + +func formatMissing(segs []MissingSeg) string { + parts := make([]string, 0, len(segs)) + for _, s := range segs { + parts = append(parts, fmt.Sprintf("%s ~ %s", + time.Unix(s.Start, 0).Format("2006-01-02"), time.Unix(s.End, 0).Format("2006-01-02"))) + } + return strings.Join(parts, ";") +} + +func summaryDeleted(deleted, skipped []ItemResult) string { + var b strings.Builder + for _, d := range deleted { + fmt.Fprintf(&b, "%s 删除 %d 行;", d.Name, d.Rows) + } + if len(skipped) > 0 { + b.WriteString(" 跳过共享附件(对端未备份):") + for _, s := range skipped { + fmt.Fprintf(&b, "%s %d 个;", s.Name, s.Rows) + } + } + return strings.TrimRight(b.String(), ";") +} + +// buildIndexHTML 生成备份清单页(仅清单 + 校验,不内嵌预览)。 +func buildIndexHTML(title string, manifest map[string]any, checksum string) string { + items, _ := manifest["items"].([]ItemResult) + var rows strings.Builder + for _, it := range items { + fmt.Fprintf(&rows, "
\n", it.Name, it.Rows, humanBytes(it.Bytes)) + } + if checksum == "" { + if c, ok := manifest["checksum"].(string); ok { + checksum = c + } + } + cs := checksum + if cs == "" { + cs = "(见 backup_record.checksum)" + } + return fmt.Sprintf(` +%s +

%s

+

范围:%s ~ %s | 操作人:%s | 校验和(sha256):%s

+

数据项

%s%d%s
%s
数据项行数字节
+

本文件仅作清单与校验用途,不内嵌任何数据预览。完整数据见包内各 data.jsonl 与 attachments/ 目录。

+`, title, title, manifest["rangeStartText"], manifest["rangeEndText"], manifest["operator"], cs, rows.String()) +} diff --git a/bj_power_mes/internal/backup/zip.go b/bj_power_mes/internal/backup/zip.go new file mode 100644 index 0000000..6366a5a --- /dev/null +++ b/bj_power_mes/internal/backup/zip.go @@ -0,0 +1,79 @@ +package backup + +import ( + "archive/zip" + "bytes" + "encoding/json" + "io" + "os" +) + +// zipWriter 把内容流式写入 zip,同时更新一个哈希 writer(用于备份包校验和)。 +// 直接写入目标文件,不落本地临时文件。 +type zipWriter struct { + zw *zip.Writer + f *os.File + h io.Writer +} + +func newZipWriter(f *os.File, h io.Writer) *zipWriter { + if h == nil { + h = io.Discard + } + return &zipWriter{zw: zip.NewWriter(f), f: f, h: h} +} + +// WriteFile 写入一个普通文件(同时更新哈希)。 +func (z *zipWriter) WriteFile(name string, data []byte) error { + w, err := z.zw.Create(name) + if err != nil { + return err + } + if _, err := io.Copy(io.MultiWriter(w, z.h), bytes.NewReader(data)); err != nil { + return err + } + return nil +} + +// WriteJSONL 把每行 JSON 编码写入(同时更新哈希与字节计数)。 +func (z *zipWriter) WriteJSONL(name string, rows []any, n *int64) error { + w, err := z.zw.Create(name) + if err != nil { + return err + } + cw := &countingWriter{w: io.MultiWriter(w, z.h), n: n} + enc := json.NewEncoder(cw) + for _, r := range rows { + if err := enc.Encode(r); err != nil { + return err + } + } + return nil +} + +// CopyFrom 把 src 拷贝进 zip(同时更新哈希),返回写入字节数。 +func (z *zipWriter) CopyFrom(name string, src io.Reader) (int64, error) { + w, err := z.zw.Create(name) + if err != nil { + return 0, err + } + return io.Copy(io.MultiWriter(w, z.h), src) +} + +// Close 关闭 zip(写出中央目录)。目标文件不在此关闭——由调用方统一 f.Close() 一次, +// 避免本方法关过 f 后调用方再关触发 "file already closed"(曾因此误删已生成的备份包)。 +func (z *zipWriter) Close() error { + return z.zw.Close() +} + +// countingWriter 写入时累加字节数到 *n。 +type countingWriter struct { + w io.Writer + n *int64 +} + +func (c *countingWriter) Write(p []byte) (int, error) { + nn, err := c.w.Write(p) + *c.n += int64(nn) + return nn, err +} diff --git a/bj_power_mes/internal/config/config.go b/bj_power_mes/internal/config/config.go index d53fa5f..447837c 100644 --- a/bj_power_mes/internal/config/config.go +++ b/bj_power_mes/internal/config/config.go @@ -92,10 +92,8 @@ type UploadConf struct { MaxMB int64 `json:",default=20"` // 单文件默认上限(MB) // 按文件类型覆盖上限(字节),键为大写枚举,如 PROCESS_PDF: 52428800 MaxSize map[string]int64 `json:",optional"` - // 本地保留年数(超过该年数的附件可归档到 ArchiveDir 后释放本地空间) + // 本地保留年数(检验记录质量追溯保留期,期内禁删) LocalRetentionYears int `json:",default=1"` - // 归档备份目录(NAS/移动硬盘等);为空时归档只标记不移动 - ArchiveDir string `json:",default="` // 磁盘空间监控:每天 DiskCheckHour 点检测一次 DiskWarnPercent int `json:",default=20"` // 剩余低于该百分比告警 DiskCriticalPercent int `json:",default=10"` // 剩余低于该百分比提示清理 diff --git a/bj_power_mes/internal/db/db.go b/bj_power_mes/internal/db/db.go index 80bc347..5e3ec4f 100644 --- a/bj_power_mes/internal/db/db.go +++ b/bj_power_mes/internal/db/db.go @@ -205,7 +205,7 @@ var schemaPatchSQL = []string{ `ALTER TABLE workpiece DROP COLUMN IF EXISTS process_seq`, `ALTER TABLE daily_plan DROP COLUMN IF EXISTS dock_codes`, // station 上早期「1:1 接驳台绑定」字段(dock_code/has_dock)已从 ent schema 移除(2026-10-13): - // 工位↔接驳台为 M:N,由 dock 表 station_no 承载(工位1~10 各 R1/R2 两个),此处清存量库残留列与唯一索引。 + // 工位↔接驳台为 M:N,由 dock 表 station_no 承载(工位1~10 各左L/右R 两个),此处清存量库残留列与唯一索引。 `DROP INDEX IF EXISTS ux_station_dock_code`, `ALTER TABLE station DROP COLUMN IF EXISTS dock_code`, `ALTER TABLE station DROP COLUMN IF EXISTS has_dock`, @@ -232,7 +232,7 @@ var schemaPatchSQL = []string{ `ALTER TABLE attachment ADD COLUMN IF NOT EXISTS deleted_by varchar(64) NOT NULL DEFAULT ''`, // ---- 接驳台主数据迁入 MES(2026-09-21,真源自 WMS 移入)---- - // 一个工位可绑多个接驳台(工位1~10 各 R1/R2 两个,对应1号/2号AGV);库房接驳台 DOCK21 station_no=0 不参与工位映射。 + // 一个工位可绑多个接驳台(工位1~10 各左L/右R 两个,命名与 AGV 编号无关);库房接驳台 DOCK21 station_no=0 不参与工位映射。 // 撤销早期 1:1 唯一索引,允许 station_no 重复(索引若已存在则删除,幂等)。 `DROP INDEX IF EXISTS ux_dock_station_no`, diff --git a/bj_power_mes/internal/handler/attachment.go b/bj_power_mes/internal/handler/attachment.go index 96fa1aa..cb68762 100644 --- a/bj_power_mes/internal/handler/attachment.go +++ b/bj_power_mes/internal/handler/attachment.go @@ -263,91 +263,4 @@ func AttachmentDiskStatusHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { } } -// AttachmentArchiveHandler POST /attachment/archive {dryRun} 归档 -// 把「早于本地保留年数」的附件移动到 ArchiveDir 并标记 archived=true(保留索引可追溯)。 -// ArchiveDir 为空时只标记不移动;dryRun=true 时仅返回将被归档的数量。 -func AttachmentArchiveHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - DryRun bool `json:"dryRun"` - } - _ = httpx.ParseJSON(r, &req) - cfg := svcCtx.Config.Upload - years := cfg.LocalRetentionYears - if years <= 0 { - years = 1 - } - cutYear := time.Now().Year() - years // 早于该年份的附件可归档 - svc := logic.New(svcCtx) - recs, err := svc.ListArchivableAttachments(r.Context()) - if err != nil { - httpx.Fail(w, 3314, err.Error()) - return - } - moved, marked, failed := 0, 0, 0 - for _, rec := range recs { - if rec.CreatedAt.Year() > cutYear-1 { - continue - } - if req.DryRun { - marked++ - continue - } - if cfg.ArchiveDir != "" { - src, ok1 := safeAbsPath(cfg.Dir, rec.FilePath) - dst, ok2 := safeAbsPath(cfg.ArchiveDir, rec.FilePath) - if !ok1 || !ok2 { - failed++ - continue - } - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - failed++ - continue - } - if err := os.Rename(src, dst); err != nil { - if err2 := copyFile(src, dst); err2 != nil { - failed++ - continue - } - _ = os.Remove(src) - } - moved++ - } - if err := svc.MarkArchived(r.Context(), rec.ID); err != nil { - failed++ - continue - } - marked++ - } - if !req.DryRun { - svcCtx.EventLog.Write(r.Context(), "attachment.archive", "", operator(r, ""), "attachment", "archive", - fmt.Sprintf("附件归档:移动%d 标记%d 失败%d(早于 %d 年)", moved, marked, failed, cutYear), - map[string]any{"moved": moved, "marked": marked, "failed": failed}) - } - httpx.Ok(w, map[string]any{ - "moved": moved, "marked": marked, "failed": failed, - "cutYear": cutYear, "archiveDir": cfg.ArchiveDir, "dryRun": req.DryRun, - }) - } -} -// copyFile 兜底复制(跨盘符 Rename 失败时用)。 -func copyFile(src, dst string) error { - in, err := os.Open(src) - if err != nil { - return err - } - defer in.Close() - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - return err - } - out, err := os.Create(dst) - if err != nil { - return err - } - if _, err := out.ReadFrom(in); err != nil { - _ = out.Close() - return err - } - return out.Close() -} diff --git a/bj_power_mes/internal/handler/backup.go b/bj_power_mes/internal/handler/backup.go new file mode 100644 index 0000000..94a48e6 --- /dev/null +++ b/bj_power_mes/internal/handler/backup.go @@ -0,0 +1,181 @@ +package handler + +import ( + "net/http" + "strconv" + + "bj_power_mes/common/httpx" + "bj_power_mes/internal/backup" + "bj_power_mes/internal/logic" + "bj_power_mes/internal/svc" +) + +// BackupItemsHandler GET /api/v1/backup/items 可选数据项(质量 4 表不出现) +func BackupItemsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + httpx.Ok(w, svcCtx.Backup.ListItems()) + } +} + +// BackupStartHandler POST /api/v1/backup/start 启动备份 +func BackupStartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req backup.BackupRequest + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + req.Operator = operator(r, "") + jobID, err := svcCtx.Backup.StartBackup(req) + if err != nil { + httpx.Fail(w, 2601, err.Error()) + return + } + httpx.Ok(w, map[string]any{"jobId": jobID}) + } +} + +// BackupProgressHandler GET /api/v1/backup/progress?jobId= +func BackupProgressHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + jobID := r.URL.Query().Get("jobId") + p, ok := svcCtx.Backup.Progress(jobID) + if !ok { + httpx.Fail(w, 2602, "任务不存在") + return + } + httpx.Ok(w, p) + } +} + +// CleanupCheckHandler POST /api/v1/cleanup/check 覆盖预检(部分/无覆盖拒绝) +func CleanupCheckHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + Start int64 `json:"start"` + End int64 `json:"end"` + } + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + cov, err := svcCtx.Backup.CheckCoverage(req.Start, req.End) + if err != nil { + httpx.Fail(w, 2603, err.Error()) + return + } + httpx.Ok(w, cov) + } +} + +// CleanupStartHandler POST /api/v1/cleanup/start 启动清理(物理删除) +func CleanupStartHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req backup.CleanupRequest + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + req.Operator = operator(r, "") + jobID, err := svcCtx.Backup.StartCleanup(req) + if err != nil { + httpx.Fail(w, 2604, err.Error()) + return + } + httpx.Ok(w, map[string]any{"jobId": jobID}) + } +} + +// CleanupProgressHandler GET /api/v1/cleanup/progress?jobId= +func CleanupProgressHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + jobID := r.URL.Query().Get("jobId") + p, ok := svcCtx.Backup.Progress(jobID) + if !ok { + httpx.Fail(w, 2605, "任务不存在") + return + } + httpx.Ok(w, p) + } +} + +// BackupDrivesHandler GET /api/v1/backup/drives 列出本机盘符(admin-only,用于服务端目录选择器) +func BackupDrivesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + drives, err := backup.ListDrives() + if err != nil { + httpx.Fail(w, 2606, "读取盘符失败:"+err.Error()) + return + } + httpx.Ok(w, drives) + } +} + +// BackupListDirHandler GET /api/v1/backup/listdir?path= 列出给定目录的一级子目录(admin-only) +func BackupListDirHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + dirs, err := backup.ListDir(r.URL.Query().Get("path")) + if err != nil { + httpx.Fail(w, 2607, "读取目录失败:"+err.Error()) + return + } + httpx.Ok(w, dirs) + } +} + +// BackupReminderHandler GET /api/v1/backup/reminder 清理提醒(按 backup_record 最近 success + 提醒周期算超期) +func BackupReminderHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + days := logic.New(svcCtx).CfgInt(r.Context(), logic.CfgArchiveRemindDays, 7) + res, err := svcCtx.Backup.Reminder(days) + if err != nil { + httpx.Fail(w, 2608, err.Error()) + return + } + httpx.Ok(w, res) + } +} + +// CleanupPreviewHandler POST /api/v1/cleanup/preview 清理预览(将删除行数/字节,不落盘) +func CleanupPreviewHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + } + if err := httpx.ParseJSON(r, &req); err != nil { + httpx.BadRequest(w, "请求体解析失败") + return + } + if req.End <= req.Start { + httpx.Fail(w, 2609, "时间窗不合法") + return + } + if len(req.Items) == 0 { + httpx.Fail(w, 2610, "请至少选择一个数据项") + return + } + res, err := svcCtx.Backup.Preview(req.Start, req.End, req.Items) + if err != nil { + httpx.Fail(w, 2611, err.Error()) + return + } + httpx.Ok(w, res) + } +} + +// BackupRecordsHandler GET /api/v1/backup/records 备份/清理历史(分页 50/页) +func BackupRecordsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + page, _ := strconv.Atoi(q.Get("page")) + size, _ := strconv.Atoi(q.Get("size")) + res, err := svcCtx.Backup.ListRecords(page, size, q.Get("status"), q.Get("scope")) + if err != nil { + httpx.Fail(w, 2612, err.Error()) + return + } + httpx.Ok(w, res) + } +} diff --git a/bj_power_mes/internal/handler/perm.go b/bj_power_mes/internal/handler/perm.go index 88ce475..8e5ff36 100644 --- a/bj_power_mes/internal/handler/perm.go +++ b/bj_power_mes/internal/handler/perm.go @@ -47,10 +47,9 @@ var pathPermMap = map[string]string{ //(produce.quality:process / produce.quality:final),此处不映射单一码,避免误拦/误放。 // 检验员签字确认(需求B 第二签,巡检终端「待签任务」) "POST:/api/v1/signs/inspector": "sys.inspect:sign", - // 附件中心(sys.attachment 菜单下):删除 / 归档清理属管理动作; + // 附件中心(sys.attachment 菜单下):删除属管理动作; // 列表/预览/下载不设按钮门槛(有菜单权限即可查阅) - "POST:/api/v1/attachment/delete": "sys.attachment:manage", - "POST:/api/v1/attachment/archive": "sys.attachment:manage", + "POST:/api/v1/attachment/delete": "sys.attachment:manage", // 账号管理(拆分自原 sys.rbac:user;sys.account 菜单下增/改/删) "POST:/api/v1/users": "sys.account:add", "PUT:/api/v1/users": "sys.account:edit", diff --git a/bj_power_mes/internal/handler/production/production.go b/bj_power_mes/internal/handler/production/production.go index 78c1bbb..bb08d12 100644 --- a/bj_power_mes/internal/handler/production/production.go +++ b/bj_power_mes/internal/handler/production/production.go @@ -336,6 +336,19 @@ func DashboardSnapshotInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFu } } +// DashboardConfigInternalHandler 门口看板(项目A)启动配置:标题文字 + 语音播报开关。 +// 基础设置页(dashboard.board.title / dashboard.board.voice)维护,保存即生效;看板端轮询跟随。 +func DashboardConfigInternalHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + vo, err := logic.New(svcCtx).GetSettings(r.Context()) + if err != nil { + httpx.Fail(w, 2010, err.Error()) + return + } + httpx.Ok(w, map[string]any{"title": vo.DashboardTitle, "voiceOn": vo.DashboardVoice}) + } +} + // DashboardMaterialQueryHandler 看板物料追溯查询入口(C7):转发 WMS 物料档案 + 库存。 func DashboardMaterialQueryHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { diff --git a/bj_power_mes/internal/handler/routes.go b/bj_power_mes/internal/handler/routes.go index 601e1f0..8384491 100644 --- a/bj_power_mes/internal/handler/routes.go +++ b/bj_power_mes/internal/handler/routes.go @@ -37,6 +37,20 @@ func RegisterRoutes(server *rest.Server, serverCtx *svc.ServiceContext) { {Method: http.MethodPost, Path: "/permissions", Handler: CreatePermissionHandler(serverCtx)}, {Method: http.MethodPut, Path: "/permissions", Handler: UpdatePermissionHandler(serverCtx)}, {Method: http.MethodDelete, Path: "/permissions/:id", Handler: DeletePermissionHandler(serverCtx)}, + + // 备份到外部存储(U盘/移动硬盘)+ 按时间窗物理清理 + {Method: http.MethodGet, Path: "/backup/items", Handler: BackupItemsHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/backup/start", Handler: BackupStartHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/backup/progress", Handler: BackupProgressHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/cleanup/check", Handler: CleanupCheckHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/cleanup/start", Handler: CleanupStartHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/cleanup/progress", Handler: CleanupProgressHandler(serverCtx)}, + // 数据归档增强:目录选择器 / 提醒 / 预览 / 历史 + {Method: http.MethodGet, Path: "/backup/drives", Handler: BackupDrivesHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/backup/listdir", Handler: BackupListDirHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/backup/reminder", Handler: BackupReminderHandler(serverCtx)}, + {Method: http.MethodPost, Path: "/cleanup/preview", Handler: CleanupPreviewHandler(serverCtx)}, + {Method: http.MethodGet, Path: "/backup/records", Handler: BackupRecordsHandler(serverCtx)}, } server.AddRoutes( rest.WithMiddlewares([]rest.Middleware{permissionGuard(serverCtx)}, jwtAdmin...), diff --git a/bj_power_mes/internal/handler/routes_production.go b/bj_power_mes/internal/handler/routes_production.go index 1725a29..e118ff9 100644 --- a/bj_power_mes/internal/handler/routes_production.go +++ b/bj_power_mes/internal/handler/routes_production.go @@ -44,6 +44,9 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/dashboard/snapshot", Handler: internal(production.DashboardSnapshotInternalHandler(serverCtx)), }) + server.AddRoute(rest.Route{ + Method: http.MethodGet, Path: "/api/internal/dashboard/config", Handler: internal(production.DashboardConfigInternalHandler(serverCtx)), + }) server.AddRoute(rest.Route{ Method: http.MethodGet, Path: "/api/internal/dashboard/material-query", Handler: internal(production.DashboardMaterialQueryHandler(serverCtx)), }) @@ -343,7 +346,6 @@ func RegisterProductionRoutes(server *rest.Server, serverCtx *svc.ServiceContext {Method: http.MethodGet, Path: "/attachment/all", Handler: AttachmentCenterHandler(serverCtx)}, {Method: http.MethodGet, Path: "/attachment/file/:id", Handler: AttachmentFileHandler(serverCtx)}, {Method: http.MethodGet, Path: "/attachment/disk-status", Handler: DiskStatusHandler(serverCtx)}, - {Method: http.MethodPost, Path: "/attachment/archive", Handler: AttachmentArchiveHandler(serverCtx)}, {Method: http.MethodPost, Path: "/attachment/delete", Handler: AttachmentDeleteHandler(serverCtx)}, // ---------- 工艺流程/工位(块3) ---------- diff --git a/bj_power_mes/internal/logic/attachment.go b/bj_power_mes/internal/logic/attachment.go index 25c7113..96df918 100644 --- a/bj_power_mes/internal/logic/attachment.go +++ b/bj_power_mes/internal/logic/attachment.go @@ -93,16 +93,4 @@ func (s *Service) ListAttachmentPage(ctx context.Context, fileType, bizType, biz return total, list, nil } -// ListArchivableAttachments 列出「未归档且未删除」的附件(归档任务用,年份判断在调用方)。 -func (s *Service) ListArchivableAttachments(ctx context.Context) ([]*ent.Attachment, error) { - return s.ctx.EntClient.Attachment.Query(). - Where(attachment.ArchivedEQ(false), attachment.DeletedEQ(false)). - All(ctx) -} -// MarkArchived 标记附件已归档(物理文件已移到外部备份目录)。 -func (s *Service) MarkArchived(ctx context.Context, id int) error { - _, err := s.ctx.EntClient.Attachment.UpdateOneID(id). - SetArchived(true).SetArchivedAt(time.Now().Unix()).Save(ctx) - return err -} diff --git a/bj_power_mes/internal/logic/call.go b/bj_power_mes/internal/logic/call.go index 1d05d22..523e2f6 100644 --- a/bj_power_mes/internal/logic/call.go +++ b/bj_power_mes/internal/logic/call.go @@ -356,7 +356,7 @@ func (s *Service) CreateCallOrders(ctx context.Context, stationNo int, items []C return 0, errors.New("工位已停用,不能叫料") } allowCross := s.CfgInt(ctx, CfgAllowCrossDay, 1) == 1 - // 接驳台校验:目标接驳台必须属于该工位(一工位 R1/R2 两个,真源=dock 表) + // 接驳台校验:目标接驳台必须属于该工位(一工位左L/右R 两个,真源=dock 表) dockSet := map[string]bool{} if dks, e := s.ctx.EntClient.Dock.Query().Where(dock.StationNo(stationNo)).All(ctx); e == nil { for _, d := range dks { diff --git a/bj_power_mes/internal/logic/dailyplan.go b/bj_power_mes/internal/logic/dailyplan.go index 96ae272..f2119ba 100644 --- a/bj_power_mes/internal/logic/dailyplan.go +++ b/bj_power_mes/internal/logic/dailyplan.go @@ -232,7 +232,7 @@ func (s *Service) saveDailyPlanBatch(ctx context.Context, req DailyPlanReq, oper // SuggestedDockCodes 查工单工艺组合覆盖工位的接驳台编码,供排产/备料默认推荐。 // 路线唯一源头 = 工单 flow_combination(按工位号升序);接驳台真源 = dock 表(按 station_no 聚合, -// 一个工位可配 R1/R2 多个接驳台),station.dock_code 仅默认兜底,故统一从 dock 表取全集。 +// 一个工位可配 左L/右R 多个接驳台),station.dock_code 仅默认兜底,故统一从 dock 表取全集。 func (s *Service) SuggestedDockCodes(ctx context.Context, orderNo string) []string { wo, err := s.ctx.EntClient.WorkOrder.Query().Where(workorder.WorkOrderNo(orderNo)).First(ctx) if err != nil { diff --git a/bj_power_mes/internal/logic/dashboard.go b/bj_power_mes/internal/logic/dashboard.go index f102921..8a94035 100644 --- a/bj_power_mes/internal/logic/dashboard.go +++ b/bj_power_mes/internal/logic/dashboard.go @@ -13,10 +13,12 @@ import ( "bj_power_mes/ent/materialrequest" "bj_power_mes/ent/plcsendlog" "bj_power_mes/ent/station" + "bj_power_mes/ent/stationstate" "bj_power_mes/ent/torquerecord" "bj_power_mes/ent/workorder" "bj_power_mes/ent/workpiece" "bj_power_mes/ent/workpieceprocess" + "bj_power_mes/internal/plc" ) const dashboardTTL = 60 // 秒,看板缓存 @@ -509,6 +511,9 @@ func (s *Service) buildEquipment(ctx context.Context, today time.Time) []Station v.CurrentSn = r.Sn v.CurrentOperator = r.Operator v.CurrentFlowId = r.FlowId + if v.CurrentProcess == "" { + v.CurrentProcess = r.ProcessName + } } if v.Status != "alarm" { if strings.EqualFold(r.Result, "NG") { @@ -521,6 +526,19 @@ func (s *Service) buildEquipment(ctx context.Context, today time.Time) []Station } } + // 当天停单(station_state):paused=true 时前端仅以图标提示,不渲染刺眼文字 + if pauses, err := s.ctx.EntClient.StationState.Query(). + Where(stationstate.Date(today.Format("2006-01-02")), stationstate.Paused(true)). + All(ctx); err == nil { + for _, p := range pauses { + if v, ok := stMap[p.StationNo]; ok { + v.Paused = true + v.PauseReason = p.Reason + stMap[p.StationNo] = v + } + } + } + // 当日累计:每个工位的完成数与 NG 数 if steps, err := s.ctx.EntClient.WorkpieceProcess.Query(). Where(workpieceprocess.EndedAtGTE(today)).All(ctx); err == nil { @@ -602,6 +620,65 @@ func agvStatusFromRequest(status string) string { } } +// ============================================================ +// 看板点位态(主线 C1~C15 / 接驳台 G1L..G10R + JBT21 / 在途路径指令) +// ============================================================ + +// dockCodeToLabel PLC/Dock 表编码(DOCK01..21)→ 布局说明命名(G1L..G10R / JBT21)。 +// 顺序即 PLC M900.0~M902.3:DOCK01=G1L(左侧)、DOCK02=G1R(右侧)、DOCK03=G2L … DOCK20=G10R;DOCK21=JBT21。 +func dockCodeToLabel(code string) string { + c := strings.ToUpper(strings.TrimSpace(code)) + if c == "DOCK21" || c == "JBT21" { + return "JBT21" + } + if !strings.HasPrefix(c, "DOCK") { + return c + } + n, err := strconv.Atoi(strings.TrimPrefix(c, "DOCK")) + if err != nil || n < 1 || n > 20 { + return c + } + // 奇数=左侧 L、偶数=右侧 R(产线布局说明.md 命名规则) + suffix := "R" + if n%2 == 1 { + suffix = "L" + } + return fmt.Sprintf("G%d%s", (n+1)/2, suffix) +} + +// buildPoints 看板点位态:主线 15 位 + 接驳台 21 位(PLC 一次位块读)+ 在途路径指令(MW 一次块读)。 +// PLC 读取失败只降级本块(返回 Mock=true 空态),不影响整屏快照。 +func (s *Service) buildPoints(ctx context.Context) FrontPoints { + out := FrontPoints{Mock: s.ctx.PLC.IsMock(), Main: []FrontPoint{}, Dock: []FrontPoint{}, Transit: []InTransit{}} + bits, err := s.ctx.PLC.ReadBits(ctx) + if err != nil { + return out + } + for i := 0; i < 15; i++ { + out.Main = append(out.Main, FrontPoint{Code: fmt.Sprintf("C%d", i+1), Has: bitAt(bits, 12+i)}) + } + for i := 0; i < 20; i++ { + out.Dock = append(out.Dock, FrontPoint{Code: dockCodeToLabel(fmt.Sprintf("DOCK%02d", i+1)), Has: bitAt(bits, 27+i)}) + } + out.Dock = append(out.Dock, FrontPoint{Code: "JBT21", Has: bitAt(bits, 47)}) + // 在途路径指令:一次批量读 MW800..MW887(44 个路由寄存器),非 0 即在途 + if vals, err := s.ctx.PLC.ReadMWBlock(ctx, 800, 88); err == nil { + for _, addr := range plc.AllRouteAddrs() { + idx := addr - 800 + if idx < 0 || idx >= len(vals) || vals[idx] == 0 { + continue + } + if srcType, tgtType, src, tgt, ok := plc.ParseMW(addr, vals[idx]); ok { + out.Transit = append(out.Transit, InTransit{ + Src: string(srcType) + strconv.Itoa(src), + Tgt: string(tgtType) + strconv.Itoa(tgt), + }) + } + } + } + return out +} + // ============================================================ // 屏6:人员绩效 // ============================================================ diff --git a/bj_power_mes/internal/logic/dashboard_front.go b/bj_power_mes/internal/logic/dashboard_front.go index 9a15e21..8dd8361 100644 --- a/bj_power_mes/internal/logic/dashboard_front.go +++ b/bj_power_mes/internal/logic/dashboard_front.go @@ -34,6 +34,10 @@ type FrontStation struct { TighteningGun FrontToolState `json:"tighteningGun"` CurrentSn string `json:"currentSn"` CurrentOperator string `json:"currentOperator"` + CurrentProcess string `json:"currentProcess"` // 最近一道工序名 + DoneCount int `json:"doneCount"` // 今日完成数 + Paused bool `json:"paused"` // 当天已停单(前端仅图标提示) + PauseReason string `json:"pauseReason,omitempty"` } // FrontProduction 产能总览(前端 ProductionOverview) @@ -107,6 +111,12 @@ type FrontDashboard struct { Progress FrontProgress `json:"progress"` Traces []TraceItem `json:"traces"` Trends FrontTrends `json:"trends"` + // Points 产线点位态(主线 15 位 / 接驳台 21 位 / 在途路径指令),驱动 2D 地图真实亮灭与流光 + Points FrontPoints `json:"points"` + // Agv AGV 实时搬运任务(真实备料任务驱动;无坐标,前端按状态+目标接驳台做过渡动画) + Agv []FrontAgvRobot `json:"agv"` + // Events 实时事件流(已过滤 NG 结果项:大屏报喜不报忧,负面事件只走语音播报) + Events []EventItem `json:"events"` // Alarms 仅用于前端语音播报(D2),不渲染到屏幕(报喜不报忧)。 Alarms []AlarmItem `json:"alarms"` // RefreshSeconds 看板轮询兜底刷新间隔(秒,1~10),由 dashboard.refresh.seconds 配置驱动; @@ -121,7 +131,7 @@ func (s *Service) DashboardFrontSnapshot(ctx context.Context) (*FrontDashboard, if err != nil { return nil, err } - f := mapFrontDashboard(rich) + f := s.mapFrontDashboard(ctx, rich) f.RefreshSeconds = s.CfgInt(ctx, CfgDashboardRefreshSeconds, 5) return f, nil }) @@ -129,7 +139,7 @@ func (s *Service) DashboardFrontSnapshot(ctx context.Context) (*FrontDashboard, // mapFrontDashboard 富快照 → 前端契约。 // 展示口径按甲方要求:负面字段(合格率/不良数/报警)一律不出现。 -func mapFrontDashboard(r *DashboardSnapshot) *FrontDashboard { +func (s *Service) mapFrontDashboard(ctx context.Context, r *DashboardSnapshot) *FrontDashboard { f := &FrontDashboard{UpdatedAt: r.UpdatedAt} // -------- production / equipment -------- @@ -162,6 +172,10 @@ func mapFrontDashboard(r *DashboardSnapshot) *FrontDashboard { TighteningGun: FrontToolState{Status: tool, CurrentSn: st.CurrentSn, ProcessedCount: st.DoneToday}, CurrentSn: st.CurrentSn, CurrentOperator: st.CurrentOperator, + CurrentProcess: st.CurrentProcess, + DoneCount: st.DoneToday, + Paused: st.Paused, + PauseReason: st.PauseReason, }) } f.Equipment = equipment @@ -227,7 +241,7 @@ func mapFrontDashboard(r *DashboardSnapshot) *FrontDashboard { pr.Traceable = stepCount > 0 && allOk f.Progress = pr - // -------- traces / trends -------- + // -------- traces / trends / points / agv / events -------- f.Traces = r.Trace.Recent if f.Traces == nil { f.Traces = []TraceItem{} @@ -236,6 +250,31 @@ func mapFrontDashboard(r *DashboardSnapshot) *FrontDashboard { if f.Trends.Production == nil { f.Trends.Production = []TrendPoint{} } + // 点位态:PLC 读取失败时 buildPoints 已降级为 Mock 空态,前端角落标「模拟数据」 + f.Points = s.buildPoints(ctx) + if f.Points.Transit == nil { + f.Points.Transit = []InTransit{} + } + // AGV:真实备料任务 → 布局说明命名(DOCK01..21 → G1L..G10R/JBT21);无假坐标、无假进度 + f.Agv = make([]FrontAgvRobot, 0, len(r.Agv.Robots)) + for _, rb := range r.Agv.Robots { + f.Agv = append(f.Agv, FrontAgvRobot{ + Code: rb.Code, + Status: rb.Status, + From: dockCodeToLabel(rb.FromDock), + To: dockCodeToLabel(rb.ToDock), + Carrier: rb.Carrier, + TaskNo: rb.TaskNo, + }) + } + // 事件流:过滤 NG 结果项(大屏报喜不报忧;负面事件只进语音播报 alarms) + f.Events = make([]EventItem, 0, len(r.Events)) + for _, e := range r.Events { + if strings.EqualFold(e.Level, "error") { + continue + } + f.Events = append(f.Events, e) + } // 报警仅透传给前端做语音播报(D2),屏幕不渲染(报喜不报忧)。 f.Alarms = r.Alarms if f.Alarms == nil { diff --git a/bj_power_mes/internal/logic/dashboard_types.go b/bj_power_mes/internal/logic/dashboard_types.go index 872afb0..f0a1f05 100644 --- a/bj_power_mes/internal/logic/dashboard_types.go +++ b/bj_power_mes/internal/logic/dashboard_types.go @@ -103,9 +103,12 @@ type StationState struct { CurrentSn string `json:"currentSn"` CurrentOperator string `json:"currentOperator"` CurrentFlowId int `json:"currentFlowId"` + CurrentProcess string `json:"currentProcess"` // 最近一道工序名(最近实绩) DoneToday int `json:"doneToday"` NgToday int `json:"ngToday"` LastActiveAt string `json:"lastActiveAt"` + Paused bool `json:"paused"` // 当天已停单(station_state) + PauseReason string `json:"pauseReason"` // 停单原因(自由文本,前端仅图标提示) } // TraceStep 工件追溯:单道工艺实绩 @@ -216,6 +219,37 @@ type AlarmItem struct { Status string `json:"status"` } +// FrontPoint 看板点位态(主线位置 / 接驳台) +type FrontPoint struct { + Code string `json:"code"` // C1..C15 / G1L..G10R / JBT21 + Has bool `json:"has"` // 有托盘=true +} + +// FrontPoints 看板点位态集合(PLC 48 位 + 在途路径指令)。 +// Mock=true 表示 PLC 未接真实设备(模拟点位),前端角落须标「模拟数据」。 +type FrontPoints struct { + Mock bool `json:"mock"` + Main []FrontPoint `json:"main"` // 15 个主线位置 C1..C15 + Dock []FrontPoint `json:"dock"` // 21 个接驳台 G1L..G10R + JBT21 + Transit []InTransit `json:"transit"` // 当前在途路径指令(MW 非 0) +} + +// InTransit 一条在途路径指令(源→目标),源/目标为 G/C 编码(如 G9→C13)。 +type InTransit struct { + Src string `json:"src"` + Tgt string `json:"tgt"` +} + +// FrontAgvRobot 看板 AGV(真实备料任务驱动,不做假坐标)。 +type FrontAgvRobot struct { + Code string `json:"code"` + Status string `json:"status"` // idle / loading / moving / done + From string `json:"from"` // 起点接驳台(G1L 格式或 JBT21) + To string `json:"to"` // 目标接驳台(空=待命) + Carrier string `json:"carrier"` // 搬运物料名 + TaskNo string `json:"taskNo"` +} + // TrendPoint 趋势点(产量/合格率/日合格率共用) type TrendPoint struct { Time string `json:"time"` diff --git a/bj_power_mes/internal/logic/line.go b/bj_power_mes/internal/logic/line.go index 7d8c483..69e39f5 100644 --- a/bj_power_mes/internal/logic/line.go +++ b/bj_power_mes/internal/logic/line.go @@ -12,7 +12,7 @@ import ( // ============ 产线点位台账(产线布局说明·修正版) ============ // 布局:上料位 IN(工位1/2间主线,人工投料)→ [1,2] → C1,C2 → [3,4] → C3,C4 → [5,6] → C5,C6 → [7,8] → C7,C8 → [9,10] → 上排末端11 / 下排末端12(下料检测位) -// 接驳台:工位1~10 各 2 个(R1=1号AGV、R2=2号AGV),属 AGV 点位,PLC 只读在位信号 +// 接驳台:工位1~10 各 2 个(L=左侧、R=右侧,与 AGV 编号无关),属 AGV 点位,PLC 只读在位信号 // 上料位:工位1/2 之间的主传送带,人工投料,带传感器,PLC 上报在位信号 type pointDef struct { diff --git a/bj_power_mes/internal/logic/seed.go b/bj_power_mes/internal/logic/seed.go index ce2461f..10fa422 100644 --- a/bj_power_mes/internal/logic/seed.go +++ b/bj_power_mes/internal/logic/seed.go @@ -122,6 +122,8 @@ func (s *Service) Seed(ctx context.Context) error { // 导致这两个菜单无法授权给任何角色(只有 SUPER_ADMIN 靠 roleCode 旁路可见),2026-09-19 补齐。 {"sys.alert", "预警中心", "MENU", "/alert-center"}, {"sys.attachment", "附件中心", "MENU", "/attachment"}, + // 数据归档(备份到 U 盘 + 按时间窗物理清理):仅管理员可用,OPERATOR/INSPECTOR 不授予 + {"sys.backup", "数据归档", "MENU", "/data-archive"}, } for _, m := range menus { exist, err := s.ctx.EntClient.Permission.Query().Where(permission.Code(m.code)).First(ctx) @@ -328,7 +330,7 @@ func seedAlertRules(ctx context.Context, s *Service) { } } -// seedDocks 接驳台主数据:DOCK01~20 对应工位1~10(每工位2个,AGV R1/R2 点位),DOCK21 库房收货。 +// seedDocks 接驳台主数据:DOCK01~20 对应工位1~10(每工位2个:奇数=左侧L、偶数=右侧R,AGV 点位),DOCK21 库房收货。 // 一次性写入(仅当表为空时);2026-10-17 块 E.2 起「产线管理」页开放增/改/删/启停,seed 不再覆盖人工改动。 func seedDocks(ctx context.Context, s *Service) { count, _ := s.ctx.EntClient.Dock.Query().Count(ctx) diff --git a/bj_power_mes/internal/logic/settings.go b/bj_power_mes/internal/logic/settings.go index 92a436b..97509fe 100644 --- a/bj_power_mes/internal/logic/settings.go +++ b/bj_power_mes/internal/logic/settings.go @@ -35,6 +35,12 @@ const ( CfgTorqueNgAlert = "torque.ng.alert.enabled" // CfgDashboardRefreshSeconds 看板大屏轮询兜底刷新间隔(秒,1~10):仅影响 SSE 实时通道不可用时的 HTTP 轮询周期(默认 5) CfgDashboardRefreshSeconds = "dashboard.refresh.seconds" + // CfgDashboardTitle 门口看板(项目A)标题文字:空=默认「总装产线实时看板」(默认空);看板端每分钟拉取跟随 + CfgDashboardTitle = "dashboard.board.title" + // CfgDashboardVoice 门口看板语音播报开关:1=开启(默认,报警语音播报),0=关闭 + CfgDashboardVoice = "dashboard.board.voice" + // CfgArchiveRemindDays 数据归档提醒周期(天):距上次成功备份超过该天数时提醒清理(默认 7,0=关闭) + CfgArchiveRemindDays = "archive.remind.days" ) // startedAt 服务启动时刻(本机信息展示用) @@ -52,6 +58,9 @@ type SettingsVO struct { AllowCrossDay int `json:"allowCrossDay"` // 允许叫非今日排产的料(1=允许(默认),0=禁止) TorqueNgAlert bool `json:"torqueNgAlert"` // 拧紧不合格报警开关(1=开启,0=关闭) DashboardRefreshSeconds int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,1~10) + ArchiveRemindDays int `json:"archiveRemindDays"` // 数据归档提醒周期(天,0=关闭) + DashboardTitle string `json:"dashboardTitle"` // 门口看板标题文字(空=不显示) + DashboardVoice bool `json:"dashboardVoice"` // 门口看板语音播报开关 // 本机基础信息(只读) LocalIPs []string `json:"localIPs"` // 本机内网 IPv4 列表 @@ -73,6 +82,9 @@ type SettingsReq struct { AllowCrossDay *int `json:"allowCrossDay"` TorqueNgAlert *bool `json:"torqueNgAlert"` // B2.1 拧紧不合格报警开关(nil=不改) DashboardRefreshSeconds *int `json:"dashboardRefreshSeconds"` // 看板轮询兜底刷新间隔(秒,nil=不改) + ArchiveRemindDays *int `json:"archiveRemindDays"` // 数据归档提醒周期(天,nil=不改) + DashboardTitle *string `json:"dashboardTitle"` // 门口看板标题文字(nil=不改) + DashboardVoice *bool `json:"dashboardVoice"` // 门口看板语音播报开关(nil=不改) } // defaults 建议默认值(未配置时生效) @@ -85,6 +97,7 @@ var settingsDefaults = map[string]int{ CfgAllowCrossDay: 1, CfgTorqueNgAlert: 1, // B2.1 默认开启拧紧不合格报警 CfgDashboardRefreshSeconds: 5, // 看板轮询兜底刷新间隔(秒) + CfgArchiveRemindDays: 7, // 数据归档提醒周期(天) } // GetSettings 读取基础设置 + 本机信息。DB 读失败时按默认值返回(设置页必须能打开)。 @@ -105,6 +118,9 @@ func (s *Service) GetSettings(ctx context.Context) (*SettingsVO, error) { AllowCrossDay: cfgIntFrom(kv, CfgAllowCrossDay), TorqueNgAlert: s.CfgInt(ctx, CfgTorqueNgAlert, 1) == 1, // B2.1 默认开启 DashboardRefreshSeconds: cfgIntFrom(kv, CfgDashboardRefreshSeconds), + ArchiveRemindDays: cfgIntFrom(kv, CfgArchiveRemindDays), + DashboardTitle: kv[CfgDashboardTitle], + DashboardVoice: s.CfgInt(ctx, CfgDashboardVoice, 1) == 1, LocalIPs: localIPv4s(), ListenAddr: fmt.Sprintf("%s:%d", s.ctx.Config.Host, s.ctx.Config.Port), DBInfo: fmt.Sprintf("%s:%d/%s", s.ctx.Config.Database.Host, s.ctx.Config.Database.Port, s.ctx.Config.Database.Dbname), @@ -139,6 +155,7 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st {CfgPipelineCache, req.PipelineCache, 0, 1, "滚筒线缓存模式(1=启用缓存位并行流转,0=串行不缓存);预留配置,PLC 真机接入时生效"}, {CfgAllowCrossDay, req.AllowCrossDay, 0, 1, "允许叫非今日排产的料(1=允许,工位端预警提示;0=禁止)"}, {CfgDashboardRefreshSeconds, req.DashboardRefreshSeconds, 1, 10, "看板轮询兜底刷新间隔(秒,1~10,仅 SSE 不可用时的 HTTP 轮询周期)"}, + {CfgArchiveRemindDays, req.ArchiveRemindDays, 0, 365, "数据归档提醒周期(天,0=关闭;距上次成功备份超过该天数时提醒)"}, } for _, it := range items { if it.val == nil { @@ -160,6 +177,24 @@ func (s *Service) SaveSettings(ctx context.Context, req SettingsReq, operator st return err } } + if req.DashboardTitle != nil { + t := strings.TrimSpace(*req.DashboardTitle) + if len(t) > 30 { + return errors.New("门口看板标题需 0~30 字(空=不显示标题)") + } + if err := s.upsertConfig(ctx, CfgDashboardTitle, t, "门口看板标题文字(空=不显示)"); err != nil { + return err + } + } + if req.DashboardVoice != nil { + v := 0 + if *req.DashboardVoice { + v = 1 + } + if err := s.upsertConfig(ctx, CfgDashboardVoice, strconv.Itoa(v), "门口看板语音播报开关(1=开启,0=关闭)"); err != nil { + return err + } + } if req.WmsBaseURL != nil { u := strings.TrimSpace(*req.WmsBaseURL) if err := s.upsertConfig(ctx, CfgWmsBaseURL, u, "WMS 服务地址(保存即生效)"); err != nil { diff --git a/bj_power_mes/internal/plc/mock.go b/bj_power_mes/internal/plc/mock.go index c722685..5cc4eaf 100644 --- a/bj_power_mes/internal/plc/mock.go +++ b/bj_power_mes/internal/plc/mock.go @@ -78,6 +78,20 @@ func (m *mockClient) QueryDockPallet(_ context.Context, dockCode string) (bool, return m.dockPallet[dockCode], nil } +// ReadMWBlock 批量读连续 MW(mock:逐地址查模拟寄存器表,缺省 0)。 +func (m *mockClient) ReadMWBlock(_ context.Context, start, count int) ([]int, error) { + if start < 0 || count <= 0 || start+count > 65536 { + return nil, errors.New("非法 MW 批量读区间") + } + m.mu.RLock() + defer m.mu.RUnlock() + out := make([]int, count) + for i := 0; i < count; i++ { + out[i] = m.mw[start+i] + } + return out, nil +} + // QueryStationPallet 读工位托盘位(mock):返回置位值,默认无件。 func (m *mockClient) QueryStationPallet(_ context.Context, stationNo int) (bool, error) { m.mu.RLock() diff --git a/bj_power_mes/internal/plc/plc.go b/bj_power_mes/internal/plc/plc.go index 9149350..e1c5857 100644 --- a/bj_power_mes/internal/plc/plc.go +++ b/bj_power_mes/internal/plc/plc.go @@ -37,6 +37,10 @@ type Client interface { ReadBits(ctx context.Context) ([]bool, error) // ReadMW 读取 16 位寄存器(MW)当前值(大端)。用于监控页读 MW800~MW886。 ReadMW(ctx context.Context, addr int) (int, error) + // ReadMWBlock 批量读取连续 MW 寄存器(大端),返回 [start..start+count-1] 每地址的 16 位值。 + // 真实 S7 一次 AGReadMB 读 count*2 字节;看板快照用它一次取 MW800..MW887(44 个路由寄存器), + // 避免 44 次 ReadMW = 88 次 TCP 往返阻塞 PLC 连接。 + ReadMWBlock(ctx context.Context, start, count int) ([]int, error) // WriteMW 向 16 位寄存器(MW)写入值(大端)。用于手动下发路径指令、在途指令清零。 WriteMW(ctx context.Context, addr, value int) error } @@ -93,6 +97,13 @@ func (m *Manager) ReadMW(ctx context.Context, addr int) (int, error) { return v, err } +// ReadMWBlock 批量读连续 MW 寄存器(带恢复检测)。 +func (m *Manager) ReadMWBlock(ctx context.Context, start, count int) ([]int, error) { + v, err := m.client.ReadMWBlock(ctx, start, count) + m.track(err) + return v, err +} + // WriteMW 写 16 位寄存器(带恢复检测)。 func (m *Manager) WriteMW(ctx context.Context, addr, value int) error { err := m.client.WriteMW(ctx, addr, value) diff --git a/bj_power_mes/internal/plc/tcp.go b/bj_power_mes/internal/plc/tcp.go index efacbc1..e20c153 100644 --- a/bj_power_mes/internal/plc/tcp.go +++ b/bj_power_mes/internal/plc/tcp.go @@ -89,28 +89,40 @@ func (s *s7Real) readBlock(ctx context.Context) ([]byte, error) { // readByte 读取单个 Merker 字节(用于 48 位块之外的完成信号位等)。 func (s *s7Real) readByte(ctx context.Context, byteOffset int) (byte, error) { + buf, err := s.readBytes(ctx, byteOffset, 1) + if err != nil { + return 0, err + } + return buf[0], nil +} + +// readBytes 读任意 Merker 字节区间(带惰性连接与断线重连),供 ReadMWBlock 等批量读使用。 +func (s *s7Real) readBytes(ctx context.Context, byteOffset, length int) ([]byte, error) { + if byteOffset < 0 || length <= 0 { + return nil, fmt.Errorf("非法读区间: offset=%d len=%d", byteOffset, length) + } s.mu.Lock() if err := s.ensure(); err != nil { s.mu.Unlock() - return 0, err + return nil, err } cl := s.client s.mu.Unlock() - buf := make([]byte, 1) + buf := make([]byte, length) done := make(chan error, 1) - go func() { done <- cl.AGReadMB(byteOffset, 1, buf) }() + go func() { done <- cl.AGReadMB(byteOffset, length, buf) }() select { case <-ctx.Done(): - return 0, ctx.Err() + return nil, ctx.Err() case err := <-done: if err != nil { s.mu.Lock() _ = s.handler.Close() s.client = nil s.mu.Unlock() - return 0, err + return nil, err } - return buf[0], nil + return buf, nil } } @@ -240,6 +252,23 @@ func (t *tcpClient) ReadMW(ctx context.Context, addr int) (int, error) { return int(hi)<<8 | int(lo), nil } +// ReadMWBlock 批量读连续 MW 寄存器(大端):一次 AGReadMB 读 count*2 字节, +// 避免逐地址读造成的 2*count 次 TCP 往返(看板快照用,MW800..MW887 一次取完)。 +func (t *tcpClient) ReadMWBlock(ctx context.Context, start, count int) ([]int, error) { + if start < 0 || count <= 0 || start+count*2 > 65536 { + return nil, fmt.Errorf("非法 MW 批量读区间: start=%d count=%d", start, count) + } + buf, err := t.real.readBytes(ctx, start, count*2) + if err != nil { + return nil, err + } + out := make([]int, count) + for i := 0; i < count; i++ { + out[i] = int(buf[i*2])<<8 | int(buf[i*2+1]) + } + return out, nil +} + // WriteMW 写 16 位寄存器(MW,大端):高字节写 addr、低字节写 addr+1。 func (t *tcpClient) WriteMW(ctx context.Context, addr, value int) error { buf := []byte{byte(value >> 8), byte(value & 0xff)} diff --git a/bj_power_mes/internal/svc/service_context.go b/bj_power_mes/internal/svc/service_context.go index 7f084bd..3be8b87 100644 --- a/bj_power_mes/internal/svc/service_context.go +++ b/bj_power_mes/internal/svc/service_context.go @@ -5,6 +5,7 @@ import ( "bj_power_mes/ent" "bj_power_mes/internal/agv" + "bj_power_mes/internal/backup" "bj_power_mes/internal/config" "bj_power_mes/internal/db" "bj_power_mes/internal/eventlog" @@ -25,6 +26,7 @@ type ServiceContext struct { PLC *plc.Manager Agv agv.Client Wms *wmsclient.Client + Backup *backup.Service } func NewServiceContext(c config.Config) *ServiceContext { @@ -47,6 +49,7 @@ func NewServiceContext(c config.Config) *ServiceContext { PLC: plcMgr, Agv: agv.New(c.Agv), Wms: wmsclient.New(c.Wms.BaseURL, c.Wms.Token), + Backup: backup.New(entClient, eventlog.NewWriter(entClient), c.Upload.Dir), } } diff --git a/bj_power_mes/public/index.html b/bj_power_mes/public/index.html index ed6b266..894f6ac 100644 --- a/bj_power_mes/public/index.html +++ b/bj_power_mes/public/index.html @@ -6,8 +6,8 @@ MES 产线控制 - - + +
diff --git a/bj_power_mes/schema/backup_record.go b/bj_power_mes/schema/backup_record.go new file mode 100644 index 0000000..860137f --- /dev/null +++ b/bj_power_mes/schema/backup_record.go @@ -0,0 +1,56 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// BackupRecord 备份记录:每次「备份到外部存储(U盘/移动硬盘)」写一条。 +// 清理前校验 backup_record 对该时间窗的完整覆盖,覆盖不全则拒绝清理。 +// +// 时间字段统一用 Int64 unix 秒(与 WMS 端一致,便于跨库覆盖比较); +// 各业务表 created_at 类型不一(MES tz-time / WMS bigint),由备份/清理层统一解析。 +type BackupRecord struct { + ent.Schema +} + +func (BackupRecord) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "backup_record"}, + entsql.WithComments(true), + schema.Comment("BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖"), + } +} + +func (BackupRecord) Fields() []ent.Field { + return []ent.Field{ + field.Int("id").Positive(), + field.Int64("executedAt").DefaultFunc(backupRecordNow).Comment("备份执行时刻(unix秒)"), + field.Int64("rangeStart").Comment("备份范围开始(unix秒,含)"), + field.Int64("rangeEnd").Comment("备份范围结束(unix秒,含)"), + field.String("backupPath").Comment("备份包(zip)在目标盘的完整路径"), + field.Int64("totalSize").Default(0).Comment("备份包总字节数"), + // 各数据项及大小:[{name,rows,bytes}],name 与备份内目录一致 + field.String("itemsJSON").Comment("各数据项及大小(JSON数组:[{name,rows,bytes}])"), + field.String("status").Default("success").MaxLen(16).Comment("success/failed/partial"), + field.String("operator").Default("").MaxLen(64).Comment("操作人"), + field.String("checksum").Default("").MaxLen(64).Comment("备份包校验和(sha256,基于 manifest)"), + field.String("scope").Default("mes").MaxLen(8).Comment("写入方 mes/wms"), + } +} + +func (BackupRecord) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("rangeStart"), + index.Fields("rangeEnd"), + index.Fields("status"), + } +} + +// backupRecordNow 备份执行时刻(unix 秒)。 +func backupRecordNow() int64 { return time.Now().Unix() } diff --git a/bj_power_mes/schema/line_point.go b/bj_power_mes/schema/line_point.go index 22ddc9f..5fdacde 100644 --- a/bj_power_mes/schema/line_point.go +++ b/bj_power_mes/schema/line_point.go @@ -13,7 +13,7 @@ import ( // LinePoint 产线点位台账:记录每个点位当前存放的工件(唯一事实源)。 // 产线布局(修正版):上料位 IN(工位1/2间主线,带传感器)、工位 1~10(有终端)、 // 末端下料检测位 11(上排末端)/12(下排末端)(无终端,PLC 点位)、缓存位 C1~C8、 -// 每个有终端工位配 R1、R2 两个接驳台(AGV 点位,PLC 只读到位信号)。 +// 每个有终端工位配左(L)、右(R)两个接驳台(AGV 点位,PLC 只读到位信号)。 type LinePoint struct { ent.Schema } diff --git a/bj_power_wms/ent/backuprecord.go b/bj_power_wms/ent/backuprecord.go new file mode 100644 index 0000000..9b2af5a --- /dev/null +++ b/bj_power_wms/ent/backuprecord.go @@ -0,0 +1,202 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/backuprecord" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖 +type BackupRecord struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 备份执行时刻(unix秒) + ExecutedAt int64 `json:"executedAt,omitempty"` + // 备份范围开始(unix秒,含) + RangeStart int64 `json:"rangeStart,omitempty"` + // 备份范围结束(unix秒,含) + RangeEnd int64 `json:"rangeEnd,omitempty"` + // 备份包(zip)在目标盘的完整路径 + BackupPath string `json:"backupPath,omitempty"` + // 备份包总字节数 + TotalSize int64 `json:"totalSize,omitempty"` + // 各数据项及大小(JSON数组:[{name,rows,bytes}]) + ItemsJSON string `json:"itemsJson,omitempty"` + // success/failed/partial + Status string `json:"status,omitempty"` + // 操作人 + Operator string `json:"operator,omitempty"` + // 备份包校验和(sha256,基于 manifest) + Checksum string `json:"checksum,omitempty"` + // 写入方 mes/wms + Scope string `json:"scope,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BackupRecord) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case backuprecord.FieldID, backuprecord.FieldExecutedAt, backuprecord.FieldRangeStart, backuprecord.FieldRangeEnd, backuprecord.FieldTotalSize: + values[i] = new(sql.NullInt64) + case backuprecord.FieldBackupPath, backuprecord.FieldItemsJSON, backuprecord.FieldStatus, backuprecord.FieldOperator, backuprecord.FieldChecksum, backuprecord.FieldScope: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the BackupRecord fields. +func (_m *BackupRecord) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case backuprecord.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case backuprecord.FieldExecutedAt: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field executed_at", values[i]) + } else if value.Valid { + _m.ExecutedAt = value.Int64 + } + case backuprecord.FieldRangeStart: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field range_start", values[i]) + } else if value.Valid { + _m.RangeStart = value.Int64 + } + case backuprecord.FieldRangeEnd: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field range_end", values[i]) + } else if value.Valid { + _m.RangeEnd = value.Int64 + } + case backuprecord.FieldBackupPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field backup_path", values[i]) + } else if value.Valid { + _m.BackupPath = value.String + } + case backuprecord.FieldTotalSize: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field total_size", values[i]) + } else if value.Valid { + _m.TotalSize = value.Int64 + } + case backuprecord.FieldItemsJSON: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field items_json", values[i]) + } else if value.Valid { + _m.ItemsJSON = value.String + } + case backuprecord.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = value.String + } + case backuprecord.FieldOperator: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field operator", values[i]) + } else if value.Valid { + _m.Operator = value.String + } + case backuprecord.FieldChecksum: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field checksum", values[i]) + } else if value.Valid { + _m.Checksum = value.String + } + case backuprecord.FieldScope: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scope", values[i]) + } else if value.Valid { + _m.Scope = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BackupRecord. +// This includes values selected through modifiers, order, etc. +func (_m *BackupRecord) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this BackupRecord. +// Note that you need to call BackupRecord.Unwrap() before calling this method if this BackupRecord +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *BackupRecord) Update() *BackupRecordUpdateOne { + return NewBackupRecordClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the BackupRecord entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *BackupRecord) Unwrap() *BackupRecord { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: BackupRecord is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *BackupRecord) String() string { + var builder strings.Builder + builder.WriteString("BackupRecord(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("executed_at=") + builder.WriteString(fmt.Sprintf("%v", _m.ExecutedAt)) + builder.WriteString(", ") + builder.WriteString("range_start=") + builder.WriteString(fmt.Sprintf("%v", _m.RangeStart)) + builder.WriteString(", ") + builder.WriteString("range_end=") + builder.WriteString(fmt.Sprintf("%v", _m.RangeEnd)) + builder.WriteString(", ") + builder.WriteString("backup_path=") + builder.WriteString(_m.BackupPath) + builder.WriteString(", ") + builder.WriteString("total_size=") + builder.WriteString(fmt.Sprintf("%v", _m.TotalSize)) + builder.WriteString(", ") + builder.WriteString("items_json=") + builder.WriteString(_m.ItemsJSON) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(_m.Status) + builder.WriteString(", ") + builder.WriteString("operator=") + builder.WriteString(_m.Operator) + builder.WriteString(", ") + builder.WriteString("checksum=") + builder.WriteString(_m.Checksum) + builder.WriteString(", ") + builder.WriteString("scope=") + builder.WriteString(_m.Scope) + builder.WriteByte(')') + return builder.String() +} + +// BackupRecords is a parsable slice of BackupRecord. +type BackupRecords []*BackupRecord diff --git a/bj_power_wms/ent/backuprecord/backuprecord.go b/bj_power_wms/ent/backuprecord/backuprecord.go new file mode 100644 index 0000000..39cc45f --- /dev/null +++ b/bj_power_wms/ent/backuprecord/backuprecord.go @@ -0,0 +1,142 @@ +// Code generated by ent, DO NOT EDIT. + +package backuprecord + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the backuprecord type in the database. + Label = "backup_record" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldExecutedAt holds the string denoting the executed_at field in the database. + FieldExecutedAt = "executed_at" + // FieldRangeStart holds the string denoting the range_start field in the database. + FieldRangeStart = "range_start" + // FieldRangeEnd holds the string denoting the range_end field in the database. + FieldRangeEnd = "range_end" + // FieldBackupPath holds the string denoting the backup_path field in the database. + FieldBackupPath = "backup_path" + // FieldTotalSize holds the string denoting the total_size field in the database. + FieldTotalSize = "total_size" + // FieldItemsJSON holds the string denoting the items_json field in the database. + FieldItemsJSON = "items_json" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldOperator holds the string denoting the operator field in the database. + FieldOperator = "operator" + // FieldChecksum holds the string denoting the checksum field in the database. + FieldChecksum = "checksum" + // FieldScope holds the string denoting the scope field in the database. + FieldScope = "scope" + // Table holds the table name of the backuprecord in the database. + Table = "backup_record" +) + +// Columns holds all SQL columns for backuprecord fields. +var Columns = []string{ + FieldID, + FieldExecutedAt, + FieldRangeStart, + FieldRangeEnd, + FieldBackupPath, + FieldTotalSize, + FieldItemsJSON, + FieldStatus, + FieldOperator, + FieldChecksum, + FieldScope, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultExecutedAt holds the default value on creation for the "executed_at" field. + DefaultExecutedAt func() int64 + // DefaultTotalSize holds the default value on creation for the "total_size" field. + DefaultTotalSize int64 + // DefaultStatus holds the default value on creation for the "status" field. + DefaultStatus string + // StatusValidator is a validator for the "status" field. It is called by the builders before save. + StatusValidator func(string) error + // DefaultOperator holds the default value on creation for the "operator" field. + DefaultOperator string + // OperatorValidator is a validator for the "operator" field. It is called by the builders before save. + OperatorValidator func(string) error + // DefaultChecksum holds the default value on creation for the "checksum" field. + DefaultChecksum string + // ChecksumValidator is a validator for the "checksum" field. It is called by the builders before save. + ChecksumValidator func(string) error + // DefaultScope holds the default value on creation for the "scope" field. + DefaultScope string + // ScopeValidator is a validator for the "scope" field. It is called by the builders before save. + ScopeValidator func(string) error +) + +// OrderOption defines the ordering options for the BackupRecord queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByExecutedAt orders the results by the executed_at field. +func ByExecutedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExecutedAt, opts...).ToFunc() +} + +// ByRangeStart orders the results by the range_start field. +func ByRangeStart(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRangeStart, opts...).ToFunc() +} + +// ByRangeEnd orders the results by the range_end field. +func ByRangeEnd(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRangeEnd, opts...).ToFunc() +} + +// ByBackupPath orders the results by the backup_path field. +func ByBackupPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBackupPath, opts...).ToFunc() +} + +// ByTotalSize orders the results by the total_size field. +func ByTotalSize(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalSize, opts...).ToFunc() +} + +// ByItemsJSON orders the results by the items_json field. +func ByItemsJSON(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldItemsJSON, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByOperator orders the results by the operator field. +func ByOperator(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOperator, opts...).ToFunc() +} + +// ByChecksum orders the results by the checksum field. +func ByChecksum(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldChecksum, opts...).ToFunc() +} + +// ByScope orders the results by the scope field. +func ByScope(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScope, opts...).ToFunc() +} diff --git a/bj_power_wms/ent/backuprecord/where.go b/bj_power_wms/ent/backuprecord/where.go new file mode 100644 index 0000000..760b883 --- /dev/null +++ b/bj_power_wms/ent/backuprecord/where.go @@ -0,0 +1,669 @@ +// Code generated by ent, DO NOT EDIT. + +package backuprecord + +import ( + "bj_power_wms/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldID, id)) +} + +// ExecutedAt applies equality check predicate on the "executed_at" field. It's identical to ExecutedAtEQ. +func ExecutedAt(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldExecutedAt, v)) +} + +// RangeStart applies equality check predicate on the "range_start" field. It's identical to RangeStartEQ. +func RangeStart(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeStart, v)) +} + +// RangeEnd applies equality check predicate on the "range_end" field. It's identical to RangeEndEQ. +func RangeEnd(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeEnd, v)) +} + +// BackupPath applies equality check predicate on the "backup_path" field. It's identical to BackupPathEQ. +func BackupPath(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldBackupPath, v)) +} + +// TotalSize applies equality check predicate on the "total_size" field. It's identical to TotalSizeEQ. +func TotalSize(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldTotalSize, v)) +} + +// ItemsJSON applies equality check predicate on the "items_json" field. It's identical to ItemsJSONEQ. +func ItemsJSON(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldItemsJSON, v)) +} + +// Status applies equality check predicate on the "status" field. It's identical to StatusEQ. +func Status(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldStatus, v)) +} + +// Operator applies equality check predicate on the "operator" field. It's identical to OperatorEQ. +func Operator(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldOperator, v)) +} + +// Checksum applies equality check predicate on the "checksum" field. It's identical to ChecksumEQ. +func Checksum(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldChecksum, v)) +} + +// Scope applies equality check predicate on the "scope" field. It's identical to ScopeEQ. +func Scope(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldScope, v)) +} + +// ExecutedAtEQ applies the EQ predicate on the "executed_at" field. +func ExecutedAtEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldExecutedAt, v)) +} + +// ExecutedAtNEQ applies the NEQ predicate on the "executed_at" field. +func ExecutedAtNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldExecutedAt, v)) +} + +// ExecutedAtIn applies the In predicate on the "executed_at" field. +func ExecutedAtIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldExecutedAt, vs...)) +} + +// ExecutedAtNotIn applies the NotIn predicate on the "executed_at" field. +func ExecutedAtNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldExecutedAt, vs...)) +} + +// ExecutedAtGT applies the GT predicate on the "executed_at" field. +func ExecutedAtGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldExecutedAt, v)) +} + +// ExecutedAtGTE applies the GTE predicate on the "executed_at" field. +func ExecutedAtGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldExecutedAt, v)) +} + +// ExecutedAtLT applies the LT predicate on the "executed_at" field. +func ExecutedAtLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldExecutedAt, v)) +} + +// ExecutedAtLTE applies the LTE predicate on the "executed_at" field. +func ExecutedAtLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldExecutedAt, v)) +} + +// RangeStartEQ applies the EQ predicate on the "range_start" field. +func RangeStartEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeStart, v)) +} + +// RangeStartNEQ applies the NEQ predicate on the "range_start" field. +func RangeStartNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldRangeStart, v)) +} + +// RangeStartIn applies the In predicate on the "range_start" field. +func RangeStartIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldRangeStart, vs...)) +} + +// RangeStartNotIn applies the NotIn predicate on the "range_start" field. +func RangeStartNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldRangeStart, vs...)) +} + +// RangeStartGT applies the GT predicate on the "range_start" field. +func RangeStartGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldRangeStart, v)) +} + +// RangeStartGTE applies the GTE predicate on the "range_start" field. +func RangeStartGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldRangeStart, v)) +} + +// RangeStartLT applies the LT predicate on the "range_start" field. +func RangeStartLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldRangeStart, v)) +} + +// RangeStartLTE applies the LTE predicate on the "range_start" field. +func RangeStartLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldRangeStart, v)) +} + +// RangeEndEQ applies the EQ predicate on the "range_end" field. +func RangeEndEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldRangeEnd, v)) +} + +// RangeEndNEQ applies the NEQ predicate on the "range_end" field. +func RangeEndNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldRangeEnd, v)) +} + +// RangeEndIn applies the In predicate on the "range_end" field. +func RangeEndIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldRangeEnd, vs...)) +} + +// RangeEndNotIn applies the NotIn predicate on the "range_end" field. +func RangeEndNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldRangeEnd, vs...)) +} + +// RangeEndGT applies the GT predicate on the "range_end" field. +func RangeEndGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldRangeEnd, v)) +} + +// RangeEndGTE applies the GTE predicate on the "range_end" field. +func RangeEndGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldRangeEnd, v)) +} + +// RangeEndLT applies the LT predicate on the "range_end" field. +func RangeEndLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldRangeEnd, v)) +} + +// RangeEndLTE applies the LTE predicate on the "range_end" field. +func RangeEndLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldRangeEnd, v)) +} + +// BackupPathEQ applies the EQ predicate on the "backup_path" field. +func BackupPathEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldBackupPath, v)) +} + +// BackupPathNEQ applies the NEQ predicate on the "backup_path" field. +func BackupPathNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldBackupPath, v)) +} + +// BackupPathIn applies the In predicate on the "backup_path" field. +func BackupPathIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldBackupPath, vs...)) +} + +// BackupPathNotIn applies the NotIn predicate on the "backup_path" field. +func BackupPathNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldBackupPath, vs...)) +} + +// BackupPathGT applies the GT predicate on the "backup_path" field. +func BackupPathGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldBackupPath, v)) +} + +// BackupPathGTE applies the GTE predicate on the "backup_path" field. +func BackupPathGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldBackupPath, v)) +} + +// BackupPathLT applies the LT predicate on the "backup_path" field. +func BackupPathLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldBackupPath, v)) +} + +// BackupPathLTE applies the LTE predicate on the "backup_path" field. +func BackupPathLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldBackupPath, v)) +} + +// BackupPathContains applies the Contains predicate on the "backup_path" field. +func BackupPathContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldBackupPath, v)) +} + +// BackupPathHasPrefix applies the HasPrefix predicate on the "backup_path" field. +func BackupPathHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldBackupPath, v)) +} + +// BackupPathHasSuffix applies the HasSuffix predicate on the "backup_path" field. +func BackupPathHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldBackupPath, v)) +} + +// BackupPathEqualFold applies the EqualFold predicate on the "backup_path" field. +func BackupPathEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldBackupPath, v)) +} + +// BackupPathContainsFold applies the ContainsFold predicate on the "backup_path" field. +func BackupPathContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldBackupPath, v)) +} + +// TotalSizeEQ applies the EQ predicate on the "total_size" field. +func TotalSizeEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldTotalSize, v)) +} + +// TotalSizeNEQ applies the NEQ predicate on the "total_size" field. +func TotalSizeNEQ(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldTotalSize, v)) +} + +// TotalSizeIn applies the In predicate on the "total_size" field. +func TotalSizeIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldTotalSize, vs...)) +} + +// TotalSizeNotIn applies the NotIn predicate on the "total_size" field. +func TotalSizeNotIn(vs ...int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldTotalSize, vs...)) +} + +// TotalSizeGT applies the GT predicate on the "total_size" field. +func TotalSizeGT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldTotalSize, v)) +} + +// TotalSizeGTE applies the GTE predicate on the "total_size" field. +func TotalSizeGTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldTotalSize, v)) +} + +// TotalSizeLT applies the LT predicate on the "total_size" field. +func TotalSizeLT(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldTotalSize, v)) +} + +// TotalSizeLTE applies the LTE predicate on the "total_size" field. +func TotalSizeLTE(v int64) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldTotalSize, v)) +} + +// ItemsJSONEQ applies the EQ predicate on the "items_json" field. +func ItemsJSONEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldItemsJSON, v)) +} + +// ItemsJSONNEQ applies the NEQ predicate on the "items_json" field. +func ItemsJSONNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldItemsJSON, v)) +} + +// ItemsJSONIn applies the In predicate on the "items_json" field. +func ItemsJSONIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldItemsJSON, vs...)) +} + +// ItemsJSONNotIn applies the NotIn predicate on the "items_json" field. +func ItemsJSONNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldItemsJSON, vs...)) +} + +// ItemsJSONGT applies the GT predicate on the "items_json" field. +func ItemsJSONGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldItemsJSON, v)) +} + +// ItemsJSONGTE applies the GTE predicate on the "items_json" field. +func ItemsJSONGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldItemsJSON, v)) +} + +// ItemsJSONLT applies the LT predicate on the "items_json" field. +func ItemsJSONLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldItemsJSON, v)) +} + +// ItemsJSONLTE applies the LTE predicate on the "items_json" field. +func ItemsJSONLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldItemsJSON, v)) +} + +// ItemsJSONContains applies the Contains predicate on the "items_json" field. +func ItemsJSONContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldItemsJSON, v)) +} + +// ItemsJSONHasPrefix applies the HasPrefix predicate on the "items_json" field. +func ItemsJSONHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldItemsJSON, v)) +} + +// ItemsJSONHasSuffix applies the HasSuffix predicate on the "items_json" field. +func ItemsJSONHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldItemsJSON, v)) +} + +// ItemsJSONEqualFold applies the EqualFold predicate on the "items_json" field. +func ItemsJSONEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldItemsJSON, v)) +} + +// ItemsJSONContainsFold applies the ContainsFold predicate on the "items_json" field. +func ItemsJSONContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldItemsJSON, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldStatus, vs...)) +} + +// StatusGT applies the GT predicate on the "status" field. +func StatusGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldStatus, v)) +} + +// StatusGTE applies the GTE predicate on the "status" field. +func StatusGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldStatus, v)) +} + +// StatusLT applies the LT predicate on the "status" field. +func StatusLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldStatus, v)) +} + +// StatusLTE applies the LTE predicate on the "status" field. +func StatusLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldStatus, v)) +} + +// StatusContains applies the Contains predicate on the "status" field. +func StatusContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldStatus, v)) +} + +// StatusHasPrefix applies the HasPrefix predicate on the "status" field. +func StatusHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldStatus, v)) +} + +// StatusHasSuffix applies the HasSuffix predicate on the "status" field. +func StatusHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldStatus, v)) +} + +// StatusEqualFold applies the EqualFold predicate on the "status" field. +func StatusEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldStatus, v)) +} + +// StatusContainsFold applies the ContainsFold predicate on the "status" field. +func StatusContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldStatus, v)) +} + +// OperatorEQ applies the EQ predicate on the "operator" field. +func OperatorEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldOperator, v)) +} + +// OperatorNEQ applies the NEQ predicate on the "operator" field. +func OperatorNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldOperator, v)) +} + +// OperatorIn applies the In predicate on the "operator" field. +func OperatorIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldOperator, vs...)) +} + +// OperatorNotIn applies the NotIn predicate on the "operator" field. +func OperatorNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldOperator, vs...)) +} + +// OperatorGT applies the GT predicate on the "operator" field. +func OperatorGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldOperator, v)) +} + +// OperatorGTE applies the GTE predicate on the "operator" field. +func OperatorGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldOperator, v)) +} + +// OperatorLT applies the LT predicate on the "operator" field. +func OperatorLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldOperator, v)) +} + +// OperatorLTE applies the LTE predicate on the "operator" field. +func OperatorLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldOperator, v)) +} + +// OperatorContains applies the Contains predicate on the "operator" field. +func OperatorContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldOperator, v)) +} + +// OperatorHasPrefix applies the HasPrefix predicate on the "operator" field. +func OperatorHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldOperator, v)) +} + +// OperatorHasSuffix applies the HasSuffix predicate on the "operator" field. +func OperatorHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldOperator, v)) +} + +// OperatorEqualFold applies the EqualFold predicate on the "operator" field. +func OperatorEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldOperator, v)) +} + +// OperatorContainsFold applies the ContainsFold predicate on the "operator" field. +func OperatorContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldOperator, v)) +} + +// ChecksumEQ applies the EQ predicate on the "checksum" field. +func ChecksumEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldChecksum, v)) +} + +// ChecksumNEQ applies the NEQ predicate on the "checksum" field. +func ChecksumNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldChecksum, v)) +} + +// ChecksumIn applies the In predicate on the "checksum" field. +func ChecksumIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldChecksum, vs...)) +} + +// ChecksumNotIn applies the NotIn predicate on the "checksum" field. +func ChecksumNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldChecksum, vs...)) +} + +// ChecksumGT applies the GT predicate on the "checksum" field. +func ChecksumGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldChecksum, v)) +} + +// ChecksumGTE applies the GTE predicate on the "checksum" field. +func ChecksumGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldChecksum, v)) +} + +// ChecksumLT applies the LT predicate on the "checksum" field. +func ChecksumLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldChecksum, v)) +} + +// ChecksumLTE applies the LTE predicate on the "checksum" field. +func ChecksumLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldChecksum, v)) +} + +// ChecksumContains applies the Contains predicate on the "checksum" field. +func ChecksumContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldChecksum, v)) +} + +// ChecksumHasPrefix applies the HasPrefix predicate on the "checksum" field. +func ChecksumHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldChecksum, v)) +} + +// ChecksumHasSuffix applies the HasSuffix predicate on the "checksum" field. +func ChecksumHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldChecksum, v)) +} + +// ChecksumEqualFold applies the EqualFold predicate on the "checksum" field. +func ChecksumEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldChecksum, v)) +} + +// ChecksumContainsFold applies the ContainsFold predicate on the "checksum" field. +func ChecksumContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldChecksum, v)) +} + +// ScopeEQ applies the EQ predicate on the "scope" field. +func ScopeEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEQ(FieldScope, v)) +} + +// ScopeNEQ applies the NEQ predicate on the "scope" field. +func ScopeNEQ(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNEQ(FieldScope, v)) +} + +// ScopeIn applies the In predicate on the "scope" field. +func ScopeIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldIn(FieldScope, vs...)) +} + +// ScopeNotIn applies the NotIn predicate on the "scope" field. +func ScopeNotIn(vs ...string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldNotIn(FieldScope, vs...)) +} + +// ScopeGT applies the GT predicate on the "scope" field. +func ScopeGT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGT(FieldScope, v)) +} + +// ScopeGTE applies the GTE predicate on the "scope" field. +func ScopeGTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldGTE(FieldScope, v)) +} + +// ScopeLT applies the LT predicate on the "scope" field. +func ScopeLT(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLT(FieldScope, v)) +} + +// ScopeLTE applies the LTE predicate on the "scope" field. +func ScopeLTE(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldLTE(FieldScope, v)) +} + +// ScopeContains applies the Contains predicate on the "scope" field. +func ScopeContains(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContains(FieldScope, v)) +} + +// ScopeHasPrefix applies the HasPrefix predicate on the "scope" field. +func ScopeHasPrefix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasPrefix(FieldScope, v)) +} + +// ScopeHasSuffix applies the HasSuffix predicate on the "scope" field. +func ScopeHasSuffix(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldHasSuffix(FieldScope, v)) +} + +// ScopeEqualFold applies the EqualFold predicate on the "scope" field. +func ScopeEqualFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldEqualFold(FieldScope, v)) +} + +// ScopeContainsFold applies the ContainsFold predicate on the "scope" field. +func ScopeContainsFold(v string) predicate.BackupRecord { + return predicate.BackupRecord(sql.FieldContainsFold(FieldScope, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BackupRecord) predicate.BackupRecord { + return predicate.BackupRecord(sql.NotPredicates(p)) +} diff --git a/bj_power_wms/ent/backuprecord_create.go b/bj_power_wms/ent/backuprecord_create.go new file mode 100644 index 0000000..1cfac9f --- /dev/null +++ b/bj_power_wms/ent/backuprecord_create.go @@ -0,0 +1,1109 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/backuprecord" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordCreate is the builder for creating a BackupRecord entity. +type BackupRecordCreate struct { + config + mutation *BackupRecordMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetExecutedAt sets the "executed_at" field. +func (_c *BackupRecordCreate) SetExecutedAt(v int64) *BackupRecordCreate { + _c.mutation.SetExecutedAt(v) + return _c +} + +// SetNillableExecutedAt sets the "executed_at" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableExecutedAt(v *int64) *BackupRecordCreate { + if v != nil { + _c.SetExecutedAt(*v) + } + return _c +} + +// SetRangeStart sets the "range_start" field. +func (_c *BackupRecordCreate) SetRangeStart(v int64) *BackupRecordCreate { + _c.mutation.SetRangeStart(v) + return _c +} + +// SetRangeEnd sets the "range_end" field. +func (_c *BackupRecordCreate) SetRangeEnd(v int64) *BackupRecordCreate { + _c.mutation.SetRangeEnd(v) + return _c +} + +// SetBackupPath sets the "backup_path" field. +func (_c *BackupRecordCreate) SetBackupPath(v string) *BackupRecordCreate { + _c.mutation.SetBackupPath(v) + return _c +} + +// SetTotalSize sets the "total_size" field. +func (_c *BackupRecordCreate) SetTotalSize(v int64) *BackupRecordCreate { + _c.mutation.SetTotalSize(v) + return _c +} + +// SetNillableTotalSize sets the "total_size" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableTotalSize(v *int64) *BackupRecordCreate { + if v != nil { + _c.SetTotalSize(*v) + } + return _c +} + +// SetItemsJSON sets the "items_json" field. +func (_c *BackupRecordCreate) SetItemsJSON(v string) *BackupRecordCreate { + _c.mutation.SetItemsJSON(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *BackupRecordCreate) SetStatus(v string) *BackupRecordCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableStatus(v *string) *BackupRecordCreate { + if v != nil { + _c.SetStatus(*v) + } + return _c +} + +// SetOperator sets the "operator" field. +func (_c *BackupRecordCreate) SetOperator(v string) *BackupRecordCreate { + _c.mutation.SetOperator(v) + return _c +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableOperator(v *string) *BackupRecordCreate { + if v != nil { + _c.SetOperator(*v) + } + return _c +} + +// SetChecksum sets the "checksum" field. +func (_c *BackupRecordCreate) SetChecksum(v string) *BackupRecordCreate { + _c.mutation.SetChecksum(v) + return _c +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableChecksum(v *string) *BackupRecordCreate { + if v != nil { + _c.SetChecksum(*v) + } + return _c +} + +// SetScope sets the "scope" field. +func (_c *BackupRecordCreate) SetScope(v string) *BackupRecordCreate { + _c.mutation.SetScope(v) + return _c +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_c *BackupRecordCreate) SetNillableScope(v *string) *BackupRecordCreate { + if v != nil { + _c.SetScope(*v) + } + return _c +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_c *BackupRecordCreate) Mutation() *BackupRecordMutation { + return _c.mutation +} + +// Save creates the BackupRecord in the database. +func (_c *BackupRecordCreate) Save(ctx context.Context) (*BackupRecord, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *BackupRecordCreate) SaveX(ctx context.Context) *BackupRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BackupRecordCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BackupRecordCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *BackupRecordCreate) defaults() { + if _, ok := _c.mutation.ExecutedAt(); !ok { + v := backuprecord.DefaultExecutedAt() + _c.mutation.SetExecutedAt(v) + } + if _, ok := _c.mutation.TotalSize(); !ok { + v := backuprecord.DefaultTotalSize + _c.mutation.SetTotalSize(v) + } + if _, ok := _c.mutation.Status(); !ok { + v := backuprecord.DefaultStatus + _c.mutation.SetStatus(v) + } + if _, ok := _c.mutation.Operator(); !ok { + v := backuprecord.DefaultOperator + _c.mutation.SetOperator(v) + } + if _, ok := _c.mutation.Checksum(); !ok { + v := backuprecord.DefaultChecksum + _c.mutation.SetChecksum(v) + } + if _, ok := _c.mutation.Scope(); !ok { + v := backuprecord.DefaultScope + _c.mutation.SetScope(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *BackupRecordCreate) check() error { + if _, ok := _c.mutation.ExecutedAt(); !ok { + return &ValidationError{Name: "executed_at", err: errors.New(`ent: missing required field "BackupRecord.executed_at"`)} + } + if _, ok := _c.mutation.RangeStart(); !ok { + return &ValidationError{Name: "range_start", err: errors.New(`ent: missing required field "BackupRecord.range_start"`)} + } + if _, ok := _c.mutation.RangeEnd(); !ok { + return &ValidationError{Name: "range_end", err: errors.New(`ent: missing required field "BackupRecord.range_end"`)} + } + if _, ok := _c.mutation.BackupPath(); !ok { + return &ValidationError{Name: "backup_path", err: errors.New(`ent: missing required field "BackupRecord.backup_path"`)} + } + if _, ok := _c.mutation.TotalSize(); !ok { + return &ValidationError{Name: "total_size", err: errors.New(`ent: missing required field "BackupRecord.total_size"`)} + } + if _, ok := _c.mutation.ItemsJSON(); !ok { + return &ValidationError{Name: "items_json", err: errors.New(`ent: missing required field "BackupRecord.items_json"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "BackupRecord.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if _, ok := _c.mutation.Operator(); !ok { + return &ValidationError{Name: "operator", err: errors.New(`ent: missing required field "BackupRecord.operator"`)} + } + if v, ok := _c.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if _, ok := _c.mutation.Checksum(); !ok { + return &ValidationError{Name: "checksum", err: errors.New(`ent: missing required field "BackupRecord.checksum"`)} + } + if v, ok := _c.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if _, ok := _c.mutation.Scope(); !ok { + return &ValidationError{Name: "scope", err: errors.New(`ent: missing required field "BackupRecord.scope"`)} + } + if v, ok := _c.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + return nil +} + +func (_c *BackupRecordCreate) sqlSave(ctx context.Context) (*BackupRecord, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *BackupRecordCreate) createSpec() (*BackupRecord, *sqlgraph.CreateSpec) { + var ( + _node = &BackupRecord{config: _c.config} + _spec = sqlgraph.NewCreateSpec(backuprecord.Table, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + _node.ExecutedAt = value + } + if value, ok := _c.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + _node.RangeStart = value + } + if value, ok := _c.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + _node.RangeEnd = value + } + if value, ok := _c.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + _node.BackupPath = value + } + if value, ok := _c.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + _node.TotalSize = value + } + if value, ok := _c.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + _node.ItemsJSON = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + _node.Status = value + } + if value, ok := _c.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + _node.Operator = value + } + if value, ok := _c.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + _node.Checksum = value + } + if value, ok := _c.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + _node.Scope = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.BackupRecord.Create(). +// SetExecutedAt(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.BackupRecordUpsert) { +// SetExecutedAt(v+v). +// }). +// Exec(ctx) +func (_c *BackupRecordCreate) OnConflict(opts ...sql.ConflictOption) *BackupRecordUpsertOne { + _c.conflict = opts + return &BackupRecordUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BackupRecordCreate) OnConflictColumns(columns ...string) *BackupRecordUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BackupRecordUpsertOne{ + create: _c, + } +} + +type ( + // BackupRecordUpsertOne is the builder for "upsert"-ing + // one BackupRecord node. + BackupRecordUpsertOne struct { + create *BackupRecordCreate + } + + // BackupRecordUpsert is the "OnConflict" setter. + BackupRecordUpsert struct { + *sql.UpdateSet + } +) + +// SetExecutedAt sets the "executed_at" field. +func (u *BackupRecordUpsert) SetExecutedAt(v int64) *BackupRecordUpsert { + u.Set(backuprecord.FieldExecutedAt, v) + return u +} + +// UpdateExecutedAt sets the "executed_at" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateExecutedAt() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldExecutedAt) + return u +} + +// AddExecutedAt adds v to the "executed_at" field. +func (u *BackupRecordUpsert) AddExecutedAt(v int64) *BackupRecordUpsert { + u.Add(backuprecord.FieldExecutedAt, v) + return u +} + +// SetRangeStart sets the "range_start" field. +func (u *BackupRecordUpsert) SetRangeStart(v int64) *BackupRecordUpsert { + u.Set(backuprecord.FieldRangeStart, v) + return u +} + +// UpdateRangeStart sets the "range_start" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateRangeStart() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldRangeStart) + return u +} + +// AddRangeStart adds v to the "range_start" field. +func (u *BackupRecordUpsert) AddRangeStart(v int64) *BackupRecordUpsert { + u.Add(backuprecord.FieldRangeStart, v) + return u +} + +// SetRangeEnd sets the "range_end" field. +func (u *BackupRecordUpsert) SetRangeEnd(v int64) *BackupRecordUpsert { + u.Set(backuprecord.FieldRangeEnd, v) + return u +} + +// UpdateRangeEnd sets the "range_end" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateRangeEnd() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldRangeEnd) + return u +} + +// AddRangeEnd adds v to the "range_end" field. +func (u *BackupRecordUpsert) AddRangeEnd(v int64) *BackupRecordUpsert { + u.Add(backuprecord.FieldRangeEnd, v) + return u +} + +// SetBackupPath sets the "backup_path" field. +func (u *BackupRecordUpsert) SetBackupPath(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldBackupPath, v) + return u +} + +// UpdateBackupPath sets the "backup_path" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateBackupPath() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldBackupPath) + return u +} + +// SetTotalSize sets the "total_size" field. +func (u *BackupRecordUpsert) SetTotalSize(v int64) *BackupRecordUpsert { + u.Set(backuprecord.FieldTotalSize, v) + return u +} + +// UpdateTotalSize sets the "total_size" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateTotalSize() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldTotalSize) + return u +} + +// AddTotalSize adds v to the "total_size" field. +func (u *BackupRecordUpsert) AddTotalSize(v int64) *BackupRecordUpsert { + u.Add(backuprecord.FieldTotalSize, v) + return u +} + +// SetItemsJSON sets the "items_json" field. +func (u *BackupRecordUpsert) SetItemsJSON(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldItemsJSON, v) + return u +} + +// UpdateItemsJSON sets the "items_json" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateItemsJSON() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldItemsJSON) + return u +} + +// SetStatus sets the "status" field. +func (u *BackupRecordUpsert) SetStatus(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldStatus, v) + return u +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateStatus() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldStatus) + return u +} + +// SetOperator sets the "operator" field. +func (u *BackupRecordUpsert) SetOperator(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldOperator, v) + return u +} + +// UpdateOperator sets the "operator" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateOperator() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldOperator) + return u +} + +// SetChecksum sets the "checksum" field. +func (u *BackupRecordUpsert) SetChecksum(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldChecksum, v) + return u +} + +// UpdateChecksum sets the "checksum" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateChecksum() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldChecksum) + return u +} + +// SetScope sets the "scope" field. +func (u *BackupRecordUpsert) SetScope(v string) *BackupRecordUpsert { + u.Set(backuprecord.FieldScope, v) + return u +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BackupRecordUpsert) UpdateScope() *BackupRecordUpsert { + u.SetExcluded(backuprecord.FieldScope) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *BackupRecordUpsertOne) UpdateNewValues() *BackupRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BackupRecordUpsertOne) Ignore() *BackupRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *BackupRecordUpsertOne) DoNothing() *BackupRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BackupRecordCreate.OnConflict +// documentation for more info. +func (u *BackupRecordUpsertOne) Update(set func(*BackupRecordUpsert)) *BackupRecordUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BackupRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetExecutedAt sets the "executed_at" field. +func (u *BackupRecordUpsertOne) SetExecutedAt(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetExecutedAt(v) + }) +} + +// AddExecutedAt adds v to the "executed_at" field. +func (u *BackupRecordUpsertOne) AddExecutedAt(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.AddExecutedAt(v) + }) +} + +// UpdateExecutedAt sets the "executed_at" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateExecutedAt() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateExecutedAt() + }) +} + +// SetRangeStart sets the "range_start" field. +func (u *BackupRecordUpsertOne) SetRangeStart(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetRangeStart(v) + }) +} + +// AddRangeStart adds v to the "range_start" field. +func (u *BackupRecordUpsertOne) AddRangeStart(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.AddRangeStart(v) + }) +} + +// UpdateRangeStart sets the "range_start" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateRangeStart() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateRangeStart() + }) +} + +// SetRangeEnd sets the "range_end" field. +func (u *BackupRecordUpsertOne) SetRangeEnd(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetRangeEnd(v) + }) +} + +// AddRangeEnd adds v to the "range_end" field. +func (u *BackupRecordUpsertOne) AddRangeEnd(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.AddRangeEnd(v) + }) +} + +// UpdateRangeEnd sets the "range_end" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateRangeEnd() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateRangeEnd() + }) +} + +// SetBackupPath sets the "backup_path" field. +func (u *BackupRecordUpsertOne) SetBackupPath(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetBackupPath(v) + }) +} + +// UpdateBackupPath sets the "backup_path" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateBackupPath() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateBackupPath() + }) +} + +// SetTotalSize sets the "total_size" field. +func (u *BackupRecordUpsertOne) SetTotalSize(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetTotalSize(v) + }) +} + +// AddTotalSize adds v to the "total_size" field. +func (u *BackupRecordUpsertOne) AddTotalSize(v int64) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.AddTotalSize(v) + }) +} + +// UpdateTotalSize sets the "total_size" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateTotalSize() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateTotalSize() + }) +} + +// SetItemsJSON sets the "items_json" field. +func (u *BackupRecordUpsertOne) SetItemsJSON(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetItemsJSON(v) + }) +} + +// UpdateItemsJSON sets the "items_json" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateItemsJSON() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateItemsJSON() + }) +} + +// SetStatus sets the "status" field. +func (u *BackupRecordUpsertOne) SetStatus(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateStatus() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateStatus() + }) +} + +// SetOperator sets the "operator" field. +func (u *BackupRecordUpsertOne) SetOperator(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetOperator(v) + }) +} + +// UpdateOperator sets the "operator" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateOperator() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateOperator() + }) +} + +// SetChecksum sets the "checksum" field. +func (u *BackupRecordUpsertOne) SetChecksum(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetChecksum(v) + }) +} + +// UpdateChecksum sets the "checksum" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateChecksum() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateChecksum() + }) +} + +// SetScope sets the "scope" field. +func (u *BackupRecordUpsertOne) SetScope(v string) *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BackupRecordUpsertOne) UpdateScope() *BackupRecordUpsertOne { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateScope() + }) +} + +// Exec executes the query. +func (u *BackupRecordUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for BackupRecordCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BackupRecordUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *BackupRecordUpsertOne) ID(ctx context.Context) (id int, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *BackupRecordUpsertOne) IDX(ctx context.Context) int { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// BackupRecordCreateBulk is the builder for creating many BackupRecord entities in bulk. +type BackupRecordCreateBulk struct { + config + err error + builders []*BackupRecordCreate + conflict []sql.ConflictOption +} + +// Save creates the BackupRecord entities in the database. +func (_c *BackupRecordCreateBulk) Save(ctx context.Context) ([]*BackupRecord, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*BackupRecord, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BackupRecordMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *BackupRecordCreateBulk) SaveX(ctx context.Context) []*BackupRecord { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *BackupRecordCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *BackupRecordCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.BackupRecord.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.BackupRecordUpsert) { +// SetExecutedAt(v+v). +// }). +// Exec(ctx) +func (_c *BackupRecordCreateBulk) OnConflict(opts ...sql.ConflictOption) *BackupRecordUpsertBulk { + _c.conflict = opts + return &BackupRecordUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *BackupRecordCreateBulk) OnConflictColumns(columns ...string) *BackupRecordUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &BackupRecordUpsertBulk{ + create: _c, + } +} + +// BackupRecordUpsertBulk is the builder for "upsert"-ing +// a bulk of BackupRecord nodes. +type BackupRecordUpsertBulk struct { + create *BackupRecordCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *BackupRecordUpsertBulk) UpdateNewValues() *BackupRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.BackupRecord.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *BackupRecordUpsertBulk) Ignore() *BackupRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *BackupRecordUpsertBulk) DoNothing() *BackupRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the BackupRecordCreateBulk.OnConflict +// documentation for more info. +func (u *BackupRecordUpsertBulk) Update(set func(*BackupRecordUpsert)) *BackupRecordUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&BackupRecordUpsert{UpdateSet: update}) + })) + return u +} + +// SetExecutedAt sets the "executed_at" field. +func (u *BackupRecordUpsertBulk) SetExecutedAt(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetExecutedAt(v) + }) +} + +// AddExecutedAt adds v to the "executed_at" field. +func (u *BackupRecordUpsertBulk) AddExecutedAt(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.AddExecutedAt(v) + }) +} + +// UpdateExecutedAt sets the "executed_at" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateExecutedAt() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateExecutedAt() + }) +} + +// SetRangeStart sets the "range_start" field. +func (u *BackupRecordUpsertBulk) SetRangeStart(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetRangeStart(v) + }) +} + +// AddRangeStart adds v to the "range_start" field. +func (u *BackupRecordUpsertBulk) AddRangeStart(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.AddRangeStart(v) + }) +} + +// UpdateRangeStart sets the "range_start" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateRangeStart() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateRangeStart() + }) +} + +// SetRangeEnd sets the "range_end" field. +func (u *BackupRecordUpsertBulk) SetRangeEnd(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetRangeEnd(v) + }) +} + +// AddRangeEnd adds v to the "range_end" field. +func (u *BackupRecordUpsertBulk) AddRangeEnd(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.AddRangeEnd(v) + }) +} + +// UpdateRangeEnd sets the "range_end" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateRangeEnd() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateRangeEnd() + }) +} + +// SetBackupPath sets the "backup_path" field. +func (u *BackupRecordUpsertBulk) SetBackupPath(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetBackupPath(v) + }) +} + +// UpdateBackupPath sets the "backup_path" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateBackupPath() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateBackupPath() + }) +} + +// SetTotalSize sets the "total_size" field. +func (u *BackupRecordUpsertBulk) SetTotalSize(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetTotalSize(v) + }) +} + +// AddTotalSize adds v to the "total_size" field. +func (u *BackupRecordUpsertBulk) AddTotalSize(v int64) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.AddTotalSize(v) + }) +} + +// UpdateTotalSize sets the "total_size" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateTotalSize() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateTotalSize() + }) +} + +// SetItemsJSON sets the "items_json" field. +func (u *BackupRecordUpsertBulk) SetItemsJSON(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetItemsJSON(v) + }) +} + +// UpdateItemsJSON sets the "items_json" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateItemsJSON() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateItemsJSON() + }) +} + +// SetStatus sets the "status" field. +func (u *BackupRecordUpsertBulk) SetStatus(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetStatus(v) + }) +} + +// UpdateStatus sets the "status" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateStatus() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateStatus() + }) +} + +// SetOperator sets the "operator" field. +func (u *BackupRecordUpsertBulk) SetOperator(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetOperator(v) + }) +} + +// UpdateOperator sets the "operator" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateOperator() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateOperator() + }) +} + +// SetChecksum sets the "checksum" field. +func (u *BackupRecordUpsertBulk) SetChecksum(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetChecksum(v) + }) +} + +// UpdateChecksum sets the "checksum" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateChecksum() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateChecksum() + }) +} + +// SetScope sets the "scope" field. +func (u *BackupRecordUpsertBulk) SetScope(v string) *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.SetScope(v) + }) +} + +// UpdateScope sets the "scope" field to the value that was provided on create. +func (u *BackupRecordUpsertBulk) UpdateScope() *BackupRecordUpsertBulk { + return u.Update(func(s *BackupRecordUpsert) { + s.UpdateScope() + }) +} + +// Exec executes the query. +func (u *BackupRecordUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the BackupRecordCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for BackupRecordCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *BackupRecordUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_wms/ent/backuprecord_delete.go b/bj_power_wms/ent/backuprecord_delete.go new file mode 100644 index 0000000..d9e813e --- /dev/null +++ b/bj_power_wms/ent/backuprecord_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/backuprecord" + "bj_power_wms/ent/predicate" + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordDelete is the builder for deleting a BackupRecord entity. +type BackupRecordDelete struct { + config + hooks []Hook + mutation *BackupRecordMutation +} + +// Where appends a list predicates to the BackupRecordDelete builder. +func (_d *BackupRecordDelete) Where(ps ...predicate.BackupRecord) *BackupRecordDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *BackupRecordDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BackupRecordDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *BackupRecordDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(backuprecord.Table, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// BackupRecordDeleteOne is the builder for deleting a single BackupRecord entity. +type BackupRecordDeleteOne struct { + _d *BackupRecordDelete +} + +// Where appends a list predicates to the BackupRecordDelete builder. +func (_d *BackupRecordDeleteOne) Where(ps ...predicate.BackupRecord) *BackupRecordDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *BackupRecordDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{backuprecord.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *BackupRecordDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_wms/ent/backuprecord_query.go b/bj_power_wms/ent/backuprecord_query.go new file mode 100644 index 0000000..f27edd8 --- /dev/null +++ b/bj_power_wms/ent/backuprecord_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/backuprecord" + "bj_power_wms/ent/predicate" + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordQuery is the builder for querying BackupRecord entities. +type BackupRecordQuery struct { + config + ctx *QueryContext + order []backuprecord.OrderOption + inters []Interceptor + predicates []predicate.BackupRecord + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BackupRecordQuery builder. +func (_q *BackupRecordQuery) Where(ps ...predicate.BackupRecord) *BackupRecordQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *BackupRecordQuery) Limit(limit int) *BackupRecordQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *BackupRecordQuery) Offset(offset int) *BackupRecordQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *BackupRecordQuery) Unique(unique bool) *BackupRecordQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *BackupRecordQuery) Order(o ...backuprecord.OrderOption) *BackupRecordQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first BackupRecord entity from the query. +// Returns a *NotFoundError when no BackupRecord was found. +func (_q *BackupRecordQuery) First(ctx context.Context) (*BackupRecord, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{backuprecord.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *BackupRecordQuery) FirstX(ctx context.Context) *BackupRecord { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BackupRecord ID from the query. +// Returns a *NotFoundError when no BackupRecord ID was found. +func (_q *BackupRecordQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{backuprecord.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *BackupRecordQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BackupRecord entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BackupRecord entity is found. +// Returns a *NotFoundError when no BackupRecord entities are found. +func (_q *BackupRecordQuery) Only(ctx context.Context) (*BackupRecord, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{backuprecord.Label} + default: + return nil, &NotSingularError{backuprecord.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *BackupRecordQuery) OnlyX(ctx context.Context) *BackupRecord { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BackupRecord ID in the query. +// Returns a *NotSingularError when more than one BackupRecord ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *BackupRecordQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{backuprecord.Label} + default: + err = &NotSingularError{backuprecord.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *BackupRecordQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of BackupRecords. +func (_q *BackupRecordQuery) All(ctx context.Context) ([]*BackupRecord, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BackupRecord, *BackupRecordQuery]() + return withInterceptors[[]*BackupRecord](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *BackupRecordQuery) AllX(ctx context.Context) []*BackupRecord { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BackupRecord IDs. +func (_q *BackupRecordQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(backuprecord.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *BackupRecordQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *BackupRecordQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*BackupRecordQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *BackupRecordQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *BackupRecordQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *BackupRecordQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BackupRecordQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *BackupRecordQuery) Clone() *BackupRecordQuery { + if _q == nil { + return nil + } + return &BackupRecordQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]backuprecord.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.BackupRecord{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// ExecutedAt int64 `json:"executedAt,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.BackupRecord.Query(). +// GroupBy(backuprecord.FieldExecutedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *BackupRecordQuery) GroupBy(field string, fields ...string) *BackupRecordGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &BackupRecordGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = backuprecord.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// ExecutedAt int64 `json:"executedAt,omitempty"` +// } +// +// client.BackupRecord.Query(). +// Select(backuprecord.FieldExecutedAt). +// Scan(ctx, &v) +func (_q *BackupRecordQuery) Select(fields ...string) *BackupRecordSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &BackupRecordSelect{BackupRecordQuery: _q} + sbuild.label = backuprecord.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BackupRecordSelect configured with the given aggregations. +func (_q *BackupRecordQuery) Aggregate(fns ...AggregateFunc) *BackupRecordSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *BackupRecordQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !backuprecord.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *BackupRecordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BackupRecord, error) { + var ( + nodes = []*BackupRecord{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BackupRecord).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BackupRecord{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *BackupRecordQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *BackupRecordQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, backuprecord.FieldID) + for i := range fields { + if fields[i] != backuprecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *BackupRecordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(backuprecord.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = backuprecord.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// BackupRecordGroupBy is the group-by builder for BackupRecord entities. +type BackupRecordGroupBy struct { + selector + build *BackupRecordQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *BackupRecordGroupBy) Aggregate(fns ...AggregateFunc) *BackupRecordGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *BackupRecordGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BackupRecordQuery, *BackupRecordGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *BackupRecordGroupBy) sqlScan(ctx context.Context, root *BackupRecordQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// BackupRecordSelect is the builder for selecting fields of BackupRecord entities. +type BackupRecordSelect struct { + *BackupRecordQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *BackupRecordSelect) Aggregate(fns ...AggregateFunc) *BackupRecordSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *BackupRecordSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BackupRecordQuery, *BackupRecordSelect](ctx, _s.BackupRecordQuery, _s, _s.inters, v) +} + +func (_s *BackupRecordSelect) sqlScan(ctx context.Context, root *BackupRecordQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/bj_power_wms/ent/backuprecord_update.go b/bj_power_wms/ent/backuprecord_update.go new file mode 100644 index 0000000..5306343 --- /dev/null +++ b/bj_power_wms/ent/backuprecord_update.go @@ -0,0 +1,651 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/backuprecord" + "bj_power_wms/ent/predicate" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BackupRecordUpdate is the builder for updating BackupRecord entities. +type BackupRecordUpdate struct { + config + hooks []Hook + mutation *BackupRecordMutation +} + +// Where appends a list predicates to the BackupRecordUpdate builder. +func (_u *BackupRecordUpdate) Where(ps ...predicate.BackupRecord) *BackupRecordUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetExecutedAt sets the "executed_at" field. +func (_u *BackupRecordUpdate) SetExecutedAt(v int64) *BackupRecordUpdate { + _u.mutation.ResetExecutedAt() + _u.mutation.SetExecutedAt(v) + return _u +} + +// SetNillableExecutedAt sets the "executed_at" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableExecutedAt(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetExecutedAt(*v) + } + return _u +} + +// AddExecutedAt adds value to the "executed_at" field. +func (_u *BackupRecordUpdate) AddExecutedAt(v int64) *BackupRecordUpdate { + _u.mutation.AddExecutedAt(v) + return _u +} + +// SetRangeStart sets the "range_start" field. +func (_u *BackupRecordUpdate) SetRangeStart(v int64) *BackupRecordUpdate { + _u.mutation.ResetRangeStart() + _u.mutation.SetRangeStart(v) + return _u +} + +// SetNillableRangeStart sets the "range_start" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableRangeStart(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetRangeStart(*v) + } + return _u +} + +// AddRangeStart adds value to the "range_start" field. +func (_u *BackupRecordUpdate) AddRangeStart(v int64) *BackupRecordUpdate { + _u.mutation.AddRangeStart(v) + return _u +} + +// SetRangeEnd sets the "range_end" field. +func (_u *BackupRecordUpdate) SetRangeEnd(v int64) *BackupRecordUpdate { + _u.mutation.ResetRangeEnd() + _u.mutation.SetRangeEnd(v) + return _u +} + +// SetNillableRangeEnd sets the "range_end" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableRangeEnd(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetRangeEnd(*v) + } + return _u +} + +// AddRangeEnd adds value to the "range_end" field. +func (_u *BackupRecordUpdate) AddRangeEnd(v int64) *BackupRecordUpdate { + _u.mutation.AddRangeEnd(v) + return _u +} + +// SetBackupPath sets the "backup_path" field. +func (_u *BackupRecordUpdate) SetBackupPath(v string) *BackupRecordUpdate { + _u.mutation.SetBackupPath(v) + return _u +} + +// SetNillableBackupPath sets the "backup_path" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableBackupPath(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetBackupPath(*v) + } + return _u +} + +// SetTotalSize sets the "total_size" field. +func (_u *BackupRecordUpdate) SetTotalSize(v int64) *BackupRecordUpdate { + _u.mutation.ResetTotalSize() + _u.mutation.SetTotalSize(v) + return _u +} + +// SetNillableTotalSize sets the "total_size" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableTotalSize(v *int64) *BackupRecordUpdate { + if v != nil { + _u.SetTotalSize(*v) + } + return _u +} + +// AddTotalSize adds value to the "total_size" field. +func (_u *BackupRecordUpdate) AddTotalSize(v int64) *BackupRecordUpdate { + _u.mutation.AddTotalSize(v) + return _u +} + +// SetItemsJSON sets the "items_json" field. +func (_u *BackupRecordUpdate) SetItemsJSON(v string) *BackupRecordUpdate { + _u.mutation.SetItemsJSON(v) + return _u +} + +// SetNillableItemsJSON sets the "items_json" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableItemsJSON(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetItemsJSON(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *BackupRecordUpdate) SetStatus(v string) *BackupRecordUpdate { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableStatus(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetOperator sets the "operator" field. +func (_u *BackupRecordUpdate) SetOperator(v string) *BackupRecordUpdate { + _u.mutation.SetOperator(v) + return _u +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableOperator(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetOperator(*v) + } + return _u +} + +// SetChecksum sets the "checksum" field. +func (_u *BackupRecordUpdate) SetChecksum(v string) *BackupRecordUpdate { + _u.mutation.SetChecksum(v) + return _u +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableChecksum(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetChecksum(*v) + } + return _u +} + +// SetScope sets the "scope" field. +func (_u *BackupRecordUpdate) SetScope(v string) *BackupRecordUpdate { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BackupRecordUpdate) SetNillableScope(v *string) *BackupRecordUpdate { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_u *BackupRecordUpdate) Mutation() *BackupRecordMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *BackupRecordUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BackupRecordUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *BackupRecordUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BackupRecordUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BackupRecordUpdate) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if v, ok := _u.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if v, ok := _u.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if v, ok := _u.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + return nil +} + +func (_u *BackupRecordUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedExecutedAt(); ok { + _spec.AddField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeStart(); ok { + _spec.AddField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeEnd(); ok { + _spec.AddField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + } + if value, ok := _u.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTotalSize(); ok { + _spec.AddField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + } + if value, ok := _u.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + } + if value, ok := _u.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{backuprecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// BackupRecordUpdateOne is the builder for updating a single BackupRecord entity. +type BackupRecordUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BackupRecordMutation +} + +// SetExecutedAt sets the "executed_at" field. +func (_u *BackupRecordUpdateOne) SetExecutedAt(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetExecutedAt() + _u.mutation.SetExecutedAt(v) + return _u +} + +// SetNillableExecutedAt sets the "executed_at" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableExecutedAt(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetExecutedAt(*v) + } + return _u +} + +// AddExecutedAt adds value to the "executed_at" field. +func (_u *BackupRecordUpdateOne) AddExecutedAt(v int64) *BackupRecordUpdateOne { + _u.mutation.AddExecutedAt(v) + return _u +} + +// SetRangeStart sets the "range_start" field. +func (_u *BackupRecordUpdateOne) SetRangeStart(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetRangeStart() + _u.mutation.SetRangeStart(v) + return _u +} + +// SetNillableRangeStart sets the "range_start" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableRangeStart(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetRangeStart(*v) + } + return _u +} + +// AddRangeStart adds value to the "range_start" field. +func (_u *BackupRecordUpdateOne) AddRangeStart(v int64) *BackupRecordUpdateOne { + _u.mutation.AddRangeStart(v) + return _u +} + +// SetRangeEnd sets the "range_end" field. +func (_u *BackupRecordUpdateOne) SetRangeEnd(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetRangeEnd() + _u.mutation.SetRangeEnd(v) + return _u +} + +// SetNillableRangeEnd sets the "range_end" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableRangeEnd(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetRangeEnd(*v) + } + return _u +} + +// AddRangeEnd adds value to the "range_end" field. +func (_u *BackupRecordUpdateOne) AddRangeEnd(v int64) *BackupRecordUpdateOne { + _u.mutation.AddRangeEnd(v) + return _u +} + +// SetBackupPath sets the "backup_path" field. +func (_u *BackupRecordUpdateOne) SetBackupPath(v string) *BackupRecordUpdateOne { + _u.mutation.SetBackupPath(v) + return _u +} + +// SetNillableBackupPath sets the "backup_path" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableBackupPath(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetBackupPath(*v) + } + return _u +} + +// SetTotalSize sets the "total_size" field. +func (_u *BackupRecordUpdateOne) SetTotalSize(v int64) *BackupRecordUpdateOne { + _u.mutation.ResetTotalSize() + _u.mutation.SetTotalSize(v) + return _u +} + +// SetNillableTotalSize sets the "total_size" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableTotalSize(v *int64) *BackupRecordUpdateOne { + if v != nil { + _u.SetTotalSize(*v) + } + return _u +} + +// AddTotalSize adds value to the "total_size" field. +func (_u *BackupRecordUpdateOne) AddTotalSize(v int64) *BackupRecordUpdateOne { + _u.mutation.AddTotalSize(v) + return _u +} + +// SetItemsJSON sets the "items_json" field. +func (_u *BackupRecordUpdateOne) SetItemsJSON(v string) *BackupRecordUpdateOne { + _u.mutation.SetItemsJSON(v) + return _u +} + +// SetNillableItemsJSON sets the "items_json" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableItemsJSON(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetItemsJSON(*v) + } + return _u +} + +// SetStatus sets the "status" field. +func (_u *BackupRecordUpdateOne) SetStatus(v string) *BackupRecordUpdateOne { + _u.mutation.SetStatus(v) + return _u +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableStatus(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetStatus(*v) + } + return _u +} + +// SetOperator sets the "operator" field. +func (_u *BackupRecordUpdateOne) SetOperator(v string) *BackupRecordUpdateOne { + _u.mutation.SetOperator(v) + return _u +} + +// SetNillableOperator sets the "operator" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableOperator(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetOperator(*v) + } + return _u +} + +// SetChecksum sets the "checksum" field. +func (_u *BackupRecordUpdateOne) SetChecksum(v string) *BackupRecordUpdateOne { + _u.mutation.SetChecksum(v) + return _u +} + +// SetNillableChecksum sets the "checksum" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableChecksum(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetChecksum(*v) + } + return _u +} + +// SetScope sets the "scope" field. +func (_u *BackupRecordUpdateOne) SetScope(v string) *BackupRecordUpdateOne { + _u.mutation.SetScope(v) + return _u +} + +// SetNillableScope sets the "scope" field if the given value is not nil. +func (_u *BackupRecordUpdateOne) SetNillableScope(v *string) *BackupRecordUpdateOne { + if v != nil { + _u.SetScope(*v) + } + return _u +} + +// Mutation returns the BackupRecordMutation object of the builder. +func (_u *BackupRecordUpdateOne) Mutation() *BackupRecordMutation { + return _u.mutation +} + +// Where appends a list predicates to the BackupRecordUpdate builder. +func (_u *BackupRecordUpdateOne) Where(ps ...predicate.BackupRecord) *BackupRecordUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *BackupRecordUpdateOne) Select(field string, fields ...string) *BackupRecordUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated BackupRecord entity. +func (_u *BackupRecordUpdateOne) Save(ctx context.Context) (*BackupRecord, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *BackupRecordUpdateOne) SaveX(ctx context.Context) *BackupRecord { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *BackupRecordUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *BackupRecordUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *BackupRecordUpdateOne) check() error { + if v, ok := _u.mutation.Status(); ok { + if err := backuprecord.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.status": %w`, err)} + } + } + if v, ok := _u.mutation.Operator(); ok { + if err := backuprecord.OperatorValidator(v); err != nil { + return &ValidationError{Name: "operator", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.operator": %w`, err)} + } + } + if v, ok := _u.mutation.Checksum(); ok { + if err := backuprecord.ChecksumValidator(v); err != nil { + return &ValidationError{Name: "checksum", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.checksum": %w`, err)} + } + } + if v, ok := _u.mutation.Scope(); ok { + if err := backuprecord.ScopeValidator(v); err != nil { + return &ValidationError{Name: "scope", err: fmt.Errorf(`ent: validator failed for field "BackupRecord.scope": %w`, err)} + } + } + return nil +} + +func (_u *BackupRecordUpdateOne) sqlSave(ctx context.Context) (_node *BackupRecord, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(backuprecord.Table, backuprecord.Columns, sqlgraph.NewFieldSpec(backuprecord.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "BackupRecord.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, backuprecord.FieldID) + for _, f := range fields { + if !backuprecord.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != backuprecord.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.ExecutedAt(); ok { + _spec.SetField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedExecutedAt(); ok { + _spec.AddField(backuprecord.FieldExecutedAt, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeStart(); ok { + _spec.SetField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeStart(); ok { + _spec.AddField(backuprecord.FieldRangeStart, field.TypeInt64, value) + } + if value, ok := _u.mutation.RangeEnd(); ok { + _spec.SetField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedRangeEnd(); ok { + _spec.AddField(backuprecord.FieldRangeEnd, field.TypeInt64, value) + } + if value, ok := _u.mutation.BackupPath(); ok { + _spec.SetField(backuprecord.FieldBackupPath, field.TypeString, value) + } + if value, ok := _u.mutation.TotalSize(); ok { + _spec.SetField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTotalSize(); ok { + _spec.AddField(backuprecord.FieldTotalSize, field.TypeInt64, value) + } + if value, ok := _u.mutation.ItemsJSON(); ok { + _spec.SetField(backuprecord.FieldItemsJSON, field.TypeString, value) + } + if value, ok := _u.mutation.Status(); ok { + _spec.SetField(backuprecord.FieldStatus, field.TypeString, value) + } + if value, ok := _u.mutation.Operator(); ok { + _spec.SetField(backuprecord.FieldOperator, field.TypeString, value) + } + if value, ok := _u.mutation.Checksum(); ok { + _spec.SetField(backuprecord.FieldChecksum, field.TypeString, value) + } + if value, ok := _u.mutation.Scope(); ok { + _spec.SetField(backuprecord.FieldScope, field.TypeString, value) + } + _node = &BackupRecord{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{backuprecord.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/bj_power_wms/ent/client.go b/bj_power_wms/ent/client.go index 8f51e71..a65a9b0 100644 --- a/bj_power_wms/ent/client.go +++ b/bj_power_wms/ent/client.go @@ -12,6 +12,7 @@ import ( "bj_power_wms/ent/migrate" "bj_power_wms/ent/attachment" + "bj_power_wms/ent/backuprecord" "bj_power_wms/ent/eventlog" "bj_power_wms/ent/inbounddetail" "bj_power_wms/ent/inboundorder" @@ -29,6 +30,7 @@ import ( "bj_power_wms/ent/semifinished" "bj_power_wms/ent/stocktakeitem" "bj_power_wms/ent/stocktakeorder" + "bj_power_wms/ent/sysconfig" "bj_power_wms/ent/user" "bj_power_wms/ent/zone" @@ -44,6 +46,8 @@ type Client struct { Schema *migrate.Schema // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient + // BackupRecord is the client for interacting with the BackupRecord builders. + BackupRecord *BackupRecordClient // EventLog is the client for interacting with the EventLog builders. EventLog *EventLogClient // InboundDetail is the client for interacting with the InboundDetail builders. @@ -78,6 +82,8 @@ type Client struct { StocktakeItem *StocktakeItemClient // StocktakeOrder is the client for interacting with the StocktakeOrder builders. StocktakeOrder *StocktakeOrderClient + // SysConfig is the client for interacting with the SysConfig builders. + SysConfig *SysConfigClient // User is the client for interacting with the User builders. User *UserClient // Zone is the client for interacting with the Zone builders. @@ -94,6 +100,7 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.Attachment = NewAttachmentClient(c.config) + c.BackupRecord = NewBackupRecordClient(c.config) c.EventLog = NewEventLogClient(c.config) c.InboundDetail = NewInboundDetailClient(c.config) c.InboundOrder = NewInboundOrderClient(c.config) @@ -111,6 +118,7 @@ func (c *Client) init() { c.SemiFinished = NewSemiFinishedClient(c.config) c.StocktakeItem = NewStocktakeItemClient(c.config) c.StocktakeOrder = NewStocktakeOrderClient(c.config) + c.SysConfig = NewSysConfigClient(c.config) c.User = NewUserClient(c.config) c.Zone = NewZoneClient(c.config) } @@ -206,6 +214,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ctx: ctx, config: cfg, Attachment: NewAttachmentClient(cfg), + BackupRecord: NewBackupRecordClient(cfg), EventLog: NewEventLogClient(cfg), InboundDetail: NewInboundDetailClient(cfg), InboundOrder: NewInboundOrderClient(cfg), @@ -223,6 +232,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { SemiFinished: NewSemiFinishedClient(cfg), StocktakeItem: NewStocktakeItemClient(cfg), StocktakeOrder: NewStocktakeOrderClient(cfg), + SysConfig: NewSysConfigClient(cfg), User: NewUserClient(cfg), Zone: NewZoneClient(cfg), }, nil @@ -245,6 +255,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ctx: ctx, config: cfg, Attachment: NewAttachmentClient(cfg), + BackupRecord: NewBackupRecordClient(cfg), EventLog: NewEventLogClient(cfg), InboundDetail: NewInboundDetailClient(cfg), InboundOrder: NewInboundOrderClient(cfg), @@ -262,6 +273,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) SemiFinished: NewSemiFinishedClient(cfg), StocktakeItem: NewStocktakeItemClient(cfg), StocktakeOrder: NewStocktakeOrderClient(cfg), + SysConfig: NewSysConfigClient(cfg), User: NewUserClient(cfg), Zone: NewZoneClient(cfg), }, nil @@ -293,11 +305,11 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.Attachment, c.EventLog, c.InboundDetail, c.InboundOrder, c.InspectionRecord, - c.Inventory, c.InventoryLock, c.Material, c.MaterialDemand, + c.Attachment, c.BackupRecord, c.EventLog, c.InboundDetail, c.InboundOrder, + c.InspectionRecord, c.Inventory, c.InventoryLock, c.Material, c.MaterialDemand, c.OrderMaterialLedger, c.OutboundDetail, c.OutboundOrder, c.Permission, c.ReturnOrder, c.Role, c.SemiFinished, c.StocktakeItem, c.StocktakeOrder, - c.User, c.Zone, + c.SysConfig, c.User, c.Zone, } { n.Use(hooks...) } @@ -307,11 +319,11 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.Attachment, c.EventLog, c.InboundDetail, c.InboundOrder, c.InspectionRecord, - c.Inventory, c.InventoryLock, c.Material, c.MaterialDemand, + c.Attachment, c.BackupRecord, c.EventLog, c.InboundDetail, c.InboundOrder, + c.InspectionRecord, c.Inventory, c.InventoryLock, c.Material, c.MaterialDemand, c.OrderMaterialLedger, c.OutboundDetail, c.OutboundOrder, c.Permission, c.ReturnOrder, c.Role, c.SemiFinished, c.StocktakeItem, c.StocktakeOrder, - c.User, c.Zone, + c.SysConfig, c.User, c.Zone, } { n.Intercept(interceptors...) } @@ -322,6 +334,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { case *AttachmentMutation: return c.Attachment.mutate(ctx, m) + case *BackupRecordMutation: + return c.BackupRecord.mutate(ctx, m) case *EventLogMutation: return c.EventLog.mutate(ctx, m) case *InboundDetailMutation: @@ -356,6 +370,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.StocktakeItem.mutate(ctx, m) case *StocktakeOrderMutation: return c.StocktakeOrder.mutate(ctx, m) + case *SysConfigMutation: + return c.SysConfig.mutate(ctx, m) case *UserMutation: return c.User.mutate(ctx, m) case *ZoneMutation: @@ -498,6 +514,139 @@ func (c *AttachmentClient) mutate(ctx context.Context, m *AttachmentMutation) (V } } +// BackupRecordClient is a client for the BackupRecord schema. +type BackupRecordClient struct { + config +} + +// NewBackupRecordClient returns a client for the BackupRecord from the given config. +func NewBackupRecordClient(c config) *BackupRecordClient { + return &BackupRecordClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `backuprecord.Hooks(f(g(h())))`. +func (c *BackupRecordClient) Use(hooks ...Hook) { + c.hooks.BackupRecord = append(c.hooks.BackupRecord, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `backuprecord.Intercept(f(g(h())))`. +func (c *BackupRecordClient) Intercept(interceptors ...Interceptor) { + c.inters.BackupRecord = append(c.inters.BackupRecord, interceptors...) +} + +// Create returns a builder for creating a BackupRecord entity. +func (c *BackupRecordClient) Create() *BackupRecordCreate { + mutation := newBackupRecordMutation(c.config, OpCreate) + return &BackupRecordCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BackupRecord entities. +func (c *BackupRecordClient) CreateBulk(builders ...*BackupRecordCreate) *BackupRecordCreateBulk { + return &BackupRecordCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *BackupRecordClient) MapCreateBulk(slice any, setFunc func(*BackupRecordCreate, int)) *BackupRecordCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BackupRecordCreateBulk{err: fmt.Errorf("calling to BackupRecordClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BackupRecordCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BackupRecordCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BackupRecord. +func (c *BackupRecordClient) Update() *BackupRecordUpdate { + mutation := newBackupRecordMutation(c.config, OpUpdate) + return &BackupRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BackupRecordClient) UpdateOne(_m *BackupRecord) *BackupRecordUpdateOne { + mutation := newBackupRecordMutation(c.config, OpUpdateOne, withBackupRecord(_m)) + return &BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BackupRecordClient) UpdateOneID(id int) *BackupRecordUpdateOne { + mutation := newBackupRecordMutation(c.config, OpUpdateOne, withBackupRecordID(id)) + return &BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BackupRecord. +func (c *BackupRecordClient) Delete() *BackupRecordDelete { + mutation := newBackupRecordMutation(c.config, OpDelete) + return &BackupRecordDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BackupRecordClient) DeleteOne(_m *BackupRecord) *BackupRecordDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BackupRecordClient) DeleteOneID(id int) *BackupRecordDeleteOne { + builder := c.Delete().Where(backuprecord.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BackupRecordDeleteOne{builder} +} + +// Query returns a query builder for BackupRecord. +func (c *BackupRecordClient) Query() *BackupRecordQuery { + return &BackupRecordQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBackupRecord}, + inters: c.Interceptors(), + } +} + +// Get returns a BackupRecord entity by its id. +func (c *BackupRecordClient) Get(ctx context.Context, id int) (*BackupRecord, error) { + return c.Query().Where(backuprecord.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BackupRecordClient) GetX(ctx context.Context, id int) *BackupRecord { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BackupRecordClient) Hooks() []Hook { + return c.hooks.BackupRecord +} + +// Interceptors returns the client interceptors. +func (c *BackupRecordClient) Interceptors() []Interceptor { + return c.inters.BackupRecord +} + +func (c *BackupRecordClient) mutate(ctx context.Context, m *BackupRecordMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BackupRecordCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BackupRecordUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BackupRecordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BackupRecordDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown BackupRecord mutation op: %q", m.Op()) + } +} + // EventLogClient is a client for the EventLog schema. type EventLogClient struct { config @@ -2759,6 +2908,139 @@ func (c *StocktakeOrderClient) mutate(ctx context.Context, m *StocktakeOrderMuta } } +// SysConfigClient is a client for the SysConfig schema. +type SysConfigClient struct { + config +} + +// NewSysConfigClient returns a client for the SysConfig from the given config. +func NewSysConfigClient(c config) *SysConfigClient { + return &SysConfigClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `sysconfig.Hooks(f(g(h())))`. +func (c *SysConfigClient) Use(hooks ...Hook) { + c.hooks.SysConfig = append(c.hooks.SysConfig, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `sysconfig.Intercept(f(g(h())))`. +func (c *SysConfigClient) Intercept(interceptors ...Interceptor) { + c.inters.SysConfig = append(c.inters.SysConfig, interceptors...) +} + +// Create returns a builder for creating a SysConfig entity. +func (c *SysConfigClient) Create() *SysConfigCreate { + mutation := newSysConfigMutation(c.config, OpCreate) + return &SysConfigCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of SysConfig entities. +func (c *SysConfigClient) CreateBulk(builders ...*SysConfigCreate) *SysConfigCreateBulk { + return &SysConfigCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *SysConfigClient) MapCreateBulk(slice any, setFunc func(*SysConfigCreate, int)) *SysConfigCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &SysConfigCreateBulk{err: fmt.Errorf("calling to SysConfigClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*SysConfigCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &SysConfigCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for SysConfig. +func (c *SysConfigClient) Update() *SysConfigUpdate { + mutation := newSysConfigMutation(c.config, OpUpdate) + return &SysConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *SysConfigClient) UpdateOne(_m *SysConfig) *SysConfigUpdateOne { + mutation := newSysConfigMutation(c.config, OpUpdateOne, withSysConfig(_m)) + return &SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *SysConfigClient) UpdateOneID(id int) *SysConfigUpdateOne { + mutation := newSysConfigMutation(c.config, OpUpdateOne, withSysConfigID(id)) + return &SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for SysConfig. +func (c *SysConfigClient) Delete() *SysConfigDelete { + mutation := newSysConfigMutation(c.config, OpDelete) + return &SysConfigDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *SysConfigClient) DeleteOne(_m *SysConfig) *SysConfigDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *SysConfigClient) DeleteOneID(id int) *SysConfigDeleteOne { + builder := c.Delete().Where(sysconfig.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &SysConfigDeleteOne{builder} +} + +// Query returns a query builder for SysConfig. +func (c *SysConfigClient) Query() *SysConfigQuery { + return &SysConfigQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeSysConfig}, + inters: c.Interceptors(), + } +} + +// Get returns a SysConfig entity by its id. +func (c *SysConfigClient) Get(ctx context.Context, id int) (*SysConfig, error) { + return c.Query().Where(sysconfig.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *SysConfigClient) GetX(ctx context.Context, id int) *SysConfig { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *SysConfigClient) Hooks() []Hook { + return c.hooks.SysConfig +} + +// Interceptors returns the client interceptors. +func (c *SysConfigClient) Interceptors() []Interceptor { + return c.inters.SysConfig +} + +func (c *SysConfigClient) mutate(ctx context.Context, m *SysConfigMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&SysConfigCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&SysConfigUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&SysConfigUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&SysConfigDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown SysConfig mutation op: %q", m.Op()) + } +} + // UserClient is a client for the User schema. type UserClient struct { config @@ -3028,15 +3310,17 @@ func (c *ZoneClient) mutate(ctx context.Context, m *ZoneMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - Attachment, EventLog, InboundDetail, InboundOrder, InspectionRecord, Inventory, - InventoryLock, Material, MaterialDemand, OrderMaterialLedger, OutboundDetail, - OutboundOrder, Permission, ReturnOrder, Role, SemiFinished, StocktakeItem, - StocktakeOrder, User, Zone []ent.Hook + Attachment, BackupRecord, EventLog, InboundDetail, InboundOrder, + InspectionRecord, Inventory, InventoryLock, Material, MaterialDemand, + OrderMaterialLedger, OutboundDetail, OutboundOrder, Permission, ReturnOrder, + Role, SemiFinished, StocktakeItem, StocktakeOrder, SysConfig, User, + Zone []ent.Hook } inters struct { - Attachment, EventLog, InboundDetail, InboundOrder, InspectionRecord, Inventory, - InventoryLock, Material, MaterialDemand, OrderMaterialLedger, OutboundDetail, - OutboundOrder, Permission, ReturnOrder, Role, SemiFinished, StocktakeItem, - StocktakeOrder, User, Zone []ent.Interceptor + Attachment, BackupRecord, EventLog, InboundDetail, InboundOrder, + InspectionRecord, Inventory, InventoryLock, Material, MaterialDemand, + OrderMaterialLedger, OutboundDetail, OutboundOrder, Permission, ReturnOrder, + Role, SemiFinished, StocktakeItem, StocktakeOrder, SysConfig, User, + Zone []ent.Interceptor } ) diff --git a/bj_power_wms/ent/ent.go b/bj_power_wms/ent/ent.go index 8373d95..8fdc043 100644 --- a/bj_power_wms/ent/ent.go +++ b/bj_power_wms/ent/ent.go @@ -4,6 +4,7 @@ package ent import ( "bj_power_wms/ent/attachment" + "bj_power_wms/ent/backuprecord" "bj_power_wms/ent/eventlog" "bj_power_wms/ent/inbounddetail" "bj_power_wms/ent/inboundorder" @@ -21,6 +22,7 @@ import ( "bj_power_wms/ent/semifinished" "bj_power_wms/ent/stocktakeitem" "bj_power_wms/ent/stocktakeorder" + "bj_power_wms/ent/sysconfig" "bj_power_wms/ent/user" "bj_power_wms/ent/zone" "context" @@ -93,6 +95,7 @@ func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ attachment.Table: attachment.ValidColumn, + backuprecord.Table: backuprecord.ValidColumn, eventlog.Table: eventlog.ValidColumn, inbounddetail.Table: inbounddetail.ValidColumn, inboundorder.Table: inboundorder.ValidColumn, @@ -110,6 +113,7 @@ func checkColumn(t, c string) error { semifinished.Table: semifinished.ValidColumn, stocktakeitem.Table: stocktakeitem.ValidColumn, stocktakeorder.Table: stocktakeorder.ValidColumn, + sysconfig.Table: sysconfig.ValidColumn, user.Table: user.ValidColumn, zone.Table: zone.ValidColumn, }) diff --git a/bj_power_wms/ent/hook/hook.go b/bj_power_wms/ent/hook/hook.go index ed744e0..fc37d66 100644 --- a/bj_power_wms/ent/hook/hook.go +++ b/bj_power_wms/ent/hook/hook.go @@ -20,6 +20,18 @@ func (f AttachmentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AttachmentMutation", m) } +// The BackupRecordFunc type is an adapter to allow the use of ordinary +// function as BackupRecord mutator. +type BackupRecordFunc func(context.Context, *ent.BackupRecordMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f BackupRecordFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.BackupRecordMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.BackupRecordMutation", m) +} + // The EventLogFunc type is an adapter to allow the use of ordinary // function as EventLog mutator. type EventLogFunc func(context.Context, *ent.EventLogMutation) (ent.Value, error) @@ -224,6 +236,18 @@ func (f StocktakeOrderFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Val return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.StocktakeOrderMutation", m) } +// The SysConfigFunc type is an adapter to allow the use of ordinary +// function as SysConfig mutator. +type SysConfigFunc func(context.Context, *ent.SysConfigMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f SysConfigFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.SysConfigMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SysConfigMutation", m) +} + // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) diff --git a/bj_power_wms/ent/migrate/schema.go b/bj_power_wms/ent/migrate/schema.go index 3278a30..7c3d4f0 100644 --- a/bj_power_wms/ent/migrate/schema.go +++ b/bj_power_wms/ent/migrate/schema.go @@ -58,6 +58,44 @@ var ( }, }, } + // BackupRecordColumns holds the columns for the "backup_record" table. + BackupRecordColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "executed_at", Type: field.TypeInt64, Comment: "备份执行时刻(unix秒)"}, + {Name: "range_start", Type: field.TypeInt64, Comment: "备份范围开始(unix秒,含)"}, + {Name: "range_end", Type: field.TypeInt64, Comment: "备份范围结束(unix秒,含)"}, + {Name: "backup_path", Type: field.TypeString, Comment: "备份包(zip)在目标盘的完整路径"}, + {Name: "total_size", Type: field.TypeInt64, Comment: "备份包总字节数", Default: 0}, + {Name: "items_json", Type: field.TypeString, Comment: "各数据项及大小(JSON数组:[{name,rows,bytes}])"}, + {Name: "status", Type: field.TypeString, Size: 16, Comment: "success/failed/partial", Default: "success"}, + {Name: "operator", Type: field.TypeString, Size: 64, Comment: "操作人", Default: ""}, + {Name: "checksum", Type: field.TypeString, Size: 64, Comment: "备份包校验和(sha256,基于 manifest)", Default: ""}, + {Name: "scope", Type: field.TypeString, Size: 8, Comment: "写入方 mes/wms", Default: "wms"}, + } + // BackupRecordTable holds the schema information for the "backup_record" table. + BackupRecordTable = &schema.Table{ + Name: "backup_record", + Comment: "BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖", + Columns: BackupRecordColumns, + PrimaryKey: []*schema.Column{BackupRecordColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "backuprecord_range_start", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[2]}, + }, + { + Name: "backuprecord_range_end", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[3]}, + }, + { + Name: "backuprecord_status", + Unique: false, + Columns: []*schema.Column{BackupRecordColumns[7]}, + }, + }, + } // EventLogColumns holds the columns for the "event_log" table. EventLogColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -757,6 +795,20 @@ var ( }, }, } + // SysConfigColumns holds the columns for the "sys_config" table. + SysConfigColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "key", Type: field.TypeString, Unique: true, Size: 64, Comment: "配置键,如 wms.base_url"}, + {Name: "value", Type: field.TypeString, Size: 512, Comment: "配置值"}, + {Name: "remark", Type: field.TypeString, Nullable: true, Size: 255, Comment: "说明"}, + } + // SysConfigTable holds the schema information for the "sys_config" table. + SysConfigTable = &schema.Table{ + Name: "sys_config", + Comment: "SysConfig 系统基础设置(key/value)。", + Columns: SysConfigColumns, + PrimaryKey: []*schema.Column{SysConfigColumns[0]}, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -813,6 +865,7 @@ var ( // Tables holds all the tables in the schema. Tables = []*schema.Table{ AttachmentsTable, + BackupRecordTable, EventLogTable, InboundDetailsTable, InboundOrdersTable, @@ -830,6 +883,7 @@ var ( SemiFinishedsTable, StocktakeItemsTable, StocktakeOrdersTable, + SysConfigTable, UsersTable, ZonesTable, } @@ -839,6 +893,9 @@ func init() { AttachmentsTable.Annotation = &entsql.Annotation{ Table: "attachments", } + BackupRecordTable.Annotation = &entsql.Annotation{ + Table: "backup_record", + } EventLogTable.Annotation = &entsql.Annotation{ Table: "event_log", } @@ -890,6 +947,9 @@ func init() { StocktakeOrdersTable.Annotation = &entsql.Annotation{ Table: "stocktake_orders", } + SysConfigTable.Annotation = &entsql.Annotation{ + Table: "sys_config", + } UsersTable.Annotation = &entsql.Annotation{ Table: "users", } diff --git a/bj_power_wms/ent/mutation.go b/bj_power_wms/ent/mutation.go index d79597e..af0156c 100644 --- a/bj_power_wms/ent/mutation.go +++ b/bj_power_wms/ent/mutation.go @@ -4,6 +4,7 @@ package ent import ( "bj_power_wms/ent/attachment" + "bj_power_wms/ent/backuprecord" "bj_power_wms/ent/eventlog" "bj_power_wms/ent/inbounddetail" "bj_power_wms/ent/inboundorder" @@ -22,6 +23,7 @@ import ( "bj_power_wms/ent/semifinished" "bj_power_wms/ent/stocktakeitem" "bj_power_wms/ent/stocktakeorder" + "bj_power_wms/ent/sysconfig" "bj_power_wms/ent/user" "bj_power_wms/ent/zone" "context" @@ -43,6 +45,7 @@ const ( // Node types. TypeAttachment = "Attachment" + TypeBackupRecord = "BackupRecord" TypeEventLog = "EventLog" TypeInboundDetail = "InboundDetail" TypeInboundOrder = "InboundOrder" @@ -60,6 +63,7 @@ const ( TypeSemiFinished = "SemiFinished" TypeStocktakeItem = "StocktakeItem" TypeStocktakeOrder = "StocktakeOrder" + TypeSysConfig = "SysConfig" TypeUser = "User" TypeZone = "Zone" ) @@ -1492,6 +1496,953 @@ func (m *AttachmentMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Attachment edge %s", name) } +// BackupRecordMutation represents an operation that mutates the BackupRecord nodes in the graph. +type BackupRecordMutation struct { + config + op Op + typ string + id *int + executed_at *int64 + addexecuted_at *int64 + range_start *int64 + addrange_start *int64 + range_end *int64 + addrange_end *int64 + backup_path *string + total_size *int64 + addtotal_size *int64 + items_json *string + status *string + operator *string + checksum *string + scope *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BackupRecord, error) + predicates []predicate.BackupRecord +} + +var _ ent.Mutation = (*BackupRecordMutation)(nil) + +// backuprecordOption allows management of the mutation configuration using functional options. +type backuprecordOption func(*BackupRecordMutation) + +// newBackupRecordMutation creates new mutation for the BackupRecord entity. +func newBackupRecordMutation(c config, op Op, opts ...backuprecordOption) *BackupRecordMutation { + m := &BackupRecordMutation{ + config: c, + op: op, + typ: TypeBackupRecord, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBackupRecordID sets the ID field of the mutation. +func withBackupRecordID(id int) backuprecordOption { + return func(m *BackupRecordMutation) { + var ( + err error + once sync.Once + value *BackupRecord + ) + m.oldValue = func(ctx context.Context) (*BackupRecord, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BackupRecord.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBackupRecord sets the old BackupRecord of the mutation. +func withBackupRecord(node *BackupRecord) backuprecordOption { + return func(m *BackupRecordMutation) { + m.oldValue = func(context.Context) (*BackupRecord, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m BackupRecordMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m BackupRecordMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *BackupRecordMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *BackupRecordMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().BackupRecord.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetExecutedAt sets the "executed_at" field. +func (m *BackupRecordMutation) SetExecutedAt(i int64) { + m.executed_at = &i + m.addexecuted_at = nil +} + +// ExecutedAt returns the value of the "executed_at" field in the mutation. +func (m *BackupRecordMutation) ExecutedAt() (r int64, exists bool) { + v := m.executed_at + if v == nil { + return + } + return *v, true +} + +// OldExecutedAt returns the old "executed_at" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldExecutedAt(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExecutedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExecutedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExecutedAt: %w", err) + } + return oldValue.ExecutedAt, nil +} + +// AddExecutedAt adds i to the "executed_at" field. +func (m *BackupRecordMutation) AddExecutedAt(i int64) { + if m.addexecuted_at != nil { + *m.addexecuted_at += i + } else { + m.addexecuted_at = &i + } +} + +// AddedExecutedAt returns the value that was added to the "executed_at" field in this mutation. +func (m *BackupRecordMutation) AddedExecutedAt() (r int64, exists bool) { + v := m.addexecuted_at + if v == nil { + return + } + return *v, true +} + +// ResetExecutedAt resets all changes to the "executed_at" field. +func (m *BackupRecordMutation) ResetExecutedAt() { + m.executed_at = nil + m.addexecuted_at = nil +} + +// SetRangeStart sets the "range_start" field. +func (m *BackupRecordMutation) SetRangeStart(i int64) { + m.range_start = &i + m.addrange_start = nil +} + +// RangeStart returns the value of the "range_start" field in the mutation. +func (m *BackupRecordMutation) RangeStart() (r int64, exists bool) { + v := m.range_start + if v == nil { + return + } + return *v, true +} + +// OldRangeStart returns the old "range_start" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldRangeStart(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRangeStart is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRangeStart requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRangeStart: %w", err) + } + return oldValue.RangeStart, nil +} + +// AddRangeStart adds i to the "range_start" field. +func (m *BackupRecordMutation) AddRangeStart(i int64) { + if m.addrange_start != nil { + *m.addrange_start += i + } else { + m.addrange_start = &i + } +} + +// AddedRangeStart returns the value that was added to the "range_start" field in this mutation. +func (m *BackupRecordMutation) AddedRangeStart() (r int64, exists bool) { + v := m.addrange_start + if v == nil { + return + } + return *v, true +} + +// ResetRangeStart resets all changes to the "range_start" field. +func (m *BackupRecordMutation) ResetRangeStart() { + m.range_start = nil + m.addrange_start = nil +} + +// SetRangeEnd sets the "range_end" field. +func (m *BackupRecordMutation) SetRangeEnd(i int64) { + m.range_end = &i + m.addrange_end = nil +} + +// RangeEnd returns the value of the "range_end" field in the mutation. +func (m *BackupRecordMutation) RangeEnd() (r int64, exists bool) { + v := m.range_end + if v == nil { + return + } + return *v, true +} + +// OldRangeEnd returns the old "range_end" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldRangeEnd(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRangeEnd is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRangeEnd requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRangeEnd: %w", err) + } + return oldValue.RangeEnd, nil +} + +// AddRangeEnd adds i to the "range_end" field. +func (m *BackupRecordMutation) AddRangeEnd(i int64) { + if m.addrange_end != nil { + *m.addrange_end += i + } else { + m.addrange_end = &i + } +} + +// AddedRangeEnd returns the value that was added to the "range_end" field in this mutation. +func (m *BackupRecordMutation) AddedRangeEnd() (r int64, exists bool) { + v := m.addrange_end + if v == nil { + return + } + return *v, true +} + +// ResetRangeEnd resets all changes to the "range_end" field. +func (m *BackupRecordMutation) ResetRangeEnd() { + m.range_end = nil + m.addrange_end = nil +} + +// SetBackupPath sets the "backup_path" field. +func (m *BackupRecordMutation) SetBackupPath(s string) { + m.backup_path = &s +} + +// BackupPath returns the value of the "backup_path" field in the mutation. +func (m *BackupRecordMutation) BackupPath() (r string, exists bool) { + v := m.backup_path + if v == nil { + return + } + return *v, true +} + +// OldBackupPath returns the old "backup_path" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldBackupPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBackupPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBackupPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBackupPath: %w", err) + } + return oldValue.BackupPath, nil +} + +// ResetBackupPath resets all changes to the "backup_path" field. +func (m *BackupRecordMutation) ResetBackupPath() { + m.backup_path = nil +} + +// SetTotalSize sets the "total_size" field. +func (m *BackupRecordMutation) SetTotalSize(i int64) { + m.total_size = &i + m.addtotal_size = nil +} + +// TotalSize returns the value of the "total_size" field in the mutation. +func (m *BackupRecordMutation) TotalSize() (r int64, exists bool) { + v := m.total_size + if v == nil { + return + } + return *v, true +} + +// OldTotalSize returns the old "total_size" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldTotalSize(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalSize is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalSize requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalSize: %w", err) + } + return oldValue.TotalSize, nil +} + +// AddTotalSize adds i to the "total_size" field. +func (m *BackupRecordMutation) AddTotalSize(i int64) { + if m.addtotal_size != nil { + *m.addtotal_size += i + } else { + m.addtotal_size = &i + } +} + +// AddedTotalSize returns the value that was added to the "total_size" field in this mutation. +func (m *BackupRecordMutation) AddedTotalSize() (r int64, exists bool) { + v := m.addtotal_size + if v == nil { + return + } + return *v, true +} + +// ResetTotalSize resets all changes to the "total_size" field. +func (m *BackupRecordMutation) ResetTotalSize() { + m.total_size = nil + m.addtotal_size = nil +} + +// SetItemsJSON sets the "items_json" field. +func (m *BackupRecordMutation) SetItemsJSON(s string) { + m.items_json = &s +} + +// ItemsJSON returns the value of the "items_json" field in the mutation. +func (m *BackupRecordMutation) ItemsJSON() (r string, exists bool) { + v := m.items_json + if v == nil { + return + } + return *v, true +} + +// OldItemsJSON returns the old "items_json" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldItemsJSON(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldItemsJSON is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldItemsJSON requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldItemsJSON: %w", err) + } + return oldValue.ItemsJSON, nil +} + +// ResetItemsJSON resets all changes to the "items_json" field. +func (m *BackupRecordMutation) ResetItemsJSON() { + m.items_json = nil +} + +// SetStatus sets the "status" field. +func (m *BackupRecordMutation) SetStatus(s string) { + m.status = &s +} + +// Status returns the value of the "status" field in the mutation. +func (m *BackupRecordMutation) Status() (r string, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldStatus(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *BackupRecordMutation) ResetStatus() { + m.status = nil +} + +// SetOperator sets the "operator" field. +func (m *BackupRecordMutation) SetOperator(s string) { + m.operator = &s +} + +// Operator returns the value of the "operator" field in the mutation. +func (m *BackupRecordMutation) Operator() (r string, exists bool) { + v := m.operator + if v == nil { + return + } + return *v, true +} + +// OldOperator returns the old "operator" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldOperator(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOperator is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOperator requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOperator: %w", err) + } + return oldValue.Operator, nil +} + +// ResetOperator resets all changes to the "operator" field. +func (m *BackupRecordMutation) ResetOperator() { + m.operator = nil +} + +// SetChecksum sets the "checksum" field. +func (m *BackupRecordMutation) SetChecksum(s string) { + m.checksum = &s +} + +// Checksum returns the value of the "checksum" field in the mutation. +func (m *BackupRecordMutation) Checksum() (r string, exists bool) { + v := m.checksum + if v == nil { + return + } + return *v, true +} + +// OldChecksum returns the old "checksum" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldChecksum(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldChecksum is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldChecksum requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldChecksum: %w", err) + } + return oldValue.Checksum, nil +} + +// ResetChecksum resets all changes to the "checksum" field. +func (m *BackupRecordMutation) ResetChecksum() { + m.checksum = nil +} + +// SetScope sets the "scope" field. +func (m *BackupRecordMutation) SetScope(s string) { + m.scope = &s +} + +// Scope returns the value of the "scope" field in the mutation. +func (m *BackupRecordMutation) Scope() (r string, exists bool) { + v := m.scope + if v == nil { + return + } + return *v, true +} + +// OldScope returns the old "scope" field's value of the BackupRecord entity. +// If the BackupRecord object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *BackupRecordMutation) OldScope(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldScope is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldScope requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldScope: %w", err) + } + return oldValue.Scope, nil +} + +// ResetScope resets all changes to the "scope" field. +func (m *BackupRecordMutation) ResetScope() { + m.scope = nil +} + +// Where appends a list predicates to the BackupRecordMutation builder. +func (m *BackupRecordMutation) Where(ps ...predicate.BackupRecord) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BackupRecordMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BackupRecordMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BackupRecord, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BackupRecordMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BackupRecordMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BackupRecord). +func (m *BackupRecordMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *BackupRecordMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.executed_at != nil { + fields = append(fields, backuprecord.FieldExecutedAt) + } + if m.range_start != nil { + fields = append(fields, backuprecord.FieldRangeStart) + } + if m.range_end != nil { + fields = append(fields, backuprecord.FieldRangeEnd) + } + if m.backup_path != nil { + fields = append(fields, backuprecord.FieldBackupPath) + } + if m.total_size != nil { + fields = append(fields, backuprecord.FieldTotalSize) + } + if m.items_json != nil { + fields = append(fields, backuprecord.FieldItemsJSON) + } + if m.status != nil { + fields = append(fields, backuprecord.FieldStatus) + } + if m.operator != nil { + fields = append(fields, backuprecord.FieldOperator) + } + if m.checksum != nil { + fields = append(fields, backuprecord.FieldChecksum) + } + if m.scope != nil { + fields = append(fields, backuprecord.FieldScope) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *BackupRecordMutation) Field(name string) (ent.Value, bool) { + switch name { + case backuprecord.FieldExecutedAt: + return m.ExecutedAt() + case backuprecord.FieldRangeStart: + return m.RangeStart() + case backuprecord.FieldRangeEnd: + return m.RangeEnd() + case backuprecord.FieldBackupPath: + return m.BackupPath() + case backuprecord.FieldTotalSize: + return m.TotalSize() + case backuprecord.FieldItemsJSON: + return m.ItemsJSON() + case backuprecord.FieldStatus: + return m.Status() + case backuprecord.FieldOperator: + return m.Operator() + case backuprecord.FieldChecksum: + return m.Checksum() + case backuprecord.FieldScope: + return m.Scope() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *BackupRecordMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case backuprecord.FieldExecutedAt: + return m.OldExecutedAt(ctx) + case backuprecord.FieldRangeStart: + return m.OldRangeStart(ctx) + case backuprecord.FieldRangeEnd: + return m.OldRangeEnd(ctx) + case backuprecord.FieldBackupPath: + return m.OldBackupPath(ctx) + case backuprecord.FieldTotalSize: + return m.OldTotalSize(ctx) + case backuprecord.FieldItemsJSON: + return m.OldItemsJSON(ctx) + case backuprecord.FieldStatus: + return m.OldStatus(ctx) + case backuprecord.FieldOperator: + return m.OldOperator(ctx) + case backuprecord.FieldChecksum: + return m.OldChecksum(ctx) + case backuprecord.FieldScope: + return m.OldScope(ctx) + } + return nil, fmt.Errorf("unknown BackupRecord field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *BackupRecordMutation) SetField(name string, value ent.Value) error { + switch name { + case backuprecord.FieldExecutedAt: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExecutedAt(v) + return nil + case backuprecord.FieldRangeStart: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRangeStart(v) + return nil + case backuprecord.FieldRangeEnd: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRangeEnd(v) + return nil + case backuprecord.FieldBackupPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBackupPath(v) + return nil + case backuprecord.FieldTotalSize: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalSize(v) + return nil + case backuprecord.FieldItemsJSON: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetItemsJSON(v) + return nil + case backuprecord.FieldStatus: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case backuprecord.FieldOperator: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOperator(v) + return nil + case backuprecord.FieldChecksum: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetChecksum(v) + return nil + case backuprecord.FieldScope: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetScope(v) + return nil + } + return fmt.Errorf("unknown BackupRecord field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BackupRecordMutation) AddedFields() []string { + var fields []string + if m.addexecuted_at != nil { + fields = append(fields, backuprecord.FieldExecutedAt) + } + if m.addrange_start != nil { + fields = append(fields, backuprecord.FieldRangeStart) + } + if m.addrange_end != nil { + fields = append(fields, backuprecord.FieldRangeEnd) + } + if m.addtotal_size != nil { + fields = append(fields, backuprecord.FieldTotalSize) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *BackupRecordMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case backuprecord.FieldExecutedAt: + return m.AddedExecutedAt() + case backuprecord.FieldRangeStart: + return m.AddedRangeStart() + case backuprecord.FieldRangeEnd: + return m.AddedRangeEnd() + case backuprecord.FieldTotalSize: + return m.AddedTotalSize() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *BackupRecordMutation) AddField(name string, value ent.Value) error { + switch name { + case backuprecord.FieldExecutedAt: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddExecutedAt(v) + return nil + case backuprecord.FieldRangeStart: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRangeStart(v) + return nil + case backuprecord.FieldRangeEnd: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddRangeEnd(v) + return nil + case backuprecord.FieldTotalSize: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalSize(v) + return nil + } + return fmt.Errorf("unknown BackupRecord numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BackupRecordMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BackupRecordMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *BackupRecordMutation) ClearField(name string) error { + return fmt.Errorf("unknown BackupRecord nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *BackupRecordMutation) ResetField(name string) error { + switch name { + case backuprecord.FieldExecutedAt: + m.ResetExecutedAt() + return nil + case backuprecord.FieldRangeStart: + m.ResetRangeStart() + return nil + case backuprecord.FieldRangeEnd: + m.ResetRangeEnd() + return nil + case backuprecord.FieldBackupPath: + m.ResetBackupPath() + return nil + case backuprecord.FieldTotalSize: + m.ResetTotalSize() + return nil + case backuprecord.FieldItemsJSON: + m.ResetItemsJSON() + return nil + case backuprecord.FieldStatus: + m.ResetStatus() + return nil + case backuprecord.FieldOperator: + m.ResetOperator() + return nil + case backuprecord.FieldChecksum: + m.ResetChecksum() + return nil + case backuprecord.FieldScope: + m.ResetScope() + return nil + } + return fmt.Errorf("unknown BackupRecord field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BackupRecordMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BackupRecordMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BackupRecordMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BackupRecordMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BackupRecordMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BackupRecordMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *BackupRecordMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BackupRecord unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *BackupRecordMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BackupRecord edge %s", name) +} + // EventLogMutation represents an operation that mutates the EventLog nodes in the graph. type EventLogMutation struct { config @@ -23889,6 +24840,462 @@ func (m *StocktakeOrderMutation) ResetEdge(name string) error { return fmt.Errorf("unknown StocktakeOrder edge %s", name) } +// SysConfigMutation represents an operation that mutates the SysConfig nodes in the graph. +type SysConfigMutation struct { + config + op Op + typ string + id *int + key *string + value *string + remark *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*SysConfig, error) + predicates []predicate.SysConfig +} + +var _ ent.Mutation = (*SysConfigMutation)(nil) + +// sysconfigOption allows management of the mutation configuration using functional options. +type sysconfigOption func(*SysConfigMutation) + +// newSysConfigMutation creates new mutation for the SysConfig entity. +func newSysConfigMutation(c config, op Op, opts ...sysconfigOption) *SysConfigMutation { + m := &SysConfigMutation{ + config: c, + op: op, + typ: TypeSysConfig, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withSysConfigID sets the ID field of the mutation. +func withSysConfigID(id int) sysconfigOption { + return func(m *SysConfigMutation) { + var ( + err error + once sync.Once + value *SysConfig + ) + m.oldValue = func(ctx context.Context) (*SysConfig, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().SysConfig.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withSysConfig sets the old SysConfig of the mutation. +func withSysConfig(node *SysConfig) sysconfigOption { + return func(m *SysConfigMutation) { + m.oldValue = func(context.Context) (*SysConfig, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m SysConfigMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m SysConfigMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *SysConfigMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *SysConfigMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().SysConfig.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetKey sets the "key" field. +func (m *SysConfigMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *SysConfigMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the SysConfig entity. +// If the SysConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SysConfigMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *SysConfigMutation) ResetKey() { + m.key = nil +} + +// SetValue sets the "value" field. +func (m *SysConfigMutation) SetValue(s string) { + m.value = &s +} + +// Value returns the value of the "value" field in the mutation. +func (m *SysConfigMutation) Value() (r string, exists bool) { + v := m.value + if v == nil { + return + } + return *v, true +} + +// OldValue returns the old "value" field's value of the SysConfig entity. +// If the SysConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SysConfigMutation) OldValue(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// ResetValue resets all changes to the "value" field. +func (m *SysConfigMutation) ResetValue() { + m.value = nil +} + +// SetRemark sets the "remark" field. +func (m *SysConfigMutation) SetRemark(s string) { + m.remark = &s +} + +// Remark returns the value of the "remark" field in the mutation. +func (m *SysConfigMutation) Remark() (r string, exists bool) { + v := m.remark + if v == nil { + return + } + return *v, true +} + +// OldRemark returns the old "remark" field's value of the SysConfig entity. +// If the SysConfig object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *SysConfigMutation) OldRemark(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRemark is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRemark requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRemark: %w", err) + } + return oldValue.Remark, nil +} + +// ClearRemark clears the value of the "remark" field. +func (m *SysConfigMutation) ClearRemark() { + m.remark = nil + m.clearedFields[sysconfig.FieldRemark] = struct{}{} +} + +// RemarkCleared returns if the "remark" field was cleared in this mutation. +func (m *SysConfigMutation) RemarkCleared() bool { + _, ok := m.clearedFields[sysconfig.FieldRemark] + return ok +} + +// ResetRemark resets all changes to the "remark" field. +func (m *SysConfigMutation) ResetRemark() { + m.remark = nil + delete(m.clearedFields, sysconfig.FieldRemark) +} + +// Where appends a list predicates to the SysConfigMutation builder. +func (m *SysConfigMutation) Where(ps ...predicate.SysConfig) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the SysConfigMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *SysConfigMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.SysConfig, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *SysConfigMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *SysConfigMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (SysConfig). +func (m *SysConfigMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *SysConfigMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.key != nil { + fields = append(fields, sysconfig.FieldKey) + } + if m.value != nil { + fields = append(fields, sysconfig.FieldValue) + } + if m.remark != nil { + fields = append(fields, sysconfig.FieldRemark) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *SysConfigMutation) Field(name string) (ent.Value, bool) { + switch name { + case sysconfig.FieldKey: + return m.Key() + case sysconfig.FieldValue: + return m.Value() + case sysconfig.FieldRemark: + return m.Remark() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *SysConfigMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case sysconfig.FieldKey: + return m.OldKey(ctx) + case sysconfig.FieldValue: + return m.OldValue(ctx) + case sysconfig.FieldRemark: + return m.OldRemark(ctx) + } + return nil, fmt.Errorf("unknown SysConfig field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SysConfigMutation) SetField(name string, value ent.Value) error { + switch name { + case sysconfig.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case sysconfig.FieldValue: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + case sysconfig.FieldRemark: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRemark(v) + return nil + } + return fmt.Errorf("unknown SysConfig field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *SysConfigMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *SysConfigMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *SysConfigMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown SysConfig numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *SysConfigMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(sysconfig.FieldRemark) { + fields = append(fields, sysconfig.FieldRemark) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *SysConfigMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *SysConfigMutation) ClearField(name string) error { + switch name { + case sysconfig.FieldRemark: + m.ClearRemark() + return nil + } + return fmt.Errorf("unknown SysConfig nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *SysConfigMutation) ResetField(name string) error { + switch name { + case sysconfig.FieldKey: + m.ResetKey() + return nil + case sysconfig.FieldValue: + m.ResetValue() + return nil + case sysconfig.FieldRemark: + m.ResetRemark() + return nil + } + return fmt.Errorf("unknown SysConfig field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *SysConfigMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *SysConfigMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *SysConfigMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *SysConfigMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *SysConfigMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *SysConfigMutation) EdgeCleared(name string) bool { + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *SysConfigMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown SysConfig unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *SysConfigMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown SysConfig edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/bj_power_wms/ent/predicate/predicate.go b/bj_power_wms/ent/predicate/predicate.go index 9191e4d..51ae701 100644 --- a/bj_power_wms/ent/predicate/predicate.go +++ b/bj_power_wms/ent/predicate/predicate.go @@ -9,6 +9,9 @@ import ( // Attachment is the predicate function for attachment builders. type Attachment func(*sql.Selector) +// BackupRecord is the predicate function for backuprecord builders. +type BackupRecord func(*sql.Selector) + // EventLog is the predicate function for eventlog builders. type EventLog func(*sql.Selector) @@ -60,6 +63,9 @@ type StocktakeItem func(*sql.Selector) // StocktakeOrder is the predicate function for stocktakeorder builders. type StocktakeOrder func(*sql.Selector) +// SysConfig is the predicate function for sysconfig builders. +type SysConfig func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/bj_power_wms/ent/runtime.go b/bj_power_wms/ent/runtime.go index c409453..0fa059f 100644 --- a/bj_power_wms/ent/runtime.go +++ b/bj_power_wms/ent/runtime.go @@ -4,6 +4,7 @@ package ent import ( "bj_power_wms/ent/attachment" + "bj_power_wms/ent/backuprecord" "bj_power_wms/ent/eventlog" "bj_power_wms/ent/inbounddetail" "bj_power_wms/ent/inboundorder" @@ -21,6 +22,7 @@ import ( "bj_power_wms/ent/semifinished" "bj_power_wms/ent/stocktakeitem" "bj_power_wms/ent/stocktakeorder" + "bj_power_wms/ent/sysconfig" "bj_power_wms/ent/user" "bj_power_wms/ent/zone" "bj_power_wms/schema" @@ -48,6 +50,40 @@ func init() { attachmentDescCreatedAt := attachmentFields[15].Descriptor() // attachment.DefaultCreatedAt holds the default value on creation for the created_at field. attachment.DefaultCreatedAt = attachmentDescCreatedAt.Default.(func() int64) + backuprecordFields := schema.BackupRecord{}.Fields() + _ = backuprecordFields + // backuprecordDescExecutedAt is the schema descriptor for executed_at field. + backuprecordDescExecutedAt := backuprecordFields[0].Descriptor() + // backuprecord.DefaultExecutedAt holds the default value on creation for the executed_at field. + backuprecord.DefaultExecutedAt = backuprecordDescExecutedAt.Default.(func() int64) + // backuprecordDescTotalSize is the schema descriptor for total_size field. + backuprecordDescTotalSize := backuprecordFields[4].Descriptor() + // backuprecord.DefaultTotalSize holds the default value on creation for the total_size field. + backuprecord.DefaultTotalSize = backuprecordDescTotalSize.Default.(int64) + // backuprecordDescStatus is the schema descriptor for status field. + backuprecordDescStatus := backuprecordFields[6].Descriptor() + // backuprecord.DefaultStatus holds the default value on creation for the status field. + backuprecord.DefaultStatus = backuprecordDescStatus.Default.(string) + // backuprecord.StatusValidator is a validator for the "status" field. It is called by the builders before save. + backuprecord.StatusValidator = backuprecordDescStatus.Validators[0].(func(string) error) + // backuprecordDescOperator is the schema descriptor for operator field. + backuprecordDescOperator := backuprecordFields[7].Descriptor() + // backuprecord.DefaultOperator holds the default value on creation for the operator field. + backuprecord.DefaultOperator = backuprecordDescOperator.Default.(string) + // backuprecord.OperatorValidator is a validator for the "operator" field. It is called by the builders before save. + backuprecord.OperatorValidator = backuprecordDescOperator.Validators[0].(func(string) error) + // backuprecordDescChecksum is the schema descriptor for checksum field. + backuprecordDescChecksum := backuprecordFields[8].Descriptor() + // backuprecord.DefaultChecksum holds the default value on creation for the checksum field. + backuprecord.DefaultChecksum = backuprecordDescChecksum.Default.(string) + // backuprecord.ChecksumValidator is a validator for the "checksum" field. It is called by the builders before save. + backuprecord.ChecksumValidator = backuprecordDescChecksum.Validators[0].(func(string) error) + // backuprecordDescScope is the schema descriptor for scope field. + backuprecordDescScope := backuprecordFields[9].Descriptor() + // backuprecord.DefaultScope holds the default value on creation for the scope field. + backuprecord.DefaultScope = backuprecordDescScope.Default.(string) + // backuprecord.ScopeValidator is a validator for the "scope" field. It is called by the builders before save. + backuprecord.ScopeValidator = backuprecordDescScope.Validators[0].(func(string) error) eventlogFields := schema.EventLog{}.Fields() _ = eventlogFields // eventlogDescEventType is the schema descriptor for event_type field. @@ -548,6 +584,20 @@ func init() { stocktakeorderDescCreatedAt := stocktakeorderFields[11].Descriptor() // stocktakeorder.DefaultCreatedAt holds the default value on creation for the created_at field. stocktakeorder.DefaultCreatedAt = stocktakeorderDescCreatedAt.Default.(func() int64) + sysconfigFields := schema.SysConfig{}.Fields() + _ = sysconfigFields + // sysconfigDescKey is the schema descriptor for key field. + sysconfigDescKey := sysconfigFields[0].Descriptor() + // sysconfig.KeyValidator is a validator for the "key" field. It is called by the builders before save. + sysconfig.KeyValidator = sysconfigDescKey.Validators[0].(func(string) error) + // sysconfigDescValue is the schema descriptor for value field. + sysconfigDescValue := sysconfigFields[1].Descriptor() + // sysconfig.ValueValidator is a validator for the "value" field. It is called by the builders before save. + sysconfig.ValueValidator = sysconfigDescValue.Validators[0].(func(string) error) + // sysconfigDescRemark is the schema descriptor for remark field. + sysconfigDescRemark := sysconfigFields[2].Descriptor() + // sysconfig.RemarkValidator is a validator for the "remark" field. It is called by the builders before save. + sysconfig.RemarkValidator = sysconfigDescRemark.Validators[0].(func(string) error) userFields := schema.User{}.Fields() _ = userFields // userDescRole is the schema descriptor for role field. diff --git a/bj_power_wms/ent/sysconfig.go b/bj_power_wms/ent/sysconfig.go new file mode 100644 index 0000000..d0f03dd --- /dev/null +++ b/bj_power_wms/ent/sysconfig.go @@ -0,0 +1,125 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/sysconfig" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// SysConfig 系统基础设置(key/value)。 +type SysConfig struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // 配置键,如 wms.base_url + Key string `json:"key,omitempty"` + // 配置值 + Value string `json:"value,omitempty"` + // 说明 + Remark string `json:"remark,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*SysConfig) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case sysconfig.FieldID: + values[i] = new(sql.NullInt64) + case sysconfig.FieldKey, sysconfig.FieldValue, sysconfig.FieldRemark: + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the SysConfig fields. +func (_m *SysConfig) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case sysconfig.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case sysconfig.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case sysconfig.FieldValue: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + _m.Value = value.String + } + case sysconfig.FieldRemark: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field remark", values[i]) + } else if value.Valid { + _m.Remark = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// GetValue returns the ent.Value that was dynamically selected and assigned to the SysConfig. +// This includes values selected through modifiers, order, etc. +func (_m *SysConfig) GetValue(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// Update returns a builder for updating this SysConfig. +// Note that you need to call SysConfig.Unwrap() before calling this method if this SysConfig +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *SysConfig) Update() *SysConfigUpdateOne { + return NewSysConfigClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the SysConfig entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *SysConfig) Unwrap() *SysConfig { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: SysConfig is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *SysConfig) String() string { + var builder strings.Builder + builder.WriteString("SysConfig(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + builder.WriteString("value=") + builder.WriteString(_m.Value) + builder.WriteString(", ") + builder.WriteString("remark=") + builder.WriteString(_m.Remark) + builder.WriteByte(')') + return builder.String() +} + +// SysConfigs is a parsable slice of SysConfig. +type SysConfigs []*SysConfig diff --git a/bj_power_wms/ent/sysconfig/sysconfig.go b/bj_power_wms/ent/sysconfig/sysconfig.go new file mode 100644 index 0000000..da028ab --- /dev/null +++ b/bj_power_wms/ent/sysconfig/sysconfig.go @@ -0,0 +1,72 @@ +// Code generated by ent, DO NOT EDIT. + +package sysconfig + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the sysconfig type in the database. + Label = "sys_config" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldValue holds the string denoting the value field in the database. + FieldValue = "value" + // FieldRemark holds the string denoting the remark field in the database. + FieldRemark = "remark" + // Table holds the table name of the sysconfig in the database. + Table = "sys_config" +) + +// Columns holds all SQL columns for sysconfig fields. +var Columns = []string{ + FieldID, + FieldKey, + FieldValue, + FieldRemark, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // KeyValidator is a validator for the "key" field. It is called by the builders before save. + KeyValidator func(string) error + // ValueValidator is a validator for the "value" field. It is called by the builders before save. + ValueValidator func(string) error + // RemarkValidator is a validator for the "remark" field. It is called by the builders before save. + RemarkValidator func(string) error +) + +// OrderOption defines the ordering options for the SysConfig queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByValue orders the results by the value field. +func ByValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValue, opts...).ToFunc() +} + +// ByRemark orders the results by the remark field. +func ByRemark(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRemark, opts...).ToFunc() +} diff --git a/bj_power_wms/ent/sysconfig/where.go b/bj_power_wms/ent/sysconfig/where.go new file mode 100644 index 0000000..48eb405 --- /dev/null +++ b/bj_power_wms/ent/sysconfig/where.go @@ -0,0 +1,289 @@ +// Code generated by ent, DO NOT EDIT. + +package sysconfig + +import ( + "bj_power_wms/ent/predicate" + + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldID, id)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldKey, v)) +} + +// Value applies equality check predicate on the "value" field. It's identical to ValueEQ. +func Value(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldValue, v)) +} + +// Remark applies equality check predicate on the "remark" field. It's identical to RemarkEQ. +func Remark(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldRemark, v)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldKey, v)) +} + +// ValueEQ applies the EQ predicate on the "value" field. +func ValueEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldValue, v)) +} + +// ValueNEQ applies the NEQ predicate on the "value" field. +func ValueNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldValue, v)) +} + +// ValueIn applies the In predicate on the "value" field. +func ValueIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldValue, vs...)) +} + +// ValueNotIn applies the NotIn predicate on the "value" field. +func ValueNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldValue, vs...)) +} + +// ValueGT applies the GT predicate on the "value" field. +func ValueGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldValue, v)) +} + +// ValueGTE applies the GTE predicate on the "value" field. +func ValueGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldValue, v)) +} + +// ValueLT applies the LT predicate on the "value" field. +func ValueLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldValue, v)) +} + +// ValueLTE applies the LTE predicate on the "value" field. +func ValueLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldValue, v)) +} + +// ValueContains applies the Contains predicate on the "value" field. +func ValueContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldValue, v)) +} + +// ValueHasPrefix applies the HasPrefix predicate on the "value" field. +func ValueHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldValue, v)) +} + +// ValueHasSuffix applies the HasSuffix predicate on the "value" field. +func ValueHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldValue, v)) +} + +// ValueEqualFold applies the EqualFold predicate on the "value" field. +func ValueEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldValue, v)) +} + +// ValueContainsFold applies the ContainsFold predicate on the "value" field. +func ValueContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldValue, v)) +} + +// RemarkEQ applies the EQ predicate on the "remark" field. +func RemarkEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEQ(FieldRemark, v)) +} + +// RemarkNEQ applies the NEQ predicate on the "remark" field. +func RemarkNEQ(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNEQ(FieldRemark, v)) +} + +// RemarkIn applies the In predicate on the "remark" field. +func RemarkIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldIn(FieldRemark, vs...)) +} + +// RemarkNotIn applies the NotIn predicate on the "remark" field. +func RemarkNotIn(vs ...string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotIn(FieldRemark, vs...)) +} + +// RemarkGT applies the GT predicate on the "remark" field. +func RemarkGT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGT(FieldRemark, v)) +} + +// RemarkGTE applies the GTE predicate on the "remark" field. +func RemarkGTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldGTE(FieldRemark, v)) +} + +// RemarkLT applies the LT predicate on the "remark" field. +func RemarkLT(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLT(FieldRemark, v)) +} + +// RemarkLTE applies the LTE predicate on the "remark" field. +func RemarkLTE(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldLTE(FieldRemark, v)) +} + +// RemarkContains applies the Contains predicate on the "remark" field. +func RemarkContains(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContains(FieldRemark, v)) +} + +// RemarkHasPrefix applies the HasPrefix predicate on the "remark" field. +func RemarkHasPrefix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasPrefix(FieldRemark, v)) +} + +// RemarkHasSuffix applies the HasSuffix predicate on the "remark" field. +func RemarkHasSuffix(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldHasSuffix(FieldRemark, v)) +} + +// RemarkIsNil applies the IsNil predicate on the "remark" field. +func RemarkIsNil() predicate.SysConfig { + return predicate.SysConfig(sql.FieldIsNull(FieldRemark)) +} + +// RemarkNotNil applies the NotNil predicate on the "remark" field. +func RemarkNotNil() predicate.SysConfig { + return predicate.SysConfig(sql.FieldNotNull(FieldRemark)) +} + +// RemarkEqualFold applies the EqualFold predicate on the "remark" field. +func RemarkEqualFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldEqualFold(FieldRemark, v)) +} + +// RemarkContainsFold applies the ContainsFold predicate on the "remark" field. +func RemarkContainsFold(v string) predicate.SysConfig { + return predicate.SysConfig(sql.FieldContainsFold(FieldRemark, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.SysConfig) predicate.SysConfig { + return predicate.SysConfig(sql.NotPredicates(p)) +} diff --git a/bj_power_wms/ent/sysconfig_create.go b/bj_power_wms/ent/sysconfig_create.go new file mode 100644 index 0000000..ddb6230 --- /dev/null +++ b/bj_power_wms/ent/sysconfig_create.go @@ -0,0 +1,600 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/sysconfig" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigCreate is the builder for creating a SysConfig entity. +type SysConfigCreate struct { + config + mutation *SysConfigMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetKey sets the "key" field. +func (_c *SysConfigCreate) SetKey(v string) *SysConfigCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetValue sets the "value" field. +func (_c *SysConfigCreate) SetValue(v string) *SysConfigCreate { + _c.mutation.SetValue(v) + return _c +} + +// SetRemark sets the "remark" field. +func (_c *SysConfigCreate) SetRemark(v string) *SysConfigCreate { + _c.mutation.SetRemark(v) + return _c +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_c *SysConfigCreate) SetNillableRemark(v *string) *SysConfigCreate { + if v != nil { + _c.SetRemark(*v) + } + return _c +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_c *SysConfigCreate) Mutation() *SysConfigMutation { + return _c.mutation +} + +// Save creates the SysConfig in the database. +func (_c *SysConfigCreate) Save(ctx context.Context) (*SysConfig, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *SysConfigCreate) SaveX(ctx context.Context) *SysConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SysConfigCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SysConfigCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *SysConfigCreate) check() error { + if _, ok := _c.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "SysConfig.key"`)} + } + if v, ok := _c.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if _, ok := _c.mutation.Value(); !ok { + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "SysConfig.value"`)} + } + if v, ok := _c.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _c.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +func (_c *SysConfigCreate) sqlSave(ctx context.Context) (*SysConfig, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *SysConfigCreate) createSpec() (*SysConfig, *sqlgraph.CreateSpec) { + var ( + _node = &SysConfig{config: _c.config} + _spec = sqlgraph.NewCreateSpec(sysconfig.Table, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + _node.Value = value + } + if value, ok := _c.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + _node.Remark = value + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SysConfig.Create(). +// SetKey(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.SysConfigUpsert) { +// SetKey(v+v). +// }). +// Exec(ctx) +func (_c *SysConfigCreate) OnConflict(opts ...sql.ConflictOption) *SysConfigUpsertOne { + _c.conflict = opts + return &SysConfigUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SysConfigCreate) OnConflictColumns(columns ...string) *SysConfigUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SysConfigUpsertOne{ + create: _c, + } +} + +type ( + // SysConfigUpsertOne is the builder for "upsert"-ing + // one SysConfig node. + SysConfigUpsertOne struct { + create *SysConfigCreate + } + + // SysConfigUpsert is the "OnConflict" setter. + SysConfigUpsert struct { + *sql.UpdateSet + } +) + +// SetKey sets the "key" field. +func (u *SysConfigUpsert) SetKey(v string) *SysConfigUpsert { + u.Set(sysconfig.FieldKey, v) + return u +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *SysConfigUpsert) UpdateKey() *SysConfigUpsert { + u.SetExcluded(sysconfig.FieldKey) + return u +} + +// SetValue sets the "value" field. +func (u *SysConfigUpsert) SetValue(v string) *SysConfigUpsert { + u.Set(sysconfig.FieldValue, v) + return u +} + +// UpdateValue sets the "value" field to the value that was provided on create. +func (u *SysConfigUpsert) UpdateValue() *SysConfigUpsert { + u.SetExcluded(sysconfig.FieldValue) + return u +} + +// SetRemark sets the "remark" field. +func (u *SysConfigUpsert) SetRemark(v string) *SysConfigUpsert { + u.Set(sysconfig.FieldRemark, v) + return u +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *SysConfigUpsert) UpdateRemark() *SysConfigUpsert { + u.SetExcluded(sysconfig.FieldRemark) + return u +} + +// ClearRemark clears the value of the "remark" field. +func (u *SysConfigUpsert) ClearRemark() *SysConfigUpsert { + u.SetNull(sysconfig.FieldRemark) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SysConfigUpsertOne) UpdateNewValues() *SysConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SysConfigUpsertOne) Ignore() *SysConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *SysConfigUpsertOne) DoNothing() *SysConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SysConfigCreate.OnConflict +// documentation for more info. +func (u *SysConfigUpsertOne) Update(set func(*SysConfigUpsert)) *SysConfigUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SysConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetKey sets the "key" field. +func (u *SysConfigUpsertOne) SetKey(v string) *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.SetKey(v) + }) +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *SysConfigUpsertOne) UpdateKey() *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateKey() + }) +} + +// SetValue sets the "value" field. +func (u *SysConfigUpsertOne) SetValue(v string) *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.SetValue(v) + }) +} + +// UpdateValue sets the "value" field to the value that was provided on create. +func (u *SysConfigUpsertOne) UpdateValue() *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateValue() + }) +} + +// SetRemark sets the "remark" field. +func (u *SysConfigUpsertOne) SetRemark(v string) *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.SetRemark(v) + }) +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *SysConfigUpsertOne) UpdateRemark() *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateRemark() + }) +} + +// ClearRemark clears the value of the "remark" field. +func (u *SysConfigUpsertOne) ClearRemark() *SysConfigUpsertOne { + return u.Update(func(s *SysConfigUpsert) { + s.ClearRemark() + }) +} + +// Exec executes the query. +func (u *SysConfigUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SysConfigCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SysConfigUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *SysConfigUpsertOne) ID(ctx context.Context) (id int, err error) { + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *SysConfigUpsertOne) IDX(ctx context.Context) int { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// SysConfigCreateBulk is the builder for creating many SysConfig entities in bulk. +type SysConfigCreateBulk struct { + config + err error + builders []*SysConfigCreate + conflict []sql.ConflictOption +} + +// Save creates the SysConfig entities in the database. +func (_c *SysConfigCreateBulk) Save(ctx context.Context) ([]*SysConfig, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*SysConfig, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*SysConfigMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *SysConfigCreateBulk) SaveX(ctx context.Context) []*SysConfig { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *SysConfigCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *SysConfigCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.SysConfig.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.SysConfigUpsert) { +// SetKey(v+v). +// }). +// Exec(ctx) +func (_c *SysConfigCreateBulk) OnConflict(opts ...sql.ConflictOption) *SysConfigUpsertBulk { + _c.conflict = opts + return &SysConfigUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *SysConfigCreateBulk) OnConflictColumns(columns ...string) *SysConfigUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &SysConfigUpsertBulk{ + create: _c, + } +} + +// SysConfigUpsertBulk is the builder for "upsert"-ing +// a bulk of SysConfig nodes. +type SysConfigUpsertBulk struct { + create *SysConfigCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *SysConfigUpsertBulk) UpdateNewValues() *SysConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.SysConfig.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *SysConfigUpsertBulk) Ignore() *SysConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *SysConfigUpsertBulk) DoNothing() *SysConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the SysConfigCreateBulk.OnConflict +// documentation for more info. +func (u *SysConfigUpsertBulk) Update(set func(*SysConfigUpsert)) *SysConfigUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&SysConfigUpsert{UpdateSet: update}) + })) + return u +} + +// SetKey sets the "key" field. +func (u *SysConfigUpsertBulk) SetKey(v string) *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.SetKey(v) + }) +} + +// UpdateKey sets the "key" field to the value that was provided on create. +func (u *SysConfigUpsertBulk) UpdateKey() *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateKey() + }) +} + +// SetValue sets the "value" field. +func (u *SysConfigUpsertBulk) SetValue(v string) *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.SetValue(v) + }) +} + +// UpdateValue sets the "value" field to the value that was provided on create. +func (u *SysConfigUpsertBulk) UpdateValue() *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateValue() + }) +} + +// SetRemark sets the "remark" field. +func (u *SysConfigUpsertBulk) SetRemark(v string) *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.SetRemark(v) + }) +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *SysConfigUpsertBulk) UpdateRemark() *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.UpdateRemark() + }) +} + +// ClearRemark clears the value of the "remark" field. +func (u *SysConfigUpsertBulk) ClearRemark() *SysConfigUpsertBulk { + return u.Update(func(s *SysConfigUpsert) { + s.ClearRemark() + }) +} + +// Exec executes the query. +func (u *SysConfigUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the SysConfigCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for SysConfigCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *SysConfigUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_wms/ent/sysconfig_delete.go b/bj_power_wms/ent/sysconfig_delete.go new file mode 100644 index 0000000..ffc473a --- /dev/null +++ b/bj_power_wms/ent/sysconfig_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/predicate" + "bj_power_wms/ent/sysconfig" + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigDelete is the builder for deleting a SysConfig entity. +type SysConfigDelete struct { + config + hooks []Hook + mutation *SysConfigMutation +} + +// Where appends a list predicates to the SysConfigDelete builder. +func (_d *SysConfigDelete) Where(ps ...predicate.SysConfig) *SysConfigDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *SysConfigDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SysConfigDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *SysConfigDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(sysconfig.Table, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// SysConfigDeleteOne is the builder for deleting a single SysConfig entity. +type SysConfigDeleteOne struct { + _d *SysConfigDelete +} + +// Where appends a list predicates to the SysConfigDelete builder. +func (_d *SysConfigDeleteOne) Where(ps ...predicate.SysConfig) *SysConfigDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *SysConfigDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{sysconfig.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *SysConfigDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/bj_power_wms/ent/sysconfig_query.go b/bj_power_wms/ent/sysconfig_query.go new file mode 100644 index 0000000..bcfbcf2 --- /dev/null +++ b/bj_power_wms/ent/sysconfig_query.go @@ -0,0 +1,527 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/predicate" + "bj_power_wms/ent/sysconfig" + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigQuery is the builder for querying SysConfig entities. +type SysConfigQuery struct { + config + ctx *QueryContext + order []sysconfig.OrderOption + inters []Interceptor + predicates []predicate.SysConfig + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the SysConfigQuery builder. +func (_q *SysConfigQuery) Where(ps ...predicate.SysConfig) *SysConfigQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *SysConfigQuery) Limit(limit int) *SysConfigQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *SysConfigQuery) Offset(offset int) *SysConfigQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *SysConfigQuery) Unique(unique bool) *SysConfigQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *SysConfigQuery) Order(o ...sysconfig.OrderOption) *SysConfigQuery { + _q.order = append(_q.order, o...) + return _q +} + +// First returns the first SysConfig entity from the query. +// Returns a *NotFoundError when no SysConfig was found. +func (_q *SysConfigQuery) First(ctx context.Context) (*SysConfig, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{sysconfig.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *SysConfigQuery) FirstX(ctx context.Context) *SysConfig { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first SysConfig ID from the query. +// Returns a *NotFoundError when no SysConfig ID was found. +func (_q *SysConfigQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{sysconfig.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *SysConfigQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single SysConfig entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one SysConfig entity is found. +// Returns a *NotFoundError when no SysConfig entities are found. +func (_q *SysConfigQuery) Only(ctx context.Context) (*SysConfig, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{sysconfig.Label} + default: + return nil, &NotSingularError{sysconfig.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *SysConfigQuery) OnlyX(ctx context.Context) *SysConfig { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only SysConfig ID in the query. +// Returns a *NotSingularError when more than one SysConfig ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *SysConfigQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{sysconfig.Label} + default: + err = &NotSingularError{sysconfig.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *SysConfigQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of SysConfigs. +func (_q *SysConfigQuery) All(ctx context.Context) ([]*SysConfig, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*SysConfig, *SysConfigQuery]() + return withInterceptors[[]*SysConfig](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *SysConfigQuery) AllX(ctx context.Context) []*SysConfig { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of SysConfig IDs. +func (_q *SysConfigQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(sysconfig.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *SysConfigQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *SysConfigQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*SysConfigQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *SysConfigQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *SysConfigQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *SysConfigQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the SysConfigQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *SysConfigQuery) Clone() *SysConfigQuery { + if _q == nil { + return nil + } + return &SysConfigQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]sysconfig.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.SysConfig{}, _q.predicates...), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Key string `json:"key,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.SysConfig.Query(). +// GroupBy(sysconfig.FieldKey). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *SysConfigQuery) GroupBy(field string, fields ...string) *SysConfigGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &SysConfigGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = sysconfig.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// Key string `json:"key,omitempty"` +// } +// +// client.SysConfig.Query(). +// Select(sysconfig.FieldKey). +// Scan(ctx, &v) +func (_q *SysConfigQuery) Select(fields ...string) *SysConfigSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &SysConfigSelect{SysConfigQuery: _q} + sbuild.label = sysconfig.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a SysConfigSelect configured with the given aggregations. +func (_q *SysConfigQuery) Aggregate(fns ...AggregateFunc) *SysConfigSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *SysConfigQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !sysconfig.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *SysConfigQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*SysConfig, error) { + var ( + nodes = []*SysConfig{} + _spec = _q.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*SysConfig).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &SysConfig{config: _q.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (_q *SysConfigQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *SysConfigQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, sysconfig.FieldID) + for i := range fields { + if fields[i] != sysconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *SysConfigQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(sysconfig.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = sysconfig.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// SysConfigGroupBy is the group-by builder for SysConfig entities. +type SysConfigGroupBy struct { + selector + build *SysConfigQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *SysConfigGroupBy) Aggregate(fns ...AggregateFunc) *SysConfigGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *SysConfigGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SysConfigQuery, *SysConfigGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *SysConfigGroupBy) sqlScan(ctx context.Context, root *SysConfigQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// SysConfigSelect is the builder for selecting fields of SysConfig entities. +type SysConfigSelect struct { + *SysConfigQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *SysConfigSelect) Aggregate(fns ...AggregateFunc) *SysConfigSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *SysConfigSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*SysConfigQuery, *SysConfigSelect](ctx, _s.SysConfigQuery, _s, _s.inters, v) +} + +func (_s *SysConfigSelect) sqlScan(ctx context.Context, root *SysConfigQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/bj_power_wms/ent/sysconfig_update.go b/bj_power_wms/ent/sysconfig_update.go new file mode 100644 index 0000000..614101d --- /dev/null +++ b/bj_power_wms/ent/sysconfig_update.go @@ -0,0 +1,341 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "bj_power_wms/ent/predicate" + "bj_power_wms/ent/sysconfig" + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// SysConfigUpdate is the builder for updating SysConfig entities. +type SysConfigUpdate struct { + config + hooks []Hook + mutation *SysConfigMutation +} + +// Where appends a list predicates to the SysConfigUpdate builder. +func (_u *SysConfigUpdate) Where(ps ...predicate.SysConfig) *SysConfigUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetKey sets the "key" field. +func (_u *SysConfigUpdate) SetKey(v string) *SysConfigUpdate { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableKey(v *string) *SysConfigUpdate { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// SetValue sets the "value" field. +func (_u *SysConfigUpdate) SetValue(v string) *SysConfigUpdate { + _u.mutation.SetValue(v) + return _u +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableValue(v *string) *SysConfigUpdate { + if v != nil { + _u.SetValue(*v) + } + return _u +} + +// SetRemark sets the "remark" field. +func (_u *SysConfigUpdate) SetRemark(v string) *SysConfigUpdate { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *SysConfigUpdate) SetNillableRemark(v *string) *SysConfigUpdate { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *SysConfigUpdate) ClearRemark() *SysConfigUpdate { + _u.mutation.ClearRemark() + return _u +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_u *SysConfigUpdate) Mutation() *SysConfigMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *SysConfigUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SysConfigUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *SysConfigUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SysConfigUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SysConfigUpdate) check() error { + if v, ok := _u.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if v, ok := _u.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _u.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +func (_u *SysConfigUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + } + if value, ok := _u.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(sysconfig.FieldRemark, field.TypeString) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sysconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// SysConfigUpdateOne is the builder for updating a single SysConfig entity. +type SysConfigUpdateOne struct { + config + fields []string + hooks []Hook + mutation *SysConfigMutation +} + +// SetKey sets the "key" field. +func (_u *SysConfigUpdateOne) SetKey(v string) *SysConfigUpdateOne { + _u.mutation.SetKey(v) + return _u +} + +// SetNillableKey sets the "key" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableKey(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetKey(*v) + } + return _u +} + +// SetValue sets the "value" field. +func (_u *SysConfigUpdateOne) SetValue(v string) *SysConfigUpdateOne { + _u.mutation.SetValue(v) + return _u +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableValue(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetValue(*v) + } + return _u +} + +// SetRemark sets the "remark" field. +func (_u *SysConfigUpdateOne) SetRemark(v string) *SysConfigUpdateOne { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *SysConfigUpdateOne) SetNillableRemark(v *string) *SysConfigUpdateOne { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *SysConfigUpdateOne) ClearRemark() *SysConfigUpdateOne { + _u.mutation.ClearRemark() + return _u +} + +// Mutation returns the SysConfigMutation object of the builder. +func (_u *SysConfigUpdateOne) Mutation() *SysConfigMutation { + return _u.mutation +} + +// Where appends a list predicates to the SysConfigUpdate builder. +func (_u *SysConfigUpdateOne) Where(ps ...predicate.SysConfig) *SysConfigUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *SysConfigUpdateOne) Select(field string, fields ...string) *SysConfigUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated SysConfig entity. +func (_u *SysConfigUpdateOne) Save(ctx context.Context) (*SysConfig, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *SysConfigUpdateOne) SaveX(ctx context.Context) *SysConfig { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *SysConfigUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *SysConfigUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *SysConfigUpdateOne) check() error { + if v, ok := _u.mutation.Key(); ok { + if err := sysconfig.KeyValidator(v); err != nil { + return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "SysConfig.key": %w`, err)} + } + } + if v, ok := _u.mutation.Value(); ok { + if err := sysconfig.ValueValidator(v); err != nil { + return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "SysConfig.value": %w`, err)} + } + } + if v, ok := _u.mutation.Remark(); ok { + if err := sysconfig.RemarkValidator(v); err != nil { + return &ValidationError{Name: "remark", err: fmt.Errorf(`ent: validator failed for field "SysConfig.remark": %w`, err)} + } + } + return nil +} + +func (_u *SysConfigUpdateOne) sqlSave(ctx context.Context) (_node *SysConfig, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(sysconfig.Table, sysconfig.Columns, sqlgraph.NewFieldSpec(sysconfig.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "SysConfig.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, sysconfig.FieldID) + for _, f := range fields { + if !sysconfig.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != sysconfig.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.Key(); ok { + _spec.SetField(sysconfig.FieldKey, field.TypeString, value) + } + if value, ok := _u.mutation.Value(); ok { + _spec.SetField(sysconfig.FieldValue, field.TypeString, value) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(sysconfig.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(sysconfig.FieldRemark, field.TypeString) + } + _node = &SysConfig{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{sysconfig.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/bj_power_wms/ent/tx.go b/bj_power_wms/ent/tx.go index d13ebae..1dd6bf6 100644 --- a/bj_power_wms/ent/tx.go +++ b/bj_power_wms/ent/tx.go @@ -14,6 +14,8 @@ type Tx struct { config // Attachment is the client for interacting with the Attachment builders. Attachment *AttachmentClient + // BackupRecord is the client for interacting with the BackupRecord builders. + BackupRecord *BackupRecordClient // EventLog is the client for interacting with the EventLog builders. EventLog *EventLogClient // InboundDetail is the client for interacting with the InboundDetail builders. @@ -48,6 +50,8 @@ type Tx struct { StocktakeItem *StocktakeItemClient // StocktakeOrder is the client for interacting with the StocktakeOrder builders. StocktakeOrder *StocktakeOrderClient + // SysConfig is the client for interacting with the SysConfig builders. + SysConfig *SysConfigClient // User is the client for interacting with the User builders. User *UserClient // Zone is the client for interacting with the Zone builders. @@ -184,6 +188,7 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.Attachment = NewAttachmentClient(tx.config) + tx.BackupRecord = NewBackupRecordClient(tx.config) tx.EventLog = NewEventLogClient(tx.config) tx.InboundDetail = NewInboundDetailClient(tx.config) tx.InboundOrder = NewInboundOrderClient(tx.config) @@ -201,6 +206,7 @@ func (tx *Tx) init() { tx.SemiFinished = NewSemiFinishedClient(tx.config) tx.StocktakeItem = NewStocktakeItemClient(tx.config) tx.StocktakeOrder = NewStocktakeOrderClient(tx.config) + tx.SysConfig = NewSysConfigClient(tx.config) tx.User = NewUserClient(tx.config) tx.Zone = NewZoneClient(tx.config) } diff --git a/bj_power_wms/etc/aitest_wms.yaml b/bj_power_wms/etc/aitest_wms.yaml index d5a5181..d72ba5a 100644 --- a/bj_power_wms/etc/aitest_wms.yaml +++ b/bj_power_wms/etc/aitest_wms.yaml @@ -66,4 +66,3 @@ Attachment: DiskWarnPercent: 20 # 剩余空间 <20% 告警 DiskCriticalPercent: 10 # 剩余空间 <10% 提示清理/归档 DiskCheckHour: 7 # 每天 07:00 检测 - ArchiveDir: "" # 外部备份目录(NAS/移动硬盘),留空则归档仅标记 diff --git a/bj_power_wms/etc/bj_power_wms-api.yaml b/bj_power_wms/etc/bj_power_wms-api.yaml index dcc677a..c655148 100644 --- a/bj_power_wms/etc/bj_power_wms-api.yaml +++ b/bj_power_wms/etc/bj_power_wms-api.yaml @@ -64,4 +64,3 @@ Attachment: DiskWarnPercent: 20 # 剩余空间 <20% 告警 DiskCriticalPercent: 10 # 剩余空间 <10% 提示清理/归档 DiskCheckHour: 7 # 每天 07:00 检测 - ArchiveDir: "" # 外部备份目录(NAS/移动硬盘),留空则归档仅标记 diff --git a/bj_power_wms/etc/test-8899.yaml b/bj_power_wms/etc/test-8899.yaml index 53b38b1..d84211d 100644 --- a/bj_power_wms/etc/test-8899.yaml +++ b/bj_power_wms/etc/test-8899.yaml @@ -66,4 +66,3 @@ Attachment: DiskWarnPercent: 20 # 剩余空间 <20% 告警 DiskCriticalPercent: 10 # 剩余空间 <10% 提示清理/归档 DiskCheckHour: 7 # 每天 07:00 检测 - ArchiveDir: "" # 外部备份目录(NAS/移动硬盘),留空则归档仅标记 diff --git a/bj_power_wms/frontend/package-lock.json b/bj_power_wms/frontend/package-lock.json index 8540764..73dad95 100644 --- a/bj_power_wms/frontend/package-lock.json +++ b/bj_power_wms/frontend/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@element-plus/icons-vue": "^2.3.1", "axios": "^1.8.4", + "echarts": "^6.1.0", "element-plus": "^2.9.11", "vue": "^3.5.13", "vue-router": "^4.5.0" @@ -1231,6 +1232,16 @@ "node": ">= 0.4" } }, + "node_modules/echarts": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz", + "integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "2.3.0", + "zrender": "6.1.0" + } + }, "node_modules/element-plus": { "version": "2.14.5", "resolved": "https://registry.npmjs.org/element-plus/-/element-plus-2.14.5.tgz", @@ -1767,6 +1778,12 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" + }, "node_modules/vite": { "version": "6.4.3", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", @@ -1883,6 +1900,15 @@ "peerDependencies": { "vue": "^3.5.0" } + }, + "node_modules/zrender": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz", + "integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==", + "license": "BSD-3-Clause", + "dependencies": { + "tslib": "2.3.0" + } } } } diff --git a/bj_power_wms/frontend/package.json b/bj_power_wms/frontend/package.json index 8f230ca..194fa1c 100644 --- a/bj_power_wms/frontend/package.json +++ b/bj_power_wms/frontend/package.json @@ -10,6 +10,7 @@ "dependencies": { "@element-plus/icons-vue": "^2.3.1", "axios": "^1.8.4", + "echarts": "^6.1.0", "element-plus": "^2.9.11", "vue": "^3.5.13", "vue-router": "^4.5.0" @@ -18,4 +19,4 @@ "@vitejs/plugin-vue": "^5.2.4", "vite": "^6.3.5" } -} \ No newline at end of file +} diff --git a/bj_power_wms/frontend/src/components/AnimNumber.vue b/bj_power_wms/frontend/src/components/AnimNumber.vue new file mode 100644 index 0000000..913f022 --- /dev/null +++ b/bj_power_wms/frontend/src/components/AnimNumber.vue @@ -0,0 +1,38 @@ + + + + + diff --git a/bj_power_wms/frontend/src/components/VChart.vue b/bj_power_wms/frontend/src/components/VChart.vue new file mode 100644 index 0000000..02c63ac --- /dev/null +++ b/bj_power_wms/frontend/src/components/VChart.vue @@ -0,0 +1,43 @@ + + + + + diff --git a/bj_power_wms/frontend/src/help.js b/bj_power_wms/frontend/src/help.js index b9bb2db..461a28f 100644 --- a/bj_power_wms/frontend/src/help.js +++ b/bj_power_wms/frontend/src/help.js @@ -301,15 +301,14 @@ export const helpZone = { export const helpAttachment = { title: '附件中心', overview: - '统一查看全系统上传的附件(图纸/报告/照片/Excel 等)。附件按「业务类型」挂靠具体单据,磁盘按「年/月/日/文件类型/uuid.ext」分层存储,库内只存相对路径。\n\n本页只读查询 + 下载/删除(不提供在线预览“查看”,统一走下载)。删除为逻辑删除(索引标记),真正的磁盘文件由「空间清理」统一处理。顶部会显示附件磁盘剩余空间告警:低于 20% 提醒、低于 10% 提示立即清理。\n\n删除保护:工艺流程(PROCESS_PDF)、流程卡(PROCESS_CARD) 为关键工艺文件,全程禁删;检验照片/报告(INSPECTION_*) 在质量追溯保留期(本地保留年数)内禁删。\n\n空间清理(页面右上「空间清理」按钮,需 attachment:manage 权限)归拢三项,每项先「预检」看影响范围、确认后再执行:① 归档清理(早于本地保留年数的附件备份到外部目录并标记);② 物理清理已删附件(删除已标记删除的磁盘文件,索引保留);③ 日志清理(仅系统管理员,清理日志目录下早于 N 天的 *.log,默认保留 30 天,系统亦每日自动滚动清理)。', + '统一查看全系统上传的附件(图纸/报告/照片/Excel 等)。附件按「业务类型」挂靠具体单据,磁盘按「年/月/日/文件类型/uuid.ext」分层存储,库内只存相对路径。\n\n本页只读查询 + 下载/删除(不提供在线预览“查看”,统一走下载)。删除为逻辑删除(索引标记),真正的磁盘文件由「已删除附件」抽屉统一物理清理释放。顶部会显示附件磁盘剩余空间告警:低于 20% 提醒、低于 10% 提示立即清理。\n\n删除保护:工艺流程(PROCESS_PDF)、流程卡(PROCESS_CARD) 为关键工艺文件,全程禁删;检验照片/报告(INSPECTION_*) 在质量追溯保留期(本地保留年数)内禁删。\n\n已删除附件(页面右上「已删除附件」按钮,需 attachment:manage 权限):物理清理已标记删除的磁盘文件释放空间(索引保留),每项先「预检」看影响范围、确认后再执行。附件历史数据按时间窗的备份与清理统一在「数据归档」页面完成。', fields: [ { name: '文件类型', source: '筛选条件。文件类型目录(大写),决定磁盘存放目录。', purpose: '按附件类别过滤', fill: '工艺流程/检验照片/检验报告/图纸/流程卡/包装照片/Excel导入/其他' }, { name: '业务类型', source: '筛选条件。附件挂靠的业务对象。', purpose: '只看某类业务的附件', fill: '入库/物料档案/质量检验/半成品/出库' }, { name: '业务标识', source: '筛选条件。', purpose: '按单号/编码/ID 定位某条业务记录的附件', fill: '如入库单号、物料编码、检验记录 ID' }, { name: '下载', source: '行末按钮。', purpose: '下载原件(带原文件名)', fill: '本页不提供在线“查看”预览,统一下载后本地打开' }, - { name: '删除', source: '行末按钮(权限 attachment:manage)。', purpose: '逻辑删除附件索引(文件待「空间清理-物理清理」统一清除)', fill: '确认后标记已删除;工艺流程/流程卡及保留期内检验记录受保护不可删' }, - { name: '空间清理', source: '页面右上按钮(权限 attachment:manage),抽屉式归拢归档/物理清理/日志清理。', purpose: '释放磁盘空间:归档旧附件、物理删除已删文件、清理旧日志', fill: '每项先「预检」(dryRun)看影响数量与释放空间,再「执行」前二次确认' }, - { name: '日志清理', source: '空间清理抽屉第③项(仅系统管理员 admin)。', purpose: '清理日志目录下早于 N 天的 *.log(默认 30 天)', fill: '不开放普通仓管;系统每日自动滚动清理,此为手动“立即清理”补充入口' }, + { name: '删除', source: '行末按钮(权限 attachment:manage)。', purpose: '逻辑删除附件索引(文件待「已删除附件」抽屉物理清理释放)', fill: '确认后标记已删除;工艺流程/流程卡及保留期内检验记录受保护不可删' }, + { name: '已删除附件', source: '页面右上按钮(权限 attachment:manage),抽屉式物理清理已删附件。', purpose: '释放磁盘空间:物理删除已删文件', fill: '先「预检」(dryRun)看影响数量与释放空间,再「执行」前二次确认;删除的附件仍占用磁盘空间,需彻底删除才释放' }, { name: '磁盘告警', source: '系统每天早上 7:00 自动检测附件目录剩余空间。', purpose: '提前发现空间不足,避免写入失败', fill: '剩余 <20% 告警、<10% 提示立即清理;本页顶部同步展示' } ] } diff --git a/bj_power_wms/frontend/src/layouts/MainLayout.vue b/bj_power_wms/frontend/src/layouts/MainLayout.vue index e38c7ea..e6b9804 100644 --- a/bj_power_wms/frontend/src/layouts/MainLayout.vue +++ b/bj_power_wms/frontend/src/layouts/MainLayout.vue @@ -1,10 +1,10 @@ + + diff --git a/bj_power_wms/frontend/src/pages/Display.vue b/bj_power_wms/frontend/src/pages/Display.vue index f463c8a..f765668 100644 --- a/bj_power_wms/frontend/src/pages/Display.vue +++ b/bj_power_wms/frontend/src/pages/Display.vue @@ -1,71 +1,313 @@ \ No newline at end of file +.panel-title { + flex-shrink: 0; + font-size: clamp(13px, 1vw, 16px); letter-spacing: 3px; color: #bfe0ff; + border-left: 4px solid #409eff; padding: clamp(8px, 1.2vh, 12px) 0 clamp(6px, 1vh, 10px) 12px; + margin: clamp(6px, 1vh, 10px) 12px 0; +} +.panel-note { font-size: clamp(10px, 0.75vw, 12px); color: #5f86b8; letter-spacing: 1px; margin-left: 10px; } +.panel-body { flex: 1; min-height: 0; padding: 4px 10px 8px; position: relative; } + +/* ---------- 出入库动态 / 叫料池滚动 ---------- + 截字修复(2026-10-27 二次拍板):上下边缘 14px 渐隐遮罩,滚动中半行被柔化淡出,不再出现硬切字 */ +.feed-viewport { + overflow: hidden; padding: 8px 0 8px; + -webkit-mask-image: linear-gradient(180deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%); + mask-image: linear-gradient(180deg, transparent 0, #000 14px, #000 calc(100% - 14px), transparent 100%); +} +.feed-track { will-change: transform; } +.feed-track.rolling { animation: feedScroll linear infinite; } +@keyframes feedScroll { + from { transform: translateY(0); } + to { transform: translateY(-50%); } +} +.feed-row { + display: flex; align-items: center; gap: 10px; + height: clamp(30px, 3.6vh, 44px); + padding: 0 clamp(10px, 1.2vw, 18px); + border-bottom: 1px dashed rgba(64, 158, 255, 0.15); + font-size: clamp(12px, 0.95vw, 15px); + white-space: nowrap; +} +.feed-time { width: 48px; color: #5f86b8; font-variant-numeric: tabular-nums; flex-shrink: 0; } +.feed-tag { + flex-shrink: 0; width: 44px; text-align: center; border-radius: 4px; + padding: 1px 0; font-size: clamp(10px, 0.8vw, 13px); font-weight: 600; +} +.tag-in { color: #04142e; background: #37e2ff; } +.tag-out { color: #eaf4ff; background: #2f6fe4; } +.feed-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; color: #cfe6ff; } +.feed-qty { flex-shrink: 0; width: clamp(48px, 5vw, 80px); text-align: right; color: #61e6ff; font-weight: 700; font-variant-numeric: tabular-nums; } +.feed-op { flex-shrink: 0; width: clamp(56px, 6vw, 96px); text-align: right; color: #7fb8ff; overflow: hidden; text-overflow: ellipsis; } + +/* ---------- 备料叫料池 ---------- */ +.call-row { gap: 12px; } +.call-station { + flex-shrink: 0; width: clamp(56px, 5.5vw, 88px); text-align: center; + color: #bfe0ff; background: rgba(19, 56, 110, 0.6); border-radius: 4px; + padding: 1px 0; font-weight: 600; font-size: clamp(11px, 0.85vw, 14px); +} +.call-badge { width: clamp(52px, 4.6vw, 72px); } +.badge-pending { color: #04142e; background: #37e2ff; } +.badge-shipping { color: #eaf4ff; background: #2f6fe4; } +.badge-done { color: #cfe6ff; background: #44598a; } + +/* ---------- 货架占用热力 ---------- */ +.heat-viewport { overflow: hidden; padding: 4px 12px 8px; display: flex; flex-direction: column; gap: clamp(6px, 1vh, 12px); } +.heat-zone { display: flex; align-items: flex-start; gap: 8px; min-height: 0; } +.heat-zone-name { + flex-shrink: 0; width: clamp(40px, 3.6vw, 64px); + padding-top: clamp(4px, 0.6vh, 8px); + text-align: right; color: #7fb8ff; font-size: clamp(11px, 0.85vw, 14px); font-weight: 600; +} +.heat-cells { flex: 1; display: grid; grid-template-columns: repeat(auto-fill, minmax(clamp(58px, 5vw, 84px), 1fr)); gap: clamp(4px, 0.5vw, 8px); } +.heat-cell { + border-radius: 6px; padding: clamp(3px, 0.5vh, 6px) 4px; + display: flex; flex-direction: column; align-items: center; line-height: 1.25; + transition: background 0.6s ease; +} +.cell-shelf { font-size: clamp(10px, 0.8vw, 13px); font-weight: 700; } +.cell-qty { font-size: clamp(9px, 0.72vw, 12px); opacity: 0.92; font-variant-numeric: tabular-nums; } + +/* ---------- 空状态 ---------- */ +.empty { + position: absolute; inset: 0; + display: flex; align-items: center; justify-content: center; + color: #5f86b8; font-size: clamp(13px, 1vw, 16px); letter-spacing: 2px; +} + +/* ---------- 页脚 ---------- */ +.foot { + flex-shrink: 0; + padding: 6px clamp(20px, 2.5vw, 40px) clamp(8px, 1.4vh, 16px); + text-align: center; color: #47709f; font-size: clamp(10px, 0.8vw, 12px); + letter-spacing: 1px; +} + diff --git a/bj_power_wms/frontend/src/pages/Settings.vue b/bj_power_wms/frontend/src/pages/Settings.vue new file mode 100644 index 0000000..286f04f --- /dev/null +++ b/bj_power_wms/frontend/src/pages/Settings.vue @@ -0,0 +1,112 @@ + + + + + diff --git a/bj_power_wms/frontend/src/router/index.js b/bj_power_wms/frontend/src/router/index.js index 0eb64db..0cc7a4d 100644 --- a/bj_power_wms/frontend/src/router/index.js +++ b/bj_power_wms/frontend/src/router/index.js @@ -26,7 +26,9 @@ const routes = [ { path: 'users', name: 'UserManage', component: () => import('../pages/UserManage.vue'), meta: { title: '账号管理', keepAlive: true, componentName: 'UserManage' } }, { path: 'roles', name: 'RoleManage', component: () => import('../pages/RoleManage.vue'), meta: { title: '角色管理', keepAlive: true, componentName: 'RoleManage' } }, { path: 'event-log', name: 'EventLog', component: () => import('../pages/EventLog.vue'), meta: { title: '操作日志', keepAlive: true, componentName: 'EventLog' } }, - { path: 'attachment', name: 'AttachmentCenter', component: () => import('../pages/AttachmentCenter.vue'), meta: { title: '附件中心', keepAlive: true, componentName: 'AttachmentCenter' } } + { path: 'attachment', name: 'AttachmentCenter', component: () => import('../pages/AttachmentCenter.vue'), meta: { title: '附件中心', keepAlive: true, componentName: 'AttachmentCenter' } }, + { path: 'data-archive', name: 'DataArchive', component: () => import('../pages/DataArchive.vue'), meta: { title: '数据归档', keepAlive: true, componentName: 'DataArchive' } }, + { path: 'settings', name: 'Settings', component: () => import('../pages/Settings.vue'), meta: { title: '基础设置', keepAlive: true, componentName: 'Settings' } } ] }, { path: '/:pathMatch(.*)*', redirect: '/' } diff --git a/bj_power_wms/internal/backup/backup.go b/bj_power_wms/internal/backup/backup.go new file mode 100644 index 0000000..13638e1 --- /dev/null +++ b/bj_power_wms/internal/backup/backup.go @@ -0,0 +1,637 @@ +// Package backup 实现「备份到外部存储(U盘/移动硬盘)」与「按时间窗物理清理」两大能力(WMS 端)。 +// 与 MES 端对称:时间字段统一 Int64 unix 秒;各端附件文件由各端独占写入与引用 +// (UUID 文件名,物料同步不含附件),不存在跨系统共享文件,清理不依赖对端服务。 +package backup + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "bj_power_wms/ent" + att "bj_power_wms/ent/attachment" + br "bj_power_wms/ent/backuprecord" + "bj_power_wms/ent/eventlog" + evlog "bj_power_wms/internal/eventlog" + + "golang.org/x/sys/windows" +) + +// ItemDef 可选备份/清理数据项(质量 4 表有意不出现)。 +type ItemDef struct { + Key string `json:"key"` + Name string `json:"name"` + Kind string `json:"kind"` // log | attachment +} + +// WMSItems WMS 端可选数据项(event_log/attachments)。 +var WMSItems = []ItemDef{ + {Key: "event_log", Name: "操作日志", Kind: "log"}, + {Key: "attachments", Name: "业务附件", Kind: "attachment"}, +} + +// BackupRequest 备份请求。 +type BackupRequest struct { + TargetPath string `json:"targetPath"` + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + Operator string `json:"operator"` +} + +// CleanupRequest 清理请求。 +type CleanupRequest struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + Operator string `json:"operator"` +} + +// ItemResult 单项导出结果。 +type ItemResult struct { + Name string `json:"name"` + Key string `json:"key"` + Rows int64 `json:"rows"` + Bytes int64 `json:"bytes"` +} + +// BackupResult 备份结果。 +type BackupResult struct { + BackupPath string `json:"backupPath"` + TotalSize int64 `json:"totalSize"` + Checksum string `json:"checksum"` + Items []ItemResult `json:"items"` +} + +// CleanupResult 清理结果。 +type CleanupResult struct { + RangeStart int64 `json:"rangeStart"` + RangeEnd int64 `json:"rangeEnd"` + Deleted []ItemResult `json:"deleted"` + Skipped []ItemResult `json:"skipped"` +} + +// MissingSeg 缺失时间段。 +type MissingSeg struct { + Start int64 `json:"start"` + End int64 `json:"end"` +} + +// CoverageResult 覆盖校验结果。 +type CoverageResult struct { + OK bool `json:"ok"` + Missing []MissingSeg `json:"missing"` +} + +// Progress 任务进度。 +type Progress struct { + JobID string `json:"jobId"` + Phase string `json:"phase"` + Stage string `json:"stage"` + Percent int `json:"percent"` + Message string `json:"message"` + Done bool `json:"done"` + Failed bool `json:"failed"` + Result any `json:"result,omitempty"` +} + +// Service 备份/清理服务。 +type Service struct { + client *ent.Client + ev *evlog.Writer + attRoot string + + mu sync.Mutex + jobs map[string]*Progress +} + +// New 构造服务。 +func New(client *ent.Client, ev *evlog.Writer, attRoot string) *Service { + return &Service{ + client: client, + ev: ev, + attRoot: attRoot, + jobs: make(map[string]*Progress), + } +} + +// ListItems 返回可选数据项。 +func (s *Service) ListItems() []ItemDef { return WMSItems } + +// ---------------- 备份 ---------------- + +// StartBackup 启动异步备份,返回 jobID。 +func (s *Service) StartBackup(req BackupRequest) (string, error) { + if strings.TrimSpace(req.TargetPath) == "" { + return "", fmt.Errorf("请选择备份目标路径") + } + if !filepath.IsAbs(req.TargetPath) { + return "", fmt.Errorf("备份目标路径必须为绝对路径") + } + if req.End <= req.Start { + return "", fmt.Errorf("时间窗不合法(结束须晚于开始)") + } + if len(req.Items) == 0 { + return "", fmt.Errorf("请至少选择一个数据项") + } + jobID := newJobID() + s.mu.Lock() + s.jobs[jobID] = &Progress{JobID: jobID, Phase: "backup", Stage: "preparing", Percent: 0} + s.mu.Unlock() + go s.runBackup(jobID, req) + return jobID, nil +} + +func (s *Service) runBackup(jobID string, req BackupRequest) { + ctx := context.Background() + setStage := func(stage string, pct int, msg string) { + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Stage, j.Percent, j.Message = stage, pct, msg + } + s.mu.Unlock() + } + + est, err := s.estimateBytes(ctx, req) + if err != nil { + s.failBackup(jobID, req, err) + return + } + free, derr := diskFree(req.TargetPath) + if derr == nil && free < uint64(est) { + need := est - int64(free) + s.failBackup(jobID, req, fmt.Errorf("目标盘空间不足:需要约 %s,当前剩余 %s(还差 %s)", + humanBytes(est), humanBytes(int64(free)), humanBytes(need))) + return + } + + setStage("writing", 5, "准备写入备份包…") + stamp := time.Now().Format("20060102_150405") + zipPath := filepath.Join(req.TargetPath, "backup_wms_"+stamp+".zip") + if err := os.MkdirAll(req.TargetPath, 0o755); err != nil { + s.failBackup(jobID, req, fmt.Errorf("无法创建目标目录:%w", err)) + return + } + f, err := os.Create(zipPath) + if err != nil { + s.failBackup(jobID, req, fmt.Errorf("无法创建备份文件(U盘是否已拔出/无写入权限):%w", err)) + return + } + + h := sha256.New() + zw := newZipWriter(f, h) + results := make([]ItemResult, 0, len(req.Items)) + total := int64(0) + itemNames := make(map[string]string, len(WMSItems)) + for _, it := range WMSItems { + itemNames[it.Key] = it.Name + } + + for i, key := range req.Items { + setStage("writing", 5+int(float64(i)/float64(len(req.Items))*80), "导出 "+itemName(itemNames, key)+" …") + var ir ItemResult + var e error + if key == "attachments" { + ir, e = s.exportAttachment(ctx, zw, req.Start, req.End) + } else { + ir, e = s.exportLog(ctx, zw, key, req.Start, req.End) + } + if e != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("导出 %s 失败(U盘是否已拔出):%w", itemName(itemNames, key), e)) + return + } + ir.Key = key + ir.Name = itemName(itemNames, key) + results = append(results, ir) + total += ir.Bytes + } + + manifest := map[string]any{ + "generatedAt": time.Now().Format(time.RFC3339), + "scope": "wms", + "rangeStart": req.Start, + "rangeEnd": req.End, + "rangeStartText": time.Unix(req.Start, 0).Format("2006-01-02 15:04:05"), + "rangeEndText": time.Unix(req.End, 0).Format("2006-01-02 15:04:05"), + "operator": req.Operator, + "items": results, + "totalSize": total, + "checksum": "", + } + manifestBytes, _ := json.MarshalIndent(manifest, "", " ") + if err := zw.WriteFile("manifest.json", manifestBytes); err != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("写入 manifest 失败:%w", err)) + return + } + + indexHTML := buildIndexHTML("WMS 备份清单", manifest, "") + if err := zw.WriteFile("index.html", []byte(indexHTML)); err != nil { + _ = zw.Close() + _ = f.Close() + _ = os.Remove(zipPath) + s.failBackup(jobID, req, fmt.Errorf("写入 index.html 失败:%w", err)) + return + } + + if err := zw.Close(); err != nil { + _ = f.Close() + _ = os.Remove(zipPath) + // 备份包已随 os.Remove 删除,无残留产物:状态=failed(非 partial) + s.failBackup(jobID, req, fmt.Errorf("备份写入中断(U盘是否已拔出):%w", err)) + return + } + if err := f.Close(); err != nil { + _ = os.Remove(zipPath) + // 备份包已随 os.Remove 删除,无残留产物:状态=failed(非 partial) + s.failBackup(jobID, req, fmt.Errorf("备份文件关闭失败:%w", err)) + return + } + + fi, _ := os.Stat(zipPath) + if fi != nil { + total = fi.Size() + } + s.finishBackup(jobID, req, zipPath, results, total, hex.EncodeToString(h.Sum(nil)), false, nil) +} + +func (s *Service) exportLog(ctx context.Context, zw *zipWriter, key string, start, end int64) (ItemResult, error) { + if key != "event_log" { + return ItemResult{}, fmt.Errorf("未知数据项 %s", key) + } + rows, err := s.client.EventLog.Query(). + Where(eventlog.CreatedAtGTE(start), eventlog.CreatedAtLTE(end)).All(ctx) + if err != nil { + return ItemResult{}, err + } + ir := ItemResult{Rows: int64(len(rows))} + if err := zw.WriteJSONL(key+"/data.jsonl", sliceToAny(rows), &ir.Bytes); err != nil { + return ir, err + } + return ir, nil +} + +func (s *Service) exportAttachment(ctx context.Context, zw *zipWriter, start, end int64) (ItemResult, error) { + rows, err := s.client.Attachment.Query(). + Where(att.CreatedAtGTE(start), att.CreatedAtLTE(end), att.DeletedEQ(false)).All(ctx) + if err != nil { + return ItemResult{}, err + } + ir := ItemResult{Rows: int64(len(rows))} + meta := make([]map[string]any, 0, len(rows)) + for _, r := range rows { + abs, ok := safeAbsPath(s.attRoot, r.FilePath) + if !ok { + continue + } + _, ferr := os.Stat(abs) + if ferr != nil { + meta = append(meta, map[string]any{ + "id": r.ID, "file_name": r.FileName, "file_path": r.FilePath, + "file_size": r.FileSize, "missing": true, + }) + continue + } + src, oerr := os.Open(abs) + if oerr != nil { + return ir, oerr + } + entryName := "attachments/" + strings.ReplaceAll(r.FilePath, "\\", "/") + n, cerr := zw.CopyFrom(entryName, src) + _ = src.Close() + if cerr != nil { + return ir, cerr + } + ir.Bytes += n + meta = append(meta, map[string]any{ + "id": r.ID, "file_name": r.FileName, "file_path": r.FilePath, + "file_size": r.FileSize, "bytes": n, + }) + } + mb, _ := json.MarshalIndent(meta, "", " ") + if err := zw.WriteFile("attachment/data.jsonl", mb); err != nil { + return ir, err + } + ir.Bytes += int64(len(mb)) + return ir, nil +} + +func (s *Service) finishBackup(jobID string, req BackupRequest, zipPath string, results []ItemResult, total int64, checksum string, partial bool, runErr error) { + status := "success" + if partial { + status = "partial" + } + itemsJSON, _ := json.Marshal(results) + _, _ = s.client.BackupRecord.Create(). + SetExecutedAt(time.Now().Unix()). + SetRangeStart(req.Start). + SetRangeEnd(req.End). + SetBackupPath(zipPath). + SetTotalSize(total). + SetItemsJSON(string(itemsJSON)). + SetStatus(status). + SetOperator(req.Operator). + SetChecksum(checksum). + SetScope("wms"). + Save(context.Background()) + + s.ev.Write(context.Background(), "backup.create", req.Operator, "backup", "", + fmt.Sprintf("备份到 %s(范围 %s ~ %s,共 %d 项,%s,校验和 %s)", + zipPath, time.Unix(req.Start, 0).Format("2006-01-02"), time.Unix(req.End, 0).Format("2006-01-02"), + len(results), humanBytes(total), checksum), nil) + + res := BackupResult{BackupPath: zipPath, TotalSize: total, Checksum: checksum, Items: results} + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + if partial { + j.Failed = true + j.Message = "备份部分成功(U盘可能已拔出):" + runErr.Error() + } else { + j.Message = "备份完成" + } + j.Result = res + j.Percent = 100 + } + s.mu.Unlock() +} + +func (s *Service) failBackup(jobID string, req BackupRequest, runErr error) { + _, _ = s.client.BackupRecord.Create(). + SetExecutedAt(time.Now().Unix()). + SetRangeStart(req.Start). + SetRangeEnd(req.End). + SetBackupPath(""). + SetTotalSize(0). + SetItemsJSON("[]"). + SetStatus("failed"). + SetOperator(req.Operator). + SetChecksum(""). + SetScope("wms"). + Save(context.Background()) + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Failed = true + j.Message = runErr.Error() + j.Percent = 100 + } + s.mu.Unlock() +} + +func (s *Service) estimateBytes(ctx context.Context, req BackupRequest) (int64, error) { + var total int64 + for _, key := range req.Items { + switch key { + case "attachments": + rows, err := s.client.Attachment.Query(). + Where(att.CreatedAtGTE(req.Start), att.CreatedAtLTE(req.End)).All(ctx) + if err != nil { + return 0, err + } + for _, r := range rows { + total += r.FileSize + } + total += int64(len(rows)) * 256 + case "event_log": + n, err := s.client.EventLog.Query(). + Where(eventlog.CreatedAtGTE(req.Start), eventlog.CreatedAtLTE(req.End)).Count(ctx) + if err != nil { + return 0, err + } + total += int64(n) * 1024 + } + } + total += 4096 + return total, nil +} + +// ---------------- 清理 ---------------- + +// StartCleanup 启动异步清理,返回 jobID。 +func (s *Service) StartCleanup(req CleanupRequest) (string, error) { + if req.End <= req.Start { + return "", fmt.Errorf("时间窗不合法") + } + if len(req.Items) == 0 { + return "", fmt.Errorf("请至少选择一个数据项") + } + jobID := newJobID() + s.mu.Lock() + s.jobs[jobID] = &Progress{JobID: jobID, Phase: "cleanup", Stage: "checking", Percent: 0} + s.mu.Unlock() + go s.runCleanup(jobID, req) + return jobID, nil +} + +// CheckCoverage 校验备份覆盖(供前端预检)。 +func (s *Service) CheckCoverage(start, end int64) (CoverageResult, error) { + recs, err := s.client.BackupRecord.Query().Where(br.StatusEQ("success")).All(context.Background()) + if err != nil { + return CoverageResult{}, err + } + ivs := make([][2]int64, 0, len(recs)) + for _, r := range recs { + ivs = append(ivs, [2]int64{r.RangeStart, r.RangeEnd}) + } + missing := complement(ivs, start, end) + return CoverageResult{OK: len(missing) == 0, Missing: missing}, nil +} + +func (s *Service) runCleanup(jobID string, req CleanupRequest) { + ctx := context.Background() + setStage := func(stage string, pct int, msg string) { + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Stage, j.Percent, j.Message = stage, pct, msg + } + s.mu.Unlock() + } + + cov, err := s.CheckCoverage(req.Start, req.End) + if err != nil { + s.failCleanup(jobID, req, fmt.Errorf("覆盖校验失败:%w", err)) + return + } + if !cov.OK { + s.failCleanup(jobID, req, fmt.Errorf("该时间窗未被完整备份,禁止清理。缺失时间段:%s", formatMissing(cov.Missing))) + return + } + + deleted := make([]ItemResult, 0, len(req.Items)) + skipped := make([]ItemResult, 0, len(req.Items)) + itemNames := make(map[string]string, len(WMSItems)) + for _, it := range WMSItems { + itemNames[it.Key] = it.Name + } + + for i, key := range req.Items { + setStage("cleaning", int(float64(i)/float64(len(req.Items))*90), "清理 "+itemName(itemNames, key)+" …") + if key == "attachments" { + d, sk, e := s.cleanupAttachment(ctx, req.Start, req.End) + if e != nil { + s.failCleanup(jobID, req, fmt.Errorf("清理附件失败:%w", e)) + return + } + d.Key, d.Name = key, itemName(itemNames, key) + sk.Key, sk.Name = key, itemName(itemNames, key) + deleted = append(deleted, d) + if sk.Rows > 0 { + skipped = append(skipped, sk) + } + } else { + n, e := s.cleanupLog(ctx, key, req.Start, req.End) + if e != nil { + s.failCleanup(jobID, req, fmt.Errorf("清理 %s 失败:%w", itemName(itemNames, key), e)) + return + } + deleted = append(deleted, ItemResult{Key: key, Name: itemName(itemNames, key), Rows: n, Bytes: 0}) + } + } + + s.ev.Write(ctx, "backup.cleanup", req.Operator, "backup", "", + fmt.Sprintf("按时间窗清理(%s ~ %s):%s", + time.Unix(req.Start, 0).Format("2006-01-02"), time.Unix(req.End, 0).Format("2006-01-02"), + summaryDeleted(deleted, skipped)), nil) + + setStage("done", 100, "清理完成") + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Result = CleanupResult{RangeStart: req.Start, RangeEnd: req.End, Deleted: deleted, Skipped: skipped} + } + s.mu.Unlock() +} + +func (s *Service) cleanupLog(ctx context.Context, key string, start, end int64) (int64, error) { + if key != "event_log" { + return 0, nil + } + n, err := s.client.EventLog.Delete(). + Where(eventlog.CreatedAtGTE(start), eventlog.CreatedAtLTE(end)).Exec(ctx) + return int64(n), err +} + +// cleanupAttachment 物理删除文件 + DELETE 记录(附件文件由本端独占写入与引用,无需跨库校验)。 +func (s *Service) cleanupAttachment(ctx context.Context, start, end int64) (ItemResult, ItemResult, error) { + rows, err := s.client.Attachment.Query(). + Where(att.CreatedAtGTE(start), att.CreatedAtLTE(end)).All(ctx) + if err != nil { + return ItemResult{}, ItemResult{}, err + } + del := ItemResult{} + sk := ItemResult{} + for _, r := range rows { + abs, ok := safeAbsPath(s.attRoot, r.FilePath) + if ok { + if rerr := os.Remove(abs); rerr != nil && !os.IsNotExist(rerr) { + sk.Rows++ + continue + } + } + if _, derr := s.client.Attachment.Delete().Where(att.ID(r.ID)).Exec(ctx); derr != nil { + sk.Rows++ + continue + } + del.Rows++ + del.Bytes += r.FileSize + } + return del, sk, nil +} + +func (s *Service) failCleanup(jobID string, req CleanupRequest, runErr error) { + s.ev.Write(context.Background(), "backup.cleanup.reject", req.Operator, "backup", "", + "清理被拒:"+runErr.Error(), nil) + s.mu.Lock() + if j, ok := s.jobs[jobID]; ok { + j.Done = true + j.Failed = true + j.Message = runErr.Error() + j.Percent = 100 + } + s.mu.Unlock() +} + +// ---------------- 进度 ---------------- + +// Progress 返回任务进度。 +func (s *Service) Progress(jobID string) (Progress, bool) { + s.mu.Lock() + defer s.mu.Unlock() + j, ok := s.jobs[jobID] + if !ok { + return Progress{}, false + } + cp := *j + return cp, true +} + +// ---------------- 工具 ---------------- + +func itemName(m map[string]string, key string) string { + if n, ok := m[key]; ok { + return n + } + return key +} + +func safeAbsPath(root, rel string) (string, bool) { + rel = strings.ReplaceAll(rel, "\\", "/") + clean := filepath.Clean(filepath.Join(root, rel)) + rootAbs, err := filepath.Abs(root) + if err != nil { + return "", false + } + abs, err := filepath.Abs(clean) + if err != nil { + return "", false + } + if abs != rootAbs && !strings.HasPrefix(abs, rootAbs+string(os.PathSeparator)) { + return "", false + } + return abs, true +} + +func diskFree(path string) (uint64, error) { + var free uint64 + p, err := windows.UTF16PtrFromString(path) + if err != nil { + return 0, err + } + if err := windows.GetDiskFreeSpaceEx(p, &free, nil, nil); err != nil { + return 0, err + } + return free, nil +} + +func humanBytes(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + div, exp := int64(unit), 0 + for x := n / unit; x >= unit; x /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.2f %cB", float64(n)/float64(div), "KMGTPE"[exp]) +} + +func newJobID() string { + b := make([]byte, 8) + _, _ = io.ReadFull(randReader(), b) + return hex.EncodeToString(b) + fmt.Sprintf("%d", time.Now().UnixNano()%100000) +} diff --git a/bj_power_wms/internal/backup/browse.go b/bj_power_wms/internal/backup/browse.go new file mode 100644 index 0000000..6c9ef2b --- /dev/null +++ b/bj_power_wms/internal/backup/browse.go @@ -0,0 +1,76 @@ +package backup + +import ( + "os" + "path/filepath" + "strings" + + "golang.org/x/sys/windows" +) + +// DriveInfo 盘符信息(Windows)。 +type DriveInfo struct { + Letter string `json:"letter"` + Path string `json:"path"` +} + +// ListDrives 列出本机所有盘符(Windows)。 +func ListDrives() ([]DriveInfo, error) { + mask, err := windows.GetLogicalDrives() + if err != nil { + return nil, err + } + out := make([]DriveInfo, 0) + for i := 0; i < 26; i++ { + if mask&(1< 0 { + last := recs[len(recs)-1] + res.LastBackupAt = last.ExecutedAt + res.LastBackupPath = last.BackupPath + } + if remindDays > 0 && res.LastBackupAt > 0 { + due := res.LastBackupAt + int64(remindDays)*86400 + res.Overdue = time.Now().Unix() >= due + } + return res, nil +} + +// PreviewItem 单项预览。 +type PreviewItem struct { + Key string `json:"key"` + Name string `json:"name"` + Rows int64 `json:"rows"` + Bytes int64 `json:"bytes"` +} + +// PreviewResult 清理预览结果。 +type PreviewResult struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []PreviewItem `json:"items"` + TotalRows int64 `json:"totalRows"` + TotalBytes int64 `json:"totalBytes"` +} + +// Preview 计算各数据项在 [start,end] 时间窗内「将删除」的行数与字节(仅估算,不落盘)。 +func (s *Service) Preview(start, end int64, keys []string) (PreviewResult, error) { + res := PreviewResult{Start: start, End: end} + itemNames := make(map[string]string, len(WMSItems)) + for _, it := range WMSItems { + itemNames[it.Key] = it.Name + } + ctx := context.Background() + for _, key := range keys { + var pi PreviewItem + var e error + if key == "attachments" { + pi.Rows, pi.Bytes, e = s.previewAttachment(ctx, start, end) + } else if key == "event_log" { + pi.Rows, e = s.countLog(ctx, key, start, end) + pi.Bytes = pi.Rows * 1024 + } else { + return res, fmt.Errorf("未知数据项 %s", key) + } + if e != nil { + return res, e + } + pi.Key = key + pi.Name = itemName(itemNames, key) + res.Items = append(res.Items, pi) + res.TotalRows += pi.Rows + res.TotalBytes += pi.Bytes + } + sort.Slice(res.Items, func(i, j int) bool { return res.Items[i].Key < res.Items[j].Key }) + return res, nil +} + +// previewAttachment 估算将删附件数量与字节(Deleted=false,与导出口径一致)。 +func (s *Service) previewAttachment(ctx context.Context, start, end int64) (int64, int64, error) { + rows, err := s.client.Attachment.Query(). + Where(att.CreatedAtGTE(start), att.CreatedAtLTE(end), att.DeletedEQ(false)).All(ctx) + if err != nil { + return 0, 0, err + } + var bytes int64 + for _, r := range rows { + bytes += int64(r.FileSize) + } + return int64(len(rows)), bytes, nil +} + +// countLog 统计日志类将删行数(WMS 仅 event_log)。 +func (s *Service) countLog(ctx context.Context, key string, start, end int64) (int64, error) { + if key != "event_log" { + return 0, fmt.Errorf("未知数据项 %s", key) + } + n, err := s.client.EventLog.Query().Where(eventlog.CreatedAtGTE(start), eventlog.CreatedAtLTE(end)).Count(ctx) + return int64(n), err +} + +// RecordItem 单条备份/清理历史(对应 backup_record 表)。 +type RecordItem struct { + ID int `json:"id"` + ExecutedAt int64 `json:"executedAt"` + RangeStart int64 `json:"rangeStart"` + RangeEnd int64 `json:"rangeEnd"` + BackupPath string `json:"backupPath"` + TotalSize int64 `json:"totalSize"` + Status string `json:"status"` + Operator string `json:"operator"` + Scope string `json:"scope"` + ItemsJSON string `json:"itemsJson"` + Checksum string `json:"checksum"` +} + +// RecordsResult 历史列表(分页)。 +type RecordsResult struct { + Total int64 `json:"total"` + List []RecordItem `json:"list"` + Page int `json:"page"` + Size int `json:"size"` +} + +// ListRecords 分页查询 backup_record(按 executedAt 倒序);status/scope 可空过滤。 +// 历史永久保留,不清(覆盖校验仅认 success)。 +func (s *Service) ListRecords(page, size int, status, scope string) (RecordsResult, error) { + if size <= 0 { + size = 50 + } + if page <= 0 { + page = 1 + } + all, err := s.client.BackupRecord.Query(). + Order(br.ByExecutedAt()). + All(context.Background()) + if err != nil { + return RecordsResult{}, err + } + filtered := make([]*ent.BackupRecord, 0, len(all)) + for _, r := range all { + if status != "" && r.Status != status { + continue + } + if scope != "" && r.Scope != scope { + continue + } + filtered = append(filtered, r) + } + for i, j := 0, len(filtered)-1; i < j; i, j = i+1, j-1 { + filtered[i], filtered[j] = filtered[j], filtered[i] + } + total := int64(len(filtered)) + start := (page - 1) * size + if start > len(filtered) { + start = len(filtered) + } + end := start + size + if end > len(filtered) { + end = len(filtered) + } + list := make([]RecordItem, 0, end-start) + for _, r := range filtered[start:end] { + list = append(list, RecordItem{ + ID: r.ID, ExecutedAt: r.ExecutedAt, RangeStart: r.RangeStart, RangeEnd: r.RangeEnd, + BackupPath: r.BackupPath, TotalSize: r.TotalSize, Status: r.Status, + Operator: r.Operator, Scope: r.Scope, ItemsJSON: r.ItemsJSON, Checksum: r.Checksum, + }) + } + return RecordsResult{Total: total, List: list, Page: page, Size: size}, nil +} diff --git a/bj_power_wms/internal/backup/util.go b/bj_power_wms/internal/backup/util.go new file mode 100644 index 0000000..4f89cff --- /dev/null +++ b/bj_power_wms/internal/backup/util.go @@ -0,0 +1,130 @@ +package backup + +import ( + "crypto/rand" + "fmt" + "io" + "reflect" + "strings" + "time" +) + +// randReader 安全随机源。 +func randReader() io.Reader { return rand.Reader } + +// sliceToAny 把任意切片转成 []any,便于统一 JSON 序列化。 +func sliceToAny(slice any) []any { + if slice == nil { + return nil + } + v := reflect.ValueOf(slice) + if v.Kind() != reflect.Slice { + return nil + } + out := make([]any, v.Len()) + for i := 0; i < v.Len(); i++ { + out[i] = v.Index(i).Interface() + } + return out +} + +// complement 计算 [start,end] 在被若干区间并集覆盖后的缺失段(闭区间,秒)。 +func complement(intervals [][2]int64, start, end int64) []MissingSeg { + if start > end { + return nil + } + ivs := make([][2]int64, 0, len(intervals)) + for _, iv := range intervals { + if iv[0] <= iv[1] && iv[1] >= start && iv[0] <= end { + ivs = append(ivs, [2]int64{maxInt64(iv[0], start), minInt64(iv[1], end)}) + } + } + sortIntervals(ivs) + missing := make([]MissingSeg, 0) + cur := start + for _, iv := range ivs { + if iv[0] > cur { + missing = append(missing, MissingSeg{Start: cur, End: iv[0] - 1}) + } + if iv[1] > cur { + cur = iv[1] + 1 + } + } + if cur <= end { + missing = append(missing, MissingSeg{Start: cur, End: end}) + } + return missing +} + +func sortIntervals(ivs [][2]int64) { + for i := 0; i < len(ivs); i++ { + for j := i + 1; j < len(ivs); j++ { + if ivs[j][0] < ivs[i][0] { + ivs[i], ivs[j] = ivs[j], ivs[i] + } + } + } +} + +func maxInt64(a, b int64) int64 { + if a > b { + return a + } + return b +} +func minInt64(a, b int64) int64 { + if a < b { + return a + } + return b +} + +func formatMissing(segs []MissingSeg) string { + parts := make([]string, 0, len(segs)) + for _, s := range segs { + parts = append(parts, fmt.Sprintf("%s ~ %s", + time.Unix(s.Start, 0).Format("2006-01-02"), time.Unix(s.End, 0).Format("2006-01-02"))) + } + return strings.Join(parts, ";") +} + +func summaryDeleted(deleted, skipped []ItemResult) string { + var b strings.Builder + for _, d := range deleted { + fmt.Fprintf(&b, "%s 删除 %d 行;", d.Name, d.Rows) + } + if len(skipped) > 0 { + b.WriteString(" 跳过共享附件(对端未备份):") + for _, s := range skipped { + fmt.Fprintf(&b, "%s %d 个;", s.Name, s.Rows) + } + } + return strings.TrimRight(b.String(), ";") +} + +// buildIndexHTML 生成备份清单页(仅清单 + 校验,不内嵌预览)。 +func buildIndexHTML(title string, manifest map[string]any, checksum string) string { + items, _ := manifest["items"].([]ItemResult) + var rows strings.Builder + for _, it := range items { + fmt.Fprintf(&rows, "%s%d%s\n", it.Name, it.Rows, humanBytes(it.Bytes)) + } + cs := checksum + if cs == "" { + if c, ok := manifest["checksum"].(string); ok { + cs = c + } + } + if cs == "" { + cs = "(见 backup_record.checksum)" + } + return fmt.Sprintf(` +%s +

%s

+

范围:%s ~ %s | 操作人:%s | 校验和(sha256):%s

+

数据项

%s
数据项行数字节
+

本文件仅作清单与校验用途,不内嵌任何数据预览。完整数据见包内各 data.jsonl 与 attachments/ 目录。

+`, title, title, manifest["rangeStartText"], manifest["rangeEndText"], manifest["operator"], cs, rows.String()) +} diff --git a/bj_power_wms/internal/backup/zip.go b/bj_power_wms/internal/backup/zip.go new file mode 100644 index 0000000..6366a5a --- /dev/null +++ b/bj_power_wms/internal/backup/zip.go @@ -0,0 +1,79 @@ +package backup + +import ( + "archive/zip" + "bytes" + "encoding/json" + "io" + "os" +) + +// zipWriter 把内容流式写入 zip,同时更新一个哈希 writer(用于备份包校验和)。 +// 直接写入目标文件,不落本地临时文件。 +type zipWriter struct { + zw *zip.Writer + f *os.File + h io.Writer +} + +func newZipWriter(f *os.File, h io.Writer) *zipWriter { + if h == nil { + h = io.Discard + } + return &zipWriter{zw: zip.NewWriter(f), f: f, h: h} +} + +// WriteFile 写入一个普通文件(同时更新哈希)。 +func (z *zipWriter) WriteFile(name string, data []byte) error { + w, err := z.zw.Create(name) + if err != nil { + return err + } + if _, err := io.Copy(io.MultiWriter(w, z.h), bytes.NewReader(data)); err != nil { + return err + } + return nil +} + +// WriteJSONL 把每行 JSON 编码写入(同时更新哈希与字节计数)。 +func (z *zipWriter) WriteJSONL(name string, rows []any, n *int64) error { + w, err := z.zw.Create(name) + if err != nil { + return err + } + cw := &countingWriter{w: io.MultiWriter(w, z.h), n: n} + enc := json.NewEncoder(cw) + for _, r := range rows { + if err := enc.Encode(r); err != nil { + return err + } + } + return nil +} + +// CopyFrom 把 src 拷贝进 zip(同时更新哈希),返回写入字节数。 +func (z *zipWriter) CopyFrom(name string, src io.Reader) (int64, error) { + w, err := z.zw.Create(name) + if err != nil { + return 0, err + } + return io.Copy(io.MultiWriter(w, z.h), src) +} + +// Close 关闭 zip(写出中央目录)。目标文件不在此关闭——由调用方统一 f.Close() 一次, +// 避免本方法关过 f 后调用方再关触发 "file already closed"(曾因此误删已生成的备份包)。 +func (z *zipWriter) Close() error { + return z.zw.Close() +} + +// countingWriter 写入时累加字节数到 *n。 +type countingWriter struct { + w io.Writer + n *int64 +} + +func (c *countingWriter) Write(p []byte) (int, error) { + nn, err := c.w.Write(p) + *c.n += int64(nn) + return nn, err +} diff --git a/bj_power_wms/internal/config/config.go b/bj_power_wms/internal/config/config.go index bd4efcc..95bf340 100644 --- a/bj_power_wms/internal/config/config.go +++ b/bj_power_wms/internal/config/config.go @@ -59,7 +59,6 @@ type AttachmentConfig struct { DiskWarnPercent int `json:",default=20"` // 剩余空间低于该百分比 → 告警 DiskCriticalPercent int `json:",default=10"` // 剩余空间低于该百分比 → 提示清理/归档 DiskCheckHour int `json:",default=7"` // 每天几点执行磁盘检测(默认 07:00) - ArchiveDir string `json:",optional"` // 外部备份目录(NAS/移动硬盘);为空则归档仅标记不动文件 } // ScannerConfig 扫码中间件(键盘 HID 注入)开关配置。 diff --git a/bj_power_wms/internal/handler/attachment.go b/bj_power_wms/internal/handler/attachment.go index b5a7971..5e8c357 100644 --- a/bj_power_wms/internal/handler/attachment.go +++ b/bj_power_wms/internal/handler/attachment.go @@ -351,7 +351,7 @@ func listAllAttachmentsHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } -// deleteAttachmentHandler 删除附件(逻辑删除:DB 标记 deleted,物理文件由归档任务统一处理) +// deleteAttachmentHandler 删除附件(逻辑删除:DB 标记 deleted;物理文件由「已删除附件」抽屉执行物理清理释放空间) // POST /api/attachments/delete body: { id } func deleteAttachmentHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -492,86 +492,6 @@ func diskStatusHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } -// archiveAttachmentsHandler 归档:把早于「本地保留年数」的附件移动到外部备份目录(ArchiveDir) -// 并标记 archived=TRUE(保留索引,可追溯)。ArchiveDir 为空时仅标记不移动。 -// POST /api/attachments/archive body: { dryRun } -func archiveAttachmentsHandler(ctx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - DryRun bool `json:"dryRun"` - ArchiveBefore int64 `json:"archiveBefore"` // 归档截止月(精确到月):归档 createdAt <= ArchiveBefore 的附件,单位 unix 秒 - } - _ = parseJSON(r, &req) - cfg := ctx.Config.Attachment - root := attRoot(ctx) - now := timeNow() - // 6 个月限制:归档截止月最晚只能选到 6 个月前,最近半年数据不可归档 - sixAgo := now.AddDate(0, -6, 0) - sixAgoEnd := time.Date(sixAgo.Year(), sixAgo.Month()+1, 0, 23, 59, 59, 0, sixAgo.Location()) - if req.ArchiveBefore <= 0 { - fail(w, http.StatusBadRequest, "请提供归档截止月") - return - } - if req.ArchiveBefore > sixAgoEnd.Unix() { - fail(w, http.StatusBadRequest, "归档截止月需早于最近 6 个月,最近半年数据不可归档") - return - } - cutMonth := time.Unix(req.ArchiveBefore, 0) - recs, err := ctx.EntClient.Attachment.Query(). - Where(attachment.ArchivedEQ(false), attachment.DeletedEQ(false)). - All(ctx0()) - if err != nil { - fail(w, http.StatusInternalServerError, err.Error()) - return - } - moved, marked, failed := 0, 0, 0 - for _, rec := range recs { - if rec.CreatedAt > req.ArchiveBefore { // 仅归档创建时间早于归档截止月(含当月)的附件 - continue - } - if req.DryRun { - marked++ - continue - } - if cfg.ArchiveDir != "" { - src, ok1 := safeAbsPath(root, rec.FilePath) - dst, ok2 := safeAbsPath(cfg.ArchiveDir, rec.FilePath) - if ok1 && ok2 { - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil { - if err := os.Rename(src, dst); err == nil { - moved++ - } else if err := copyFile(src, dst); err == nil { - _ = os.Remove(src) - moved++ - } else { - failed++ - continue - } - } else { - failed++ - continue - } - } else { - failed++ - continue - } - } - if _, err := ctx.EntClient.Attachment.UpdateOneID(rec.ID). - SetArchived(true).SetArchivedAt(timeNow().Unix()).Save(ctx0()); err != nil { - failed++ - continue - } - marked++ - } - if !req.DryRun { - ctx.EventLog.Write(ctx0(), "attachment.archive", r.Header.Get("X-Username"), "attachment", "", - fmt.Sprintf("附件归档:移动%d 标记%d 失败%d(截止月 %d-%02d)", moved, marked, failed, cutMonth.Year(), cutMonth.Month()), - map[string]any{"moved": moved, "marked": marked, "failed": failed}) - } - ok(w, map[string]any{"moved": moved, "marked": marked, "failed": failed, - "archiveBefore": req.ArchiveBefore, "archiveDir": cfg.ArchiveDir, "dryRun": req.DryRun}) - } -} // isInlineExt 判断扩展名是否可在浏览器内联预览(图片 / PDF)。 // 与 MES attachment 包的判定保持一致:只有这类文件才允许 inline,其余一律强制下载, @@ -584,27 +504,6 @@ func isInlineExt(ext string) bool { return false } -// copyFile 兜底复制(跨盘符 Rename 失败时用)。 -func copyFile(src, dst string) error { - in, err := os.Open(src) - if err != nil { - return err - } - defer in.Close() - if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { - return err - } - out, err := os.Create(dst) - if err != nil { - return err - } - if _, err := io.Copy(out, in); err != nil { - _ = out.Close() - return err - } - return out.Close() -} - // StartDiskMonitor 启动磁盘空间监控:每天 DiskCheckHour(默认7点) 检测一次, // 剩余空间 <20% 告警、<10% 提示清理(写日志 + 操作日志,页面顶部同步提示)。 func StartDiskMonitor(ctx *svc.ServiceContext) { @@ -642,8 +541,8 @@ func checkDiskOnce(ctx *svc.ServiceContext) { } // purgeDeletedHandler 物理清理已逻辑删除的附件(需求2): -// 扫描 deleted=true 的索引,删除对应磁盘文件(仅当文件未被归档到 ArchiveDir 时), -// 释放本地空间;索引保留(deleted 标记不变)以便追溯。默认 dryRun 预检,返回将清理数量与释放字节。 +// 扫描 deleted=true 的索引,物理删除对应磁盘文件释放本地空间; +// 索引保留(deleted 标记不变)以便追溯。默认 dryRun 预检,返回将清理数量与释放字节。 // POST /api/attachments/purge-deleted body: { dryRun } func purgeDeletedHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { @@ -660,11 +559,6 @@ func purgeDeletedHandler(ctx *svc.ServiceContext) http.HandlerFunc { } removed, freed, missing, failed := 0, int64(0), 0, 0 for _, rec := range recs { - // 已归档的文件已移至 ArchiveDir,不在本地,跳过 - if rec.Archived { - missing++ - continue - } abs, okp := safeAbsPath(root, rec.FilePath) if !okp { failed++ @@ -697,58 +591,3 @@ func purgeDeletedHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } -// cleanLogsHandler 日志清理(需求2,仅管理员):清理日志目录(Config.Log.Path)下 -// 早于 N 天(默认 30)的 *.log 文件。与 logdaily 自动滚动清理互补,提供手动「立即清理」入口。 -// 默认 dryRun 预检。POST /api/attachments/clean-logs body: { days, dryRun } -func cleanLogsHandler(ctx *svc.ServiceContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req struct { - Days int `json:"days"` - DryRun bool `json:"dryRun"` - } - _ = parseJSON(r, &req) - days := req.Days - if days <= 0 { - days = 30 // 默认保留 30 天 - } - dir := strings.TrimSpace(ctx.Config.Log.Path) - if dir == "" { - dir = "logs" - } - cutoff := timeNow().AddDate(0, 0, -days) - entries, err := os.ReadDir(dir) - if err != nil { - fail(w, http.StatusInternalServerError, "读取日志目录失败: "+err.Error()) - return - } - removed, failed := 0, 0 - for _, e := range entries { - if e.IsDir() || !strings.HasSuffix(e.Name(), ".log") { - continue - } - info, ierr := e.Info() - if ierr != nil { - continue - } - // 按文件名日期(base-2006-01-02.log)或修改时间判定,早于 cutoff 才清 - if !info.ModTime().Before(cutoff) { - continue - } - if req.DryRun { - removed++ - continue - } - if err := os.Remove(filepath.Join(dir, e.Name())); err != nil { - failed++ - continue - } - removed++ - } - if !req.DryRun { - ctx.EventLog.Write(ctx0(), "system.cleanlog", r.Header.Get("X-Username"), "log", dir, - fmt.Sprintf("清理日志:删除%d 个早于%d天的日志文件,失败%d", removed, days, failed), - map[string]any{"removed": removed, "failed": failed, "days": days}) - } - ok(w, map[string]any{"removed": removed, "failed": failed, "days": days, "dir": dir, "dryRun": req.DryRun}) - } -} diff --git a/bj_power_wms/internal/handler/backup.go b/bj_power_wms/internal/handler/backup.go new file mode 100644 index 0000000..e171f13 --- /dev/null +++ b/bj_power_wms/internal/handler/backup.go @@ -0,0 +1,197 @@ +package handler + +import ( + "net/http" + "strconv" + + "bj_power_wms/internal/backup" + "bj_power_wms/internal/svc" +) + +// backupItemsHandler GET /api/backup/items 可选数据项(质量 4 表不出现) +func backupItemsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + ok(w, ctx.Backup.ListItems()) + } +} + +// backupStartHandler POST /api/backup/start 启动备份(流式写入选定目标路径) +func backupStartHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + TargetPath string `json:"targetPath"` + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + } + if err := parseJSON(r, &req); err != nil { + fail(w, http.StatusBadRequest, "请求体解析失败:"+err.Error()) + return + } + jobID, err := ctx.Backup.StartBackup(backup.BackupRequest{ + TargetPath: req.TargetPath, + Start: req.Start, + End: req.End, + Items: req.Items, + Operator: r.Header.Get("X-Username"), + }) + if err != nil { + fail(w, http.StatusBadRequest, err.Error()) + return + } + ok(w, map[string]any{"jobId": jobID}) + } +} + +// backupProgressHandler GET /api/backup/progress?jobId= +func backupProgressHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + jobID := r.URL.Query().Get("jobId") + p, found := ctx.Backup.Progress(jobID) + if !found { + fail(w, http.StatusNotFound, "任务不存在") + return + } + ok(w, p) + } +} + +// cleanupCheckHandler POST /api/cleanup/check 覆盖预检(部分/无覆盖拒绝) +func cleanupCheckHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + Start int64 `json:"start"` + End int64 `json:"end"` + } + if err := parseJSON(r, &req); err != nil { + fail(w, http.StatusBadRequest, "请求体解析失败:"+err.Error()) + return + } + cov, err := ctx.Backup.CheckCoverage(req.Start, req.End) + if err != nil { + fail(w, http.StatusInternalServerError, err.Error()) + return + } + ok(w, cov) + } +} + +// cleanupStartHandler POST /api/cleanup/start 启动清理(物理删除) +func cleanupStartHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + } + if err := parseJSON(r, &req); err != nil { + fail(w, http.StatusBadRequest, "请求体解析失败:"+err.Error()) + return + } + jobID, err := ctx.Backup.StartCleanup(backup.CleanupRequest{ + Start: req.Start, + End: req.End, + Items: req.Items, + Operator: r.Header.Get("X-Username"), + }) + if err != nil { + fail(w, http.StatusBadRequest, err.Error()) + return + } + ok(w, map[string]any{"jobId": jobID}) + } +} + +// cleanupProgressHandler GET /api/cleanup/progress?jobId= +func cleanupProgressHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + jobID := r.URL.Query().Get("jobId") + p, found := ctx.Backup.Progress(jobID) + if !found { + fail(w, http.StatusNotFound, "任务不存在") + return + } + ok(w, p) + } +} + +// backupDrivesHandler GET /api/backup/drives 列出本机盘符(admin-only,服务端目录选择器) +func backupDrivesHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + drives, err := backup.ListDrives() + if err != nil { + fail(w, http.StatusInternalServerError, "读取盘符失败:"+err.Error()) + return + } + ok(w, drives) + } +} + +// backupListDirHandler GET /api/backup/listdir?path= 列出给定目录的一级子目录 +func backupListDirHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + dirs, err := backup.ListDir(r.URL.Query().Get("path")) + if err != nil { + fail(w, http.StatusInternalServerError, "读取目录失败:"+err.Error()) + return + } + ok(w, dirs) + } +} + +// backupReminderHandler GET /api/backup/reminder 清理提醒(按 backup_record 最近 success + 提醒周期算超期) +func backupReminderHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + days := CfgIntFromSysConfig(ctx, CfgArchiveRemindDays, 7) + res, err := ctx.Backup.Reminder(days) + if err != nil { + fail(w, http.StatusInternalServerError, err.Error()) + return + } + ok(w, res) + } +} + +// cleanupPreviewHandler POST /api/cleanup/preview 清理预览(将删除行数/字节,不落盘) +func cleanupPreviewHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Items []string `json:"items"` + } + if err := parseJSON(r, &req); err != nil { + fail(w, http.StatusBadRequest, "请求体解析失败") + return + } + if req.End <= req.Start { + fail(w, http.StatusBadRequest, "时间窗不合法") + return + } + if len(req.Items) == 0 { + fail(w, http.StatusBadRequest, "请至少选择一个数据项") + return + } + res, err := ctx.Backup.Preview(req.Start, req.End, req.Items) + if err != nil { + fail(w, http.StatusInternalServerError, err.Error()) + return + } + ok(w, res) + } +} + +// backupRecordsHandler GET /api/backup/records 备份/清理历史(分页 50/页) +func backupRecordsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + page, _ := strconv.Atoi(q.Get("page")) + size, _ := strconv.Atoi(q.Get("size")) + res, err := ctx.Backup.ListRecords(page, size, q.Get("status"), q.Get("scope")) + if err != nil { + fail(w, http.StatusInternalServerError, err.Error()) + return + } + ok(w, res) + } +} diff --git a/bj_power_wms/internal/handler/internalapi.go b/bj_power_wms/internal/handler/internalapi.go index 22f9cc6..998cac8 100644 --- a/bj_power_wms/internal/handler/internalapi.go +++ b/bj_power_wms/internal/handler/internalapi.go @@ -1,6 +1,7 @@ package handler import ( + "fmt" "net/http" "sort" "strings" @@ -57,13 +58,72 @@ func internalDisplayHandler(ctx *svc.ServiceContext) http.HandlerFunc { locTotal = n } usedKeys := map[string]bool{} - if invs, e := ctx.EntClient.Inventory.Query().Where(inventory.QuantityGT(0)).All(ctx0()); e == nil { + invs, invErr := ctx.EntClient.Inventory.Query().Where(inventory.QuantityGT(0)).All(ctx0()) + if invErr == nil { for _, iv := range invs { usedKeys[locKey(iv.ZoneCode, iv.ShelfNo, "", "")] = true } } locUsed := len(usedKeys) + // ---- 货架级占用(大屏热力图):每货架在库数量 + 批次行数 + 占用率(位置级口径)---- + // 占用率 = 已占位置数 / 架内位置总数(zones level=4 位置号行计数); + // 已占位置 = 库存 qty>0 按 区域|货架|层|位置 去重。主数据缺 level=4 时 totalPos=0,前端退化为按存量着色。 + type shelfRow struct { + Zone string `json:"zone"` + Shelf string `json:"shelf"` + Name string `json:"name"` + Qty int `json:"qty"` + Batches int `json:"batches"` + Used bool `json:"used"` + UsedPos int `json:"usedPos"` + TotalPos int `json:"totalPos"` + } + shelfTotalPos := map[string]int{} + if z4, e := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4)).All(ctx0()); e == nil { + for _, z := range z4 { + shelfTotalPos[z.ZoneCode+"|"+z.ShelfNo]++ + } + } + posUsedCnt := map[string]int{} + seenPos := map[string]bool{} + if invErr == nil { + for _, iv := range invs { + k := iv.ZoneCode + "|" + iv.ShelfNo + pk := k + "|" + iv.LayerNo + "|" + iv.PositionNo + if !seenPos[pk] { + seenPos[pk] = true + posUsedCnt[k]++ + } + } + } + shelfMap := map[string]*shelfRow{} + shelvesOut := []*shelfRow{} + if zs, e := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(2)).All(ctx0()); e == nil { + for _, z := range zs { + key := z.ZoneCode + "|" + z.Code + r := &shelfRow{Zone: z.ZoneCode, Shelf: z.Code, Name: z.Name, + UsedPos: posUsedCnt[key], TotalPos: shelfTotalPos[key]} + shelfMap[z.ZoneCode+"/"+z.Code] = r + shelvesOut = append(shelvesOut, r) + } + } + if invErr == nil { + for _, iv := range invs { + if r, ok := shelfMap[iv.ZoneCode+"/"+iv.ShelfNo]; ok { + r.Qty += iv.Quantity + r.Batches++ + r.Used = true + } + } + } + sort.Slice(shelvesOut, func(i, j int) bool { + if shelvesOut[i].Zone != shelvesOut[j].Zone { + return shelvesOut[i].Zone < shelvesOut[j].Zone + } + return shelvesOut[i].Shelf < shelvesOut[j].Shelf + }) + // ---- 待处理出入库任务 ---- // 入库待处理 = 入库检未闭环(质量状态 空/未检 且未作废);出库待处理 = 已出库待送达。 pendingInbound := 0 @@ -127,6 +187,7 @@ func internalDisplayHandler(ctx *svc.ServiceContext) http.HandlerFunc { "zoneDetail": zones, "locationUsed": locUsed, "locationTotal": locTotal, + "shelves": shelvesOut, "pendingInbound": pendingInbound, "pendingOutbound": pendingOutbound, "movements": movements, @@ -135,6 +196,147 @@ func internalDisplayHandler(ctx *svc.ServiceContext) http.HandlerFunc { } } +// displayNamedQty 大屏聚合通用行(key/name/qty) +type displayNamedQty struct { + Key int `json:"key"` + Name string `json:"name"` + Qty int `json:"qty"` +} + +// displayTrendRow 近7日出入库趋势行(按天聚合数量) +type displayTrendRow struct { + Day string `json:"day"` + In int `json:"in"` + Out int `json:"out"` +} + +// internalDisplayAnalyticsHandler 库房大屏聚合数据(近7日趋势/物料分类双维度/库龄分档),免登录。 +// 库龄口径(2026-10-27 用户拍板):按入库时间(inventories.created_at)计算「入库至今 N 天」; +// 统计范围 = quantity>0 且状态 在库/锁定 的库存行,按数量加权。 +func internalDisplayAnalyticsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + now := time.Now() + // ---- 近 7 天出入库趋势(按天聚合出库/入库数量,含今天共 7 天)---- + dayStart := now.Truncate(24 * time.Hour) + since := dayStart.AddDate(0, 0, -6) + days := make([]displayTrendRow, 7) + for i := 0; i < 7; i++ { + days[i].Day = since.AddDate(0, 0, i).Format("01-02") + } + dayIndexOf := func(unix int64) int { + d := time.Unix(unix, 0).Truncate(24 * time.Hour).Unix() + return int((d - since.Unix()) / 86400) + } + if rows, e := ctx.EntClient.InboundOrder.Query(). + Where(inboundorder.Voided(false), inboundorder.CreatedAtGTE(since.Unix())).All(ctx0()); e == nil { + for _, o := range rows { + if i := dayIndexOf(o.CreatedAt); i >= 0 && i < 7 { + days[i].In += o.Quantity + } + } + } + if rows, e := ctx.EntClient.OutboundOrder.Query(). + Where(outboundorder.CreatedAtGTE(since.Unix())).All(ctx0()); e == nil { + for _, o := range rows { + if i := dayIndexOf(o.CreatedAt); i >= 0 && i < 7 { + days[i].Out += o.Quantity + } + } + } + + // ---- 物料分类(双维度)+ 库龄分档:一次库存扫描同时聚合 ---- + // 库龄分档阈值来自基础设置 display.age.buckets(默认 30/90/180,基础设置页可改,保存即生效) + ageTh := AgeBucketsFromConfig(ctx) + mm := map[int]int{} // 类型:1结构件/2电气件/3其他 + it := map[int]int{} // 物料类别:1原材料/2半成品/3成品 + age := [4]int{} // 0-a / a+1-b / b+1-c / c+ 天 + if invs, e := ctx.EntClient.Inventory.Query(). + Where(inventory.QuantityGT(0), inventory.StatusIn("在库", "锁定")).All(ctx0()); e == nil { + for _, iv := range invs { + mm[iv.ManageMode] += iv.Quantity + it[iv.Category] += iv.Quantity + ageDays := int((now.Unix() - iv.CreatedAt) / 86400) + switch { + case ageDays <= ageTh[0]: + age[0] += iv.Quantity + case ageDays <= ageTh[1]: + age[1] += iv.Quantity + case ageDays <= ageTh[2]: + age[2] += iv.Quantity + default: + age[3] += iv.Quantity + } + } + } + + ok(w, map[string]any{ + "trend": days, + "manageMode": []displayNamedQty{ + {Key: 1, Name: "结构件", Qty: mm[1]}, + {Key: 2, Name: "电气件", Qty: mm[2]}, + {Key: 3, Name: "其他", Qty: mm[3]}, + }, + "itemType": []displayNamedQty{ + {Key: 1, Name: "原材料", Qty: it[1]}, + {Key: 2, Name: "半成品", Qty: it[2]}, + {Key: 3, Name: "成品", Qty: it[3]}, + }, + "ageBuckets": []displayNamedQty{ + {Name: fmt.Sprintf("0-%d天", ageTh[0]), Qty: age[0]}, + {Name: fmt.Sprintf("%d-%d天", ageTh[0]+1, ageTh[1]), Qty: age[1]}, + {Name: fmt.Sprintf("%d-%d天", ageTh[1]+1, ageTh[2]), Qty: age[2]}, + {Name: fmt.Sprintf("%d天以上", ageTh[2]), Qty: age[3]}, + }, + "time": now.Format("2006-01-02 15:04:05"), + }) + } +} + +// internalDisplayCallsHandler 大屏备料叫料池(免登录):代理 MES 叫料单,只取三个活跃态。 +// 七态口径(MES internal/logic/call.go:33):PENDING 待备料 → SHIPPED 已发货 → DONE 已完成; +// CANCELLED/REJECTED/RETURNING/RETURNED 为分支/退库态,大屏不展示。 +// MES 未配置或不可达时静默降级为空列表(大屏不报错),mesOk=false 供前端提示。 +func internalDisplayCallsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + calls := []map[string]any{} + mesOk := false + if ctx.Mes != nil { + if list, err := ctx.Mes.ListMaterialRequests(r.Context(), ""); err == nil { + mesOk = true + keep := map[string]string{ + "PENDING": "待备料", + "SHIPPED": "配送中", + "DONE": "已送达", + } + for _, m := range list { // MES 已按 created_at desc, id desc 排序(logic/call.go:743) + label, ok2 := keep[m.Status] + if !ok2 { + continue + } + t := "" + if m.CreatedAt != "" { + if tt, e := time.Parse(time.RFC3339, m.CreatedAt); e == nil { + t = tt.Format("15:04") + } + } + mat := m.MaterialName + if mat == "" { + mat = m.MaterialCode + } + calls = append(calls, map[string]any{ + "time": t, "stationNo": m.StationNo, "material": mat, + "qty": m.ReqQty, "status": label, "statusKey": m.Status, + }) + if len(calls) >= 30 { + break + } + } + } + } + ok(w, map[string]any{"calls": calls, "mesOk": mesOk}) + } +} + // materialQueryInternalHandler 物料档案 + 库存查询(看板物料追溯入口复用,X-API-TOKEN 内部接口) // // 入参:code(物料编码,必填)/ batch(批次号,可选)。 diff --git a/bj_power_wms/internal/handler/rbac_admin.go b/bj_power_wms/internal/handler/rbac_admin.go index 356289e..388247d 100644 --- a/bj_power_wms/internal/handler/rbac_admin.go +++ b/bj_power_wms/internal/handler/rbac_admin.go @@ -45,6 +45,9 @@ var seedPermissions = []seedPerm{ {"role:manage", "角色管理", "MENU", "/roles", "Key", 120, ""}, {"eventlog:manage", "操作日志", "MENU", "/event-log", "Clock", 130, ""}, {"attachment:view", "附件中心", "MENU", "/attachment", "Folder", 138, ""}, + {"backup:manage", "数据归档", "MENU", "/data-archive", "Tools", 140, ""}, + {"sys.settings:view", "基础设置", "MENU", "/settings", "Setting", 150, ""}, + {"sys.settings:edit", "保存基础设置", "BUTTON", "", "", 290, "sys.settings:view"}, // ===== 按钮权限 ===== {"inbound:create", "批量入库", "BUTTON", "", "", 200, "inbound:view"}, {"inbound:import", "Excel导入", "BUTTON", "", "", 201, "inbound:view"}, diff --git a/bj_power_wms/internal/handler/routes.go b/bj_power_wms/internal/handler/routes.go index c613984..a2d69de 100644 --- a/bj_power_wms/internal/handler/routes.go +++ b/bj_power_wms/internal/handler/routes.go @@ -221,10 +221,8 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) { // 附件中心(系统管理 → 附件中心) {Method: http.MethodGet, Path: "/api/attachments/all", Handler: requirePerm(ctx, "attachment:view", listAllAttachmentsHandler(ctx))}, {Method: http.MethodGet, Path: "/api/attachments/disk-status", Handler: requirePerm(ctx, "attachment:view", diskStatusHandler(ctx))}, - {Method: http.MethodPost, Path: "/api/attachments/archive", Handler: requirePerm(ctx, "attachment:manage", archiveAttachmentsHandler(ctx))}, - // 空间清理(需求2):物理清理已删附件归 attachment:manage;日志清理仅管理员 + // 空间清理(需求2):物理清理已删附件归 attachment:manage {Method: http.MethodPost, Path: "/api/attachments/purge-deleted", Handler: requirePerm(ctx, "attachment:manage", purgeDeletedHandler(ctx))}, - {Method: http.MethodPost, Path: "/api/attachments/clean-logs", Handler: requireAdmin(cleanLogsHandler(ctx))}, }, ) @@ -232,9 +230,39 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) { server.AddRoutes( []rest.Route{ {Method: http.MethodGet, Path: "/api/display/overview", Handler: internalDisplayHandler(ctx)}, + {Method: http.MethodGet, Path: "/api/display/analytics", Handler: internalDisplayAnalyticsHandler(ctx)}, + {Method: http.MethodGet, Path: "/api/display/calls", Handler: internalDisplayCallsHandler(ctx)}, + {Method: http.MethodGet, Path: "/api/display/config", Handler: displayConfigHandler(ctx)}, }, ) + // 数据归档(系统管理 → 备份到 U 盘 / 腾空间):仅管理员。 + // 备份=流式导出到外部存储并记 backup_record;清理=物理删除(严格覆盖校验,不可逆)。 + server.AddRoutes( + []rest.Route{ + {Method: http.MethodGet, Path: "/api/backup/items", Handler: requireAdmin(backupItemsHandler(ctx))}, + {Method: http.MethodPost, Path: "/api/backup/start", Handler: requireAdmin(backupStartHandler(ctx))}, + {Method: http.MethodGet, Path: "/api/backup/progress", Handler: requireAdmin(backupProgressHandler(ctx))}, + {Method: http.MethodPost, Path: "/api/cleanup/check", Handler: requireAdmin(cleanupCheckHandler(ctx))}, + {Method: http.MethodPost, Path: "/api/cleanup/start", Handler: requireAdmin(cleanupStartHandler(ctx))}, + {Method: http.MethodGet, Path: "/api/cleanup/progress", Handler: requireAdmin(cleanupProgressHandler(ctx))}, + // 数据归档增强:目录选择器 / 提醒 / 预览 / 历史 + {Method: http.MethodGet, Path: "/api/backup/drives", Handler: requireAdmin(backupDrivesHandler(ctx))}, + {Method: http.MethodGet, Path: "/api/backup/listdir", Handler: requireAdmin(backupListDirHandler(ctx))}, + {Method: http.MethodGet, Path: "/api/backup/reminder", Handler: requireAdmin(backupReminderHandler(ctx))}, + {Method: http.MethodPost, Path: "/api/cleanup/preview", Handler: requireAdmin(cleanupPreviewHandler(ctx))}, + {Method: http.MethodGet, Path: "/api/backup/records", Handler: requireAdmin(backupRecordsHandler(ctx))}, + }, +) + +// 系统基础设置(admin-only):保存即生效,无需重启。 +server.AddRoutes( + []rest.Route{ + {Method: http.MethodGet, Path: "/api/settings", Handler: requireAdmin(SettingsHandler(ctx))}, + {Method: http.MethodPut, Path: "/api/settings", Handler: requireAdmin(SaveSettingsHandler(ctx))}, + }, +) + // 项目间内部 API(X-API-TOKEN 写死 token 保护) // 与 JWT 侧业务接口同实现,仅供 MES(B)/工位终端(D) 等服务间调用 server.AddRoutes( @@ -261,8 +289,8 @@ func RegisterHandlers(server *rest.Server, ctx *svc.ServiceContext) { {Method: http.MethodGet, Path: "/api/internal/materials", Handler: wrapInternal(ctx)(queryMaterialsHandler(ctx))}, {Method: http.MethodGet, Path: "/api/internal/material/list-all", Handler: wrapInternal(ctx)(listMaterialsHandler(ctx))}, {Method: http.MethodPost, Path: "/api/internal/return-order", Handler: wrapInternal(ctx)(createReturnOrderInternalHandler(ctx))}, - // MES 质量检验(过程检/完工检)判不合格 → 联动 WMS 在库处置(按物料+SN/批次定位库存行) - {Method: http.MethodPost, Path: "/api/internal/inventory/dispose", Handler: wrapInternal(ctx)(internalInventoryDisposeHandler(ctx))}, - }, - ) + // MES 质量检验(过程检/完工检)判不合格 → 联动 WMS 在库处置(按物料+SN/批次定位库存行) + {Method: http.MethodPost, Path: "/api/internal/inventory/dispose", Handler: wrapInternal(ctx)(internalInventoryDisposeHandler(ctx))}, + }, +) } diff --git a/bj_power_wms/internal/handler/settings.go b/bj_power_wms/internal/handler/settings.go new file mode 100644 index 0000000..79d721e --- /dev/null +++ b/bj_power_wms/internal/handler/settings.go @@ -0,0 +1,231 @@ +package handler + +import ( + "net/http" + "strconv" + "strings" + + "bj_power_wms/ent/sysconfig" + "bj_power_wms/internal/svc" +) + +// WMS 基础设置配置键(sys_config 表,系统管理员「基础设置」页维护,保存即生效)。 +const ( + CfgArchiveRemindDays = "archive.remind.days" // 数据归档提醒周期(天,0=关闭) + CfgArchiveBackupPath = "archive.backup.path" // 备份默认目标路径(记住上次成功路径) + CfgLocationRule = "location.recommend.rule" // 库位推荐规则:last=上次位置优先 / same_shelf=同货架优先 + CfgInboundOrderPrefix = "inbound.order.prefix" // 入库单默认前缀/流水规则 + CfgAttachmentMaxSize = "attachment.max.size.hint" // 附件单文件大小上限提示(MB) + // 库存大屏(/display)配置组(2026-10-27:大屏相关配置进基础设置) + CfgDisplayStockTitle = "display.stock.title" // 大屏主标题 + CfgDisplayStockCorner = "display.stock.corner" // 大屏左上角角标文案 + CfgDisplayStockRefresh = "display.stock.refresh" // 概览刷新间隔(秒) + CfgDisplayCallsRefresh = "display.calls.refresh" // 备料叫料池刷新间隔(秒) + CfgDisplayAgeBuckets = "display.age.buckets" // 库龄分档阈值(天,逗号分隔 3 档,升序) +) + +var wmsSettingsDefaults = map[string]string{ + CfgArchiveRemindDays: "7", + CfgArchiveBackupPath: "", + CfgLocationRule: "last", + CfgInboundOrderPrefix: "", + CfgAttachmentMaxSize: "50", + CfgDisplayStockTitle: "库存动态大屏", + CfgDisplayStockCorner: "库房监控", + CfgDisplayStockRefresh: "5", + CfgDisplayCallsRefresh: "10", + CfgDisplayAgeBuckets: "30,90,180", +} + +// SettingsVO WMS 基础设置视图(保存即生效)。 +type SettingsVO struct { + ArchiveRemindDays int `json:"archiveRemindDays"` // 数据归档提醒周期(天,0=关闭) + ArchiveBackupPath string `json:"archiveBackupPath"` // 备份默认目标路径 + LocationRule string `json:"locationRule"` // 库位推荐规则 + InboundOrderPrefix string `json:"inboundOrderPrefix"` // 入库单默认前缀 + AttachmentMaxSize int `json:"attachmentMaxSize"` // 附件单文件大小上限提示(MB) + DisplayStockTitle string `json:"displayStockTitle"` // 库存大屏主标题 + DisplayStockCorner string `json:"displayStockCorner"` // 库存大屏左上角角标文案 + DisplayStockRefresh int `json:"displayStockRefresh"` // 库存大屏概览刷新间隔(秒) + DisplayCallsRefresh int `json:"displayCallsRefresh"` // 备料叫料池刷新间隔(秒) + DisplayAgeBuckets string `json:"displayAgeBuckets"` // 库龄分档阈值(天,逗号分隔 3 档) +} + +func cfgStr(kv map[string]string, key, def string) string { + if v, ok := kv[key]; ok && strings.TrimSpace(v) != "" { + return v + } + return def +} + +func cfgInt(kv map[string]string, key string, def int) int { + v := cfgStr(kv, key, strconv.Itoa(def)) + n, err := strconv.Atoi(v) + if err != nil { + return def + } + return n +} + +func loadSettingsKV(ctx *svc.ServiceContext) map[string]string { + kv := map[string]string{} + if rows, err := ctx.EntClient.SysConfig.Query().All(ctx0()); err == nil { + for _, r := range rows { + kv[r.Key] = r.Value + } + } + return kv +} + +// CfgIntFromSysConfig 读取整型配置(未配置/非法回退 def),供提醒等模块复用。 +func CfgIntFromSysConfig(ctx *svc.ServiceContext, key string, def int) int { + kv := loadSettingsKV(ctx) + return cfgInt(kv, key, def) +} + +// SettingsHandler GET /api/settings 基础设置(admin-only) +func SettingsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + kv := loadSettingsKV(ctx) + vo := SettingsVO{ + ArchiveRemindDays: cfgInt(kv, CfgArchiveRemindDays, 7), + ArchiveBackupPath: cfgStr(kv, CfgArchiveBackupPath, ""), + LocationRule: cfgStr(kv, CfgLocationRule, "last"), + InboundOrderPrefix: cfgStr(kv, CfgInboundOrderPrefix, ""), + AttachmentMaxSize: cfgInt(kv, CfgAttachmentMaxSize, 50), + DisplayStockTitle: cfgStr(kv, CfgDisplayStockTitle, wmsSettingsDefaults[CfgDisplayStockTitle]), + DisplayStockCorner: cfgStr(kv, CfgDisplayStockCorner, wmsSettingsDefaults[CfgDisplayStockCorner]), + DisplayStockRefresh: cfgInt(kv, CfgDisplayStockRefresh, 5), + DisplayCallsRefresh: cfgInt(kv, CfgDisplayCallsRefresh, 10), + DisplayAgeBuckets: cfgStr(kv, CfgDisplayAgeBuckets, wmsSettingsDefaults[CfgDisplayAgeBuckets]), + } + ok(w, vo) + } +} + +// SaveSettingsHandler PUT /api/settings 保存基础设置(admin-only) +func SaveSettingsHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req SettingsVO + if err := parseJSON(r, &req); err != nil { + fail(w, http.StatusBadRequest, "请求体解析失败") + return + } + if req.ArchiveRemindDays < 0 || req.ArchiveRemindDays > 365 { + fail(w, http.StatusBadRequest, "提醒周期需 0~365 天") + return + } + if req.AttachmentMaxSize <= 0 || req.AttachmentMaxSize > 1024 { + fail(w, http.StatusBadRequest, "附件单文件大小上限提示需 1~1024 MB") + return + } + if req.LocationRule != "last" && req.LocationRule != "same_shelf" { + fail(w, http.StatusBadRequest, "库位推荐规则仅支持 last(上次位置优先)/ same_shelf(同货架优先)") + return + } + title := strings.TrimSpace(req.DisplayStockTitle) + if title == "" || len(title) > 60 { + fail(w, http.StatusBadRequest, "库存大屏主标题需 1~60 字") + return + } + corner := strings.TrimSpace(req.DisplayStockCorner) + if len(corner) > 30 { + fail(w, http.StatusBadRequest, "库存大屏角标文案需 0~30 字") + return + } + if req.DisplayStockRefresh < 3 || req.DisplayStockRefresh > 120 { + fail(w, http.StatusBadRequest, "库存大屏概览刷新间隔需 3~120 秒") + return + } + if req.DisplayCallsRefresh < 5 || req.DisplayCallsRefresh > 300 { + fail(w, http.StatusBadRequest, "备料叫料池刷新间隔需 5~300 秒") + return + } + buckets := parseAgeBuckets(req.DisplayAgeBuckets) + if buckets == nil { + fail(w, http.StatusBadRequest, "库龄分档阈值需为逗号分隔的 3 个升序天数(如 30,90,180),各档 1~3650") + return + } + kv := map[string]string{ + CfgArchiveRemindDays: strconv.Itoa(req.ArchiveRemindDays), + CfgArchiveBackupPath: strings.TrimSpace(req.ArchiveBackupPath), + CfgLocationRule: req.LocationRule, + CfgInboundOrderPrefix: strings.TrimSpace(req.InboundOrderPrefix), + CfgAttachmentMaxSize: strconv.Itoa(req.AttachmentMaxSize), + CfgDisplayStockTitle: title, + CfgDisplayStockCorner: corner, + CfgDisplayStockRefresh: strconv.Itoa(req.DisplayStockRefresh), + CfgDisplayCallsRefresh: strconv.Itoa(req.DisplayCallsRefresh), + CfgDisplayAgeBuckets: strconv.Itoa(buckets[0]) + "," + strconv.Itoa(buckets[1]) + "," + strconv.Itoa(buckets[2]), + } + for k, v := range kv { + if err := upsertConfig(ctx, k, v, ""); err != nil { + fail(w, http.StatusInternalServerError, err.Error()) + return + } + } + ok(w, map[string]any{"ok": true}) + } +} + +// parseAgeBuckets 解析库龄分档阈值 "30,90,180" → [30 90 180];非法返回 nil。 +func parseAgeBuckets(s string) []int { + parts := strings.Split(s, ",") + if len(parts) != 3 { + return nil + } + out := make([]int, 3) + for i, p := range parts { + n, err := strconv.Atoi(strings.TrimSpace(p)) + if err != nil || n < 1 || n > 3650 { + return nil + } + out[i] = n + } + if out[0] >= out[1] || out[1] >= out[2] { + return nil + } + return out +} + +// AgeBucketsFromConfig 读库龄分档配置(非法回退默认 30/90/180),供大屏聚合接口用。 +func AgeBucketsFromConfig(ctx *svc.ServiceContext) []int { + if b := parseAgeBuckets(cfgStr(loadSettingsKV(ctx), CfgDisplayAgeBuckets, "30,90,180")); b != nil { + return b + } + return []int{30, 90, 180} +} + +// DisplayConfigVO 库存大屏运行配置(免登录只读,仅展示性配置,不含敏感信息)。 +type DisplayConfigVO struct { + Title string `json:"title"` // 大屏主标题 + Corner string `json:"corner"` // 左上角角标文案 + RefreshSeconds int `json:"refreshSeconds"` // 概览刷新间隔(秒) + CallsRefreshSeconds int `json:"callsRefreshSeconds"` // 备料叫料池刷新间隔(秒) + AgeBuckets []int `json:"ageBuckets"` // 库龄分档阈值(天,3 档升序) +} + +// displayConfigHandler GET /api/display/config 大屏运行配置(免登录,与 overview 同组)。 +func displayConfigHandler(ctx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + kv := loadSettingsKV(ctx) + ok(w, DisplayConfigVO{ + Title: cfgStr(kv, CfgDisplayStockTitle, wmsSettingsDefaults[CfgDisplayStockTitle]), + Corner: cfgStr(kv, CfgDisplayStockCorner, wmsSettingsDefaults[CfgDisplayStockCorner]), + RefreshSeconds: cfgInt(kv, CfgDisplayStockRefresh, 5), + CallsRefreshSeconds: cfgInt(kv, CfgDisplayCallsRefresh, 10), + AgeBuckets: AgeBucketsFromConfig(ctx), + }) + } +} + +// upsertConfig 幂等写入配置(sys_config key/value)。 +func upsertConfig(ctx *svc.ServiceContext, key, value, remark string) error { + exist, err := ctx.EntClient.SysConfig.Query().Where(sysconfig.Key(key)).Only(ctx0()) + if err == nil && exist != nil { + _, e := exist.Update().SetValue(value).SetRemark(remark).Save(ctx0()) + return e + } + _, e := ctx.EntClient.SysConfig.Create().SetKey(key).SetValue(value).SetRemark(remark).Save(ctx0()) + return e +} diff --git a/bj_power_wms/internal/handler/zone.go b/bj_power_wms/internal/handler/zone.go index f7a7f3d..e54ac68 100644 --- a/bj_power_wms/internal/handler/zone.go +++ b/bj_power_wms/internal/handler/zone.go @@ -123,8 +123,29 @@ func listZonesHandler(ctx *svc.ServiceContext) http.HandlerFunc { } list := make([]zoneNodeVO, 0, len(rows)) byZone, byShelf, byLayer, byPos, byUnshelved := zoneStockMaps(ctx) + // 区域名称回填:zone_name 冗余字段仅 level1 区域行有值;子层级(货架/层/位置号)按 zone_code 反查所属区域名称。 + zoneNameByCode := map[string]string{} + zcKeys := make([]string, 0) + for _, z := range rows { + if z.Level != zoneLevelRegion && z.ZoneCode != "" { + k := strings.ToUpper(strings.TrimSpace(z.ZoneCode)) + if _, ok := zoneNameByCode[k]; !ok { + zcKeys = append(zcKeys, k) + } + } + } + if len(zcKeys) > 0 { + if regs, err := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(zoneLevelRegion), zone.CodeIn(zcKeys...)).All(ctx0()); err == nil { + for _, rg := range regs { + zoneNameByCode[strings.ToUpper(strings.TrimSpace(rg.Code))] = rg.Name + } + } + } for _, z := range rows { vo := toZoneNodeVO(z) + if z.Level != zoneLevelRegion { + vo.ZoneName = zoneNameByCode[strings.ToUpper(strings.TrimSpace(z.ZoneCode))] + } zc := strings.ToLower(strings.TrimSpace(z.ZoneCode)) sh := strings.ToLower(strings.TrimSpace(z.ShelfNo)) ly := strings.TrimSpace(z.LayerNo) @@ -340,6 +361,7 @@ func createZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc { type zoneNodeUpdateReq struct { ID int `json:"id"` + Code string `json:"code"` // 仅 level=4 位置号允许改编码;货架/层/区域忽略(避免级联子节点与库存的破坏性重命名) Name string `json:"name"` Remark string `json:"remark"` Status string `json:"status"` @@ -371,18 +393,59 @@ func updateZoneNodeHandler(ctx *svc.ServiceContext) http.HandlerFunc { fail(w, http.StatusBadRequest, "状态取值非法") return } + // 位置号(level4)放开编辑:允许改编码(支持字符串,如 P-01);同步冗余 position_no 并级联库存,避免库存挂空。 + // 货架/层/区域编码维持不可改(重命名会级联全部子节点+库存,破坏性,需单独裁决)。 + renamedCode := "" + if z.Level == zoneLevelPos { + newCode := strings.ToUpper(strings.TrimSpace(req.Code)) + if newCode == "" { + fail(w, http.StatusBadRequest, "位置号必填") + return + } + if newCode != z.Code { + dup, _ := ctx.EntClient.Zone.Query(). + Where(zone.LevelEQ(zoneLevelPos), zone.ZoneCodeEQ(z.ZoneCode), + zone.ShelfNoEQ(z.ShelfNo), zone.LayerNoEQ(z.LayerNo), + zone.CodeEQ(newCode), zone.Not(zone.IDEQ(z.ID))).Exist(ctx0()) + if dup { + fail(w, http.StatusConflict, "该位置号已存在:"+newCode) + return + } + renamedCode = newCode + } + } upd := ctx.EntClient.Zone.UpdateOneID(req.ID).SetStatus(status). SetName(strings.TrimSpace(req.Name)). SetNillableDescription(strPtr(strings.TrimSpace(req.Remark))) + if renamedCode != "" { + upd.SetCode(renamedCode).SetNillablePositionNo(strPtr(renamedCode)) + } if z.Level == 1 { upd.SetZoneName(strings.TrimSpace(req.Name)) // 区域名称冗余同步 } + // 位置号重命名:先级联库存 position_no(用旧码定位→新码),再落库 zone,保证库存不挂空。 + if renamedCode != "" { + if _, err := ctx.EntClient.Inventory.Update(). + Where(inventory.ZoneCodeEQ(z.ZoneCode), inventory.ShelfNoEQ(z.ShelfNo), + inventory.LayerNoEQ(z.LayerNo), inventory.PositionNoEQ(z.Code)). + SetPositionNo(renamedCode).Save(ctx0()); err != nil { + fail(w, http.StatusInternalServerError, "级联更新库存位置号失败: "+err.Error()) + return + } + } if _, err := upd.Save(ctx0()); err != nil { fail(w, http.StatusInternalServerError, err.Error()) return } - ctx.EventLog.Write(ctx0(), "zone.update", r.Header.Get("X-Username"), "zone", z.Code, - "编辑"+zoneLevelName(z.Level)+" "+z.Code, nil) + finalCode := z.Code + if renamedCode != "" { + finalCode = renamedCode + } + logMsg := "编辑" + zoneLevelName(z.Level) + " " + finalCode + if renamedCode != "" { + logMsg = "位置号更名 " + z.Code + " → " + renamedCode + "(已级联库存 position_no)" + } + ctx.EventLog.Write(ctx0(), "zone.update", r.Header.Get("X-Username"), "zone", finalCode, logMsg, nil) ok(w, map[string]any{"id": req.ID}) } } @@ -509,7 +572,7 @@ type zoneBatchGenReq struct { ShelfNo string `json:"shelfNo"` LayerStart int `json:"layerStart"` // level=3 批量生成层:层范围起 LayerEnd int `json:"layerEnd"` // level=3 批量生成层:层范围止 - LayerNo string `json:"layerNo"` // level=4 批量生成位置号:层号(放开字母+数字,层节点不存在时自动创建) + LayerNo string `json:"layerNo"` // level=4 批量生成位置号:层号(必须为已存在的层) PosStart int `json:"posStart"` PosEnd int `json:"posEnd"` Count int `json:"count"` // level=4 批量生成位置号:生成数量(从「该层最大位置号+1」起连续生成) @@ -623,27 +686,25 @@ func batchGenerateHandler(ctx *svc.ServiceContext) http.HandlerFunc { return } - // ---------- level=4:批量生成位置号(层号放开字母+数字,按最近编码序号+1 生成 N 个) ---------- - layerNo := strings.ToUpper(strings.TrimSpace(req.LayerNo)) - if layerNo == "" { - fail(w, http.StatusBadRequest, "请填写层号") - return - } - if req.Count <= 0 { - fail(w, http.StatusBadRequest, "请填写生成数量(≥1)") - return - } - if req.Count > 2000 { - fail(w, http.StatusBadRequest, "一次最多生成 2000 个位置,请缩小数量") - return - } - // 层号放开:该层节点不存在则自动创建(作为位置号的父级) - if exist, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(3), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.CodeEQ(layerNo)).Exist(ctx0()); !exist { - if _, err := ctx.EntClient.Zone.Create().SetLevel(3).SetCode(layerNo).SetParentCode(req.ShelfNo).SetZoneCode(zoneCode).SetShelfNo(req.ShelfNo).SetLayerNo(layerNo).SetName(req.ShelfNo + "架" + layerNo + "层").SetStatus("启用").Save(ctx0()); err != nil { - fail(w, http.StatusInternalServerError, "自动创建层失败: "+err.Error()) - return - } - } + // ---------- level=4:批量生成位置号(必须选已存在的层,按最近编码序号+1 生成 N 个) ---------- + layerNo := strings.ToUpper(strings.TrimSpace(req.LayerNo)) + if layerNo == "" { + fail(w, http.StatusBadRequest, "请选择具体的层") + return + } + if req.Count <= 0 { + fail(w, http.StatusBadRequest, "请填写生成数量(≥1)") + return + } + if req.Count > 2000 { + fail(w, http.StatusBadRequest, "一次最多生成 2000 个位置,请缩小数量") + return + } + // 层级字段用下拉选择,层必须已存在;不存在则报错,不自动创建 + if exist, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(3), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.CodeEQ(layerNo)).Exist(ctx0()); !exist { + fail(w, http.StatusBadRequest, "层不存在,请先在层管理里创建") + return + } // 最近编码序号:该层下已存在的最大位置号(按整数解析,非整数忽略) maxNo := 0 cur, _ := ctx.EntClient.Zone.Query().Where(zone.LevelEQ(4), zone.ZoneCodeEQ(zoneCode), zone.ShelfNoEQ(req.ShelfNo), zone.LayerNoEQ(layerNo)).All(ctx0()) diff --git a/bj_power_wms/internal/mesclient/client.go b/bj_power_wms/internal/mesclient/client.go index c1c7d19..8aa78fc 100644 --- a/bj_power_wms/internal/mesclient/client.go +++ b/bj_power_wms/internal/mesclient/client.go @@ -53,6 +53,7 @@ type MaterialRequest struct { OutboundNo string `json:"outboundNo"` RejectReason string `json:"rejectReason"` Operator string `json:"operator"` + CreatedAt string `json:"createdAt"` // RFC3339(MES ent 序列化),大屏叫料池显示 HH:MM 用 } // ListMaterialRequests 拉取备料单(含 target_dock) diff --git a/bj_power_wms/internal/svc/service_context.go b/bj_power_wms/internal/svc/service_context.go index a5ed48a..2ee7f69 100644 --- a/bj_power_wms/internal/svc/service_context.go +++ b/bj_power_wms/internal/svc/service_context.go @@ -4,6 +4,7 @@ import ( "strings" "bj_power_wms/ent" + "bj_power_wms/internal/backup" "bj_power_wms/internal/config" "bj_power_wms/internal/db" "bj_power_wms/internal/eventlog" @@ -15,6 +16,7 @@ type ServiceContext struct { EntClient *ent.Client EventLog *eventlog.Writer Mes *mesclient.Client + Backup *backup.Service } func NewServiceContext(c config.Config) *ServiceContext { @@ -52,6 +54,9 @@ func NewServiceContext(c config.Config) *ServiceContext { EntClient: entClient, EventLog: eventlog.NewWriter(entClient), Mes: mesclient.New(c.Mes.BaseURL, c.Mes.Token), + // 备份/清理:attRoot 用 WMS 附件根目录;sibling 为 MES 内部接口地址与 token, + // 用于清理共享附件目录前跨库确认对端已备份(fail-closed)。 + Backup: backup.New(entClient, eventlog.NewWriter(entClient), c.Attachment.RootDir), } } diff --git a/bj_power_wms/schema/backup_record.go b/bj_power_wms/schema/backup_record.go new file mode 100644 index 0000000..f0e45d7 --- /dev/null +++ b/bj_power_wms/schema/backup_record.go @@ -0,0 +1,49 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// BackupRecord 备份记录:每次「备份到外部存储(U盘/移动硬盘)」写一条。 +// 清理前校验 backup_record 对该时间窗的完整覆盖,覆盖不全则拒绝清理。 +// +// 时间字段统一用 Int64 unix 秒(与 MES 端一致,便于跨库覆盖比较)。 +type BackupRecord struct { + ent.Schema +} + +func (BackupRecord) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Annotation{Table: "backup_record"}, + entsql.WithComments(true), + schema.Comment("BackupRecord 备份记录:备份到外部存储写一条,清理前校验时间窗覆盖"), + } +} + +func (BackupRecord) Fields() []ent.Field { + return []ent.Field{ + field.Int64("executed_at").DefaultFunc(nowUnix).Comment("备份执行时刻(unix秒)"), + field.Int64("range_start").Comment("备份范围开始(unix秒,含)"), + field.Int64("range_end").Comment("备份范围结束(unix秒,含)"), + field.String("backup_path").Comment("备份包(zip)在目标盘的完整路径"), + field.Int64("total_size").Default(0).Comment("备份包总字节数"), + // 各数据项及大小:[{name,rows,bytes}] + field.String("items_json").Comment("各数据项及大小(JSON数组:[{name,rows,bytes}])"), + field.String("status").Default("success").MaxLen(16).Comment("success/failed/partial"), + field.String("operator").Default("").MaxLen(64).Comment("操作人"), + field.String("checksum").Default("").MaxLen(64).Comment("备份包校验和(sha256,基于 manifest)"), + field.String("scope").Default("wms").MaxLen(8).Comment("写入方 mes/wms"), + } +} + +func (BackupRecord) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("range_start"), + index.Fields("range_end"), + index.Fields("status"), + } +} diff --git a/bj_power_wms/schema/sys_config.go b/bj_power_wms/schema/sys_config.go new file mode 100644 index 0000000..ea0887e --- /dev/null +++ b/bj_power_wms/schema/sys_config.go @@ -0,0 +1,27 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// SysConfig 系统基础设置(key/value)。 +// 系统管理员「基础设置」页维护,保存即生效(无需重启);敏感信息(JWT secret、 +// 内部 Token、数据库密码)仍留在 etc/*.yaml,不进本表。 +type SysConfig struct { + ent.Schema +} + +func (SysConfig) Annotations() []schema.Annotation { + return []schema.Annotation{entsql.Annotation{Table: "sys_config"}, entsql.WithComments(true), schema.Comment("SysConfig 系统基础设置(key/value)。")} +} + +func (SysConfig) Fields() []ent.Field { + return []ent.Field{ + field.String("key").Unique().MaxLen(64).Comment("配置键,如 wms.base_url"), + field.String("value").MaxLen(512).Comment("配置值"), + field.String("remark").Optional().MaxLen(255).Comment("说明"), + } +} diff --git a/bj_power_wms/web/static/index.html b/bj_power_wms/web/static/index.html index 282f654..0fac3ac 100644 --- a/bj_power_wms/web/static/index.html +++ b/bj_power_wms/web/static/index.html @@ -6,8 +6,8 @@ WMS库房管理 - - + +
diff --git a/bj_power_workstation/frontend/src/api/index.js b/bj_power_workstation/frontend/src/api/index.js index 7493cc1..25ce6ef 100644 --- a/bj_power_workstation/frontend/src/api/index.js +++ b/bj_power_workstation/frontend/src/api/index.js @@ -75,7 +75,7 @@ export const occupyLinePoint = (data) => request.post('/api/line/occupy', data) // 叫料池(本工位物料行四数:需求/调整/已发/占用/可用) export const callPool = (params) => request.get('/api/call/pool', { params }) -// 接驳台列表(本工位 R1/R2 下拉用) +// 接驳台列表(本工位 左L/右R 下拉用) export const listDocks = (params) => request.get('/api/docks', { params }) // 发起叫料:{stationNo, items:[{materialCode, qty, dock?}]} → 按物料行拆 N 张单(占用池子可用量) diff --git a/bj_power_workstation/frontend/src/store/station.js b/bj_power_workstation/frontend/src/store/station.js index a6550b4..beffa98 100644 --- a/bj_power_workstation/frontend/src/store/station.js +++ b/bj_power_workstation/frontend/src/store/station.js @@ -108,7 +108,7 @@ export const myPoint = computed(() => state.points.find((p) => p.pointType === 'STATION' && String(p.pointNo) === String(state.stationNo)) ) export const myPointSn = computed(() => (myPoint.value?.occupied ? myPoint.value.currentSn : '')) -// 本工位接驳台(AGV 点位,工位 1~10 各 R1/R2) +// 本工位接驳台(AGV 点位,工位 1~10 各 左L/右R) export const myDocks = computed(() => state.points.filter((p) => p.pointType === 'DOCK' && Number(p.stationNo) === Number(state.stationNo)) ) diff --git a/bj_power_workstation/internal/config/config.go b/bj_power_workstation/internal/config/config.go index 2fe3326..db29884 100644 --- a/bj_power_workstation/internal/config/config.go +++ b/bj_power_workstation/internal/config/config.go @@ -32,7 +32,7 @@ type SqliteConfig struct { // 一个工位一个终端,终端不允许修改工位;变更工位只能改配置并重启服务。 type StationConfig struct { StationNo int `json:",default=1"` // 固定工位号,启动时校验范围 - Dock string `json:",default=R1"` // 固定本工位接驳台(AGV 点位),叫料自动送达;工人不可选,仅运维改配置后重启生效 + Dock string `json:",default="` // 固定本工位接驳台(AGV 点位编码,如 DOCK01;产线命名 左L/右R),叫料自动送达;工人不可选,仅运维改配置后重启生效。留空=未配置,叫料未选接驳台时明确报错 // 核实4:空闲无操作自动登出阈值(秒)。超时清登录态并失效 Bearer 凭证, // 强制下一班/换班操作工重新登录,避免共享终端身份错位(张三未登出、李四直接用)。 // 应小于登录 JWT 有效期(AccessExpire),才能真正先于令牌过期拦截"忘了登出"的场景。 diff --git a/bj_power_workstation/internal/handler/line.go b/bj_power_workstation/internal/handler/line.go index 7568e65..5fcd540 100644 --- a/bj_power_workstation/internal/handler/line.go +++ b/bj_power_workstation/internal/handler/line.go @@ -60,7 +60,7 @@ func lineOccupyHandler(ctx *svc.ServiceContext) http.HandlerFunc { } // ============ B5 叫料(代理 MES 内部 API,2026-10-13 定稿) ============ -// 接驳台:每行可选(GxR1/GxR2),未选时用 yaml Station.Dock 配置兜底(本工位固定接驳台)。 +// 接驳台:每行可选(本工位 左L/右R 两个接驳台),未选时用 yaml Station.Dock 配置兜底(本工位固定接驳台)。 // callPoolHandler GET /api/call/pool 叫料池(本工位物料行四数:需求/调整/已发/占用/可用) func callPoolHandler(ctx *svc.ServiceContext) http.HandlerFunc { @@ -176,7 +176,7 @@ func callStateHandler(ctx *svc.ServiceContext, mesPath, action string) http.Hand } } -// docksHandler GET /api/docks 接驳台列表(代理 MES /api/internal/docks;终端按工位过滤 R1/R2) +// docksHandler GET /api/docks 接驳台列表(代理 MES /api/internal/docks;终端按工位过滤 左L/右R) func docksHandler(ctx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { body, _, err := ctx.Mes.Get("/api/internal/docks", url.Values{}) diff --git a/产线布局说明.md b/产线布局说明.md index e7efe93..1681ea0 100644 --- a/产线布局说明.md +++ b/产线布局说明.md @@ -2,10 +2,11 @@ ## 产线布局说明(主线位置编址版) + > 修正:主线位置统一编址 C1~C15(左→右);**没有独立缓存位**——缓存是主线位置的属性:正对工位的停靠位不缓存,其余位置可缓存。工位 1~12 与主线位置的对应见下表。 > > 本文已与 PLC 点表逐条核对:信号地址、数值编码、握手时序与四类路由地址表见 **§四 PLC 点表与通信协议**。 -> 命名说明:工位G 。缓存停靠位C 。接驳台分两部分 第一部分是工位接驳台,命名方式 工位名 + (R1\R2) 例如 工位1左右两个接驳台分别命名 G1R1 G1R2; 第二部分 库房接驳台,命名JBT21 +> 命名说明:工位G 。缓存停靠位C 。接驳台分两部分 第一部分是工位接驳台,命名方式 工位名 + (L\R) L=左侧、R=右侧 例如 工位1左右两个接驳台分别命名 G1L G1R; 第二部分 库房接驳台,命名JBT21 > 方向: 左右方向: 主线 从左到右,流水线形式流动,物理条件限制,无法从右至左流动。沿着流水线主线方向上下分5层(上排接驳台、上排工位、主线、下排工位、下排接驳台) @@ -16,25 +17,25 @@ -上排接驳台:G1R1 G1R2 G3R1 G3R2 G5R1 G5R2 G7R1 G7R2 G9R1 G9R2 [工位G11·下料检测] +上排接驳台:G1L G1R G3L G3R G5L G5R G7L G7R G9L G9R [工位G11·下料检测] 上排工位: [工位G1] [工位G3] [工位G5] [工位G7] [工位G9] [工位G11·下料检测] 主线: 左═════C1═══C2 C3═════C4════C5 C6═════C7═══C8 C9═════C10═══C11 C12════C13════C14════════C15════════════右 下排工位: [工位G2] [工位G4] [工位G6] [工位G8] [工位G10] [工位G12·下料检测] -下排接驳台:G2R1 G2R2 G4R1 G4R2 G6R1 G6R2 G8R1 G8R2 G10R1 G10R2 [工位G12·下料检测] +下排接驳台:G2L G2R G4L G4R G6L G6R G8L G8R G10L G10R [工位G12·下料检测] 缓存停靠位:C2C3(G1/G2与G3/G4间)、 C5C6(G3/G4与G5/G6间)、 C8C9(G5/G6与G7/G8间)、 C11C12(G7/G8与G9/G10间)、 C14(G9/G10与G11/G12间) 缓存停靠位正对工位(缓存位C 上下分别是两个正对着的工位G):C1正对(G1/G2)、 C4(G3/G4)、 C7(G5/G6)、 C10(G7/G8)、 C13(G9/G10)、 C15(G11/G12) -接驳台:工位1~10 各配 R1、R2 两个接驳台;另有库房位接驳台 1 个;11、12 无接驳台 +接驳台:工位1~10 各配左(L)、右(R)两个接驳台;另有库房位接驳台 1 个;11、12 无接驳台 接驳台对应工位: -工位G1 上方左右分别 G1R1 G1R2;工位G3 上方左右分别 G3R1 G3R2;;工位G5 上方左右分别 G5R1 G5R2;工位G7 上方左右分别 G7R1 G7R2;工位G9 上方左右分别 G9R1 G9R2; -工位G2 下方左右分别 G2R1 G2R2;工位G4 下方左右分别 G4R1 G4R2;工位G6 下方左右分别 G6R1 G6R2;工位G8 下方左右分别 G8R1 G8R2;工位G10 下方左右分别 G10R1 G10R2; +工位G1 上方左右分别 G1L G1R;工位G3 上方左右分别 G3L G3R;;工位G5 上方左右分别 G5L G5R;工位G7 上方左右分别 G7L G7R;工位G9 上方左右分别 G9L G9R; +工位G2 下方左右分别 G2L G2R;工位G4 下方左右分别 G4L G4R;工位G6 下方左右分别 G6L G6R;工位G8 下方左右分别 G8L G8R;工位G10 下方左右分别 G10L G10R; ``` **图例:** - `[工位X]`:工位 1~10(有终端),11/12 检测位(无终端) - `C1~C15`:主线位置编号(左→右),即 PLC 点表"进入主线N号位置"中的位置号 -- `[G1R1]`/`[G1R2]`: AGV 接驳台(AGV 点位) +- `[G1L]`/`[G1R]`: AGV 接驳台(AGV 点位) - `[库房位]`:库房位接驳台(AGV 点位),位置与用途待现场确认 - `════`:主传送带,单方向流水线 @@ -79,9 +80,9 @@ - 工位终端用于:显示当前任务、叫料、退料、报工、查看工艺。 4. **接驳台与AGV点位** - - 每个有终端的工位(1~10)配 R1、R2 两个接驳台。 + - 每个有终端的工位(1~10)配左(L)、右(R)两个接驳台。 - 接驳台是 AGV 的停靠目标点位(AGV 点位);接驳台同时装有 PLC 传感器,PLC 读取接驳台上有无托盘(M900.0 ~ M902.4)。 - - R1、R2 只是同一工位两个接驳台的位置编号(R1=左、R2=右,如 G1R1、G1R2),与 AGV 编号无关;全线只有 2 台 AGV,是公用移动设备、会跑动,不归属任何接驳台。 + - L、R 只是同一工位两个接驳台的位置编号(L=左、R=右,如 G1L、G1R),与 AGV 编号无关;全线只有 2 台 AGV,是公用移动设备、会跑动,不归属任何接驳台。 - 工位接驳台合计 20 个(AGV点位)。 - 另有库房位接驳台 1 个(点表信号 `库房位接驳台有无 M902.4`),同为AGV点位,PLC 只读其在位信号。 - **PLC仅提供接驳台是否在位的信号**(即接驳台上是否有托盘),不控制接驳台动作。 @@ -90,7 +91,7 @@ 5. **叫料与退料规则** - 叫料由工位终端发起,日排产不发起叫料。 - 退料也由工位终端发起。 - - 工位终端叫料时,显示该工位的两个接驳台(AGV点位),操作员选择由哪个AGV送到哪个接驳台(如工位G1 显示 G1R1、G1R2)。 + - 工位终端叫料时,显示该工位的两个接驳台(AGV点位),操作员选择由哪个AGV送到哪个接驳台(如工位G1 显示 G1L、G1R)。 6. **流转方式(三种)** - **出料到主线**:工位出料后工件上主线(PLC 上报"进入主线N号位置"),随线流动。 @@ -110,7 +111,7 @@ ### 四、PLC 点表与通信协议 -> 本节内容全部出自车间交互信息点表(权威,一条不少),并按本文命名规则对应:工位 = G、主线位置 = C、工位接驳台 = 工位名+R1/R2、库房接驳台 = JBT21。 +> 本节内容全部出自车间交互信息点表(权威,一条不少),并按本文命名规则对应:工位 = G、主线位置 = C、工位接驳台 = 工位名+L/R、库房接驳台 = JBT21。 #### 4.0 点表名称 ↔ 本文命名 @@ -118,7 +119,7 @@ |---|---| | 工位1 ~ 工位12 | G1 ~ G12(工位11/12 = 末端下料检测位,无终端、无接驳台) | | 主线1号位置 ~ 主线15号位置 | C1 ~ C15 | -| 工位1后接驳台1 / 接驳台2 | G1R1 / G1R2(工位2~10 同理,接驳台1 = R1、接驳台2 = R2) | +| 工位1后接驳台1 / 接驳台2 | G1L / G1R(工位2~10 同理,接驳台1 = 左侧L、接驳台2 = 右侧R) | | 库房位接驳台 | JBT21 | #### 4.1 位地址信号(BOOL,48 个,逐条列全) @@ -154,26 +155,26 @@ | 主线13有无托盘 | M898.0 | C13 | | 主线14有无托盘 | M898.1 | C14 | | 主线15有无托盘 | M898.2 | C15 | -| 工位1后接驳台1有无 | M900.0 | G1R1 | -| 工位1后接驳台2有无 | M900.1 | G1R2 | -| 工位2后接驳台1有无 | M900.2 | G2R1 | -| 工位2后接驳台2有无 | M900.3 | G2R2 | -| 工位3后接驳台1有无 | M900.4 | G3R1 | -| 工位3后接驳台2有无 | M900.5 | G3R2 | -| 工位4后接驳台1有无 | M900.6 | G4R1 | -| 工位4后接驳台2有无 | M900.7 | G4R2 | -| 工位5后接驳台1有无 | M901.0 | G5R1 | -| 工位5后接驳台2有无 | M901.1 | G5R2 | -| 工位6后接驳台1有无 | M901.2 | G6R1 | -| 工位6后接驳台2有无 | M901.3 | G6R2 | -| 工位7后接驳台1有无 | M901.4 | G7R1 | -| 工位7后接驳台2有无 | M901.5 | G7R2 | -| 工位8后接驳台1有无 | M901.6 | G8R1 | -| 工位8后接驳台2有无 | M901.7 | G8R2 | -| 工位9后接驳台1有无 | M902.0 | G9R1 | -| 工位9后接驳台2有无 | M902.1 | G9R2 | -| 工位10后接驳台1有无 | M902.2 | G10R1 | -| 工位10后接驳台2有无 | M902.3 | G10R2 | +| 工位1后接驳台1有无 | M900.0 | G1L | +| 工位1后接驳台2有无 | M900.1 | G1R | +| 工位2后接驳台1有无 | M900.2 | G2L | +| 工位2后接驳台2有无 | M900.3 | G2R | +| 工位3后接驳台1有无 | M900.4 | G3L | +| 工位3后接驳台2有无 | M900.5 | G3R | +| 工位4后接驳台1有无 | M900.6 | G4L | +| 工位4后接驳台2有无 | M900.7 | G4R | +| 工位5后接驳台1有无 | M901.0 | G5L | +| 工位5后接驳台2有无 | M901.1 | G5R | +| 工位6后接驳台1有无 | M901.2 | G6L | +| 工位6后接驳台2有无 | M901.3 | G6R | +| 工位7后接驳台1有无 | M901.4 | G7L | +| 工位7后接驳台2有无 | M901.5 | G7R | +| 工位8后接驳台1有无 | M901.6 | G8L | +| 工位8后接驳台2有无 | M901.7 | G8R | +| 工位9后接驳台1有无 | M902.0 | G9L | +| 工位9后接驳台2有无 | M902.1 | G9R | +| 工位10后接驳台1有无 | M902.2 | G10L | +| 工位10后接驳台2有无 | M902.3 | G10R | | 库房位接驳台有无 | M902.4 | JBT21 | | (点表未列) | M898.3 ~ M899.7 | 按地址间隙推断为保留,未使用 | diff --git a/问题临时.md b/问题临时.md index 402c85a..8cbe13d 100644 --- a/问题临时.md +++ b/问题临时.md @@ -1,4 +1,14 @@ -1、 + +wms 批量生成位置号 手填 层号 ? 你是不是搞错了,请让执行ai弄清楚现状,原来是选择。 + + + + + + + + +