Импорт с предпросмотром и обновлением по ключу, фоновая выгрузка задачей
This commit is contained in:
1 parent
00bba5abfa
commit
7fc7630e34
19 files changed
+1219
-65
No files matched your search
@@ -93,6 +93,8 @@ UI_PER_PAGE=25
|
||||
# Выгрузка списков в CSV: разделитель и предел строк на файл
|
||||
EXPORT_DELIMITER=;
|
||||
EXPORT_MAX_ROWS=20000
|
||||
# Сколько дней живут готовые файлы фоновых выгрузок
|
||||
EXPORT_KEEP_DAYS=7
|
||||
|
||||
# Загрузка списков из CSV: сколько строк принимаем за раз
|
||||
IMPORT_MAX_ROWS=5000
|
||||
|
||||
@@ -39,7 +39,7 @@ final class AuditController extends Controller
|
||||
'entity_id' => 'Запись',
|
||||
'description' => 'Описание',
|
||||
'ip' => 'Адрес',
|
||||
], 'audit', 'audit', 'admin.audit');
|
||||
], 'audit', 'audit', 'admin.audit', $request);
|
||||
}
|
||||
|
||||
private function listFilters(Request $request): Filters
|
||||
|
||||
@@ -52,7 +52,7 @@ final class UsersController extends Controller
|
||||
'active' => ['Активен', static fn (User $user): string => $user->isActive() ? 'да' : 'нет'],
|
||||
'created_at' => 'Заведён',
|
||||
'last_login_at' => 'Последний вход',
|
||||
], 'users', 'user', 'admin.users');
|
||||
], 'users', 'user', 'admin.users', $request);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\ExportFile;
|
||||
|
||||
/**
|
||||
* Готовые файлы фоновых выгрузок.
|
||||
*
|
||||
* Вход не нужен: право скачать доказывает подпись ссылки из уведомления.
|
||||
* Сами файлы лежат вне public, поэтому отдаёт их код, а имя проверяется —
|
||||
* из адреса приходит что угодно.
|
||||
*/
|
||||
final class ExportsController extends Controller
|
||||
{
|
||||
public function download(string $file): Response
|
||||
{
|
||||
$path = ExportFile::path($file);
|
||||
|
||||
if ($path === null) {
|
||||
throw new RecordNotFound('Файл выгрузки не найден или уже удалён');
|
||||
}
|
||||
|
||||
return Response::download((string) file_get_contents($path), $file, 'text/csv; charset=utf-8');
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,12 @@ use Rsgrinko\Proton\View\View;
|
||||
*/
|
||||
final class NotesController extends Controller
|
||||
{
|
||||
/** Колонки файла: те же, что в выгрузке */
|
||||
private const COLUMNS = ['Название' => 'title', 'Текст' => 'body', 'Закреплена' => 'pinned'];
|
||||
|
||||
/** Проверка строки файла */
|
||||
private const RULES = ['title' => 'required|max:191', 'body' => 'nullable|max:20000', 'pinned' => 'nullable|max:10'];
|
||||
|
||||
public function index(Request $request, Scope $scope): Response
|
||||
{
|
||||
$filters = $this->listFilters($request);
|
||||
@@ -60,7 +66,7 @@ final class NotesController extends Controller
|
||||
'pinned' => ['Закреплена', static fn (Note $note): string => $note->pinned ? 'да' : 'нет'],
|
||||
'created_at' => 'Создана',
|
||||
'updated_at' => 'Изменена',
|
||||
], 'notes', 'note', 'notes.index');
|
||||
], 'notes', 'note', 'notes.index', $request);
|
||||
}
|
||||
|
||||
private function listFilters(Request $request): Filters
|
||||
@@ -86,33 +92,63 @@ final class NotesController extends Controller
|
||||
*/
|
||||
public function import(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
$file = $request->file('file');
|
||||
|
||||
if ($file === null || !$file->uploaded()) {
|
||||
$this->flash($file?->error() ?? 'Выберите файл CSV', 'error');
|
||||
$content = $this->uploaded($request);
|
||||
|
||||
if ($content === null) {
|
||||
return $this->redirect('notes.index');
|
||||
}
|
||||
|
||||
if ($file->extension() !== 'csv') {
|
||||
$this->flash('Нужен файл CSV', 'error');
|
||||
// Первый шаг — предпросмотр: человек видит, что заведётся, что обновится
|
||||
// и что отвалится, и только потом решает
|
||||
$plan = Import::plan(
|
||||
$content,
|
||||
self::COLUMNS,
|
||||
self::RULES,
|
||||
[],
|
||||
fn (array $row): ?Note => $this->locate($row, $viewer)
|
||||
);
|
||||
|
||||
View::stash('import_plan', $plan);
|
||||
View::stash('import_file', $this->keepFile($content));
|
||||
|
||||
$this->flash(
|
||||
$plan->any() ? 'Проверьте, что получится, и подтвердите загрузку' : 'Загружать нечего',
|
||||
$plan->any() ? 'ok' : 'error'
|
||||
);
|
||||
|
||||
return $this->redirect('notes.index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Второй шаг: подтверждённая загрузка. Файл берётся тот же, что смотрели
|
||||
* в предпросмотре, — заново его не присылают.
|
||||
*/
|
||||
public function importConfirm(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
$content = $this->takeFile((string) $request->input('file', ''));
|
||||
|
||||
if ($content === null) {
|
||||
$this->flash('Файл потерялся — загрузите его заново', 'error');
|
||||
|
||||
return $this->redirect('notes.index');
|
||||
}
|
||||
|
||||
$report = Import::csv(
|
||||
(string) file_get_contents($file->tmpPath()),
|
||||
['Название' => 'title', 'Текст' => 'body', 'Закреплена' => 'pinned'],
|
||||
['title' => 'required|max:191', 'body' => 'nullable|max:20000', 'pinned' => 'nullable|max:10'],
|
||||
static function (array $row) use ($viewer): void {
|
||||
$note = new Note([
|
||||
'title' => (string) $row['title'],
|
||||
'body' => (string) ($row['body'] ?? ''),
|
||||
'pinned' => in_array(mb_strtolower((string) ($row['pinned'] ?? '')), ['да', '1', 'true'], true) ? 1 : 0,
|
||||
]);
|
||||
$content,
|
||||
self::COLUMNS,
|
||||
self::RULES,
|
||||
function (array $row) use ($viewer): void {
|
||||
$note = new Note($this->fields($row));
|
||||
|
||||
$note->setAttribute('user_id', $viewer->id());
|
||||
$note->save();
|
||||
},
|
||||
[],
|
||||
fn (array $row): ?Note => $this->locate($row, $viewer),
|
||||
function (Note $note, array $row): void {
|
||||
// Повторная загрузка того же файла правит запись, а не двоит её
|
||||
$note->fill($this->fields($row));
|
||||
$note->save();
|
||||
}
|
||||
);
|
||||
|
||||
@@ -125,6 +161,104 @@ final class NotesController extends Controller
|
||||
return $this->redirect('notes.index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Содержимое присланного файла или null, если прислали не то.
|
||||
*/
|
||||
private function uploaded(Request $request): ?string
|
||||
{
|
||||
$file = $request->file('file');
|
||||
|
||||
if ($file === null || !$file->uploaded()) {
|
||||
$this->flash($file?->error() ?? 'Выберите файл CSV', 'error');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($file->extension() !== 'csv') {
|
||||
$this->flash('Нужен файл CSV', 'error');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return (string) file_get_contents($file->tmpPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Кладёт файл между шагами во временный каталог и возвращает метку.
|
||||
* В сессии его держать нельзя: файл бывает на мегабайты.
|
||||
*/
|
||||
private function keepFile(string $content): string
|
||||
{
|
||||
$token = bin2hex(random_bytes(8));
|
||||
|
||||
file_put_contents($this->tempPath($token), $content);
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Забирает отложенный файл и сразу убирает его: второй раз он не нужен.
|
||||
*/
|
||||
private function takeFile(string $token): ?string
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{16}$/', $token) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $this->tempPath($token);
|
||||
|
||||
if (!is_file($path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = (string) file_get_contents($path);
|
||||
|
||||
@unlink($path);
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
private function tempPath(string $token): string
|
||||
{
|
||||
$dir = (string) Config::get('paths.tmp', APP_ROOT . '/var/tmp') . '/import';
|
||||
|
||||
@mkdir($dir, 0775, true);
|
||||
|
||||
return $dir . '/' . $token . '.csv';
|
||||
}
|
||||
|
||||
/**
|
||||
* Уже есть такая заметка? Ключ — название в пределах своих записей.
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*/
|
||||
private function locate(array $row, Viewer $viewer): ?Note
|
||||
{
|
||||
/** @var Note|null $note */
|
||||
$note = Note::query()
|
||||
->where('user_id', $viewer->id())
|
||||
->where('title', (string) $row['title'])
|
||||
->first();
|
||||
|
||||
return $note;
|
||||
}
|
||||
|
||||
/**
|
||||
* Поля заметки из строки файла.
|
||||
*
|
||||
* @param array<string, mixed> $row
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fields(array $row): array
|
||||
{
|
||||
return [
|
||||
'title' => (string) $row['title'],
|
||||
'body' => (string) ($row['body'] ?? ''),
|
||||
'pinned' => in_array(mb_strtolower((string) ($row['pinned'] ?? '')), ['да', '1', 'true'], true) ? 1 : 0,
|
||||
];
|
||||
}
|
||||
|
||||
public function create(): Response
|
||||
{
|
||||
return $this->view('notes/form', [
|
||||
|
||||
+5
-1
@@ -189,8 +189,12 @@ return [
|
||||
'export' => [
|
||||
// Разделитель CSV: Excel с русской локалью ждёт точку с запятой
|
||||
'delimiter' => Env::string('EXPORT_DELIMITER', ';'),
|
||||
// Предел строк на выгрузку: файл собирается в памяти, а человек ждёт ответа
|
||||
// Предел строк на выгрузку: файл собирается в памяти, а человек ждёт ответа.
|
||||
// Больше — уходит в очередь, ссылка приходит уведомлением
|
||||
'max_rows' => Env::int('EXPORT_MAX_ROWS', 20000),
|
||||
// Где лежат готовые файлы фоновых выгрузок и сколько они живут
|
||||
'path' => APP_ROOT . '/var/exports',
|
||||
'keep_days' => Env::int('EXPORT_KEEP_DAYS', 7),
|
||||
],
|
||||
|
||||
'trash' => [
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Выгрузки, которые умеет готовить очередь.
|
||||
*
|
||||
* Синхронная кнопка «Выгрузить CSV» отдаёт файл сразу, пока строк немного.
|
||||
* Всё, что больше EXPORT_MAX_ROWS, уходит сюда: задача собирает запрос заново
|
||||
* по имени и параметрам отбора, поэтому запрос описывается здесь, а не
|
||||
* в контроллере.
|
||||
*
|
||||
* Запрос получает параметры адреса и того, кто заказал выгрузку: область
|
||||
* видимости должна остаться в силе и в фоне.
|
||||
*/
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\Exports;
|
||||
use Rsgrinko\Proton\Support\Filter;
|
||||
use Rsgrinko\Proton\Support\Filters;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
|
||||
Exports::register(
|
||||
'users',
|
||||
'Пользователи',
|
||||
static function (array $params, Viewer $viewer): Builder {
|
||||
$filters = Filters::make(Request::create('GET', '/admin/users', [], $params), [
|
||||
Filter::search('q', 'Поиск', ['login', 'email', 'name']),
|
||||
Filter::select('role_id', 'Роль', []),
|
||||
Filter::flag('active', 'Активен'),
|
||||
Filter::dates('created', 'Заведён', 'created_at'),
|
||||
]);
|
||||
|
||||
return $filters->apply(User::query());
|
||||
},
|
||||
[
|
||||
'id' => 'ID',
|
||||
'login' => 'Логин',
|
||||
'name' => 'Имя',
|
||||
'email' => 'Почта',
|
||||
'active' => ['Активен', static fn (User $user): string => $user->isActive() ? 'да' : 'нет'],
|
||||
'created_at' => 'Заведён',
|
||||
'last_login_at' => 'Последний вход',
|
||||
],
|
||||
Permission::USERS_MANAGE
|
||||
);
|
||||
|
||||
Exports::register(
|
||||
'audit',
|
||||
'Журнал действий',
|
||||
static function (array $params, Viewer $viewer): Builder {
|
||||
$filters = Filters::make(Request::create('GET', '/admin/audit', [], $params), [
|
||||
Filter::select('action', 'Действие', AuditEntry::LABELS),
|
||||
Filter::text('entity', 'Раздел'),
|
||||
Filter::search('q', 'Поиск', ['description', 'user_login']),
|
||||
Filter::dates('when', 'Когда', 'created_at'),
|
||||
]);
|
||||
|
||||
return $filters->apply(AuditEntry::query());
|
||||
},
|
||||
[
|
||||
'created_at' => 'Когда',
|
||||
'user_login' => 'Кто',
|
||||
'action' => ['Действие', static fn (AuditEntry $entry): string => AuditEntry::label((string) $entry->raw('action'))],
|
||||
'entity' => 'Раздел',
|
||||
'description' => 'Описание',
|
||||
'ip' => 'Адрес',
|
||||
],
|
||||
Permission::AUDIT_VIEW
|
||||
);
|
||||
|
||||
Exports::register(
|
||||
'notes',
|
||||
'Заметки',
|
||||
static function (array $params, Viewer $viewer): Builder {
|
||||
$filters = Filters::make(Request::create('GET', '/notes', [], $params), [
|
||||
Filter::search('q', 'Поиск', ['title', 'body']),
|
||||
Filter::flag('pinned', 'Закреплена'),
|
||||
Filter::dates('created', 'Создана', 'created_at'),
|
||||
]);
|
||||
|
||||
// Область видимости заказчика: в фоне она так же обязательна
|
||||
return $filters->apply($viewer->scope()->apply(Note::query()));
|
||||
},
|
||||
[
|
||||
'id' => 'ID',
|
||||
'title' => 'Название',
|
||||
'body' => 'Текст',
|
||||
'pinned' => ['Закреплена', static fn (Note $note): string => $note->pinned ? 'да' : 'нет'],
|
||||
'created_at' => 'Создана',
|
||||
],
|
||||
'notes.view'
|
||||
);
|
||||
@@ -11,7 +11,10 @@ use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Rsgrinko\Proton\Support\Export;
|
||||
use Rsgrinko\Proton\Support\ExportJob;
|
||||
use Rsgrinko\Proton\Support\Exports;
|
||||
use Rsgrinko\Proton\Support\Filter;
|
||||
use Rsgrinko\Proton\Support\Filters;
|
||||
use Rsgrinko\Proton\Support\Validator;
|
||||
@@ -144,9 +147,31 @@ abstract class Controller
|
||||
*
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*/
|
||||
protected function exportCsv(Builder $query, array $columns, string $name, string $entity = '', string $route = ''): Response
|
||||
{
|
||||
protected function exportCsv(
|
||||
Builder $query,
|
||||
array $columns,
|
||||
string $name,
|
||||
string $entity = '',
|
||||
string $route = '',
|
||||
?Request $request = null
|
||||
): Response {
|
||||
if (!Export::fits($query)) {
|
||||
// Большую выборку отдаёт очередь: файл соберётся в фоне, а человек
|
||||
// получит ссылку уведомлением
|
||||
if ($request !== null && Exports::get($name) !== null) {
|
||||
Queue::push(ExportJob::class, [
|
||||
'kind' => $name,
|
||||
'params' => $request->query,
|
||||
'user_id' => (int) $request->attribute('user')?->id(),
|
||||
]);
|
||||
|
||||
Audit::action($entity !== '' ? $entity : $name, 0, 'заказана фоновая выгрузка: ' . $name);
|
||||
|
||||
$this->flash('Строк слишком много для мгновенной выгрузки — готовлю файл в фоне, пришлю ссылку уведомлением');
|
||||
|
||||
return $this->redirect($route !== '' ? $route : 'home');
|
||||
}
|
||||
|
||||
$this->flash('Слишком много строк для выгрузки — сузьте отбор (предел ' . Export::limit() . ')', 'error');
|
||||
|
||||
return $this->redirect($route !== '' ? $route : 'home');
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Notifications;
|
||||
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\SignedUrl;
|
||||
|
||||
/**
|
||||
* Выгрузка готова — вот ссылка.
|
||||
*
|
||||
* Ссылка подписанная и со сроком: файл лежит вне public, скачать его можно
|
||||
* только по ней, и она перестаёт работать вместе с самим файлом.
|
||||
*/
|
||||
final class ExportReadyNotification extends Notification
|
||||
{
|
||||
public function __construct(
|
||||
private string $label,
|
||||
private string $file,
|
||||
private int $rows
|
||||
) {
|
||||
}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'export.ready';
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return 'Выгрузка «' . $this->label . '» готова';
|
||||
}
|
||||
|
||||
public function body(): string
|
||||
{
|
||||
$days = max(1, (int) Config::get('export.keep_days', 7));
|
||||
|
||||
return 'Строк в файле: ' . $this->rows . '. Ссылка действует ' . $days
|
||||
. ' дн., потом файл удаляется вместе с ней.';
|
||||
}
|
||||
|
||||
public function url(): string
|
||||
{
|
||||
$days = max(1, (int) Config::get('export.keep_days', 7));
|
||||
|
||||
return SignedUrl::absolute('exports.download', ['file' => $this->file], $days * 86400);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function channels(): array
|
||||
{
|
||||
return [Notify::DATABASE, Notify::MAIL];
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use Rsgrinko\Proton\Models\WebhookDelivery;
|
||||
use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\ExportFile;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\Trash;
|
||||
use Rsgrinko\Proton\Support\RequestId;
|
||||
@@ -239,6 +240,7 @@ final class Worker
|
||||
SecurityEvent::purge((int) Config::get('security.keep_days', 60));
|
||||
BlockedIp::purgeExpired();
|
||||
Trash::purge((int) Config::get('trash.keep_days', 30));
|
||||
ExportFile::purge((int) Config::get('export.keep_days', 7));
|
||||
Notify::purge();
|
||||
|
||||
(new Logger('app'))->purge();
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
|
||||
/**
|
||||
* Готовые файлы выгрузок: сборка строк, хранение в var/exports и уборка.
|
||||
*
|
||||
* Файлы лежат вне public и отдаются только по подписанной ссылке: в выгрузке
|
||||
* данные, которые видны не всем.
|
||||
*/
|
||||
final class ExportFile
|
||||
{
|
||||
/** Сколько строк забираем из базы за один запрос */
|
||||
private const CHUNK = 500;
|
||||
|
||||
/**
|
||||
* Заголовки таблицы по описанию колонок.
|
||||
*
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function headers(array $columns): array
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$headers[] = is_array($column) ? $column[0] : $column;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Строки выгрузки.
|
||||
*
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*
|
||||
* @return array<int, array<int, mixed>>
|
||||
*/
|
||||
public static function rows(Builder $query, array $columns): array
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
$query->chunk(self::CHUNK, static function (array $records) use ($columns, &$rows): void {
|
||||
foreach ($records as $record) {
|
||||
$line = [];
|
||||
|
||||
foreach ($columns as $key => $column) {
|
||||
$line[] = is_array($column) ? ($column[1])($record) : self::value($record, $key);
|
||||
}
|
||||
|
||||
$rows[] = $line;
|
||||
}
|
||||
});
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить готовый файл, вернуть его имя.
|
||||
*/
|
||||
public static function save(string $kind, string $content): string
|
||||
{
|
||||
$dir = self::directory();
|
||||
|
||||
@mkdir($dir, 0775, true);
|
||||
|
||||
$name = Export::fileName($kind);
|
||||
|
||||
file_put_contents($dir . '/' . $name, $content);
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Путь к файлу выгрузки. Имя проверяется: из адреса сюда приходит что угодно.
|
||||
*/
|
||||
public static function path(string $name): ?string
|
||||
{
|
||||
if (preg_match('/^[A-Za-z0-9_\-]+-\d{4}-\d{2}-\d{2}-\d{6}\.csv$/', $name) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = self::directory() . '/' . $name;
|
||||
|
||||
return is_file($path) ? $path : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько строк в готовом файле (без заголовка) — для сообщения человеку.
|
||||
*/
|
||||
public static function rowCount(string $content): int
|
||||
{
|
||||
return max(0, substr_count($content, "\n") - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Убрать файлы старше стольких дней: выгрузка нужна один раз, а данные
|
||||
* в ней лежать вечно не должны.
|
||||
*/
|
||||
public static function purge(int $days): int
|
||||
{
|
||||
if ($days <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$edge = time() - $days * 86400;
|
||||
$removed = 0;
|
||||
|
||||
foreach ((array) glob(self::directory() . '/*.csv') as $file) {
|
||||
$file = (string) $file;
|
||||
|
||||
if (is_file($file) && filemtime($file) < $edge && @unlink($file)) {
|
||||
$removed++;
|
||||
}
|
||||
}
|
||||
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Где лежат готовые файлы.
|
||||
*/
|
||||
public static function directory(): string
|
||||
{
|
||||
return (string) Config::get('export.path', APP_ROOT . '/var/exports');
|
||||
}
|
||||
|
||||
/**
|
||||
* Значение поля и у модели, и у обычной строки запроса.
|
||||
*/
|
||||
private static function value(mixed $row, string $key): mixed
|
||||
{
|
||||
if ($row instanceof Model) {
|
||||
return $row->raw($key);
|
||||
}
|
||||
|
||||
if (is_array($row)) {
|
||||
return $row[$key] ?? '';
|
||||
}
|
||||
|
||||
return $row->{$key} ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Notifications\ExportReadyNotification;
|
||||
use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\Queue\Job;
|
||||
|
||||
/**
|
||||
* Готовит большую выгрузку в фоне и зовёт человека, когда файл готов.
|
||||
*
|
||||
* Запрос задаче не передашь — в очереди лежит JSON. Поэтому передаются имя
|
||||
* выгрузки из реестра (`Exports`) и параметры отбора, а запрос собирается
|
||||
* заново уже в воркере, от лица того, кто выгрузку заказал: чужие записи
|
||||
* не должны уехать в файл из-за того, что считает их воркер.
|
||||
*/
|
||||
final class ExportJob extends Job
|
||||
{
|
||||
public function attempts(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function handle(array $payload): void
|
||||
{
|
||||
$key = (string) ($payload['kind'] ?? '');
|
||||
$params = (array) ($payload['params'] ?? []);
|
||||
$userId = (int) ($payload['user_id'] ?? 0);
|
||||
|
||||
$kind = Exports::get($key);
|
||||
$user = User::find($userId);
|
||||
|
||||
if ($kind === null || $user === null) {
|
||||
(new Logger('export'))->warning('Выгрузку некому отдать', ['kind' => $key, 'user' => $userId]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$viewer = Viewer::fromUser($user);
|
||||
$query = Exports::query($key, array_map('strval', $params), $viewer);
|
||||
|
||||
if ($query === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$content = Csv::write(
|
||||
ExportFile::rows($query, $kind['columns']),
|
||||
ExportFile::headers($kind['columns'])
|
||||
);
|
||||
|
||||
$name = ExportFile::save($key, $content);
|
||||
|
||||
Audit::action('export', 0, 'подготовлена выгрузка «' . $kind['label'] . '»: ' . $name);
|
||||
|
||||
Notify::send($user, new ExportReadyNotification($kind['label'], $name, ExportFile::rowCount($content)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Query\Builder;
|
||||
|
||||
/**
|
||||
* Реестр выгрузок: что и как выгружать в фоне.
|
||||
*
|
||||
* Синхронная выгрузка (`Controller::exportCsv`) собирает файл в памяти и потому
|
||||
* ограничена `EXPORT_MAX_ROWS`. Большую выборку делает задача очереди, а ей
|
||||
* нельзя передать готовый запрос — только его имя и параметры. Отсюда реестр:
|
||||
*
|
||||
* Exports::register('users', 'Пользователи',
|
||||
* static fn (array $params, Viewer $viewer): Builder => User::query(),
|
||||
* ['login' => 'Логин', 'email' => 'Почта'],
|
||||
* Permission::USERS_MANAGE
|
||||
* );
|
||||
*
|
||||
* Свои выгрузки приложение дописывает в `config/exports.php`.
|
||||
*/
|
||||
final class Exports
|
||||
{
|
||||
/** @var array<string, array{label: string, query: callable, columns: array<string, mixed>, permission: string}>|null */
|
||||
private static ?array $kinds = null;
|
||||
|
||||
/**
|
||||
* @param callable(array<string, string>, Viewer): Builder $query
|
||||
* @param array<string, string|array{0: string, 1: callable}> $columns
|
||||
*/
|
||||
public static function register(string $key, string $label, callable $query, array $columns, string $permission = ''): void
|
||||
{
|
||||
self::boot();
|
||||
|
||||
self::$kinds[$key] = [
|
||||
'label' => $label,
|
||||
'query' => $query,
|
||||
'columns' => $columns,
|
||||
'permission' => $permission,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, query: callable, columns: array<string, mixed>, permission: string}>
|
||||
*/
|
||||
public static function all(): array
|
||||
{
|
||||
self::boot();
|
||||
|
||||
return self::$kinds ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{label: string, query: callable, columns: array<string, mixed>, permission: string}|null
|
||||
*/
|
||||
public static function get(string $key): ?array
|
||||
{
|
||||
return self::all()[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Запрос выгрузки с теми же параметрами, что были на экране.
|
||||
*
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
public static function query(string $key, array $params, Viewer $viewer): ?Builder
|
||||
{
|
||||
$kind = self::get($key);
|
||||
|
||||
return $kind === null ? null : ($kind['query'])($params, $viewer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Забыть реестр — нужно тестам.
|
||||
*/
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$kinds = null;
|
||||
}
|
||||
|
||||
private static function boot(): void
|
||||
{
|
||||
if (self::$kinds !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$kinds = [];
|
||||
|
||||
$file = APP_ROOT . '/config/exports.php';
|
||||
|
||||
if (is_file($file)) {
|
||||
require $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
+171
-37
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
@@ -23,64 +24,72 @@ use Throwable;
|
||||
* Одна плохая строка не отменяет весь файл: она попадает в отчёт с номером,
|
||||
* остальные загружаются. Номер строки — как в Excel, вместе с заголовком,
|
||||
* иначе искать ошибку в файле неудобно.
|
||||
*
|
||||
* Повторную загрузку того же файла спасает режим обновления: `locator` ищет
|
||||
* запись по ключу, и найденная не создаётся заново, а правится (`updater`).
|
||||
* Без него повторный файл просто задвоил бы данные.
|
||||
*
|
||||
* Перед загрузкой есть смысл посмотреть, что получится: `plan()` считает то же
|
||||
* самое, но ничего не пишет.
|
||||
*/
|
||||
final class Import
|
||||
{
|
||||
/**
|
||||
* Загрузка файла.
|
||||
*
|
||||
* @param array<string, string> $columns заголовок в файле => поле
|
||||
* @param array<string, string> $rules правила проверки полей
|
||||
* @param callable(array<string, mixed>, int): void $handler что делать со строкой
|
||||
* @param callable(array<string, mixed>, int): void $handler что делать с новой строкой
|
||||
* @param array<string, string> $labels подписи полей для сообщений об ошибках
|
||||
* @param callable(array<string, mixed>): ?Model $locator как найти уже существующую запись
|
||||
* @param callable(Model, array<string, mixed>): void $updater что делать с найденной
|
||||
*/
|
||||
public static function csv(string $content, array $columns, array $rules, callable $handler, array $labels = []): ImportReport
|
||||
{
|
||||
// Без подписей человек читал бы «поле title» — подставляем заголовки файла
|
||||
if ($labels === []) {
|
||||
$labels = array_flip($columns);
|
||||
public static function csv(
|
||||
string $content,
|
||||
array $columns,
|
||||
array $rules,
|
||||
callable $handler,
|
||||
array $labels = [],
|
||||
?callable $locator = null,
|
||||
?callable $updater = null
|
||||
): ImportReport {
|
||||
$prepared = self::prepare($content, $columns, $labels);
|
||||
|
||||
if (is_string($prepared)) {
|
||||
return new ImportReport(0, 0, [$prepared]);
|
||||
}
|
||||
|
||||
$rows = Csv::read($content);
|
||||
[$rows, $labels] = $prepared;
|
||||
|
||||
if ($rows === []) {
|
||||
return new ImportReport(0, 0, ['В файле нет ни одной строки с данными']);
|
||||
}
|
||||
|
||||
$limit = max(1, (int) Config::get('import.max_rows', 5000));
|
||||
|
||||
if (count($rows) > $limit) {
|
||||
return new ImportReport(0, 0, ['Строк в файле больше, чем разрешено за раз: ' . $limit]);
|
||||
}
|
||||
|
||||
$missing = self::missing($rows[0], $columns);
|
||||
|
||||
if ($missing !== []) {
|
||||
return new ImportReport(0, 0, ['В файле нет колонок: ' . implode(', ', $missing)]);
|
||||
}
|
||||
|
||||
$loaded = 0;
|
||||
$failed = 0;
|
||||
$errors = [];
|
||||
$loaded = 0;
|
||||
$updated = 0;
|
||||
$failed = 0;
|
||||
$errors = [];
|
||||
|
||||
foreach ($rows as $index => $row) {
|
||||
// Первая строка файла — заголовки, поэтому данные начинаются со второй
|
||||
$line = $index + 2;
|
||||
$data = self::map($row, $columns);
|
||||
|
||||
$data = [];
|
||||
$error = self::check($data, $rules, $labels);
|
||||
|
||||
foreach ($columns as $header => $field) {
|
||||
$data[$field] = $row[$header] ?? '';
|
||||
}
|
||||
|
||||
$validator = Validator::make($data, $rules, $labels);
|
||||
|
||||
if (!$validator->passes()) {
|
||||
if ($error !== '') {
|
||||
$failed++;
|
||||
$errors[] = 'Строка ' . $line . ': ' . self::first($validator->errors());
|
||||
$errors[] = 'Строка ' . $line . ': ' . $error;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$existing = $locator !== null ? $locator($data) : null;
|
||||
|
||||
if ($existing instanceof Model && $updater !== null) {
|
||||
$updater($existing, $data);
|
||||
|
||||
$updated++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$handler($data, $line);
|
||||
|
||||
$loaded++;
|
||||
@@ -90,7 +99,132 @@ final class Import
|
||||
}
|
||||
}
|
||||
|
||||
return new ImportReport($loaded, $failed, $errors);
|
||||
return new ImportReport($loaded, $failed, $errors, $updated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Что будет, если загрузить этот файл: ничего не пишется, только считается.
|
||||
*
|
||||
* @param array<string, string> $columns
|
||||
* @param array<string, string> $rules
|
||||
* @param array<string, string> $labels
|
||||
* @param callable(array<string, mixed>): ?Model $locator
|
||||
*/
|
||||
public static function plan(
|
||||
string $content,
|
||||
array $columns,
|
||||
array $rules,
|
||||
array $labels = [],
|
||||
?callable $locator = null,
|
||||
int $show = 20
|
||||
): ImportPlan {
|
||||
$prepared = self::prepare($content, $columns, $labels);
|
||||
|
||||
if (is_string($prepared)) {
|
||||
return new ImportPlan(0, 0, 0, [], [$prepared]);
|
||||
}
|
||||
|
||||
[$rows, $labels] = $prepared;
|
||||
|
||||
$create = 0;
|
||||
$update = 0;
|
||||
$failed = 0;
|
||||
$sample = [];
|
||||
$errors = [];
|
||||
|
||||
foreach ($rows as $index => $row) {
|
||||
$line = $index + 2;
|
||||
$data = self::map($row, $columns);
|
||||
|
||||
$error = self::check($data, $rules, $labels);
|
||||
|
||||
if ($error !== '') {
|
||||
$failed++;
|
||||
$errors[] = 'Строка ' . $line . ': ' . $error;
|
||||
$verdict = ImportPlan::SKIP;
|
||||
} elseif ($locator !== null && $locator($data) instanceof Model) {
|
||||
$update++;
|
||||
$verdict = ImportPlan::UPDATE;
|
||||
} else {
|
||||
$create++;
|
||||
$verdict = ImportPlan::CREATE;
|
||||
}
|
||||
|
||||
if (count($sample) < max(1, $show)) {
|
||||
$sample[] = ['line' => $line, 'verdict' => $verdict, 'data' => $data, 'error' => $error];
|
||||
}
|
||||
}
|
||||
|
||||
return new ImportPlan($create, $update, $failed, $sample, $errors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Общая подготовка: разбор файла и проверки, после которых читать нечего.
|
||||
*
|
||||
* @param array<string, string> $columns
|
||||
* @param array<string, string> $labels
|
||||
*
|
||||
* @return string|array{0: array<int, array<string, string>>, 1: array<string, string>}
|
||||
*/
|
||||
private static function prepare(string $content, array $columns, array $labels): string|array
|
||||
{
|
||||
// Без подписей человек читал бы «поле title» — подставляем заголовки файла
|
||||
if ($labels === []) {
|
||||
$labels = array_flip($columns);
|
||||
}
|
||||
|
||||
$rows = Csv::read($content);
|
||||
|
||||
if ($rows === []) {
|
||||
return 'В файле нет ни одной строки с данными';
|
||||
}
|
||||
|
||||
$limit = max(1, (int) Config::get('import.max_rows', 5000));
|
||||
|
||||
if (count($rows) > $limit) {
|
||||
return 'Строк в файле больше, чем разрешено за раз: ' . $limit;
|
||||
}
|
||||
|
||||
$missing = self::missing($rows[0], $columns);
|
||||
|
||||
if ($missing !== []) {
|
||||
return 'В файле нет колонок: ' . implode(', ', $missing);
|
||||
}
|
||||
|
||||
return [$rows, $labels];
|
||||
}
|
||||
|
||||
/**
|
||||
* Строка файла в поля.
|
||||
*
|
||||
* @param array<string, string> $row
|
||||
* @param array<string, string> $columns
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function map(array $row, array $columns): array
|
||||
{
|
||||
$data = [];
|
||||
|
||||
foreach ($columns as $header => $field) {
|
||||
$data[$field] = $row[$header] ?? '';
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Первая ошибка строки или пустая строка, если всё в порядке.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param array<string, string> $rules
|
||||
* @param array<string, string> $labels
|
||||
*/
|
||||
private static function check(array $data, array $rules, array $labels): string
|
||||
{
|
||||
$validator = Validator::make($data, $rules, $labels);
|
||||
|
||||
return $validator->passes() ? '' : self::first($validator->errors());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
/**
|
||||
* Что получится, если загрузить файл: сколько записей заведётся, сколько
|
||||
* обновится и что отвалится. Ничего не пишет — это предпросмотр.
|
||||
*/
|
||||
final class ImportPlan
|
||||
{
|
||||
public const CREATE = 'create';
|
||||
public const UPDATE = 'update';
|
||||
public const SKIP = 'skip';
|
||||
|
||||
/** @var array<string, string> Подписи для страницы */
|
||||
public const LABELS = [
|
||||
self::CREATE => 'заведём',
|
||||
self::UPDATE => 'обновим',
|
||||
self::SKIP => 'пропустим',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<int, array{line: int, verdict: string, data: array<string, mixed>, error: string}> $sample
|
||||
* @param array<int, string> $errors
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $create,
|
||||
public readonly int $update,
|
||||
public readonly int $failed,
|
||||
public readonly array $sample = [],
|
||||
public readonly array $errors = [],
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Есть ли что загружать.
|
||||
*/
|
||||
public function any(): bool
|
||||
{
|
||||
return $this->create > 0 || $this->update > 0;
|
||||
}
|
||||
|
||||
public function total(): int
|
||||
{
|
||||
return $this->create + $this->update + $this->failed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Строка для кнопки и сообщения.
|
||||
*/
|
||||
public function summary(): string
|
||||
{
|
||||
if ($this->total() === 0) {
|
||||
return 'Загружать нечего';
|
||||
}
|
||||
|
||||
$parts = [];
|
||||
|
||||
if ($this->create > 0) {
|
||||
$parts[] = 'заведём ' . $this->create;
|
||||
}
|
||||
|
||||
if ($this->update > 0) {
|
||||
$parts[] = 'обновим ' . $this->update;
|
||||
}
|
||||
|
||||
if ($this->failed > 0) {
|
||||
$parts[] = 'пропустим ' . $this->failed;
|
||||
}
|
||||
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
public static function label(string $verdict): string
|
||||
{
|
||||
return self::LABELS[$verdict] ?? $verdict;
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,13 @@ final class ImportReport
|
||||
public readonly int $loaded,
|
||||
public readonly int $failed,
|
||||
public readonly array $errors = [],
|
||||
public readonly int $updated = 0,
|
||||
) {
|
||||
}
|
||||
|
||||
public function ok(): bool
|
||||
{
|
||||
return $this->failed === 0 && $this->loaded > 0;
|
||||
return $this->failed === 0 && ($this->loaded > 0 || $this->updated > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -51,12 +52,20 @@ final class ImportReport
|
||||
*/
|
||||
public function summary(): string
|
||||
{
|
||||
if ($this->loaded === 0 && $this->failed === 0) {
|
||||
if ($this->loaded === 0 && $this->updated === 0 && $this->failed === 0) {
|
||||
return 'Из файла ничего не загружено';
|
||||
}
|
||||
|
||||
$text = 'Загружено строк: ' . $this->loaded;
|
||||
$parts = ['загружено: ' . $this->loaded];
|
||||
|
||||
return $this->failed > 0 ? $text . ', с ошибками: ' . $this->failed : $text;
|
||||
if ($this->updated > 0) {
|
||||
$parts[] = 'обновлено: ' . $this->updated;
|
||||
}
|
||||
|
||||
if ($this->failed > 0) {
|
||||
$parts[] = 'с ошибками: ' . $this->failed;
|
||||
}
|
||||
|
||||
return ucfirst(implode(', ', $parts));
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,18 @@ declare(strict_types=1);
|
||||
* @var \Rsgrinko\Proton\Support\Filters $filters
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Support\ImportPlan;
|
||||
use Rsgrinko\Proton\Support\ImportReport;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/** @var ImportReport|null $report отчёт после загрузки файла */
|
||||
$report = View::takeStash('import');
|
||||
|
||||
/** @var ImportPlan|null $plan что получится, если подтвердить загрузку */
|
||||
$plan = View::takeStash('import_plan');
|
||||
|
||||
/** @var string $planFile метка отложенного файла */
|
||||
$planFile = (string) View::takeStash('import_file', '');
|
||||
?>
|
||||
<div class="row">
|
||||
<h1 style="margin: 0;">Заметки</h1>
|
||||
@@ -44,14 +51,59 @@ $report = View::takeStash('import');
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($plan instanceof ImportPlan) { ?>
|
||||
<div class="card" style="border-color: var(--accent);">
|
||||
<h2>Что получится: <?= View::e($plan->summary()) ?></h2>
|
||||
|
||||
<?php if ($plan->sample !== []) { ?>
|
||||
<div class="table-wrap">
|
||||
<table class="list">
|
||||
<tr class="head">
|
||||
<th>Строка</th>
|
||||
<th>Что сделаем</th>
|
||||
<th>Название</th>
|
||||
<th class="hide-sm">Причина отказа</th>
|
||||
</tr>
|
||||
|
||||
<?php foreach ($plan->sample as $row) { ?>
|
||||
<tr>
|
||||
<td class="muted small"><?= (int) $row['line'] ?></td>
|
||||
<td>
|
||||
<span class="badge <?= $row['verdict'] === ImportPlan::SKIP ? 'error' : ($row['verdict'] === ImportPlan::UPDATE ? 'warn' : 'ok') ?>">
|
||||
<?= View::e(ImportPlan::label((string) $row['verdict'])) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td><?= View::e((string) ($row['data']['title'] ?? '')) ?></td>
|
||||
<td class="hide-sm muted small"><?= View::e((string) $row['error'] ?: '—') ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<?php if ($plan->total() > count($plan->sample)) { ?>
|
||||
<p class="muted small">Показаны первые <?= count($plan->sample) ?> строк из <?= $plan->total() ?>.</p>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($plan->any() && $planFile !== '') { ?>
|
||||
<form method="post" action="<?= View::e(View::route('notes.import.confirm')) ?>">
|
||||
<?= View::csrf() ?>
|
||||
<input type="hidden" name="file" value="<?= View::e($planFile) ?>">
|
||||
<button type="submit" class="primary">Загрузить</button>
|
||||
<span class="muted small">Файл уже у нас — присылать заново не нужно</span>
|
||||
</form>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if (View::can('notes.manage')) { ?>
|
||||
<div class="card">
|
||||
<h2>Загрузка из CSV</h2>
|
||||
|
||||
<p class="muted small">
|
||||
Колонки: <span class="mono">Название</span>, <span class="mono">Текст</span>,
|
||||
<span class="mono">Закреплена</span> — такие же, как в выгрузке. Плохая строка
|
||||
попадёт в отчёт, остальные загрузятся.
|
||||
<span class="mono">Закреплена</span> — такие же, как в выгрузке. Сначала покажем,
|
||||
что получится: заметка с тем же названием обновится, а не задвоится.
|
||||
</p>
|
||||
|
||||
<form method="post" action="<?= View::e(View::route('notes.import')) ?>" enctype="multipart/form-data">
|
||||
@@ -59,7 +111,7 @@ $report = View::takeStash('import');
|
||||
|
||||
<div class="row">
|
||||
<input type="file" name="file" accept=".csv,text/csv" required>
|
||||
<button type="submit" class="primary">Загрузить</button>
|
||||
<button type="submit" class="primary">Посмотреть, что получится</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,7 @@ declare(strict_types=1);
|
||||
*/
|
||||
|
||||
use App\Controllers\Web\AuthController;
|
||||
use App\Controllers\Web\ExportsController;
|
||||
use App\Controllers\Web\HomeController;
|
||||
use App\Controllers\Web\InstallController;
|
||||
use App\Controllers\Web\NotesController;
|
||||
@@ -53,6 +54,11 @@ return static function (Router $router): void {
|
||||
->middleware('signed')
|
||||
->name('notes.file.shared');
|
||||
|
||||
// Готовая фоновая выгрузка: только по подписанной ссылке из уведомления
|
||||
$router->get('/exports/{file}', [ExportsController::class, 'download'])
|
||||
->middleware('signed')
|
||||
->name('exports.download');
|
||||
|
||||
// Подтверждение почты открыто и вошедшему: письмо могли открыть позже
|
||||
$router->get('/verify/{token}', [RegisterController::class, 'verify'])->name('verify');
|
||||
|
||||
@@ -85,6 +91,7 @@ return static function (Router $router): void {
|
||||
$router->get('', [NotesController::class, 'index'])->middleware('can:notes.view')->name('notes.index');
|
||||
$router->get('/export', [NotesController::class, 'export'])->middleware('can:notes.view')->name('notes.export');
|
||||
$router->post('/import', [NotesController::class, 'import'])->middleware('can:notes.manage')->name('notes.import');
|
||||
$router->post('/import/confirm', [NotesController::class, 'importConfirm'])->middleware('can:notes.manage')->name('notes.import.confirm');
|
||||
$router->get('/new', [NotesController::class, 'create'])->middleware('can:notes.manage')->name('notes.create');
|
||||
$router->post('/new', [NotesController::class, 'store'])->middleware('can:notes.manage');
|
||||
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Предпросмотр импорта, обновление по ключу и фоновая выгрузка.
|
||||
*/
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Database\Model\Factory;
|
||||
use Rsgrinko\Proton\Models\Role;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Models\UserNotification;
|
||||
use Rsgrinko\Proton\Queue\Queue;
|
||||
use Rsgrinko\Proton\Queue\Worker;
|
||||
use Rsgrinko\Proton\Support\Csv;
|
||||
use Rsgrinko\Proton\Support\ExportFile;
|
||||
use Rsgrinko\Proton\Support\Exports;
|
||||
use Rsgrinko\Proton\Support\Import;
|
||||
use Rsgrinko\Proton\Support\ImportPlan;
|
||||
use Rsgrinko\Proton\Support\SignedUrl;
|
||||
|
||||
/**
|
||||
* Колонки и правила демонстрационного импорта заметок.
|
||||
*
|
||||
* @return array{0: array<string, string>, 1: array<string, string>}
|
||||
*/
|
||||
function notesImportSpec(): array
|
||||
{
|
||||
return [
|
||||
['Название' => 'title', 'Текст' => 'body'],
|
||||
['title' => 'required|max:191', 'body' => 'nullable|max:1000'],
|
||||
];
|
||||
}
|
||||
|
||||
test('предпросмотр: считает, что заведётся, что обновится и что отвалится', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $owner */
|
||||
$owner = Factory::of(User::class)->create();
|
||||
|
||||
Note::create(['title' => 'Уже есть', 'body' => 'старый текст'])
|
||||
->forceFill(['user_id' => $owner->id()])
|
||||
->save();
|
||||
|
||||
$content = Csv::write([
|
||||
['Уже есть', 'новый текст'],
|
||||
['Совсем новая', 'текст'],
|
||||
['', 'без названия'],
|
||||
], ['Название', 'Текст']);
|
||||
|
||||
[$columns, $rules] = notesImportSpec();
|
||||
|
||||
$plan = Import::plan($content, $columns, $rules, [], static fn (array $row): ?Note => Note::query()
|
||||
->where('user_id', $owner->id())
|
||||
->where('title', (string) $row['title'])
|
||||
->first());
|
||||
|
||||
assertSame(1, $plan->create);
|
||||
assertSame(1, $plan->update);
|
||||
assertSame(1, $plan->failed);
|
||||
assertSame(3, $plan->total());
|
||||
assertTrue($plan->any());
|
||||
assertCount(3, $plan->sample, 'в предпросмотре видно построчно');
|
||||
assertSame(ImportPlan::UPDATE, $plan->sample[0]['verdict']);
|
||||
assertSame(ImportPlan::SKIP, $plan->sample[2]['verdict']);
|
||||
|
||||
// Предпросмотр ничего не пишет
|
||||
assertSame(1, Note::query()->count());
|
||||
});
|
||||
});
|
||||
|
||||
test('импорт: повторная загрузка правит запись, а не двоит её', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $owner */
|
||||
$owner = Factory::of(User::class)->create();
|
||||
|
||||
[$columns, $rules] = notesImportSpec();
|
||||
|
||||
$locator = static fn (array $row): ?Note => Note::query()
|
||||
->where('user_id', $owner->id())
|
||||
->where('title', (string) $row['title'])
|
||||
->first();
|
||||
|
||||
$creator = static function (array $row) use ($owner): void {
|
||||
$note = new Note(['title' => (string) $row['title'], 'body' => (string) $row['body']]);
|
||||
|
||||
$note->setAttribute('user_id', $owner->id());
|
||||
$note->save();
|
||||
};
|
||||
|
||||
$updater = static function (Note $note, array $row): void {
|
||||
$note->fill(['body' => (string) $row['body']]);
|
||||
$note->save();
|
||||
};
|
||||
|
||||
$content = Csv::write([['Отчёт', 'первая версия']], ['Название', 'Текст']);
|
||||
|
||||
$first = Import::csv($content, $columns, $rules, $creator, [], $locator, $updater);
|
||||
|
||||
assertSame(1, $first->loaded);
|
||||
assertSame(0, $first->updated);
|
||||
|
||||
// Тот же файл со свежим текстом
|
||||
$again = Csv::write([['Отчёт', 'вторая версия']], ['Название', 'Текст']);
|
||||
|
||||
$second = Import::csv($again, $columns, $rules, $creator, [], $locator, $updater);
|
||||
|
||||
assertSame(0, $second->loaded);
|
||||
assertSame(1, $second->updated);
|
||||
assertSame(1, Note::query()->count(), 'запись одна');
|
||||
assertSame('вторая версия', (string) Note::query()->first()?->body);
|
||||
assertContains('обновлено: 1', $second->summary());
|
||||
});
|
||||
});
|
||||
|
||||
test('выгрузка: слишком большая выборка уходит в очередь', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $admin */
|
||||
$admin = Factory::of(User::class)->create(['role_id' => Role::admin()?->id() ?? 0]);
|
||||
|
||||
Factory::of(User::class)->times(4)->create();
|
||||
|
||||
actingAs($admin);
|
||||
|
||||
withConfig(['export.max_rows' => 2], static function () use ($admin): void {
|
||||
$response = get('/admin/users/export');
|
||||
|
||||
assertStatus(302, $response);
|
||||
assertSame(1, Queue::stats()['queued'] ?? 0, 'задача поставлена');
|
||||
|
||||
// Воркер собирает файл и уведомляет заказчика
|
||||
(new Worker())->run(true);
|
||||
|
||||
$notification = UserNotification::query()
|
||||
->where('user_id', $admin->id())
|
||||
->where('type', 'export.ready')
|
||||
->first();
|
||||
|
||||
assertNotNull($notification, 'пришло уведомление о готовой выгрузке');
|
||||
|
||||
$url = (string) $notification->raw('url');
|
||||
$name = [];
|
||||
|
||||
preg_match('~/exports/([^?]+)~', $url, $name);
|
||||
|
||||
assertTrue(($name[1] ?? '') !== '', 'в ссылке есть имя файла');
|
||||
assertNotNull(ExportFile::path(urldecode($name[1])), 'файл лежит в var/exports');
|
||||
});
|
||||
|
||||
actingAs(null);
|
||||
});
|
||||
});
|
||||
|
||||
test('выгрузка: готовый файл отдаётся только по подписи', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
$name = ExportFile::save('users', Csv::write([['ivan', 'ivan@example.com']], ['Логин', 'Почта']));
|
||||
|
||||
afterTests(static function () use ($name): void {
|
||||
$path = ExportFile::path($name);
|
||||
|
||||
if ($path !== null) {
|
||||
@unlink($path);
|
||||
}
|
||||
});
|
||||
|
||||
actingAs(null);
|
||||
|
||||
assertStatus(403, get('/exports/' . $name), 'без подписи нельзя');
|
||||
|
||||
$url = SignedUrl::to('exports.download', ['file' => $name], 3600);
|
||||
|
||||
parse_str((string) parse_url($url, PHP_URL_QUERY), $query);
|
||||
|
||||
$response = get('/exports/' . $name, $query);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertContains('ivan@example.com', $response->body());
|
||||
|
||||
// Чужое имя файла не подберёшь: путь проверяется
|
||||
assertNull(ExportFile::path('../../.env'));
|
||||
assertNull(ExportFile::path('нет-такого.csv'));
|
||||
});
|
||||
});
|
||||
|
||||
test('выгрузка: старые файлы убираются', function (): void {
|
||||
$name = ExportFile::save('users', "тест\n");
|
||||
$path = (string) ExportFile::path($name);
|
||||
|
||||
assertTrue(is_file($path));
|
||||
|
||||
// Отматываем время файла назад
|
||||
touch($path, time() - 10 * 86400);
|
||||
|
||||
assertTrue(ExportFile::purge(7) >= 1);
|
||||
assertNull(ExportFile::path($name));
|
||||
|
||||
// Ноль дней — уборка выключена
|
||||
assertSame(0, ExportFile::purge(0));
|
||||
});
|
||||
|
||||
test('реестр выгрузок: знает пользователей, журнал и заметки', function (): void {
|
||||
$kinds = Exports::all();
|
||||
|
||||
assertTrue(isset($kinds['users'], $kinds['audit'], $kinds['notes']));
|
||||
assertSame('Пользователи', $kinds['users']['label']);
|
||||
assertNull(Exports::get('нет-такой'));
|
||||
});
|
||||
Reference in new issue
Block a user