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

394 lines
20 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\Category;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipConfirmation;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\DropshipShareLink;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
use RuntimeException;
use Throwable;
/** 代发运费对账:代发厂家开的运费 对 系统核算运费,按我方核算结算;不进快递应付汇总。 */
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,
private readonly DropshipConfirmation $confirmations,
) {}
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;
}
}
$notifier = app(SupplierDingTalkNotifier::class);
return ['dfRows' => $rows, 'dfWithout' => $without, 'dfStates' => $this->confirmations->states($month, self::companyId()),
'dfRobots' => $notifier->configurationMap(array_column($rows, 'factory')), '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,
'dfState' => $this->confirmations->state($month, (int) $factory->id, self::companyId()),
'dfDisputes' => $this->confirmations->disputes($month, (int) $factory->id, self::companyId()),
'dfRobot' => app(SupplierDingTalkNotifier::class)->configuration((string) $factory->name)];
}
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 importSummaryTemplates(Request $request)
{
$data = $request->validate([
'month' => ['required', 'date_format:Y-m'],
'files' => ['required', 'array', 'max:80'], 'files.*' => ['file', 'max:51200'],
], [], ['files' => '手工汇总', 'files.*' => '手工汇总']);
$files = [];
foreach ($data['files'] as $file) {
if (! in_array(strtolower($file->getClientOriginalExtension()), ['xlsx', 'xls'], true)) {
throw ValidationException::withMessages(['templates' => '只支持 xlsx、xls:' . $file->getClientOriginalName()]);
}
$files[] = [$file->getClientOriginalName(), (string) $file->getRealPath()];
}
$result = $this->guard(fn () => $this->store->importSummaryTemplates($files, $data['month']));
return $this->back($request, ['df_view' => 'upload', 'month' => $data['month']], '读到 ' . $result['blocks'] . ' 份汇总,记下 '
. count($result['saved']) . ' 家 ' . $data['month'] . ' 的汇总样子' . ($result['saved'] !== [] ? ':' . implode('、', $result['saved']) : '')
. ($result['unknown'] !== [] ? '。没认出的:' . implode('、', array_slice($result['unknown'], 0, 20)) . '(文件名或汇总标题里要有厂家名)' : '') . '。');
}
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 check(Request $request, int $factory)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'checked' => ['required', 'boolean']]);
$f = $this->factory($factory);
$summary = $this->reconciler->factoryMonth($f, $data['month'])['summary'];
$this->guard(fn () => $this->confirmations->check($data['month'], $f, $summary, (bool) $data['checked'], self::companyId(),
user()?->id, self::user()));
return $this->back($request, [], (bool) $data['checked'] ? '「' . $f->name . '」' . $data['month'] . ' 已标记核对完成,可以推送给厂家确认。'
: '已撤销「' . $f->name . '」的核对完成。');
}
/** 推送到厂家钉钉群(和供应商货款对账同一个群机器人),附免登录确认页链接;重新推送版本号加一,旧链接作废。 */
public function push(Request $request, int $factory)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m']]);
$month = $data['month'];
$f = $this->factory($factory);
$result = $this->reconciler->factoryMonth($f, $month);
$summary = $result['summary'];
$attention = self::attention($result['rows']);
$notifier = app(SupplierDingTalkNotifier::class);
if (! $notifier->configuration((string) $f->name)['configured']) {
throw ValidationException::withMessages(['dropship' => '「' . $f->name . '」还没有配置钉钉群机器人,请先在供应商对账里给这家配上(和货款对账同一个群)。']);
}
$companyId = self::companyId();
$version = $this->guard(fn () => $this->confirmations->startPush($month, $f, $summary, $attention, $companyId, user()?->id, self::user()));
$url = app(DropshipShareLink::class)->pageUrl($companyId, (int) $f->id, $month, $version);
try {
$notifier->pushDropshipFreight((string) $f->name, $month, $summary, $attention, $version, $url);
} catch (Throwable $error) {
$this->confirmations->markFailed($month, (int) $f->id, $companyId, $error->getMessage());
report($error);
throw ValidationException::withMessages(['dropship' => '推送失败:' . $error->getMessage()]);
}
$this->confirmations->markPushed($month, (int) $f->id, $companyId);
return $this->back($request, [], '已推送到「' . $f->name . '」钉钉群(第 ' . $version . ' 次),等厂家在确认页确认。');
}
/**
* 通知厂家上传代发运费账单:传 factory 只通知这一家;不传就通知这个月还没上传、且配了钉钉群机器人的全部厂家。
*/
public function notifyUpload(Request $request)
{
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'factory' => ['nullable', 'integer']]);
$month = $data['month'];
$notifier = app(SupplierDingTalkNotifier::class);
$factories = collect($this->store->factories());
$single = ! empty($data['factory']);
if ($single) {
$factories = $factories->where('id', (int) $data['factory'])->values();
abort_if($factories->isEmpty(), 404);
}
$uploaded = array_flip($this->store->db()->table('dropship_bill_files')->where('bill_month', $month)->whereNotNull('factory_id')
->distinct()->pluck('factory_id')->map('intval')->all());
$robots = $notifier->configurationMap($factories->pluck('name')->map('strval')->all());
$portal = route('business.supplier-portal.home', ['company_id' => self::companyId()]);
$sent = $failed = [];
$noRobot = $done = 0;
foreach ($factories as $f) {
if (! $single && isset($uploaded[(int) $f->id])) {
$done++;
continue;
}
if (! ($robots[$f->name]['configured'] ?? false)) {
$noRobot++;
continue;
}
try {
$notifier->pushDropshipUploadReminder((string) $f->name, $month, $portal);
$sent[] = $f->name;
} catch (Throwable $error) {
report($error);
$failed[] = $f->name;
}
}
if ($single && $noRobot > 0) {
throw ValidationException::withMessages(['dropship' => '这家还没有配置钉钉群机器人(在供应商对账里配置,和货款对账同一个群)。']);
}
return $this->back($request, [], '已通知 ' . count($sent) . ' 家上传 ' . $month . ' 代发运费账单' . ($sent !== [] ? ':' . implode('、', array_slice($sent, 0, 40)) : '')
. ($done > 0 ? ';' . $done . ' 家已经上传,没再通知' : '') . ($noRobot > 0 ? ';' . $noRobot . ' 家没配钉钉群机器人' : '')
. ($failed !== [] ? ';发送失败:' . implode('、', $failed) : '') . '。');
}
/** 厂家开了运费、但不是「一致」的单:不结算或运费有差,确认页上请厂家重点看。 */
public static function attention(array $rows): int
{
return count(array_filter($rows, static fn (array $r): bool => $r['bill'] !== null && $r['status'] !== Category::MATCH));
}
private function factory(int $id): object
{
$factory = collect($this->store->factories())->firstWhere('id', $id);
abort_if($factory === null, 404);
return $factory;
}
private static function companyId(): int
{
return (int) (company_id() ?: 1);
}
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');
}
}