feat(queue): write batch activation last_result summary for observability

This commit is contained in:
萝卜
2026-03-17 12:58:39 +08:00
parent 7723dd8daf
commit 82d68105de
2 changed files with 194 additions and 2 deletions

View File

@@ -55,6 +55,10 @@ class BatchActivateSubscriptionsJob implements ShouldQueue
// 批次号:用于把一次队列批量执行关联起来,便于后续追溯/筛选/可观测。
$runId = 'BAS' . now()->format('YmdHis') . str_pad((string) random_int(1, 9999), 4, '0', STR_PAD_LEFT);
$success = 0;
$failed = 0;
$failedReasonCounts = [];
foreach ($this->orderIds as $orderId) {
/** @var PlatformOrder|null $order */
$order = PlatformOrder::query()->find($orderId);
@@ -100,16 +104,81 @@ class BatchActivateSubscriptionsJob implements ShouldQueue
$order->meta = $meta;
$order->save();
$success++;
} catch (\Throwable $e) {
$failed++;
$reason = trim((string) $e->getMessage());
$reason = $reason !== '' ? $reason : '未知错误';
$failedReasonCounts[$reason] = ($failedReasonCounts[$reason] ?? 0) + 1;
$meta = (array) ($order->meta ?? []);
$nowStr = now()->toDateTimeString();
data_set($meta, 'subscription_activation_error', [
'message' => trim((string) $e->getMessage()) !== '' ? trim((string) $e->getMessage()) : '未知错误',
'at' => now()->toDateTimeString(),
'message' => $reason,
'at' => $nowStr,
'admin_id' => $this->adminId,
]);
// 即使失败也写入 batch_activation包含 run_id确保本批次可追溯/可汇总。
data_set($meta, 'batch_activation', [
'at' => $nowStr,
'admin_id' => $this->adminId,
'scope' => $this->scope,
'mode' => 'queue',
'run_id' => $runId,
]);
$order->meta = $meta;
$order->save();
}
}
// 最小结果汇总(写入到每个订单的 meta.batch_activation.last_result便于运营在列表页直接看到“本次队列批量的执行结果”。
// 注意:为避免引入新表,当前阶段采取“冗余写入到每条订单”策略;后续可演进为独立批次表或日志表。
$topReasons = [];
if ($failed > 0 && count($failedReasonCounts) > 0) {
arsort($failedReasonCounts);
$top = array_slice($failedReasonCounts, 0, 3, true);
foreach ($top as $reason => $cnt) {
$topReasons[] = [
'reason' => mb_substr((string) $reason, 0, 80),
'count' => (int) $cnt,
];
}
}
$summary = [
'run_id' => $runId,
'success' => $success,
'failed' => $failed,
'matched' => $this->matchedTotal,
'processed' => $this->processed,
'top_reasons' => $topReasons,
'at' => now()->toDateTimeString(),
];
foreach ($this->orderIds as $orderId) {
$order = PlatformOrder::query()->find($orderId);
if (! $order) {
continue;
}
$meta = (array) ($order->meta ?? []);
$ba = (array) (data_get($meta, 'batch_activation', []) ?? []);
// 仅当 run_id 与当前 job 一致时才回写 last_result避免并发覆盖。
if ((string) (data_get($ba, 'run_id') ?? '') !== $runId) {
continue;
}
data_set($ba, 'last_result', $summary);
data_set($meta, 'batch_activation', $ba);
$order->meta = $meta;
$order->save();
}
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace Tests\Feature;
use App\Jobs\BatchActivateSubscriptionsJob;
use App\Models\Merchant;
use App\Models\Plan;
use App\Models\PlatformOrder;
use App\Support\SubscriptionActivationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class BatchActivateSubscriptionsJobShouldWriteLastResultSummaryTest extends TestCase
{
use RefreshDatabase;
protected function loginAsPlatformAdmin(): void
{
$this->seed();
$this->post('/admin/login', [
'email' => 'platform.admin@demo.local',
'password' => 'Platform@123456',
])->assertRedirect('/admin');
}
public function test_job_should_write_last_result_summary_into_batch_activation_meta(): void
{
$this->loginAsPlatformAdmin();
$merchant = Merchant::query()->firstOrFail();
$plan = Plan::query()->create([
'code' => 'job_batch_activate_last_result_plan',
'name' => 'Job 批量同步 last_result 测试套餐',
'billing_cycle' => 'monthly',
'price' => 10,
'list_price' => 10,
'status' => 'active',
'sort' => 10,
'published_at' => now(),
]);
$ok = PlatformOrder::query()->create([
'merchant_id' => $merchant->id,
'plan_id' => $plan->id,
'order_no' => 'PO_JOB_LAST_RESULT_OK_0001',
'order_type' => 'new_purchase',
'status' => 'activated',
'payment_status' => 'paid',
'plan_name' => $plan->name,
'billing_cycle' => $plan->billing_cycle,
'period_months' => 1,
'quantity' => 1,
'payable_amount' => 10,
'paid_amount' => 10,
'placed_at' => now()->subMinutes(10),
'paid_at' => now()->subMinutes(9),
'activated_at' => now()->subMinutes(8),
'meta' => [],
]);
$bad = PlatformOrder::query()->create([
'merchant_id' => $merchant->id,
'plan_id' => $plan->id,
'order_no' => 'PO_JOB_LAST_RESULT_BAD_0002',
'order_type' => 'new_purchase',
'status' => 'activated',
'payment_status' => 'paid',
'plan_name' => $plan->name,
'billing_cycle' => $plan->billing_cycle,
'period_months' => 1,
'quantity' => 1,
'payable_amount' => 10,
'paid_amount' => 10,
'placed_at' => now()->subMinutes(7),
'paid_at' => now()->subMinutes(6),
'activated_at' => now()->subMinutes(5),
'meta' => [],
]);
// 绑定一个假的 service让它对 bad 抛异常,以便验证 top_reasons 写入
$badId = $bad->id;
$fakeService = new class($badId) extends SubscriptionActivationService {
public function __construct(private int $badId) {}
public function activateOrder(int $orderId, ?int $adminId = null): \App\Models\SiteSubscription
{
if ($orderId === $this->badId) {
throw new \RuntimeException('模拟失败:订阅同步异常');
}
return parent::activateOrder($orderId, $adminId);
}
};
$job = new BatchActivateSubscriptionsJob([
$ok->id,
$bad->id,
], 1, 'filtered', 'syncable_only=1', 50, 2, 2);
$job->handle($fakeService);
$ok->refresh();
$bad->refresh();
$this->assertNotEmpty((string) data_get($ok->meta, 'batch_activation.run_id'));
$this->assertSame(1, (int) data_get($ok->meta, 'batch_activation.last_result.success'));
$this->assertSame(1, (int) data_get($ok->meta, 'batch_activation.last_result.failed'));
$this->assertSame(2, (int) data_get($ok->meta, 'batch_activation.last_result.processed'));
$top = (array) (data_get($ok->meta, 'batch_activation.last_result.top_reasons', []) ?? []);
$this->assertNotEmpty($top);
$this->assertSame('模拟失败:订阅同步异常', (string) data_get($top, '0.reason'));
$this->assertSame(1, (int) data_get($top, '0.count'));
// bad 订单也应写入同一个 last_result同批次 run_id
$this->assertSame(
(string) data_get($ok->meta, 'batch_activation.last_result.run_id'),
(string) data_get($bad->meta, 'batch_activation.last_result.run_id')
);
}
}