396 lines
22 KiB
PHP
396 lines
22 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Controllers\Business;
|
||
|
||
use App\Support\CourierBills\Category;
|
||
use App\Support\CourierBills\CourierBillMatcher;
|
||
use App\Support\CourierBills\CourierBillStore;
|
||
use App\Support\CourierBills\StatementExporter;
|
||
use App\Support\CourierBills\StreamingWorkbook;
|
||
use App\Support\CourierBills\Waybill;
|
||
use Illuminate\Database\QueryException;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Routing\Controller;
|
||
use Illuminate\Validation\Rule;
|
||
use Illuminate\Validation\ValidationException;
|
||
use RuntimeException;
|
||
|
||
/** 快递账单对账(第一期:运费):对账总览 / 单家对账单 / 对账明细 / 上传账单 / 结算台账 / 对账分组。 */
|
||
final class CourierBillController extends Controller
|
||
{
|
||
public const VIEWS = ['overview' => '对账总览', 'statement' => '单家对账单', 'details' => '对账明细', 'upload' => '上传账单',
|
||
'ledger' => '结算台账', 'groups' => '对账分组'];
|
||
|
||
public function __construct(
|
||
private readonly CourierBillStore $store,
|
||
private readonly CourierBillMatcher $matcher,
|
||
) {}
|
||
|
||
public function page(Request $request): array
|
||
{
|
||
$view = array_key_exists((string) $request->query('cb_view'), self::VIEWS) ? (string) $request->query('cb_view') : 'overview';
|
||
$data = ['view' => 'business.pages.courier-payables.courier-bills.page', 'cbView' => $view, 'cbViews' => self::VIEWS,
|
||
'cbSection' => self::section($request), 'cbUnavailable' => false];
|
||
try {
|
||
$db = $this->store->db();
|
||
$months = $db->table('courier_bill_statements')->distinct()->orderByDesc('bill_month')->pluck('bill_month')->all();
|
||
$month = self::monthParam($request->query('month')) ?? ($months[0] ?? now()->subMonth()->format('Y-m'));
|
||
$data += ['cbMonth' => $month, 'cbMonths' => array_values(array_unique([...$months, $month])), 'cbGroups' => $this->store->groups()];
|
||
$data += match ($view) {
|
||
'statement' => $this->statementData($request),
|
||
'details' => $this->detailsData($request, $month),
|
||
'upload' => $this->uploadData($month),
|
||
'ledger' => $this->ledgerData($request),
|
||
'groups' => [],
|
||
default => $this->overviewData($month),
|
||
};
|
||
} catch (QueryException $error) {
|
||
report($error);
|
||
$data['cbUnavailable'] = true;
|
||
}
|
||
|
||
return $data;
|
||
}
|
||
|
||
private function overviewData(string $month): array
|
||
{
|
||
$db = $this->store->db();
|
||
$statements = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||
->where('s.bill_month', $month)->orderBy('g.owner')->orderBy('g.name')
|
||
->get(['s.*', 'g.name as group_name', 'g.owner', 'g.summary_carrier']);
|
||
$sums = $db->table('courier_bill_summary_items')->whereIn('statement_id', $statements->pluck('id'))
|
||
->groupBy('statement_id')->selectRaw('statement_id, SUM(bill_amount) as bill, SUM(self_amount) as self')
|
||
->get()->keyBy('statement_id');
|
||
$pending = $db->table('courier_bill_lines')->whereIn('statement_id', $statements->pluck('id'))
|
||
->whereNull('resolution')->whereNotIn('category', [Category::MATCH])
|
||
->groupBy('statement_id')->selectRaw('statement_id, COUNT(*) as n')->pluck('n', 'statement_id');
|
||
$rows = $statements->map(function ($s) use ($sums, $pending): array {
|
||
$bill = (float) ($sums[$s->id]->bill ?? 0);
|
||
$self = (float) ($sums[$s->id]->self ?? 0);
|
||
|
||
return ['id' => $s->id, 'group' => $s->group_name, 'owner' => $s->owner, 'carrier' => $s->summary_carrier ?: $s->group_name,
|
||
'status' => $s->status, 'lines' => (int) $s->line_count, 'bill' => $bill, 'diff' => round($bill - $self, 2),
|
||
'confirmed' => $self, 'pending' => (int) ($pending[$s->id] ?? 0), 'matched_at' => $s->matched_at];
|
||
})->all();
|
||
$without = collect($this->store->groups())->reject(fn ($g) => $statements->contains('group_id', $g->id))->values()->all();
|
||
|
||
return ['cbRows' => $rows, 'cbWithout' => $without, 'cbTotals' => [
|
||
'count' => count($rows), 'bill' => array_sum(array_column($rows, 'bill')), 'diff' => array_sum(array_column($rows, 'diff')),
|
||
'confirmed' => count(array_filter($rows, fn ($r) => $r['status'] === 'confirmed')),
|
||
]];
|
||
}
|
||
|
||
private function statementData(Request $request): array
|
||
{
|
||
$db = $this->store->db();
|
||
$statement = $db->table('courier_bill_statements')->find((int) $request->query('statement'));
|
||
if ($statement === null) {
|
||
return ['cbStatement' => null];
|
||
}
|
||
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||
$counts = $db->table('courier_bill_lines')->where('statement_id', $statement->id)
|
||
->groupBy('category', 'category_month')->selectRaw('category, category_month, COUNT(*) as n, SUM(bill_amount) as bill')
|
||
->get();
|
||
$tabs = [];
|
||
foreach ($counts as $row) {
|
||
$key = in_array($row->category, [Category::PRIOR, Category::LATER], true) ? $row->category . ':' . $row->category_month : (string) $row->category;
|
||
$tabs[$key] = ['label' => Category::label((string) $row->category, $row->category_month), 'count' => (int) $row->n];
|
||
}
|
||
uksort($tabs, fn ($a, $b) => array_search(strtok($a, ':'), array_keys(Category::LABELS), true) <=> array_search(strtok($b, ':'), array_keys(Category::LABELS), true) ?: strcmp($a, $b));
|
||
$unprovided = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->count();
|
||
if ($unprovided > 0) {
|
||
$tabs[Category::UNPROVIDED] = ['label' => Category::LABELS[Category::UNPROVIDED], 'count' => $unprovided];
|
||
}
|
||
$tab = (string) $request->query('cat', array_key_first($tabs) ?? '');
|
||
if ($tab === Category::UNPROVIDED) {
|
||
$lines = $db->table('courier_bill_unprovided')->where('statement_id', $statement->id)->orderBy('id')->paginate(50, ['*'], 'page')->withQueryString();
|
||
} else {
|
||
[$category, $categoryMonth] = array_pad(explode(':', $tab, 2), 2, null);
|
||
$query = $db->table('courier_bill_lines')->where('statement_id', $statement->id)->where('category', $category);
|
||
if ($categoryMonth !== null) {
|
||
$query->where('category_month', $categoryMonth);
|
||
}
|
||
$lines = $query->orderBy('id')->paginate(50, ['id', 'waybill_no', 'bill_amount', 'bill_weight', 'ship_time', 'express_name',
|
||
'calc_freight', 'charge_weight', 'self_amount', 'resolution', 'resolved_by', 'unshipped_sources', 'category', 'category_month'], 'page')->withQueryString();
|
||
}
|
||
$items = $db->table('courier_bill_summary_items')->where('statement_id', $statement->id)->orderBy('sort')->get();
|
||
$files = $db->table('courier_bill_files')->where('statement_id', $statement->id)->orderBy('id')->get();
|
||
$shippingSync = null;
|
||
try {
|
||
$shippingSync = app(\App\Support\CourierBills\ShippingLookup::class)->connection()->table('jst_oms_shipping')->max('ship_time');
|
||
} catch (QueryException) {
|
||
}
|
||
|
||
return ['cbStatement' => $statement, 'cbGroup' => $group, 'cbTabs' => $tabs, 'cbTab' => $tab, 'cbLines' => $lines,
|
||
'cbItems' => $items, 'cbFiles' => $files, 'cbShippingSync' => $shippingSync];
|
||
}
|
||
|
||
private function detailsData(Request $request, string $month): array
|
||
{
|
||
$filters = $request->validate([
|
||
'group_id' => ['nullable', 'integer'], 'category' => ['nullable', Rule::in(array_keys(Category::LABELS))],
|
||
'resolution' => ['nullable', Rule::in(['pending', 'all', ...array_keys(Category::RESOLUTIONS)])],
|
||
'owner' => ['nullable', 'string', 'max:64'], 'min_diff' => ['nullable', 'numeric'], 'waybills' => ['nullable', 'string', 'max:20000'],
|
||
'all_months' => ['nullable', 'boolean'],
|
||
]);
|
||
$query = $this->detailsQuery($filters, $month);
|
||
|
||
return ['cbFilters' => $filters, 'cbLines' => $query->orderBy('l.id')->paginate(50, ['l.*', 's.bill_month', 's.status as statement_status', 'g.name as group_name', 'g.owner'])
|
||
->withQueryString(), 'cbOwners' => collect($this->store->groups())->pluck('owner')->filter()->unique()->values()->all()];
|
||
}
|
||
|
||
private function detailsQuery(array $filters, string $month)
|
||
{
|
||
$query = $this->store->db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
|
||
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id');
|
||
if (empty($filters['all_months'])) {
|
||
$query->where('s.bill_month', $month);
|
||
}
|
||
if (! empty($filters['group_id'])) {
|
||
$query->where('s.group_id', (int) $filters['group_id']);
|
||
}
|
||
if (! empty($filters['category'])) {
|
||
$query->where('l.category', $filters['category']);
|
||
}
|
||
$resolution = $filters['resolution'] ?? 'pending';
|
||
if ($resolution === 'pending') {
|
||
$query->whereNull('l.resolution')->where('l.category', '<>', Category::MATCH);
|
||
} elseif ($resolution !== 'all') {
|
||
$query->where('l.resolution', $resolution);
|
||
}
|
||
if (! empty($filters['owner'])) {
|
||
$query->where('g.owner', $filters['owner']);
|
||
}
|
||
if (isset($filters['min_diff']) && $filters['min_diff'] !== null && $filters['min_diff'] !== '') {
|
||
$query->whereRaw('ABS(COALESCE(l.bill_amount,0) - COALESCE(l.self_amount,0)) >= ?', [(float) $filters['min_diff']]);
|
||
}
|
||
$numbers = array_values(array_unique(array_filter(array_map(fn ($n) => Waybill::normalize($n),
|
||
preg_split('/[\r\n,,\s]+/u', (string) ($filters['waybills'] ?? '')) ?: []))));
|
||
if (count($numbers) > 1000) {
|
||
throw ValidationException::withMessages(['waybills' => '最多同时查询 1000 个快递单号。']);
|
||
}
|
||
if ($numbers !== []) {
|
||
$query->whereIn('l.waybill_no', $numbers);
|
||
}
|
||
|
||
return $query;
|
||
}
|
||
|
||
private function uploadData(string $month): array
|
||
{
|
||
return ['cbFiles' => $this->store->db()->table('courier_bill_files as f')->leftJoin('courier_bill_groups as g', 'g.id', '=', 'f.group_id')
|
||
->where('f.bill_month', $month)->orderByDesc('f.id')->get(['f.*', 'g.name as group_name'])];
|
||
}
|
||
|
||
private function ledgerData(Request $request): array
|
||
{
|
||
$db = $this->store->db();
|
||
$search = Waybill::normalize((string) $request->query('waybill'));
|
||
|
||
return [
|
||
'cbLedgerStats' => $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||
->groupBy('g.name', 'l.settle_month')->selectRaw('g.name as group_name, l.settle_month, COUNT(*) as n, SUM(l.amount) as amount, SUM(CASE WHEN l.statement_id IS NULL THEN 1 ELSE 0 END) as imported')
|
||
->orderByDesc('l.settle_month')->orderBy('g.name')->limit(500)->get(),
|
||
'cbLedgerHits' => $search === null ? collect() : $db->table('courier_bill_ledger as l')->join('courier_bill_groups as g', 'g.id', '=', 'l.group_id')
|
||
->where('l.waybill_no', $search)->get(['l.*', 'g.name as group_name']),
|
||
'cbSearch' => $search,
|
||
];
|
||
}
|
||
|
||
public function upload(Request $request)
|
||
{
|
||
$data = $request->validate([
|
||
'month' => ['required', 'date_format:Y-m'], 'group_id' => ['nullable', 'integer'],
|
||
'files' => ['required', 'array', 'max:60'], 'files.*' => ['file', 'max:51200'],
|
||
], [], ['files' => '账单文件', 'files.*' => '账单文件']);
|
||
foreach ($data['files'] as $file) {
|
||
if (! in_array(strtolower($file->getClientOriginalExtension()), CourierBillStore::EXTENSIONS, true)) {
|
||
throw ValidationException::withMessages(['files' => '只支持 xlsx、xls、csv、zip:' . $file->getClientOriginalName()]);
|
||
}
|
||
}
|
||
$ids = $this->guard(fn () => $this->store->upload($data['files'], $data['month'], isset($data['group_id']) ? (int) $data['group_id'] : null, self::user()));
|
||
$files = $this->store->db()->table('courier_bill_files')->whereIn('id', $ids)->get();
|
||
|
||
return $this->back($request, ['cb_view' => 'upload', 'month' => $data['month']],
|
||
'已上传 ' . count($ids) . ' 个文件:已读入 ' . $files->where('status', 'parsed')->count() . ' 个,待选分组 '
|
||
. $files->where('status', 'pending_group')->count() . ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个。');
|
||
}
|
||
|
||
public function assign(Request $request, int $file)
|
||
{
|
||
$data = $request->validate(['group_id' => ['required', 'integer']]);
|
||
$this->guard(fn () => $this->store->assign($file, (int) $data['group_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 rematch(Request $request, int $statement)
|
||
{
|
||
$this->guard(fn () => $this->matcher->match($statement));
|
||
|
||
return $this->back($request, [], '已按最新发货数据、未发出明细和结算台账重新匹配。');
|
||
}
|
||
|
||
public function resolve(Request $request)
|
||
{
|
||
$data = $request->validate([
|
||
'lines' => ['required', 'array', 'max:2000'], 'lines.*' => ['integer'],
|
||
'resolution' => ['required', Rule::in(['clear', ...array_keys(Category::RESOLUTIONS)])],
|
||
], [], ['lines' => '明细']);
|
||
$resolution = $data['resolution'] === 'clear' ? null : $data['resolution'];
|
||
$count = 0;
|
||
$byStatement = $this->store->db()->table('courier_bill_lines')->whereIn('id', $data['lines'])->get(['id', 'statement_id'])->groupBy('statement_id');
|
||
foreach ($byStatement as $statementId => $lines) {
|
||
$count += $this->guard(fn () => $this->matcher->resolve((int) $statementId, $lines->pluck('id')->all(), $resolution, self::user()));
|
||
}
|
||
|
||
return $this->back($request, [], '已更新 ' . $count . ' 条明细的处理结果,小汇总已重算。');
|
||
}
|
||
|
||
public function addItem(Request $request, int $statement)
|
||
{
|
||
$data = $request->validate(['label' => ['required', 'string', 'max:255'], 'bill' => ['nullable', 'numeric'], 'self' => ['nullable', 'numeric']],
|
||
[], ['label' => '项目名称', 'bill' => '快递提供金额', 'self' => '自算金额']);
|
||
$this->guard(fn () => $this->store->addSummaryItem($statement, $data['label'], isset($data['bill']) ? (float) $data['bill'] : null,
|
||
isset($data['self']) ? (float) $data['self'] : null));
|
||
|
||
return $this->back($request, [], '已加入小汇总。');
|
||
}
|
||
|
||
public function deleteItem(Request $request, int $statement, int $item)
|
||
{
|
||
$this->guard(fn () => $this->store->deleteSummaryItem($statement, $item));
|
||
|
||
return $this->back($request, [], '已删除。');
|
||
}
|
||
|
||
public function confirm(Request $request, int $statement)
|
||
{
|
||
$this->guard(fn () => $this->store->confirm($statement, self::user()));
|
||
|
||
return $this->back($request, [], '已确认结算,单号已记入结算台账。');
|
||
}
|
||
|
||
public function unconfirm(Request $request, int $statement)
|
||
{
|
||
$this->guard(fn () => $this->store->unconfirm($statement));
|
||
|
||
return $this->back($request, [], '已撤销确认,结算台账里这批单号已删除。');
|
||
}
|
||
|
||
public function saveGroup(Request $request)
|
||
{
|
||
$data = $request->validate([
|
||
'id' => ['nullable', 'integer'], 'name' => ['required', 'string', 'max:128'], 'express_names' => ['required', 'string', 'max:2000'],
|
||
'summary_carrier' => ['nullable', 'string', 'max:128'], 'owner' => ['nullable', 'string', 'max:64'], 'keywords' => ['nullable', 'string', 'max:255'],
|
||
'waybill_header' => ['nullable', 'string', 'max:64'], 'amount_header' => ['nullable', 'string', 'max:64'], 'weight_header' => ['nullable', 'string', 'max:64'],
|
||
], [], ['name' => '分组名称', 'express_names' => '快递名称1']);
|
||
$exists = $this->store->db()->table('courier_bill_groups')->where('name', trim($data['name']))
|
||
->when(! empty($data['id']), fn ($q) => $q->where('id', '<>', (int) $data['id']))->exists();
|
||
if ($exists) {
|
||
throw ValidationException::withMessages(['name' => '分组名称已存在。']);
|
||
}
|
||
$data['express_names'] = preg_split('/[\r\n,,、]+/u', $data['express_names']) ?: [];
|
||
$this->store->saveGroup(empty($data['id']) ? null : (int) $data['id'], $data);
|
||
|
||
return $this->back($request, ['cb_view' => 'groups'], '已保存分组。');
|
||
}
|
||
|
||
public function importLedger(Request $request)
|
||
{
|
||
$file = $request->validate(['ledger' => ['required', 'file', 'max:51200']], [], ['ledger' => '台账文件'])['ledger'];
|
||
$extension = strtolower($file->getClientOriginalExtension());
|
||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||
throw ValidationException::withMessages(['ledger' => '只支持 xlsx、xls、csv。']);
|
||
}
|
||
$result = $this->guard(fn () => $this->store->importLedger($file->getRealPath(), $extension));
|
||
$message = '读到 ' . $result['rows'] . ' 行,新增 ' . $result['inserted'] . ' 条已结算单号';
|
||
if ($result['rejected'] > 0) {
|
||
$message .= ',' . $result['rejected'] . ' 行未导入' . ($result['unknown_groups'] ? '(分组不存在:' . implode('、', array_slice($result['unknown_groups'], 0, 10)) . ')' : '');
|
||
}
|
||
|
||
return $this->back($request, ['cb_view' => 'ledger'], $message . '。');
|
||
}
|
||
|
||
public function exportStatement(Request $request, int $statement)
|
||
{
|
||
$row = $this->store->db()->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||
->where('s.id', $statement)->first(['s.bill_month', 'g.name']);
|
||
abort_if($row === null, 404);
|
||
$name = str_replace(['/', '\\'], '-', $row->name) . '_' . $row->bill_month . '_对账(内部版).xlsx';
|
||
|
||
return response()->streamDownload(function () use ($statement): void {
|
||
$output = fopen('php://output', 'wb');
|
||
app(StatementExporter::class)->export($statement, $output);
|
||
}, $name);
|
||
}
|
||
|
||
public function exportDetails(Request $request)
|
||
{
|
||
$month = self::monthParam($request->query('month')) ?? now()->subMonth()->format('Y-m');
|
||
$filters = $request->validate(['group_id' => ['nullable', 'integer'], 'category' => ['nullable', 'string'],
|
||
'resolution' => ['nullable', 'string'], 'owner' => ['nullable', 'string'], 'min_diff' => ['nullable', 'numeric'],
|
||
'waybills' => ['nullable', 'string', 'max:20000'], 'all_months' => ['nullable', 'boolean']]);
|
||
$query = $this->detailsQuery($filters, $month);
|
||
|
||
return response()->streamDownload(function () use ($query): void {
|
||
$book = new StreamingWorkbook();
|
||
$book->row('对账明细', ['账单月份', '对账分组', '负责人', '快递单号', '快递提供运费', '快递提供重量', '分类', '发货时间', '发货数据快递名称1',
|
||
'核算运费', '计费重量', '自算金额', '差异', '未发出来源', '处理结果', '处理人'], true);
|
||
foreach ($query->orderBy('l.id')->select(['l.*', 's.bill_month', 'g.name as group_name', 'g.owner'])->lazyById(1000, 'l.id', 'id') as $line) {
|
||
$book->row('对账明细', [$line->bill_month, $line->group_name, $line->owner, (string) $line->waybill_no,
|
||
$line->bill_amount === null ? null : (float) $line->bill_amount, $line->bill_weight === null ? null : (float) $line->bill_weight,
|
||
Category::label((string) $line->category, $line->category_month), $line->ship_time, $line->express_name,
|
||
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->charge_weight === null ? null : (float) $line->charge_weight,
|
||
$line->self_amount === null ? null : (float) $line->self_amount, round((float) $line->bill_amount - (float) $line->self_amount, 2),
|
||
$line->unshipped_sources, Category::RESOLUTIONS[$line->resolution] ?? null, $line->resolved_by]);
|
||
}
|
||
$book->writeTo(fopen('php://output', 'wb'));
|
||
}, '对账明细.xlsx');
|
||
}
|
||
|
||
/** @template T @param callable():T $action @return T */
|
||
private function guard(callable $action): mixed
|
||
{
|
||
try {
|
||
return $action();
|
||
} catch (RuntimeException $error) {
|
||
throw ValidationException::withMessages(['courier_bills' => $error->getMessage()]);
|
||
}
|
||
}
|
||
|
||
private function back(Request $request, array $query, string $message)
|
||
{
|
||
$target = $query === [] ? url()->previous() : route('business.pages.show', ['section' => self::section($request),
|
||
'page' => 'courier-bill-reconciliation', ...$query]);
|
||
|
||
return redirect()->to($target)->with('courier_bills_message', $message);
|
||
}
|
||
|
||
public static function section(Request $request): string
|
||
{
|
||
$section = (string) ($request->route('section') ?? $request->input('section') ?? '');
|
||
|
||
return $section === 'courier-payables-final' ? 'courier-payables-final' : 'courier-payables';
|
||
}
|
||
|
||
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');
|
||
}
|
||
}
|