CaiWuXiTong/tests/Feature/Business/CourierBillRebooksTest.php

313 lines
21 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 App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\Rebooks;
use App\Support\CourierBills\StatementExporter;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class CourierBillRebooksTest extends FeatureTestCase
{
private array $temp = [];
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
}
protected function tearDown(): void
{
foreach ($this->temp as $path) {
@unlink($path);
}
parent::tearDown();
}
public function test_rule_comes_from_the_summary_labels(): void
{
// 11 月账单:上月小汇总顺延过来的类目
$this->assertSame(2, Rebooks::monthsFromLabels(['运费', '记账', '补10月记账', '补9月记账'], '2026-11')); // 苏北宿迁圆通
$this->assertSame(1, Rebooks::monthsFromLabels(['运费', '补10月记账'], '2026-11')); // 常州安能
$this->assertSame(2, Rebooks::monthsFromLabels(['运费', '2026.9-10月记账补款'], '2026-11')); // 曹县韵达等
$this->assertSame(1, Rebooks::monthsFromLabels(['专线运费', '快递记账', '补记账'], '2026-11')); // 合众物流
$this->assertSame(1, Rebooks::monthsFromLabels(['10月记账补款'], '2026-11'));
$this->assertSame(0, Rebooks::monthsFromLabels(['运费', '记账', '违约金', '补送货费'], '2026-11'));
$this->assertSame(0, Rebooks::monthsFromLabels(null, '2026-11'));
$this->assertSame(2, Rebooks::monthsFromLabels(['2026.12-2027.1月记账补款'], '2027-02')); // 跨年
$this->assertSame(['2026-09', '2026-10'], Rebooks::window('2026-11', 2));
$this->assertSame(['2026-12'], Rebooks::window('2027-01', 1));
$this->assertSame([], Rebooks::window('2026-11', 0));
$this->assertSame('2026.9-10月记账补款', Rebooks::sheetName(['2026-09', '2026-10']));
$this->assertSame('2026.12-2027.1月记账补款', Rebooks::sheetName(['2026-12', '2027-01']));
$this->assertSame('补10月记账', Rebooks::sheetName(['2026-10']));
$this->assertTrue(Rebooks::labelCovers('2026.9-10月记账补款', 9));
$this->assertTrue(Rebooks::labelCovers('补记账', 10));
$this->assertFalse(Rebooks::labelCovers('补10月记账', 9));
$this->assertFalse(Rebooks::labelCovers('快递记账', 9));
$this->assertFalse(Rebooks::labelCovers('补送货费', 9));
}
public function test_statement_refunds_returned_deductions_once(): void
{
$store = app(CourierBillStore::class);
$groupId = $store->saveGroup(null, ['name' => '苏北宿迁圆通', 'express_names' => ['苏北宿迁圆通', '睢宁宿迁圆通'],
'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
// 10 月手工小汇总:补 9 月、补 8 月 → 11 月补 9–10 月
$store->saveSummaryTemplates([['title' => '10月苏北宿迁圆通', 'labels' => ['运费', '记账', '补9月记账', '补8月记账'], 'group' => '苏北宿迁圆通']], '2026-10');
$this->bookkeeping([
['2026-09', 'YT0001', '苏北宿迁圆通', 100, '6919047515577462663'], // 退回了,现应扣 0 → 补 100
['2026-09', 'YT0002', '睢宁宿迁圆通', 50, 'T2'], // 复核仍应扣 50 → 不补
['2026-09', 'YT0006', '苏北宿迁圆通', 40, 'T6'], // 10 月已经补过 → 不再补
['2026-09', 'YT0007', '苏北宿迁圆通', 30, 'T7'], // 没复核 → 先不补
['2026-09', 'YD0005', '曹县韵达', 30, 'T5'], // 别家的
['2026-10', 'YT0003', '苏北宿迁圆通', 50, 'T3'], // 一单两行,合计 80,现应扣 20 → 补 60
['2026-10', 'YT0003', '苏北宿迁圆通', 30, 'T3'],
['2026-08', 'YT0004', '苏北宿迁圆通', 60, 'T4'], // 超过两个月,不补
]);
$rebooks = app(Rebooks::class);
$this->assertSame(['rows' => 2, 'inserted' => 1, 'rejected' => 1], $rebooks->importRefunds($this->workbook([
['单号', '扣款月份', '补款账期', '补款金额', '对账分组'], ['YT0006', '2026-09', '2026-10', 40, '苏北宿迁圆通'], ['YT0009', '九月', '2026-10', 5, ''],
]), 'xlsx'));
$reviews = $rebooks->importReviews($this->workbook([
['单号', '扣款月份', '现应扣'], ['YT0001', '2026-09', 0], ['YT0002', '2026.9', 50], ['YT0003', '2026年10月', 20], ['YT0004', '2026-08', 0], ['YT0006', '2026-09', 0],
]), 'xlsx', '11.19记账.xlsx');
$this->assertSame([5, 0], [$reviews['rows'], $reviews['rejected']]);
$this->assertSame(5, Rebooks::db()->table('courier_bill_rebook_reviews')->count());
$db = Rebooks::db();
$statementId = $db->table('courier_bill_statements')->insertGetId(['group_id' => $groupId, 'bill_month' => '2026-11', 'status' => 'open',
'created_at' => now(), 'updated_at' => now()]);
$plan = $rebooks->forStatement($statementId);
$this->assertSame(['months' => 2, 'source' => 'summary', 'window' => ['2026-09', '2026-10']], array_slice($plan, 0, 3));
$status = collect($plan['rows'])->mapWithKeys(fn ($r) => [$r['waybill'] => [$r['status'], $r['amount']]])->all();
$this->assertSame([
'YT0001' => ['本期补款', 100.0], 'YT0002' => ['仍应扣,不补', 0.0], 'YT0006' => ['已补(2026-10)', 0.0],
'YT0007' => ['无新增退回,不补', 0.0], 'YT0003' => ['本期补款', 60.0],
], $status);
$this->assertSame(['2026-09' => 100.0, '2026-10' => 60.0], Rebooks::totals($plan['rows']));
// 小汇总:照上月类目落到「补10月记账」「补9月记账」,补款放自算金额
app(CourierBillMatcher::class)->refreshSummary($statementId);
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')->get()
->mapWithKeys(fn ($i) => [$i->label => [$i->bill_amount === null ? null : (float) $i->bill_amount, $i->self_amount === null ? null : (float) $i->self_amount]])->all();
$this->assertSame([null, 60.0], $items['补10月记账']);
$this->assertSame([null, 100.0], $items['补9月记账']);
// 导出:「2026.9-10月记账补款」子表
$path = tempnam(sys_get_temp_dir(), 'rebook_export_');
$this->temp[] = $path;
$handle = fopen($path, 'wb');
app(StatementExporter::class)->export($statementId, $handle);
fclose($handle);
$book = IOFactory::createReader('Xlsx')->load($path);
$sheet = $book->getSheetByName('2026.9-10月记账补款');
$this->assertNotNull($sheet);
$rows = $sheet->toArray(null, true, false);
$this->assertSame(['月份', '物流单号', '快递单号整理', '物流公司', '线上订单号'], array_slice($rows[0], 0, 5));
$this->assertSame(['结算记账', '现结算记账金额', '需补款记账金额', '结算运费'], array_slice($rows[0], 28, 4));
$this->assertSame(['2026-09', 'YT0001', 'YT0001', '苏北宿迁圆通', '6919047515577462663'], array_slice($rows[1], 0, 5));
$this->assertEquals([100, 0, 100], array_slice($rows[1], 28, 3));
$splitRows = array_values(array_filter(array_slice($rows, 1), static fn ($r) => $r[1] === 'YT0003'));
$this->assertCount(2, $splitRows);
$this->assertEquals([50, 12.5, 37.5], array_slice($splitRows[0], 28, 3));
$this->assertEquals([30, 7.5, 22.5], array_slice($splitRows[1], 28, 3));
$this->assertSame('原单退回', $rows[1][5]);
$this->assertSame('已退回,不记', $rows[1][32]);
$this->assertSame('=AC2-AD2', $sheet->getCell('AE2')->getValue());
$this->assertContains($sheet->getCell('E2')->getDataType(), [DataType::TYPE_STRING, DataType::TYPE_INLINE]);
$this->assertCount(7, $rows);
$this->assertSame('汇总', $book->getSheetNames()[0]);
$book->disconnectWorksheets();
// 确认:记进补记账台账;取消确认撤掉
$store->confirm($statementId, 'tester');
$this->assertSame(2, $db->table('courier_bill_rebooks')->where('statement_id', $statementId)->count());
$store->unconfirm($statementId);
$this->assertSame(0, $db->table('courier_bill_rebooks')->where('statement_id', $statementId)->count());
$store->confirm($statementId, 'tester');
// 12 月:补 10–11 月,YT0003 11 月已经补过,不再补;9 月的超期
$december = $db->table('courier_bill_statements')->insertGetId(['group_id' => $groupId, 'bill_month' => '2026-12', 'status' => 'open',
'created_at' => now(), 'updated_at' => now()]);
$rebooks->importReviews($this->workbook([['单号', '扣款月份', '现应扣'], ['YT0003', '2026-10', 0]]), 'xlsx', '12月复核.xlsx');
$plan = $rebooks->forStatement($december);
$this->assertSame(['2026-10', '2026-11'], $plan['window']);
$this->assertSame([['YT0003', '已补(2026-11)', 0.0]], collect($plan['rows'])->map(fn ($r) => [$r['waybill'], $r['status'], $r['amount']])->all());
// 分组里设「不补」:不按小汇总了
$group = (array) $db->table('courier_bill_groups')->find($groupId);
$group['express_names'] = json_decode($group['express_names'], true);
$store->saveGroup($groupId, ['rebook_months' => '0'] + $group);
$this->assertSame(['months' => 0, 'source' => 'group', 'window' => [], 'rows' => []], $rebooks->forStatement($december));
}
public function test_pages_import_files_and_show_the_rule(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$store = app(CourierBillStore::class);
$groupId = $store->saveGroup(null, ['name' => '常州安能', 'express_names' => ['常州安能新'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
$section = 'courier-payables-final';
$action = fn (string $name, array $p = []) => route("business.$section.courier-bills.$name", $p);
$page = fn (array $q) => route('business.pages.show', ['section' => $section, 'page' => 'courier-bill-reconciliation', ...$q]);
$file = fn (array $rows) => new UploadedFile($this->workbook($rows), 'x.xlsx', null, null, true);
$this->post($action('import-rebooks'), ['rebooks' => $file([['单号', '扣款月份', '补款账期', '补款金额'], ['730006219339', '2026-09', '2026-10', 489.05]])])
->assertSessionHas('courier_bills_message', fn (string $m): bool => str_contains($m, '新增 1 条已补记录'));
$this->post($action('import-rebook-reviews'), ['reviews' => $file([['单号', '扣款月份', '现应扣'], ['730006219339', '2026-10', 0]])])
->assertSessionHas('courier_bills_message', fn (string $m): bool => str_contains($m, '复核记账'));
$this->post($action('import-rebook-reviews'), ['reviews' => $file([['单号', '现应扣'], ['1', 0]])])->assertSessionHasErrors('courier_bills');
$this->get($page(['cb_view' => 'ledger']))->assertOk()->assertSeeText('补记账台账')->assertSeeText('历史导入')->assertSeeText('489.05');
$this->get($page(['cb_view' => 'ledger', 'waybill' => '730006219339']))->assertOk()
->assertSeeText('2026-09 扣的,2026-10 已补')->assertSeeText('现在应扣');
$this->post($action('save-group'), ['id' => $groupId, 'name' => '常州安能', 'express_names' => '常州安能新', 'rebook_months' => '1'])
->assertSessionHasNoErrors();
$this->assertSame(1, (int) Rebooks::db()->table('courier_bill_groups')->where('id', $groupId)->value('rebook_months'));
$this->get($page(['cb_view' => 'groups']))->assertOk()->assertSeeText('补记账')->assertSeeText('补上月');
$this->get($page(['cb_view' => 'groups', 'edit' => $groupId]))->assertOk()->assertSee('<option value="1" selected>补上月</option>', false);
$this->post($action('save-group'), ['id' => $groupId, 'name' => '常州安能', 'express_names' => '常州安能新', 'rebook_months' => ''])->assertSessionHasNoErrors();
$this->assertNull(Rebooks::db()->table('courier_bill_groups')->where('id', $groupId)->value('rebook_months'));
$this->post($action('save-group'), ['id' => $groupId, 'name' => '常州安能', 'express_names' => '常州安能新', 'rebook_months' => '5'])->assertSessionHasErrors('rebook_months');
$statementId = Rebooks::db()->table('courier_bill_statements')->insertGetId(['group_id' => $groupId, 'bill_month' => '2026-11', 'status' => 'open',
'created_at' => now(), 'updated_at' => now()]);
$this->get($page(['cb_view' => 'statement', 'statement' => $statementId]))->assertOk()->assertSeeText('补记账:不补');
}
public function test_already_refunded_records_remain_visible_but_do_not_add_to_summary(): void
{
$store = app(CourierBillStore::class);
$group = $store->saveGroup(null, ['name' => '新北中通测试', 'express_names' => ['新北中通测试'], 'rebook_months' => 2]);
$store->saveSummaryTemplates([['title' => '新北中通测试11月', 'labels' => ['运费11月', '2026.9-10月记账补款'], 'group' => '新北中通测试']], '2026-11');
$this->bookkeeping([['2026-09', 'PAID100', '新北中通测试', 100, 'ORDER100']]);
Rebooks::db()->table('courier_bill_rebooks')->insert([
'waybill_no' => 'PAID100', 'deduct_month' => '2026-09', 'refund_month' => '2026-10',
'amount' => 100, 'source' => 'import', 'created_at' => now(),
]);
$id = Rebooks::db()->table('courier_bill_statements')->insertGetId([
'group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
app(CourierBillMatcher::class)->refreshSummary($id);
$amount = Rebooks::db()->table('courier_bill_summary_items')->where('statement_id', $id)
->where('label', '2026.9-10月记账补款')->value('self_amount');
$this->assertNotNull($amount);
$this->assertEquals(0, $amount);
$path = tempnam(sys_get_temp_dir(), 'rebook_zero_');
$this->temp[] = $path;
$output = fopen($path, 'wb');
try { app(StatementExporter::class)->export($id, $output); } finally { fclose($output); }
$book = IOFactory::createReader('Xlsx')->load($path);
try {
$sheet = $book->getSheetByName('2026.9-10月记账补款');
$this->assertNotNull($sheet);
$this->assertSame(2, $sheet->getHighestDataRow());
$this->assertSame('需补款记账金额', (string) $sheet->getCell('AE1')->getValue());
$this->assertSame('PAID100', (string) $sheet->getCell('B2')->getValue());
$headers = array_map('strval', $sheet->rangeToArray('A1:AR1')[0]);
$this->assertSame('已补(2026-10)', (string) $sheet->getCell([array_search('补款状态', $headers, true) + 1, 2])->getValue());
$this->assertEquals(0, $sheet->getCell([array_search('本期补款金额', $headers, true) + 1, 2])->getValue());
} finally { $book->disconnectWorksheets(); }
}
public function test_rebook_analysis_preserves_reason_and_uses_required_keywords(): void
{
$db = Rebooks::db();
if (! \Illuminate\Support\Facades\Schema::connection($db->getName())->hasTable('courier_returned_parcels')) {
\Illuminate\Support\Facades\Schema::connection($db->getName())->create('courier_returned_parcels', function ($table): void {
$table->unsignedBigInteger('source_id')->primary();
$table->string('waybill');
$table->dateTime('received_at');
$table->decimal('returned_qty', 12, 4);
});
}
$store = app(CourierBillStore::class);
$group = $store->saveGroup(null, ['name' => '原因验证', 'express_names' => ['原因验证'], 'rebook_months' => 1]);
$reasons = ['快递丢件', '双面单', '违规件', '站点异常', '运输破损'];
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
foreach ($reasons as $i => $reason) {
$connection->table('supplier_payable_overrides')->insert([
'company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET, 'record_key' => 'reason-'.$i,
'values' => json_encode(['summary_month' => '2026-10', 'tracking_no' => 'REASON'.$i, 'carrier' => '原因验证',
'settle_bookkeeping' => '100', 'cost' => '40', 'loss' => '8', 'settle_freight' => '7',
'bookkeeping_reason' => $reason, 'analysis' => '未退回', 'product_code' => '000123'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
Rebooks::db()->table('courier_bill_rebook_reviews')->insert([
'waybill_no' => 'REASON'.$i, 'deduct_month' => '2026-10', 'current_amount' => $i < 4 ? 15 : 0, 'updated_at' => now(),
]);
$returned = ['source_id' => 500 + $i, 'waybill' => 'REASON'.$i, 'received_at' => '2026-12-02 10:00:00', 'returned_qty' => 1];
if (\Illuminate\Support\Facades\Schema::connection($db->getName())->hasColumn('courier_returned_parcels', 'generation')) {
$returned += ['generation' => 'test', 'synced_at' => now()];
}
$db->table('courier_returned_parcels')->insert($returned);
}
$id = Rebooks::db()->table('courier_bill_statements')->insertGetId([
'group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
app(CourierBillMatcher::class)->refreshSummary($id);
$path = tempnam(sys_get_temp_dir(), 'rebook_reasons_');
$this->temp[] = $path;
$output = fopen($path, 'wb');
try { app(StatementExporter::class)->export($id, $output); } finally { fclose($output); }
$book = IOFactory::createReader('Xlsx')->load($path);
try {
$sheet = $book->getSheetByName('补10月记账');
foreach ($reasons as $i => $reason) {
$r = $i + 2;
$this->assertSame($reason, (string) $sheet->getCell('F'.$r)->getValue());
$this->assertSame($i < 4 ? '记账损耗+运费' : '原单退回改0', (string) $sheet->getCell('AG'.$r)->getValue());
$this->assertSame('000123', (string) $sheet->getCell('G'.$r)->getValue());
$this->assertEquals($i < 4 ? 85 : 100, $sheet->getCell('AE'.$r)->getCalculatedValue());
}
} finally { $book->disconnectWorksheets(); }
}
/** @param list<array{string,string,string,float|int,string}> $rows 扣款月份、物流单号、物流公司、结算记账、线上订单号 */
private function bookkeeping(array $rows): void
{
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
foreach ($rows as $i => [$month, $waybill, $carrier, $settle, $order]) {
$connection->table('supplier_payable_overrides')->insert([
'company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET, 'record_key' => 'bk-' . $i,
'values' => json_encode(['summary_month' => $month, 'tracking_no' => $waybill, 'tracking_no_clean' => $waybill, 'carrier' => $carrier,
'online_order_no' => $order, 'bookkeeping_reason' => '原单退回', 'settle_bookkeeping' => (string) $settle, 'analysis' => '已退回,不记'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
}
}
/** @param list<list<mixed>> $rows */
private function workbook(array $rows): string
{
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
if ($value === null) {
continue;
}
$cell = $sheet->getCell([$c + 1, $r + 1]);
is_string($value) ? $cell->setValueExplicit($value, DataType::TYPE_STRING) : $cell->setValue($value);
}
}
$path = tempnam(sys_get_temp_dir(), 'rebook_xlsx_') . '.xlsx';
$this->temp[] = $path;
(new Xlsx($book))->save($path);
$book->disconnectWorksheets();
return $path;
}
}