快递应付汇总:自动实付、合同日期与对账状态筛选 #1776

Open
limeng wants to merge 1 commits from fix/limeng-courier-payable-auto-paid into main
6 changed files with 256 additions and 9 deletions

View File

@ -96,6 +96,36 @@ class CourierContractPageData
}
}
/** @return array<string,array{start_date:?string,end_date:?string}> 同名快递取最新归档合作合同的日期。 */
public function datesByCourierNames(array $names): array
{
$names = array_values(array_unique(array_filter(array_map('trim', $names))));
if ($names === [] || ! Schema::hasTable('business_courier_agreement_signatures')) {
return [];
}
$dates = [];
foreach (array_chunk($names, 500) as $chunk) {
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
->whereIn('courier_name', $chunk)
->select(['id', 'courier_name', 'payload', 'document_type', 'status'])
->orderByDesc('archived_at')->orderByDesc('id')->cursor();
foreach ($signatures as $signature) {
$name = trim((string) $signature->courier_name);
if (isset($dates[$name]) || ($payload = $signature->archivedCourierContractPayload()) === null) {
continue;
}
$dates[$name] = [
'start_date' => $this->date($payload['cooperation_start_date'] ?? null),
'end_date' => $this->date($payload['cooperation_end_date'] ?? null),
];
}
}
return $dates;
}
private function filters(): array
{
$search = request()->query('contract_search');

View File

@ -2,6 +2,7 @@
namespace App\Support\CourierBills;
use App\Business\CourierContractPageData;
use Illuminate\Database\ConnectionInterface;
use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository;
use RuntimeException;
@ -38,7 +39,10 @@ final class PayableSummary
/** 有对账单时由小汇总覆盖的列。 */
private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT'];
public function __construct(private readonly CourierInformationMirrorRepository $couriers) {}
public function __construct(
private readonly CourierInformationMirrorRepository $couriers,
private readonly CourierContractPageData $contractDates,
) {}
public function db(): ConnectionInterface
{
@ -66,6 +70,7 @@ final class PayableSummary
report($error);
$contracts = [];
}
$contractDates = $this->contractDates->datesByCourierNames($stored->pluck('carrier')->all());
$today = now()->toDateString();
$rows = [];
foreach ($stored as $row) {
@ -77,6 +82,9 @@ final class PayableSummary
$cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null);
$cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null);
}
$dates = $contractDates[$row->carrier] ?? [];
$cells['A'] = $dates['start_date'] ?? ($cells['A'] ?? null);
$cells['B'] = $dates['end_date'] ?? ($cells['B'] ?? null);
$mine = $statements[$row->carrier] ?? [];
// 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对;
// 新建的月份金额是空的,才用对账单的小汇总填。
@ -182,6 +190,13 @@ final class PayableSummary
if ($row === null) {
throw new RuntimeException('汇总行不存在。');
}
if ($column === 'S') {
foreach ($this->rows((string) $row->month) as $current) {
if ($current['id'] === $rowId && $current['cells']['R'] > 0) {
throw new RuntimeException('本月应付金额大于 0 时,本次实付金额自动等于本月应付金额,无需手工修改。');
}
}
}
$cells = (array) json_decode((string) $row->cells, true);
if (in_array($column, self::MONEY, true)) {
$number = BillParser::number($value);

View File

@ -126,12 +126,15 @@ final class SummaryMapper
];
}
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */
/** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;R > 0 时实付 S = R。 */
public static function totals(array $cells): array
{
$n = static fn (string $key): float => (float) ($cells[$key] ?? 0);
$cells['M'] = round($n('K') - $n('L'), 2);
$cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2);
if ($cells['R'] > 0) {
$cells['S'] = $cells['R'];
}
return $cells;
}

View File

@ -33,8 +33,8 @@
<label>签订公司<select name="company"><option value="">全部</option>@foreach ($psCompanies ?? [] as $v)<option @selected(request('company') === $v)>{{ $v }}</option>@endforeach</select></label>
<label>负责人<select name="owner"><option value="">全部</option>@foreach ($psOwners ?? [] as $v)<option @selected(request('owner') === $v)>{{ $v }}</option>@endforeach</select></label>
<label>承运状态<select name="state"><option value="">全部</option>@foreach (['承运', '停运'] as $v)<option @selected(request('state') === $v)>{{ $v }}</option>@endforeach</select></label>
<label>对账状态<select name="status"><option value="">全部</option>@foreach (\App\Http\Controllers\Business\CourierPayableSummaryController::STATUSES as $status)<option value="{{ $status }}" @selected($psStatus === $status)>{{ $status === '已确认' ? '核对无误' : $status }}</option>@endforeach</select></label>
<label>搜索<input type="search" name="q" value="{{ request('q') }}" placeholder="承运商或快递公司主体"></label>
@if ($psStatus)<input type="hidden" name="status" value="{{ $psStatus }}">@endif
<button type="submit">查询</button>
</form>
@ -80,7 +80,7 @@
<td style="font-weight:600">{{ $c['H'] ?? '' }}</td>
<td><span class="cbr-chip {{ $chip[$row['status']] }}">{{ $row['status'] === '已确认' ? '核对无误' : $row['status'] }}</span></td>
@foreach ($main as $k)
@if (isset($editable[$k]))
@if (isset($editable[$k]) && ! ($k === 'S' && ($c['R'] ?? 0) > 0))
<td class="num"><input type="number" step="0.01" data-ps-edit="{{ $route('update', ['row' => $row['id']]) }}" data-column="{{ $k }}" value="{{ isset($c[$k]) ? round((float) $c[$k], 2) : '' }}" aria-label="{{ $c['H'] }} {{ $editable[$k] }}" style="width:110px;text-align:right"></td>
@else
<td class="num {{ $k === 'L' ? 'cbr-diff' : '' }}" @if ($k === 'R') style="font-weight:700" @endif>{{ $money($c[$k] ?? 0) }}</td>
@ -106,7 +106,7 @@
</tfoot>
</table>
</div>
<div class="cbr-footer"><span role="status" data-ps-status>负责人、承运状态、月初结余、其他补款、本次实付、备注、仓库可直接改,改完自动保存。</span></div>
<div class="cbr-footer"><span role="status" data-ps-status>本月应付金额大于 0 时,本次实付金额自动等额带出;其余实付及负责人、承运状态、月初结余、其他补款、备注、仓库可直接改,改完自动保存。</span></div>
</section>
@endif
@ -148,7 +148,8 @@
<p>已用 10 月 36 份手工对账表里的 42 个小汇总验证:按下面的规则归集,与手工快递汇总表逐行、逐列一致。小汇总里的项目名称决定归到哪一列,依次判断,命中即停。</p>
<table>
<tbody>
<tr><td>合同开始/截止时间、签订公司、快递公司主体名称</td><td>取「快递资料」(按承运商名称);快递资料里没有的保留导入值。截止时间早于今天标「已到期」。</td></tr>
<tr><td>合同开始/截止时间</td><td>优先取「快递资料 → 合同管理」中同名承运商最新归档合作合同的日期;未填写的日期沿用快递资料或导入值。截止时间早于今天标「已到期」。</td></tr>
<tr><td>签订公司、快递公司主体名称</td><td>取「快递资料」(按承运商名称);快递资料里没有的保留导入值。</td></tr>
<tr><td>月初结余</td><td>上月「本月应付金额 − 本次实付金额」结转(没填实付按 0 算);可手工改。签署完结后再按工作平台状态自动判断,细则后定。</td></tr>
<tr><td>原单补发配件</td><td>项目名称含「补发配件」或「配件补发」(排在第一条,「成品补发配件扣快递」也算这里)。</td></tr>
<tr><td>补给快递</td><td>以「补」开头、含「记账补款」或以「需补」结尾的项目,取正数;名称含「记账」的同时计入「记账补款金额」。不进差异明细。</td></tr>
@ -167,7 +168,8 @@
<tr><td>对账差异金额</td><td>差异明细 13 列合计 − 违约金 − 借支。</td></tr>
<tr><td>核对确定金额</td><td>快递提供金额 − 对账差异金额。</td></tr>
<tr><td>本月应付金额</td><td>快递提供 − 对账差异 − 面单 − 借支 − 赔付 + 其他补款 + 补给快递 + 月初结余。</td></tr>
<tr><td>其他补款、本次实付金额</td><td>手工填。</td></tr>
<tr><td>其他补款</td><td>手工填。</td></tr>
<tr><td>本次实付金额</td><td>本月应付金额大于 0 时自动等于本月应付金额,随应付金额重算;本月应付金额为 0 或负数时保留原值,可手工填。</td></tr>
</tbody>
</table>
</details>
@ -223,7 +225,7 @@
if (!response.ok) throw new Error((await response.json().catch(() => ({})))?.message || 'save');
await swap(location.href);
const next = document.querySelector('[data-ps-status]');
if (next) next.textContent = '已保存,本月应付已重算。';
if (next) next.textContent = '已保存,本月应付及正数应付对应的本次实付已重算。';
} catch (error) {
input.disabled = false;
if (status) status.textContent = '保存失败:' + (error.message === 'save' ? '请刷新后重试' : error.message);

View File

@ -81,7 +81,7 @@ final class CourierBillPagesTest extends FeatureTestCase
$this->post(route("business.$section.courier-payable-summary.import"), ['month' => '2026-10', 'summary' => $this->summaryFile()])->assertRedirect();
$row = $db->table('courier_payable_summary_rows')->where('carrier', '河北中通')->sole();
$this->get($summary . '?month=2026-10')->assertOk()->assertSeeText('河北中通')->assertSeeText('核对无误')->assertSeeText('上楼费5元');
$this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertOk();
$this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertUnprocessable();
$this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'K', 'value' => '1'])->assertUnprocessable();
$this->post(route("business.$section.courier-payable-summary.create-month"), ['month' => '2026-11'])->assertRedirect();
$this->get(route("business.$section.courier-payable-summary.export", ['month' => '2026-11']))->assertOk();

View File

@ -0,0 +1,197 @@
<?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_pages_and_updates_keep_positive_paid_amount_automatic(): 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()
->assertDontSee('aria-label="正数快递 本次实付金额"', false)
->assertSee('aria-label="负数快递 本次实付金额"', false);
$this->assertSame(102.0, $response->viewData('content')['psTotals']['S']);
$this->withExceptionHandling();
$this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $positive]), ['column' => 'S', 'value' => '5'])
->assertUnprocessable()->assertJsonValidationErrors('courier_summary');
}
$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(112.34, $rows['正数快递']['cells']['S']);
$this->assertSame(-3.0, $rows['负数快递']['cells']['S']);
}
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,
]);
}
}