feat(厂家门户): 上传运费账单并后台校验读入 #1669

Closed
limeng wants to merge 7 commits from feature/limeng-portal-freight-bills into main
20 changed files with 907 additions and 10 deletions

View File

@ -0,0 +1,18 @@
<?php
namespace App\Console\Commands;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Console\Command;
final class ImportPortalFreightBills extends Command
{
protected $signature = 'portal-freight:import-pending';
protected $description = '受限批容器处理一份厂家或快递门户运费账单';
public function handle(PortalFreightBillImports $imports): int
{
$imports->processNext();
return self::SUCCESS;
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Http\Controllers\Business;
use App\Services\Auth\SupplierPortalAccess;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBills;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* 厂家门户(钉钉登录的供应商对账入口)上传运费账单:代发厂家传代发运费账单,快递传快递账单,统一模板、严格校验。
* 厂家/快递只能给钉钉组织里绑定的自己上传;财务在同一页面可以代任意一家上传。
*/
final class PortalFreightBillController extends Controller
{
public const KINDS = ['dropship' => '代发运费账单', 'courier' => '快递账单'];
public function __construct(
private readonly FreightBillTemplate $template,
private readonly PortalFreightBills $portal,
private readonly SupplierPortalAccess $access,
) {
$this->middleware('auth');
$this->middleware('company.identify');
}
public function template(): StreamedResponse
{
return $this->template->download('运费账单上传模板.xlsx');
}
public function upload(Request $request): RedirectResponse
{
$data = $request->validate([
'kind' => ['required', 'in:dropship,courier'],
'month' => ['required', 'date_format:Y-m'],
'group' => ['nullable', 'integer'],
'import' => ['required', 'file', 'max:51200'],
], [], ['import' => '账单文件', 'month' => '账单月份']);
$file = $request->file('import');
$extension = strtolower($file->getClientOriginalExtension());
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']);
}
$name = $this->effectiveName($request);
if ($data['kind'] === 'dropship') {
$target = $this->portal->factory($name);
} else {
$groups = $this->portal->groups($name);
$target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0));
}
if ($target === null) {
throw ValidationException::withMessages(['freight_bill' => '当前厂家或快递分组不匹配,请联系财务。']);
}
app(PortalFreightBillImports::class)->submit($file, [
'name' => $name, 'kind' => $data['kind'], 'month' => $data['month'], 'target_id' => (int) $target->id,
'company_id' => (int) company_id(), 'user_id' => (int) $request->user()->id,
'uploader' => mb_substr((string) ($request->user()->name ?: $request->user()->email) . '(门户)', 0, 64),
]);
return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。');
}
/** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */
private function effectiveName(Request $request): string
{
$user = $request->user();
$name = trim((string) $request->input('supplier', ''));
if ($user && SupplierPortalAccess::isSupplierUser($user)) {
$names = $this->access->supplierNamesFor($user);
abort_if($names === [], 403, '当前钉钉账号未绑定有效厂家,请联系财务人员。');
if (count($names) === 1 && $name === '') {
return $names[0];
}
abort_unless(in_array($name, $names, true), 403, '该厂家不在当前账号的授权范围内。');
return $name;
}
if ($name === '') {
throw ValidationException::withMessages(['freight_bill' => '请先选择厂家。']);
}
return $name;
}
}

View File

@ -130,6 +130,20 @@ class SupplierPortalAccess
}
$resolved = [];
// 快递:部门名是快递账单对账分组名或承运商名的,也能登录厂家门户上传快递账单(不在供应商主档里)
foreach (\App\Support\CourierBills\PortalFreightBills::courierNames(array_keys($groupsByName)) as $courierName) {
if (isset($matchedSupplierNames[$courierName])) {
continue;
}
usort($groupsByName[$courierName], static fn (array $left, array $right): int =>
(int) ($right['depth'] ?? 0) <=> (int) ($left['depth'] ?? 0));
$resolved[] = [
'supplier_name' => $courierName,
'supplier_code' => '',
'dingtalk_group_id' => (int) ($groupsByName[$courierName][0]['Id'] ?? 0),
'dingtalk_group_name' => $courierName,
];
}
foreach (array_keys($matchedSupplierNames) as $supplierName) {
$matchingRows = array_values(array_filter(
$supplierRows,

View File

@ -352,6 +352,16 @@ final class CourierBillStore
return $ids;
}
/** 门户上传仅写入已授权分组;不从可控文件名或合并账单配置扩展到其他分组。 */
public function uploadFor(\Illuminate\Http\UploadedFile $file, string $month, int $groupId, string $user): int
{
$groups = $this->groups();
if (! collect($groups)->contains('id', $groupId)) throw new RuntimeException('快递分组不存在。');
$id = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month, [$groupId], $groups, $user, true);
foreach ($this->statementsOfFiles([$id]) as $statementId) $this->matcher->match($statementId);
return $id;
}
/** 给待选分组的文件指定分组,读入并对账。 */
public function assign(int $fileId, int $groupId): void
{
@ -413,7 +423,7 @@ final class CourierBillStore
* @param list<int> $groupIds
* @param list<object> $groups
*/
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): int
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user, bool $portal = false): int
{
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
@ -422,7 +432,7 @@ final class CourierBillStore
$group = $groupIds !== []
? collect($groups)->firstWhere('id', $groupIds[0])
: self::identify($name, $groups);
$extra = array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)]));
$extra = $portal ? [] : array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)]));
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
@ -435,14 +445,14 @@ final class CourierBillStore
return $id;
}
if ($group !== null) {
$this->ingest($id, $group);
$this->ingest($id, $group, false, $portal);
}
return $id;
}
/** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */
private function ingest(int $fileId, object $group, bool $reread = false): void
private function ingest(int $fileId, object $group, bool $reread = false, bool $portal = false): void
{
$db = $this->db();
$file = $db->table('courier_bill_files')->find($fileId);
@ -471,7 +481,7 @@ final class CourierBillStore
$feeCount = 0;
$overlap = null;
try {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, $portal, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap, &$surcharge, &$fees, &$feeTotal, &$feeCount): string {
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
}
@ -480,7 +490,9 @@ final class CourierBillStore
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
}
$db->table('courier_bill_surcharges')->where('file_id', $fileId)->delete();
$overrides = ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
$overrides = $portal
? ['waybill_header' => '单号', 'amount_header' => '运费', 'weight_header' => '重量']
: ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
foreach ($this->parser->parse($path, $extension, $overrides) as $item) {
if ($item['type'] === 'sheet') {
$sheets[] = isset($item['skipped'])
@ -550,7 +562,7 @@ final class CourierBillStore
$db->table('courier_bill_surcharges')->insert($fees);
}
return $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
return $portal ? '' : $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
});
} catch (Throwable $error) {
if ($reread) {

View File

@ -0,0 +1,121 @@
<?php
namespace App\Support\CourierBills;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 快递 / 代发厂家自己上传运费账单用的统一模板:单号、省、重量、运费、送货备注、面单、费率。
* 严格按模板:第一张表第一行必须就是这 7 列;单号、运费必填,重量、面单、费率填了就得是数字。
*/
final class FreightBillTemplate
{
public const HEADERS = ['单号', '省', '重量', '运费', '送货备注', '面单', '费率'];
private const MAX_ERRORS = 10;
private const TOTAL_WORDS = ['合计', '总计', '小计'];
public function __construct(private readonly BillWorkbookReader $reader) {}
public function download(string $fileName): StreamedResponse
{
return response()->streamDownload(static function (): void {
$book = new StreamingWorkbook();
$book->row('账单', self::HEADERS, true);
$book->writeTo(fopen('php://output', 'wb'));
}, $fileName);
}
/**
* 校验上传的文件是不是按模板填的,不对就把前几处错误一起报出来。
*
* @return array{rows:int,waybills:int,amount:float}
*/
public function validate(string $path, string $extension): array
{
try {
$sheets = $this->reader->sheets($path, $extension);
$rows = $sheets->current();
} catch (Throwable $error) {
throw new RuntimeException('读不了这个文件:' . $error->getMessage());
}
if ($rows === null) {
throw new RuntimeException('文件是空的。');
}
if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) {
throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。');
}
$errors = [];
$header = null;
$count = 0;
$amount = 0.0;
$waybills = [];
foreach ($rows as $index => $row) {
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
if ($header === null) {
$cells[0] = preg_replace('/^\x{FEFF}/u', '', $cells[0] ?? '');
$header = array_values(self::trimTail($cells));
if ($header !== self::HEADERS) {
throw new RuntimeException('请用上传模板:第一行必须依次是「' . implode('、', self::HEADERS) . '」,现在是「'
. implode('、', array_filter($header, static fn (string $h): bool => $h !== '')) . '」。');
}
continue;
}
if (implode('', $cells) === '') {
continue;
}
$line = (int) $index;
$waybill = $cells[0] ?? '';
if (in_array($waybill, self::TOTAL_WORDS, true)) {
continue;
}
if ($waybill === '') {
$errors[] = '第 ' . $line . ' 行没有单号';
} elseif (Waybill::normalize($waybill) === null) {
$errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
}
$freight = BillParser::number($cells[3] ?? null);
if ($freight === null || ! is_finite($freight)) {
$errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字');
}
foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) {
$value = BillParser::number($cells[$col] ?? null);
if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) {
$errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字';
}
}
if (count($errors) >= self::MAX_ERRORS) {
break;
}
$count++;
if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。');
$amount += (float) $freight;
$waybills[$waybill] = true;
}
if ($header === null) {
throw new RuntimeException('文件是空的。');
}
if ($errors !== []) {
throw new RuntimeException('账单有 ' . (count($errors) >= self::MAX_ERRORS ? '多处' : count($errors) . ' 处') . '要改:'
. implode(';', array_slice($errors, 0, self::MAX_ERRORS)) . '。');
}
if ($count === 0) {
throw new RuntimeException('模板里还没有填账单明细。');
}
$sheets->next();
if ($sheets->valid()) throw new RuntimeException('请只保留模板的一张账单工作表,不要附带其他工作表。');
return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)];
}
/** @param list<string> $cells */
private static function trimTail(array $cells): array
{
while ($cells !== [] && end($cells) === '') {
array_pop($cells);
}
return $cells;
}
}

View File

@ -0,0 +1,126 @@
<?php
namespace App\Support\CourierBills;
use App\Models\Auth\User;
use App\Services\Auth\SupplierPortalAccess;
use App\Support\DropshipFreight\DropshipFreightStore;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Throwable;
/** 沿用文件任务模式;网页只收文件,受限批容器逐个校验、读入,不自动重试。 */
final class PortalFreightBillImports
{
public const ROOT = 'private/portal-freight-bills';
public function submit(UploadedFile $file, array $details): void
{
$token = (string) Str::uuid();
$dir = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token);
if (! mkdir($dir, 0700, true)) throw new RuntimeException('无法保存账单,请稍后重试。');
$extension = strtolower($file->getClientOriginalExtension());
$file->move($dir, 'input.' . $extension);
$task = $details + ['token' => $token, 'extension' => $extension,
'original_name' => mb_substr($file->getClientOriginalName(), 0, 255),
'status' => 'queued', 'created_at' => now('Asia/Shanghai')->toDateTimeString(), 'message' => null];
$this->write($task);
$queue = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending');
if (! is_dir($queue)) mkdir($queue, 0700, true);
touch($queue . '/' . $token);
}
public function recent(int $companyId, string $name): array
{
$files = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $companyId . '/' . hash('sha256', $name) . '/*.json')) ?: [];
rsort($files);
$out = [];
foreach (array_slice($files, 0, 10) as $path) {
$task = json_decode((string) file_get_contents($path), true);
if (! is_array($task) || $task['company_id'] !== $companyId || $task['name'] !== $name || $task['status'] === 'completed') continue;
$out[] = ['kind' => $task['kind'] === 'dropship' ? '代发运费' : '快递账单', 'month' => $task['month'],
'name' => $task['original_name'], 'count' => 0, 'amount' => 0, 'status' => $task['status'],
'message' => $task['message'], 'at' => $task['created_at']];
}
usort($out, static fn ($a, $b) => strcmp($b['at'], $a['at']));
return array_slice($out, 0, 10);
}
public function processNext(): bool
{
$pending = glob(\Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/pending/*')) ?: [];
sort($pending);
foreach ($pending as $marker) {
$token = basename($marker);
if (! Str::isUuid($token)) continue;
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $token . '/task.json');
$task = json_decode((string) file_get_contents($path), true, 32, JSON_THROW_ON_ERROR);
if ($task['status'] !== 'queued') {
// 上次进程中断后不重导,保留现场供财务核对。
if ($task['status'] === 'running') $this->write(array_replace($task, ['status' => 'failed', 'message' => '处理曾中断,请联系财务核对后重新上传。']));
unlink($marker);
return true;
}
$task['status'] = 'running';
$this->write($task);
try {
$this->process($task);
$task['status'] = 'completed';
} catch (Throwable $e) {
$task['status'] = 'failed';
$task['message'] = $e instanceof RuntimeException && ! $e instanceof \Illuminate\Database\QueryException
? mb_substr($e->getMessage(), 0, 500) : '账单处理失败,请联系财务核对。';
report($e);
}
$this->write($task);
unlink($marker);
return true;
}
return false;
}
private function process(array $task): void
{
$user = User::find($task['user_id']);
if (! $user || ! $user->enabled || ! $user->companies()->where('companies.id', $task['company_id'])->exists()) throw new RuntimeException('上传账号已停用或授权已变化,请联系财务。');
\App\Models\Common\Company::findOrFail($task['company_id'])->makeCurrent(true);
if (SupplierPortalAccess::isSupplierUser($user) && ! in_array($task['name'], app(SupplierPortalAccess::class)->supplierNamesFor($user), true)) throw new RuntimeException('厂家授权已变化,请联系财务。');
$portal = app(PortalFreightBills::class);
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/input.' . $task['extension']);
app(FreightBillTemplate::class)->validate($path, $task['extension']);
if ($task['kind'] === 'dropship') {
$factory = $portal->factory($task['name']);
if ($factory === null || (int) $factory->id !== $task['target_id']) throw new RuntimeException('厂家设置已变化,请联系财务。');
$store = app(DropshipFreightStore::class);
$id = $store->uploadFor($task['original_name'], $path, $task['month'], $task['target_id'], $task['uploader']);
$row = $store->db()->table('dropship_bill_files')->find($id);
} else {
if (! collect($portal->groups($task['name']))->contains(fn ($g) => (int) $g->id === $task['target_id'])) throw new RuntimeException('快递分组设置已变化,请联系财务。');
$store = app(CourierBillStore::class);
$id = $store->uploadFor(new UploadedFile($path, $task['original_name'], null, null, true), $task['month'], $task['target_id'], $task['uploader']);
$row = $store->db()->table('courier_bill_files')->find($id);
}
if ($row === null || $row->status !== 'parsed') throw new RuntimeException('没有读入:' . ($row->message ?? '请联系财务。'));
// 回执采用实际读入金额,避免重复单号等过滤后仍报上传文件总额。
$summary = ['rows' => (int) ($row->row_count ?? $row->waybill_count), 'waybills' => (int) ($row->waybill_count ?? $row->row_count), 'amount' => (float) $row->amount];
try {
app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($task['name'], $task['kind'] === 'dropship' ? '代发运费账单' : '快递账单', $task['month'], $task['original_name'], $summary);
} catch (Throwable $e) { report($e); }
}
private function write(array $task): void
{
$path = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/tasks/' . $task['token'] . '/task.json');
if (file_put_contents($path . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX) === false) throw new RuntimeException('账单状态保存失败。');
chmod($path . '.tmp', 0600);
rename($path . '.tmp', $path);
$index = \Illuminate\Support\Facades\Storage::disk('local')->path(self::ROOT . '/index/' . $task['company_id'] . '/' . hash('sha256', $task['name']));
if (! is_dir($index)) mkdir($index, 0700, true);
$indexPath = $index . '/' . str_replace([' ', ':', '-'], '', $task['created_at']) . '-' . $task['token'] . '.json';
file_put_contents($indexPath . '.tmp', json_encode($task, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), LOCK_EX);
chmod($indexPath . '.tmp', 0600);
rename($indexPath . '.tmp', $indexPath);
}
}

View File

@ -0,0 +1,105 @@
<?php
namespace App\Support\CourierBills;
use App\Support\DropshipFreight\DropshipFreightStore;
use Throwable;
/**
* 厂家门户里的「运费账单」:代发厂家上传代发运费账单、快递上传快递账单,都按统一模板。
* 代发厂家按厂家名对上代发厂家设置;快递按承运商名对上快递账单对账分组(分组名或小汇总承运商)。
*/
final class PortalFreightBills
{
public function __construct(
private readonly CourierBillStore $courier,
private readonly DropshipFreightStore $dropship,
) {}
public function factory(string $name): ?object
{
try {
return collect($this->dropship->factories())->first(static fn (object $f): bool => trim((string) $f->name) === trim($name));
} catch (Throwable) {
return null;
}
}
/** @return list<object> 这个承运商名对应的快递对账分组 */
public function groups(string $name): array
{
$name = trim($name);
try {
return array_values(array_filter($this->courier->groups(), static fn (object $g): bool => $name !== ''
&& (trim((string) $g->name) === $name || trim((string) ($g->summary_carrier ?? '')) === $name)));
} catch (Throwable) {
return [];
}
}
/** 财务代传入口包含尚未上传货款对账单的代发厂家与快递。 */
public function names(): array
{
try {
return array_values(array_unique([
...array_map(static fn ($f) => (string) $f->name, $this->dropship->factories()),
...array_map(static fn ($g) => (string) $g->name, $this->courier->groups()),
]));
} catch (Throwable) {
return [];
}
}
/**
* 钉钉组织里能认作「快递」的部门名:快递对账分组名和小汇总承运商名。
*
* @param list<string> $names
* @return list<string>
*/
public static function courierNames(array $names): array
{
$names = array_values(array_unique(array_filter(array_map('trim', $names))));
if ($names === []) {
return [];
}
try {
$db = CourierBillMatcher::db();
$found = $db->table('courier_bill_groups')->whereIn('name', $names)->pluck('name')
->merge($db->table('courier_bill_groups')->whereIn('summary_carrier', $names)->pluck('summary_carrier'))
->map(static fn ($n): string => trim((string) $n))->unique()->values()->all();
} catch (Throwable) {
return [];
}
return array_values(array_intersect($names, $found));
}
/** @return array{factory:?object,groups:list<object>,files:list<array<string,mixed>>} */
public function panel(string $name): array
{
$factory = $this->factory($name);
$groups = $this->groups($name);
$files = app(PortalFreightBillImports::class)->recent((int) company_id(), $name);
try {
if ($factory !== null) {
foreach ($this->dropship->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->orderByDesc('id')->limit(10)
->get() as $f) {
$files[] = ['kind' => '代发运费', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->waybill_count,
'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at];
}
}
if ($groups !== []) {
$ids = array_map(static fn (object $g): int => (int) $g->id, $groups);
foreach ($this->courier->db()->table('courier_bill_files')->whereIn('group_id', $ids)->orderByDesc('id')->limit(10)->get() as $f) {
$files[] = ['kind' => '快递账单', 'month' => $f->bill_month, 'name' => $f->original_name, 'count' => (int) $f->row_count,
'amount' => (float) $f->amount, 'status' => $f->status, 'message' => $f->message, 'at' => (string) $f->created_at];
}
}
} catch (Throwable) {
// 表没建好时只是不显示上传记录
}
usort($files, static fn (array $a, array $b): int => strcmp($b['at'], $a['at']));
return ['factory' => $factory, 'groups' => $groups, 'files' => array_slice($files, 0, 10)];
}
}

View File

@ -174,6 +174,17 @@ final class DropshipFreightStore
return $ids;
}
/** 厂家自己上传(厂家门户):已经知道是哪家,不用从文件名认。 */
public function uploadFor(string $name, string $path, string $month, int $factoryId, string $user): int
{
$factory = collect($this->factories())->firstWhere('id', $factoryId);
if ($factory === null) {
throw new RuntimeException('厂家不存在。');
}
return $this->register($name, $path, $month, [$factory], $user, $factory);
}
public function assign(int $fileId, int $factoryId): void
{
$file = $this->db()->table('dropship_bill_files')->find($fileId);
@ -287,12 +298,12 @@ final class DropshipFreightStore
}
/** @param list<object> $factories */
private function register(string $name, string $path, string $month, array $factories, string $user): int
private function register(string $name, string $path, string $month, array $factories, string $user, ?object $known = null): int
{
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'dropship-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
$factory = self::identify($name, $factories);
$factory = $known ?? self::identify($name, $factories);
$id = (int) $this->db()->table('dropship_bill_files')->insertGetId([
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored, 'status' => 'pending_factory',
'message' => $factory === null ? '文件名里没认出是哪家厂家,请选择厂家' : null,

View File

@ -264,6 +264,7 @@ CRON_TZ=Asia/Shanghai
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。

View File

@ -268,6 +268,7 @@ CRON_TZ=Asia/Shanghai
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
28 1 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jushuitan:sync-shipping --days=40 >/dev/null 2>&1
# 聚水潭发货数据:凌晨部分出库单商品明细未到齐、副本库也可能超时,晚上再补拉最近 3 天。

View File

@ -1,4 +1,5 @@
[
"portal-freight:import-pending",
"planting-reimbursement:auto-confirm",
"jushuitan:apply-shipping-corrections",
"actual-tax:import",

View File

@ -8,6 +8,7 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
portal-freight:import-pending) is_import=1 ;;
planting-reimbursement:auto-confirm) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
@ -26,6 +27,12 @@ case "${1:-}" in
;;
esac
cd "$REMOTE_DIR"
if [ "$1" = 'portal-freight:import-pending' ]; then
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
[ -n "$storage_root" ] && [ -d "$storage_root/app/private/portal-freight-bills/pending" ] || exit 0
pending="$(find "$storage_root/app/private/portal-freight-bills/pending" -maxdepth 1 -type f -print -quit)"
[ -n "$pending" ] || exit 0
fi
if [ "$1" = 'account-bills:exports:run' ]; then
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
[ -n "$storage_root" ] && [ -d "$storage_root" ] || exit 65

View File

@ -0,0 +1,15 @@
# 厂家门户上传运费账单
厂家和快递通过原有钉钉入口进入门户,下载统一模板后提交账单。账号仅能给绑定的厂家或快递上传。财务账号沿用原页面权限,可为选定对象代传。
模板第一行依次为:单号、省、重量、运费、送货备注、面单、费率。仅一张可见账单表,单号及运费必填;单号须完整,数字列须为有效数字。支持 XLSX、XLS、CSV,单份最多50MB、100,000行;XLS沿用现有读取器20MB限制。
网页只保存文件并显示等待处理。服务器每分钟通过现有独立批容器执行 `portal-freight:import-pending`,每次处理一份。使用共享同步锁,1 CPU、1GiB容器内存、PHP512MiB和一小时上限。无待办时不启动容器。校验失败在上传记录显示原因;进程中断不自动重导,下一次标记失败,财务核对已有记录后再决定重传。
后台继续使用现有代发/快递账单读取与对账规则,重复上传、已结算月份等限制仍生效。门户快递上传不会通过文件名或合并分组设置扩大目标范围。成功回执使用实际读入行数和金额;未配置群机器人时不发送。
不新增数据库表。任务文件沿用私有共享storage目录,原账单由现有账单存储流程留存。页面仅查当前对象的近期任务及最近10份已读入账单。
验证需包含:两类门户上传、未授权对象拒绝、停用账号拒绝、模板错误、多表拒绝、后台隔离、重复导入和原有对账回归。性能基准以线上已有约7,500行账单为参照,使用10,000行合成账单在隔离环境测量,不向真实厂家群发送测试消息。
本次隔离SQLite验证:10,000行代发账单,文件222,830字节,读入0.482秒,45次数据库查询,数据库累计44.89ms;7,500行快递账单,文件167878字节,读入1.003秒,7609次查询,数据库累计243.36ms。进程峰值分别约128.7MiB和130MiB;包含测试框架开销。未对生产执行压测。

View File

@ -505,6 +505,30 @@ class SupplierDingTalkNotifier
return true;
}
/** @param array{rows:int,waybills:int,amount:float} $summary */
public function sendFreightBillUploadReceipt(string $name, string $kind, string $month, string $fileName, array $summary): bool
{
$configs = $this->configs();
$config = is_array($configs[$name] ?? null) ? $configs[$name] : [];
$webhook = trim((string) ($config['webhook'] ?? ''));
if ($webhook === '') {
return false;
}
$this->assertWebhook($webhook);
$fileName = mb_strimwidth(trim((string) preg_replace('/[\r\n`]+/u', ' ', basename($fileName))), 0, 120, '…', 'UTF-8');
$this->send($webhook, trim((string) ($config['secret'] ?? '')), (bool) ($config['at_all'] ?? false),
$name . ' · ' . $kind . '上传回执 · ' . $this->displayMonth($month), implode("\n", [
'### ' . $kind . '上传回执 · ' . $name,
'- 账单月份:**' . $this->displayMonth($month) . '**',
'- 上传文件:' . ($fileName !== '' ? $fileName : '未命名文件'),
'- 账单:**' . $summary['rows'] . '** 行,运费合计 **¥' . number_format((float) $summary['amount'], 2) . '**',
'- 上传时间:' . $this->platformTimestamp(),
'- 数据状态:**已进入财务核对**',
]));
return true;
}
public function sendStatementReminder(
string $supplier,
string $accountingMonth,

View File

@ -331,6 +331,9 @@ class SupplierReconciliationPageData
) as $name) {
$suppliers[$name] = true;
}
foreach (app(\App\Support\CourierBills\PortalFreightBills::class)->names() as $name) {
$suppliers[$name] = true;
}
$supplierNames = array_keys($suppliers);
sort($supplierNames);
@ -350,8 +353,17 @@ class SupplierReconciliationPageData
? $this->returnPanelData($selected, $companyId, request()->query())
: ['returnPanel' => null, 'returnWarehouses' => []];
$freightPanel = $selected !== '' ? app(\App\Support\CourierBills\PortalFreightBills::class)->panel($selected) : null;
// 只是快递(不是供应商、也不是代发厂家)的账号:不显示货款对账单和退货,只上传快递账单
$courierOnly = $freightPanel !== null && $freightPanel['groups'] !== [] && $freightPanel['factory'] === null
&& $statementPage['total'] === 0 && ! $this->isSupplier($selected);
return [
'view' => 'business.pages.supplier-reconciliation.supplier-data',
'freightPanel' => $freightPanel,
'courierOnly' => $courierOnly,
'freightTemplateUrl' => route('business.supplier-reconciliation.freight-bill.template'),
'freightUploadUrl' => route('business.supplier-reconciliation.freight-bill.upload'),
'supplierNames' => $supplierNames,
'supplierQuery' => $supplierQuery,
'supplierNotFound' => $supplierNotFound,
@ -374,6 +386,16 @@ class SupplierReconciliationPageData
] + $this->vendorPeriodContext();
}
private function isSupplier(string $name): bool
{
try {
return app(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class)->suppliersByNames([$name]) !== [];
} catch (\Throwable) {
// 供应商主档镜像暂时读不到:名字已经对上快递分组、又没有货款对账单,按快递处理
return false;
}
}
/**
* 厂家门户只读取当前登录联系人绑定的供应商数据。
*

View File

@ -0,0 +1,72 @@
@php
$fp = $freightPanel;
$kinds = [];
if ($fp['factory'] !== null) { $kinds['dropship'] = '代发运费账单'; }
if ($fp['groups'] !== []) { $kinds['courier'] = '快递账单'; }
$defaultMonth = $accountingMonthKey ?? now()->startOfMonth()->subMonth()->format('Y-m');
@endphp
<style>
.fb-panel { margin: 12px 0; padding: 16px; border: 1px solid #d8d2c7; border-radius: 12px; background: #fff; }
.fb-panel h3 { margin: 0 0 4px; font-size: 14px; font-weight: 600; }
.fb-panel p { margin: 0 0 10px; color: #595959; font-size: 12px; line-height: 1.6; }
.fb-form { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-end; }
.fb-form label { display: grid; gap: 4px; font-size: 12px; color: #5c5548; }
.fb-form select, .fb-form input[type=month], .fb-form input[type=file] { min-height: 34px; padding: 4px 8px; border: 1px solid #d8d2c7; border-radius: 8px; background: #fff; }
.fb-btn { display: inline-flex; align-items: center; min-height: 34px; padding: 0 14px; border: 1px solid #d8d2c7; border-radius: 8px; background: #fff; color: #24211c; font-size: 13px; font-weight: 600; text-decoration: none; cursor: pointer; }
.fb-btn.is-primary { border-color: #856632; background: #856632; color: #fff; }
.fb-alert { margin: 0 0 10px; padding: 9px 12px; border-radius: 8px; font-size: 13px; border: 1px solid #b8d8bc; background: #eef8ef; color: #285f31; }
.fb-alert.is-error { border-color: #e2b7b2; background: #fff2f0; color: #8c2f26; }
.fb-table { width: 100%; margin-top: 12px; border-collapse: collapse; font-size: 12px; }
.fb-table th, .fb-table td { padding: 6px 8px; border-bottom: 1px solid #f0ece4; text-align: left; }
.fb-table th { background: #f7f0de; color: #5b5343; }
.fb-table .num { text-align: right; font-variant-numeric: tabular-nums; }
</style>
<section class="fb-panel" aria-label="上传运费账单">
<h3>上传运费账单</h3>
<p>
请先下载上传模板,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」;
单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。
同一个月可以分几次上传。上传后由后台校验和读入,刷新本页可查看结果;读入成功后进入财务核对。每份最多50MB、100,000行。
</p>
@if (session('success'))
<div class="fb-alert" role="status">{{ session('success') }}</div>
@endif
@if ($errors->any())
<div class="fb-alert is-error" role="alert">{{ $errors->first() }}</div>
@endif
<form method="POST" action="{{ $freightUploadUrl }}" enctype="multipart/form-data" class="fb-form">
@csrf
<input type="hidden" name="supplier" value="{{ $name }}">
<label>账单类型
<select name="kind" required>
@foreach ($kinds as $key => $label)<option value="{{ $key }}">{{ $label }}</option>@endforeach
</select>
</label>
@if (count($fp['groups']) > 1)
<label>哪一个快递
<select name="group">
@foreach ($fp['groups'] as $g)<option value="{{ $g->id }}">{{ $g->name }}</option>@endforeach
</select>
</label>
@endif
<label>账单月份<input type="month" name="month" value="{{ $defaultMonth }}" required></label>
<label>账单文件<input type="file" name="import" accept=".xlsx,.xls,.csv" required></label>
<button type="submit" class="fb-btn is-primary">上传</button>
<a class="fb-btn" href="{{ $freightTemplateUrl }}">下载上传模板</a>
</form>
@if ($fp['files'] !== [])
<table class="fb-table">
<thead><tr><th>类型</th><th>月份</th><th>文件</th><th class="num">行数</th><th class="num">运费合计</th><th>状态</th><th>上传时间</th></tr></thead>
<tbody>
@foreach ($fp['files'] as $f)
<tr>
<td>{{ $f['kind'] }}</td><td>{{ $f['month'] }}</td><td>{{ $f['name'] }}</td>
<td class="num">{{ in_array($f['status'], ['queued','running','failed'], true) ? '—' : number_format($f['count']) }}</td><td class="num">{{ in_array($f['status'], ['queued','running','failed'], true) ? '—' : number_format($f['amount'], 2) }}</td>
<td>{{ ['parsed'=>'已读入','queued'=>'等待处理','running'=>'正在校验读入'][$f['status']] ?? ($f['status'] === 'failed' ? '失败:' . $f['message'] : '待财务处理') }}</td>
<td>{{ substr($f['at'], 0, 16) }}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
</section>

View File

@ -270,7 +270,7 @@
<div class="sr-selector-shell">
@if ($supplierLocked)
<div class="sr-selector-current">
<span>当前厂家(由钉钉组织自动确定)</span>
<span>{{ ($courierOnly ?? false) ? '当前快递(由钉钉组织自动确定)' : '当前厂家(由钉钉组织自动确定)' }}</span>
<strong>{{ $selectedSupplier }}</strong>
@if (($supplierCount ?? 1) > 1)
<a class="sr-selector-button" href="{{ route('business.pages.show', ['section' => $section['slug'], 'page' => $page['slug']]) }}">切换厂家</a>
@ -306,6 +306,11 @@
@endif
</div>
@if (! empty($freightPanel) && ($freightPanel['factory'] !== null || $freightPanel['groups'] !== []))
@include('business.pages.supplier-reconciliation._freight-bills', ['name' => $selectedSupplier])
@endif
@unless ($courierOnly ?? false)
@include('portal.supplier-reconciliation.workspace', [
'supplier' => $selectedSupplier,
'workspaceIndexUrl' => route('business.pages.show', [
@ -318,5 +323,6 @@
]),
'workspaceFilterSupplier' => $selectedSupplier,
])
@endunless
@endif
</div>

View File

@ -586,6 +586,15 @@ Route::get('workspace/supplier-portal', [\App\Http\Controllers\Business\Supplier
->middleware('business.page:supplier-reconciliation,supplier-data')
->name('business.supplier-portal.home');
// 厂家门户:代发厂家 / 快递按统一模板上传运费账单
Route::get('workspace/supplier-reconciliation/freight-bill-template', [\App\Http\Controllers\Business\PortalFreightBillController::class, 'template'])
->middleware('business.page:supplier-reconciliation,supplier-data')
->name('business.supplier-reconciliation.freight-bill.template');
Route::post('workspace/supplier-reconciliation/freight-bill', [\App\Http\Controllers\Business\PortalFreightBillController::class, 'upload'])
->middleware(['business.page:supplier-reconciliation,supplier-data', 'throttle:import-upload'])
->name('business.supplier-reconciliation.freight-bill.upload');
Route::get('workspace/supplier-reconciliation/statement-template', [SupplierReconciliationActions::class, 'template'])
->middleware('business.page:supplier-reconciliation,supplier-data')
->name('business.supplier-reconciliation.template');

View File

@ -0,0 +1,222 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\DingTalkIdentity;
use App\Models\Auth\Permission;
use App\Models\Auth\Role;
use App\Models\Auth\SupplierPortalIdentity;
use App\Models\Auth\SupplierPortalSupplier;
use App\Models\Auth\User;
use App\Services\Auth\SupplierPortalAccess;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBills;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use RuntimeException;
use Tests\Feature\FeatureTestCase;
final class PortalFreightBillTest extends FeatureTestCase
{
private const H = ['单号', '省', '重量', '运费', '送货备注', '面单', '费率'];
public function test_template_is_strict_about_headers_and_required_columns(): void
{
$t = new FreightBillTemplate(new BillWorkbookReader());
$ok = $t->validate($this->xlsx([self::H, ['773444000001', '江苏', 3.2, 8, null, 1, 2.1], ['773444000002', null, null, '6.5'], ['合计', null, null, 14.5]]), 'xlsx');
$this->assertSame(['rows' => 2, 'waybills' => 2, 'amount' => 14.5], $ok);
foreach ([
[[['快递单号', '运费'], ['1', 2]], '第一行必须依次是'],
[[self::H, ['773444000001', '江苏', 3, null]], '第 2 行运费没填'],
[[self::H, [null, '江苏', 3, 5]], '第 2 行没有单号'],
[[self::H, ['773444000001', '江苏', '三公斤', 5]], '重量「三公斤」不是数字'],
[[self::H, ['7.9E+13', '江苏', 3, 5]], '单号格式不对'],
[[self::H], '还没有填账单明细'],
] as [$rows, $message]) {
try {
$t->validate($this->xlsx($rows), 'xlsx');
$this->fail('应当拒收:' . $message);
} catch (RuntimeException $e) {
$this->assertStringContainsString($message, $e->getMessage());
}
}
}
public function test_dropship_factory_and_courier_upload_their_own_bills_in_the_supplier_portal(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$db = CourierBillMatcher::db();
$db->table('dropship_factories')->insert(['name' => '临沂卿德客', 'warehouse' => '工厂-山东卿德客代发仓', 'keywords' => '卿德客',
'created_at' => now(), 'updated_at' => now()]);
$db->table('courier_bill_groups')->insert(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE),
'summary_carrier' => '曹县韵达', 'created_at' => now(), 'updated_at' => now()]);
$this->assertSame(['曹县韵达'], PortalFreightBills::courierNames(['曹县韵达', '财务中心', '临沂卿德客']));
\Illuminate\Support\Facades\URL::defaults(['company_id' => $this->company->id]);
$page = route('business.pages.show', ['section' => 'supplier-reconciliation', 'page' => 'supplier-data']);
$upload = route('business.supplier-reconciliation.freight-bill.upload');
$file = fn (array $rows, string $name = '账单.xlsx') => new UploadedFile($this->xlsx($rows), $name, null, null, true);
// 代发厂家:厂家门户里多了「上传运费账单」,传代发运费账单
$factoryUser = $this->portalUser('临沂卿德客');
$this->actingAsPortal($factoryUser)->get($page)->assertOk()->assertSeeText('上传运费账单')->assertSeeText('代发运费账单');
$this->get(route('business.supplier-reconciliation.freight-bill.template'))->assertOk();
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([['快递单号', '运费'], ['773444000001', 8]])])
->assertSessionHas('success');
$imports = app(PortalFreightBillImports::class);
$this->assertSame(0, $db->table('dropship_bill_files')->count());
$this->assertTrue($imports->processNext());
$this->get($page)->assertOk()->assertSeeText('第一行必须依次是');
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['773444000001', '江苏', 3, 8], ['773444000002', '', '', 6]])])
->assertSessionHas('success');
$this->assertTrue($imports->processNext());
$f = $db->table('dropship_bill_files')->sole();
$this->assertSame('parsed', $f->status);
$this->assertSame(2, (int) $f->waybill_count);
$this->assertEquals(14, (float) $f->amount);
$this->assertStringContainsString('(门户)', (string) $f->uploaded_by);
// 不能替别的厂家传
$this->post($upload, ['kind' => 'dropship', 'supplier' => '别家', 'month' => '2026-11', 'import' => $file([self::H, ['1', '', '', 1]])])
->assertForbidden();
// 快递:钉钉部门名是承运商名,只看得到上传快递账单,看不到货款对账
$courierUser = $this->portalUser('曹县韵达');
$this->actingAsPortal($courierUser)->get($page)->assertOk()->assertSeeText('快递账单')->assertSeeText('当前快递')
->assertDontSeeText('代发运费账单');
$this->post($upload, ['kind' => 'courier', 'month' => '2026-11', 'import' => $file([self::H, ['YD0001', '山东', 1.2, 4.5, '送货上门', 1, 3]])])
->assertSessionHas('success');
$this->assertSame(0, $db->table('courier_bill_files')->count());
$this->assertTrue($imports->processNext());
$c = $db->table('courier_bill_files')->sole();
$this->assertSame('parsed', $c->status);
$this->assertEquals(4.5, (float) $c->amount);
$this->assertSame(1, $db->table('courier_bill_statements')->where('bill_month', '2026-11')->count());
// 快递账号传代发运费账单:不是代发厂家
$this->post($upload, ['kind' => 'dropship', 'month' => '2026-11', 'import' => $file([self::H, ['YD0002', '', '', 4]])])
->assertSessionHasErrors('freight_bill');
$this->assertFalse($imports->processNext());
}
public function test_queued_bill_is_rejected_if_binding_is_revoked_before_processing(): void
{
Storage::fake('local');
$this->company->makeCurrent(true);
$db = CourierBillMatcher::db();
$id = $db->table('dropship_factories')->insertGetId(['name' => '测试厂家', 'warehouse' => '测试仓', 'keywords' => '测试', 'created_at' => now(), 'updated_at' => now()]);
$user = $this->portalUser('测试厂家');
$imports = app(PortalFreightBillImports::class);
$imports->submit(new UploadedFile($this->xlsx([self::H, ['SF12345678', '', 1, 8]]), '账单.xlsx', null, null, true), [
'name' => '测试厂家', 'kind' => 'dropship', 'month' => '2026-11', 'target_id' => $id,
'user_id' => (int) $user->id, 'company_id' => (int) $this->company->id, 'uploader' => '测试',
]);
$user->update(['enabled' => false]);
$this->assertTrue($imports->processNext());
$this->assertSame(0, $db->table('dropship_bill_files')->count());
$this->assertSame('failed', $imports->recent((int) $this->company->id, '测试厂家')[0]['status']);
$this->assertSame([], $imports->recent((int) $this->company->id, '别家'));
$this->assertSame([], $imports->recent((int) $this->company->id + 1, '测试厂家'));
}
public function test_multiple_worksheets_are_not_partially_accepted(): void
{
$path = $this->xlsx([self::H, ['SF12345678', '', 1, 8]]);
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$book->createSheet()->fromArray([self::H, ['SF87654321', '', 1, 99]]);
(new Xlsx($book))->save($path);
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('只保留模板的一张账单工作表');
app(FreightBillTemplate::class)->validate($path, 'xlsx');
}
public function test_portal_filename_cannot_add_another_courier_group(): void
{
Storage::fake('local');
$db = CourierBillMatcher::db();
$a = $db->table('courier_bill_groups')->insertGetId(['name' => '本家快递', 'express_names' => '["本家快递"]', 'bundle' => '同一合并账单', 'waybill_header' => '旧单号列', 'amount_header' => '旧金额列', 'weight_header' => '旧重量列', 'created_at' => now(), 'updated_at' => now()]);
$b = $db->table('courier_bill_groups')->insertGetId(['name' => '另一家快递', 'express_names' => '["另一家快递"]', 'bundle' => '同一合并账单', 'created_at' => now(), 'updated_at' => now()]);
$db->table('jst_oms_shipping')->insert(['source_id' => 888001, 'sku_source_id' => 1, 'express_no' => 'SF12345678', 'express_name1' => '另一家快递', 'ship_time' => '2026-11-10']);
$file = new UploadedFile($this->xlsx([self::H, ['SF12345678', '江苏', 1, 8]]), '本家快递与另一家快递.xlsx', null, null, true);
$id = app(\App\Support\CourierBills\CourierBillStore::class)->uploadFor($file, '2026-11', $a, '测试');
$this->assertSame('parsed', $db->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $db->table('courier_bill_statements')->where('group_id', $b)->count());
$this->assertNull($db->table('courier_bill_files')->find($id)->extra_group_ids);
}
public function test_finance_can_choose_a_courier_without_supplier_statements(): void
{
$db = CourierBillMatcher::db();
$db->table('courier_bill_groups')->insert(['name' => '测试财务快递', 'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->get(route('business.pages.show', ['section' => 'supplier-reconciliation', 'page' => 'supplier-data', 'supplier' => '测试财务快递']))
->assertOk()->assertSeeText('上传运费账单')->assertSeeText('快递账单');
}
public function test_courier_department_in_dingtalk_resolves_to_a_portal_binding(): void
{
CourierBillMatcher::db()->table('courier_bill_groups')->insert(['name' => '曹县韵达小件', 'summary_carrier' => '曹县韵达',
'express_names' => '[]', 'created_at' => now(), 'updated_at' => now()]);
$query = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery::class);
$query->shouldReceive('select')->andReturnUsing(static fn (string $sql): array => str_contains($sql, 'hr_employee')
? [['userid' => 'ding-c', 'unionid' => 'union-c', 'active' => 1, 'dept_id_list' => '77']]
: [['Id' => 77, 'parent_id' => 70, 'name' => '曹县韵达', 'depth' => 0], ['Id' => 70, 'parent_id' => 1, 'name' => '快递', 'depth' => 1]]);
$factory = \Mockery::mock(\Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory::class);
$factory->shouldReceive('forSource')->andReturn($query);
$suppliers = \Mockery::mock(\Modules\EcommerceFinance\Repositories\SupplierManagementMirrorRepository::class);
$suppliers->shouldReceive('suppliersByNames')->andReturn([]);
$resolved = (new SupplierPortalAccess($factory, $suppliers))->resolveAll('ding-c', 'union-c');
$this->assertSame([['supplier_name' => '曹县韵达', 'supplier_code' => '', 'dingtalk_group_id' => 77, 'dingtalk_group_name' => '曹县韵达']], $resolved);
}
private function portalUser(string $name): User
{
$user = User::create(['name' => $name . '对账员', 'email' => Str::lower(Str::random(12)) . '@portal.test', 'password' => Str::random(32),
'locale' => 'zh-CN', 'enabled' => true, 'created_from' => SupplierPortalAccess::CREATED_FROM,
'landing_page' => 'business.supplier-portal.home', 'created_by' => 0]);
$user->roles()->attach(Role::where('name', 'user')->firstOrFail()->id);
$user->permissions()->attach(Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
$user->companies()->attach($this->company->id);
DingTalkIdentity::create(['user_id' => $user->id, 'union_id' => 'union-' . $user->id, 'dingtalk_user_id' => 'ding-' . $user->id]);
SupplierPortalIdentity::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null,
'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]);
SupplierPortalSupplier::create(['company_id' => $this->company->id, 'user_id' => $user->id, 'supplier_code' => null,
'supplier_name' => $name, 'dingtalk_group_id' => 1, 'dingtalk_group_name' => $name, 'last_verified_at' => now()]);
return $user;
}
private function actingAsPortal(User $user): self
{
$identity = DingTalkIdentity::query()->where('user_id', $user->id)->firstOrFail();
return $this->withExceptionHandling()->loginAs($user)->withSession(['dingtalk_identity_id' => $identity->id, 'dingtalk_roster_checked_at' => now()->timestamp]);
}
/** @param list<list<mixed>> $rows */
private function xlsx(array $rows): string
{
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
if ($value !== null && $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(), 'pfb_') . '.xlsx';
(new Xlsx($book))->save($path);
return $path;
}
}

View File

@ -7,6 +7,26 @@ use Symfony\Component\Process\Process;
class FinanceBatchIsolationTest extends TestCase
{
public function test_portal_import_uses_registered_batch_and_skips_an_empty_queue(): void
{
$directory = sys_get_temp_dir() . '/caiwu-portal-import-' . bin2hex(random_bytes(6));
mkdir($directory . '/storage/app/private/portal-freight-bills/pending', 0777, true);
file_put_contents($directory . '/run-finance-import.py', '');
file_put_contents($directory . '/python3', '#!/bin/sh' . "\n" . 'printf "%s\n" "$@" > "$CAIWU_CAPTURE"' . "\n");
chmod($directory . '/python3', 0700);
try {
$this->assertTrue($this->runBatch($directory, ['portal-freight:import-pending'])->isSuccessful());
$this->assertFileDoesNotExist($directory . '/called');
file_put_contents($directory . '/storage/app/private/portal-freight-bills/pending/test', '');
$result = $this->runBatch($directory, ['portal-freight:import-pending']);
$this->assertTrue($result->isSuccessful(), $result->getErrorOutput());
$this->assertStringContainsString('run-finance-import.py', file_get_contents($directory . '/called'));
$this->assertContains('portal-freight:import-pending', json_decode(file_get_contents(dirname(__DIR__, 3) . '/deploy/finance-batch-imports.json'), true));
} finally {
(new \Illuminate\Filesystem\Filesystem())->deleteDirectory($directory);
}
}
public function test_busy_sync_lock_prevents_starting_a_second_heavy_job(): void
{
$directory = sys_get_temp_dir() . '/caiwu-batch-' . bin2hex(random_bytes(6));