CaiWuXiTong/tests/Feature/Business/CourierPayableSummaryRulesTest.php

227 lines
13 KiB
PHP

<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Models\Business\CourierAgreementSignature;
use App\Support\CourierBills\PayableSummary;
use Illuminate\Support\Facades\Storage;
use Mockery;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Feature\FeatureTestCase;
final class CourierPayableSummaryRulesTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
$mirror = Mockery::mock(CourierInformationMirrorRepository::class);
$mirror->shouldReceive('contractsByName')->andReturn([
'合同快递' => ['contract_start' => '2025-01-01', 'contract_end' => '2025-12-31', 'company' => '原签订公司', 'body' => '原合同主体'],
]);
$this->app->instance(CourierInformationMirrorRepository::class, $mirror);
}
public function test_positive_payables_drive_paid_amount_export_and_next_month_balance(): void
{
$service = app(PayableSummary::class);
$expected = [];
foreach ([
['正数快递', ['K' => 2000, 'L' => 50, 'I' => 100.5, 'S' => 1000], 2050.5, 2050.5],
['一分钱快递', ['K' => 0.01, 'S' => null], 0.01, 0.01],
['零数快递', ['K' => 0.004, 'S' => 9], 0.0, 9.0],
['负数快递', ['I' => -50, 'S' => -5], -50.0, -5.0],
['空值快递', ['I' => -20], -20.0, null],
] as [$carrier, $cells, $payable, $paid]) {
$this->row($carrier, $cells);
$expected[$carrier] = [$payable, $paid];
}
$rows = $service->rows('2026-11');
foreach ($rows as $row) {
[$payable, $paid] = $expected[$row['cells']['H']];
$this->assertSame($payable, $row['cells']['R']);
$this->assertSame($paid, $row['cells']['S'] ?? null);
}
$stored = json_decode($service->db()->table('courier_payable_summary_rows')->where('carrier', '正数快递')->value('cells'), true);
$this->assertSame(1000, $stored['S']);
$file = tempnam(sys_get_temp_dir(), 'courier-auto-paid-');
try {
$handle = fopen($file, 'wb');
$service->export('2026-11', $handle);
fclose($handle);
$book = IOFactory::load($file);
$sheet = $book->getSheetByName('汇总');
$this->assertEquals(2050.5, $sheet->getCell('R4')->getValue());
$this->assertEquals(2050.5, $sheet->getCell('S4')->getValue());
$this->assertEquals(9, $sheet->getCell('S6')->getValue());
$this->assertEquals(2054.51, $sheet->getCell('S9')->getValue());
$book->disconnectWorksheets();
} finally {
@unlink($file);
}
$this->assertSame(5, $service->createMonth('2026-12'));
$next = collect($service->rows('2026-12'))->keyBy('cells.H');
$this->assertSame(0.0, $next['正数快递']['cells']['I']);
$this->assertSame(0.0, $next['一分钱快递']['cells']['I']);
$this->assertSame(-9.0, $next['零数快递']['cells']['I']);
$this->assertSame(-45.0, $next['负数快递']['cells']['I']);
$this->assertSame(-20.0, $next['空值快递']['cells']['I']);
}
public function test_manual_paid_amount_is_editable_and_survives_recalculation(): void
{
$positive = $this->row('正数快递', ['K' => 100, 'S' => 7]);
$negative = $this->row('负数快递', ['I' => -10, 'S' => 2]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs();
foreach (['courier-payables', 'courier-payables-final'] as $section) {
$page = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']);
$response = $this->get($page)->assertOk()
->assertSee('aria-label="正数快递 本次实付金额"', false)
->assertSee('aria-label="负数快递 本次实付金额"', false);
$this->assertSame($section === 'courier-payables' ? 102.0 : 7.0, $response->viewData('content')['psTotals']['S']);
$this->withExceptionHandling();
$this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $positive]), ['column' => 'S', 'value' => '5'])
->assertOk();
}
$update = fn (int $id) => route('business.courier-payables.courier-payable-summary.update', ['row' => $id]);
$this->postJson($update($positive), ['column' => 'Q', 'value' => '12.34'])->assertOk();
$this->postJson($update($negative), ['column' => 'S', 'value' => '-3'])->assertOk();
$rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H');
$this->assertSame(112.34, $rows['正数快递']['cells']['R']);
$this->assertSame(5.0, $rows['正数快递']['cells']['S']);
$this->assertSame(-3.0, $rows['负数快递']['cells']['S']);
$this->postJson($update($positive), ['column' => 'S', 'value' => 'not-a-number'])
->assertUnprocessable()->assertJsonValidationErrors('courier_summary');
$this->assertSame(5.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']);
$this->postJson($update($positive), ['column' => 'S', 'value' => '0'])->assertOk();
$this->postJson($update($positive), ['column' => 'Q', 'value' => '20'])->assertOk();
$this->assertSame(0.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']);
$this->postJson($update($positive), ['column' => 'S', 'value' => ''])->assertOk();
$this->assertSame(120.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']);
$this->postJson($update($positive), ['column' => 'S', 'value' => '25.55'])->assertOk();
$file = tempnam(sys_get_temp_dir(), 'courier-manual-paid-');
try {
$handle = fopen($file, 'wb');
app(PayableSummary::class)->export('2026-11', $handle);
fclose($handle);
$book = IOFactory::load($file);
$sheet = $book->getSheetByName('汇总');
$this->assertEquals(25.55, $sheet->getCell('S4')->getValue());
$this->assertEquals(22.55, $sheet->getCell('S6')->getValue());
$book->disconnectWorksheets();
} finally {
@unlink($file);
}
app(PayableSummary::class)->createMonth('2026-12');
$next = app(PayableSummary::class)->rows('2026-12');
$this->assertSame(94.45, $next[0]['cells']['I']);
$this->assertSame(94.45, $next[0]['cells']['S']);
$this->assertArrayNotHasKey('_paid_manual', $next[0]['cells']);
}
public function test_reconciliation_status_filter_combines_with_other_filters_and_updates_totals(): void
{
$this->row('已确认快递', ['K' => 100, 'Y' => '已确认', 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']);
$this->row('待处理快递', ['K' => 80, 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']);
$this->row('旧账快递', ['I' => -20]);
$this->row('无账单快递', []);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs();
foreach (['courier-payables', 'courier-payables-final'] as $section) {
$url = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']);
$response = $this->get($url . '&' . http_build_query(['status' => '已确认', 'company' => '甲公司', 'owner' => '负责人甲', 'state' => '承运', 'q' => '快递']))
->assertOk()->assertSee('<select name="status">', false)->assertSeeText('核对无误')
->assertSee('value="已确认" selected', false)->assertDontSee('type="hidden" name="status"', false);
$data = $response->viewData('content');
$this->assertCount(1, $data['psRows']);
$this->assertSame('已确认快递', $data['psRows'][0]['cells']['H']);
$this->assertSame(100.0, $data['psTotals']['S']);
$this->assertSame(4, $data['psAll']);
foreach (['待处理', '旧账挂账', '本月无账单'] as $status) {
$filtered = $this->get($url . '&' . http_build_query(['status' => $status]))->assertOk()->viewData('content');
$this->assertCount(1, $filtered['psRows']);
$this->assertSame($status, $filtered['psRows'][0]['status']);
}
$this->assertCount(4, $this->get($url . '&status=')->assertOk()->viewData('content')['psRows']);
$empty = $this->get($url . '&' . http_build_query(['status' => '已确认', 'q' => '不存在']))->assertOk();
$empty->assertSeeText('当前条件下没有承运商。');
$this->assertSame(0, $empty->viewData('content')['psTotals']['S']);
}
}
public function test_contract_management_dates_override_mirror_with_tenant_and_archive_boundaries(): void
{
$this->row('合同快递', ['A' => '2024-01-01', 'B' => '2024-12-31']);
$this->row('缺截止日期', ['A' => '2024-01-01', 'B' => '2024-12-31']);
$this->row('仅导入日期', ['A' => '2024-01-01', 'B' => '2024-12-31']);
$this->signature('合同快递', ['cooperation_start_date' => '2026-01-01', 'cooperation_end_date' => '2026-11-01'], ['archived_at' => '2026-01-02']);
$latest = $this->signature('合同快递', ['cooperation_start_date' => '2026-11-02', 'cooperation_end_date' => '2027-11-01'], ['archived_at' => '2026-11-03']);
$this->signature('合同快递', ['cooperation_end_date' => '2030-01-01'], ['archived_at' => '2026-01-03']);
$this->signature('合同快递', ['partner_type' => 'supplier']);
$this->signature('合同快递', [], ['company_id' => $this->company->id + 10]);
$this->signature('合同快递', [], ['status' => 'completed']);
$this->signature('合同快递', [], ['document_type' => 'account-proof']);
$deleted = $this->signature('合同快递', ['cooperation_end_date' => '2035-01-01']);
$deleted->delete();
$this->signature('缺截止日期', ['cooperation_start_date' => '2026-02-01', 'cooperation_end_date' => '2026-02-30']);
$rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H');
$this->assertSame('2026-11-02', $rows['合同快递']['cells']['A']);
$this->assertSame('2027-11-01', $rows['合同快递']['cells']['B']);
$this->assertSame('原签订公司', $rows['合同快递']['cells']['C']);
$this->assertSame('原合同主体', $rows['合同快递']['cells']['G']);
$this->assertFalse($rows['合同快递']['expired']);
$this->assertSame('2026-02-01', $rows['缺截止日期']['cells']['A']);
$this->assertSame('2024-12-31', $rows['缺截止日期']['cells']['B']);
$this->assertSame('2024-01-01', $rows['仅导入日期']['cells']['A']);
$this->assertSame('2024-12-31', $rows['仅导入日期']['cells']['B']);
$this->assertTrue($rows['仅导入日期']['expired']);
$latest->refresh();
$this->assertSame('2026-11-02', $latest->payload['cooperation_start_date']);
$file = tempnam(sys_get_temp_dir(), 'courier-contract-dates-');
try {
$handle = fopen($file, 'wb');
app(PayableSummary::class)->export('2026-11', $handle);
fclose($handle);
$book = IOFactory::load($file);
$sheet = $book->getSheetByName('汇总');
$this->assertSame('2026-11-02', (string) $sheet->getCell('A4')->getValue());
$this->assertSame('2027-11-01', (string) $sheet->getCell('B4')->getValue());
$book->disconnectWorksheets();
} finally {
@unlink($file);
}
}
private function row(string $carrier, array $cells): int
{
$db = app(PayableSummary::class)->db();
return (int) $db->table('courier_payable_summary_rows')->insertGetId([
'month' => '2026-11', 'sort' => $db->table('courier_payable_summary_rows')->count() + 1,
'carrier' => $carrier, 'cells' => json_encode($cells + ['H' => $carrier], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
}
private function signature(string $carrier, array $payload = [], array $attributes = []): CourierAgreementSignature
{
$key = 'summary-' . bin2hex(random_bytes(8));
return CourierAgreementSignature::create($attributes + [
'company_id' => $this->company->id, 'business_no' => $key, 'idempotency_key' => $key,
'document_type' => 'cooperation-contract', 'template_code' => 'TPL-COOPERATION-CONTRACT-V1',
'template_version' => '1', 'source_file_name' => 'contract.pdf', 'status' => 'archived',
'courier_name' => $carrier, 'company_full_name' => '甲方', 'organization_name' => '乙方',
'operator_name' => '经办人', 'payload' => $payload + ['partner_type' => 'courier', 'cooperation_start_date' => '2026-01-01', 'cooperation_end_date' => '2026-12-31'],
'source_pdf_path' => $key . '/source.pdf', 'source_pdf_sha256' => '',
'archived_at' => now(), 'created_by' => $this->user->id, 'updated_by' => $this->user->id,
]);
}
}