diff --git a/furniture-3d-system/scripts/install-store-account-authorization-notice-timer.sh b/furniture-3d-system/scripts/install-store-account-authorization-notice-timer.sh new file mode 100644 index 00000000..f8b8a481 --- /dev/null +++ b/furniture-3d-system/scripts/install-store-account-authorization-notice-timer.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +set -euo pipefail + +BASE="${FURNITURE_PROD_BASE:-/opt/furniture-3d-system-prod}" +SERVICE_NAME="${STORE_ACCOUNT_AUTH_NOTICE_SERVICE_NAME:-furniture-store-account-authorization-notice}" +APP_ROOT="$BASE/current/furniture-3d-system" +APP_ENV="$BASE/shared/.env" +SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service" +TIMER_FILE="/etc/systemd/system/$SERVICE_NAME.timer" +# 授权数据每天上午约 10:00 从聚水潭刷新进公司报表库,任务安排在 11:00 取当天新数据。 +SCHEDULE="${STORE_ACCOUNT_AUTH_NOTICE_SCHEDULE:-*-*-* 11:00:00 Asia/Shanghai}" + +if [ "$(id -u)" -ne 0 ]; then + echo "This installer must run as root." >&2 + exit 1 +fi + +if [ ! -d "$APP_ROOT" ]; then + echo "Missing app root: $APP_ROOT" >&2 + exit 1 +fi + +if [ ! -f "$APP_ENV" ]; then + echo "Missing app env: $APP_ENV" >&2 + exit 1 +fi + +# 授权状态来自公司报表库,推送走通知中心;两组环境变量缺一不可。 +if ! grep -Eq '^JST_REPORT_DB_HOST=.+' "$APP_ENV"; then + echo "JST_REPORT_DB_HOST must be configured in $APP_ENV." >&2 + exit 1 +fi +if ! grep -Eq '^YYD_NOTIFICATION_CENTER_URL=.+' "$APP_ENV"; then + echo "YYD_NOTIFICATION_CENTER_URL must be configured in $APP_ENV." >&2 + exit 1 +fi + +if command -v systemd-analyze >/dev/null 2>&1; then + systemd-analyze calendar "$SCHEDULE" >/dev/null +fi + +cat >"$SERVICE_FILE" <"$TIMER_FILE" < record.storeName), + ) + const byStore = new Map() + for (const record of records) { + if (authorizationStatusByStoreName.get(record.storeName.trim()) !== 'UNAUTHORIZED') continue + const previous = byStore.get(record.storeName) + if (!previous || (previous.accountType !== 'MAIN' && record.accountType === 'MAIN')) { + byStore.set(record.storeName, record) + } + } + const ids = [...byStore.values()].map((record) => record.id) + console.log(`[auth-notice] 店铺状态=正常 且 授权状态=未授权 的店铺(按店铺去重):${ids.length} 家`) + if (ids.length === 0) { + console.log('[auth-notice] 今日无需推送。') + return + } + if (!apply) { + const preview = [...byStore.values()].map((record) => `${record.storeName}(负责人:${record.operationOwner || '未填'})`) + console.log(`[auth-notice] [dry-run] 未发送;确认后加 --apply 执行推送。今天会推送:\n${preview.join('\n')}`) + return + } + + const result = await storeAccountAuthorizationNoticeService.notifyUnauthorizedStores({ + ids, + initiatedByName: '店铺授权提醒定时任务', + }) + console.log(`[auth-notice] 汇总:${JSON.stringify(result.summary)}`) + for (const item of result.items.filter((entry) => entry.status !== 'sent')) { + console.log(`[auth-notice] ${item.status} | ${item.storeName} | ${item.reason}`) + } +} + +main().catch((error) => { + console.error(`店铺授权提醒推送失败:${error instanceof Error ? error.message : String(error)}`) + process.exitCode = 1 +}) diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountAuthorizationNoticeDialog.tsx b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountAuthorizationNoticeDialog.tsx index fbe22fb2..bf50d393 100644 --- a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountAuthorizationNoticeDialog.tsx +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountAuthorizationNoticeDialog.tsx @@ -110,8 +110,8 @@ export function StoreAccountAuthorizationNoticeDialog({ ) : ( <>

- 仅推送「店铺状态=正常 且 授权状态=未授权」的账号;正常推送给店铺运营负责人, - 负责人离职或无法接收时按 店铺运营部门负责人 → 店铺运营总监 顺延。 + 仅推送「店铺状态=正常 且 授权状态=未授权」的账号;推送给店铺运营负责人, + 负责人不在内部账号时整店不推送,负责人离职或无法接收时按 店铺运营部门负责人 → 店铺运营总监 顺延。

{rows.length === 0 ? ( diff --git a/furniture-3d-system/src/server/services/__tests__/store-account-authorization-notice.service.test.ts b/furniture-3d-system/src/server/services/__tests__/store-account-authorization-notice.service.test.ts index ef8c0496..2179c27a 100644 --- a/furniture-3d-system/src/server/services/__tests__/store-account-authorization-notice.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/store-account-authorization-notice.service.test.ts @@ -201,9 +201,32 @@ describe('store account authorization notice recipients', () => { expect(sendToEmployee).toHaveBeenCalledWith(expect.objectContaining({ recipientUserId: 'director-1' })) }) + it('skips the whole store when the owner is not an internal account', async () => { + const record = buildRecord() + const head = buildRecipient({ id: 'head-1', name: '李四' }) + const { service, sendToEmployee } = setupService([record], [head]) + const result = await service.notifyUnauthorizedStores({ ids: ['account-1'], user, now }) + expect(result.items[0]).toMatchObject({ status: 'skipped', recipientName: '张三' }) + expect(result.items[0].reason).toContain('不在内部账号,整店不推送') + expect(sendToEmployee).not.toHaveBeenCalled() + }) + + it('skips the whole store when the owner is an external account', async () => { + const record = buildRecord() + const supplierOwner = buildRecipient({ + id: 'owner-1', name: '张三', businessRoles: ['SUPPLIER' as never], + }) + const { service, sendToEmployee } = setupService([record], [supplierOwner]) + const result = await service.notifyUnauthorizedStores({ ids: ['account-1'], user, now }) + expect(result.items[0]).toMatchObject({ status: 'skipped' }) + expect(result.items[0].reason).toContain('不在内部账号,整店不推送') + expect(sendToEmployee).not.toHaveBeenCalled() + }) + it('marks failure with an audit record when nobody in the chain can receive', async () => { const record = buildRecord() - const { service, sendToEmployee, recordUndeliverable } = setupService([record], []) + const departedOwner = buildRecipient({ id: 'owner-1', name: '张三', status: 'INACTIVE' }) + const { service, sendToEmployee, recordUndeliverable } = setupService([record], [departedOwner]) const result = await service.notifyUnauthorizedStores({ ids: ['account-1'], user, now }) expect(result.items[0]).toMatchObject({ status: 'failed' }) expect(result.items[0].reason).toContain('均无法接收') @@ -213,6 +236,18 @@ describe('store account authorization notice recipients', () => { })) }) + it('runs without a user for scheduled jobs using SYSTEM source', async () => { + const record = buildRecord() + const owner = buildRecipient() + const { service, sendToEmployee } = setupService([record], [owner]) + const result = await service.notifyUnauthorizedStores({ ids: ['account-1'], now }) + expect(result.summary).toEqual({ total: 1, sent: 1, skipped: 0, failed: 0 }) + expect(sendToEmployee).toHaveBeenCalledWith(expect.objectContaining({ + source: 'SYSTEM', + initiatedByName: '店铺授权提醒任务', + })) + }) + it('reports delivery failures per account without stopping the batch', async () => { const first = buildRecord({ id: 'account-1', storeName: '拼多多-测试店铺' }) const second = buildRecord({ id: 'account-2', storeName: '拼多多-另一家店', operationOwner: '李四' }) diff --git a/furniture-3d-system/src/server/services/store-account-authorization-notice.service.ts b/furniture-3d-system/src/server/services/store-account-authorization-notice.service.ts index 7f78b98b..e8f7f39e 100644 --- a/furniture-3d-system/src/server/services/store-account-authorization-notice.service.ts +++ b/furniture-3d-system/src/server/services/store-account-authorization-notice.service.ts @@ -29,7 +29,7 @@ import { export const STORE_ACCOUNT_AUTHORIZATION_NOTICE_EVENT = 'store_account_authorization_notice' -// 推送目标解析顺序:正常只推店铺运营负责人;负责人离职或无在职内部账号时按部门负责人、运营总监顺延。 +// 推送目标解析顺序:店铺运营负责人不在内部账号时整店跳过;负责人在职但离职/无法接收时按部门负责人、运营总监顺延。 const RECIPIENT_CHAIN = [ { key: 'operationOwner', label: '店铺运营负责人' }, { key: 'operationDepartmentHead', label: '店铺运营部门负责人' }, @@ -72,16 +72,22 @@ export class StoreAccountAuthorizationNoticeService { async notifyUnauthorizedStores(params: { ids: string[] testRecipientName?: string - user: AuthUser + user?: AuthUser + initiatedByName?: string now?: Date }): Promise { - const access = await supplyChainPermissionSettingsService.getUserAccess( - params.user, - 'storeAccountManagement', - ) - if (!access.edit) { - throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有触发店铺授权提醒推送的权限') + if (params.user) { + const access = await supplyChainPermissionSettingsService.getUserAccess( + params.user, + 'storeAccountManagement', + ) + if (!access.edit) { + throw new AppError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有触发店铺授权提醒推送的权限') + } } + const source = params.user ? 'USER' as const : 'SYSTEM' as const + const initiatedById = params.user?.id + const initiatedByName = params.user?.name ?? params.initiatedByName ?? '店铺授权提醒任务' const now = params.now ?? new Date() const day = formatDayBucket(now) @@ -93,9 +99,9 @@ export class StoreAccountAuthorizationNoticeService { ) const testRecipient = await this.resolveTestRecipient(params.testRecipientName) - const deliverableUserByName = testRecipient - ? new Map() - : await this.loadDeliverableUsers(records) + const recipientIndex = testRecipient + ? null + : await this.loadRecipientIndex(records) const items: StoreAccountAuthorizationNoticeItem[] = [] for (const id of ids) { @@ -134,9 +140,19 @@ export class StoreAccountAuthorizationNoticeService { const target = testRecipient ? { recipient: testRecipient, role: '测试收件人' } - : this.resolveChainRecipient(record, deliverableUserByName) + : this.resolveChainRecipient(record, recipientIndex) + if (target && 'skip' in target) { + items.push({ + storeName: record.storeName, + recipientName: record.operationOwner.trim(), + recipientRole: '店铺运营负责人', + status: 'skipped', + reason: target.reason, + }) + continue + } if (!target) { - await this.recordNoRecipientAudit(record, day, params.user) + await this.recordNoRecipientAudit(record, day, initiatedById, initiatedByName) items.push({ storeName: record.storeName, recipientName: '', @@ -158,9 +174,9 @@ export class StoreAccountAuthorizationNoticeService { idempotencyKey, businessEvent: STORE_ACCOUNT_AUTHORIZATION_NOTICE_EVENT, businessRecordId: record.id, - source: 'USER', - initiatedById: params.user.id, - initiatedByName: params.user.name, + source, + initiatedById, + initiatedByName, recipientUserId: target.recipient.id, title: '店铺授权提醒', content: formatNoticeContent(record.storeName), @@ -203,7 +219,7 @@ export class StoreAccountAuthorizationNoticeService { return matched } - private async loadDeliverableUsers(records: StoreAccountRecord[]) { + private async loadRecipientIndex(records: StoreAccountRecord[]) { const names = [ ...new Set( records @@ -213,27 +229,43 @@ export class StoreAccountAuthorizationNoticeService { ] const users = names.length > 0 ? await this.userReader.findUsersByNames(names) : [] const deliverableByName = new Map() + const internalNames = new Set() for (const user of users) { - if (!isDeliverableRecipient(user)) continue - if (!deliverableByName.has(user.name)) deliverableByName.set(user.name, user) + // 供应商等外部账号不算内部人员,既不推送也不算“离职顺延”。 + if (user.businessRoles.some((role) => EXTERNAL_ACCOUNT_ROLES.has(role))) continue + internalNames.add(user.name) + if (isDeliverableRecipient(user) && !deliverableByName.has(user.name)) { + deliverableByName.set(user.name, user) + } } - return deliverableByName + return { deliverableByName, internalNames } } + // 返回 { recipient, role } 表示可推送;{ skip, reason } 表示负责人不在内部、整店跳过;null 表示三级都收不了。 private resolveChainRecipient( record: StoreAccountRecord, - deliverableUserByName: Map, - ) { + index: Awaited> | null, + ): { recipient: StoreAccountNotificationRecipient; role: string } | { skip: true; reason: string } | null { + if (!index) return null + const ownerName = record.operationOwner.trim() + if (ownerName && !index.internalNames.has(ownerName)) { + return { skip: true, reason: `店铺运营负责人「${ownerName}」不在内部账号,整店不推送` } + } for (const { key, label } of RECIPIENT_CHAIN) { const name = record[key].trim() if (!name) continue - const recipient = deliverableUserByName.get(name) + const recipient = index.deliverableByName.get(name) if (recipient) return { recipient, role: label } } return null } - private async recordNoRecipientAudit(record: StoreAccountRecord, day: string, user: AuthUser) { + private async recordNoRecipientAudit( + record: StoreAccountRecord, + day: string, + initiatedById: string | undefined, + initiatedByName: string, + ) { const chainNames = RECIPIENT_CHAIN.map(({ key }) => record[key].trim()).filter(Boolean) const auditId = `missing:store-account-auth-notice:${record.id}` try { @@ -242,9 +274,9 @@ export class StoreAccountAuthorizationNoticeService { idempotencyKey: `${STORE_ACCOUNT_AUTHORIZATION_NOTICE_EVENT}:${record.id}:${day}:no-recipient`, businessEvent: STORE_ACCOUNT_AUTHORIZATION_NOTICE_EVENT, businessRecordId: record.id, - source: 'USER', - initiatedById: user.id, - initiatedByName: user.name, + source: initiatedById ? 'USER' : 'SYSTEM', + initiatedById, + initiatedByName, recipient: { id: auditId, name: chainNames[chainNames.length - 1] ?? '未维护负责人',