fix: 隔离门户账单导入并严格校验授权与模板

This commit is contained in:
limeng 2026-12-02 20:00:53 +08:00
parent 08d06ab918
commit a9f34b93cf
13 changed files with 275 additions and 57 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

@ -3,18 +3,14 @@
namespace App\Http\Controllers\Business;
use App\Services\Auth\SupplierPortalAccess;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\FreightBillTemplate;
use App\Support\CourierBills\PortalFreightBills;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\CourierBills\PortalFreightBillImports;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Throwable;
/**
* 厂家门户(钉钉登录的供应商对账入口)上传运费账单:代发厂家传代发运费账单,快递传快递账单,统一模板、严格校验。
@ -52,48 +48,22 @@ final class PortalFreightBillController extends Controller
throw ValidationException::withMessages(['freight_bill' => '只支持 xlsx、xls、csv,请用上传模板。']);
}
$name = $this->effectiveName($request);
$original = (string) $file->getClientOriginalName();
try {
$summary = $this->template->validate((string) $file->getRealPath(), $extension);
} catch (RuntimeException $error) {
throw ValidationException::withMessages(['freight_bill' => $error->getMessage()]);
}
$uploader = mb_substr((string) ($request->user()?->name ?: $request->user()?->email ?: '厂家门户') . '(门户)', 0, 64);
if ($data['kind'] === 'dropship') {
$factory = $this->portal->factory($name);
if ($factory === null) {
throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在代发厂家里,请联系财务。']);
}
$id = app(DropshipFreightStore::class)->uploadFor($original, (string) $file->getRealPath(), $data['month'], (int) $factory->id, $uploader);
$row = app(DropshipFreightStore::class)->db()->table('dropship_bill_files')->find($id);
$target = $this->portal->factory($name);
} else {
$groups = $this->portal->groups($name);
if ($groups === []) {
throw ValidationException::withMessages(['freight_bill' => '「' . $name . '」不在快递账单对账分组里,请联系财务。']);
}
$group = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0));
if ($group === null) {
throw ValidationException::withMessages(['freight_bill' => '请选择是哪一个快递的账单。']);
}
$ids = app(CourierBillStore::class)->upload([$file], $data['month'], [(int) $group->id], $uploader);
$row = app(CourierBillStore::class)->db()->table('courier_bill_files')->find($ids[0] ?? 0);
$target = count($groups) === 1 ? $groups[0] : collect($groups)->firstWhere('id', (int) ($data['group'] ?? 0));
}
if ($row === null || $row->status !== 'parsed') {
throw ValidationException::withMessages(['freight_bill' => '文件已收到,但没有读入:' . ($row->message ?? '未知原因') . '。请联系财务。']);
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),
]);
$message = '已上传' . self::KINDS[$data['kind']] . ':' . $name . ' ' . $data['month'] . ',' . number_format($summary['rows']) . ' 行,运费合计 '
. number_format($summary['amount'], 2) . ' 元,已进入财务核对';
try {
if (app(SupplierDingTalkNotifier::class)->sendFreightBillUploadReceipt($name, self::KINDS[$data['kind']], $data['month'], $original, $summary)) {
$message .= ';上传回执已发到钉钉群';
}
} catch (Throwable $error) {
report($error);
}
return back()->with('success', $message . '。');
return back()->with('success', '文件已收到,正在等待校验和读入。处理结果请在下方上传记录查看。');
}
/** 厂家/快递账号只能是钉钉组织绑定的那几家;财务账号按页面上选的那家。 */

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('这家快递本月对账单已确认结算,先撤销确认再上传。');
}
@ -550,7 +560,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

@ -43,6 +43,9 @@ final class FreightBillTemplate
if ($rows === null) {
throw new RuntimeException('文件是空的。');
}
if (\App\Support\DropshipFreight\FactoryBillParser::skipWord((string) $sheets->key()) !== null) {
throw new RuntimeException('请保留模板的「账单」工作表名称,不要改成汇总、对账或报价等名称。');
}
$errors = [];
$header = null;
$count = 0;
@ -69,13 +72,16 @@ final class FreightBillTemplate
}
if ($waybill === '') {
$errors[] = '第 ' . $line . ' 行没有单号';
} elseif (Waybill::normalize($waybill) === null) {
$errors[] = '第 ' . $line . ' 行单号格式不对,请使用完整单号文本';
}
$freight = BillParser::number($cells[3] ?? null);
if ($freight === null) {
if ($freight === null || ! is_finite($freight)) {
$errors[] = '第 ' . $line . ' 行运费' . (($cells[3] ?? '') === '' ? '没填' : '「' . $cells[3] . '」不是数字');
}
foreach ([2 => '重量', 5 => '面单', 6 => '费率'] as $col => $name) {
if (($cells[$col] ?? '') !== '' && BillParser::number($cells[$col]) === null) {
$value = BillParser::number($cells[$col] ?? null);
if (($cells[$col] ?? '') !== '' && ($value === null || ! is_finite($value))) {
$errors[] = '第 ' . $line . ' 行' . $name . '「' . $cells[$col] . '」不是数字';
}
}
@ -83,6 +89,7 @@ final class FreightBillTemplate
break;
}
$count++;
if ($count > 100000) throw new RuntimeException('每份账单最多100,000行,请分批上传。');
$amount += (float) $freight;
$waybills[$waybill] = true;
}
@ -96,6 +103,8 @@ final class FreightBillTemplate
if ($count === 0) {
throw new RuntimeException('模板里还没有填账单明细。');
}
$sheets->next();
if ($sheets->valid()) throw new RuntimeException('请只保留模板的一张账单工作表,不要附带其他工作表。');
return ['rows' => $count, 'waybills' => count($waybills), 'amount' => round($amount, 2)];
}

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

@ -66,7 +66,7 @@ final class PortalFreightBills
{
$factory = $this->factory($name);
$groups = $this->groups($name);
$files = [];
$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)

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

@ -3,7 +3,7 @@
$kinds = [];
if ($fp['factory'] !== null) { $kinds['dropship'] = '代发运费账单'; }
if ($fp['groups'] !== []) { $kinds['courier'] = '快递账单'; }
$defaultMonth = $accountingMonthKey ?? now()->subMonth()->format('Y-m');
$defaultMonth = $accountingMonthKey ?? now()->startOfMonth()->subMonth()->format('Y-m');
@endphp
<style>
.fb-panel { margin: 12px 0; padding: 14px 16px; border: 1px solid #ded7c9; border-radius: 10px; background: #fff; }
@ -26,10 +26,10 @@
<p>
请先下载上传模板,按模板填好再上传:第一行表头不要改,依次是「{{ implode('、', \App\Support\CourierBills\FreightBillTemplate::HEADERS) }}」;
单号、运费必填,重量、面单、费率填数字,省、送货备注可空。不按模板的文件会被退回并提示哪里要改。
同一个月可以分几次上传,上传后进入财务核对。
同一个月可以分几次上传。上传后由后台校验和读入,刷新本页可查看结果;读入成功后进入财务核对。每份最多50MB、100,000行。
</p>
@if ($errors->has('freight_bill'))
<div class="fb-alert is-error" role="alert">{{ $errors->first('freight_bill') }}</div>
@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
@ -58,8 +58,8 @@
@foreach ($fp['files'] as $f)
<tr>
<td>{{ $f['kind'] }}</td><td>{{ $f['month'] }}</td><td>{{ $f['name'] }}</td>
<td class="num">{{ number_format($f['count']) }}</td><td class="num">{{ number_format($f['amount'], 2) }}</td>
<td>{{ $f['status'] === 'parsed' ? '已读入' : ($f['status'] === 'failed' ? '失败:' . $f['message'] : '待财务处理') }}</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

View File

@ -13,6 +13,7 @@ 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;
@ -36,6 +37,7 @@ final class PortalFreightBillTest extends FeatureTestCase
[[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 {
@ -68,9 +70,14 @@ final class PortalFreightBillTest extends FeatureTestCase
$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]])])
->assertSessionHasErrors('freight_bill');
->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);
@ -86,6 +93,8 @@ final class PortalFreightBillTest extends FeatureTestCase
->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);
@ -93,6 +102,52 @@ final class PortalFreightBillTest extends FeatureTestCase
// 快递账号传代发运费账单:不是代发厂家
$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' => '同一合并账单', '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_courier_department_in_dingtalk_resolves_to_a_portal_binding(): void

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));