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

168 lines
7.9 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 Illuminate\Routing\Controller;
use App\Support\UnshippedWaybills;
use App\Utilities\SystemAccess;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Throwable;
final class UnshippedWaybillController extends Controller
{
public function __construct(private readonly UnshippedWaybills $waybills) {}
public function page(Request $request): array
{
$data = ['view' => 'business.pages.courier-payables.unshipped-waybills', 'sources' => UnshippedWaybills::SOURCES,
'syncSources' => UnshippedWaybills::SYNC_SOURCES, 'canImport' => $this->canImport(), 'rows' => null, 'states' => collect(), 'coverage' => null, 'unavailable' => false];
try {
$data['rows'] = $this->filtered($request)->orderByDesc('evidence_time')->orderByDesc('id')->paginate(50)->withQueryString();
$db = $this->waybills->connection();
$data['states'] = $db->table('courier_unshipped_sync')->get()->keyBy('source');
$data['coverage'] = $db->table('courier_unshipped_order_logs')->selectRaw('min(operated_at) as start_at,max(operated_at) as end_at')->first();
} catch (\Illuminate\Database\QueryException $error) {
report($error);
$data['unavailable'] = true;
}
return $data;
}
private function filtered(Request $request)
{
$filters = $request->validate([
'waybills' => ['nullable', 'string', 'max:15000'],
'sources' => ['nullable', 'array', 'max:3'],
'sources.*' => [Rule::in(array_keys(UnshippedWaybills::SOURCES))],
'courier' => ['nullable', 'string', 'max:255'],
'from' => ['nullable', 'date_format:Y-m-d'],
'to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:from'],
]);
$query = $this->waybills->results();
$numbers = array_values(array_unique(array_filter(array_map(UnshippedWaybills::normalize(...),
preg_split('/[\r\n,,]+/u', $filters['waybills'] ?? '') ?: []), fn ($number) => $number !== '')));
if (count($numbers) > 500) throw ValidationException::withMessages(['waybills' => '最多同时查询 500 个快递单号。']);
if ($numbers !== []) $query->whereIn('waybill_no', $numbers);
if (!empty($filters['sources'])) $query->whereIn('source', UnshippedWaybills::storedSources($filters['sources']));
if (!empty($filters['courier'])) $query->where('courier_name', trim($filters['courier']));
if (!empty($filters['from'])) $query->where('evidence_time', '>=', $filters['from']);
if (!empty($filters['to'])) $query->where('evidence_time', '<', CarbonImmutable::parse($filters['to'])->addDay()->toDateString());
return $query;
}
public function export(Request $request)
{
$query = $this->filtered($request);
return response()->streamDownload(function () use ($query): void {
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->fromArray(['快递单号', '来源']);
$line = 2;
foreach ($query->orderBy('id')->lazyById(1000) as $row) {
$values = [$row->waybill_no, UnshippedWaybills::label($row->source)];
foreach ($values as $column => $value) {
$sheet->setCellValueExplicit(chr(65 + $column).$line, (string) $value, DataType::TYPE_STRING);
}
$line++;
}
(new Xlsx($book))->save('php://output');
$book->disconnectWorksheets();
}, '未发出明细.xlsx');
}
public function import(Request $request)
{
abort_unless($this->canImport(), 403);
$file = $request->validate(['log' => ['required', 'file', 'mimes:xlsx,csv,txt', 'max:10240']])['log'];
$isCsv = strtolower($file->getClientOriginalExtension()) === 'csv';
$entries = [];
$header = null;
$errors = [];
foreach ($this->fileRows($file->getRealPath(), $isCsv) as $line => $row) {
if ($header === null) {
$header = array_flip(array_map(fn ($value) => trim((string) $value, "\xEF\xBB\xBF \t"), $row));
if (array_diff(['订单编号', '类型', '操作备注', '操作时间', '操作人'], array_keys($header))) {
throw ValidationException::withMessages(['log' => '文件缺少订单编号、类型、操作备注、操作时间或操作人列。']);
}
continue;
}
if (trim((string) ($row[$header['类型']] ?? '')) !== '修改快递单号') continue;
$remark = (string) ($row[$header['操作备注']] ?? '');
$parsed = UnshippedWaybills::parseRemark($remark);
$order = trim((string) ($row[$header['订单编号']] ?? ''));
$time = $row[$header['操作时间']] ?? null;
try {
$operated = is_int($time) || is_float($time)
? CarbonImmutable::instance(Date::excelToDateTimeObject($time))
: (filled($time) ? CarbonImmutable::parse($time) : null);
} catch (Throwable) {
$operated = null;
}
if (!$parsed || !$operated || !preg_match('/^[A-Za-z0-9-]{1,96}$/', $order) || preg_match('/^\d+e[+-]?\d+$/i', $order)) {
if (count($errors) < 10) $errors[] = $line;
continue;
}
if ($operated->toDateString() < UnshippedWaybills::START || $operated->toDateString() >= today()->toDateString()) continue;
$entries[] = $parsed + ['order_no' => $order, 'operated_at' => $operated->toDateTimeString(),
'operator' => trim((string) ($row[$header['操作人']] ?? '')), 'remark' => $remark];
}
if ($errors !== []) {
throw ValidationException::withMessages(['log' => '这些行的订单编号、时间或备注格式有误(含科学计数法单号):'.implode('、', $errors).'。请修正后重新上传。']);
}
if ($entries === []) throw ValidationException::withMessages(['log' => '没有符合日期及操作类型的记录。']);
$db = $this->waybills->connection();
$count = $db->transaction(function () use ($db, $entries): int {
$count = 0;
foreach (array_chunk($entries, 500) as $batch) {
$count += $db->table('courier_unshipped_order_logs')->insertOrIgnore($batch);
}
return $count;
});
return back()->with('unshipped_import', '已新增 '.$count.' 条日志,下次每日同步后更新换单明细。');
}
private function fileRows(string $path, bool $isCsv): iterable
{
if ($isCsv) {
$file = new \SplFileObject($path);
$file->setCsvControl(',', '"', '');
$file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY);
foreach ($file as $index => $row) {
if ($row !== [null]) yield $index + 1 => $row;
}
return;
}
$reader = IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(true);
$book = $reader->load($path);
try {
foreach ($book->getSheet(0)->getRowIterator() as $row) {
yield $row->getRowIndex() => array_map(
fn ($cell) => $cell->getValue(),
iterator_to_array($row->getCellIterator(), false)
);
}
} finally {
$book->disconnectWorksheets();
}
}
private function canImport(): bool
{
return in_array(SystemAccess::roleName(user()), [SystemAccess::SUPER_ADMIN, SystemAccess::ADMIN], true);
}
}