feat(supply-chain): 店铺授权提醒每日定时推送(11:00)+ 负责人不在内部整店跳过
This commit is contained in:
parent
9996ee83b2
commit
7979671a3d
@ -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" <<EOF
|
||||
[Unit]
|
||||
Description=Furniture store account authorization notice daily push (normal + unauthorized stores)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=$APP_ROOT
|
||||
Environment=NODE_ENV=production
|
||||
EnvironmentFile=$APP_ENV
|
||||
ExecStart=/bin/bash -lc 'set -euo pipefail; cd "$APP_ROOT"; ./node_modules/.bin/tsx scripts/push-store-account-authorization-notice.ts --apply'
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
EOF
|
||||
|
||||
cat >"$TIMER_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=Run Furniture store account authorization notice push daily
|
||||
|
||||
[Timer]
|
||||
OnCalendar=$SCHEDULE
|
||||
Persistent=true
|
||||
RandomizedDelaySec=120
|
||||
Unit=$SERVICE_NAME.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now "$SERVICE_NAME.timer"
|
||||
systemctl list-timers --all "$SERVICE_NAME.timer" --no-pager
|
||||
@ -0,0 +1,81 @@
|
||||
import { config as loadDotenv } from 'dotenv'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
loadDotenv({ path: '.env.local', override: false })
|
||||
loadDotenv()
|
||||
|
||||
function parseMode(argv: string[]) {
|
||||
if (argv.length === 0) return { apply: false }
|
||||
if (argv.length === 1 && argv[0] === '--apply') return { apply: true }
|
||||
if (argv.includes('--help') || argv.includes('-h')) {
|
||||
console.log('Usage: tsx scripts/push-store-account-authorization-notice.ts [--apply]')
|
||||
console.log(' (default) dry-run: 只列出今天会推送的店铺,不发送')
|
||||
console.log(' --apply 实际推送到店铺负责人钉钉(同店铺同日只发一条)')
|
||||
process.exit(0)
|
||||
}
|
||||
throw new Error(`Unknown arguments: ${argv.join(' ')}`)
|
||||
}
|
||||
|
||||
async function ensureServerOnlyStub() {
|
||||
const stubDir = path.join(process.cwd(), 'node_modules', 'server-only')
|
||||
await mkdir(stubDir, { recursive: true })
|
||||
await writeFile(path.join(stubDir, 'index.js'), 'module.exports = {}\n', 'utf8')
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { apply } = parseMode(process.argv.slice(2))
|
||||
await ensureServerOnlyStub()
|
||||
const [
|
||||
{ EMPTY_STORE_ACCOUNT_FILTERS },
|
||||
{ storeAccountManagementRepository },
|
||||
{ storeAccountAuthorizationService },
|
||||
{ storeAccountAuthorizationNoticeService },
|
||||
] = await Promise.all([
|
||||
import('../src/lib/store-account-management'),
|
||||
import('../src/server/repositories/store-account-management.repository'),
|
||||
import('../src/server/services/store-account-authorization.service'),
|
||||
import('../src/server/services/store-account-authorization-notice.service'),
|
||||
])
|
||||
|
||||
// 授权状态以报表库实时数据为准(每天上午约 10:00 刷新),定时任务安排在 11:00 保证取到当天新数据。
|
||||
const records = await storeAccountManagementRepository.listAll({
|
||||
filters: { ...EMPTY_STORE_ACCOUNT_FILTERS, shopState: '0' },
|
||||
})
|
||||
const authorizationStatusByStoreName = await storeAccountAuthorizationService.getStatusMap(
|
||||
records.map((record) => record.storeName),
|
||||
)
|
||||
const byStore = new Map<string, (typeof records)[number]>()
|
||||
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
|
||||
})
|
||||
@ -110,8 +110,8 @@ export function StoreAccountAuthorizationNoticeDialog({
|
||||
) : (
|
||||
<>
|
||||
<p className="notice-rules">
|
||||
仅推送「店铺状态=正常 且 授权状态=未授权」的账号;正常推送给店铺运营负责人,
|
||||
负责人离职或无法接收时按 店铺运营部门负责人 → 店铺运营总监 顺延。
|
||||
仅推送「店铺状态=正常 且 授权状态=未授权」的账号;推送给店铺运营负责人,
|
||||
负责人不在内部账号时整店不推送,负责人离职或无法接收时按 店铺运营部门负责人 → 店铺运营总监 顺延。
|
||||
</p>
|
||||
<div className="notice-preview-list">
|
||||
{rows.length === 0 ? (
|
||||
|
||||
@ -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: '李四' })
|
||||
|
||||
@ -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<StoreAccountAuthorizationNoticeResult> {
|
||||
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<string, StoreAccountNotificationRecipient>()
|
||||
: 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<string, StoreAccountNotificationRecipient>()
|
||||
const internalNames = new Set<string>()
|
||||
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<string, StoreAccountNotificationRecipient>,
|
||||
) {
|
||||
index: Awaited<ReturnType<StoreAccountAuthorizationNoticeService['loadRecipientIndex']>> | 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] ?? '未维护负责人',
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user