This commit is contained in:
Your Name
2026-09-07 10:07:47 +08:00
parent cf3fbdc5ef
commit d5164b7369
388 changed files with 19863 additions and 18720 deletions
@@ -359,9 +359,37 @@ class WecomPromotionLogic
$automation,
$skipVerify,
$createdRemote,
&$eligibleUserIds,
$now,
$adminId
): void {
if ($existingPool !== null) {
$lockedPool = Db::name('qywx_promotion_pool')
->where('id', $id)
->whereNull('delete_time')
->lock(true)
->find();
if (!$lockedPool) {
throw new RuntimeException('分流方案不存在或已删除');
}
Db::name('qywx_promotion_range_sync')->where('pool_id', $id)->lock(true)->find();
$lockedRules = Db::name('qywx_promotion_pool_member')
->where('pool_id', $id)
->order('id', 'asc')
->lock(true)
->select()->toArray();
$lockedActiveRules = array_values(array_filter(
$lockedRules,
static fn (array $rule): bool => ($rule['delete_time'] ?? null) === null
));
// 用锁内最新状态再校验最终成员集合,避免与单个或批量下线并发后留下空范围。
$eligibleUserIds = self::eligibleSelectedUserIds(
$id,
$members,
$automation ?? [],
$lockedActiveRules
);
}
if ($existingPool === null) {
$id = (int) Db::name('qywx_promotion_pool')->insertGetId($poolData + [
'public_key' => bin2hex(random_bytes(16)),
@@ -428,7 +456,13 @@ class WecomPromotionLogic
}
$syncError = '';
if (!$createdRemote) {
// 已有方案补建官方链接时,创建接口发生在事务锁之前;若锁内成员范围已变化,
// 仍需把最终范围加入同步队列,避免新链接停留在过期的远端成员集合。
$createdRangeChanged = $createdRemote
&& $remote !== null
&& !QywxPromotionMemberRange::same((array) ($remote['range_userids'] ?? []), $eligibleUserIds);
$needsQueuedSync = !$createdRemote || $createdRangeChanged;
if ($needsQueuedSync) {
QywxPromotionMemberSchedulerService::requestPoolSync($id, $linkId);
if ($syncImmediately) {
try {
@@ -455,15 +489,15 @@ class WecomPromotionLogic
// 前端据此确认标签、欢迎语等扩展配置已和方案一并提交并完成回读校验。
'automation_saved' => $automation !== null,
'sync_error' => $syncError,
'sync_queued' => !$createdRemote && !$syncImmediately,
'sync_queued' => $needsQueuedSync && !$syncImmediately,
];
}
/**
* 批量局部更新分流方案。changes 只覆盖显式传入的字段;每个方案仍复用
* savePool 的成员、自动化、素材和企业微信同步校验。
* 批量局部更新分流方案。changes 只覆盖显式传入的字段;方案配置仍复用
* savePool 的成员、自动化、素材和企业微信同步校验,员工状态按方案合并更新
*
* @return array{pool_ids:list<int>,updated:int,failed:int,sync_error_count:int,sync_queued_count:int,results:list<array<string,mixed>>}
* @return array{pool_ids:list<int>,updated:int,failed:int,sync_error_count:int,sync_queued_count:int,member_matched:int,member_updated:int,results:list<array<string,mixed>>}
*/
public static function batchUpdatePools(array $params, int $adminId, array $adminInfo): array
{
@@ -481,7 +515,7 @@ class WecomPromotionLogic
if (!is_array($changes)) {
throw new RuntimeException('批量修改内容格式不正确');
}
$allowedFields = ['skip_verify', 'fallback_url', 'status', 'automation_config'];
$allowedFields = ['skip_verify', 'fallback_url', 'status', 'automation_config', 'member_status'];
$unknownFields = array_diff(array_keys($changes), $allowedFields);
if ($unknownFields !== []) {
throw new RuntimeException('批量修改包含不支持的字段');
@@ -493,6 +527,31 @@ class WecomPromotionLogic
throw new RuntimeException('兜底获客助手链接格式不正确');
}
$memberStatusPatch = null;
if (array_key_exists('member_status', $changes)) {
if (!is_array($changes['member_status'])) {
throw new RuntimeException('员工上下线配置格式不正确');
}
if (array_diff(array_keys($changes['member_status']), ['member_admin_ids', 'status']) !== []) {
throw new RuntimeException('员工上下线配置包含不支持的字段');
}
$memberAdminIds = self::normalizePositiveIds((array) ($changes['member_status']['member_admin_ids'] ?? []));
if ($memberAdminIds === []) {
throw new RuntimeException('请至少选择一名需要批量上线或下线的员工');
}
if (count($memberAdminIds) > 100) {
throw new RuntimeException('单次最多设置 100 名员工');
}
$memberStatus = $changes['member_status']['status'] ?? null;
if (!in_array($memberStatus, [0, 1, '0', '1'], true)) {
throw new RuntimeException('员工上线状态只能为上线或下线');
}
$memberStatusPatch = [
'member_admin_ids' => $memberAdminIds,
'status' => (int) $memberStatus,
];
}
$automationPatch = null;
if (array_key_exists('automation_config', $changes)) {
if (!is_array($changes['automation_config']) || $changes['automation_config'] === []) {
@@ -510,6 +569,9 @@ class WecomPromotionLogic
QywxPromotionConfig::assertInstalled();
$automationPatch = $changes['automation_config'];
}
if ($memberStatusPatch !== null && count($changes) > 1) {
throw new RuntimeException('员工上下线需要单独批量保存,请勿与其他方案配置同时修改');
}
// 必须在任何方案写入前完成整批权限校验,避免越权请求产生部分更新。
$pools = [];
@@ -523,11 +585,48 @@ class WecomPromotionLogic
);
}
// 在任何方案写入前验证员工范围和“至少一名上线员工”约束,避免可预见的部分更新。
if ($memberStatusPatch !== null) {
$memberRowsByPool = [];
foreach (Db::name('qywx_promotion_pool_member')
->whereIn('pool_id', $poolIds)
->whereNull('delete_time')
->select()->toArray() as $memberRow) {
$memberRowsByPool[(int) ($memberRow['pool_id'] ?? 0)][] = $memberRow;
}
$matchedMembers = 0;
foreach ($poolIds as $poolId) {
$simulatedAutomation = QywxPromotionConfig::forPool($poolId);
if ($automationPatch !== null) {
$simulatedAutomation = QywxPromotionConfig::normalize(array_replace(
$simulatedAutomation,
$automationPatch
));
}
$poolMembers = $memberRowsByPool[$poolId] ?? [];
$simulatedAutomation = self::automationWithMemberUserIds($simulatedAutomation, $poolMembers);
$preview = self::previewPoolMemberStatus(
$poolMembers,
$memberStatusPatch['member_admin_ids'],
$memberStatusPatch['status'],
$simulatedAutomation,
(string) ($pools[$poolId]['name'] ?? ('#' . $poolId))
);
$matchedMembers += count($preview['matched_ids']);
}
if ($matchedMembers === 0) {
throw new RuntimeException('所选方案中没有找到指定员工,请刷新页面后重试');
}
}
$results = [];
$updated = 0;
$failed = 0;
$syncErrorCount = 0;
$syncQueuedCount = 0;
$memberMatched = 0;
$memberUpdated = 0;
$hasPoolConfigChanges = array_diff(array_keys($changes), ['member_status']) !== [];
foreach ($poolIds as $poolId) {
$pool = $pools[$poolId];
$currentAutomation = QywxPromotionConfig::forPool($poolId);
@@ -565,14 +664,28 @@ class WecomPromotionLogic
}
try {
// 批量操作只落本地并入同步队列,避免大量企微请求阻塞管理端 HTTP 请求。
$saved = self::savePool($saveParams, $adminId, $adminInfo, false);
$saved = ['sync_error' => '', 'sync_queued' => false];
if ($hasPoolConfigChanges) {
// 批量操作只落本地并入同步队列,避免大量企微请求阻塞管理端 HTTP 请求。
$saved = self::savePool($saveParams, $adminId, $adminInfo, false);
}
$poolMemberResult = ['matched' => 0, 'updated' => 0, 'dispatch' => null];
if ($memberStatusPatch !== null) {
$poolMemberResult = self::updatePoolMemberStatuses(
$poolId,
$memberStatusPatch['member_admin_ids'],
$memberStatusPatch['status']
);
$memberMatched += $poolMemberResult['matched'];
$memberUpdated += $poolMemberResult['updated'];
}
$syncError = trim((string) ($saved['sync_error'] ?? ''));
$updated++;
if ($syncError !== '') {
$syncErrorCount++;
}
$syncQueued = !empty($saved['sync_queued']);
$syncQueued = !empty($saved['sync_queued'])
|| !empty($poolMemberResult['dispatch']['queued']);
if ($syncQueued) {
$syncQueuedCount++;
}
@@ -582,6 +695,8 @@ class WecomPromotionLogic
'success' => true,
'sync_error' => $syncError,
'sync_queued' => $syncQueued,
'member_matched' => $poolMemberResult['matched'],
'member_updated' => $poolMemberResult['updated'],
];
} catch (\Throwable $error) {
$failed++;
@@ -600,10 +715,156 @@ class WecomPromotionLogic
'failed' => $failed,
'sync_error_count' => $syncErrorCount,
'sync_queued_count' => $syncQueuedCount,
'member_matched' => $memberMatched,
'member_updated' => $memberUpdated,
'results' => $results,
];
}
/**
* @param list<int> $memberAdminIds
* @return array{matched:int,updated:int,dispatch:?array}
*/
private static function updatePoolMemberStatuses(int $poolId, array $memberAdminIds, int $status): array
{
return Db::transaction(function () use ($poolId, $memberAdminIds, $status): array {
// 先锁方案阻止同方案获客回调进入,再按“同步任务 -> 成员规则”顺序加锁。
$pool = Db::name('qywx_promotion_pool')->where('id', $poolId)->whereNull('delete_time')->lock(true)->find();
if (!$pool) {
throw new RuntimeException('分流方案不存在或已删除');
}
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->lock(true)->find();
$members = Db::name('qywx_promotion_pool_member')
->where('pool_id', $poolId)
->whereNull('delete_time')
->lock(true)
->select()->toArray();
$preview = self::previewPoolMemberStatus(
$members,
$memberAdminIds,
$status,
QywxPromotionConfig::forPool($poolId)
);
$matchedIds = $preview['matched_ids'];
$updateIds = $preview['update_ids'];
if ($updateIds !== []) {
Db::name('qywx_promotion_pool_member')->whereIn('id', $updateIds)->update([
'enabled' => $status,
'update_time' => time(),
]);
}
$dispatch = $updateIds !== []
? QywxPromotionMemberSchedulerService::reconcilePool($poolId)
: null;
// 下线必须能够安全收缩远端范围;上线即使尚未到生效时段,也应先保存规则。
if ($dispatch !== null && $status === 0) {
self::assertMemberDispatchReady($dispatch);
}
return [
'matched' => count($matchedIds),
'updated' => count($updateIds),
'dispatch' => $dispatch,
];
});
}
/**
* @param list<array<string,mixed>> $members
* @param list<int> $memberAdminIds
* @param array<string,mixed> $automation
* @return array{members:list<array<string,mixed>>,matched_ids:list<int>,update_ids:list<int>}
*/
private static function previewPoolMemberStatus(
array $members,
array $memberAdminIds,
int $status,
array $automation,
string $poolName = ''
): array {
$targetAdminIds = array_fill_keys($memberAdminIds, true);
$matchedIds = [];
$updateIds = [];
$targetedEnabled = 0;
$remainingEnabled = 0;
foreach ($members as &$member) {
$isTarget = isset($targetAdminIds[(int) ($member['admin_id'] ?? 0)]);
if ($isTarget) {
$matchedIds[] = (int) ($member['id'] ?? 0);
if ((int) ($member['enabled'] ?? 0) !== $status) {
$updateIds[] = (int) ($member['id'] ?? 0);
}
}
if ((int) ($member['enabled'] ?? 0) === 1) {
if ($isTarget) {
$targetedEnabled++;
} else {
$remainingEnabled++;
}
}
if ($isTarget) {
$member['enabled'] = $status;
}
}
unset($member);
if ($status === 0 && $targetedEnabled > 0 && $remainingEnabled === 0) {
throw new RuntimeException(self::memberStatusError(
$poolName,
'至少需要保留一名上线员工'
));
}
if ($status === 0 && $targetedEnabled > 0) {
$range = QywxPromotionMemberRange::evaluate($members, date('Y-m-d'), time(), $automation);
if ($range['userids'] === []) {
throw new RuntimeException(self::memberStatusError(
$poolName,
'至少需要保留一名当前可用的上线员工'
));
}
}
return ['members' => $members, 'matched_ids' => $matchedIds, 'update_ids' => $updateIds];
}
private static function memberStatusError(string $poolName, string $message): string
{
return $poolName === '' ? $message : sprintf('分流方案“%s”%s', $poolName, $message);
}
/** @param array<string,mixed> $dispatch */
private static function assertMemberDispatchReady(array $dispatch): void
{
if (!empty($dispatch['blocked'])) {
throw new RuntimeException('企业微信成员范围当前无法同步,请先检查官方链接状态和可用员工');
}
}
/** @param array<string,mixed> $automation @param list<array<string,mixed>> $members */
private static function automationWithMemberUserIds(array $automation, array $members): array
{
$userIdByAdminId = [];
foreach ($members as $member) {
$adminId = (int) ($member['admin_id'] ?? 0);
$userId = trim((string) ($member['userid'] ?? ''));
if ($adminId > 0 && $userId !== '') {
$userIdByAdminId[$adminId] = $userId;
}
}
$automation['backup_userids'] = array_values(array_filter(array_map(
static fn ($adminId): string => $userIdByAdminId[(int) $adminId] ?? '',
(array) ($automation['backup_member_admin_ids'] ?? [])
)));
foreach ((array) ($automation['reception_schedule'] ?? []) as $index => $slot) {
$automation['reception_schedule'][$index]['member_userids'] = array_values(array_filter(array_map(
static fn ($adminId): string => $userIdByAdminId[(int) $adminId] ?? '',
(array) ($slot['member_admin_ids'] ?? [])
)));
}
return $automation;
}
public static function saveWidget(array $params, int $adminId, array $adminInfo): array
{
$id = max(0, (int) ($params['pool_id'] ?? $params['id'] ?? 0));
@@ -877,36 +1138,93 @@ class WecomPromotionLogic
$poolId = (int) $member['pool_id'];
self::assertScopedRow('qywx_promotion_pool', $poolId, $adminId, $adminInfo);
$enabled = (int) ($params['status'] ?? $params['enabled'] ?? 1) === 1 ? 1 : 0;
if ($enabled === 0) {
$otherEnabled = (int) Db::name('qywx_promotion_pool_member')
->where('pool_id', $poolId)
->where('id', '<>', $id)
->where('enabled', 1)
->whereNull('delete_time')
->count();
if ($otherEnabled <= 0) {
throw new RuntimeException('至少需要保留一名启用的获客医助');
}
}
$startAt = self::parseTime($params['active_start'] ?? null);
$endAt = self::parseTime($params['active_end'] ?? null);
$statusOnly = !empty($params['_status_only']);
$startAt = $statusOnly ? 0 : self::parseTime($params['active_start'] ?? null);
$endAt = $statusOnly ? 0 : self::parseTime($params['active_end'] ?? null);
if ($startAt > 0 && $endAt > 0 && $endAt <= $startAt) {
throw new RuntimeException('生效结束时间必须晚于开始时间');
}
$now = time();
Db::transaction(function () use ($id, $enabled, $params, $startAt, $endAt, $now): void {
Db::name('qywx_promotion_pool_member')->where('id', $id)->update([
$planned = Db::transaction(function () use (
$id,
$poolId,
$enabled,
$statusOnly,
$params,
$startAt,
$endAt,
$now
): array {
// 所有成员状态写入口使用相同锁顺序,防止单个与批量下线并发绕过保底校验。
$lockedPool = Db::name('qywx_promotion_pool')->where('id', $poolId)->whereNull('delete_time')->lock(true)->find();
if (!$lockedPool) {
throw new RuntimeException('分流方案不存在或已删除');
}
Db::name('qywx_promotion_range_sync')->where('pool_id', $poolId)->lock(true)->find();
$members = Db::name('qywx_promotion_pool_member')
->where('pool_id', $poolId)
->whereNull('delete_time')
->order('id', 'asc')
->lock(true)
->select()->toArray();
$lockedMember = null;
foreach ($members as $current) {
if ((int) ($current['id'] ?? 0) === $id) {
$lockedMember = $current;
break;
}
}
if ($lockedMember === null) {
throw new RuntimeException('分流成员不存在或已移除');
}
$memberData = [
'enabled' => $enabled,
// 企业微信原生多人路由不支持逐成员权重;字段固定为 1,仅兼容已部署表结构。
'weight' => 1,
'daily_limit' => min(1000000, max(0, (int) ($params['daily_limit'] ?? 0))),
'active_start' => $startAt,
'active_end' => $endAt,
'remark' => mb_substr(trim((string) ($params['remark'] ?? '')), 0, 255),
'daily_limit' => $statusOnly
? (int) ($lockedMember['daily_limit'] ?? 0)
: min(1000000, max(0, (int) ($params['daily_limit'] ?? 0))),
'active_start' => $statusOnly ? (int) ($lockedMember['active_start'] ?? 0) : $startAt,
'active_end' => $statusOnly ? (int) ($lockedMember['active_end'] ?? 0) : $endAt,
'remark' => $statusOnly
? (string) ($lockedMember['remark'] ?? '')
: mb_substr(trim((string) ($params['remark'] ?? '')), 0, 255),
'update_time' => $now,
]);
];
$isGoingOffline = (int) ($lockedMember['enabled'] ?? 0) === 1 && $enabled === 0;
$simulatedMembers = $members;
$enabledAfter = 0;
foreach ($simulatedMembers as &$simulatedMember) {
if ((int) ($simulatedMember['id'] ?? 0) === $id) {
$simulatedMember = array_replace($simulatedMember, $memberData);
}
if ((int) ($simulatedMember['enabled'] ?? 0) === 1) {
$enabledAfter++;
}
}
unset($simulatedMember);
if ($isGoingOffline) {
if ($enabledAfter === 0) {
throw new RuntimeException('至少需要保留一名启用的获客医助');
}
}
$today = date('Y-m-d', $now);
$automation = QywxPromotionConfig::forPool($poolId);
$currentRange = QywxPromotionMemberRange::evaluate($members, $today, $now, $automation);
$nextRange = QywxPromotionMemberRange::evaluate($simulatedMembers, $today, $now, $automation);
$rangeShrank = array_diff($currentRange['userids'], $nextRange['userids']) !== [];
if (($isGoingOffline || $rangeShrank) && $nextRange['userids'] === []) {
throw new RuntimeException('至少需要保留一名当前可用的上线员工');
}
Db::name('qywx_promotion_pool_member')->where('id', $id)->whereNull('delete_time')->update($memberData);
$dispatch = QywxPromotionMemberSchedulerService::reconcilePool($poolId);
if ($isGoingOffline || $rangeShrank) {
self::assertMemberDispatchReady($dispatch);
}
return $dispatch;
});
$planned = QywxPromotionMemberSchedulerService::reconcilePool($poolId);
$syncError = '';
if ($planned['queued']) {
try {
@@ -931,10 +1249,7 @@ class WecomPromotionLogic
return self::saveMember([
'id' => $id,
'status' => $status,
'daily_limit' => (int) ($row['daily_limit'] ?? 0),
'active_start' => (int) ($row['active_start'] ?? 0),
'active_end' => (int) ($row['active_end'] ?? 0),
'remark' => (string) ($row['remark'] ?? ''),
'_status_only' => true,
], $adminId, $adminInfo);
}
@@ -1274,14 +1589,19 @@ class WecomPromotionLogic
}
/** @param list<array{id:int,userid:string}> $members @return list<string> */
private static function eligibleSelectedUserIds(int $poolId, array $members, array $config = []): array
private static function eligibleSelectedUserIds(
int $poolId,
array $members,
array $config = [],
?array $existingRules = null
): array
{
if ($members === []) {
throw new RuntimeException('请至少选择一名获客成员');
}
$rules = $poolId > 0
$rules = $existingRules ?? ($poolId > 0
? Db::name('qywx_promotion_pool_member')->where('pool_id', $poolId)->whereNull('delete_time')->select()->toArray()
: [];
: []);
$rulesByUserId = [];
foreach ($rules as $rule) {
$rulesByUserId[(string) $rule['userid']] = $rule;