CaiWuXiTong/app/Http/Controllers/Business/DropshipFreightController.php

256 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use RuntimeException;
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
final class DropshipFreightController extends Controller
{
public const PAGE = 'dropship-freight-reconciliation';
public const VIEWS = ['overview' => '各厂家汇总', 'factory' => '单家明细', 'upload' => '上传厂家账单', 'factories' => '代发厂家设置'];
public function __construct(
private readonly DropshipFreightStore $store,
private readonly DropshipReconciler $reconciler,
) {}
public function page(Request $request): array
{
$view = array_key_exists((string) $request->query('df_view'), self::VIEWS) ? (string) $request->query('df_view') : 'overview';
$data = ['view' => 'business.pages.courier-payables.dropship-freight.page', 'dfView' => $view, 'dfViews' => self::VIEWS,
'dfSection' => CourierBillController::section($request), 'dfUnavailable' => false];
try {
$months = $this->store->db()->table('dropship_bill_files')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
$data += ['dfMonth' => $month, 'dfFactories' => $this->store->factories()];
$data += match ($view) {
'factory' => $this->factoryData($request, $month),
'upload' => $this->uploadData($month),
'factories' => [],
default => $this->overviewData($month),
};
} catch (QueryException $error) {
report($error);
$data['dfUnavailable'] = true;
}
return $data;
}
private function overviewData(string $month): array
{
$billed = $this->store->db()->table('dropship_bill_lines')->where('bill_month', $month)->distinct()->pluck('factory_id')
->map(static fn ($id): int => (int) $id)->all();
$own = $this->store->ownExpressNames();
$rows = [];
$without = [];
foreach ($this->store->factories() as $factory) {
if (in_array((int) $factory->id, $billed, true)) {
$rows[] = $this->reconciler->factoryMonth($factory, $month, $own)['summary'];
} else {
$without[] = $factory->name;
}
}
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfTotals' => [
'bill' => array_sum(array_column($rows, 'bill')), 'settle' => array_sum(array_column($rows, 'settle')),
'diff' => array_sum(array_column($rows, 'diff')), 'attention' => array_sum(array_column($rows, 'attention')),
]];
}
private function factoryData(Request $request, string $month): array
{
$factory = collect($this->store->factories())->firstWhere('id', (int) $request->query('factory'));
if ($factory === null) {
return ['dfFactory' => null];
}
$result = $this->reconciler->factoryMonth($factory, $month);
$status = (string) $request->query('status', '');
$rows = $result['rows'];
if ($status === 'attention') {
$rows = array_values(array_filter($rows, static fn (array $r): bool => in_array($r['status'], DropshipReconciler::ATTENTION, true)));
} elseif (array_key_exists($status, DropshipReconciler::LABELS)) {
$rows = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] === $status));
}
$page = max(1, (int) $request->query('page', 1));
$paginator = new LengthAwarePaginator(array_slice($rows, ($page - 1) * 100, 100), count($rows), 100, $page,
['path' => $request->url(), 'query' => $request->query()]);
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)->orderBy('id')->get();
return ['dfFactory' => $factory, 'dfSummary' => $result['summary'], 'dfLines' => $paginator, 'dfStatus' => $status, 'dfFiles' => $files];
}
private function uploadData(string $month): array
{
$files = $this->store->db()->table('dropship_bill_files as f')->leftJoin('dropship_factories as d', 'd.id', '=', 'f.factory_id')
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'd.name as factory_name']);
return ['dfFiles' => $files];
}
public function upload(Request $request)
{
$data = $request->validate([
'month' => ['required', 'date_format:Y-m'],
'files' => ['required', 'array', 'max:80'], 'files.*' => ['file', 'max:51200'],
], [], ['files' => '厂家账单', 'files.*' => '厂家账单']);
foreach ($data['files'] as $file) {
if (! in_array(strtolower($file->getClientOriginalExtension()), DropshipFreightStore::EXTENSIONS, true)) {
throw ValidationException::withMessages(['dropship' => '只支持 xlsx、xls、csv、zip:' . $file->getClientOriginalName()]);
}
}
$ids = $this->guard(fn () => $this->store->upload($data['files'], $data['month'], self::user()));
$files = $this->store->db()->table('dropship_bill_files')->whereIn('id', $ids)->get();
return $this->back($request, ['df_view' => 'upload', 'month' => $data['month']], '已上传 ' . count($ids) . ' 个文件:已读入 '
. $files->where('status', 'parsed')->count() . ' 个,待选厂家 ' . $files->where('status', 'pending_factory')->count()
. ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个。');
}
public function assign(Request $request, int $file)
{
$data = $request->validate(['factory_id' => ['required', 'integer']]);
$this->guard(fn () => $this->store->assign($file, (int) $data['factory_id']));
return $this->back($request, [], '已读入。');
}
public function deleteFile(Request $request, int $file)
{
$this->guard(fn () => $this->store->deleteFile($file));
return $this->back($request, [], '已删除文件。');
}
public function saveFactory(Request $request)
{
$data = $request->validate([
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'warehouse' => ['required', 'string', 'max:128'],
'keywords' => ['required', 'string', 'max:255'], 'note' => ['nullable', 'string', 'max:255'],
], [], ['name' => '厂家', 'warehouse' => '代发仓', 'keywords' => '代发快递关键字']);
$this->guard(fn () => $this->store->saveFactory(isset($data['id']) ? (int) $data['id'] : null, $data));
return $this->back($request, ['df_view' => 'factories'], '已保存厂家「' . trim($data['name']) . '」。');
}
public function deleteFactory(Request $request, int $factory)
{
$this->guard(fn () => $this->store->deleteFactory($factory));
return $this->back($request, ['df_view' => 'factories'], '已删除厂家。');
}
public function generate(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m']]);
$result = $this->guard(fn () => $this->store->generate($data['month']));
return $this->back($request, ['df_view' => 'factories'], '按 ' . $data['month'] . ' 发货数据新增 ' . count($result['created']) . ' 家'
. ($result['created'] !== [] ? ':' . implode('、', $result['created']) : '')
. ($result['skipped'] !== [] ? '。没加的代发仓:' . implode('、', $result['skipped']) : '') . '。请逐家核对关键字。');
}
public function export(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
$month = $data['month'];
$factories = collect($this->store->factories());
if (! empty($data['factory'])) {
$factories = $factories->where('id', (int) $data['factory'])->values();
abort_if($factories->isEmpty(), 404);
} else {
$billed = $this->store->db()->table('dropship_bill_lines')->where('bill_month', $month)->distinct()->pluck('factory_id')->map('intval')->all();
$factories = $factories->filter(fn ($f) => in_array((int) $f->id, $billed, true))->values();
}
if (! empty($data['factory'])) {
// 单家:和快递账单对账的导出一样,以厂家原始账单为底,后面接汇总、对账(厂家原始列 + 发货数据)和各分类
$factory = $factories->first();
$name = str_replace(['/', '\\'], '-', (string) $factory->name) . '_' . $month . '_代发运费对账(内部版).xlsx';
$path = tempnam(sys_get_temp_dir(), 'dropship_download_');
if ($path === false) {
throw new RuntimeException('无法创建导出文件。');
}
$output = fopen($path, 'wb');
try {
$this->guard(fn () => app(DropshipExporter::class)->export($factory, $month, $output));
} catch (\Throwable $error) {
fclose($output);
@unlink($path);
throw $error;
} finally {
if (is_resource($output)) {
fclose($output);
}
}
return response()->download($path, $name)->deleteFileAfterSend(true);
}
$own = $this->store->ownExpressNames();
$name = '代发厂家' . $month . '代发运费对账.xlsx';
return response()->streamDownload(function () use ($factories, $month, $own): void {
$book = new StreamingWorkbook();
$book->row('汇总', ['厂家', '代发仓', '代发快递关键字', '账单月份', '厂家开运费单数', '厂家运费合计', '结算运费(按我方核算)',
'差额(厂家−结算)', ...array_values(DropshipReconciler::LABELS)], true);
$details = [];
foreach ($factories as $factory) {
$result = $this->reconciler->factoryMonth($factory, $month, $own);
$s = $result['summary'];
$book->row('汇总', [$s['factory'], $s['warehouse'], $s['keywords'], $month, $s['billed'], $s['bill'], $s['settle'], $s['diff'],
...array_values($s['counts'])]);
$details[] = [$factory, $result['rows']];
}
foreach ($details as [$factory, $rows]) {
$sheet = $factories->count() === 1 ? '明细' : mb_substr((string) $factory->name, 0, 28);
$book->row($sheet, ['快递单号', '发货时间', '快递名称1', '仓库', '厂家运费', '我方核算运费', '结算运费', '差额(厂家−我方)', '状态', '说明', '核算公式'], true);
foreach ($rows as $r) {
$book->row($sheet, [$r['waybill'], $r['ship_time'], $r['express'], $r['warehouse'], $r['bill'], $r['calc'], $r['settle'],
$r['diff'], $r['label'], $r['note'], $r['formula']]);
}
}
$book->writeTo(fopen('php://output', 'wb'));
}, $name);
}
/** @template T @param callable():T $action @return T */
private function guard(callable $action): mixed
{
try {
return $action();
} catch (RuntimeException $error) {
throw ValidationException::withMessages(['dropship' => $error->getMessage()]);
}
}
private function back(Request $request, array $query, string $message)
{
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => CourierBillController::section($request),
'page' => self::PAGE, ...$query]);
return redirect()->to($target)->with('dropship_message', $message);
}
private static function monthParam(mixed $value): ?string
{
return is_string($value) && preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $value) ? $value : null;
}
private static function user(): string
{
$user = user();
return (string) ($user?->name ?? $user?->email ?? 'system');
}
}