CaiWuXiTong/tests/Feature/Business/DropshipFreightConfirmTest.php

164 lines
11 KiB
PHP

<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup;
use App\Support\DropshipFreight\DropshipConfirmation;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class DropshipFreightConfirmTest extends FeatureTestCase
{
private const WAREHOUSE = '工厂-山东卿德客代发仓';
private const SECTION = 'courier-payables-final';
public function test_checked_factory_is_pushed_to_its_dingtalk_group_and_the_factory_disputes_single_waybills(): void
{
$this->withoutMiddleware(\Illuminate\Routing\Middleware\ThrottleRequests::class);
Storage::fake('local');
$this->company->makeCurrent(true);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$this->ship('773444000001', '卿德客申通', '2026-10-03 09:00:00', 1, 8); // 一致
$this->ship('773444000002', '卿德客申通', '2026-10-04 09:00:00', 2, 5); // 厂家多开
$this->ship('773444000003', '卿德客申通', '2026-10-05 09:00:00', 3, 6); // 厂家没开:不在确认页
$this->shipping()->table('jst_oms_shipping')->update(['supplier_name' => '临沂卿德客']);
$this->post(route('business.' . self::SECTION . '.dropship-freight.generate'), ['month' => '2026-10'])->assertRedirect();
$factory = CourierBillMatcher::db()->table('dropship_factories')->sole();
$bill = new UploadedFile($this->xlsx([['快递单号', '快递公司', '运费'], ['773444000001', '卿德客申通', 8], ['773444000002', '卿德客申通', 6]]),
'临沂卿德客10月.xlsx', null, null, true);
$this->post(route('business.' . self::SECTION . '.dropship-freight.upload'), ['month' => '2026-10', 'files' => [$bill]])->assertRedirect();
$action = fn (string $name) => route('business.' . self::SECTION . '.dropship-freight.' . $name, ['factory' => $factory->id]);
$overview = route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'month' => '2026-10']);
// 没核对完成不能推送;没配机器人也不能推送
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHasErrors('dropship');
$this->post($action('check'), ['month' => '2026-10', 'checked' => 1])->assertSessionHas('dropship_message');
$this->get($overview)->assertOk()->assertSeeText('已核完,待推送')->assertSeeText('未配钉钉群机器人');
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHasErrors('dropship');
app(SupplierDingTalkNotifier::class)->save('临沂卿德客', 'https://oapi.dingtalk.com/robot/send?access_token=df-test', 'SEC-df', false);
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('代发运费对账确认 · 临沂卿德客', $text);
$this->assertStringContainsString('厂家开运费:**2** 单,**¥14.00**', $text);
$this->assertStringContainsString('核对后应结运费:**¥13.00**', $text);
$this->assertStringContainsString('不结或运费有差的单:**1** 单', $text);
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$link1 = $m[1];
$this->get($overview)->assertOk()->assertSeeText('已推送,待厂家确认');
$page = $this->get($link1)->assertOk()->assertHeader('X-Robots-Tag', 'noindex, nofollow, noarchive')
->assertSeeText('临沂卿德客 · 2026年10月 代发运费对账确认')->assertSeeText('773444000002')->assertSeeText('一致但运费有差')
->assertDontSeeText('773444000003');
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $m);
$submit = html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
// 不在账单里的单号、勾选了没写原因:都退回
$this->post($submit, ['other' => '999 不对'])->assertSessionHasErrors('dispute');
$this->post($submit, ['d' => ['773444000002']])->assertSessionHasErrors('dispute');
$this->post($submit, ['d' => ['773444000002'], 'r' => ['773444000002' => '偏远地区,应为 6 元'],
'other' => "773444000001 这单重量不对"])->assertRedirect()->assertSessionHas('success');
$c = app(DropshipConfirmation::class);
$state = $c->state('2026-10', (int) $factory->id, (int) $this->company->id);
$this->assertSame(DropshipConfirmation::DISPUTED, $state['status']);
$this->assertSame(2, $state['disputed_count']);
$this->assertSame(['773444000001' => '这单重量不对', '773444000002' => '偏远地区,应为 6 元'],
collect($c->disputes('2026-10', (int) $factory->id, (int) $this->company->id))->sortBy('waybill')->pluck('reason', 'waybill')->all());
$receipt = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('代发运费确认回执 · 临沂卿德客', $receipt);
$this->assertStringContainsString('有异议 2 单', $receipt);
$sent = count(Http::recorded());
$this->post($submit, [])->assertSessionHasErrors('dispute');
$this->assertCount($sent, Http::recorded());
$this->assertSame(DropshipConfirmation::DISPUTED, $c->state('2026-10', (int) $factory->id, (int) $this->company->id)['status']);
$this->get($link1)->assertOk()->assertSeeText('提交 2 单异议');
$detail = route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation',
'df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']);
$this->get($detail)->assertOk()->assertSeeText('厂家有异议')->assertSeeText('偏远地区,应为 6 元');
// 重新推送:第 2 次,旧链接作废;厂家这次确认无异议
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
$this->assertStringContainsString('第 **2** 次推送', $text);
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$this->get($link1)->assertOk()->assertSeeText('不是最新一次推送');
$page = $this->get($m[1])->assertOk();
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $s);
$this->post(html_entity_decode($s[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'), [])->assertSessionHas('success', '已确认无异议,财务系统已实时收到。回执已发到钉钉群。');
$this->assertSame(DropshipConfirmation::CONFIRMED, $c->state('2026-10', (int) $factory->id, (int) $this->company->id)['status']);
$this->get($overview)->assertOk()->assertSeeText('厂家已确认')->assertSeeText('重新推送');
$this->post($action('check'), ['month' => '2026-10', 'checked' => 0])->assertSessionHasErrors('dropship');
preg_match('/href="([^"]*dropship-freight[^"]*\/excel[^"]*)"/', (string) $page->getContent(), $x);
$this->get(html_entity_decode($x[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'))->assertOk()
->assertHeader('content-disposition');
// 已确认后仍可重新推送;同一单号的新异议不能覆盖上一版本。
$this->post($action('push'), ['month' => '2026-10'])->assertSessionHas('dropship_message');
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
preg_match('/\[打开运费确认页\]\(([^)]+)\)/', $text, $m);
$page = $this->get($m[1])->assertOk();
preg_match('/action="([^"]*dropship-freight[^"]*\/submit[^"]*)"/', (string) $page->getContent(), $s);
$this->post(html_entity_decode($s[1], ENT_QUOTES | ENT_HTML5, 'UTF-8'), [
'other' => '773444000002 第三版核对原因',
])->assertSessionHas('success');
$this->assertCount(2, $c->disputes('2026-10', (int) $factory->id, (int) $this->company->id, 1));
$this->assertSame('第三版核对原因', $c->disputes('2026-10', (int) $factory->id, (int) $this->company->id, 3)[0]['reason']);
}
public function test_share_tokens_are_limited_to_the_company_and_expiry(): void
{
$links = app(\App\Support\DropshipFreight\DropshipShareLink::class);
$company = (int) $this->company->id;
$url = $links->pageUrl($company, 1, '2026-10', 1);
$token = basename((string) parse_url($url, PHP_URL_PATH));
$this->assertSame(['factory_id' => 1, 'month' => '2026-10', 'version' => 1], $links->resolveToken($token, $company));
$this->assertNull($links->resolveToken($token, $company + 1));
$this->assertNull($links->resolveToken('invalid-token', $company));
$this->withExceptionHandling()->get(str_replace('/' . $token . '?', '/invalid-token?', $url))->assertForbidden();
$this->travel(31)->days();
$this->withExceptionHandling()->get($url)->assertForbidden();
$this->travelBack();
}
private function shipping()
{
return app(ShippingLookup::class)->connection();
}
private function ship(string $waybill, string $express, string $time, int $source, ?float $freight): void
{
$this->shipping()->table('jst_oms_shipping')->insert(['express_no' => $waybill, 'express_name1' => $express, 'warehouse_name' => self::WAREHOUSE,
'ship_time' => $time, 'source_id' => $source]);
$this->shipping()->table('jst_oms_shipping_freight')->insert(['source_id' => $source, 'freight' => $freight, 'status' => 'OK', 'charge_weight' => 1]);
}
/** @param list<list<mixed>> $rows */
private function xlsx(array $rows): string
{
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->setTitle('运费+货款');
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
$sheet->setCellValueExplicit([$c + 1, $r + 1], $value, is_string($value)
? \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING : \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC);
}
}
$path = tempnam(sys_get_temp_dir(), 'dfc_') . '.xlsx';
(new Xlsx($book))->save($path);
return $path;
}
}