203 lines
15 KiB
PHP
203 lines
15 KiB
PHP
<?php
|
||
|
||
namespace Tests\Feature\Business;
|
||
|
||
use App\Support\CourierBills\CourierBillStore;
|
||
use App\Support\CourierBills\Rebooks;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use Tests\Feature\FeatureTestCase;
|
||
|
||
final class CourierRebookReturnReviewTest extends FeatureTestCase
|
||
{
|
||
public function test_return_cursor_does_not_skip_taobao_row_sharing_a_batch_boundary_id(): void
|
||
{
|
||
$schema=Schema::connection('business_mirror');$schema->dropIfExists('courier_returned_parcels');
|
||
$schema->create('courier_returned_parcels',function($table):void{
|
||
$table->string('source_kind');$table->integer('source_id');$table->primary(['source_kind','source_id']);
|
||
$table->string('waybill');$table->dateTime('received_at');$table->integer('returned_qty');
|
||
});
|
||
$rows=[];
|
||
for($id=1;$id<=1000;$id++)$rows[]=['source_kind'=>'regular','source_id'=>$id,'waybill'=>'UNRELATED'.$id,'received_at'=>'2026-11-01','returned_qty'=>1];
|
||
foreach(array_chunk($rows,200) as $chunk)Rebooks::db()->table('courier_returned_parcels')->insert($chunk);
|
||
Rebooks::db()->table('courier_returned_parcels')->insert(['source_kind'=>'taobao','source_id'=>1000,
|
||
'waybill'=>'RETURN-BOUNDARY','received_at'=>'2026-12-06','returned_qty'=>1]);
|
||
$result=app(\App\Support\CourierBills\RebookReturns::class)->annotate([
|
||
['tracking_no'=>'RETURN-BOUNDARY','analysis'=>'未退回','bookkeeping_reason'=>'买家原因'],
|
||
]);
|
||
$this->assertSame('已退回',$result[0]['_return_status']);
|
||
$this->assertSame(0.0,$result[0]['_return_current']);
|
||
}
|
||
|
||
public function test_changed_return_number_requires_exact_internal_order_and_sku(): void
|
||
{
|
||
$db=Rebooks::db();
|
||
$db->getSchemaBuilder()->create('js_jst_order_express_details', function($t){$t->integer('id')->primary();$t->string('inner_order_id');$t->string('so_id');});
|
||
$db->table('js_jst_order_express_details')->insert([['id'=>71,'inner_order_id'=>'I71','so_id'=>'SAME-ONLINE'],['id'=>72,'inner_order_id'=>'I72','so_id'=>'SAME-ONLINE']]);
|
||
$db->table('jst_oms_shipping')->insert([
|
||
['source_id'=>71,'express_no'=>'NEW0071','trade_no'=>'SAME-ONLINE'],
|
||
['source_id'=>72,'express_no'=>'OLD0072','trade_no'=>'SAME-ONLINE'],
|
||
]);
|
||
$db->table('courier_unshipped_waybills')->insert(['source'=>'replacement','evidence_no'=>'shipping:71','waybill_no'=>'OLD0071','new_waybill_no'=>'NEW0071','evidence_time'=>'2026-12-06']);
|
||
$db->table('courier_returned_parcels')->insert([
|
||
['source_id'=>1,'source_kind'=>'regular','waybill'=>'RETURN71','received_at'=>'2026-12-06','returned_qty'=>1,'order_id'=>'I71','online_order_no'=>'SAME-ONLINE','sku'=>'SKU-A','generation'=>'test','synced_at'=>now()],
|
||
['source_id'=>1,'source_kind'=>'taobao','waybill'=>'RETURN72','received_at'=>'2026-12-06','returned_qty'=>1,'order_id'=>'I72','online_order_no'=>'SAME-ONLINE','sku'=>'SKU-B','generation'=>'test','synced_at'=>now()],
|
||
]);
|
||
$result=app(\App\Support\CourierBills\RebookReturns::class)->annotate([
|
||
['tracking_no'=>'OLD0071','product_code'=>'SKU-A','analysis'=>'未退回'],
|
||
['tracking_no'=>'OLD0072','product_code'=>'SKU-A','analysis'=>'未退回'],
|
||
['tracking_no'=>'UNKNOWN','internal_order_id'=>'I71','product_code'=>'SKU-B','analysis'=>'未退回'],
|
||
]);
|
||
$this->assertSame('RETURN71',$result[0]['_matched_return_no']);
|
||
$this->assertSame(0.0,$result[0]['_return_current']);
|
||
$this->assertSame('原内部订单及商品匹配',$result[0]['_return_method']);
|
||
$this->assertSame('',$result[1]['_matched_return_no']);
|
||
$this->assertSame('',$result[2]['_matched_return_no']);
|
||
$wrongOrder=app(\App\Support\CourierBills\RebookReturns::class)->annotate([
|
||
['tracking_no'=>'UNKNOWN','internal_order_id'=>'I71','online_order_no'=>'OTHER-ONLINE','product_code'=>'SKU-A','analysis'=>'未退回'],
|
||
]);
|
||
$this->assertSame('',$wrongOrder[0]['_matched_return_no']);
|
||
}
|
||
|
||
public function test_composite_cursor_does_not_skip_other_source_after_page_boundary(): void
|
||
{
|
||
$db=Rebooks::db();$rows=[];
|
||
for($i=1;$i<=77000;$i++){
|
||
$rows[]=['source_id'=>$i,'source_kind'=>'regular','waybill'=>'RETURN'.str_pad((string)$i,5,'0',STR_PAD_LEFT),'received_at'=>'2026-12-06','returned_qty'=>1,'generation'=>'test','synced_at'=>now()];
|
||
if(count($rows)===100){$db->table('courier_returned_parcels')->insert($rows);$rows=[];}
|
||
}
|
||
$db->table('courier_returned_parcels')->insert(['source_id'=>1,'source_kind'=>'taobao','waybill'=>'SECOND0001','received_at'=>'2026-12-06','returned_qty'=>1,'generation'=>'test','synced_at'=>now()]);
|
||
$started=microtime(true);$queries=0;$sqlMs=0;
|
||
DB::listen(function($q)use(&$queries,&$sqlMs){$queries++;$sqlMs+=$q->time;});
|
||
$result=app(\App\Support\CourierBills\RebookReturns::class)->annotate([['tracking_no'=>'SECOND0001','analysis'=>'未退回']]);
|
||
$this->assertSame('已退回',$result[0]['_return_status']);
|
||
fwrite(STDERR,sprintf("\nRETURN_MATCH_PERF rows=77001 seconds=%.3f peak_mb=%.1f queries=%d sql_ms=%.1f\n",microtime(true)-$started,memory_get_peak_usage(true)/1048576,$queries,$sqlMs));
|
||
}
|
||
|
||
public function test_four_carrier_names_returns_fuzzy_match_and_prior_refund_are_accounted_once(): void
|
||
{
|
||
$db = Rebooks::db();
|
||
if (! Schema::connection($db->getName())->hasTable('courier_returned_parcels')) {
|
||
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);
|
||
});
|
||
}
|
||
$names = ['新北中通', '新北中通其他', '新北中通配件', '新北中通其他配件'];
|
||
$group = app(CourierBillStore::class)->saveGroup(null, ['name' => '新北分组', 'express_names' => $names, 'rebook_months' => 2]);
|
||
$reasons = ['快递丢件', '双面单', '买家原因', '站点异常'];
|
||
$nums = ['301233122220', '301233122221', '301233122222', '301233122223'];
|
||
$store = DB::connection(config('database.supplier_payable_maintenance_connection'));
|
||
foreach ($names as $i => $name) {
|
||
$row = ['summary_month' => '2026-10', 'tracking_no' => $nums[$i], 'carrier' => $name,
|
||
'settle_bookkeeping' => '100', 'analysis' => '未退回', 'bookkeeping_reason' => $reasons[$i], 'cost' => '40', 'settle_freight' => '7'];
|
||
$store->table('supplier_payable_overrides')->insert(['company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
|
||
'record_key' => 'return-'.$i, 'values' => json_encode($row), 'created_at' => now(), 'updated_at' => now()]);
|
||
if ($i === 0) {
|
||
$store->table('supplier_payable_overrides')->insert(['company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
|
||
'record_key' => 'duplicate-source', 'values' => json_encode($row), 'created_at' => now(), 'updated_at' => now()]);
|
||
}
|
||
// 第二票通过去掉 T 前缀匹配;第四票未实际退回,不能触发补款。
|
||
$return = ['source_id' => 100 + $i, 'waybill' => $i === 1 ? 'T'.$nums[$i] : $nums[$i],
|
||
'received_at' => '2026-12-02 10:00:00', 'returned_qty' => $i === 3 ? 0 : 1];
|
||
if (Schema::connection($db->getName())->hasColumn('courier_returned_parcels', 'generation')) {
|
||
$return += ['generation' => 'test', 'synced_at' => now()];
|
||
}
|
||
$db->table('courier_returned_parcels')->insert($return);
|
||
}
|
||
$db->table('courier_bill_rebooks')->insert(['waybill_no' => $nums[0], 'deduct_month' => '2026-10',
|
||
'refund_month' => '2026-10', 'amount' => 85, 'source' => 'import', 'created_at' => now()]);
|
||
$id = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open',
|
||
'created_at' => now(), 'updated_at' => now()]);
|
||
$plan = app(Rebooks::class)->forStatement($id);
|
||
$rows = collect($plan['rows'])->keyBy('waybill');
|
||
$this->assertCount(4, $rows);
|
||
$this->assertSame(200.0, $rows[$nums[0]]['deducted']);
|
||
$this->assertCount(2, $rows[$nums[0]]['info']['_rebook_sources']);
|
||
$this->assertSame(0.0, $rows[$nums[0]]['amount']);
|
||
$this->assertSame(30.0, $rows[$nums[0]]['current']);
|
||
$this->assertSame(85.0, $rows[$nums[1]]['amount']);
|
||
$this->assertSame('模糊匹配(格式或T前缀)', $rows[$nums[1]]['info']['_rebook_sources'][0]['_return_method']);
|
||
$this->assertSame(100.0, $rows[$nums[2]]['amount']);
|
||
$this->assertSame(0.0, $rows[$nums[3]]['amount']);
|
||
$this->assertSame(['2026-10' => 185.0], Rebooks::totals($plan['rows']));
|
||
$this->assertSame(15.0, $rows[$nums[1]]['info']['_rebook_sources'][0]['_return_current']);
|
||
$this->assertSame(0.0, $rows[$nums[2]]['info']['_rebook_sources'][0]['_return_current']);
|
||
$this->assertArrayNotHasKey('_return_current', $rows[$nums[3]]['info']['_rebook_sources'][0]);
|
||
|
||
$annotated = app(\App\Support\CourierBills\RebookReturns::class)->annotate([
|
||
['tracking_no' => $nums[0], 'analysis' => '未退回', 'bookkeeping_reason' => '丢件', 'cost' => null, 'settle_freight' => 7],
|
||
['tracking_no' => $nums[0], 'analysis' => '已退回,记账损耗+运费', 'bookkeeping_reason' => '丢件', 'cost' => 40, 'settle_freight' => 7],
|
||
]);
|
||
$this->assertSame('已退回,成本或结算运费缺失待核对', $annotated[0]['_return_status']);
|
||
$this->assertArrayNotHasKey('_return_current', $annotated[0]);
|
||
$this->assertSame('已退回,记账损耗+运费', $annotated[1]['analysis']);
|
||
$this->assertArrayNotHasKey('_return_analysis', $annotated[1]);
|
||
|
||
$db->table('courier_bill_summary_items')->insert(['statement_id' => $id, 'label' => '2026.9-10月记账补款', 'self_amount' => 0, 'manual' => false, 'sort' => 1]);
|
||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->get();
|
||
$this->assertEquals(185, app(Rebooks::class)->summaryItems($id, $items)->first()->self_amount);
|
||
$this->assertEquals(0, $db->table('courier_bill_summary_items')->where('statement_id', $id)->value('self_amount'));
|
||
app(CourierBillStore::class)->confirm($id, 'tester');
|
||
$this->assertEquals(185, $db->table('courier_bill_summary_items')->where('statement_id', $id)->value('self_amount'));
|
||
$this->assertEquals(185, $db->table('courier_bill_rebooks')->where('statement_id', $id)->sum('amount'));
|
||
$this->assertCount(2, app(Rebooks::class)->forStatement($id)['rows']);
|
||
$db->table('courier_returned_parcels')->delete();
|
||
$this->artisan('courier-surcharge:match-bills',['--all'=>true,'--existing-only'=>true,'--all-months'=>true,'--refresh-rebooks'=>true])->assertSuccessful();
|
||
$this->assertEquals(185,$db->table('courier_bill_summary_items')->where('statement_id',$id)->value('self_amount'));
|
||
$this->assertEquals(185,$db->table('courier_bill_rebooks')->where('statement_id',$id)->sum('amount'));
|
||
}
|
||
|
||
public function test_automatic_refund_preserves_per_product_costs_and_holds_missing_costs(): void
|
||
{
|
||
\Illuminate\Support\Facades\Storage::fake('local');
|
||
$db = Rebooks::db();
|
||
if (! Schema::connection($db->getName())->hasTable('courier_returned_parcels')) {
|
||
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);
|
||
});
|
||
}
|
||
$group = app(CourierBillStore::class)->saveGroup(null, ['name' => '自动核对', 'express_names' => ['自动核对'], 'rebook_months' => 1]);
|
||
$source = DB::connection(config('database.supplier_payable_maintenance_connection'));
|
||
foreach ([[100,40,7],[50,20,3],[100,null,7],[50,20,3],[5,40,7]] as $i => [$old,$cost,$freight]) {
|
||
$wb = $i < 2 ? '100100100100' : ($i < 4 ? '100100100101' : '100100100102');
|
||
$source->table('supplier_payable_overrides')->insert(['company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
|
||
'record_key' => 'automatic-'.$i, 'values' => json_encode(['summary_month' => '2026-10', 'tracking_no' => $wb, 'carrier' => '自动核对', 'analysis' => '未退回',
|
||
'bookkeeping_reason' => '快递丢件', 'settle_bookkeeping' => $old, 'cost' => $cost, 'settle_freight' => $freight]), 'created_at' => now(), 'updated_at' => now()]);
|
||
}
|
||
foreach (['100100100100','100100100101','100100100102'] as $i => $wb) {
|
||
$return = ['source_id' => 5000+$i, 'waybill' => $wb, 'received_at' => now(), 'returned_qty' => 1];
|
||
if (Schema::connection($db->getName())->hasColumn('courier_returned_parcels', 'generation')) $return += ['generation' => 'test', 'synced_at' => now()];
|
||
$db->table('courier_returned_parcels')->insert($return);
|
||
}
|
||
$id = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now()]);
|
||
$db->table('courier_bill_summary_items')->insert(['statement_id' => $id, 'label' => '补10月记账', 'self_amount' => 0, 'manual' => false, 'sort' => 1]);
|
||
$plan = app(Rebooks::class)->forStatement($id);$rows = collect($plan['rows'])->keyBy('waybill');
|
||
$this->assertSame(22.0, $rows['100100100100']['current']);
|
||
$this->assertSame(128.0, $rows['100100100100']['amount']);
|
||
$this->assertNull($rows['100100100101']['current']);
|
||
$this->assertSame(0.0, $rows['100100100101']['amount']);
|
||
$this->assertSame(0.0, $rows['100100100102']['amount']);
|
||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->get();
|
||
$this->assertEquals(128, app(Rebooks::class)->summaryItems($id, $items)->first()->self_amount);
|
||
$items->first()->manual = true;$items->first()->self_amount = 90;
|
||
$this->assertEquals(90, app(Rebooks::class)->summaryItems($id, $items)->first()->self_amount);
|
||
$path = tempnam(sys_get_temp_dir(), 'auto-refund-');
|
||
try {
|
||
$fp=fopen($path,'wb');try { app(\App\Support\CourierBills\StatementExporter::class)->export($id,$fp); } finally { fclose($fp); }
|
||
$book=\PhpOffice\PhpSpreadsheet\IOFactory::load($path);
|
||
try {
|
||
$sheet=$book->getSheetByName('补10月记账');$values=$sheet->toArray(null,true,false);
|
||
$this->assertEquals([100,15,85],array_slice($values[1],28,3));
|
||
$this->assertEquals([50,7,43],array_slice($values[2],28,3));
|
||
$index=array_search('本期补款金额',$values[0],true);
|
||
$this->assertEquals(128,array_sum(array_column(array_slice($values,1),$index)));
|
||
$summary=$book->getSheetByName('汇总')->toArray(null,true,false);
|
||
$this->assertEquals(128,$summary[1][2]);
|
||
} finally { $book->disconnectWorksheets(); }
|
||
} finally { @unlink($path); }
|
||
}
|
||
}
|