CaiWuXiTong/tests/Feature/Business/DropshipWeightTest.php

133 lines
11 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\Http\Controllers\Business\DropshipFreightController;
use App\Support\CourierBills\{ShippingLookup, StreamingWorkbook};
use App\Support\DropshipFreight\{DropshipExporter, DropshipFreightStore, DropshipReconciler, FactoryBillParser};
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Feature\FeatureTestCase;
class DropshipWeightTest extends FeatureTestCase
{
public function test_lower_freight_also_uses_billed_weight_without_overwriting_original_calculation(): void
{
Storage::fake('local');$store=app(DropshipFreightStore::class);$shipping=app(ShippingLookup::class)->connection();
$id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']);
$file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',"单号,运费,重量\nWTLOW0001,8,2\nWTMISSING0001,8,\nWTHIGH0001,12,7\n")], '2026-11', '测试')[0];
foreach(['WTLOW0001','WTMISSING0001','WTHIGH0001'] as $i=>$no){
$shipping->table('jst_oms_shipping')->insert(['source_id'=>$i+1,'express_no'=>$no,'express_name1'=>'测试快递','warehouse_name'=>'测试代发仓','ship_time'=>'2026-11-03 09:00:00']);
$shipping->table('jst_oms_shipping_freight')->insert(['source_id'=>$i+1,'status'=>'OK','freight'=>10,'charge_weight'=>5]);
}
$factory=collect($store->factories())->firstWhere('id',$id);$result=app(DropshipReconciler::class)->factoryMonth($factory,'2026-11');
$rows=collect($result['rows'])->keyBy('waybill');
$this->assertEquals([10,5,8,2,0,0],array_map(fn($key)=>$rows['WTLOW0001'][$key],['calc','charge_weight','final','settlement_weight','weight_diff','freight_diff']));
$this->assertNull($rows['WTMISSING0001']['settlement_weight']);$this->assertNull($rows['WTMISSING0001']['weight_diff']);
$this->assertEquals([10,5,2,2],array_map(fn($key)=>$rows['WTHIGH0001'][$key],['final','settlement_weight','weight_diff','freight_diff']));
$this->assertEquals(26,$result['summary']['settle']);
$path=tempnam(sys_get_temp_dir(),'drop-weight');$out=fopen($path,'wb');
try{app(DropshipExporter::class)->export($factory,'2026-11',$out);}finally{fclose($out);}
try{
$book=IOFactory::load($path);$grid=$book->getSheetByName('对账')->toArray(null,false,false);$headers=array_shift($grid);
$low=collect($grid)->first(fn($row)=>$row[array_search('快递单号',$headers,true)]==='WTLOW0001');
$this->assertEquals(2,$low[array_search('结算重量',$headers,true)]);
$this->assertEquals(0,$low[array_search('重量差',$headers,true)]);
$this->assertEquals(0,$low[array_search('运费差',$headers,true)]);
$book->disconnectWorksheets();
}finally{@unlink($path);}
$this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail());$this->loginAs();
$this->get(route('business.pages.show',['section'=>'courier-payables','page'=>DropshipFreightController::PAGE,'df_view'=>'factory','factory'=>$id,'month'=>'2026-11']))
->assertOk()->assertSeeText('结算重量(kg)')->assertSeeText('运费差');
$this->assertEquals(28,$store->db()->table('dropship_bill_lines')->where('file_id',$file)->sum('amount'));
}
public function test_parser_sums_weight_without_treating_partial_missing_as_zero_or_reading_system_weight(): void
{
$path = tempnam(sys_get_temp_dir(), 'weight') . '.csv';
file_put_contents($path, "单号,运费,计费重量(kg),我方重量\nWB0001,5,2,99\nWB0001,6,3,99\nWB0002,5,2,99\nWB0002,6,,99\nWB0003,8,0,99\nWB0004,8,-1,99\n");
try {
$rows = app(FactoryBillParser::class)->parse($path, 'csv')['lines'];
$this->assertEquals(11, $rows['WB0001']['amount']);
$this->assertEquals(5, $rows['WB0001']['weight']);
$this->assertNull($rows['WB0002']['weight']);
$this->assertSame(0.0, $rows['WB0003']['weight']);
$this->assertNull($rows['WB0004']['weight']);
$this->assertNull(FactoryBillParser::findColumns(['单号','运费','我方计费重量','重量差'])['weight']);
} finally { @unlink($path); }
}
public function test_weight_difference_uses_unique_packages_and_is_visible_in_page_filter_and_export(): void
{
Storage::fake('local'); $store=app(DropshipFreightStore::class); $db=$store->db();
$id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']);
$path=tempnam(sys_get_temp_dir(),'weights').'.xlsx';$book=new StreamingWorkbook();
$book->row('账单',['单号','运费','重量'],true);
foreach([['WB0001',12,5],['WB0002',12,3],['WB0003',8,null],['OLD4',12,2],['WB0005',12,1]] as $row)$book->row('账单',$row);
$handle=fopen($path,'wb');$book->writeTo($handle);fclose($handle);
try {
$file=$store->upload([new UploadedFile($path,'重量测试.xlsx',null,null,true)],'2026-11','测试')[0];
$shipping=app(ShippingLookup::class)->connection();
foreach([['WB0001',1,2,5],['WB0001',1,2,5],['WB0001',2,1,5],['WB0002',3,3,10],['WB0003',4,3,10],['NEWB0004',5,2,10],['WB0005',6,3,10]] as $n=>[$no,$source,$weight,$amount]) {
$shipping->table('jst_oms_shipping')->insert(['express_no'=>$no,'source_id'=>$source,'sku_source_id'=>$n+1,'warehouse_name'=>'测试代发仓','express_name1'=>'测试快递','ship_time'=>'2026-11-03 09:00:00','front_no'=>$no==='NEWB0004'?'OLD4':null]);
$shipping->table('jst_oms_shipping_freight')->updateOrInsert(['source_id'=>$source],['charge_weight'=>$weight,'freight'=>$amount,'status'=>'OK']);
}
$factory=collect($store->factories())->firstWhere('id',$id);$result=app(DropshipReconciler::class)->factoryMonth($factory,'2026-11');
$rows=collect($result['rows'])->keyBy('waybill');
$this->assertEquals(3,$rows['WB0001']['charge_weight']);
$this->assertEquals(2,$rows['WB0001']['weight_diff']);
$this->assertSame('price_diff',$rows['WB0002']['diff_kind']);
$this->assertSame('missing_weight',$rows['WB0003']['diff_kind']);
$this->assertNull($rows['WB0003']['weight_diff']);
$this->assertEquals(0,$rows['OLD4']['weight_diff']);
$this->assertEquals(-2,$rows['WB0005']['weight_diff']);
$this->assertEquals(48,$result['summary']['settle']);
$this->assertSame(['weight_diff'=>2,'price_diff'=>2,'missing_weight'=>1],$result['summary']['diff_counts']);
$this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail());
$this->loginAs();
$url=route('business.pages.show',['section'=>'courier-payables','page'=>DropshipFreightController::PAGE,'df_view'=>'factory','factory'=>$id,'month'=>'2026-11','status'=>'weight_diff']);
$this->get($url)->assertOk()->assertSeeText('厂家重量(kg)')->assertSeeText('重量差(kg)')->assertSeeText('WB0001')->assertSeeText('WB0005')->assertDontSeeText('WB0002');
$out=tempnam(sys_get_temp_dir(),'weight-export');$handle=fopen($out,'wb');
try{app(DropshipExporter::class)->export($factory,'2026-11',$handle);}finally{fclose($handle);}
try{
$export=IOFactory::load($out);$grid=$export->getSheetByName('对账')->toArray(null,false,false);$headers=array_shift($grid);$weightCol=array_search('重量差',$headers,true);$wbCol=array_search('快递单号',$headers,true);
$w1=collect($grid)->first(fn($r)=>$r[$wbCol]==='WB0001');$this->assertEquals(2,$w1[$weightCol]);
$this->assertNotFalse(array_search('厂家重量(kg)',$headers,true));$export->disconnectWorksheets();
}finally{@unlink($out);}
$this->assertEquals(5,$db->table('dropship_bill_lines')->where('file_id',$file)->where('waybill_no','WB0001')->value('bill_weight'));
} finally {@unlink($path);}
}
public function test_backfill_preserves_amounts_and_skips_changed_source_and_is_idempotent(): void
{
Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db();
$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']);
$csv="单号,运费,重量\n";for($i=0;$i<1001;$i++)$csv.="BACK{$i},8,3\n";
$file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',$csv)],'2026-11','测试')[0];
$db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]);
$db->table('dropship_bill_lines')->where('waybill_no','BACK0')->update(['amount'=>9]);
$this->artisan('dropship-freight:backfill-weights',['--all'=>true])->assertSuccessful();
$this->assertSame(0,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count());
$this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful();
$this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count());
$this->assertEquals(8009,$db->table('dropship_bill_lines')->sum('amount'));
$this->assertNull($db->table('dropship_bill_lines')->where('waybill_no','BACK0')->value('bill_weight'));
$this->assertNotEmpty(Storage::disk('local')->allFiles('private/dropship-weight'));
$this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful();
$this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count());
}
public function test_backfill_skips_confirmed_factory_bills(): void
{
Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db();
$id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']);
$file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',"单号,运费,重量\nCONFIRM1,8,3\n")],'2026-11','测试')[0];
$db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]);
app(\Modules\EcommerceFinance\Services\SupplierPayableOverrideStore::class)->save('dropship-freight-confirm','2026-11|'.$id,
['status'=>'confirmed','month'=>'2026-11','factory_id'=>$id],(int)$this->company->id,null,'test');
$this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--company'=>$this->company->id,'--apply'=>true])->assertSuccessful();
$this->assertNull($db->table('dropship_bill_lines')->value('bill_weight'));
}
}