feat(platform-orders): queue batch activate subscriptions job

This commit is contained in:
萝卜
2026-03-17 12:40:21 +08:00
parent 5158703a3e
commit e9ec968379
4 changed files with 206 additions and 91 deletions

View File

@@ -0,0 +1,110 @@
<?php
namespace App\Jobs;
use App\Models\PlatformOrder;
use App\Support\SubscriptionActivationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class BatchActivateSubscriptionsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var int[] */
public array $orderIds;
public int $adminId;
public string $scope;
public string $filterSummary;
public int $limit;
public int $matchedTotal;
public int $processed;
/**
* @param int[] $orderIds
*/
public function __construct(
array $orderIds,
int $adminId,
string $scope,
string $filterSummary,
int $limit,
int $matchedTotal,
int $processed,
) {
$this->orderIds = array_values(array_map('intval', $orderIds));
$this->adminId = $adminId;
$this->scope = $scope;
$this->filterSummary = $filterSummary;
$this->limit = $limit;
$this->matchedTotal = $matchedTotal;
$this->processed = $processed;
}
public function handle(SubscriptionActivationService $service): void
{
foreach ($this->orderIds as $orderId) {
/** @var PlatformOrder|null $order */
$order = PlatformOrder::query()->find($orderId);
if (! $order) {
continue;
}
try {
// 双保险:续费单必须绑定订阅
if ((string) ($order->order_type ?? '') === 'renewal' && ! (int) ($order->site_subscription_id ?? 0)) {
throw new \InvalidArgumentException('续费单未绑定订阅site_subscription_id 为空),不允许批量同步订阅。');
}
$subscription = $service->activateOrder($orderId, $this->adminId);
// 注意activateOrder 内会更新 meta这里 refresh 避免覆盖
$order->refresh();
$meta = (array) ($order->meta ?? []);
$audit = (array) (data_get($meta, 'audit', []) ?? []);
$nowStr = now()->toDateTimeString();
$audit[] = [
'action' => 'batch_activate_subscription',
'scope' => $this->scope,
'at' => $nowStr,
'admin_id' => $this->adminId,
'subscription_id' => $subscription->id,
'filters' => $this->filterSummary,
'note' => '批量同步订阅queue, limit=' . $this->limit . ', matched=' . $this->matchedTotal . ', processed=' . $this->processed . ')',
];
data_set($meta, 'audit', $audit);
// 便于筛选/统计:记录最近一次批量同步信息(扁平字段)
data_set($meta, 'batch_activation', [
'at' => $nowStr,
'admin_id' => $this->adminId,
'scope' => $this->scope,
'mode' => 'queue',
]);
$order->meta = $meta;
$order->save();
} catch (\Throwable $e) {
$meta = (array) ($order->meta ?? []);
data_set($meta, 'subscription_activation_error', [
'message' => trim((string) $e->getMessage()) !== '' ? trim((string) $e->getMessage()) : '未知错误',
'at' => now()->toDateTimeString(),
'admin_id' => $this->adminId,
]);
$order->meta = $meta;
$order->save();
}
}
}
}