diff --git a/.env.example b/.env.example index ca0fe0b..024f0a4 100644 --- a/.env.example +++ b/.env.example @@ -93,6 +93,8 @@ UI_PER_PAGE=25 # Выгрузка списков в CSV: разделитель и предел строк на файл EXPORT_DELIMITER=; EXPORT_MAX_ROWS=20000 +# Сколько дней живут готовые файлы фоновых выгрузок +EXPORT_KEEP_DAYS=7 # Загрузка списков из CSV: сколько строк принимаем за раз IMPORT_MAX_ROWS=5000 diff --git a/app/Controllers/Admin/AuditController.php b/app/Controllers/Admin/AuditController.php index 5f44a76..dd1f0ce 100644 --- a/app/Controllers/Admin/AuditController.php +++ b/app/Controllers/Admin/AuditController.php @@ -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 diff --git a/app/Controllers/Admin/UsersController.php b/app/Controllers/Admin/UsersController.php index 0d5a4d3..4fe784d 100644 --- a/app/Controllers/Admin/UsersController.php +++ b/app/Controllers/Admin/UsersController.php @@ -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); } /** diff --git a/app/Controllers/Web/ExportsController.php b/app/Controllers/Web/ExportsController.php new file mode 100644 index 0000000..bfd7b51 --- /dev/null +++ b/app/Controllers/Web/ExportsController.php @@ -0,0 +1,31 @@ + '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 $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 $row + * + * @return array + */ + 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', [ diff --git a/config/config.php b/config/config.php index 3e88e05..3de15d0 100644 --- a/config/config.php +++ b/config/config.php @@ -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' => [ diff --git a/config/exports.php b/config/exports.php new file mode 100644 index 0000000..b00eed7 --- /dev/null +++ b/config/exports.php @@ -0,0 +1,98 @@ +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' +); diff --git a/framework/Http/Controller.php b/framework/Http/Controller.php index b88b005..9500860 100644 --- a/framework/Http/Controller.php +++ b/framework/Http/Controller.php @@ -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 $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'); diff --git a/framework/Notifications/ExportReadyNotification.php b/framework/Notifications/ExportReadyNotification.php new file mode 100644 index 0000000..e78a205 --- /dev/null +++ b/framework/Notifications/ExportReadyNotification.php @@ -0,0 +1,57 @@ +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 + */ + public function channels(): array + { + return [Notify::DATABASE, Notify::MAIL]; + } +} diff --git a/framework/Queue/Worker.php b/framework/Queue/Worker.php index 4cbb421..d661b40 100644 --- a/framework/Queue/Worker.php +++ b/framework/Queue/Worker.php @@ -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(); diff --git a/framework/Support/ExportFile.php b/framework/Support/ExportFile.php new file mode 100644 index 0000000..74fd56a --- /dev/null +++ b/framework/Support/ExportFile.php @@ -0,0 +1,150 @@ + $columns + * + * @return array + */ + public static function headers(array $columns): array + { + $headers = []; + + foreach ($columns as $column) { + $headers[] = is_array($column) ? $column[0] : $column; + } + + return $headers; + } + + /** + * Строки выгрузки. + * + * @param array $columns + * + * @return array> + */ + 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} ?? ''; + } +} diff --git a/framework/Support/ExportJob.php b/framework/Support/ExportJob.php new file mode 100644 index 0000000..9d2e384 --- /dev/null +++ b/framework/Support/ExportJob.php @@ -0,0 +1,64 @@ + $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))); + } +} diff --git a/framework/Support/Exports.php b/framework/Support/Exports.php new file mode 100644 index 0000000..5ab9053 --- /dev/null +++ b/framework/Support/Exports.php @@ -0,0 +1,98 @@ + User::query(), + * ['login' => 'Логин', 'email' => 'Почта'], + * Permission::USERS_MANAGE + * ); + * + * Свои выгрузки приложение дописывает в `config/exports.php`. + */ +final class Exports +{ + /** @var array, permission: string}>|null */ + private static ?array $kinds = null; + + /** + * @param callable(array, Viewer): Builder $query + * @param array $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, permission: string}> + */ + public static function all(): array + { + self::boot(); + + return self::$kinds ?? []; + } + + /** + * @return array{label: string, query: callable, columns: array, permission: string}|null + */ + public static function get(string $key): ?array + { + return self::all()[$key] ?? null; + } + + /** + * Запрос выгрузки с теми же параметрами, что были на экране. + * + * @param array $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; + } + } +} diff --git a/framework/Support/Import.php b/framework/Support/Import.php index cfc40d2..6e07815 100644 --- a/framework/Support/Import.php +++ b/framework/Support/Import.php @@ -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 $columns заголовок в файле => поле * @param array $rules правила проверки полей - * @param callable(array, int): void $handler что делать со строкой + * @param callable(array, int): void $handler что делать с новой строкой * @param array $labels подписи полей для сообщений об ошибках + * @param callable(array): ?Model $locator как найти уже существующую запись + * @param callable(Model, array): 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 $columns + * @param array $rules + * @param array $labels + * @param callable(array): ?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 $columns + * @param array $labels + * + * @return string|array{0: array>, 1: array} + */ + 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 $row + * @param array $columns + * + * @return array + */ + private static function map(array $row, array $columns): array + { + $data = []; + + foreach ($columns as $header => $field) { + $data[$field] = $row[$header] ?? ''; + } + + return $data; + } + + /** + * Первая ошибка строки или пустая строка, если всё в порядке. + * + * @param array $data + * @param array $rules + * @param array $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()); } /** diff --git a/framework/Support/ImportPlan.php b/framework/Support/ImportPlan.php new file mode 100644 index 0000000..9fe9d66 --- /dev/null +++ b/framework/Support/ImportPlan.php @@ -0,0 +1,80 @@ + Подписи для страницы */ + public const LABELS = [ + self::CREATE => 'заведём', + self::UPDATE => 'обновим', + self::SKIP => 'пропустим', + ]; + + /** + * @param array, error: string}> $sample + * @param array $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; + } +} diff --git a/framework/Support/ImportReport.php b/framework/Support/ImportReport.php index e378d25..c979475 100644 --- a/framework/Support/ImportReport.php +++ b/framework/Support/ImportReport.php @@ -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)); } } diff --git a/resources/views/notes/index.php b/resources/views/notes/index.php index bc180e9..cd5b13f 100644 --- a/resources/views/notes/index.php +++ b/resources/views/notes/index.php @@ -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', ''); ?>

Заметки

@@ -44,14 +51,59 @@ $report = View::takeStash('import');
+ +
+

Что получится: summary()) ?>

+ + sample !== []) { ?> +
+ + + + + + + + + sample as $row) { ?> + + + + + + + +
СтрокаЧто сделаемНазваниеПричина отказа
+ + + +
+
+ + total() > count($plan->sample)) { ?> +

Показаны первые sample) ?> строк из total() ?>.

+ + + + any() && $planFile !== '') { ?> +
+ + + + Файл уже у нас — присылать заново не нужно +
+ +
+ +

Загрузка из CSV

Колонки: Название, Текст, - Закреплена — такие же, как в выгрузке. Плохая строка - попадёт в отчёт, остальные загрузятся. + Закреплена — такие же, как в выгрузке. Сначала покажем, + что получится: заметка с тем же названием обновится, а не задвоится.

@@ -59,7 +111,7 @@ $report = View::takeStash('import');
- +
diff --git a/routes/web.php b/routes/web.php index 8477a0f..e66061d 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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'); diff --git a/tests/ImportExportTest.php b/tests/ImportExportTest.php new file mode 100644 index 0000000..d99f5b0 --- /dev/null +++ b/tests/ImportExportTest.php @@ -0,0 +1,207 @@ +, 1: array} + */ +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('нет-такой')); +});