CaiWuXiTong/tests/Feature/Business/PlantingReimbursementWorkbenchTest.php
limeng 8e1d9ab778 feat(种菜报销): 确认本批 + 聚工单操作清单,提速商品负责人查询
- 确认本批:把当天校验结果固定下来(每天 11:20 放行检查通过自动确认,也可手动;钉钉已提交前可撤销),
  之后页面、导出、通知、提交钉钉都按确认时的结果,聚工单锁单 / 标记打款后批次不再消失
- 聚工单操作清单(同手工顺序):① 整批锁单(标处理中)② 取消判为取消的 ③ 打款后标记打款(变为已完成),
  给出未完成工单的线上订单号(逗号分隔可直接粘贴查询)和工单编号,进度按同步回来的工单状态核对
- 取单默认改为「待处理 + 处理中」:整批锁单后待复查的单留在处理中,下次批次再带进来
- 商品负责人查询:商品ID 校验后内联为 varchar 字面量(参数按 nvarchar 绑定用不上索引,本机实测 2,271 个商品 181 秒),
  并按商品缓存一天,只查新出现的商品
- 每日群汇总写明本批确认情况和聚工单三步待办数

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UNTa9ohkCsVFACqjz3KMcG
2026-12-01 06:38:03 +00:00

383 lines
26 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\PlantingCommissionPeople;
use Modules\EcommerceFinance\Services\PlantingQuotaDimensions;
use Modules\EcommerceFinance\Services\PlantingQuotaRules;
use Modules\EcommerceFinance\Services\PlantingReimbursementDirectory;
use Modules\EcommerceFinance\Repositories\PlantingReimbursementRepository;
use Modules\EcommerceFinance\Services\PlantingReimbursementReferences;
use Tests\Feature\FeatureTestCase;
class PlantingReimbursementWorkbenchTest extends FeatureTestCase
{
/** @var array<string,string> 聚工单当前状态(currentStatuses 的模拟返回) */
private array $statuses = [];
private function row(string $orderNo, string $amount, array $patch = []): array
{
return array_replace([
'work_order_no' => 'GD' . $orderNo, 'online_order_no' => $orderNo, 'status' => '待处理', 'paid_at' => '2026-11-11 10:00:00',
'started_at' => '2026-11-11 12:00:00', 'completed_at' => '', 'initiator' => '白菜', 'executor' => '李斯', 'completer' => '',
'platform' => '天猫', 'shop_name' => '天猫-欧意朗旗舰店', 'internal_order_no' => '1', 'task_remark' => '', 'seller_remark' => 'CCDD',
'actual_paid_amount' => $amount, 'task_payment' => $amount, 'task_freight' => '0.00', 'task_commission' => '0.00',
'jingxi_price_diff' => '0.00', 'task_deduction' => '0.00', 'task_empty_package_fee' => '0.00', 'reimbursement_amount' => $amount,
'payee_name' => '姚佳炜', 'payee_account' => '6228760405006454377', 'payee_bank' => '农业银行', 'payee_mobile' => '13800000000',
'erp_order_label' => '工单同步', 'erp_order_status' => '已发货', 'platform_order_status' => '', 'product_code' => '',
'product_name' => '', 'product_quantity' => '', 'platform_product_id' => '1001', 'status_code' => 'WAIT_CONFIRM',
], $patch);
}
private function mockRepository(array $rows): void
{
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
// 放行检查要求 20 分钟内同步成功。
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => now()->subMinutes(3)->format('Y-m-d H:i:s')]);
// 默认取「待处理 + 处理中」:整批锁单后,待复查的单留在处理中,下次批次还要带进来。
$repository->shouldReceive('pendingRows')->with('2026-11-05 00:00:00', '2026-11-11 23:59:59', ['WAIT_CONFIRM', 'CONFIRMING'])->andReturn($rows);
$repository->shouldReceive('currentStatuses')->andReturnUsing(fn (array $workOrders): array => array_intersect_key($this->statuses, array_flip($workOrders)));
$repository->shouldReceive('reimbursedOrders')->andReturn(['900' => '2026-11-03']);
// 额度:本月 1 日起的全部种菜工单(这里就是本批)。
$repository->shouldReceive('quotaRows')->with('2026-11-01 00:00:00')->andReturn($rows);
$dimensions = \Mockery::mock(PlantingQuotaDimensions::class);
$dimensions->shouldReceive('shops')->andReturn(['source' => 'replica', 'shops' => [
'天猫-欧意朗旗舰店' => ['platform' => '天猫', 'shop_head' => '白菜', 'profit_center' => '运营中心A'],
'京喜-星光闪闪京喜自营工厂店' => ['platform' => '京喜', 'shop_head' => '星璃', 'profit_center' => '运营中心A'],
'天猫-新开的店' => ['platform' => '天猫', 'shop_head' => '白菜', 'profit_center' => ''],
]]);
$dimensions->shouldReceive('owners')->andReturn([]);
$dimensions->shouldReceive('levels')->andReturn(['白菜' => 'P2', '星璃' => 'P2']);
$this->app->instance(PlantingQuotaDimensions::class, $dimensions);
$this->app->instance(PlantingReimbursementRepository::class, $repository);
Storage::fake('local');
$directory = \Mockery::mock(PlantingReimbursementDirectory::class);
$directory->shouldReceive('userIds')->andReturnUsing(static fn (array $names): array => array_intersect_key(['白菜' => 'U-BAICAI', '星璃' => 'U-XINGLI', '胖虎' => 'U-PANGHU', '李斯' => 'U-LISI'], array_flip($names)));
$directory->shouldReceive('activeNames')->andReturn(['姚佳炜' => true, '王敏佳' => true]);
$this->app->instance(PlantingReimbursementDirectory::class, $directory);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
}
private function upload(string $kind, string $name, string $content)
{
return $this->loginAs()->post(route('business.planting-data.planting-reimbursement-workbench.upload', [
'company_id' => $this->company->id, 'kind' => $kind,
]), ['date' => '2026-11-12', 'file' => UploadedFile::fake()->createWithContent($name, $content)]);
}
private function url(array $query = []): string
{
return route('business.pages.show', ['company_id' => $this->company->id, 'section' => 'planting-data', 'page' => 'planting-reimbursement-workbench'])
. ($query ? '?' . http_build_query($query) : '');
}
public function test_workbench_audits_pending_rows_and_exports(): void
{
$this->mockRepository([
$this->row('101', '60.00'),
$this->row('102', '40.50', ['shop_name' => '京喜-星光闪闪京喜自营工厂店', 'initiator' => '星璃', 'payee_name' => '王敏佳']),
$this->row('900', '10.00', ['initiator' => '星璃']),
$this->row('103', '20.00', ['payee_name' => '离职的人']),
$this->row('104', '30.00', ['shop_name' => '天猫-新开的店']),
]);
// 以前上传过的报销佣金人员名单:第一次读取时自动导入。
Storage::disk('local')->put('planting-reimbursement-references/' . $this->company->id . '/commission.json', json_encode(['rows' => [['key' => '白菜', 'payload' => null]]], JSON_UNESCAPED_UNICODE));
$this->upload('roster', '花名册.csv', "序号,花名,姓名\n1,白,姚佳炜\n2,星,王敏佳\n")->assertRedirect();
// 104 的店铺在工作平台查不到利润中心 → 待复查;额度按初始 309 条规则(天猫 / 京喜 P2)计算,均未超额。
$this->assertSame(['白菜' => true], app(PlantingCommissionPeople::class)->nameSet($this->company->id));
$this->assertSame(['姚佳炜' => true, '王敏佳' => true], app(PlantingReimbursementReferences::class)->nameSet($this->company->id, 'roster'));
$this->loginAs()->get($this->url(['date' => '2026-11-12']))
->assertOk()
->assertSee('种菜报销工作台', false)
->assertSee('2026-11-05 00:00:00')
->assertSee('100.50')
->assertSee('11.11种菜报销')
->assertSee('欧意朗')
->assertSee('重复报销')
->assertSee('不在在职花名册')
->assertSee('@星璃 以上订单本次不予报销', false)
->assertSee('待复查')
->assertSee('全部通过')
->assertSee('5 条', false)
->assertDontSee('已在聚工单核对')
->assertSee('钉钉明细合计 = 可报销合计')
->assertSee('平台+职级:天猫/P2')
->assertSee('种菜额度规则(309 条,启用 306)', false)
->assertDontSee('未上传看板');
$response = $this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => 'reconciliation', 'date' => '2026-11-12',
]));
$response->assertOk();
$this->assertStringContainsString('11.11.xlsx', (string) $response->headers->get('content-disposition'));
$this->assertStringStartsWith('PK', $response->streamedContent());
foreach (['details', 'import-template'] as $type) {
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => $type, 'date' => '2026-11-12',
]))->assertOk();
}
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-13-40']))->assertStatus(422);
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-11-12', 'paid_from' => '2026-11-12']))->assertStatus(422);
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-11-12', 'scope' => 'x']))->assertStatus(422);
}
public function test_initial_decision_filter_keeps_complete_batch_and_totals_for_local_switching(): void
{
$this->mockRepository([$this->row('101', '60.00'), $this->row('900', '10.00')]);
$page = $this->loginAs()->get($this->url(['date' => '2026-11-12', 'decision' => 'cancel']))
->assertOk()
->assertViewHas('content', static fn (array $content): bool => $content['workbenchFilters']['decision'] === 'cancel'
&& count($content['workbenchRows']) === 2
&& array_column($content['workbenchRows'], 'decision') === ['cancel', 'pass']
&& $content['workbenchSummary']['source']['count'] === 2
&& $content['workbenchSummary']['total'] === '60.00');
$dom = new \DOMDocument;
@$dom->loadHTML($page->getContent());
$this->assertSame(1, (new \DOMXPath($dom))->query('//tr[@data-pwb-row and @data-decision="pass" and @hidden]')->length);
$this->withExceptionHandling()->loginAs()->get($this->url(['date' => '2026-11-12', 'decision' => 'invalid']))->assertStatus(422);
}
public function test_unready_mirror_shows_retry_without_export_actions(): void
{
$this->mockRepository([]);
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
$repository->shouldReceive('syncStatus')->once()->andReturn(['code' => 'unavailable', 'last_succeeded_at' => null]);
$repository->shouldNotReceive('pendingRows');
$this->app->instance(PlantingReimbursementRepository::class, $repository);
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertSee('聚工单镜像未就绪')
->assertSee('data-pwb-retry', false)
->assertDontSee('data-pwb-export', false);
}
public function test_bad_upload_reports_error(): void
{
$this->mockRepository([]);
$this->upload('roster', 'x.csv', "a,b\n1,2\n")->assertRedirect()->assertSessionHas('error');
$this->loginAs()->post(route('business.planting-data.planting-reimbursement-workbench.commission.import', ['company_id' => $this->company->id]), [
'file' => UploadedFile::fake()->createWithContent('x.csv', "a,b\n1,2\n"),
])->assertSessionHas('error');
// 看板、店铺信息不再上传。
$status = $this->withExceptionHandling()->upload('monitor', 'x.csv', "a,b\n1,2\n")->status();
$this->assertContains($status, [404, 405]);
$this->upload('roster', 'x.txt', "姓名\n张三\n")->assertRedirect()->assertSessionHas('error');
}
public function test_quota_over_limit_cancels_and_rules_can_be_maintained(): void
{
$this->mockRepository([
$this->row('101', '200.00', ['paid_at' => '2026-11-11 09:00:00']),
$this->row('102', '400.00', ['paid_at' => '2026-11-11 10:00:00']),
]);
$rulesUrl = fn (string $name, array $extra = []): string => route('business.planting-data.planting-reimbursement-workbench.rules.' . $name, ['company_id' => $this->company->id] + $extra);
// 天猫 P2:单笔 300 / 日 500 → 102 单笔超额,两单当日累计 600 都超日限额 → 全部取消。
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['cancel', 'cancel'])
->assertSee('当日累计 600.00 超过上限 500.00');
// 给白菜单独设 ID负责人额度(日 1000、单笔 500)→ 两单都可报。
$this->loginAs()->post($rulesUrl('save'), ['rule_type' => 'ider', 'ider' => '白菜', 'day_limit' => '1000', 'single_limit' => '500', 'is_enabled' => '1', 'date' => '2026-11-12'])
->assertRedirect()->assertSessionHas('success');
$this->loginAs()->post($rulesUrl('save'), ['rule_type' => 'ider', 'ider' => '白菜', 'day_limit' => '1', 'is_enabled' => '1'])
->assertSessionHas('error');
$rules = app(PlantingQuotaRules::class)->all($this->company->id);
$this->assertCount(310, $rules);
$added = end($rules);
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['pass', 'pass'])
->assertSee('ID负责人:白菜');
$export = $this->loginAs()->get($rulesUrl('export'))->assertOk();
$this->assertStringContainsString('ider,,,,,白菜,,1000.00,500.00,1,', $export->streamedContent());
$this->loginAs()->post($rulesUrl('delete', ['rule' => $added['id']]))->assertSessionHas('success');
$this->assertCount(309, app(PlantingQuotaRules::class)->all($this->company->id));
$this->loginAs()->post($rulesUrl('import'), ['file' => UploadedFile::fake()->createWithContent('rules.csv', "rule_type,platform,shop_name,channel,position_level,ider,month_limit,day_limit,single_limit,is_enabled,remark\nplatform,天猫,,,P2,,,5000,5000,1,\n")])
->assertSessionHas('success', '额度规则已整体替换:1 条。');
$this->assertCount(1, app(PlantingQuotaRules::class)->all($this->company->id));
}
public function test_quota_unavailable_puts_batch_on_recheck(): void
{
$this->mockRepository([$this->row('101', '60.00')]);
$dimensions = \Mockery::mock(PlantingQuotaDimensions::class);
$dimensions->shouldReceive('shops')->andReturn(['source' => 'mirror', 'shops' => ['天猫-欧意朗旗舰店' => ['platform' => '', 'shop_head' => '', 'profit_center' => '运营中心A']]]);
$dimensions->shouldReceive('owners')->andThrow(new \RuntimeException('timeout'));
$this->app->instance(PlantingQuotaDimensions::class, $dimensions);
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['recheck'])
->assertSee('种菜额度没有校验')
->assertSee('工作平台店铺信息暂时读不到');
}
public function test_commission_people_can_be_maintained(): void
{
$this->mockRepository([$this->row('101', '65.00', ['task_commission' => '5.00', 'task_payment' => '60.00'])]);
$url = fn (string $name): string => route('business.planting-data.planting-reimbursement-workbench.commission.' . $name, ['company_id' => $this->company->id]);
// 名单为空:带佣金的单取消。
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['cancel'])
->assertSee('报销佣金人员(0 人)', false);
$this->loginAs()->post($url('add'), ['name' => ' 白 菜 ', 'platform' => '天猫', 'date' => '2026-11-12'])->assertSessionHas('success');
$this->loginAs()->post($url('add'), ['name' => '白菜'])->assertSessionHas('error');
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertViewHas('content', static fn (array $content): bool => array_column($content['workbenchRows'], 'decision') === ['pass']);
$this->loginAs()->post($url('import'), ['file' => UploadedFile::fake()->createWithContent('报销佣金人员.csv', "平台,人员,佣金,人员,平台\n天猫,王也,10元,白菜,天猫\n,,,星璃,京东\n")])
->assertSessionHas('success', '报销佣金人员导入:新增 1 人,已在名单里 1 人。');
$this->assertStringContainsString('"星璃"', $this->loginAs()->get($url('export'))->streamedContent());
$this->loginAs()->post($url('remove'), ['name' => '白菜'])->assertSessionHas('success');
$this->assertSame(['星璃' => true], app(PlantingCommissionPeople::class)->nameSet($this->company->id));
}
public function test_stale_sync_blocks_export(): void
{
$this->mockRepository([$this->row('101', '60.00')]);
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => now()->subHours(2)->format('Y-m-d H:i:s')]);
$repository->shouldReceive('pendingRows')->andReturn([$this->row('101', '60.00')]);
$repository->shouldReceive('quotaRows')->andReturn([$this->row('101', '60.00')]);
$repository->shouldReceive('reimbursedOrders')->andReturn([]);
$this->app->instance(PlantingReimbursementRepository::class, $repository);
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', [
'company_id' => $this->company->id, 'type' => 'details', 'date' => '2026-11-12',
]))->assertRedirect()->assertSessionHas('error', fn (string $message): bool => str_contains($message, '超过 20 分钟没同步'));
}
public function test_dingtalk_preview_and_one_click_submit(): void
{
$this->mockRepository([$this->row('101', '60.00'), $this->row('102', '40.50')]);
config(['planting_reimbursement.dingtalk' => [
'enabled' => true, 'client_id' => 'ding-app', 'client_secret' => 'ding-secret', 'agent_id' => '3001',
'process_code' => 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6', 'originator_flower_name' => '李斯', 'originator_user_id' => null, 'dept_id' => null,
]]);
Http::fake([
'api.dingtalk.com/v1.0/oauth2/accessToken' => Http::response(['accessToken' => 'TOKEN']),
'api.dingtalk.com/v1.0/workflow/forms/schemas/processCodes*' => Http::response(['result' => ['schemaContent' => ['items' => \Tests\Unit\EcommerceFinance\PlantingDingTalkFormTest::schema()]]]),
'oapi.dingtalk.com/topapi/v2/user/get*' => Http::response(['errcode' => 0, 'result' => ['unionid' => 'UNION-LISI', 'dept_id_list' => [123]]]),
'api.dingtalk.com/v1.0/workflow/processInstances/spaces/infos/query' => Http::response(['result' => ['spaceId' => 'S1']]),
'api.dingtalk.com/v1.0/storage/spaces/S1/files/uploadInfos/query*' => Http::response(['uploadKey' => 'UK', 'headerSignatureInfo' => ['resourceUrls' => ['https://upload.example.com/f'], 'headers' => ['Authorization' => 'sig']]]),
'upload.example.com/*' => Http::response('', 200),
'api.dingtalk.com/v1.0/storage/spaces/S1/files/commit*' => Http::response(['dentry' => ['id' => 'F1', 'spaceId' => 'S1', 'name' => '种菜报销明细11.11.xlsx', 'size' => 2048, 'extension' => 'xlsx']]),
'api.dingtalk.com/v1.0/workflow/processInstances' => Http::response(['instanceId' => 'INST-1']),
]);
Storage::disk('local')->put('planting-reimbursement-references/' . $this->company->id . '/commission-people.json', json_encode(['people' => [], 'source' => 'edited', 'updated_at' => null]));
$this->loginAs()->get($this->url(['date' => '2026-11-12', 'ding_preview' => '1']))->assertOk()
->assertSee('钉钉表单预览')
->assertSee('表单必填项都能自动填好')
->assertSee('U-LISI');
Http::assertNotSent(static fn ($request): bool => str_ends_with($request->url(), '/workflow/processInstances'));
$submitUrl = route('business.planting-data.planting-reimbursement-workbench.dingtalk.submit', ['company_id' => $this->company->id]);
$this->loginAs()->post($submitUrl, ['date' => '2026-11-12'])->assertSessionHas('success', fn (string $message): bool => str_contains($message, 'INST-1') && str_contains($message, '100.50'));
Http::assertSent(static function ($request): bool {
if (! str_ends_with($request->url(), '/workflow/processInstances')) {
return false;
}
$values = array_column($request['formComponentValues'], 'value', 'name');
return $request['originatorUserId'] === 'U-LISI' && $request['deptId'] === 123
&& $request['processCode'] === 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6'
&& $values['收款合计'] === '100.50' && $values['报销类型'] === '种菜核销'
&& json_decode($values['附件'], true)[0]['fileId'] === 'F1'
&& count(json_decode($values['收款费用明细'], true)) === 1;
});
// 同一批不能重复提交。
$this->loginAs()->post($submitUrl, ['date' => '2026-11-12'])->assertSessionHas('error', fn (string $message): bool => str_contains($message, '已经在'));
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()->assertSee('审批编号 INST-1');
}
public function test_confirmed_batch_is_frozen_and_tracks_jugongdan_progress(): void
{
$this->mockRepository([$this->row('101', '60.00'), $this->row('900', '10.00')]);
$confirmUrl = route('business.planting-data.planting-reimbursement-workbench.batch.confirm', ['company_id' => $this->company->id]);
$this->loginAs()->post($confirmUrl, ['date' => '2026-11-12'])->assertSessionHas('success', fn (string $message): bool => str_contains($message, '已确认本批:2 单'));
$this->loginAs()->post($confirmUrl, ['date' => '2026-11-12'])->assertSessionHas('error');
// 聚工单里锁单、取消、标记打款后,这两单不再是待处理 / 处理中:工作台仍按确认时的批次显示。
$repository = \Mockery::mock(PlantingReimbursementRepository::class);
$repository->shouldReceive('syncStatus')->andReturn(['code' => 'ready', 'last_succeeded_at' => now()->subMinutes(1)->format('Y-m-d H:i:s')]);
$repository->shouldNotReceive('pendingRows');
$repository->shouldReceive('currentStatuses')->andReturn(['GD101' => 'CONFIRMED', 'GD900' => 'DISABLED']);
$this->app->instance(PlantingReimbursementRepository::class, $repository);
$this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()
->assertSee('本批已于')
->assertSee('2 / 2 已完成')
->assertSee('全部已处理')
->assertViewHas('content', static fn (array $content): bool => count($content['workbenchRows']) === 2
&& $content['workbenchOperations']['paid']['done_count'] === 1 && $content['workbenchOperations']['cancel']['done_count'] === 1);
$this->loginAs()->get(route('business.planting-data.planting-reimbursement-workbench.export', ['company_id' => $this->company->id, 'type' => 'details', 'date' => '2026-11-12']))->assertOk();
$this->loginAs()->post(route('business.planting-data.planting-reimbursement-workbench.batch.discard', ['company_id' => $this->company->id]), ['date' => '2026-11-12'])
->assertSessionHas('success');
}
public function test_robot_settings_notices_and_daily_digest(): void
{
$this->mockRepository([
$this->row('101', '60.00'),
$this->row('900', '10.00', ['initiator' => '星璃']),
$this->row('103', '20.00', ['payee_name' => '离职的人']),
]);
Http::fake(['oapi.dingtalk.com/*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$robotUrl = route('business.planting-data.planting-reimbursement-workbench.robot', ['company_id' => $this->company->id]);
$notifyUrl = route('business.planting-data.planting-reimbursement-workbench.notify', ['company_id' => $this->company->id]);
$this->withExceptionHandling()->loginAs()->post($robotUrl, ['webhook' => 'https://example.com/robot/send?access_token=x'])->assertSessionHasErrors('webhook');
$this->loginAs()->post($robotUrl, [
'webhook' => 'https://oapi.dingtalk.com/robot/send?access_token=SECRET-TOKEN-1234',
'secret' => 'SECabc', 'keyword' => '种菜报销', 'reporters' => '胖虎', 'date' => '2026-11-12',
])->assertRedirect()->assertSessionHas('success');
// 页面不回显 Webhook 和密钥;没上传花名册时按钉钉花名册在职名单判断。
$page = $this->loginAs()->get($this->url(['date' => '2026-11-12']))->assertOk()->assertSee('钉钉机器人设置(已配置)')->assertSee('钉钉花名册');
$page->assertDontSee('SECRET-TOKEN-1234')->assertDontSee('SECabc');
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12'])->assertSessionHas('success');
Http::assertSentCount(2);
Http::assertSent(static fn ($request): bool => str_contains($request->url(), 'sign=')
&& $request['at']['atUserIds'] === ['U-XINGLI'] && str_contains($request['markdown']['text'], '900'));
Http::assertSent(static fn ($request): bool => $request['at']['atUserIds'] === ['U-BAICAI'] && str_contains($request['markdown']['text'], '103'));
// 同一批再点不重复发。
$this->loginAs()->post($notifyUrl, ['date' => '2026-11-12'])->assertSessionHas('success', '群通知:发送 0 人,跳过已发 2 人。');
Http::assertSentCount(2);
$this->artisan('planting-reimbursement:daily-digest', ['--date' => '2026-11-12'])->assertExitCode(0);
Http::assertSentCount(3);
// 每日汇总自动发不予报销通知:同一批已发过的跳过。
Http::assertSent(static fn ($request): bool => str_contains($request['markdown']['text'], '可报销:1 条')
&& str_contains($request['markdown']['text'], '3 条 / 90.00 元') && str_contains($request['markdown']['text'], '已自动发不予报销通知:0 人(之前已发 2 人)')
&& str_contains($request['markdown']['text'], '本批已自动确认,聚工单待处理:① 整批锁单 3 单 ② 取消 2 单 ③ 打款后标记打款 1 单')
&& $request['at']['atUserIds'] === ['U-PANGHU']);
// 当天只推一次。
$this->artisan('planting-reimbursement:daily-digest', ['--date' => '2026-11-12'])->assertExitCode(0);
Http::assertSentCount(3);
}
}