-
+
+
+ 最近更新的插件
+ 管理插件 →
-
-
{{ c.value }}
-
{{ c.label }}
+
+
+
+
+
+
+
+
{{ row.name }}
+
{{ row.id }}
+
+
+
+
+
+
+ v{{ row.latest_version }}
+
+
+
+ {{ row.versions?.length || 0 }}
+
+
+
+ {{ statusLabel(row.status) }}
+
+
+
+
+
+
+
+
+ 管理员与账号
+
+
+ 普通账号
+ {{ Math.max(0, accountCount - adminCount) }}
+
+
前往账号管理 →
-
-
-
-
- 运行统计
-
- {{ stats.runs?.durationSec || 0 }} 秒
- {{ stats.runs?.activePlugins || 0 }}
- {{ stats.today || '-' }}
-
- {{ stats.plugins?.published || 0 }} 发布 / {{ stats.plugins?.disabled || 0 }} 禁用
-
-
-
-
-
-
- 账号概览
-
-
- {{ overview.admins?.length || 0 }}
-
-
- {{ (overview.accounts?.length || 0) - (overview.admins?.length || 0) }}
-
-
-
-
-
diff --git a/desktop/controlplane-next/frontend/src/views/plugins/index.vue b/desktop/controlplane-next/frontend/src/views/plugins/index.vue
index 5171e92..b3077c6 100644
--- a/desktop/controlplane-next/frontend/src/views/plugins/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/plugins/index.vue
@@ -1,183 +1,184 @@
-
-
-
-
-
-
插件管理
- 上传发布
-
-
-
-
-
-
-
-
-
- 查询
- 重置
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ statusMap[row.status]?.label || row.status }}
-
-
-
-
-
-
- {{ row.versions.length }} 个版本
-
- -
-
-
-
-
- 启用
- 禁用
- 下架
- 删除
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- (uploadForm.file = e.target.files[0] || null)" />
-
-
-
- 取消
- 发布
-
-
-
-
+
+
+
+
+
+
+ 上传发布
+
+
+
+
+
+
+
+
+
+
+ 查询
+ 重置
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {{ statusMap[row.status]?.label || row.status }}
+
+
+
+
+
+
+ {{ row.versions.length }} 个版本
+
+ -
+
+
+
+
+ 启用
+ 禁用
+ 下架
+ 删除
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ (uploadForm.file = e.target.files[0] || null)" />
+
+
+
+ 取消
+ 发布
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/reports/index.vue b/desktop/controlplane-next/frontend/src/views/reports/index.vue
index 768adc7..1917d66 100644
--- a/desktop/controlplane-next/frontend/src/views/reports/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/reports/index.vue
@@ -1,101 +1,100 @@
-
-
-
-
-
-
运行记录
-
- 今日 {{ today }} 条
- 失败 {{ failed }} 条
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 查询
- 重置
-
-
-
-
-
-
-
-
- {{ row.nickname || row.account || '-' }}
-
-
-
-
-
-
- {{ statusMap[row.status]?.label || row.status }}
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ 今日 {{ today }} 条
+ 失败 {{ failed }} 条
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 查询
+ 重置
+
+
+
+
+
+
+
+
+ {{ row.nickname || row.account || '-' }}
+
+
+
+
+
+
+ {{ statusMap[row.status]?.label || row.status }}
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/stats/index.vue b/desktop/controlplane-next/frontend/src/views/stats/index.vue
index 64489bf..168ea22 100644
--- a/desktop/controlplane-next/frontend/src/views/stats/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/stats/index.vue
@@ -1,21 +1,46 @@
-
-
-
数据看板
- 刷新
-
+
+
+
+
+ 刷新
+
+
+
-
-
-
- {{ data.runs?.[c.key] || 0 }}
- {{ c.label }}
-
-
-
-
- {{ data.runs?.durationSec || 0 }}s
- 总时长
-
+
+
+
+
-
-
-
- 插件排行(Top 8)
-
-
-
-
-
-
-
-
-
-
-
- 活跃用户(Top 8)
-
-
-
-
-
-
-
-
-
-
- 近 14 天运行趋势
-
-
-
{{ t.runs }}
-
-
{{ t.day }}
+
+
+
+
+ 近 14 天运行趋势
+ 触发 = start · 成功 = done/success · 失败 = error/failed
-
-
+
+
+
+
+
+
+
+ 插件排行 Top 8
+
+
+
+
+
+ 活跃用户 Top 8
+
+
+
+
+
+
+
+
+
+ 插件运行明细
+
+
+
+ {{ row.name }}
+ {{ row.pluginId }}
+
+
+
+
+ {{ row.success }}
+
+
+ {{ row.failed }}
+
+
+
+
+ {{ row.failed ? '有失败' : '正常' }}
+
+
+
+
+
+
+
+
+ 活跃用户明细
+
+
+
+
+
+ {{ (row.nickname || row.account || '?').slice(0, 1) }}
+
+
+
{{ row.nickname || row.account }}
+
{{ row.account }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/system/department/index.vue b/desktop/controlplane-next/frontend/src/views/system/department/index.vue
index ed9c41f..8febfc6 100644
--- a/desktop/controlplane-next/frontend/src/views/system/department/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/system/department/index.vue
@@ -1,96 +1,95 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- 添加子级
- 编辑
- 删除
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ 刷新
+ 新增部门
+
+
+
+
+
+
+
+
+
+
+ 添加子级
+ 编辑
+ 删除
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/system/menu/index.vue b/desktop/controlplane-next/frontend/src/views/system/menu/index.vue
index 0327c02..2270134 100644
--- a/desktop/controlplane-next/frontend/src/views/system/menu/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/system/menu/index.vue
@@ -1,107 +1,106 @@
-
-
-
-
-
-
-
-
-
-
-
- {{ typeName(row.type) }}
-
-
-
-
-
-
-
-
- 添加子级
- 编辑
- 删除
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ 刷新
+ 新增菜单
+
+
+
+
+
+
+
+
+ {{ typeName(row.type) }}
+
+
+
+
+
+
+
+
+ 添加子级
+ 编辑
+ 删除
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/system/role/index.vue b/desktop/controlplane-next/frontend/src/views/system/role/index.vue
index d287f13..c8e4b91 100644
--- a/desktop/controlplane-next/frontend/src/views/system/role/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/system/role/index.vue
@@ -1,141 +1,140 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ row.name }}
- 内置
-
-
-
-
-
-
- {{ row.relevance ? '是' : '否' }}
-
-
-
-
-
- 编辑
- 授权
- 删除
-
- 全部权限
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ 刷新
+ 新增角色
+
+
+
+
+
+
+
+
+
+
+ {{ row.name }}
+ 内置
+
+
+
+
+
+
+ {{ row.relevance ? '是' : '否' }}
+
+
+
+
+
+ 编辑
+ 授权
+ 删除
+
+ 全部权限
+
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/system/user-center/index.vue b/desktop/controlplane-next/frontend/src/views/system/user-center/index.vue
index 1245714..2b2a055 100644
--- a/desktop/controlplane-next/frontend/src/views/system/user-center/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/system/user-center/index.vue
@@ -1,247 +1,201 @@
-
-
-
-
-
-
-

-

-
{{ userInfo.userName }}
-
专注于用户体验跟视觉设计
-
-
-
-
-
jdkjjfnndf@mall.com
-
-
-
-
-
-
-
-
-
-
-
-
基本设置
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ isEdit ? '保存' : '编辑' }}
-
-
-
-
-
-
-
更改密码
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {{ isEditPwd ? '保存' : '编辑' }}
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+

+
![]()
+
{{ me.nickname || me.account }}
+
+ 当前为初始密码,请尽快修改
+
+
+
+
+
+
账号:{{ me.account }}
+
+
+
+
部门:{{ me.dept || '—' }}
+
+
+
+
身份:{{ me.is_admin ? '管理员' : '普通用户' }}
+
+
+
+
+
+ 更换头像
+
+
支持 jpg/png/gif/webp,≤2MB
+
+
+
+
+
+
+
+
修改密码
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 保存修改
+
+
+ 修改成功后当前登录仍有效;执行机侧下次登录请使用新密码。
+
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/system/user/index.vue b/desktop/controlplane-next/frontend/src/views/system/user/index.vue
index a01019f..08aa920 100644
--- a/desktop/controlplane-next/frontend/src/views/system/user/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/system/user/index.vue
@@ -1,136 +1,135 @@
-
-
-
-
-
-
用户管理(控制台)
-
- 新增用户
- 刷新
-
-
-
-
-
-
-
-
-
-
- {{ row.username }}
- 内置
-
-
-
-
-
-
-
-
- {{ row.status === 1 ? '启用' : '禁用' }}
-
-
-
-
-
-
-
- 编辑
- 删除
-
- 受保护
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ 刷新
+ 新增用户
+
+
+
+
+
+
+
+
+
+
+ {{ row.username }}
+ 内置
+
+
+
+
+
+
+
+
+ {{ row.status === 1 ? '启用' : '禁用' }}
+
+
+
+
+
+
+
+ 编辑
+ 删除
+
+ 受保护
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/frontend/src/views/upgrade/index.vue b/desktop/controlplane-next/frontend/src/views/upgrade/index.vue
index 276a756..630ba66 100644
--- a/desktop/controlplane-next/frontend/src/views/upgrade/index.vue
+++ b/desktop/controlplane-next/frontend/src/views/upgrade/index.vue
@@ -1,14 +1,70 @@
-
-
-
升级进度
- 刷新
-
-
-
-
- 执行机汇总(共 {{ data.total || 0 }} 台)
+
+
+
+
+ 最新壳子版本 v{{ latest }}
+
+ 未配置壳子版本源(大文件源 shell 分类)
+
+ 刷新
+
-
-
- {{ row.nickname || row.account }}
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 版本分布
+
+
+
+
+ v{{ r.version }}
+ {{ stateTag(r.state).label }}
+
+
{{ r.count }} 台 · {{ r.pct }}%
+
+
+
+
+
+
+
+
+
+
+
+ 按账号追踪
+
+
+
+
+
+ {{ (row.nickname || row.account || '?').slice(0, 1).toUpperCase() }}
+
+
+
{{ row.nickname || row.account }}
+
{{ row.account }} · {{ row.dept || '—' }}
+
+
+
+
+
+
+ v{{ row.client_version }}
+
+
+
+
+
+
+
+
+
diff --git a/desktop/controlplane-next/server/src/modules/center/controller/admin/menu.ts b/desktop/controlplane-next/server/src/modules/center/controller/admin/menu.ts
index f87d72a..069ca81 100644
--- a/desktop/controlplane-next/server/src/modules/center/controller/admin/menu.ts
+++ b/desktop/controlplane-next/server/src/modules/center/controller/admin/menu.ts
@@ -21,6 +21,8 @@ interface MenuNode {
icon: string;
perms: string[];
roles?: string[];
+ /** 侧栏隐藏(如个人中心,仅从用户菜单进入) */
+ isHide?: boolean;
};
children?: MenuNode[];
}
@@ -76,13 +78,17 @@ const CONSOLE_MENUS: MenuNode[] = [
meta: { title: '大文件源', icon: 'ri:database-2-line', perms: ['center:fileSource:list'] },
},
{
- path: '/system', name: 'System', component: '/system/index',
+ // 嵌套菜单的父级 component 必须是布局容器(RoutesAlias.Layout='/index/index'),
+ // 否则一级带 children 的路由不会包 Layout,子页面渲染不出(空白页)
+ path: '/system', name: 'System', component: '/index/index',
meta: { title: '系统管理', icon: 'ri:settings-3-line', perms: [] },
children: [
{ path: 'user', name: 'SysUser', component: '/system/user', meta: { title: '用户管理', icon: '', perms: ['center:sys:user'] } },
{ path: 'role', name: 'SysRole', component: '/system/role', meta: { title: '角色管理', icon: '', perms: ['center:sys:role'] } },
{ path: 'menu', name: 'SysMenu', component: '/system/menu', meta: { title: '菜单管理', icon: '', perms: ['center:sys:menu'] } },
{ path: 'department', name: 'SysDept', component: '/system/department', meta: { title: '部门管理', icon: '', perms: ['center:sys:dept'] } },
+ // 个人中心:从头像下拉进入,不在侧栏显示(自助改密 + 头像)
+ { path: 'user-center', name: 'UserCenter', component: '/system/user-center', meta: { title: '个人中心', icon: '', perms: [], isHide: true } },
],
},
];
diff --git a/desktop/controlplane-next/server/src/modules/center/controller/admin/ops.ts b/desktop/controlplane-next/server/src/modules/center/controller/admin/ops.ts
index ac4c016..32b38e8 100644
--- a/desktop/controlplane-next/server/src/modules/center/controller/admin/ops.ts
+++ b/desktop/controlplane-next/server/src/modules/center/controller/admin/ops.ts
@@ -222,7 +222,7 @@ export class AdminOpsController extends BaseController {
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
const rows: any[] = await m.query(
`SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok,
- last_seen, status, created_at, updated_at
+ client_version, last_seen, status, created_at, updated_at
FROM devices ORDER BY last_seen DESC LIMIT ? OFFSET ?`, [limit, offset]);
return { items: rows.map((r: any) => ({ ...r, last_seen: fmtStr(r.last_seen), created_at: fmtStr(r.created_at), updated_at: fmtStr(r.updated_at) })), total: Number(total.c || 0) };
}
@@ -235,17 +235,66 @@ export class AdminOpsController extends BaseController {
await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
const m = this.deviceRepo.manager;
const total: any = (await m.query('SELECT COUNT(*) AS c FROM devices'))[0];
+ const byVersion: any[] = await m.query(
+ `SELECT COALESCE(NULLIF(client_version, ''), '未知') AS client_version, COUNT(*) AS count
+ FROM devices GROUP BY client_version ORDER BY count DESC`);
const byAccount: any[] = await m.query(
- 'SELECT account, COUNT(*) AS device_count, MAX(last_seen) AS last_seen FROM devices GROUP BY account ORDER BY account');
+ `SELECT account, COALESCE(NULLIF(client_version, ''), '未知') AS client_version,
+ COUNT(*) AS device_count, MAX(last_seen) AS last_seen
+ FROM devices GROUP BY account, client_version ORDER BY account`);
+ const statusRows: any[] = await m.query(
+ `SELECT status, COUNT(*) AS c FROM devices GROUP BY status`);
+ const chromeRows: any[] = await m.query(
+ `SELECT COALESCE(SUM(chrome_ok = 1), 0) AS ok, COUNT(*) AS c FROM devices`);
const nick: Record = {};
for (const a of await this.accountRepo.find()) nick[a.account] = [a.nickname || '', a.dept || ''];
+ // 最新壳子版本(与 /api/shell/version 同源:file_sources category=shell 优先,其次 SHELL_DIR/version.json)
+ const latestShell = await this.latestShellVersion();
return {
total: Number(total.c || 0),
- by_version: [],
- by_account: byAccount.map((r: any) => ({ ...r, nickname: nick[r.account]?.[0] || '', dept: nick[r.account]?.[1] || '' })),
+ online: Number(statusRows.find((r: any) => Number(r.status) === 1)?.c || 0),
+ offline: Number(statusRows.find((r: any) => Number(r.status) === 0)?.c || 0),
+ chrome_ok: Number(chromeRows[0]?.ok || 0),
+ chrome_total: Number(chromeRows[0]?.c || 0),
+ latest_shell_version: latestShell.version || '',
+ by_version: byVersion.map((r: any) => ({ client_version: String(r.client_version || '未知'), count: Number(r.count) })),
+ by_account: byAccount.map((r: any) => ({
+ ...r,
+ client_version: String(r.client_version || '未知'),
+ device_count: Number(r.device_count),
+ last_seen: fmtStr(r.last_seen),
+ nickname: nick[r.account]?.[0] || '',
+ dept: nick[r.account]?.[1] || '',
+ })),
};
}
+ /** 最新壳子版本(shellSourceUrl 优先 / version.json 兜底;与 /api/shell/version 同语义) */
+ private async latestShellVersion(): Promise<{ version: string; available: boolean }> {
+ try {
+ const rows = await this.fileSourceRepo
+ .createQueryBuilder('f')
+ .select(['f.version'])
+ .where('f.category = :c', { c: 'shell' })
+ .andWhere('f.enabled = 1')
+ .orderBy('f.id', 'DESC')
+ .getMany();
+ if (rows.length && rows[0].version) return { version: rows[0].version, available: true };
+ } catch (e) {
+ /* fallthrough */
+ }
+ try {
+ const vf = path.join(SHELL_DIR, 'version.json');
+ if (fs.existsSync(vf)) {
+ const d = JSON.parse(fs.readFileSync(vf, 'utf-8').replace(/^\uFEFF/, ''));
+ if (d?.version) return { version: String(d.version), available: true };
+ }
+ } catch (e) {
+ /* ignore */
+ }
+ return { version: '', available: false };
+ }
+
/** POST /api/admin/shell-release — 发布壳子新版 */
@Post('/shell-release')
async shellRelease(
@@ -407,6 +456,26 @@ export class AdminOpsController extends BaseController {
}
/** 通知管理 CRUD */
+ @Get('/notifications/latest')
+ async notifLatest(
+ @Query('limit') limit: number = 15,
+ @Headers('X-Admin-Token') xAdminToken: string = '', @Headers('X-API-Token') xApiToken: string = ''
+ ) {
+ await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
+ const n = Math.max(1, Math.min(50, Number(limit) || 15));
+ const rows: any[] = await this.notificationRepo.manager.query(
+ `SELECT id, title, content, level, target, account, created_at, expires_at
+ FROM notifications
+ WHERE active = 1 AND (expires_at IS NULL OR expires_at > NOW())
+ ORDER BY id DESC LIMIT ${n}`
+ );
+ const items = rows.map((r: any) => ({
+ id: r.id, title: r.title, content: r.content, level: r.level,
+ target: r.target, account: r.account, created_at: fmtStr(r.created_at),
+ }));
+ return { items };
+ }
+
@Get('/notifications')
async notifList(
@Query('page') page: number = 1, @Query('page_size') pageSize: number = 20,
diff --git a/desktop/controlplane-next/server/src/modules/center/controller/admin/plugin.ts b/desktop/controlplane-next/server/src/modules/center/controller/admin/plugin.ts
index 834b57b..2497697 100644
--- a/desktop/controlplane-next/server/src/modules/center/controller/admin/plugin.ts
+++ b/desktop/controlplane-next/server/src/modules/center/controller/admin/plugin.ts
@@ -263,6 +263,139 @@ export class AdminPluginController extends BaseController {
platforms: platforms.map((r: any) => r.platform_id),
};
}
+
+ // ==================== 双向批量授权(新 UI 专用;旧 /account_plugins 契约保持不动供 agent_cli 使用) ====================
+
+ /** GET /api/admin/plugin_grants?plugin_id= — 插件维度:该插件已授权账号列表(含昵称/部门/权限/授权时间) */
+ @Get('/plugin_grants')
+ async pluginGrants(
+ @Query('plugin_id') pluginId: string = '',
+ @Headers('X-Admin-Token') xAdminToken: string = '',
+ @Headers('X-API-Token') xApiToken: string = ''
+ ) {
+ await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
+ pluginId = (pluginId || '').trim();
+ if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
+ const pl = await this.pluginRepo.findOneBy({ id: pluginId });
+ if (!pl) throw new ApiError(404, `插件 ${pluginId} 不存在`);
+ const rows: any[] = await this.accountPluginRepo.manager.query(
+ `SELECT ap.account, a.nickname, a.dept, ap.can_download, ap.can_run, ap.granted_at, ap.updated_at
+ FROM account_plugins ap LEFT JOIN accounts a ON a.account = ap.account
+ WHERE ap.plugin_id = ? ORDER BY ap.account`,
+ [pluginId]
+ );
+ return {
+ plugin: { id: pl.id, name: pl.name, status: pl.status, latest_version: pl.latestVersion },
+ items: rows.map(r => ({
+ account: r.account,
+ nickname: r.nickname || '',
+ dept: r.dept || '',
+ can_download: !!Number(r.can_download),
+ can_run: !!Number(r.can_run),
+ granted_at: fmtStr(r.granted_at),
+ updated_at: fmtStr(r.updated_at),
+ })),
+ };
+ }
+
+ /** POST /api/admin/plugin_grants/batch — 批量授权/更新(事务 upsert) */
+ @Post('/plugin_grants/batch')
+ async pluginGrantsBatch(
+ @Body() b: any,
+ @Headers('X-Admin-Token') xAdminToken: string = '',
+ @Headers('X-API-Token') xApiToken: string = ''
+ ) {
+ const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
+ const pluginId = String(b?.plugin_id || '').trim();
+ const items: any[] = Array.isArray(b?.items) ? b.items : [];
+ if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
+ if (!items.length) throw new ApiError(400, 'items 不能为空');
+ const pl = await this.pluginRepo.findOneBy({ id: pluginId });
+ if (!pl) throw new ApiError(404, `插件 ${pluginId} 不存在`);
+ const accounts: string[] = [];
+ for (const it of items) {
+ const acc = String(it?.account || '').trim();
+ if (acc) accounts.push(acc);
+ }
+ if (!accounts.length) throw new ApiError(400, 'items 中无有效 account');
+ const existRows: any[] = await this.pluginRepo.manager.query(
+ `SELECT account FROM accounts WHERE account IN (${accounts.map(() => '?').join(',')})`,
+ accounts
+ );
+ const existSet = new Set(existRows.map(r => String(r.account)));
+ const unknown = accounts.filter(a => !existSet.has(a));
+ if (unknown.length) throw new ApiError(400, `账号不存在:${unknown.slice(0, 5).join(', ')}${unknown.length > 5 ? ' ...' : ''}`);
+ await this.pluginRepo.manager.transaction(async (em) => {
+ for (const it of items) {
+ const acc = String(it.account || '').trim();
+ const dl = it?.can_download === undefined ? 1 : Number(!!it.can_download);
+ const rn = it?.can_run === undefined ? 1 : Number(!!it.can_run);
+ await em.query(
+ `INSERT INTO account_plugins(account, plugin_id, can_download, can_run, granted_at, updated_at)
+ VALUES (?, ?, ?, ?, NOW(), NOW())
+ ON DUPLICATE KEY UPDATE can_download = VALUES(can_download), can_run = VALUES(can_run), updated_at = NOW()`,
+ [acc, pluginId, dl, rn]
+ );
+ }
+ });
+ await this.centerAuthService.audit(login, 'grant-batch', pluginId, JSON.stringify({ accounts, count: items.length }));
+ return { ok: true, plugin_id: pluginId, count: items.length };
+ }
+
+ /** POST /api/admin/plugin_grants/revoke — 批量撤销 */
+ @Post('/plugin_grants/revoke')
+ async pluginGrantsRevoke(
+ @Body() b: any,
+ @Headers('X-Admin-Token') xAdminToken: string = '',
+ @Headers('X-API-Token') xApiToken: string = ''
+ ) {
+ const login = await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
+ const pluginId = String(b?.plugin_id || '').trim();
+ const accounts: string[] = Array.isArray(b?.accounts) ? b.accounts.map((a: any) => String(a || '').trim()).filter(Boolean) : [];
+ if (!pluginId) throw new ApiError(400, 'plugin_id 不能为空');
+ if (!accounts.length) throw new ApiError(400, 'accounts 不能为空');
+ const res = await this.accountPluginRepo
+ .createQueryBuilder()
+ .delete()
+ .where('plugin_id = :pid', { pid: pluginId })
+ .andWhere('account IN (:...accounts)', { accounts })
+ .execute();
+ await this.centerAuthService.audit(login, 'grant-revoke-batch', pluginId, JSON.stringify({ accounts, count: accounts.length }));
+ return { ok: true, plugin_id: pluginId, removed: Number(res?.affected || 0) };
+ }
+
+ /** GET /api/admin/grants/matrix — 授权矩阵总览(账号 × 插件 + 平台白名单) */
+ @Get('/grants/matrix')
+ async grantsMatrix(
+ @Headers('X-Admin-Token') xAdminToken: string = '',
+ @Headers('X-API-Token') xApiToken: string = ''
+ ) {
+ await this.centerAuthService.requireAdmin(xAdminToken, xApiToken);
+ const m = this.accountPluginRepo.manager;
+ const plugins: any[] = await m.query(`SELECT id, name, status, latest_version FROM plugins ORDER BY id`);
+ const accounts: any[] = await m.query(
+ `SELECT account, nickname, dept, status, is_admin FROM accounts ORDER BY account`
+ );
+ const grants: any[] = await m.query(
+ `SELECT account, plugin_id, can_download, can_run FROM account_plugins`
+ );
+ const platforms: any[] = await m.query(`SELECT account, platform_id FROM account_platforms`);
+ return {
+ plugins: plugins.map(p => ({ id: p.id, name: p.name, status: p.status, latest_version: p.latest_version })),
+ accounts: accounts.map(a => ({
+ account: a.account, nickname: a.nickname || '', dept: a.dept || '',
+ status: Number(a.status), is_admin: !!Number(a.is_admin),
+ })),
+ grants: grants.map(g => ({
+ account: g.account, plugin_id: g.plugin_id,
+ can_download: !!Number(g.can_download), can_run: !!Number(g.can_run),
+ })),
+ platforms: platforms.reduce((acc: Record, r) => {
+ (acc[String(r.account)] ||= []).push(String(r.platform_id));
+ return acc;
+ }, {}),
+ };
+ }
}
function fmt(d: Date | null): string {
diff --git a/desktop/controlplane-next/server/src/modules/center/controller/api/device.ts b/desktop/controlplane-next/server/src/modules/center/controller/api/device.ts
index 7eed655..3f16b2d 100644
--- a/desktop/controlplane-next/server/src/modules/center/controller/api/device.ts
+++ b/desktop/controlplane-next/server/src/modules/center/controller/api/device.ts
@@ -7,7 +7,7 @@ import { CenterAuthService, ApiError } from '../../service/auth';
/**
* 运行上报 + 设备上报(对齐旧 FastAPI apis/plugins.py /api/runtime/report、/api/device/report)
- * 注意:现网 devices 表无 client_version 列(以现网 schema 为准),上报仅 upsert 现有列
+ * devices.client_version:壳子心跳携带的客户端版本号(老库迁移已含该列),供升级进度统计
*/
@Provide()
@CoolController('/api')
@@ -45,12 +45,13 @@ export class ApiDeviceController extends BaseController {
const deviceId = (b?.device_id || '').trim();
if (!deviceId) throw new ApiError(400, 'device_id 不能为空');
await this.deviceRepo.manager.query(
- `INSERT INTO devices(device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok, last_seen, status)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
+ `INSERT INTO devices(device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok, client_version, last_seen, status)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
ON DUPLICATE KEY UPDATE
account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os),
ip = VALUES(ip), chrome_installed = VALUES(chrome_installed),
chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok),
+ client_version = VALUES(client_version),
last_seen = VALUES(last_seen), status = VALUES(status)`,
[
deviceId,
@@ -61,6 +62,7 @@ export class ApiDeviceController extends BaseController {
Number(!!b?.chrome_installed),
(b?.chrome_version || '').trim(),
Number(!!b?.chrome_ok),
+ (b?.client_version || '').trim(),
Number(!!b?.status),
]
);
diff --git a/desktop/controlplane-next/server/src/modules/center/entity/runtime.ts b/desktop/controlplane-next/server/src/modules/center/entity/runtime.ts
index e2f49df..c570592 100644
--- a/desktop/controlplane-next/server/src/modules/center/entity/runtime.ts
+++ b/desktop/controlplane-next/server/src/modules/center/entity/runtime.ts
@@ -67,6 +67,9 @@ export class DeviceEntity {
@Column({ name: 'chrome_ok', type: 'tinyint', width: 1, default: 0, comment: 'Chrome 是否就绪' })
chromeOk: number;
+ @Column({ name: 'client_version', type: 'varchar', length: 32, default: '', comment: '客户端(壳子)版本号,心跳上报' })
+ clientVersion: string;
+
@Index()
@Column({ name: 'last_seen', type: 'datetime', default: () => 'CURRENT_TIMESTAMP', comment: '最后在线时间' })
lastSeen: Date;
diff --git a/docs/插件/发版规范.md b/docs/插件/发版规范.md
index ca58a6b..80ae3b3 100644
--- a/docs/插件/发版规范.md
+++ b/docs/插件/发版规范.md
@@ -6,7 +6,14 @@
## 1. 总览
-版本源(插件包 + 壳子安装包 + 文件登记)全部在**中心机控制面**(`http://117.72.191.188:8800`)。
+版本源(插件包 + 壳子安装包 + 文件登记)全部在**中心机控制面**(内网 `http://172.30.30.243:8800`)。
+
+> ⚠️ **发版必须指向内网库**(2026-10-15 踩坑):控制面有两套——
+> 内网生产库 `http://172.30.30.243:8800`(执行机实际连接源,端口分工:8800 控制面 / 8802 文件服务器下载 /
+> 8899 文件服务器管理台)与公网旧库 `http://117.72.191.188:8800`(迁移前旧库,仍在线但执行机不连)。
+> 两库数据不同步,发错库的症状:执行机永远"已是最新版本"/插件不更新,而公网库里查得到记录。
+> 发版命令一律**显式** `--base http://172.30.30.243:8800`;
+> 验证:`curl -H "X-API-Token: " http://172.30.30.243:8800/api/shell/version`。
| 交付物 | 更新机制 | 入口 |
|--------|----------|------|
@@ -26,16 +33,16 @@ d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent
1. **密码登录(推荐,任意机器可用)**:
`--admin <管理员> --password <密码>`(或环境变量 `AGENT_ADMIN_PASSWORD` / `AGENT_ADMIN_ACCOUNT`),
- 远程机器再加 `--base http://<中心机地址>:8800`
+ 并**一律显式加** `--base http://172.30.30.243:8800`(内网生产库,勿用公网旧库,见第 1 节警告)
2. **本机密钥自签(仅中心机本机)**:复用 `controlplane/.env` 与 `.admin_secret`
-实际账号:管理员 `puddy`,密码 `123456`,中心机控制面 `http://117.72.191.188:8800`。
+实际账号:管理员 `puddy`,密码 `123456`,中心机控制面 `http://172.30.30.243:8800`。
本开发机直接示例:
```powershell
d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
- --admin puddy --password 123456 --base http://117.72.191.188:8800 `
+ --admin puddy --password 123456 --base http://172.30.30.243:8800 `
publish <插件.zip> --id --version
```
@@ -47,7 +54,7 @@ d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent
```powershell
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
- --admin puddy --password 123456 `
+ --admin puddy --password 123456 --base http://172.30.30.243:8800 `
publish dist-plugin\_v<版本>.zip --id --version <版本>
```
@@ -55,8 +62,8 @@ d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent
3. **授权 / 收回**(按账号管控可执行性):
```powershell
- .venv\Scripts\python.exe -m controlplane.tools.agent_cli grant <账号>
- .venv\Scripts\python.exe -m controlplane.tools.agent_cli revoke <账号>
+ .venv\Scripts\python.exe -m controlplane.tools.agent_cli --base http://172.30.30.243:8800 grant <账号>
+ .venv\Scripts\python.exe -m controlplane.tools.agent_cli --base http://172.30.30.243:8800 revoke <账号>
```
4. **执行机端**:登录后按账号权限自动同步——`plugin_sync.py` 拉版本清单 → 下载 → sha256 校验 →
@@ -77,12 +84,13 @@ d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent
```powershell
.venv\Scripts\python.exe -m controlplane.tools.agent_cli `
- --admin puddy --password 123456 `
+ --admin puddy --password 123456 --base http://172.30.30.243:8800 `
file push <安装包> --category shell --version <新版本> [--notes "说明"]
```
- > 安装包上传到内网文件服务器(`FILESERVER_BASE_URL=172.30.35.135:8802`),并登记到中心机
+ > 安装包上传到内网文件服务器(`FILESERVER_BASE_URL=172.30.30.243:8802`),并登记到**内网中心机**
> `file_sources(shell)`,执行机 `shell_updater` 从该直链下载。**不要用旧的 `shell-release` 子命令**。
+ > 登记(`--base`)必须指内网库 `http://172.30.30.243:8800`,发到公网旧库执行机检测不到(见第 1 节警告)。
6. **执行机端**:自动下载安装包,前端提示后用户点击升级重启。
diff --git a/docs/架构/服务端迁移方案_cool-admin.md b/docs/架构/服务端迁移方案_cool-admin.md
index 832ed4f..95f0738 100644
--- a/docs/架构/服务端迁移方案_cool-admin.md
+++ b/docs/架构/服务端迁移方案_cool-admin.md
@@ -296,6 +296,8 @@ Art Design Pro 是纯前端模板,需与 cool-admin-midway 后端 RBAC API 对
| **本次补齐 3** | 文件服务器离线监控(原子认领翻转 + 钉钉工作通知/群机器人回退,对齐 monitor.py/notify.py;环境变量 FILESERVER_HEARTBEAT_TIMEOUT/FILESERVER_MONITOR_INTERVAL 默认 180s/30s) |
| **本次补齐 4** | `server/.env` 轻量加载器(comm/env.ts,不覆盖已有环境变量),凭证与老 controlplane/.env 同源 |
| **本次补齐 5** | **系统管理四页(用户/角色/菜单/部门)全功能落地**:服务端 `/api/admin/sys/*` 自建 CRUD(委托 cool-admin 原生 service,md5 密码/passwordV 失效旧 token/授权缓存刷新与原生登录链路完全一致;内置 admin 用户与超管角色双重保护;防环/子级检查/审计落库);前端四页补齐搜索/新增/编辑/删除/授权对话框(角色授权=菜单树+部门树,回显与原子保存)。实测:CRUD 全通过、授权确定性(原生 modifyAfter 未 await 的竞态已绕开)、md5 密码与原生登录逐字一致 |
+| **本次补齐 6** | **权限授权工作台重设计**(原"单下拉选账号+逐个开关"不可扩展):三视图——「按用户」主从布局(左账号列表搜索/部门过滤/授权数角标,右全部插件行内开关即时保存+平台白名单+批量授予/撤销);「按插件」成员表(行内开关、多选批量撤销、「添加授权」对话框账号多选+默认权限);「矩阵总览」账号×插件网格(单元格 ⬇/▶ 徽标点击切换,双关自动撤销,列头/首列冻结)。参照:GitLab project members / RuoYi 角色↔用户分配 / 阿里云 RAM 双向授权 / GitHub 权限矩阵。新增接口(旧 /account_plugins 契约不动,agent_cli 零影响):GET /api/admin/plugin_grants、POST /api/admin/plugin_grants/batch(事务 upsert)、POST /api/admin/plugin_grants/revoke、GET /api/admin/grants/matrix(单一数据源) |
+| **本次补齐 7** | **页眉挂件清理与通知中心激活**:① 聊天挂件整链路移除(按钮/全局组件注册/组件文件/mitt 事件,headerBarConfig.chat=false);② 用户菜单"使用文档/GitHub"模板外链移除,快速入口改为 37du 真实页面(概览/插件/账号/授权/通知/看板);③ **通知中心接真实数据**:新增 GET /api/admin/notifications/latest(active 且未过期),前端 useNotifyCenter 组合式(60s 轮询单例 + localStorage 已读水位 + 铃铛红点 + 面板"新"角标/级别图标/全员@定向标记 + 全部已读 + 前往通知推送页),与员工端壳子 notifier.js 消费的 /api/notifications 同源同语义 |
| **本次修复** | ① `pageBounds` 返回顺序反转导致全部列表接口 items 为空(9 处调用点一并生效);② `/api/admin/fileserver/status` 键名 `items`→`fileservers`、status/offline_notified 布尔化、total_size 数值化(对齐老契约);③ 菜单树移除无对应视图的 `/plugins/upload` 子项(上传发布在插件页内弹窗) |
### 11.2 尚未完成(后续阶段)
diff --git a/docs/需求单/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/需求文档.md b/docs/需求单/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/需求文档.md
new file mode 100644
index 0000000..6d4216d
--- /dev/null
+++ b/docs/需求单/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/需求文档.md
@@ -0,0 +1,65 @@
+# XQ0033 门店管理及服务岗出勤积分更新
+
+## 一、需求背景
+
+金色印象 / 金色湖畔事业部门店管理及服务岗员工按日出勤遵章积分(正常/迟到/早退/调休假/小时特假等 = 2 分,各类假/旷工 = 0 分),人资按月把每人每日积分导入 HR 系统。此前全程人工维护 Excel(拉报表、滚动快照、逐日对比、拆导入/删除名单),改为影刀脚本自动化。
+
+- 需求方:陈莲
+- 形态:影刀版(`workflows/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/`),WPS COM + 本地文件 + 定时跑
+- 数据口径:仅 HR 系统「考勤统计报表」(XQ0009 同款接口),不含收银系统(技师不在范围)
+
+## 二、目标文件
+
+`D:\资料\人资\门店管理及服务岗出勤积分更新\员工出勤及遵章积分导入{MMDD}.xlsx`
+
+- 文件名 = 本批处理的积分日期段(如 `1009` 单日、`1011-12` 跨日),一个文件可跑多轮
+- 目录现有历史批次文件留存,脚本按「文件名含本轮 T-2 日」或「最新修改」选择写入文件
+
+## 三、工作簿结构(sheet)
+
+| sheet | 用途 | 脚本动作 |
+|---|---|---|
+| 考勤统计报表-源数据 / -今日 | 接口原始平铺留存(无表头) | 不动 |
+| 操作说明 | 代号映射说明(2=享受积分,0=不享受) | 不动 |
+| 辅助菜单 | 考勤状态→代号映射(B:C 列) | 不动 |
+| 当月再入职名单 | 离职当月再入职台账(人工维护) | 不动 |
+| 考勤统计报表 | 带表头(行5)+ A 列圈人公式的报表 | **写入当月全量数据**(B6 起 B~AO),更新 B2 标题 |
+| 考勤--今日导出 | 本轮快照(A 列=正确 的行,41 列) | 清空重写 |
+| 考勤-前一日导出 | 上一轮快照 | 清空重写(= 旧「考勤--今日导出」) |
+| 对比结果 | B~J 值区 + K~AO 差值公式 + AP~BT 今日镜像 + BU~CY 前一日镜像 | 只写 B~J 值区(行4 起),公式不动 |
+| 积分导入 | B工号~J姓名(同对比结果 B~J)+ K积分日期 + L查重列(空) | 按积分日期先删后插 |
+| 积分删除 | 同上 | 按积分日期先删后插 |
+
+A 列圈人公式逻辑(模板自带,写在「考勤统计报表」A6 起):
+
+- 所属单位含「金色印象事业部」:排除四级部门=虚拟会馆/空;PLUS会馆/彩云坊/大学城只留店长、收银组长、主管、领班;其余排除技师工号非空
+- 所属单位含「金色湖畔事业部」:一级部门须含「大区」;排除所属部门=石桥铺会馆/人事组/库管组/维护组/行政运营组、岗位含宿管员
+- 其余:错误
+- 脚本另在写入今日导出时排除岗位「湖畔兼职服务顾问」
+
+## 四、流程步骤
+
+1. **拉取当月考勤统计报表**:HR 接口分页抓取(reportId=f880c52a…,month=当月,登录态读 `%LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json`,失效自动补登)
+2. **写「考勤统计报表」**:清 B6 起旧数据 → 写入全量行(B工号 C部门全路径 D所属单位 E所属部门 F一级部门 G四级部门 H岗位名称 I技师工号 J姓名 K~AO=1~31日 ← base_code/org_full_path/belong_unit_org_name/dept_org_name/dept_one/dept_four/post_name/ext_technician_code/staff_name/v_1~31)→ 更新 B2 标题
+3. **COM 重算**:WPS/Excel COM 打开 → 取消所有 sheet 筛选 → 全量重算 → 保存关闭
+4. **滚动快照**:读 A 列="正确" 的行(排除湖畔兼职服务顾问)→ 旧「考勤--今日导出」先复制到「考勤-前一日导出」→ 新行写入「考勤--今日导出」(41 列,技师工号在 H 列)
+5. **写对比结果**:今日导出 A5 起 A~I → 对比结果 B4 起 B~J(值区,旧超出行清空)
+6. **COM 重算** → 读对比结果公式值:
+ - **新增积分**:今日镜像 T-2 日列 = 2 的行(T-2 = 运行日 - 2,与 F1=TODAY()-2 一致)
+ - **修正积分**:差值列(今日镜像 - 前一日镜像)日 1~T-3 中 > 0 → 补积分;< 0 → 删积分
+7. **写积分导入**:新增段(积分日期=T-2)在前 + 修正段(积分日期=对应日,升序)在后;写入前删除表内「积分日期 ∈ [月首, T-3] 且非历史新增段日」及「积分日期 = T-2」的旧行(幂等重跑)
+8. **写积分删除**:负差值行,写入前删除表内「积分日期 ∈ [月首, T-3]」旧行(全月刷新)
+9. COM 重算保存收尾,输出统计日志
+
+## 五、导入表维护策略(与人工模式对齐)
+
+- **新增段按批保留**:每轮 T-2 新增段写入后不再被后续轮次删除。历号新增段日期记录在目标目录 `_xq0033_state.json`(按文件名分 key);删除修正旧行时跳过这些日期。兜底:状态文件丢失时仍保护「上轮新增段日 = T-3」
+- **修正段全月重算刷新**:每轮把 [月首, T-3] 的修正旧行删掉重插(差值窗口滚动后行数自然变化,与 1011-12 文件观察一致)
+- **新批文件**:目录中无「文件名含 T-2」的文件时,复制最新文件另存为 `员工出勤及遵章积分导入{T-2 MMDD}.xlsx` 并清空积分导入/删除表(与人工新建批次一致)
+
+## 六、运行方式
+
+- 影刀「调用模块」:`main({})`,无外部参数(配置全部在脚本头部常量区)
+- 定时建议:每日运行(周一至周五),HR 登录态由「37duHR登录(接口版)」指令维护
+- 依赖:requests python-dotenv openpyxl pywin32(COM 兜底链 Ket.Application / et.Application / Excel.Application)
+- 注意:运行前关闭 WPS 中打开的目标文件(脚本检测到 ~$ 锁文件会退出提示)
diff --git a/docs/需求单/实现形态登记表.md b/docs/需求单/实现形态登记表.md
index 954e64a..6a536ec 100644
--- a/docs/需求单/实现形态登记表.md
+++ b/docs/需求单/实现形态登记表.md
@@ -85,7 +85,7 @@
| XQ0030 | 培训老师下店上钟数据统计 | ⬜ 待定形态 | ⬜ 待定形态 | 新纳入 |
| XQ0031 | ERP物料收发汇总导出整合 | ✅ 已实现 | ✅ `xq0031_xq0032` v1.0.11(有 UI) | 双版本并存;与 XQ0032 合并一个插件 |
| XQ0032 | ERP采购订单导出 | ✅ 已实现 | ✅ `xq0031_xq0032` v1.0.11(有 UI) | 双版本并存;无独立需求单目录,并入 XQ0031 插件 |
-| XQ0033 | 门店管理及服务岗出勤积分更新 | ⬜ 待定形态 | ⬜ 待定形态 | 新纳入 |
+| XQ0033 | 门店管理及服务岗出勤积分更新 | ✅ 已实现 | — | HR 报表→圈人→快照滚动→对比→积分导入/删除,详见需求单目录 |
| XQ0034 | 续签电子签 | ⬜ 待定形态 | ⬜ 待定形态 | 新纳入 |
| XQ0035 | 服务岗转正不通过电子签(离职+入职) | ⬜ 待定形态 | ⬜ 待定形态 | 新纳入 |
| XQ0036 | 门店员工起调停薪处理 | ⬜ 待定形态 | ⬜ 待定形态 | 新纳入 |
diff --git a/workflows/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/attendance_points_update.py b/workflows/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/attendance_points_update.py
new file mode 100644
index 0000000..0a9325c
--- /dev/null
+++ b/workflows/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/attendance_points_update.py
@@ -0,0 +1,877 @@
+"""
+@FileName: attendance_points_update.py
+@Author: 小布丁
+@CreateTime: 2026-10-15
+@Description: 门店管理及服务岗出勤积分更新(影刀单文件版)
+ 业务逻辑:HR「考勤统计报表」当月全量 → 写入积分工作簿「考勤统计报表」sheet
+ → COM 重算按 A 列公式圈人 → 滚动「考勤--今日导出/考勤-前一日导出」快照
+ → 对比结果(今日镜像-前一日镜像)逐日差值 → 新增积分(T-2 日代号=2)
+ 与修正积分(1~T-3 日差值正补/负删)写入「积分导入/积分删除」表。
+ 规则与文件结构见 docs/需求单/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/需求文档.md。
+@Version: 1.0.0
+
+设计说明(与 workflows 下其它单文件版一致):
+ - 单文件自包含,内联 HR 接口(XQ0009 同款),不依赖项目其它模块。
+ - 登录态仅读取「37duHR登录」指令写入的 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json。
+ - 公式重算走 WPS/Excel COM(Ket.Application → et.Application → Excel.Application 兜底),
+ openpyxl 只负责读写值区,模板公式(A 列圈人、差值、镜像、SUBTOTAL)一律不动。
+ - 积分导入表维护策略(对齐人工模式):
+ 新增段按批保留(历号新增段日期记录在 _xq0033_state.json,删除旧行时跳过);
+ 修正段全月重算刷新(每轮先删 [月首, T-3] 旧行再插)。
+
+依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
+ pip install requests python-dotenv openpyxl pywin32
+
+运行:
+ - 影刀「调用模块」:main({})(无外部参数,配置全部在下方常量区)
+ - 直接运行:python attendance_points_update.py
+ - 运行前关闭 WPS/Excel 中打开的目标文件(检测到 ~$ 锁文件会退出提示)
+"""
+
+# ==================== 标准库导入 ====================
+import json
+import os
+import re
+import shutil
+import time
+import traceback
+from datetime import date, datetime, timedelta
+
+# ==================== 第三方库导入(影刀版启动校验) ====================
+try:
+ from dotenv import load_dotenv
+ import requests
+ import openpyxl
+ import pythoncom
+ import win32com.client
+except ImportError as _import_err:
+ raise RuntimeError(
+ "缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
+ "请先执行安装:\n"
+ " pip install requests python-dotenv openpyxl pywin32\n"
+ f"缺失依赖详情: {_import_err}")
+
+load_dotenv()
+
+# ==================== 日志(print) ====================
+class _PrintLogger:
+ """影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
+
+ @staticmethod
+ def debug(msg, *args):
+ if args:
+ msg = msg % args
+ print(f"[DEBUG] {msg}")
+
+ @staticmethod
+ def info(msg, *args):
+ if args:
+ msg = msg % args
+ print(f"[INFO] {msg}")
+
+ @staticmethod
+ def warning(msg, *args):
+ if args:
+ msg = msg % args
+ print(f"[WARN] {msg}")
+
+ @staticmethod
+ def error(msg, *args):
+ if args:
+ msg = msg % args
+ print(f"[ERROR] {msg}")
+
+
+logger = _PrintLogger()
+
+# ==================== 常量配置 ====================
+# 积分工作簿目录与文件名前缀(文件名 = 本批积分日期段,如 1009 / 1011-12)
+TARGET_DIR = r"D:\资料\人资\门店管理及服务岗出勤积分更新"
+FILE_PREFIX = "员工出勤及遵章积分导入"
+# 新增段历史记录(按数据文件名分 key,删除修正旧行时跳过这些日期,防误删历史新增段)
+STATE_FILE = os.path.join(TARGET_DIR, "_xq0033_state.json")
+# 测试/指定文件:非空时跳过文件自动选择直接写该文件(交付默认 None)
+FORCE_FILE = None
+# 岗位黑名单(A 列公式之外脚本层再排除)
+EXCLUDE_POSTS = {"湖畔兼职服务顾问"}
+
+# HR 接口(与 XQ0009 一致)
+HR_BASE_URL = "https://hr.37du.co"
+GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
+MONTH_ATT_REPORT_URL = f"{HR_BASE_URL}/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
+MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
+COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
+REPORT_PAGE_SIZE = 1000
+MAX_REQUEST_RETRY = 3 # 项目级重试:瞬时故障最多 3 次,三次失败后记录错误日志
+RELOGIN_MAX = 3 # 登录态失效自动补登上限
+
+_APP_DATA_DIR = os.path.join(
+ os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
+ '37duAutomation')
+SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
+SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
+
+# COM ProgID 兜底链(WPS 表格 → 旧版 WPS → MS Excel)
+COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application")
+
+# 工作簿 sheet 名与结构常量
+SHEET_REPORT = "考勤统计报表" # 行5表头,B6 起数据:B工号 C部门全路径 D所属单位 E所属部门 F一级部门 G四级部门 H岗位名称 I技师工号 J姓名 K~AO=1~31日(40列)
+SHEET_TODAY = "考勤--今日导出" # 行4表头,A5 起数据:A工号 ~ I姓名 J~AN=1~31日(40列)
+SHEET_PREV = "考勤-前一日导出" # 结构同今日导出
+SHEET_CMP = "对比结果" # 行3表头,B4 起值区(B~J 员工信息),K~AO 差值公式,AP~BT 今日镜像,BU~CY 前一日镜像
+SHEET_IMPORT = "积分导入" # 行3表头,B4 起数据:B工号~J姓名(同对比结果 B~J)+ K积分日期
+SHEET_DELETE = "积分删除" # 结构同积分导入
+
+REPORT_DATA_START = 6 # 考勤统计报表数据起始行
+EXP_DATA_START = 5 # 今日导出/前一日导出数据起始行
+CMP_DATA_START = 4 # 对比结果数据起始行
+IMP_DATA_START = 4 # 积分导入/删除数据起始行
+
+
+# ==================== 工具函数 ====================
+def _clean(v):
+ """None → "",其余转字符串并去首尾空白(None 单元格写空串,保持与人工粘贴一致)。"""
+ if v is None:
+ return ""
+ return str(v).strip()
+
+
+def _to_date(v):
+ """K 列积分日期值 → date(datetime/date 直取,字符串尝试 ISO 解析),失败返回 None。"""
+ if isinstance(v, datetime):
+ return v.date()
+ if isinstance(v, date):
+ return v
+ if v is None:
+ return None
+ s = str(v).strip()[:10]
+ try:
+ return date.fromisoformat(s)
+ except ValueError:
+ return None
+
+
+def _delete_sheet_rows(ws, row_nums):
+ """按行号集合删除行:排序后合并连续段,从后往前 delete_rows,避免逐行移动。"""
+ if not row_nums:
+ return 0
+ nums = sorted(set(row_nums))
+ removed = 0
+ start = prev = nums[0]
+ segments = []
+ for n in nums[1:]:
+ if n == prev + 1:
+ prev = n
+ continue
+ segments.append((start, prev - start + 1))
+ start = prev = n
+ segments.append((start, prev - start + 1))
+ for seg_start, seg_len in sorted(segments, reverse=True):
+ ws.delete_rows(seg_start, seg_len)
+ removed += seg_len
+ return removed
+
+
+def _scan_last_data_row(ws, col, start_row):
+ """扫描某列非空值(含空串外任意值)的最后一行。"""
+ last = start_row - 1
+ for r in range(start_row, ws.max_row + 1):
+ if ws.cell(row=r, column=col).value not in (None, ""):
+ last = r
+ return last
+
+
+def _write_block(ws, start_row, rows_values, col_start, old_last_row, col_count=None):
+ """写入行块并清理旧尾部:新行写入 [start_row, start_row+n),其后的旧数据行清 None。
+
+ rows_values 每项为定长列表;col_count 缺省取首行长度。old_last_row 为该值区旧数据最后行。
+ """
+ n = len(rows_values)
+ if col_count is None:
+ col_count = len(rows_values[0]) if rows_values else 0
+ for i, row_vals in enumerate(rows_values):
+ r = start_row + i
+ for j, v in enumerate(row_vals):
+ ws.cell(row=r, column=col_start + j, value=v)
+ tail_start = start_row + n
+ for r in range(tail_start, max(old_last_row, tail_start - 1) + 1):
+ for c in range(col_start, col_start + col_count):
+ ws.cell(row=r, column=c, value=None)
+ return n
+
+
+# ==================== HR 接口(内联,XQ0009 同款) ====================
+class HRSessionExpiredError(Exception):
+ """HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
+
+
+def _load_shared_hr_cookies():
+ """读取共享 HR cookies 文件(由「37duHR登录」指令写入)。"""
+ if os.path.exists(SHARED_HR_COOKIE_FILE):
+ with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
+ cookies = json.load(f)
+ return cookies or None
+ return None
+
+
+def _ensure_hr_cookies():
+ """确保存在 HR 登录态文件;缺失时提示先运行「37duHR登录」指令。"""
+ if _load_shared_hr_cookies():
+ return True
+ raise RuntimeError(
+ "未找到 HR 登录态(hr_cookies.json)或已失效。\n"
+ "请在影刀流程开头先调用「37duHR登录(接口版)」指令,或本地先运行 "
+ "python workflows/share/hr_login_api.py")
+
+
+def _request_with_retry(session, method, url, params, timeout, label):
+ """带项目级重试的 HTTP 请求:连接/超时/5xx 等瞬时故障最多重试 MAX_REQUEST_RETRY 次。"""
+ last_exc = None
+ for attempt in range(1, MAX_REQUEST_RETRY + 1):
+ try:
+ resp = session.request(method.upper(), url, data=params, timeout=timeout)
+ resp.raise_for_status()
+ return resp
+ except requests.HTTPError as e:
+ if e.response is not None and e.response.status_code < 500:
+ raise # 4xx 不重试
+ last_exc = e
+ except (requests.ConnectionError, requests.Timeout) as e:
+ last_exc = e
+ if attempt < MAX_REQUEST_RETRY:
+ delay = 2 ** (attempt - 1)
+ logger.warning("%s 第 %d 次请求失败(%s),%d 秒后重试", label, attempt, last_exc, delay)
+ time.sleep(delay)
+ logger.error("%s 请求重试 %d 次仍失败:%s", label, MAX_REQUEST_RETRY, last_exc)
+ raise last_exc
+
+
+def hr_request_json(session, method, url, params, label, timeout=30):
+ """POST/GET 请求(带项目级重试)并校验返回 JSON;失效抛 HRSessionExpiredError。"""
+ resp = _request_with_retry(session, method, url, params, timeout, label)
+ text = resp.text
+ if not text or not text.lstrip().startswith(("{", "[")):
+ raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
+ return resp.json()
+
+
+def build_hr_session():
+ """用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
+ _ensure_hr_cookies()
+ cookies = _load_shared_hr_cookies()
+ session = requests.Session()
+ session.headers.update({
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
+ "Content-Type": "application/x-www-form-urlencoded",
+ })
+ for c in cookies:
+ if c.get("domain") and "37du.co" in c["domain"]:
+ session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
+ return session
+
+
+def fetch_cur_user_info(session):
+ """调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
+ return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
+
+
+def _relogin_get_user_info():
+ """登录态失效后:重建会话(读最新 cookies)→ 重新获取 userId。
+
+ 补登后仍失效时抛出明确提示,引导重新执行登录指令。
+ """
+ try:
+ _ensure_hr_cookies()
+ session = build_hr_session()
+ info = fetch_cur_user_info(session)
+ return session, info.get("userId", "")
+ except HRSessionExpiredError as e:
+ raise HRSessionExpiredError(
+ "补登后 HR 登录态仍失效,请先重新运行「37duHR登录」指令,再重试本流程") from e
+
+
+def fetch_attendance_stat_page(session, user_id, month, page_no=1):
+ """请求单页「考勤统计报表」数据(每人一行,v_1~v_31 为当月逐日出勤状态)。"""
+ params = {
+ "reportId": MONTH_ATT_REPORT_ID,
+ "struId": COMPANY_STRU_ID,
+ "start": (page_no - 1) * REPORT_PAGE_SIZE,
+ "sortType": "",
+ "sortName": "",
+ "pageNo": page_no,
+ "pageSize": REPORT_PAGE_SIZE,
+ "ds1.userId": user_id,
+ "ds1.struId": COMPANY_STRU_ID,
+ "ds1.month": month,
+ "ds2.stru_id": COMPANY_STRU_ID,
+ "ds3.month": "#ds1.month#",
+ "orgTypeCode": "1",
+ "rootId": "cq37du",
+ "showSetField": "1",
+ "menuName": "考勤统计报表",
+ "treePermitType": "permit",
+ "struTreeCode": "cq37du",
+ "belongUnitStruId": COMPANY_STRU_ID,
+ "isVirtual": "0",
+ "isHistory": "undefined",
+ "useSealTreeData": "0",
+ "orgAlias": "集团",
+ "commonQuery": "[]",
+ "ds1.base_code": "",
+ }
+ url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
+ return hr_request_json(session, "POST", url, params, "考勤统计报表")
+
+
+def _fetch_attendance_page_retry(session, user_id, month, page_no):
+ """抓单页考勤报表;登录态失效自动补登重试(上限 RELOGIN_MAX 次)。"""
+ for attempt in range(1, RELOGIN_MAX + 1):
+ try:
+ data = fetch_attendance_stat_page(session, user_id, month, page_no)
+ return session, user_id, data
+ except HRSessionExpiredError:
+ logger.warning("考勤统计报表 HR 登录态过期,自动补登后重试(第 %d/%d 次)",
+ attempt, RELOGIN_MAX)
+ session, user_id = _relogin_get_user_info()
+ raise HRSessionExpiredError(
+ "考勤统计报表:HR 登录态多次补登仍失效,请先重新运行「37duHR登录」指令再重试")
+
+
+def fetch_all_attendance_stat(session, user_id, month):
+ """分页抓取当月「考勤统计报表」全量明细;某页失败直接抛异常终止,绝不返回部分数据。"""
+ all_rows = []
+ page_no = 1
+ while True:
+ session, user_id, data = _fetch_attendance_page_retry(session, user_id, month, page_no)
+ if data.get("state") != "1":
+ raise RuntimeError(f"考勤统计报表第 {page_no} 页请求失败:{data.get('meg')}")
+ page_list = data.get("datas", []) or []
+ if not page_list:
+ logger.info("考勤统计报表无更多数据")
+ break
+ all_rows.extend(page_list)
+ total_page = data.get("pageCount", 0)
+ logger.info("考勤统计报表已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
+ if page_no >= total_page:
+ break
+ page_no += 1
+ time.sleep(0.2)
+ return all_rows
+
+
+def report_row_to_list(rec):
+ """接口行 → 40 列值(与「考勤统计报表」B~AO 对应):
+ 工号/部门全路径/所属单位/所属部门/一级部门/四级部门/岗位名称/技师工号/姓名/1~31日。"""
+ row = [
+ _clean(rec.get("base_code")),
+ _clean(rec.get("org_full_path")),
+ _clean(rec.get("belong_unit_org_name")),
+ _clean(rec.get("dept_org_name")),
+ _clean(rec.get("dept_one")),
+ _clean(rec.get("dept_four")),
+ _clean(rec.get("post_name")),
+ _clean(rec.get("ext_technician_code")),
+ _clean(rec.get("staff_name")),
+ ]
+ row.extend(_clean(rec.get(f"v_{i}")) for i in range(1, 32))
+ return row
+
+
+# ==================== COM 重算 ====================
+def calc_and_save_via_com(target_file):
+ """经 WPS/Excel COM 打开目标文件:取消全部筛选 → 全量重算公式 → 保存关闭。
+
+ openpyxl 覆盖保存后公式缓存丢失,必须全量重算并保存,后续 data_only 读取才有值。
+ 目标文件若已在 WPS/Excel 中打开则复用该工作簿(保存即用户当前所见内容),
+ 此时不会关闭该工作簿、也不会退出程序,避免影响用户正在使用的会话。
+ """
+ abspath = os.path.abspath(target_file)
+ if not os.path.isfile(abspath):
+ raise FileNotFoundError(f"目标文件不存在:{abspath}")
+
+ pythoncom.CoInitialize()
+ try:
+ app = None
+ last_err = None
+ for prog_id in COM_PROG_IDS:
+ try:
+ app = win32com.client.Dispatch(prog_id)
+ break
+ except Exception as e:
+ last_err = e
+ if app is None:
+ raise RuntimeError(
+ "无法启动 WPS/Excel COM(依次尝试 "
+ + " / ".join(COM_PROG_IDS)
+ + f" 均失败):{last_err}。\n"
+ "请确认本机已安装 WPS 或 MS Excel,且已安装依赖:pip install pywin32")
+
+ wb = None
+ already_open = False
+ try:
+ app.DisplayAlerts = False
+ for w in app.Workbooks:
+ try:
+ if os.path.normcase(str(w.FullName or "")) == os.path.normcase(abspath):
+ wb = w
+ already_open = True
+ break
+ except Exception:
+ continue
+ if wb is None:
+ wb = app.Workbooks.Open(abspath)
+
+ removed = 0
+ for ws in wb.Worksheets:
+ try:
+ if ws.AutoFilterMode:
+ ws.AutoFilterMode = False
+ removed += 1
+ except Exception:
+ pass
+
+ try:
+ app.CalculateFullRebuild()
+ except Exception:
+ try:
+ app.CalculateFull()
+ except Exception:
+ app.Calculate()
+
+ wb.Save()
+ logger.info("COM 处理完成:取消 %d 个 sheet 的筛选,公式全量重算并保存%s",
+ removed, "(复用 WPS 中已打开的工作簿)" if already_open else "")
+ finally:
+ try:
+ app.DisplayAlerts = True
+ except Exception:
+ pass
+ if wb is not None and not already_open:
+ try:
+ wb.Close(SaveChanges=False)
+ except Exception:
+ pass
+ try:
+ if app.Workbooks.Count == 0:
+ app.Quit()
+ except Exception:
+ pass
+ finally:
+ pythoncom.CoUninitialize()
+
+
+# ==================== 目标文件选择 ====================
+def _parse_name_dates(filename):
+ """从文件名解析积分日期段集合 → {date}。支持 1009(单日)、1011-12(跨日,
+ 次段可为 2 位日,沿用首段月份),并按起止展开为逐日集合。"""
+ stem = os.path.splitext(filename)[0]
+ if stem.startswith(FILE_PREFIX):
+ stem = stem[len(FILE_PREFIX):]
+ today = date.today()
+ dates = set()
+ first_month = None
+ for seg in stem.split("-"):
+ seg = seg.strip()
+ if re.fullmatch(r"\d{4}", seg):
+ m, d = int(seg[:2]), int(seg[2:])
+ if 1 <= m <= 12 and 1 <= d <= 31:
+ first_month = m
+ dates.add(date(today.year, m, d))
+ elif re.fullmatch(r"\d{2}", seg) and first_month is not None:
+ d = int(seg)
+ if 1 <= d <= 31:
+ dates.add(date(today.year, first_month, d))
+ if len(dates) > 1:
+ lo, hi = min(dates), max(dates)
+ span, cur = set(), lo
+ while cur <= hi:
+ span.add(cur)
+ cur += timedelta(days=1)
+ dates = span
+ return dates
+
+
+def pick_target_file(today):
+ """选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件)。
+
+ 优先文件名日期段包含 T-2 的文件(续用追加);否则复制修改时间最新的文件
+ 另存为「员工出勤及遵章积分导入{T-2 MMDD}.xlsx」作为新批(积分导入/删除表由
+ 调用方清空重写)。目录无数据文件时报错。检测到 ~$ 锁文件时报错提示先关闭 WPS。
+ """
+ if FORCE_FILE:
+ if not os.path.isfile(FORCE_FILE):
+ raise FileNotFoundError(f"FORCE_FILE 指定的文件不存在:{FORCE_FILE}")
+ return os.path.abspath(FORCE_FILE), False
+
+ if not os.path.isdir(TARGET_DIR):
+ raise FileNotFoundError(f"目标目录不存在:{TARGET_DIR}")
+
+ locks = [f for f in os.listdir(TARGET_DIR)
+ if f.startswith("~$") and f.endswith(".xlsx")]
+ if locks:
+ raise RuntimeError(
+ "检测到 WPS/Excel 锁文件(%s),目标文件正被打开,请先关闭后重试" % "、".join(locks))
+
+ files = [f for f in os.listdir(TARGET_DIR)
+ if f.startswith(FILE_PREFIX) and f.endswith(".xlsx")
+ and not f.startswith("~$") and _parse_name_dates(f)]
+ if not files:
+ raise RuntimeError(
+ f"目录 {TARGET_DIR} 下未找到「{FILE_PREFIX}MMDD.xlsx」格式数据文件,请先放入模板文件")
+
+ t2 = today - timedelta(days=2)
+ for f in files:
+ if t2 in _parse_name_dates(f):
+ path = os.path.join(TARGET_DIR, f)
+ logger.info("命中文件名含 T-2(%s) 的数据文件:%s(续用追加模式)", t2.strftime("%m%d"), f)
+ return path, False
+
+ newest = max(files, key=lambda f: os.path.getmtime(os.path.join(TARGET_DIR, f)))
+ new_name = f"{FILE_PREFIX}{t2.strftime('%m%d')}.xlsx"
+ new_path = os.path.join(TARGET_DIR, new_name)
+ if os.path.exists(new_path):
+ logger.warning("新批文件 %s 已存在但文件名未匹配 T-2,直接复用", new_name)
+ return new_path, False
+ shutil.copy2(os.path.join(TARGET_DIR, newest), new_path)
+ logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s", newest, new_name)
+ return new_path, True
+
+
+# ==================== 新增段历史记录 ====================
+def load_state():
+ """读取新增段历史记录(JSON 损坏时按空处理并告警)。"""
+ if not os.path.exists(STATE_FILE):
+ return {}
+ try:
+ with open(STATE_FILE, encoding="utf-8") as f:
+ return json.load(f) or {}
+ except Exception as e:
+ logger.warning("状态文件读取失败(按空历史处理):%s", e)
+ return {}
+
+
+def save_state(state):
+ with open(STATE_FILE, "w", encoding="utf-8") as f:
+ json.dump(state, f, ensure_ascii=False, indent=2)
+
+
+# ==================== sheet 写入 ====================
+def write_report_sheet(wb, rows, year, month):
+ """「考勤统计报表」:B2 月份标题 + B6 起写入全量行(B~AO 40 列),清旧尾部。
+
+ A 列圈人公式为模板预置,不动;写入行数超过公式预置行数时告警(会漏筛)。
+ """
+ ws = wb[SHEET_REPORT]
+ ws["B2"] = f"{year}年{month:02d}月考勤统计报表"
+ old_last = _scan_last_data_row(ws, 2, REPORT_DATA_START)
+ n = _write_block(ws, REPORT_DATA_START, rows, col_start=2, old_last_row=old_last)
+ # A 列公式预置行数检查
+ last_formula = REPORT_DATA_START - 1
+ for r in range(REPORT_DATA_START, ws.max_row + 1):
+ v = ws.cell(row=r, column=1).value
+ if isinstance(v, str) and v.startswith("="):
+ last_formula = r
+ if REPORT_DATA_START + n - 1 > last_formula:
+ logger.warning("考勤统计报表写入 %d 行超过 A 列公式预置行数(%d),超出行不会被圈人公式判定!"
+ "请在模板中下拉 A 列公式后重跑", n, last_formula - REPORT_DATA_START + 1)
+ logger.info("考勤统计报表写入 %d 行(原数据至第 %d 行),标题:%s", n, old_last, ws["B2"].value)
+
+
+def copy_today_to_prev(wb):
+ """「考勤-前一日导出」← 旧「考勤--今日导出」全量(A~AO 41 列,数据行原样平移)。"""
+ ws_src, ws_dst = wb[SHEET_TODAY], wb[SHEET_PREV]
+ old_last = _scan_last_data_row(ws_src, 1, EXP_DATA_START)
+ rows = []
+ for r in range(EXP_DATA_START, old_last + 1):
+ rows.append([ws_src.cell(row=r, column=c).value for c in range(1, 42)])
+ dst_old_last = _scan_last_data_row(ws_dst, 1, EXP_DATA_START)
+ _write_block(ws_dst, EXP_DATA_START, rows, col_start=1, old_last_row=dst_old_last)
+ logger.info("考勤-前一日导出已更新为原今日导出快照:%d 行", len(rows))
+ return len(rows)
+
+
+def select_report_rows(wb_values):
+ """读「考勤统计报表」A 列="正确" 的行,返回 40 列值列表(工号/部门全路径/所属单位/
+ 所属部门/一级部门/四级部门/岗位名称/技师工号/姓名/1~31日,与报表 B~AO 对应),
+ 排除黑名单岗位。read_only 模式必须走 iter_rows,随机 cell 访问会极慢。"""
+ ws = wb_values[SHEET_REPORT]
+ sel = []
+ for row in ws.iter_rows(min_row=REPORT_DATA_START, min_col=1, max_col=41, values_only=True):
+ # row[0]=A 列圈人结果,row[1..40]=B~AO
+ a = row[0]
+ if a is None or row[1] in (None, ""):
+ continue
+ if _clean(a) != "正确":
+ continue
+ data = list(row[1:41])
+ if _clean(data[6]) in EXCLUDE_POSTS: # H 列岗位名称(data[0]=B 工号 → data[6]=H)
+ continue
+ sel.append(data)
+ return sel
+
+
+def write_today_export(wb, sel_rows):
+ """「考勤--今日导出」:清空重写。报表 B~AO 40 列 → A~AN 40 列(平移一列,技师工号落 H 列)。"""
+ ws = wb[SHEET_TODAY]
+ old_last = _scan_last_data_row(ws, 1, EXP_DATA_START)
+ out = []
+ for row in sel_rows:
+ # row: [工号,部门全路径,所属单位,所属部门,一级部门,四级部门,岗位名称,技师工号,姓名,1~31日]
+ out.append([row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]]
+ + [row[9 + i] for i in range(31)])
+ _write_block(ws, EXP_DATA_START, out, col_start=1, old_last_row=old_last)
+ logger.info("考勤--今日导出写入 %d 行(原数据至第 %d 行)", len(out), old_last)
+
+
+def write_compare_values(wb, sel_rows):
+ """「对比结果」:今日导出行前 9 列(工号~姓名)→ B4 起 B~J 值区,旧超出行清空。
+
+ K~AO 差值、AP~BT/BU~CY 镜像、A 列再入职公式为模板预置,不动。
+ """
+ ws = wb[SHEET_CMP]
+ old_last = _scan_last_data_row(ws, 2, CMP_DATA_START)
+ out = [row[:9] for row in sel_rows]
+ n = _write_block(ws, CMP_DATA_START, out, col_start=2, old_last_row=old_last)
+ # 镜像/差值公式预置行数检查(以 AP 列为准)
+ last_formula = CMP_DATA_START - 1
+ for r in range(CMP_DATA_START, ws.max_row + 1):
+ v = ws.cell(row=r, column=42).value
+ if isinstance(v, str) and v.startswith("="):
+ last_formula = r
+ if CMP_DATA_START + n - 1 > last_formula:
+ logger.warning("对比结果写入 %d 行超过公式预置行数(%d),超出行差值/镜像公式缺失!"
+ "请在模板中下拉 K~CY 列公式后重跑", n, last_formula - CMP_DATA_START + 1)
+ logger.info("对比结果写入 %d 行员工信息(原值区至第 %d 行)", n, old_last)
+
+
+# ==================== 对比结果读取与积分计算 ====================
+def read_compare_results(wv, today, t2):
+ """读「对比结果」公式值 → (新增段行, 修正补行列表, 修正删行列表)。
+
+ 新增段:今日镜像 T-2 日列 = 2 的行(跨月时 T-2 不在本月报表,返回空并告警)。
+ 修正段:差值列(今日镜像-前一日镜像)日 1~T-3 中 > 0 补积分 / < 0 删积分。
+ 每行 = (员工信息 9 列, 积分日期 date)。
+ read_only 模式走 iter_rows(min_col=1):行元组 idx = 列号-1
+ (info=B~J 即 idx 1~9,镜像日 d → idx 40+d,差值日 d → idx 9+d)。
+ """
+ ws = wv[SHEET_CMP]
+ month_first = date(today.year, today.month, 1)
+ # 新增段镜像列(仅当 T-2 在本月)
+ mirror_idx = 40 + t2.day if t2 >= month_first else None
+ if mirror_idx is None:
+ logger.warning("T-2(%s) 不在本月报表范围,跳过新增段(月初边缘场景属正常)", t2)
+ # 修正段窗口:本月 1 日 ~ T-3
+ fix_end = t2 - timedelta(days=1)
+ fix_days = []
+ if t2 >= month_first and fix_end >= month_first:
+ fix_days = list(range(month_first.day, fix_end.day + 1))
+
+ new_rows, fix_rows, del_rows = [], [], []
+ for row in ws.iter_rows(min_row=CMP_DATA_START, min_col=1, max_col=72, values_only=True):
+ # row[0]=A 再入职,row[1..9]=B~J 员工信息,row[9+d]=差值列日 d,row[40+d]=今日镜像列日 d
+ info = list(row[1:10])
+ if _clean(info[0]) == "":
+ continue
+ if mirror_idx is not None and mirror_idx < len(row):
+ v = row[mirror_idx]
+ try:
+ if v not in (None, "") and abs(float(v) - 2) < 1e-9:
+ new_rows.append((info, t2))
+ except (TypeError, ValueError):
+ pass
+ for d in fix_days:
+ idx = 9 + d
+ if idx >= len(row):
+ continue
+ v = row[idx]
+ if v in (None, ""):
+ continue
+ try:
+ diff = float(v)
+ except (TypeError, ValueError):
+ continue
+ fix_date = date(today.year, today.month, d)
+ if diff > 0:
+ fix_rows.append((info, fix_date))
+ elif diff < 0:
+ del_rows.append((info, fix_date))
+ fix_rows.sort(key=lambda x: x[1])
+ del_rows.sort(key=lambda x: x[1])
+ return new_rows, fix_rows, del_rows
+
+
+# ==================== 积分表写入 ====================
+def _clear_import_sheets(wb):
+ """新批文件:清空积分导入/删除全部数据行(含 L 查重列之后无内容,清 B~K 即可)。"""
+ for name in (SHEET_IMPORT, SHEET_DELETE):
+ ws = wb[name]
+ last = _scan_last_data_row(ws, 2, IMP_DATA_START)
+ if last >= IMP_DATA_START:
+ ws.delete_rows(IMP_DATA_START, last - IMP_DATA_START + 1)
+ logger.info("%s 已清空(原数据至第 %d 行)", name, last)
+
+
+def _gather_rows_to_delete(ws, today, t2, protected_dates):
+ """收集「积分导入」需删除的行号:
+ 积分日期 ∈ [月首, T-3] 且不在保护集合(历号新增段日 ∪ {T-3}),或积分日期 = T-2(重跑幂等)。
+ B 列(工号)为空的行一律跳过不碰。"""
+ month_first = date(today.year, today.month, 1)
+ t3 = t2 - timedelta(days=1)
+ row_nums = []
+ unknown = 0
+ for r in range(IMP_DATA_START, ws.max_row + 1):
+ if ws.cell(row=r, column=2).value in (None, ""):
+ continue
+ d = _to_date(ws.cell(row=r, column=11).value) # K 积分日期
+ if d is None:
+ unknown += 1
+ continue
+ if d == t2:
+ row_nums.append(r)
+ elif month_first <= d <= t3 and d not in protected_dates:
+ row_nums.append(r)
+ if unknown:
+ logger.warning("积分导入存在 %d 行积分日期无法解析,已原样保留", unknown)
+ return row_nums
+
+
+def write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_new_batch):
+ """「积分导入」:删除旧修正段/同日新增段 → 追加新增段(在前)+ 修正段(按日期升序)。
+
+ 历号新增段保护:状态文件 new_dates + 兜底 {T-3}(上轮新增段日)不删。
+ """
+ ws = wb[SHEET_IMPORT]
+ if is_new_batch:
+ _clear_import_sheets(wb)
+ state.setdefault(file_key, {})["new_dates"] = []
+ protected = set(state.get(file_key, {}).get("new_dates", [])) | {t2 - timedelta(days=1)}
+ row_nums = _gather_rows_to_delete(ws, today, t2, protected)
+ removed = _delete_sheet_rows(ws, row_nums)
+
+ last = _scan_last_data_row(ws, 2, IMP_DATA_START)
+ out = []
+ for info, d in new_rows:
+ out.append(list(info) + [datetime(d.year, d.month, d.day)])
+ for info, d in fix_rows:
+ out.append(list(info) + [datetime(d.year, d.month, d.day)])
+ _write_block(ws, last + 1, out, col_start=2, old_last_row=last)
+
+ # 登记本轮新增段日期(幂等:集合去重)
+ dates = set(state.setdefault(file_key, {}).setdefault("new_dates", []))
+ if t2 >= date(today.year, today.month, 1):
+ dates.add(t2.isoformat())
+ state[file_key]["new_dates"] = sorted(dates)
+ logger.info("积分导入:删除旧行 %d(历史新增段保护日期 %s),追加新增段 %d 行(%s)+ 修正段 %d 行,"
+ "现共 %d 行", removed, state[file_key].get("new_dates") or "无",
+ len(new_rows), t2, len(fix_rows),
+ _scan_last_data_row(ws, 2, IMP_DATA_START) - IMP_DATA_START + 1)
+ return len(out)
+
+
+def write_delete_sheet(wb, today, t2, del_rows):
+ """「积分删除」:修正段(负差值)全月刷新——删除 [月首, T-3] 旧行后按日期升序追加。"""
+ ws = wb[SHEET_DELETE]
+ month_first = date(today.year, today.month, 1)
+ t3 = t2 - timedelta(days=1)
+ row_nums = []
+ for r in range(IMP_DATA_START, ws.max_row + 1):
+ if ws.cell(row=r, column=2).value in (None, ""):
+ continue
+ d = _to_date(ws.cell(row=r, column=11).value)
+ if d is not None and month_first <= d <= t3:
+ row_nums.append(r)
+ removed = _delete_sheet_rows(ws, row_nums)
+
+ last = _scan_last_data_row(ws, 2, IMP_DATA_START)
+ out = [list(info) + [datetime(d.year, d.month, d.day)] for info, d in del_rows]
+ _write_block(ws, last + 1, out, col_start=2, old_last_row=last)
+ logger.info("积分删除:删除旧行 %d,追加修正删行 %d 行,现共 %d 行",
+ removed, len(out), _scan_last_data_row(ws, 2, IMP_DATA_START) - IMP_DATA_START + 1)
+ return len(out)
+
+
+# ==================== 主流程 ====================
+def main(args=None):
+ """入口:影刀「调用模块」main({}),无外部参数。"""
+ started = time.time()
+ today = date.today()
+ t2 = today - timedelta(days=2)
+ month = f"{today.year}-{today.month:02d}"
+ logger.info("===== XQ0033 门店管理及服务岗出勤积分更新开始,运行日 %s,T-2=%s,报表月份 %s =====",
+ today, t2, month)
+
+ # 1. HR 登录态 + 分页拉取当月考勤统计报表
+ session = build_hr_session()
+ info = fetch_cur_user_info(session)
+ user_id = info.get("userId", "")
+ if not user_id:
+ raise RuntimeError("获取当前用户信息失败:userId 为空")
+ raw_rows = fetch_all_attendance_stat(session, user_id, month)
+ if not raw_rows:
+ raise RuntimeError(f"考勤统计报表 {month} 无数据,请检查月份或权限")
+ report_rows = [report_row_to_list(rec) for rec in raw_rows]
+ logger.info("考勤统计报表共 %d 人", len(report_rows))
+
+ # 2. 选择目标文件
+ target_path, is_new_batch = pick_target_file(today)
+ file_key = os.path.basename(target_path)
+ logger.info("目标文件:%s(%s)", target_path, "新批文件" if is_new_batch else "续用追加")
+
+ # 3. 写「考勤统计报表」+ 快照滚动(旧今日导出 → 前一日导出)
+ wb = openpyxl.load_workbook(target_path, data_only=False)
+ for name in (SHEET_REPORT, SHEET_TODAY, SHEET_PREV, SHEET_CMP, SHEET_IMPORT, SHEET_DELETE):
+ if name not in wb.sheetnames:
+ raise RuntimeError(f"目标文件缺少工作表「{name}」,请确认模板完整")
+ write_report_sheet(wb, report_rows, today.year, today.month)
+ copy_today_to_prev(wb)
+ wb.save(target_path)
+ wb.close()
+
+ # 4. COM 重算(A 列圈人公式生效)
+ calc_and_save_via_com(target_path)
+
+ # 5. 读 A 列="正确" 的行(排除黑名单岗位)→ 写今日导出 + 对比结果值区
+ wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
+ sel_rows = select_report_rows(wv)
+ wv.close()
+ if not sel_rows:
+ raise RuntimeError("考勤统计报表 A 列无「正确」行,圈人公式判定异常,请检查模板")
+ logger.info("圈人公式命中 %d 人(已排除岗位:%s)", len(sel_rows), "、".join(sorted(EXCLUDE_POSTS)))
+
+ wb = openpyxl.load_workbook(target_path, data_only=False)
+ write_today_export(wb, sel_rows)
+ write_compare_values(wb, sel_rows)
+ wb.save(target_path)
+ wb.close()
+
+ # 6. COM 重算(差值/镜像公式生效)
+ calc_and_save_via_com(target_path)
+
+ # 7. 读对比结果 → 计算新增段/修正段
+ wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
+ new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2)
+ wv.close()
+ logger.info("积分计算结果:新增段 %d 行(%s),修正补 %d 行,修正删 %d 行",
+ len(new_rows), t2, len(fix_rows), len(del_rows))
+
+ # 8. 写积分导入/积分删除(新增段保护 + 修正段全月刷新)
+ state = load_state()
+ wb = openpyxl.load_workbook(target_path, data_only=False)
+ write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_new_batch)
+ write_delete_sheet(wb, today, t2, del_rows)
+ save_state(state)
+ wb.save(target_path)
+ wb.close()
+
+ # 9. COM 收尾重算保存(SUBTOTAL 等统计公式刷新)
+ calc_and_save_via_com(target_path)
+
+ logger.info("===== XQ0033 完成,总耗时 %.1f 秒 =====", time.time() - started)
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except Exception:
+ traceback.print_exc()
+ raise SystemExit(1)
diff --git a/workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py b/workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py
index 3cb4770..3aca7da 100644
--- a/workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py
+++ b/workflows/XQ0001-0100/XQ0034 续签电子签/step1_renewal_esign.py
@@ -701,3 +701,6 @@ def main(dry_run=None):
logger.error("续签电子签执行异常:%s\n%s", exc, traceback.format_exc())
_set_glv("messages", [f"续签电子签执行异常:{exc}"])
return {"success": False, "message": f"续签电子签执行异常:{exc}", "results": results}
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/workflows/XQ0001-0100/XQ0037 调动改签离职电子签/step5_transfer_aitable.py b/workflows/XQ0001-0100/XQ0037 调动改签离职电子签/step5_transfer_aitable.py
index 1b031a5..7f3a4be 100644
--- a/workflows/XQ0001-0100/XQ0037 调动改签离职电子签/step5_transfer_aitable.py
+++ b/workflows/XQ0001-0100/XQ0037 调动改签离职电子签/step5_transfer_aitable.py
@@ -17,9 +17,12 @@
「本月发起名单」对应行「发起日期」列(openpyxl 直写,试算模式不写);
6. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
-字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect 且选项为会馆名
-(四级部门级),取名单表「现四级部门/原四级部门」列,不是「现单位/原单位」
-(事业部级名称不在选项集,写入报 invalid)。
+字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect,选项为 124 个
+单位名(会馆名 + 石桥铺系「石桥铺会馆-前厅部」式路径名 + 经营中心等),不是
+「现单位/原单位」(事业部级名称不在选项集,写入报 invalid)。取值按选项集
+匹配(fetch_field_choices + pick_unit):候选依次 四级部门 -> 二级-三级 ->
+二级 -> 三级,首个命中选项集者即用;全不命中留空并告警,保证批次不被
+单个无效选项卡死(裸「石桥铺会馆」「礼宾组」均不在选项集)。
date 字段写毫秒时间戳(XQ0035 同款口径);singleSelect 写入传选项名字符串
(读取才返回 {"name","id"} 对象)。
@@ -61,8 +64,8 @@ RECORDS_ADD_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_I
# 名单表「本月发起名单」所需列(按表头名解析,列序无关)
ROSTER_COLS = ("姓名", "工号", "调动时间",
- "现四级部门", "现岗位", "现技师工号",
- "原四级部门", "原岗位", "原技师工号")
+ "现二级部门", "现三级部门", "现四级部门", "现岗位", "现技师工号",
+ "原二级部门", "原三级部门", "原四级部门", "原岗位", "原技师工号")
FIELD_INITIATED = "是否已发起改签离职"
FIELD_INIT_TIME = "发起时间"
@@ -77,6 +80,37 @@ def _s(v):
return str(v).strip() if v is not None else ""
+def fetch_field_choices():
+ """「现/原单位名称」字段选项集(两字段选项一致,取并集兜底)。
+
+ fields 接口响应结构 {"value": [field...]},单选选项在 property.choices。
+ """
+ url = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}"
+ f"/sheets/{TABLE_ID}/fields")
+ d = _aitable_request("GET", url, params={"operatorId": AITABLE_OPERATOR_UNIONID})
+ names = set()
+ for f in d.get("value") or []:
+ if f.get("name") in ("现单位名称", "原单位名称"):
+ names |= {c["name"] for c in (f.get("property") or {}).get("choices") or []
+ if c.get("name")}
+ return names
+
+
+def pick_unit(row, prefix, choices):
+ """单位名称候选依次 四级 -> 二级-三级 -> 二级 -> 三级,首个命中选项集者。
+
+ 金色印象系四级=会馆名直接命中;石桥铺会馆直管体系选项为
+ 「石桥铺会馆-前厅部」式路径名,由 二级-三级 拼接命中。
+ """
+ l2 = row[f"{prefix}二级部门"]
+ l3 = row[f"{prefix}三级部门"]
+ l4 = row[f"{prefix}四级部门"]
+ for cand in (l4, f"{l2}-{l3}" if l2 and l3 else "", l2, l3):
+ if cand and cand in choices:
+ return cand
+ return ""
+
+
def _ms_day(value):
"""datetime / 'yyyy-MM-dd…' / 毫秒时间戳(int) -> 当天 0 点毫秒;失败 None。
@@ -118,9 +152,13 @@ def load_roster_rows():
"姓名": _s(ws.cell(r, header["姓名"]).value),
"工号": code,
"调动时间": ws.cell(r, header["调动时间"]).value,
+ "现二级部门": _s(ws.cell(r, header["现二级部门"]).value),
+ "现三级部门": _s(ws.cell(r, header["现三级部门"]).value),
"现四级部门": _s(ws.cell(r, header["现四级部门"]).value),
"现岗位": _s(ws.cell(r, header["现岗位"]).value),
"现技师工号": _s(ws.cell(r, header["现技师工号"]).value),
+ "原二级部门": _s(ws.cell(r, header["原二级部门"]).value),
+ "原三级部门": _s(ws.cell(r, header["原三级部门"]).value),
"原四级部门": _s(ws.cell(r, header["原四级部门"]).value),
"原岗位": _s(ws.cell(r, header["原岗位"]).value),
"原技师工号": _s(ws.cell(r, header["原技师工号"]).value),
@@ -214,10 +252,11 @@ def backfill_init_dates(rows, items):
return done
-def build_fields(row, today_ms):
- """名单行 + 发起时间 -> AI 表新增行 fields(空值字段不写)。
+def build_fields(row, today_ms, choices):
+ """名单行 + 发起时间 + 选项集 -> AI 表新增行 fields(空值字段不写)。
- singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串。
+ singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串;
+ 单位名称经 pick_unit 匹配选项集,未命中不写该字段(留空告警)。
"""
fields = {
"姓名": row["姓名"],
@@ -228,14 +267,16 @@ def build_fields(row, today_ms):
t = _ms_day(row["调动时间"])
if t:
fields["调动时间"] = t
- if row["现四级部门"]:
- fields["现单位名称"] = row["现四级部门"]
+ u = pick_unit(row, "现", choices)
+ if u:
+ fields["现单位名称"] = u
if row["现岗位"]:
fields["现岗位"] = row["现岗位"]
if row["现技师工号"]:
fields["现技师工号"] = str(row["现技师工号"])
- if row["原四级部门"]:
- fields["原单位名称"] = row["原四级部门"]
+ u = pick_unit(row, "原", choices)
+ if u:
+ fields["原单位名称"] = u
if row["原岗位"]:
fields["原岗位"] = row["原岗位"]
if row["原技师工号"]:
@@ -305,6 +346,9 @@ def main(dry_run=None):
f"{'(试算模式)' if dry_run else ''}")
return stats
+ choices = fetch_field_choices()
+ if not choices:
+ raise RuntimeError("未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
add_items, done_codes, init_items = [], [], []
today_ms = _ms_day(datetime.now())
for code in sorted(initiated):
@@ -323,9 +367,11 @@ def main(dry_run=None):
done_codes.append(code)
init_items.append((code, dup[2]))
continue
- fields = build_fields(row, today_ms)
- _log(f"[回写] {code} {row['姓名']} | 现单位 {row['现四级部门'] or '空'} | "
- f"原单位 {row['原四级部门'] or '空'} | 调动 {row['调动时间']}")
+ fields = build_fields(row, today_ms, choices)
+ warn = "" if ("现单位名称" in fields and "原单位名称" in fields) \
+ else "(存在无匹配选项的单位名称,已留空待人工核对)"
+ _log(f"[回写] {code} {row['姓名']} | 现单位 {fields.get('现单位名称') or '空'} | "
+ f"原单位 {fields.get('原单位名称') or '空'} | 调动 {row['调动时间']}{warn}")
add_items.append(fields)
if add_items and not dry_run: