274 lines
19 KiB
PHP
274 lines
19 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 App\Support\DropshipFreight\DropshipUploadReminder;
|
||
use Carbon\Carbon;
|
||
use Illuminate\Support\Facades\Cache;
|
||
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();
|
||
}
|
||
|
||
public function test_notify_factories_that_have_not_uploaded_this_month(): void
|
||
{
|
||
Carbon::setTestNow(Carbon::parse('2026-12-03 10:00:00', 'Asia/Shanghai'));
|
||
$db = $this->reminderFixture();
|
||
$url = route('business.' . self::SECTION . '.dropship-freight.notify-upload');
|
||
|
||
$this->post($url, ['month' => '2026-11'])->assertSessionHas('dropship_message', '已通知 1 家上传 2026-11 代发运费账单:临沂卿德客'
|
||
. '(写明 12月14日 截止,逾期本月货款和运费不予结算);1 家已经上传,没再通知;1 家这个月没有代发发货,没通知;1 家没配钉钉群机器人:没配群。');
|
||
$this->assertCount(1, Http::recorded());
|
||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||
$this->assertStringContainsString('代发运费账单上传提醒 · 临沂卿德客', $text);
|
||
$this->assertStringContainsString('请于 **12月14日** 前上传 **2026年11月** 代发运费账单,还剩 11 天', $text);
|
||
$this->assertStringContainsString('**逾期未上传,本月货款和运费将不予结算**', $text);
|
||
$this->assertStringContainsString('[打开厂家对账入口](', $text);
|
||
// 不在上传期里的月份(比如单独补催 10 月):不写截止和后果;10 月没有代发发货,批量不发
|
||
$this->post($url, ['month' => '2026-10'])->assertSessionHas('dropship_message', fn (string $m): bool => str_starts_with($m, '已通知 0 家'));
|
||
$this->post($url, ['month' => '2026-10', 'factory' => $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id')]);
|
||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||
$this->assertStringContainsString('请上传 **2026年10月** 代发运费账单', $text);
|
||
$this->assertStringNotContainsString('不予结算', $text);
|
||
$count = count(Http::recorded());
|
||
// 单独通知一家:已上传、没代发发货也照发;没配机器人报错
|
||
$this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id')])
|
||
->assertSessionHas('dropship_message');
|
||
$this->assertCount($count + 1, Http::recorded());
|
||
$this->post($url, ['month' => '2026-11', 'factory' => $db->table('dropship_factories')->where('name', '没配群')->value('id')])
|
||
->assertSessionHasErrors('dropship');
|
||
$this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'factories', 'month' => '2026-11']))
|
||
->assertOk()->assertSeeText('通知上传');
|
||
$this->get(route('business.pages.show', ['section' => self::SECTION, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'upload', 'month' => '2026-11']))
|
||
->assertOk()->assertSeeText('通知厂家上传')->assertSeeText('自动提醒:已开启')->assertSeeText('关闭自动提醒');
|
||
Carbon::setTestNow();
|
||
}
|
||
|
||
public function test_auto_reminder_runs_on_the_1st_to_14th_for_last_months_bill(): void
|
||
{
|
||
$db = $this->reminderFixture();
|
||
$run = fn (string $date, array $options = []) => $this->artisan('dropship-freight:remind-upload', ['--date' => $date, ...$options]);
|
||
|
||
// 15 日以后不发
|
||
$run('2026-12-15')->assertExitCode(0);
|
||
$this->assertCount(0, Http::recorded());
|
||
// 试运行只列名单
|
||
$run('2026-12-04', ['--dry-run' => true])->expectsOutputToContain('会提醒 1 家:临沂卿德客')->assertExitCode(0);
|
||
$this->assertCount(0, Http::recorded());
|
||
|
||
$run('2026-12-04')->expectsOutputToContain('已通知 1 家上传 2026-11 代发运费账单:临沂卿德客')->assertExitCode(0);
|
||
$this->assertCount(1, Http::recorded());
|
||
$this->assertStringContainsString('还剩 10 天', (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? ''));
|
||
// 同一天不重复发
|
||
$run('2026-12-04')->expectsOutputToContain('今天已经提醒过')->assertExitCode(0);
|
||
$this->assertCount(1, Http::recorded());
|
||
// 14 日:今天截止
|
||
$run('2026-12-14')->assertExitCode(0);
|
||
$text = (string) (collect(Http::recorded())->last()[0]['markdown']['text'] ?? '');
|
||
$this->assertStringContainsString('代发运费账单上传提醒(今天截止) · 临沂卿德客', $text);
|
||
$this->assertStringContainsString('**今天截止**', $text);
|
||
// 厂家传了(解析失败的不算),第二天就不再催
|
||
$factory = $db->table('dropship_factories')->where('name', '临沂卿德客')->value('id');
|
||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'bad.xlsx',
|
||
'stored_path' => 'bad', 'status' => 'failed', 'created_at' => now(), 'updated_at' => now()]);
|
||
$run('2026-12-05')->expectsOutputToContain('已通知 1 家')->assertExitCode(0);
|
||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $factory, 'original_name' => 'ok.xlsx',
|
||
'stored_path' => 'ok', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]);
|
||
$sent = count(Http::recorded());
|
||
$run('2026-12-06')->expectsOutputToContain('已通知 0 家')->assertExitCode(0);
|
||
$this->assertCount($sent, Http::recorded());
|
||
|
||
// 关掉开关就不发
|
||
$db->table('dropship_bill_files')->where('original_name', 'ok.xlsx')->delete();
|
||
$this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 0])->assertSessionHas('dropship_message', '已关闭自动提醒。');
|
||
$this->assertFalse(DropshipUploadReminder::enabled());
|
||
$run('2026-12-07')->expectsOutputToContain('自动提醒已关闭')->assertExitCode(0);
|
||
$this->assertCount($sent, Http::recorded());
|
||
$this->post(route('business.' . self::SECTION . '.dropship-freight.auto-remind'), ['enabled' => 1]);
|
||
$this->assertTrue(DropshipUploadReminder::enabled());
|
||
}
|
||
|
||
private function reminderFixture()
|
||
{
|
||
Storage::fake('local');
|
||
Cache::flush();
|
||
$this->company->makeCurrent(true);
|
||
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
|
||
$this->loginAs()->withExceptionHandling();
|
||
$db = CourierBillMatcher::db();
|
||
$notifier = app(SupplierDingTalkNotifier::class);
|
||
$source = 9100;
|
||
foreach (['临沂卿德客' => '德客', '河北丽彪' => '丽彪', '没配群' => '配群', '无代发厂' => '代发厂'] as $name => $keyword) {
|
||
$warehouse = '工厂-' . $name . '代发仓';
|
||
$db->table('dropship_factories')->insert(['name' => $name, 'warehouse' => $warehouse, 'keywords' => $keyword,
|
||
'created_at' => now(), 'updated_at' => now()]);
|
||
if ($name !== '无代发厂') {
|
||
$this->shipping()->table('jst_oms_shipping')->insert(['express_no' => 'DF' . $source, 'express_name1' => $keyword . '代发韵达',
|
||
'warehouse_name' => $warehouse, 'ship_time' => '2026-11-20 10:00:00', 'source_id' => $source++]);
|
||
}
|
||
if ($name !== '没配群') {
|
||
$notifier->save($name, 'https://oapi.dingtalk.com/robot/send?access_token=' . $source++, '', false);
|
||
}
|
||
}
|
||
$db->table('dropship_bill_files')->insert(['bill_month' => '2026-11', 'factory_id' => $db->table('dropship_factories')->where('name', '河北丽彪')->value('id'),
|
||
'original_name' => 'x.xlsx', 'stored_path' => 'x', 'status' => 'parsed', 'created_at' => now(), 'updated_at' => now()]);
|
||
Http::fake(['*' => Http::response(['errcode' => 0, 'errmsg' => 'ok'])]);
|
||
|
||
return $db;
|
||
}
|
||
|
||
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;
|
||
}
|
||
}
|