From 603c7d29251f6bf1941fc0c92cdb07ed6ab7da7b Mon Sep 17 00:00:00 2001 From: Dhaverd Date: Sat, 28 Nov 2026 12:59:18 +0800 Subject: [PATCH] initial-commit --- README.md | 76 ++++++ app/Actions/Fortify/CreateNewUser.php | 33 +++ app/Actions/Fortify/ResetUserPassword.php | 29 ++ app/Concerns/PasswordValidationRules.php | 29 ++ app/Concerns/ProfileValidationRules.php | 52 ++++ app/Http/Controllers/Controller.php | 10 + app/Http/Controllers/MarkerController.php | 42 +++ app/Http/Controllers/PlannerController.php | 45 ++++ .../Settings/ProfileController.php | 52 ++++ .../Settings/SecurityController.php | 38 +++ .../Controllers/VacationPeriodController.php | 78 ++++++ app/Http/Middleware/HandleAppearance.php | 23 ++ app/Http/Middleware/HandleInertiaRequests.php | 46 ++++ .../Settings/PasswordUpdateRequest.php | 25 ++ .../Settings/ProfileDeleteRequest.php | 24 ++ .../Settings/ProfileUpdateRequest.php | 33 +++ app/Http/Requests/StoreMarkerRequest.php | 42 +++ app/Http/Requests/StorePeriodRequest.php | 50 ++++ app/Http/Requests/TogglePeriodRequest.php | 29 ++ app/Http/Requests/UpdateMarkerRequest.php | 32 +++ app/Http/Requests/UpdatePeriodRequest.php | 48 ++++ app/Models/Marker.php | 42 +++ app/Models/User.php | 59 ++++ app/Models/VacationPeriod.php | 55 ++++ app/Policies/MarkerPolicy.php | 24 ++ app/Policies/VacationPeriodPolicy.php | 24 ++ app/Providers/AppServiceProvider.php | 50 ++++ app/Providers/FortifyServiceProvider.php | 84 ++++++ app/Services/PeriodService.php | 105 ++++++++ artisan | 18 ++ bootstrap/app.php | 36 +++ bootstrap/cache/.gitignore | 2 + bootstrap/providers.php | 9 + components.json | 21 ++ composer.json | 115 ++++++++ config/app.php | 126 +++++++++ config/auth.php | 117 ++++++++ config/cache.php | 136 ++++++++++ config/database.php | 184 +++++++++++++ config/filesystems.php | 80 ++++++ config/fortify.php | 150 +++++++++++ config/inertia.php | 70 +++++ config/logging.php | 140 ++++++++++ config/mail.php | 118 ++++++++ config/queue.php | 129 +++++++++ config/services.php | 38 +++ config/session.php | 233 ++++++++++++++++ database/.gitignore | 1 + database/factories/MarkerFactory.php | 25 ++ database/factories/UserFactory.php | 45 ++++ database/factories/VacationPeriodFactory.php | 31 +++ .../0001_01_01_000000_create_users_table.php | 49 ++++ .../0001_01_01_000001_create_cache_table.php | 35 +++ .../0001_01_01_000002_create_jobs_table.php | 59 ++++ ...2026_11_27_000001_create_markers_table.php | 26 ++ ...7_000002_create_vacation_periods_table.php | 27 ++ database/seeders/DatabaseSeeder.php | 63 +++++ lang/ru.json | 12 + lang/ru/auth.php | 7 + lang/ru/passwords.php | 9 + lang/ru/validation.php | 120 +++++++++ package.json | 62 +++++ phpstan.neon | 13 + phpunit.xml | 36 +++ pint.json | 3 + pnpm-workspace.yaml | 5 + public/.htaccess | 25 ++ public/apple-touch-icon.png | Bin 0 -> 1662 bytes public/favicon.ico | Bin 0 -> 4286 bytes public/favicon.svg | 1 + public/index.php | 20 ++ public/robots.txt | 2 + resources/css/app.css | 143 ++++++++++ resources/js/app.tsx | 38 +++ resources/js/components/alert-error.tsx | 24 ++ resources/js/components/app-logo-icon.tsx | 26 ++ resources/js/components/app-logo.tsx | 20 ++ resources/js/components/appearance-tabs.tsx | 45 ++++ resources/js/components/delete-user.tsx | 120 +++++++++ resources/js/components/heading.tsx | 26 ++ resources/js/components/input-error.tsx | 17 ++ resources/js/components/password-input.tsx | 37 +++ .../js/components/planner/day-dialog.tsx | 219 +++++++++++++++ .../js/components/planner/marker-dialog.tsx | 135 ++++++++++ .../js/components/planner/marker-panel.tsx | 179 ++++++++++++ .../js/components/planner/month-calendar.tsx | 154 +++++++++++ .../js/components/planner/year-select.tsx | 44 +++ resources/js/components/text-link.tsx | 23 ++ resources/js/components/ui/alert.tsx | 66 +++++ resources/js/components/ui/avatar.tsx | 51 ++++ resources/js/components/ui/badge.tsx | 46 ++++ resources/js/components/ui/button.tsx | 58 ++++ resources/js/components/ui/checkbox.tsx | 30 +++ resources/js/components/ui/dialog.tsx | 133 +++++++++ resources/js/components/ui/dropdown-menu.tsx | 255 ++++++++++++++++++ resources/js/components/ui/input.tsx | 21 ++ resources/js/components/ui/label.tsx | 22 ++ resources/js/components/ui/select.tsx | 193 +++++++++++++ resources/js/components/ui/separator.tsx | 26 ++ resources/js/components/ui/sonner.tsx | 27 ++ resources/js/components/ui/spinner.tsx | 16 ++ resources/js/components/ui/tooltip.tsx | 55 ++++ resources/js/components/user-info.tsx | 32 +++ resources/js/components/user-menu-content.tsx | 58 ++++ resources/js/hooks/use-appearance.tsx | 115 ++++++++ resources/js/hooks/use-current-url.ts | 83 ++++++ resources/js/hooks/use-flash-toast.ts | 19 ++ resources/js/hooks/use-initials.tsx | 26 ++ resources/js/hooks/use-planner.ts | 227 ++++++++++++++++ resources/js/layouts/app-layout.tsx | 53 ++++ resources/js/layouts/auth-layout.tsx | 17 ++ .../js/layouts/auth/auth-simple-layout.tsx | 38 +++ resources/js/layouts/settings/layout.tsx | 78 ++++++ resources/js/lib/calendar.ts | 152 +++++++++++ resources/js/lib/marker-colors.ts | 35 +++ resources/js/lib/periods.ts | 91 +++++++ resources/js/lib/utils.ts | 12 + resources/js/pages/auth/confirm-password.tsx | 51 ++++ resources/js/pages/auth/forgot-password.tsx | 68 +++++ resources/js/pages/auth/login.tsx | 114 ++++++++ resources/js/pages/auth/register.tsx | 120 +++++++++ resources/js/pages/auth/reset-password.tsx | 96 +++++++ resources/js/pages/planner.tsx | 141 ++++++++++ resources/js/pages/settings/appearance.tsx | 22 ++ resources/js/pages/settings/profile.tsx | 95 +++++++ resources/js/pages/settings/security.tsx | 121 +++++++++ resources/js/types/auth.ts | 13 + resources/js/types/global.d.ts | 17 ++ resources/js/types/index.ts | 3 + resources/js/types/navigation.ts | 9 + resources/js/types/planner.ts | 19 ++ resources/js/types/ui.ts | 13 + resources/js/types/vite-env.d.ts | 1 + resources/views/app.blade.php | 48 ++++ routes/console.php | 8 + routes/settings.php | 24 ++ routes/web.php | 23 ++ storage/app/.gitignore | 4 + storage/app/private/.gitignore | 2 + storage/app/public/.gitignore | 2 + storage/framework/.gitignore | 10 + storage/framework/cache/.gitignore | 4 + storage/framework/cache/data/.gitignore | 2 + storage/framework/cache/locks/.gitignore | 2 + storage/framework/sessions/.gitignore | 2 + storage/framework/testing/.gitignore | 2 + storage/framework/views/.gitignore | 2 + storage/logs/.gitignore | 2 + tests/Feature/Auth/AuthenticationTest.php | 70 +++++ .../Feature/Auth/PasswordConfirmationTest.php | 33 +++ tests/Feature/Auth/PasswordResetTest.php | 95 +++++++ tests/Feature/Auth/RegistrationTest.php | 39 +++ tests/Feature/ExampleTest.php | 20 ++ tests/Feature/MarkerTest.php | 182 +++++++++++++ tests/Feature/Settings/ProfileUpdateTest.php | 123 +++++++++ tests/Feature/Settings/SecurityTest.php | 75 ++++++ tests/Feature/VacationPeriodTest.php | 159 +++++++++++ tests/TestCase.php | 16 ++ tests/Unit/ExampleTest.php | 16 ++ tests/Unit/PeriodServiceTest.php | 178 ++++++++++++ tsconfig.json | 120 +++++++++ vite.config.ts | 77 ++++++ 162 files changed, 9205 insertions(+) create mode 100644 README.md create mode 100755 app/Actions/Fortify/CreateNewUser.php create mode 100755 app/Actions/Fortify/ResetUserPassword.php create mode 100755 app/Concerns/PasswordValidationRules.php create mode 100755 app/Concerns/ProfileValidationRules.php create mode 100755 app/Http/Controllers/Controller.php create mode 100755 app/Http/Controllers/MarkerController.php create mode 100755 app/Http/Controllers/PlannerController.php create mode 100755 app/Http/Controllers/Settings/ProfileController.php create mode 100755 app/Http/Controllers/Settings/SecurityController.php create mode 100755 app/Http/Controllers/VacationPeriodController.php create mode 100755 app/Http/Middleware/HandleAppearance.php create mode 100755 app/Http/Middleware/HandleInertiaRequests.php create mode 100755 app/Http/Requests/Settings/PasswordUpdateRequest.php create mode 100755 app/Http/Requests/Settings/ProfileDeleteRequest.php create mode 100755 app/Http/Requests/Settings/ProfileUpdateRequest.php create mode 100755 app/Http/Requests/StoreMarkerRequest.php create mode 100755 app/Http/Requests/StorePeriodRequest.php create mode 100755 app/Http/Requests/TogglePeriodRequest.php create mode 100755 app/Http/Requests/UpdateMarkerRequest.php create mode 100755 app/Http/Requests/UpdatePeriodRequest.php create mode 100755 app/Models/Marker.php create mode 100755 app/Models/User.php create mode 100755 app/Models/VacationPeriod.php create mode 100755 app/Policies/MarkerPolicy.php create mode 100755 app/Policies/VacationPeriodPolicy.php create mode 100755 app/Providers/AppServiceProvider.php create mode 100755 app/Providers/FortifyServiceProvider.php create mode 100755 app/Services/PeriodService.php create mode 100755 artisan create mode 100755 bootstrap/app.php create mode 100755 bootstrap/cache/.gitignore create mode 100755 bootstrap/providers.php create mode 100755 components.json create mode 100755 composer.json create mode 100755 config/app.php create mode 100755 config/auth.php create mode 100755 config/cache.php create mode 100755 config/database.php create mode 100755 config/filesystems.php create mode 100755 config/fortify.php create mode 100755 config/inertia.php create mode 100755 config/logging.php create mode 100755 config/mail.php create mode 100755 config/queue.php create mode 100755 config/services.php create mode 100755 config/session.php create mode 100755 database/.gitignore create mode 100755 database/factories/MarkerFactory.php create mode 100755 database/factories/UserFactory.php create mode 100755 database/factories/VacationPeriodFactory.php create mode 100755 database/migrations/0001_01_01_000000_create_users_table.php create mode 100755 database/migrations/0001_01_01_000001_create_cache_table.php create mode 100755 database/migrations/0001_01_01_000002_create_jobs_table.php create mode 100755 database/migrations/2026_11_27_000001_create_markers_table.php create mode 100755 database/migrations/2026_11_27_000002_create_vacation_periods_table.php create mode 100755 database/seeders/DatabaseSeeder.php create mode 100755 lang/ru.json create mode 100755 lang/ru/auth.php create mode 100755 lang/ru/passwords.php create mode 100755 lang/ru/validation.php create mode 100755 package.json create mode 100755 phpstan.neon create mode 100755 phpunit.xml create mode 100755 pint.json create mode 100755 pnpm-workspace.yaml create mode 100755 public/.htaccess create mode 100755 public/apple-touch-icon.png create mode 100755 public/favicon.ico create mode 100755 public/favicon.svg create mode 100755 public/index.php create mode 100755 public/robots.txt create mode 100755 resources/css/app.css create mode 100755 resources/js/app.tsx create mode 100755 resources/js/components/alert-error.tsx create mode 100755 resources/js/components/app-logo-icon.tsx create mode 100755 resources/js/components/app-logo.tsx create mode 100755 resources/js/components/appearance-tabs.tsx create mode 100755 resources/js/components/delete-user.tsx create mode 100755 resources/js/components/heading.tsx create mode 100755 resources/js/components/input-error.tsx create mode 100755 resources/js/components/password-input.tsx create mode 100755 resources/js/components/planner/day-dialog.tsx create mode 100755 resources/js/components/planner/marker-dialog.tsx create mode 100755 resources/js/components/planner/marker-panel.tsx create mode 100755 resources/js/components/planner/month-calendar.tsx create mode 100755 resources/js/components/planner/year-select.tsx create mode 100755 resources/js/components/text-link.tsx create mode 100755 resources/js/components/ui/alert.tsx create mode 100755 resources/js/components/ui/avatar.tsx create mode 100755 resources/js/components/ui/badge.tsx create mode 100755 resources/js/components/ui/button.tsx create mode 100755 resources/js/components/ui/checkbox.tsx create mode 100755 resources/js/components/ui/dialog.tsx create mode 100755 resources/js/components/ui/dropdown-menu.tsx create mode 100755 resources/js/components/ui/input.tsx create mode 100755 resources/js/components/ui/label.tsx create mode 100755 resources/js/components/ui/select.tsx create mode 100755 resources/js/components/ui/separator.tsx create mode 100755 resources/js/components/ui/sonner.tsx create mode 100755 resources/js/components/ui/spinner.tsx create mode 100755 resources/js/components/ui/tooltip.tsx create mode 100755 resources/js/components/user-info.tsx create mode 100755 resources/js/components/user-menu-content.tsx create mode 100755 resources/js/hooks/use-appearance.tsx create mode 100755 resources/js/hooks/use-current-url.ts create mode 100755 resources/js/hooks/use-flash-toast.ts create mode 100755 resources/js/hooks/use-initials.tsx create mode 100755 resources/js/hooks/use-planner.ts create mode 100755 resources/js/layouts/app-layout.tsx create mode 100755 resources/js/layouts/auth-layout.tsx create mode 100755 resources/js/layouts/auth/auth-simple-layout.tsx create mode 100755 resources/js/layouts/settings/layout.tsx create mode 100755 resources/js/lib/calendar.ts create mode 100755 resources/js/lib/marker-colors.ts create mode 100755 resources/js/lib/periods.ts create mode 100755 resources/js/lib/utils.ts create mode 100755 resources/js/pages/auth/confirm-password.tsx create mode 100755 resources/js/pages/auth/forgot-password.tsx create mode 100755 resources/js/pages/auth/login.tsx create mode 100755 resources/js/pages/auth/register.tsx create mode 100755 resources/js/pages/auth/reset-password.tsx create mode 100755 resources/js/pages/planner.tsx create mode 100755 resources/js/pages/settings/appearance.tsx create mode 100755 resources/js/pages/settings/profile.tsx create mode 100755 resources/js/pages/settings/security.tsx create mode 100755 resources/js/types/auth.ts create mode 100755 resources/js/types/global.d.ts create mode 100755 resources/js/types/index.ts create mode 100755 resources/js/types/navigation.ts create mode 100755 resources/js/types/planner.ts create mode 100755 resources/js/types/ui.ts create mode 100755 resources/js/types/vite-env.d.ts create mode 100755 resources/views/app.blade.php create mode 100755 routes/console.php create mode 100755 routes/settings.php create mode 100755 routes/web.php create mode 100755 storage/app/.gitignore create mode 100755 storage/app/private/.gitignore create mode 100755 storage/app/public/.gitignore create mode 100755 storage/framework/.gitignore create mode 100755 storage/framework/cache/.gitignore create mode 100755 storage/framework/cache/data/.gitignore create mode 100755 storage/framework/cache/locks/.gitignore create mode 100755 storage/framework/sessions/.gitignore create mode 100755 storage/framework/testing/.gitignore create mode 100755 storage/framework/views/.gitignore create mode 100755 storage/logs/.gitignore create mode 100755 tests/Feature/Auth/AuthenticationTest.php create mode 100755 tests/Feature/Auth/PasswordConfirmationTest.php create mode 100755 tests/Feature/Auth/PasswordResetTest.php create mode 100755 tests/Feature/Auth/RegistrationTest.php create mode 100755 tests/Feature/ExampleTest.php create mode 100755 tests/Feature/MarkerTest.php create mode 100755 tests/Feature/Settings/ProfileUpdateTest.php create mode 100755 tests/Feature/Settings/SecurityTest.php create mode 100755 tests/Feature/VacationPeriodTest.php create mode 100755 tests/TestCase.php create mode 100755 tests/Unit/ExampleTest.php create mode 100755 tests/Unit/PeriodServiceTest.php create mode 100755 tsconfig.json create mode 100755 vite.config.ts diff --git a/README.md b/README.md new file mode 100644 index 0000000..b9e0927 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +# Vacation Planner + +Веб-приложение для визуального планирования отпусков с учётом отпусков других +людей (коллег, родственников и т.д.). + +Пользователь авторизуется, выбирает год и видит 12 календарей. «Маркеры» +(цвет + имя человека) используются как кисти: ими отмечаются отдельные дни и +периоды на календарях. Все маркеры и отметки хранятся в БД с привязкой к +пользователю. + +## Стек + +- Laravel 13, PHP 8.3+, MySQL +- Inertia v3 + React 19 + TypeScript +- Tailwind CSS 4 + shadcn/ui +- Fortify (регистрация, вход, сброс пароля), Wayfinder (типизированные роуты) + +## Запуск + +```bash +composer setup # зависимости, .env, key, миграции, npm install, build +``` + +Приложение обслуживается nginx + php-fpm (vhost `http://vacation-planner.localhost/`, +`APP_URL` в `.env`). Альтернатива для локальной разработки: `php artisan serve` +или `composer dev` (serve + vite dev с hot-reload). + +После изменения blade-шаблонов или прав пользователей выполняйте +`php artisan view:clear && php artisan view:cache`, чтобы кэш представлений был доступен +и веб-серверу, и CLI-пользователю. + +Демо-данные (пользователь `demo@example.com` / `password`, три маркера и +отпуска, включая период через границу года): + +```bash +php artisan migrate:fresh --seed +``` + +## Проверки + +```bash +composer test # Pint + PHPStan + PHPUnit +npm run check # линтер/форматтер фронтенда +npm run types:check # tsc --noEmit +npm run build # прод-сборка +``` + +Тесты используют отдельную БД `vacation_planner_test` (MySQL). + +## Модель данных + +- `markers` — `user_id`, `name` (уникально в рамках пользователя), `color` + (`#RRGGBB`). Лимит — 20 маркеров на пользователя. +- `vacation_periods` — `user_id`, `marker_id`, `start_date`, `end_date` + (`DATE`). Одиночный день: `start_date = end_date`. Периоды могут пересекать + границу года; выборка года — по пересечению диапазонов. + +Доменная логика (`App\Services\PeriodService`): + +- добавление диапазона сливает пересекающиеся и примыкающие периоды одного + маркера; +- клик по дню (toggle) снимает отметку (период в середине разрезается на два) + или ставит её со склейкой соседних; +- пересечения периодов **разных** маркеров допустимы — на календаре такой день + показывается диагональными полосами цветов. + +## Интерфейс + +- Выбор года: текущий ±5 лет. +- Панель маркеров: чипы с счётчиком дней за год, создание/редактирование + (фиксированная палитра из 12 цветов), удаление с подтверждением. +- Отметка дат: активный маркер = «кисть». Мышь — клик по дню или протяжка + диапазона; сенсорный экран — два касания (начало и конец). +- Клик по дню без кисти — диалог со списком отметок: редактирование границ и + маркера, удаление периода. +- Адаптивная сетка календарей: 1 / 2 / 3 / 4 колонки, светлая и тёмная темы. diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php new file mode 100755 index 0000000..3c7c00c --- /dev/null +++ b/app/Actions/Fortify/CreateNewUser.php @@ -0,0 +1,33 @@ + $input + */ + public function create(array $input): User + { + Validator::make($input, [ + ...$this->profileRules(), + 'password' => $this->passwordRules(), + ])->validate(); + + return User::create([ + 'name' => $input['name'], + 'email' => $input['email'], + 'password' => $input['password'], + ]); + } +} diff --git a/app/Actions/Fortify/ResetUserPassword.php b/app/Actions/Fortify/ResetUserPassword.php new file mode 100755 index 0000000..8fda5dd --- /dev/null +++ b/app/Actions/Fortify/ResetUserPassword.php @@ -0,0 +1,29 @@ + $input + */ + public function reset(User $user, array $input): void + { + Validator::make($input, [ + 'password' => $this->passwordRules(), + ])->validate(); + + $user->forceFill([ + 'password' => $input['password'], + ])->save(); + } +} diff --git a/app/Concerns/PasswordValidationRules.php b/app/Concerns/PasswordValidationRules.php new file mode 100755 index 0000000..7409ed8 --- /dev/null +++ b/app/Concerns/PasswordValidationRules.php @@ -0,0 +1,29 @@ +|string> + */ + protected function passwordRules(): array + { + return ['required', 'string', Password::default(), 'confirmed']; + } + + /** + * Get the validation rules used to validate the current password. + * + * @return array|string> + */ + protected function currentPasswordRules(): array + { + return ['required', 'string', 'current_password']; + } +} diff --git a/app/Concerns/ProfileValidationRules.php b/app/Concerns/ProfileValidationRules.php new file mode 100755 index 0000000..760e41e --- /dev/null +++ b/app/Concerns/ProfileValidationRules.php @@ -0,0 +1,52 @@ +|string>> + */ + protected function profileRules(?int $userId = null): array + { + return [ + 'name' => $this->nameRules(), + 'email' => $this->emailRules($userId), + ]; + } + + /** + * Get the validation rules used to validate user names. + * + * @return array|string> + */ + protected function nameRules(): array + { + return ['required', 'string', 'max:255']; + } + + /** + * Get the validation rules used to validate user emails. + * + * @return array|string> + */ + protected function emailRules(?int $userId = null): array + { + return [ + 'required', + 'string', + 'email', + 'max:255', + $userId === null + ? Rule::unique(User::class) + : Rule::unique(User::class)->ignore($userId), + ]; + } +} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php new file mode 100755 index 0000000..e7f7c94 --- /dev/null +++ b/app/Http/Controllers/Controller.php @@ -0,0 +1,10 @@ +user()->markers()->create($request->validated()); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Marker created.')]); + + return back(); + } + + public function update(UpdateMarkerRequest $request, Marker $marker): RedirectResponse + { + $marker->update($request->validated()); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Marker updated.')]); + + return back(); + } + + public function destroy(Request $request, Marker $marker): RedirectResponse + { + $this->authorize('delete', $marker); + + $marker->delete(); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Marker deleted.')]); + + return back(); + } +} diff --git a/app/Http/Controllers/PlannerController.php b/app/Http/Controllers/PlannerController.php new file mode 100755 index 0000000..c19c486 --- /dev/null +++ b/app/Http/Controllers/PlannerController.php @@ -0,0 +1,45 @@ +format('Y'); + $minYear = $currentYear - self::YEAR_SPAN; + $maxYear = $currentYear + self::YEAR_SPAN; + + $year = (int) $request->query('year', $currentYear); + + if ($year < $minYear || $year > $maxYear) { + $year = $currentYear; + } + + $user = $request->user(); + + $markers = $user->markers() + ->orderBy('id') + ->get(['id', 'name', 'color']); + + $periods = $user->vacationPeriods() + ->where('start_date', '<=', Carbon::create($year, 12, 31)->toDateString()) + ->where('end_date', '>=', Carbon::create($year, 1, 1)->toDateString()) + ->orderBy('start_date') + ->get(['id', 'marker_id', 'start_date', 'end_date']); + + return Inertia::render('planner', [ + 'year' => $year, + 'years' => range($minYear, $maxYear), + 'markers' => $markers, + 'periods' => $periods, + ]); + } +} diff --git a/app/Http/Controllers/Settings/ProfileController.php b/app/Http/Controllers/Settings/ProfileController.php new file mode 100755 index 0000000..31ec18a --- /dev/null +++ b/app/Http/Controllers/Settings/ProfileController.php @@ -0,0 +1,52 @@ +user()->fill($request->validated())->save(); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Profile updated.')]); + + return to_route('profile.edit'); + } + + /** + * Delete the user's profile. + */ + public function destroy(ProfileDeleteRequest $request): RedirectResponse + { + $user = $request->user(); + + Auth::logout(); + + $user->delete(); + + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return redirect('/'); + } +} diff --git a/app/Http/Controllers/Settings/SecurityController.php b/app/Http/Controllers/Settings/SecurityController.php new file mode 100755 index 0000000..04b4b14 --- /dev/null +++ b/app/Http/Controllers/Settings/SecurityController.php @@ -0,0 +1,38 @@ + Password::defaults()->toPasswordRulesString(), + ]); + } + + /** + * Update the user's password. + */ + public function update(PasswordUpdateRequest $request): RedirectResponse + { + $request->user()->update([ + 'password' => $request->password, + ]); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Password updated.')]); + + return back(); + } +} diff --git a/app/Http/Controllers/VacationPeriodController.php b/app/Http/Controllers/VacationPeriodController.php new file mode 100755 index 0000000..4dc1fef --- /dev/null +++ b/app/Http/Controllers/VacationPeriodController.php @@ -0,0 +1,78 @@ +integer('marker_id')); + + $this->periods->addRange( + $request->user(), + $marker, + CarbonImmutable::parse($request->input('start_date')), + CarbonImmutable::parse($request->input('end_date')), + ); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Period saved.')]); + + return back(); + } + + public function toggle(TogglePeriodRequest $request): RedirectResponse + { + $marker = Marker::findOrFail($request->integer('marker_id')); + + $this->periods->toggleDay( + $request->user(), + $marker, + CarbonImmutable::parse($request->input('date')), + ); + + return back(); + } + + public function update(UpdatePeriodRequest $request, VacationPeriod $period): RedirectResponse + { + $marker = $request->filled('marker_id') + ? Marker::findOrFail($request->integer('marker_id')) + : $period->marker; + + $this->periods->reschedule( + $request->user(), + $period, + $marker, + CarbonImmutable::parse($request->input('start_date')), + CarbonImmutable::parse($request->input('end_date')), + ); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Period saved.')]); + + return back(); + } + + public function destroy(Request $request, VacationPeriod $period): RedirectResponse + { + $this->authorize('delete', $period); + + $period->delete(); + + Inertia::flash('toast', ['type' => 'success', 'message' => __('Period deleted.')]); + + return back(); + } +} diff --git a/app/Http/Middleware/HandleAppearance.php b/app/Http/Middleware/HandleAppearance.php new file mode 100755 index 0000000..1a01684 --- /dev/null +++ b/app/Http/Middleware/HandleAppearance.php @@ -0,0 +1,23 @@ +cookie('appearance') ?? 'system'); + + return $next($request); + } +} diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php new file mode 100755 index 0000000..bdca0a8 --- /dev/null +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -0,0 +1,46 @@ + + */ + public function share(Request $request): array + { + return [ + ...parent::share($request), + 'name' => config('app.name'), + 'auth' => [ + 'user' => $request->user(), + ], + ]; + } +} diff --git a/app/Http/Requests/Settings/PasswordUpdateRequest.php b/app/Http/Requests/Settings/PasswordUpdateRequest.php new file mode 100755 index 0000000..0e5ff2f --- /dev/null +++ b/app/Http/Requests/Settings/PasswordUpdateRequest.php @@ -0,0 +1,25 @@ +|string> + */ + public function rules(): array + { + return [ + 'current_password' => $this->currentPasswordRules(), + 'password' => $this->passwordRules(), + ]; + } +} diff --git a/app/Http/Requests/Settings/ProfileDeleteRequest.php b/app/Http/Requests/Settings/ProfileDeleteRequest.php new file mode 100755 index 0000000..aec9174 --- /dev/null +++ b/app/Http/Requests/Settings/ProfileDeleteRequest.php @@ -0,0 +1,24 @@ +|string> + */ + public function rules(): array + { + return [ + 'password' => $this->currentPasswordRules(), + ]; + } +} diff --git a/app/Http/Requests/Settings/ProfileUpdateRequest.php b/app/Http/Requests/Settings/ProfileUpdateRequest.php new file mode 100755 index 0000000..9ef1731 --- /dev/null +++ b/app/Http/Requests/Settings/ProfileUpdateRequest.php @@ -0,0 +1,33 @@ +input('email'))) { + $this->merge(['email' => Str::lower($this->input('email'))]); + } + } + + /** + * Get the validation rules that apply to the request. + * + * @return array|string> + */ + public function rules(): array + { + return $this->profileRules($this->user()->id); + } +} diff --git a/app/Http/Requests/StoreMarkerRequest.php b/app/Http/Requests/StoreMarkerRequest.php new file mode 100755 index 0000000..f7bf7c5 --- /dev/null +++ b/app/Http/Requests/StoreMarkerRequest.php @@ -0,0 +1,42 @@ + + */ + public function rules(): array + { + return [ + 'name' => [ + 'required', + 'string', + 'max:50', + Rule::unique('markers', 'name')->where('user_id', $this->user()->id), + ], + 'color' => ['required', 'string', 'regex:/^#[0-9a-fA-F]{6}$/'], + ]; + } + + public function withValidator(Validator $validator): void + { + $validator->after(function ($validator) { + if ($this->user()->markers()->count() >= self::MAX_MARKERS) { + $validator->errors()->add('name', __('The marker limit has been reached.')); + } + }); + } +} diff --git a/app/Http/Requests/StorePeriodRequest.php b/app/Http/Requests/StorePeriodRequest.php new file mode 100755 index 0000000..773354e --- /dev/null +++ b/app/Http/Requests/StorePeriodRequest.php @@ -0,0 +1,50 @@ + + */ + public function rules(): array + { + return [ + 'marker_id' => [ + 'required', + 'integer', + Rule::exists('markers', 'id')->where('user_id', $this->user()->id), + ], + 'start_date' => ['required', 'date_format:Y-m-d'], + 'end_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:start_date'], + ]; + } + + public function withValidator(Validator $validator): void + { + $validator->after(function ($validator) { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $start = CarbonImmutable::parse($this->input('start_date')); + $end = CarbonImmutable::parse($this->input('end_date')); + + if ($start->diffInDays($end) + 1 > self::MAX_RANGE_DAYS) { + $validator->errors()->add('end_date', __('validation.max.string', ['attribute' => __('validation.attributes.end_date'), 'max' => self::MAX_RANGE_DAYS])); + } + }); + } +} diff --git a/app/Http/Requests/TogglePeriodRequest.php b/app/Http/Requests/TogglePeriodRequest.php new file mode 100755 index 0000000..5455025 --- /dev/null +++ b/app/Http/Requests/TogglePeriodRequest.php @@ -0,0 +1,29 @@ + + */ + public function rules(): array + { + return [ + 'marker_id' => [ + 'required', + 'integer', + Rule::exists('markers', 'id')->where('user_id', $this->user()->id), + ], + 'date' => ['required', 'date_format:Y-m-d'], + ]; + } +} diff --git a/app/Http/Requests/UpdateMarkerRequest.php b/app/Http/Requests/UpdateMarkerRequest.php new file mode 100755 index 0000000..ee1d806 --- /dev/null +++ b/app/Http/Requests/UpdateMarkerRequest.php @@ -0,0 +1,32 @@ +user()->can('update', $this->route('marker')); + } + + /** + * @return array + */ + public function rules(): array + { + return [ + 'name' => [ + 'required', + 'string', + 'max:50', + Rule::unique('markers', 'name') + ->where('user_id', $this->user()->id) + ->ignore($this->route('marker')), + ], + 'color' => ['required', 'string', 'regex:/^#[0-9a-fA-F]{6}$/'], + ]; + } +} diff --git a/app/Http/Requests/UpdatePeriodRequest.php b/app/Http/Requests/UpdatePeriodRequest.php new file mode 100755 index 0000000..513b001 --- /dev/null +++ b/app/Http/Requests/UpdatePeriodRequest.php @@ -0,0 +1,48 @@ +user()->can('update', $this->route('period')); + } + + /** + * @return array + */ + public function rules(): array + { + return [ + 'marker_id' => [ + 'sometimes', + 'integer', + Rule::exists('markers', 'id')->where('user_id', $this->user()->id), + ], + 'start_date' => ['required', 'date_format:Y-m-d'], + 'end_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:start_date'], + ]; + } + + public function withValidator(Validator $validator): void + { + $validator->after(function ($validator) { + if ($validator->errors()->isNotEmpty()) { + return; + } + + $start = CarbonImmutable::parse($this->input('start_date')); + $end = CarbonImmutable::parse($this->input('end_date')); + + if ($start->diffInDays($end) + 1 > StorePeriodRequest::MAX_RANGE_DAYS) { + $validator->errors()->add('end_date', __('validation.max.string', ['attribute' => __('validation.attributes.end_date'), 'max' => StorePeriodRequest::MAX_RANGE_DAYS])); + } + }); + } +} diff --git a/app/Models/Marker.php b/app/Models/Marker.php new file mode 100755 index 0000000..96eaa07 --- /dev/null +++ b/app/Models/Marker.php @@ -0,0 +1,42 @@ + */ + use HasFactory; + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * @return HasMany + */ + public function periods(): HasMany + { + return $this->hasMany(VacationPeriod::class); + } +} diff --git a/app/Models/User.php b/app/Models/User.php new file mode 100755 index 0000000..8deb544 --- /dev/null +++ b/app/Models/User.php @@ -0,0 +1,59 @@ + */ + use HasFactory, Notifiable; + + /** + * @return HasMany + */ + public function markers(): HasMany + { + return $this->hasMany(Marker::class); + } + + /** + * @return HasMany + */ + public function vacationPeriods(): HasMany + { + return $this->hasMany(VacationPeriod::class); + } + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'email_verified_at' => 'datetime', + 'password' => 'hashed', + ]; + } +} diff --git a/app/Models/VacationPeriod.php b/app/Models/VacationPeriod.php new file mode 100755 index 0000000..8ccf360 --- /dev/null +++ b/app/Models/VacationPeriod.php @@ -0,0 +1,55 @@ + */ + use HasFactory; + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * @return BelongsTo + */ + public function marker(): BelongsTo + { + return $this->belongsTo(Marker::class); + } + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'start_date' => 'date:Y-m-d', + 'end_date' => 'date:Y-m-d', + ]; + } +} diff --git a/app/Policies/MarkerPolicy.php b/app/Policies/MarkerPolicy.php new file mode 100755 index 0000000..cc536cb --- /dev/null +++ b/app/Policies/MarkerPolicy.php @@ -0,0 +1,24 @@ +id === $marker->user_id; + } + + public function update(User $user, Marker $marker): bool + { + return $user->id === $marker->user_id; + } + + public function delete(User $user, Marker $marker): bool + { + return $user->id === $marker->user_id; + } +} diff --git a/app/Policies/VacationPeriodPolicy.php b/app/Policies/VacationPeriodPolicy.php new file mode 100755 index 0000000..f95d096 --- /dev/null +++ b/app/Policies/VacationPeriodPolicy.php @@ -0,0 +1,24 @@ +id === $period->user_id; + } + + public function update(User $user, VacationPeriod $period): bool + { + return $user->id === $period->user_id; + } + + public function delete(User $user, VacationPeriod $period): bool + { + return $user->id === $period->user_id; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php new file mode 100755 index 0000000..f1525e9 --- /dev/null +++ b/app/Providers/AppServiceProvider.php @@ -0,0 +1,50 @@ +configureDefaults(); + } + + /** + * Configure default behaviors for production-ready applications. + */ + protected function configureDefaults(): void + { + Date::use(CarbonImmutable::class); + + DB::prohibitDestructiveCommands( + app()->isProduction(), + ); + + Password::defaults(fn (): ?Password => app()->isProduction() + ? Password::min(12) + ->mixedCase() + ->letters() + ->numbers() + ->symbols() + ->uncompromised() + : null, + ); + } +} diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php new file mode 100755 index 0000000..1771d39 --- /dev/null +++ b/app/Providers/FortifyServiceProvider.php @@ -0,0 +1,84 @@ +configureActions(); + $this->configureViews(); + $this->configureRateLimiting(); + } + + /** + * Configure Fortify actions. + */ + private function configureActions(): void + { + Fortify::resetUserPasswordsUsing(ResetUserPassword::class); + Fortify::createUsersUsing(CreateNewUser::class); + } + + /** + * Configure Fortify views. + */ + private function configureViews(): void + { + Fortify::loginView(fn (Request $request) => Inertia::render('auth/login', [ + 'canResetPassword' => Features::enabled(Features::resetPasswords()), + 'status' => $request->session()->get('status'), + ])); + + Fortify::resetPasswordView(fn (Request $request) => Inertia::render('auth/reset-password', [ + 'email' => $request->email, + 'token' => $request->route('token'), + 'passwordRules' => Password::defaults()->toPasswordRulesString(), + ])); + + Fortify::requestPasswordResetLinkView(fn (Request $request) => Inertia::render('auth/forgot-password', [ + 'status' => $request->session()->get('status'), + ])); + + Fortify::registerView(fn () => Inertia::render('auth/register', [ + 'passwordRules' => Password::defaults()->toPasswordRulesString(), + ])); + + Fortify::confirmPasswordView(fn () => Inertia::render('auth/confirm-password')); + } + + /** + * Configure rate limiting. + */ + private function configureRateLimiting(): void + { + RateLimiter::for('login', function (Request $request) { + $throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip()); + + return Limit::perMinute(5)->by($throttleKey); + }); + } +} diff --git a/app/Services/PeriodService.php b/app/Services/PeriodService.php new file mode 100755 index 0000000..bffa362 --- /dev/null +++ b/app/Services/PeriodService.php @@ -0,0 +1,105 @@ +periods() + ->where('start_date', '<=', $end->addDay()->toDateString()) + ->where('end_date', '>=', $start->subDay()->toDateString()) + ->get(); + + foreach ($neighbours as $neighbour) { + $start = $start->min(CarbonImmutable::parse($neighbour->start_date)); + $end = $end->max(CarbonImmutable::parse($neighbour->end_date)); + } + + $neighbours->each->delete(); + + return VacationPeriod::create([ + 'user_id' => $user->id, + 'marker_id' => $marker->id, + 'start_date' => $start->toDateString(), + 'end_date' => $end->toDateString(), + ]); + }); + } + + /** + * Toggle a single day for a marker: remove it if already marked + * (splitting the period when the day is in the middle), otherwise + * mark it (merging with neighbouring periods). + */ + public function toggleDay(User $user, Marker $marker, CarbonImmutable $date): void + { + DB::transaction(function () use ($user, $marker, $date) { + $period = $marker->periods() + ->where('start_date', '<=', $date->toDateString()) + ->where('end_date', '>=', $date->toDateString()) + ->first(); + + if ($period === null) { + $this->addRange($user, $marker, $date, $date); + + return; + } + + $start = CarbonImmutable::parse($period->start_date); + $end = CarbonImmutable::parse($period->end_date); + + if ($start->equalTo($date) && $end->equalTo($date)) { + $period->delete(); + + return; + } + + if ($start->equalTo($date)) { + $period->update(['start_date' => $date->addDay()->toDateString()]); + + return; + } + + if ($end->equalTo($date)) { + $period->update(['end_date' => $date->subDay()->toDateString()]); + + return; + } + + // Day is in the middle: split into two periods. + $period->update(['end_date' => $date->subDay()->toDateString()]); + + VacationPeriod::create([ + 'user_id' => $user->id, + 'marker_id' => $marker->id, + 'start_date' => $date->addDay()->toDateString(), + 'end_date' => $end->toDateString(), + ]); + }); + } + + /** + * Replace a period's range (and optionally its marker) with a new one, + * merging with the target marker's neighbouring periods. + */ + public function reschedule(User $user, VacationPeriod $period, Marker $marker, CarbonImmutable $start, CarbonImmutable $end): VacationPeriod + { + return DB::transaction(function () use ($user, $period, $marker, $start, $end) { + $period->delete(); + + return $this->addRange($user, $marker, $start, $end); + }); + } +} diff --git a/artisan b/artisan new file mode 100755 index 0000000..c35e31d --- /dev/null +++ b/artisan @@ -0,0 +1,18 @@ +#!/usr/bin/env php +handleCommand(new ArgvInput); + +exit($status); diff --git a/bootstrap/app.php b/bootstrap/app.php new file mode 100755 index 0000000..7d206fc --- /dev/null +++ b/bootstrap/app.php @@ -0,0 +1,36 @@ +withRouting( + web: __DIR__.'/../routes/web.php', + commands: __DIR__.'/../routes/console.php', + health: '/up', + ) + ->withMiddleware(function (Middleware $middleware): void { + $middleware->encryptCookies(except: ['appearance']); + + $middleware->web(append: [ + HandleAppearance::class, + HandleInertiaRequests::class, + AddLinkHeadersForPreloadedAssets::class, + ]); + }) + ->withExceptions(function (Exceptions $exceptions): void { + $exceptions->shouldRenderJsonWhen( + fn (Request $request) => $request->is('api/*') || $request->expectsJson(), + ); + })->create(); + +if (file_exists(dirname(__DIR__) . '/.env.local')) { + $app->loadEnvironmentFrom('.env.local'); +} + +return $app; diff --git a/bootstrap/cache/.gitignore b/bootstrap/cache/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/bootstrap/cache/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/bootstrap/providers.php b/bootstrap/providers.php new file mode 100755 index 0000000..5ffd769 --- /dev/null +++ b/bootstrap/providers.php @@ -0,0 +1,9 @@ + env('APP_NAME', 'Laravel'), + + /* + |-------------------------------------------------------------------------- + | Application Environment + |-------------------------------------------------------------------------- + | + | This value determines the "environment" your application is currently + | running in. This may determine how you prefer to configure various + | services the application utilizes. Set this in your ".env" file. + | + */ + + 'env' => env('APP_ENV', 'production'), + + /* + |-------------------------------------------------------------------------- + | Application Debug Mode + |-------------------------------------------------------------------------- + | + | When your application is in debug mode, detailed error messages with + | stack traces will be shown on every error that occurs within your + | application. If disabled, a simple generic error page is shown. + | + */ + + 'debug' => (bool) env('APP_DEBUG', false), + + /* + |-------------------------------------------------------------------------- + | Application URL + |-------------------------------------------------------------------------- + | + | This URL is used by the console to properly generate URLs when using + | the Artisan command line tool. You should set this to the root of + | the application so that it's available within Artisan commands. + | + */ + + 'url' => env('APP_URL', 'http://localhost'), + + /* + |-------------------------------------------------------------------------- + | Application Timezone + |-------------------------------------------------------------------------- + | + | Here you may specify the default timezone for your application, which + | will be used by the PHP date and date-time functions. The timezone + | is set to "UTC" by default as it is suitable for most use cases. + | + */ + + 'timezone' => 'UTC', + + /* + |-------------------------------------------------------------------------- + | Application Locale Configuration + |-------------------------------------------------------------------------- + | + | The application locale determines the default locale that will be used + | by Laravel's translation / localization methods. This option can be + | set to any locale for which you plan to have translation strings. + | + */ + + 'locale' => env('APP_LOCALE', 'en'), + + 'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'), + + 'faker_locale' => env('APP_FAKER_LOCALE', 'ru_RU'), + + /* + |-------------------------------------------------------------------------- + | Encryption Key + |-------------------------------------------------------------------------- + | + | This key is utilized by Laravel's encryption services and should be set + | to a random, 32 character string to ensure that all encrypted values + | are secure. You should do this prior to deploying the application. + | + */ + + 'cipher' => 'AES-256-CBC', + + 'key' => env('APP_KEY'), + + 'previous_keys' => [ + ...array_filter( + explode(',', (string) env('APP_PREVIOUS_KEYS', '')), + ), + ], + + /* + |-------------------------------------------------------------------------- + | Maintenance Mode Driver + |-------------------------------------------------------------------------- + | + | These configuration options determine the driver used to determine and + | manage Laravel's "maintenance mode" status. The "cache" driver will + | allow maintenance mode to be controlled across multiple machines. + | + | Supported drivers: "file", "cache", "array" + | + */ + + 'maintenance' => [ + 'driver' => env('APP_MAINTENANCE_DRIVER', 'file'), + 'store' => env('APP_MAINTENANCE_STORE', 'database'), + ], + +]; diff --git a/config/auth.php b/config/auth.php new file mode 100755 index 0000000..d7568ff --- /dev/null +++ b/config/auth.php @@ -0,0 +1,117 @@ + [ + 'guard' => env('AUTH_GUARD', 'web'), + 'passwords' => env('AUTH_PASSWORD_BROKER', 'users'), + ], + + /* + |-------------------------------------------------------------------------- + | Authentication Guards + |-------------------------------------------------------------------------- + | + | Next, you may define every authentication guard for your application. + | Of course, a great default configuration has been defined for you + | which utilizes session storage plus the Eloquent user provider. + | + | All authentication guards have a user provider, which defines how the + | users are actually retrieved out of your database or other storage + | system used by the application. Typically, Eloquent is utilized. + | + | Supported: "session" + | + */ + + 'guards' => [ + 'web' => [ + 'driver' => 'session', + 'provider' => 'users', + ], + ], + + /* + |-------------------------------------------------------------------------- + | User Providers + |-------------------------------------------------------------------------- + | + | All authentication guards have a user provider, which defines how the + | users are actually retrieved out of your database or other storage + | system used by the application. Typically, Eloquent is utilized. + | + | If you have multiple user tables or models you may configure multiple + | providers to represent the model / table. These providers may then + | be assigned to any extra authentication guards you have defined. + | + | Supported: "database", "eloquent" + | + */ + + 'providers' => [ + 'users' => [ + 'driver' => 'eloquent', + 'model' => env('AUTH_MODEL', User::class), + ], + + // 'users' => [ + // 'driver' => 'database', + // 'table' => 'users', + // ], + ], + + /* + |-------------------------------------------------------------------------- + | Resetting Passwords + |-------------------------------------------------------------------------- + | + | These configuration options specify the behavior of Laravel's password + | reset functionality, including the table utilized for token storage + | and the user provider that is invoked to actually retrieve users. + | + | The expiry time is the number of minutes that each reset token will be + | considered valid. This security feature keeps tokens short-lived so + | they have less time to be guessed. You may change this as needed. + | + | The throttle setting is the number of seconds a user must wait before + | generating more password reset tokens. This prevents the user from + | quickly generating a very large amount of password reset tokens. + | + */ + + 'passwords' => [ + 'users' => [ + 'provider' => 'users', + 'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'), + 'expire' => 60, + 'throttle' => 60, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Password Confirmation Timeout + |-------------------------------------------------------------------------- + | + | Here you may define the number of seconds before a password confirmation + | window expires and users are asked to re-enter their password via the + | confirmation screen. By default, the timeout lasts for three hours. + | + */ + + 'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800), + +]; diff --git a/config/cache.php b/config/cache.php new file mode 100755 index 0000000..d88a596 --- /dev/null +++ b/config/cache.php @@ -0,0 +1,136 @@ + env('CACHE_STORE', 'database'), + + /* + |-------------------------------------------------------------------------- + | Cache Stores + |-------------------------------------------------------------------------- + | + | Here you may define all of the cache "stores" for your application as + | well as their drivers. You may even define multiple stores for the + | same cache driver to group types of items stored in your caches. + | + | Supported drivers: "array", "database", "file", "memcached", + | "redis", "dynamodb", "storage", "octane", + | "session", "failover", "null" + | + */ + + 'stores' => [ + + 'array' => [ + 'driver' => 'array', + 'serialize' => false, + ], + + 'database' => [ + 'driver' => 'database', + 'connection' => env('DB_CACHE_CONNECTION'), + 'table' => env('DB_CACHE_TABLE', 'cache'), + 'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'), + 'lock_table' => env('DB_CACHE_LOCK_TABLE'), + ], + + 'file' => [ + 'driver' => 'file', + 'path' => storage_path('framework/cache/data'), + 'lock_path' => storage_path('framework/cache/locks'), + ], + + 'storage' => [ + 'driver' => 'storage', + 'disk' => env('CACHE_STORAGE_DISK'), + 'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'), + ], + + 'memcached' => [ + 'driver' => 'memcached', + 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), + 'sasl' => [ + env('MEMCACHED_USERNAME'), + env('MEMCACHED_PASSWORD'), + ], + 'options' => [ + // Memcached::OPT_CONNECT_TIMEOUT => 2000, + ], + 'servers' => [ + [ + 'host' => env('MEMCACHED_HOST', '127.0.0.1'), + 'port' => env('MEMCACHED_PORT', 11211), + 'weight' => 100, + ], + ], + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => env('REDIS_CACHE_CONNECTION', 'cache'), + 'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'), + ], + + 'dynamodb' => [ + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'endpoint' => env('DYNAMODB_ENDPOINT'), + ], + + 'octane' => [ + 'driver' => 'octane', + ], + + 'failover' => [ + 'driver' => 'failover', + 'stores' => [ + 'database', + 'array', + ], + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Cache Key Prefix + |-------------------------------------------------------------------------- + | + | When utilizing the APC, database, memcached, Redis, and DynamoDB cache + | stores, there might be other applications using the same cache. For + | that reason, you may prefix every cache key to avoid collisions. + | + */ + + 'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'), + + /* + |-------------------------------------------------------------------------- + | Serializable Classes + |-------------------------------------------------------------------------- + | + | This value determines the classes that can be unserialized from cache + | storage. By default, no PHP classes will be unserialized from your + | cache to prevent gadget chain attacks if your APP_KEY is leaked. + | + */ + + 'serializable_classes' => false, + +]; diff --git a/config/database.php b/config/database.php new file mode 100755 index 0000000..abbb88e --- /dev/null +++ b/config/database.php @@ -0,0 +1,184 @@ + env('DB_CONNECTION', 'sqlite'), + + /* + |-------------------------------------------------------------------------- + | Database Connections + |-------------------------------------------------------------------------- + | + | Below are all of the database connections defined for your application. + | An example configuration is provided for each database system which + | is supported by Laravel. You're free to add / remove connections. + | + */ + + 'connections' => [ + + 'sqlite' => [ + 'driver' => 'sqlite', + 'url' => env('DB_URL'), + 'database' => env('DB_DATABASE', database_path('database.sqlite')), + 'prefix' => '', + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + 'busy_timeout' => null, + 'journal_mode' => null, + 'synchronous' => null, + 'transaction_mode' => 'DEFERRED', + ], + + 'mysql' => [ + 'driver' => 'mysql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'mariadb' => [ + 'driver' => 'mariadb', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => env('DB_CHARSET', 'utf8mb4'), + 'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'), + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ], + + 'pgsql' => [ + 'driver' => 'pgsql', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '5432'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + 'search_path' => 'public', + 'sslmode' => env('DB_SSLMODE', 'prefer'), + ], + + 'sqlsrv' => [ + 'driver' => 'sqlsrv', + 'url' => env('DB_URL'), + 'host' => env('DB_HOST', 'localhost'), + 'port' => env('DB_PORT', '1433'), + 'database' => env('DB_DATABASE', 'laravel'), + 'username' => env('DB_USERNAME', 'root'), + 'password' => env('DB_PASSWORD', ''), + 'charset' => env('DB_CHARSET', 'utf8'), + 'prefix' => '', + 'prefix_indexes' => true, + // 'encrypt' => env('DB_ENCRYPT', 'yes'), + // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Migration Repository Table + |-------------------------------------------------------------------------- + | + | This table keeps track of all the migrations that have already run for + | your application. Using this information, we can determine which of + | the migrations on disk haven't actually been run on the database. + | + */ + + 'migrations' => [ + 'table' => 'migrations', + 'update_date_on_publish' => true, + ], + + /* + |-------------------------------------------------------------------------- + | Redis Databases + |-------------------------------------------------------------------------- + | + | Redis is an open source, fast, and advanced key-value store that also + | provides a richer body of commands than a typical key-value system + | such as Memcached. You may define your connection settings here. + | + */ + + 'redis' => [ + + 'client' => env('REDIS_CLIENT', 'phpredis'), + + 'options' => [ + 'cluster' => env('REDIS_CLUSTER', 'redis'), + 'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'), + 'persistent' => env('REDIS_PERSISTENT', false), + ], + + 'default' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_DB', '0'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + 'cache' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'port' => env('REDIS_PORT', '6379'), + 'database' => env('REDIS_CACHE_DB', '1'), + 'max_retries' => env('REDIS_MAX_RETRIES', 3), + 'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'), + 'backoff_base' => env('REDIS_BACKOFF_BASE', 100), + 'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000), + ], + + ], + +]; diff --git a/config/filesystems.php b/config/filesystems.php new file mode 100755 index 0000000..6cfdfb3 --- /dev/null +++ b/config/filesystems.php @@ -0,0 +1,80 @@ + env('FILESYSTEM_DISK', 'local'), + + /* + |-------------------------------------------------------------------------- + | Filesystem Disks + |-------------------------------------------------------------------------- + | + | Below you may configure as many filesystem disks as necessary, and you + | may even configure multiple disks for the same driver. Examples for + | most supported storage drivers are configured here for reference. + | + | Supported drivers: "local", "ftp", "sftp", "s3" + | + */ + + 'disks' => [ + + 'local' => [ + 'driver' => 'local', + 'root' => storage_path('app/private'), + 'serve' => true, + 'throw' => false, + 'report' => false, + ], + + 'public' => [ + 'driver' => 'local', + 'root' => storage_path('app/public'), + 'url' => rtrim((string) env('APP_URL', 'http://localhost'), '/').'/storage', + 'visibility' => 'public', + 'throw' => false, + 'report' => false, + ], + + 's3' => [ + 'driver' => 's3', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION'), + 'bucket' => env('AWS_BUCKET'), + 'url' => env('AWS_URL'), + 'endpoint' => env('AWS_ENDPOINT'), + 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), + 'throw' => false, + 'report' => false, + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Symbolic Links + |-------------------------------------------------------------------------- + | + | Here you may configure the symbolic links that will be created when the + | `storage:link` Artisan command is executed. The array keys should be + | the locations of the links and the values should be their targets. + | + */ + + 'links' => [ + public_path('storage') => storage_path('app/public'), + ], + +]; diff --git a/config/fortify.php b/config/fortify.php new file mode 100755 index 0000000..836da90 --- /dev/null +++ b/config/fortify.php @@ -0,0 +1,150 @@ + 'web', + + /* + |-------------------------------------------------------------------------- + | Fortify Password Broker + |-------------------------------------------------------------------------- + | + | Here you may specify which password broker Fortify can use when a user + | is resetting their password. This configured value should match one + | of your password brokers setup in your "auth" configuration file. + | + */ + + 'passwords' => 'users', + + /* + |-------------------------------------------------------------------------- + | Username / Email + |-------------------------------------------------------------------------- + | + | This value defines which model attribute should be considered as your + | application's "username" field. Typically, this might be the email + | address of the users but you are free to change this value here. + | + | Out of the box, Fortify expects forgot password and reset password + | requests to have a field named 'email'. If the application uses + | another name for the field you may define it below as needed. + | + */ + + 'username' => 'email', + + 'email' => 'email', + + /* + |-------------------------------------------------------------------------- + | Lowercase Usernames + |-------------------------------------------------------------------------- + | + | This value defines whether usernames should be lowercased before saving + | them in the database, as some database system string fields are case + | sensitive. You may disable this for your application if necessary. + | + */ + + 'lowercase_usernames' => true, + + /* + |-------------------------------------------------------------------------- + | Home Path + |-------------------------------------------------------------------------- + | + | Here you may configure the path where users will get redirected during + | authentication or password reset when the operations are successful + | and the user is authenticated. You are free to change this value. + | + */ + + 'home' => '/planner', + + /* + |-------------------------------------------------------------------------- + | Fortify Routes Prefix / Subdomain + |-------------------------------------------------------------------------- + | + | Here you may specify which prefix Fortify will assign to all the routes + | that it registers with the application. If necessary, you may change + | subdomain under which all of the Fortify routes will be available. + | + */ + + 'prefix' => '', + + 'domain' => null, + + /* + |-------------------------------------------------------------------------- + | Fortify Routes Middleware + |-------------------------------------------------------------------------- + | + | Here you may specify which middleware Fortify will assign to the routes + | that it registers with the application. If necessary, you may change + | these middleware but typically this provided default is preferred. + | + */ + + 'middleware' => ['web'], + + /* + |-------------------------------------------------------------------------- + | Rate Limiting + |-------------------------------------------------------------------------- + | + | By default, Fortify will throttle logins to five requests per minute for + | every email and IP address combination. However, if you would like to + | specify a custom rate limiter to call then you may specify it here. + | + */ + + 'limiters' => [ + 'login' => 'login', + ], + + /* + |-------------------------------------------------------------------------- + | Register View Routes + |-------------------------------------------------------------------------- + | + | Here you may specify if the routes returning views should be disabled as + | you may not need them when building your own application. This may be + | especially true if you're writing a custom single-page application. + | + */ + + 'views' => true, + + /* + |-------------------------------------------------------------------------- + | Features + |-------------------------------------------------------------------------- + | + | Some of the Fortify features are optional. You may disable the features + | by removing them from this array. You're free to only remove some of + | these features, or you can even remove all of these if you need to. + | + */ + + 'features' => [ + Features::registration(), + Features::resetPasswords(), + ], + +]; diff --git a/config/inertia.php b/config/inertia.php new file mode 100755 index 0000000..70f6b9b --- /dev/null +++ b/config/inertia.php @@ -0,0 +1,70 @@ + [ + 'enabled' => true, + 'url' => 'http://127.0.0.1:13714', + // 'bundle' => base_path('bootstrap/ssr/ssr.mjs'), + + ], + + /* + |-------------------------------------------------------------------------- + | Pages + |-------------------------------------------------------------------------- + | + | These options configure how Inertia discovers page components on the + | filesystem. The paths and extensions are used to locate components + | when rendering responses and during testing assertions. + | + */ + + 'pages' => [ + + 'paths' => [ + resource_path('js/pages'), + ], + + 'extensions' => [ + 'js', + 'jsx', + 'svelte', + 'ts', + 'tsx', + 'vue', + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Testing + |-------------------------------------------------------------------------- + | + | The values described here are used to locate Inertia components on the + | filesystem. For instance, when using `assertInertia`, the assertion + | attempts to locate the component as a file relative to the paths. + | + */ + + 'testing' => [ + + 'ensure_pages_exist' => true, + + ], + +]; diff --git a/config/logging.php b/config/logging.php new file mode 100755 index 0000000..97bdc03 --- /dev/null +++ b/config/logging.php @@ -0,0 +1,140 @@ + env('LOG_CHANNEL', 'stack'), + + /* + |-------------------------------------------------------------------------- + | Deprecations Log Channel + |-------------------------------------------------------------------------- + | + | This option controls the log channel that should be used to log warnings + | regarding deprecated PHP and library features. This allows you to get + | your application ready for upcoming major versions of dependencies. + | + */ + + 'deprecations' => [ + 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), + 'trace' => env('LOG_DEPRECATIONS_TRACE', false), + ], + + /* + |-------------------------------------------------------------------------- + | Log Channels + |-------------------------------------------------------------------------- + | + | Here you may configure the log channels for your application. Laravel + | utilizes the Monolog PHP logging library, which includes a variety + | of powerful log handlers and formatters that you're free to use. + | + | Available drivers: "single", "daily", "monthly", "slack", "syslog", + | "errorlog", "monolog", "custom", "stack" + | + */ + + 'channels' => [ + + 'stack' => [ + 'driver' => 'stack', + 'channels' => explode(',', (string) env('LOG_STACK', 'single')), + 'ignore_exceptions' => false, + ], + + 'single' => [ + 'driver' => 'single', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'replace_placeholders' => true, + ], + + 'daily' => [ + 'driver' => 'daily', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'max_files' => env('LOG_DAILY_DAYS', 14), + 'replace_placeholders' => true, + ], + + 'monthly' => [ + 'driver' => 'monthly', + 'path' => storage_path('logs/laravel.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'max_files' => 3, + 'replace_placeholders' => true, + ], + + 'slack' => [ + 'driver' => 'slack', + 'url' => env('LOG_SLACK_WEBHOOK_URL'), + 'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')), + 'emoji' => env('LOG_SLACK_EMOJI', ':boom:'), + 'level' => env('LOG_LEVEL', 'critical'), + 'replace_placeholders' => true, + ], + + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), + 'handler_with' => [ + 'host' => env('PAPERTRAIL_URL'), + 'port' => env('PAPERTRAIL_PORT'), + 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), + ], + 'processors' => [PsrLogMessageProcessor::class], + ], + + 'stderr' => [ + 'driver' => 'monolog', + 'level' => env('LOG_LEVEL', 'debug'), + 'handler' => StreamHandler::class, + 'handler_with' => [ + 'stream' => 'php://stderr', + ], + 'formatter' => env('LOG_STDERR_FORMATTER'), + 'processors' => [PsrLogMessageProcessor::class], + ], + + 'syslog' => [ + 'driver' => 'syslog', + 'level' => env('LOG_LEVEL', 'debug'), + 'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER), + 'replace_placeholders' => true, + ], + + 'errorlog' => [ + 'driver' => 'errorlog', + 'level' => env('LOG_LEVEL', 'debug'), + 'replace_placeholders' => true, + ], + + 'null' => [ + 'driver' => 'monolog', + 'handler' => NullHandler::class, + ], + + 'emergency' => [ + 'path' => storage_path('logs/laravel.log'), + ], + + ], + +]; diff --git a/config/mail.php b/config/mail.php new file mode 100755 index 0000000..e32e88d --- /dev/null +++ b/config/mail.php @@ -0,0 +1,118 @@ + env('MAIL_MAILER', 'log'), + + /* + |-------------------------------------------------------------------------- + | Mailer Configurations + |-------------------------------------------------------------------------- + | + | Here you may configure all of the mailers used by your application plus + | their respective settings. Several examples have been configured for + | you and you are free to add your own as your application requires. + | + | Laravel supports a variety of mail "transport" drivers that can be used + | when delivering an email. You may specify which one you're using for + | your mailers below. You may also add additional mailers if needed. + | + | Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2", + | "postmark", "resend", "log", "array", + | "failover", "roundrobin" + | + */ + + 'mailers' => [ + + 'smtp' => [ + 'transport' => 'smtp', + 'scheme' => env('MAIL_SCHEME'), + 'url' => env('MAIL_URL'), + 'host' => env('MAIL_HOST', '127.0.0.1'), + 'port' => env('MAIL_PORT', 2525), + 'username' => env('MAIL_USERNAME'), + 'password' => env('MAIL_PASSWORD'), + 'timeout' => null, + 'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)), + ], + + 'ses' => [ + 'transport' => 'ses', + ], + + 'postmark' => [ + 'transport' => 'postmark', + // 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'), + // 'client' => [ + // 'timeout' => 5, + // ], + ], + + 'resend' => [ + 'transport' => 'resend', + ], + + 'sendmail' => [ + 'transport' => 'sendmail', + 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), + ], + + 'log' => [ + 'transport' => 'log', + 'channel' => env('MAIL_LOG_CHANNEL'), + ], + + 'array' => [ + 'transport' => 'array', + ], + + 'failover' => [ + 'transport' => 'failover', + 'mailers' => [ + 'smtp', + 'log', + ], + 'retry_after' => 60, + ], + + 'roundrobin' => [ + 'transport' => 'roundrobin', + 'mailers' => [ + 'ses', + 'postmark', + ], + 'retry_after' => 60, + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Global "From" Address + |-------------------------------------------------------------------------- + | + | You may wish for all emails sent by your application to be sent from + | the same address. Here you may specify a name and address that is + | used globally for all emails that are sent by your application. + | + */ + + 'from' => [ + 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), + 'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')), + ], + +]; diff --git a/config/queue.php b/config/queue.php new file mode 100755 index 0000000..79c2c0a --- /dev/null +++ b/config/queue.php @@ -0,0 +1,129 @@ + env('QUEUE_CONNECTION', 'database'), + + /* + |-------------------------------------------------------------------------- + | Queue Connections + |-------------------------------------------------------------------------- + | + | Here you may configure the connection options for every queue backend + | used by your application. An example configuration is provided for + | each backend supported by Laravel. You're also free to add more. + | + | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", + | "deferred", "background", "failover", "null" + | + */ + + 'connections' => [ + + 'sync' => [ + 'driver' => 'sync', + ], + + 'database' => [ + 'driver' => 'database', + 'connection' => env('DB_QUEUE_CONNECTION'), + 'table' => env('DB_QUEUE_TABLE', 'jobs'), + 'queue' => env('DB_QUEUE', 'default'), + 'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90), + 'after_commit' => false, + ], + + 'beanstalkd' => [ + 'driver' => 'beanstalkd', + 'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'), + 'queue' => env('BEANSTALKD_QUEUE', 'default'), + 'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90), + 'block_for' => 0, + 'after_commit' => false, + ], + + 'sqs' => [ + 'driver' => 'sqs', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), + 'queue' => env('SQS_QUEUE', 'default'), + 'suffix' => env('SQS_SUFFIX'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'after_commit' => false, + ], + + 'redis' => [ + 'driver' => 'redis', + 'connection' => env('REDIS_QUEUE_CONNECTION', 'default'), + 'queue' => env('REDIS_QUEUE', 'default'), + 'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90), + 'block_for' => null, + 'after_commit' => false, + ], + + 'deferred' => [ + 'driver' => 'deferred', + ], + + 'background' => [ + 'driver' => 'background', + ], + + 'failover' => [ + 'driver' => 'failover', + 'connections' => [ + 'database', + 'deferred', + ], + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Job Batching + |-------------------------------------------------------------------------- + | + | The following options configure the database and table that store job + | batching information. These options can be updated to any database + | connection and table which has been defined by your application. + | + */ + + 'batching' => [ + 'database' => env('DB_CONNECTION', 'sqlite'), + 'table' => 'job_batches', + ], + + /* + |-------------------------------------------------------------------------- + | Failed Queue Jobs + |-------------------------------------------------------------------------- + | + | These options configure the behavior of failed queue job logging so you + | can control how and where failed jobs are stored. Laravel ships with + | support for storing failed jobs in a simple file or in a database. + | + | Supported drivers: "database-uuids", "dynamodb", "file", "null" + | + */ + + 'failed' => [ + 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), + 'database' => env('DB_CONNECTION', 'sqlite'), + 'table' => 'failed_jobs', + ], + +]; diff --git a/config/services.php b/config/services.php new file mode 100755 index 0000000..ec226a4 --- /dev/null +++ b/config/services.php @@ -0,0 +1,38 @@ + [ + 'key' => env('POSTMARK_API_KEY'), + ], + + 'resend' => [ + 'key' => env('RESEND_API_KEY'), + ], + + 'ses' => [ + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + ], + + 'slack' => [ + 'notifications' => [ + 'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'), + 'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'), + ], + ], + +]; diff --git a/config/session.php b/config/session.php new file mode 100755 index 0000000..e0c0eac --- /dev/null +++ b/config/session.php @@ -0,0 +1,233 @@ + env('SESSION_DRIVER', 'database'), + + /* + |-------------------------------------------------------------------------- + | Session Lifetime + |-------------------------------------------------------------------------- + | + | Here you may specify the number of minutes that you wish the session + | to be allowed to remain idle before it expires. If you want them + | to expire immediately when the browser is closed then you may + | indicate that via the expire_on_close configuration option. + | + */ + + 'lifetime' => (int) env('SESSION_LIFETIME', 120), + + 'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false), + + /* + |-------------------------------------------------------------------------- + | Session Encryption + |-------------------------------------------------------------------------- + | + | This option allows you to easily specify that all of your session data + | should be encrypted before it's stored. All encryption is performed + | automatically by Laravel and you may use the session like normal. + | + */ + + 'encrypt' => env('SESSION_ENCRYPT', false), + + /* + |-------------------------------------------------------------------------- + | Session File Location + |-------------------------------------------------------------------------- + | + | When utilizing the "file" session driver, the session files are placed + | on disk. The default storage location is defined here; however, you + | are free to provide another location where they should be stored. + | + */ + + 'files' => storage_path('framework/sessions'), + + /* + |-------------------------------------------------------------------------- + | Session Database Connection + |-------------------------------------------------------------------------- + | + | When using the "database" or "redis" session drivers, you may specify a + | connection that should be used to manage these sessions. This should + | correspond to a connection in your database configuration options. + | + */ + + 'connection' => env('SESSION_CONNECTION'), + + /* + |-------------------------------------------------------------------------- + | Session Database Table + |-------------------------------------------------------------------------- + | + | When using the "database" session driver, you may specify the table to + | be used to store sessions. Of course, a sensible default is defined + | for you; however, you're welcome to change this to another table. + | + */ + + 'table' => env('SESSION_TABLE', 'sessions'), + + /* + |-------------------------------------------------------------------------- + | Session Cache Store + |-------------------------------------------------------------------------- + | + | When using one of the framework's cache driven session backends, you may + | define the cache store which should be used to store the session data + | between requests. This must match one of your defined cache stores. + | + | Affects: "dynamodb", "memcached", "redis" + | + */ + + 'store' => env('SESSION_STORE'), + + /* + |-------------------------------------------------------------------------- + | Session Sweeping Lottery + |-------------------------------------------------------------------------- + | + | Some session drivers must manually sweep their storage location to get + | rid of old sessions from storage. Here are the chances that it will + | happen on a given request. By default, the odds are 2 out of 100. + | + */ + + 'lottery' => [2, 100], + + /* + |-------------------------------------------------------------------------- + | Session Cookie Name + |-------------------------------------------------------------------------- + | + | Here you may change the name of the session cookie that is created by + | the framework. Typically, you should not need to change this value + | since doing so does not grant a meaningful security improvement. + | + */ + + 'cookie' => env( + 'SESSION_COOKIE', + Str::slug((string) env('APP_NAME', 'laravel')).'-session', + ), + + /* + |-------------------------------------------------------------------------- + | Session Cookie Path + |-------------------------------------------------------------------------- + | + | The session cookie path determines the path for which the cookie will + | be regarded as available. Typically, this will be the root path of + | your application, but you're free to change this when necessary. + | + */ + + 'path' => env('SESSION_PATH', '/'), + + /* + |-------------------------------------------------------------------------- + | Session Cookie Domain + |-------------------------------------------------------------------------- + | + | This value determines the domain and subdomains the session cookie is + | available to. By default, the cookie will be available to the root + | domain without subdomains. Typically, this shouldn't be changed. + | + */ + + 'domain' => env('SESSION_DOMAIN'), + + /* + |-------------------------------------------------------------------------- + | HTTPS Only Cookies + |-------------------------------------------------------------------------- + | + | By setting this option to true, session cookies will only be sent back + | to the server if the browser has a HTTPS connection. This will keep + | the cookie from being sent to you when it can't be done securely. + | + */ + + 'secure' => env('SESSION_SECURE_COOKIE'), + + /* + |-------------------------------------------------------------------------- + | HTTP Access Only + |-------------------------------------------------------------------------- + | + | Setting this value to true will prevent JavaScript from accessing the + | value of the cookie and the cookie will only be accessible through + | the HTTP protocol. It's unlikely you should disable this option. + | + */ + + 'http_only' => env('SESSION_HTTP_ONLY', true), + + /* + |-------------------------------------------------------------------------- + | Same-Site Cookies + |-------------------------------------------------------------------------- + | + | This option determines how your cookies behave when cross-site requests + | take place, and can be used to mitigate CSRF attacks. By default, we + | will set this value to "lax" to permit secure cross-site requests. + | + | See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value + | + | Supported: "lax", "strict", "none", null + | + */ + + 'same_site' => env('SESSION_SAME_SITE', 'lax'), + + /* + |-------------------------------------------------------------------------- + | Partitioned Cookies + |-------------------------------------------------------------------------- + | + | Setting this value to true will tie the cookie to the top-level site for + | a cross-site context. Partitioned cookies are accepted by the browser + | when flagged "secure" and the Same-Site attribute is set to "none". + | + */ + + 'partitioned' => env('SESSION_PARTITIONED_COOKIE', false), + + /* + |-------------------------------------------------------------------------- + | Session Serialization + |-------------------------------------------------------------------------- + | + | This value controls the serialization strategy for session data, which + | is JSON by default. Setting this to "php" allows the storage of PHP + | objects in the session but can make an application vulnerable to + | "gadget chain" serialization attacks if the APP_KEY is leaked. + | + | Supported: "json", "php" + | + */ + + 'serialization' => 'json', + +]; diff --git a/database/.gitignore b/database/.gitignore new file mode 100755 index 0000000..9b19b93 --- /dev/null +++ b/database/.gitignore @@ -0,0 +1 @@ +*.sqlite* diff --git a/database/factories/MarkerFactory.php b/database/factories/MarkerFactory.php new file mode 100755 index 0000000..07f0b1c --- /dev/null +++ b/database/factories/MarkerFactory.php @@ -0,0 +1,25 @@ + + */ +class MarkerFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'name' => fake()->unique()->firstName(), + 'color' => fake()->safeHexColor(), + ]; + } +} diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php new file mode 100755 index 0000000..c4ceb07 --- /dev/null +++ b/database/factories/UserFactory.php @@ -0,0 +1,45 @@ + + */ +class UserFactory extends Factory +{ + /** + * The current password being used by the factory. + */ + protected static ?string $password; + + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->name(), + 'email' => fake()->unique()->safeEmail(), + 'email_verified_at' => now(), + 'password' => static::$password ??= Hash::make('password'), + 'remember_token' => Str::random(10), + ]; + } + + /** + * Indicate that the model's email address should be unverified. + */ + public function unverified(): static + { + return $this->state(fn (array $attributes) => [ + 'email_verified_at' => null, + ]); + } +} diff --git a/database/factories/VacationPeriodFactory.php b/database/factories/VacationPeriodFactory.php new file mode 100755 index 0000000..9d7c76b --- /dev/null +++ b/database/factories/VacationPeriodFactory.php @@ -0,0 +1,31 @@ + + */ +class VacationPeriodFactory extends Factory +{ + /** + * @return array + */ + public function definition(): array + { + $start = Carbon::instance(fake()->dateTimeBetween('first day of january this year', 'last day of december this year')); + $end = (clone $start)->addDays(fake()->numberBetween(0, 13)); + + return [ + 'user_id' => User::factory(), + 'marker_id' => Marker::factory(), + 'start_date' => $start->toDateString(), + 'end_date' => $end->toDateString(), + ]; + } +} diff --git a/database/migrations/0001_01_01_000000_create_users_table.php b/database/migrations/0001_01_01_000000_create_users_table.php new file mode 100755 index 0000000..05fb5d9 --- /dev/null +++ b/database/migrations/0001_01_01_000000_create_users_table.php @@ -0,0 +1,49 @@ +id(); + $table->string('name'); + $table->string('email')->unique(); + $table->timestamp('email_verified_at')->nullable(); + $table->string('password'); + $table->rememberToken(); + $table->timestamps(); + }); + + Schema::create('password_reset_tokens', function (Blueprint $table) { + $table->string('email')->primary(); + $table->string('token'); + $table->timestamp('created_at')->nullable(); + }); + + Schema::create('sessions', function (Blueprint $table) { + $table->string('id')->primary(); + $table->foreignId('user_id')->nullable()->index(); + $table->string('ip_address', 45)->nullable(); + $table->text('user_agent')->nullable(); + $table->longText('payload'); + $table->integer('last_activity')->index(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('users'); + Schema::dropIfExists('password_reset_tokens'); + Schema::dropIfExists('sessions'); + } +}; diff --git a/database/migrations/0001_01_01_000001_create_cache_table.php b/database/migrations/0001_01_01_000001_create_cache_table.php new file mode 100755 index 0000000..06dc7a5 --- /dev/null +++ b/database/migrations/0001_01_01_000001_create_cache_table.php @@ -0,0 +1,35 @@ +string('key')->primary(); + $table->mediumText('value'); + $table->bigInteger('expiration')->index(); + }); + + Schema::create('cache_locks', function (Blueprint $table) { + $table->string('key')->primary(); + $table->string('owner'); + $table->bigInteger('expiration')->index(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('cache'); + Schema::dropIfExists('cache_locks'); + } +}; diff --git a/database/migrations/0001_01_01_000002_create_jobs_table.php b/database/migrations/0001_01_01_000002_create_jobs_table.php new file mode 100755 index 0000000..edac6fe --- /dev/null +++ b/database/migrations/0001_01_01_000002_create_jobs_table.php @@ -0,0 +1,59 @@ +id(); + $table->string('queue')->index(); + $table->longText('payload'); + $table->unsignedSmallInteger('attempts'); + $table->unsignedInteger('reserved_at')->nullable(); + $table->unsignedInteger('available_at'); + $table->unsignedInteger('created_at'); + }); + + Schema::create('job_batches', function (Blueprint $table) { + $table->string('id')->primary(); + $table->string('name'); + $table->integer('total_jobs'); + $table->integer('pending_jobs'); + $table->integer('failed_jobs'); + $table->longText('failed_job_ids'); + $table->mediumText('options')->nullable(); + $table->integer('cancelled_at')->nullable(); + $table->integer('created_at'); + $table->integer('finished_at')->nullable(); + }); + + Schema::create('failed_jobs', function (Blueprint $table) { + $table->id(); + $table->string('uuid')->unique(); + $table->string('connection'); + $table->string('queue'); + $table->longText('payload'); + $table->longText('exception'); + $table->timestamp('failed_at')->useCurrent(); + + $table->index(['connection', 'queue', 'failed_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('jobs'); + Schema::dropIfExists('job_batches'); + Schema::dropIfExists('failed_jobs'); + } +}; diff --git a/database/migrations/2026_11_27_000001_create_markers_table.php b/database/migrations/2026_11_27_000001_create_markers_table.php new file mode 100755 index 0000000..cacd15a --- /dev/null +++ b/database/migrations/2026_11_27_000001_create_markers_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('name', 50); + $table->string('color', 7); + $table->timestamps(); + + $table->unique(['user_id', 'name']); + }); + } + + public function down(): void + { + Schema::dropIfExists('markers'); + } +}; diff --git a/database/migrations/2026_11_27_000002_create_vacation_periods_table.php b/database/migrations/2026_11_27_000002_create_vacation_periods_table.php new file mode 100755 index 0000000..2d7d214 --- /dev/null +++ b/database/migrations/2026_11_27_000002_create_vacation_periods_table.php @@ -0,0 +1,27 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->foreignId('marker_id')->constrained()->cascadeOnDelete(); + $table->date('start_date'); + $table->date('end_date'); + $table->timestamps(); + + $table->index(['user_id', 'start_date', 'end_date']); + }); + } + + public function down(): void + { + Schema::dropIfExists('vacation_periods'); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php new file mode 100755 index 0000000..d581598 --- /dev/null +++ b/database/seeders/DatabaseSeeder.php @@ -0,0 +1,63 @@ +create([ + 'name' => 'Demo User', + 'email' => 'demo@example.com', + ]); + + $year = (int) date('Y'); + + $me = Marker::factory()->for($user)->create([ + 'name' => 'Я', + 'color' => '#2563eb', + ]); + + $anna = Marker::factory()->for($user)->create([ + 'name' => 'Анна', + 'color' => '#db2777', + ]); + + $igor = Marker::factory()->for($user)->create([ + 'name' => 'Игорь', + 'color' => '#16a34a', + ]); + + VacationPeriod::factory()->for($user)->for($me)->create([ + 'start_date' => Carbon::create($year, 7, 6)->toDateString(), + 'end_date' => Carbon::create($year, 7, 19)->toDateString(), + ]); + + VacationPeriod::factory()->for($user)->for($me)->create([ + 'start_date' => Carbon::create($year, 12, 28)->toDateString(), + 'end_date' => Carbon::create($year + 1, 1, 8)->toDateString(), + ]); + + VacationPeriod::factory()->for($user)->for($anna)->create([ + 'start_date' => Carbon::create($year, 7, 13)->toDateString(), + 'end_date' => Carbon::create($year, 7, 26)->toDateString(), + ]); + + VacationPeriod::factory()->for($user)->for($igor)->create([ + 'start_date' => Carbon::create($year, 8, 3)->toDateString(), + 'end_date' => Carbon::create($year, 8, 9)->toDateString(), + ]); + } +} diff --git a/lang/ru.json b/lang/ru.json new file mode 100755 index 0000000..619ae96 --- /dev/null +++ b/lang/ru.json @@ -0,0 +1,12 @@ +{ + "Password updated.": "Пароль обновлён.", + "Profile updated.": "Профиль обновлён.", + "Marker created.": "Маркер добавлен.", + "Marker updated.": "Маркер обновлён.", + "Marker deleted.": "Маркер удалён.", + "Period saved.": "Отметка сохранена.", + "Period deleted.": "Период удалён.", + "The marker limit has been reached.": "Достигнут лимит маркеров.", + "This name is already taken.": "Маркер с таким именем уже существует.", + "You do not own this marker.": "Этот маркер вам не принадлежит." +} diff --git a/lang/ru/auth.php b/lang/ru/auth.php new file mode 100755 index 0000000..4403624 --- /dev/null +++ b/lang/ru/auth.php @@ -0,0 +1,7 @@ + 'Неверный email или пароль.', + 'password' => 'Неверный пароль.', + 'throttle' => 'Слишком много попыток входа. Повторите через :seconds секунд.', +]; diff --git a/lang/ru/passwords.php b/lang/ru/passwords.php new file mode 100755 index 0000000..3931302 --- /dev/null +++ b/lang/ru/passwords.php @@ -0,0 +1,9 @@ + 'Ваш пароль был сброшен.', + 'sent' => 'Ссылка для сброса пароля отправлена на ваш email.', + 'throttled' => 'Подождите перед повторной попыткой.', + 'token' => 'Недействительный токен сброса пароля.', + 'user' => 'Пользователь с таким email не найден.', +]; diff --git a/lang/ru/validation.php b/lang/ru/validation.php new file mode 100755 index 0000000..f32c530 --- /dev/null +++ b/lang/ru/validation.php @@ -0,0 +1,120 @@ + 'Вы должны принять :attribute.', + 'active_url' => 'Поле :attribute содержит недействительный URL.', + 'after' => 'Поле :attribute должно содержать дату после :date.', + 'after_or_equal' => 'Поле :attribute должно содержать дату не раньше :date.', + 'alpha' => 'Поле :attribute может содержать только буквы.', + 'alpha_dash' => 'Поле :attribute может содержать только буквы, цифры, дефисы и подчёркивания.', + 'alpha_num' => 'Поле :attribute может содержать только буквы и цифры.', + 'array' => 'Поле :attribute должно быть массивом.', + 'before' => 'Поле :attribute должно содержать дату до :date.', + 'before_or_equal' => 'Поле :attribute должно содержать дату не позже :date.', + 'between' => [ + 'array' => 'Количество элементов в поле :attribute должно быть от :min до :max.', + 'file' => 'Размер файла в поле :attribute должен быть от :min до :max Кб.', + 'numeric' => 'Поле :attribute должно быть между :min и :max.', + 'string' => 'Количество символов в поле :attribute должно быть от :min до :max.', + ], + 'boolean' => 'Поле :attribute должно иметь значение да или нет.', + 'confirmed' => 'Поле :attribute не совпадает с подтверждением.', + 'current_password' => 'Неверный текущий пароль.', + 'date' => 'Поле :attribute не является корректной датой.', + 'date_equals' => 'Поле :attribute должно содержать дату, равную :date.', + 'date_format' => 'Поле :attribute не соответствует формату :format.', + 'declined' => 'Вы должны отклонить :attribute.', + 'different' => 'Поля :attribute и :other должны различаться.', + 'digits' => 'Длина цифрового поля :attribute должна быть :digits.', + 'digits_between' => 'Длина цифрового поля :attribute должна быть от :min до :max.', + 'email' => 'Поле :attribute должно содержать корректный email.', + 'ends_with' => 'Поле :attribute должно заканчиваться одним из следующих значений: :values.', + 'exists' => 'Выбранное значение для :attribute некорректно.', + 'file' => 'Поле :attribute должно быть файлом.', + 'filled' => 'Поле :attribute обязательно для заполнения.', + 'gt' => [ + 'array' => 'Количество элементов в поле :attribute должно быть больше :value.', + 'file' => 'Размер файла в поле :attribute должен быть больше :value Кб.', + 'numeric' => 'Поле :attribute должно быть больше :value.', + 'string' => 'Количество символов в поле :attribute должно быть больше :value.', + ], + 'gte' => [ + 'array' => 'Количество элементов в поле :attribute должно быть не меньше :value.', + 'file' => 'Размер файла в поле :attribute должен быть не меньше :value Кб.', + 'numeric' => 'Поле :attribute должно быть не меньше :value.', + 'string' => 'Количество символов в поле :attribute должно быть не меньше :value.', + ], + 'image' => 'Поле :attribute должно быть изображением.', + 'in' => 'Выбранное значение для :attribute некорректно.', + 'integer' => 'Поле :attribute должно быть целым числом.', + 'ip' => 'Поле :attribute должно содержать корректный IP-адрес.', + 'json' => 'Поле :attribute должно содержать корректную JSON-строку.', + 'lowercase' => 'Поле :attribute должно быть в нижнем регистре.', + 'lt' => [ + 'array' => 'Количество элементов в поле :attribute должно быть меньше :value.', + 'file' => 'Размер файла в поле :attribute должен быть меньше :value Кб.', + 'numeric' => 'Поле :attribute должно быть меньше :value.', + 'string' => 'Количество символов в поле :attribute должно быть меньше :value.', + ], + 'lte' => [ + 'array' => 'Количество элементов в поле :attribute должно быть не больше :value.', + 'file' => 'Размер файла в поле :attribute должен быть не больше :value Кб.', + 'numeric' => 'Поле :attribute должно быть не больше :value.', + 'string' => 'Количество символов в поле :attribute должно быть не больше :value.', + ], + 'max' => [ + 'array' => 'Количество элементов в поле :attribute не может превышать :max.', + 'file' => 'Размер файла в поле :attribute не может превышать :max Кб.', + 'numeric' => 'Поле :attribute не может быть больше :max.', + 'string' => 'Количество символов в поле :attribute не может превышать :max.', + ], + 'mimes' => 'Поле :attribute должно быть файлом одного из типов: :values.', + 'min' => [ + 'array' => 'Количество элементов в поле :attribute должно быть не меньше :min.', + 'file' => 'Размер файла в поле :attribute должен быть не меньше :min Кб.', + 'numeric' => 'Поле :attribute должно быть не меньше :min.', + 'string' => 'Количество символов в поле :attribute должно быть не меньше :min.', + ], + 'missing' => 'Поле :attribute должно отсутствовать.', + 'not_in' => 'Выбранное значение для :attribute некорректно.', + 'not_regex' => 'Некорректный формат поля :attribute.', + 'numeric' => 'Поле :attribute должно быть числом.', + 'present' => 'Поле :attribute должно присутствовать.', + 'prohibited' => 'Поле :attribute запрещено.', + 'regex' => 'Некорректный формат поля :attribute.', + 'required' => 'Поле :attribute обязательно для заполнения.', + 'required_if' => 'Поле :attribute обязательно, когда :other равно :value.', + 'required_with' => 'Поле :attribute обязательно, когда указано :values.', + 'required_without' => 'Поле :attribute обязательно, когда не указано :values.', + 'same' => 'Значения полей :attribute и :other должны совпадать.', + 'size' => [ + 'array' => 'Количество элементов в поле :attribute должно быть равно :size.', + 'file' => 'Размер файла в поле :attribute должен быть равен :size Кб.', + 'numeric' => 'Поле :attribute должно быть равно :size.', + 'string' => 'Количество символов в поле :attribute должно быть равно :size.', + ], + 'starts_with' => 'Поле :attribute должно начинаться с одного из следующих значений: :values.', + 'string' => 'Поле :attribute должно быть строкой.', + 'timezone' => 'Поле :attribute должно содержать корректный часовой пояс.', + 'unique' => 'Такое значение поля :attribute уже занято.', + 'uploaded' => 'Не удалось загрузить файл в поле :attribute.', + 'uppercase' => 'Поле :attribute должно быть в верхнем регистре.', + 'url' => 'Поле :attribute должно содержать корректный URL.', + 'uuid' => 'Поле :attribute должно содержать корректный UUID.', + + 'custom' => [], + + 'attributes' => [ + 'name' => 'имя', + 'email' => 'email', + 'password' => 'пароль', + 'current_password' => 'текущий пароль', + 'password_confirmation' => 'подтверждение пароля', + 'color' => 'цвет', + 'start_date' => 'дата начала', + 'end_date' => 'дата окончания', + 'date' => 'дата', + 'marker_id' => 'маркер', + 'year' => 'год', + ], +]; diff --git a/package.json b/package.json new file mode 100755 index 0000000..80cf50f --- /dev/null +++ b/package.json @@ -0,0 +1,62 @@ +{ + "$schema": "https://www.schemastore.org/package.json", + "private": true, + "type": "module", + "scripts": { + "build": "vp build", + "build:ssr": "vp build && vp build --ssr", + "dev": "vp dev", + "check": "vp check", + "check:fix": "vp check --fix", + "types:check": "tsc --noEmit" + }, + "dependencies": { + "@inertiajs/react": "^3.0.0", + "@inertiajs/vite": "^3.0.0", + "@radix-ui/react-avatar": "^1.1.3", + "@radix-ui/react-checkbox": "^1.1.4", + "@radix-ui/react-dialog": "^1.1.6", + "@radix-ui/react-dropdown-menu": "^2.1.6", + "@radix-ui/react-label": "^2.1.2", + "@radix-ui/react-select": "^2.1.6", + "@radix-ui/react-separator": "^1.1.2", + "@radix-ui/react-slot": "^1.2.3", + "@radix-ui/react-tooltip": "^1.1.8", + "@tailwindcss/vite": "^4.1.11", + "@types/react": "^19.2.0", + "@types/react-dom": "^19.2.0", + "@vitejs/plugin-react": "^6.1.1", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "concurrently": "^10.0.3", + "laravel-vite-plugin": "^3.0.0", + "lucide-react": "^0.475.0", + "react": "^19.2.0", + "react-dom": "^19.2.0", + "sonner": "^2.0.0", + "tailwind-merge": "^3.0.1", + "tailwindcss": "^4.0.0", + "tw-animate-css": "^1.4.0", + "typescript": "^5.7.2", + "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0" + }, + "devDependencies": { + "@laravel/vite-plugin-wayfinder": "^0.1.3", + "@rolldown/plugin-babel": "^0.2.3", + "@types/node": "^22.13.5", + "babel-plugin-react-compiler": "^1.0.0", + "vite-plus": "1.4.0" + }, + "optionalDependencies": { + "@laravel/multiplex": "^0.4.1", + "@rollup/rollup-linux-x64-gnu": "4.9.5", + "@rollup/rollup-win32-x64-msvc": "4.9.5", + "@tailwindcss/oxide-linux-x64-gnu": "^4.0.1", + "@tailwindcss/oxide-win32-x64-msvc": "^4.0.1", + "lightningcss-linux-x64-gnu": "^1.29.1", + "lightningcss-win32-x64-msvc": "^1.29.1" + }, + "overrides": { + "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0" + } +} diff --git a/phpstan.neon b/phpstan.neon new file mode 100755 index 0000000..1ca23a4 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,13 @@ +includes: + - vendor/larastan/larastan/extension.neon + - vendor/nesbot/carbon/extension.neon + +parameters: + paths: + - app/ + - bootstrap/app.php + - config/ + - database/ + - routes/ + + level: 7 diff --git a/phpunit.xml b/phpunit.xml new file mode 100755 index 0000000..9e7845b --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,36 @@ + + + + + tests/Unit + + + tests/Feature + + + + + app + + + + + + + + + + + + + + + + + + + diff --git a/pint.json b/pint.json new file mode 100755 index 0000000..93061b6 --- /dev/null +++ b/pint.json @@ -0,0 +1,3 @@ +{ + "preset": "laravel" +} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100755 index 0000000..3d4f451 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,5 @@ +packages: + - '.' + +publicHoistPattern: + - '@inertiajs/core' diff --git a/public/.htaccess b/public/.htaccess new file mode 100755 index 0000000..a165eb1 --- /dev/null +++ b/public/.htaccess @@ -0,0 +1,25 @@ + + + Options -MultiViews -Indexes + + + RewriteEngine On + + # Handle Authorization Header + RewriteCond %{HTTP:Authorization} . + RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] + + # Handle X-XSRF-Token Header + RewriteCond %{HTTP:x-xsrf-token} . + RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}] + + # Redirect Trailing Slashes If Not A Folder... + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_URI} (.+)/$ + RewriteRule ^ %1 [L,R=308] + + # Send Requests To Front Controller... + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^ index.php [L] + diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100755 index 0000000000000000000000000000000000000000..c2efef6de4482ad4ec770787891fb3ab7f7b1f58 GIT binary patch literal 1662 zcmV-^27&pBP)40{{R3XI2D70000&P)t-s00030 zFd+XeApb8Q|1BW@E+GFcApbBR|1Kc^Eg=6bApb5P|1Kc^EFk|aApa~N|1BW@Eg=6e zApb5P|1BW@Eg&n7Ql0<+02OpnPE!CNzd)dXU=ZKm?|<)rkZ`ZhFmF)fpgb%900q`b zL_t(|+U%Oqj+-zLMaMYBBrGf>;s1ZNY7`jIiI_O8!Rm4!Tgf`>xtSR*$bTdkB!69t zVK_O-TcI8P=u%70x?P5+&ZXoke;#Hk@~pfohJ~`UXs9Q;_B2)gTk?{cvbc)et1K<* zr+Qaj9xAKsDzB#eYQpr7r@Sm0>dVCQfKCB0Kf{y|EP9n~<+TZwVye09V$sm9n9{PSY^C}VzXiE}GC#|%c)PWA z!&5y>`JP4VkDV6b8$Z_jJJu@A$QeFse^IT?qj=G4l>4y#(Kj|Guiq{iFk{=Fwl*76 z)xQ4|>IRkjy#1lI8JM_!yJWG>8ZJNf8dXXx zrk~GbPG4tWE+u0Q(BCgl#w@cPJ5nx)T9MuG26Ggy6OkTfT zvPjI^>P)^G7FA5^`aMfVOxu)|x2A9549ulPjgm!RI{t-}!yN(BSbnfZ0rTAmB^Yxa z0ShsC{k=0v223kLF@%7Hn5rZ4wL=GnpitveraoqSfe(_EIcO5du!CjnDf@wtxv3e z-u^bn6xYI{>k~_4b4*0{)`LMCWEV`GECi(~y~rMz#`428YDY}1JOdWj&DW^?F-Ib; zJl{lRfw{1#A0resWj2_y2v`;oie!a3x9HrIxnXL+G9OMEVvZJ7Q)Y@O(#)P#Gsb*Y zz6+8!=6Lpjd0-xx2j+o!U>=wU<`2TWpY@?U`fOKhgXs$-hQ`^*57T3Y7GFKsXEUm) zBmpLJD?F4LXCptnrod!)-s4>q&NlMH1ep8=0k2DW_S$RM1ei2s8;}?pXCpsMfQj(j zNDOf{^1}p}D=)N>81ii9hY2uO&CkS;XEQ%chDr0UB!)N}`C$S~^BV*vhRd^&A11-1 z`R$K=!+176!AgetySX#KX&8o~XtND<+Gs@?_dhEVl?dUf^KAF4`3KmZ#1o5M$8F`` z3P!Tl&&CLr3Ul6+|GA>4A2dj*!Zf~z9YX~DLkTA3XY8i74zs-cJ)DTceLfYYA-}08 zCfNm;#x)M#D5naO^M{f7;@Z>}U}BCre7ypnoy1IDM_|xHKkNy25-bsNjhURKb+p6ga^RJ>eNU6hI2E^Ow5A+W|JeZDC8Wqj7Y8Fr9@Uvc=cY`i& zDS4WCQI*lV*os&Gro@tzcjHTqy#y%$-R|Mc0;Z=P9R-{!<>DZ*bg~pkU*-o&W#<07*qo IM6N<$f;hnhc>n+a literal 0 HcmV?d00001 diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100755 index 0000000000000000000000000000000000000000..236fadb94188e9189807c50aa8480b3070a0cc8d GIT binary patch literal 4286 zcmcJSYiv|S6vqb^Sj9>!kD_?#USEjFuB*k05m`ulKhQ)0{ZR3Nj~ES!#h9qrHiD>$ zFCbA83#r6d--z!Q-dZre@B@j4kBxrw(=r7ZdN&YYP!=ggUN z&s>a|z(3zN`fK`{jA=H;%m+kf8A$GajE&{z=dAJbc7mU^S=a@A(CVLujIm?&L%;DC zLe@6JdI;b*I0WCqqi~9wGmd_s)3`n7>{QyT;Y-k-FM>{Z23kR}*bD8AB1Y}dT<%4|D*yFG{ipz1dZ-md_9asjFVAL*Xjeow=eI@kwWU_SmSU;ft*cgCUqSjPbCwmKa-bR^DI`k=CZ?Ca;^-d5Ll<&7I3$q~lW zumU~>#c()c$ zznq=I*j4Zy`~=s7e6N}x_jxK`Zh-@E10+?J+sM~|@>qVCnUcYu{D&HP^q=+0M}32-cM_!3Ciyi+W;gJQ1O$7`Uq{%qEf zQ&BAEGXHHD1l564qg*VjMHc7h8MJr9F#HPgp`07>0%S*IU-OwO9s`}T@>+3T1B!b* zKArZ1un%4W-3_mTYTL(f9k{v?=^U+ny>m|ylSw>PH%q64pG5ofa4((kv;&-?dWdAkLy`uhG@CDoiOQ8?+ z9kmLbnp3s^M6T<5NBhy**WqFab58X;{Fc}ICS9`EhD_t_k?aMYs+oF+X2x}$w)C!s zub>y+giUTd`u=o2$VPbg%w}A5K=FGP&VnVNeaN?!pjv4BMJ}c{)BXz-le3+UDBqmk zP^aQH6SlzLumSXcGEJ%aDelxC<@f^F20w!KrQDna?i}Mq^k;zX6#3f)bNvO(k)BF^ zHzB_V0(cothr0F?dSz!aw81>*Q(|8=^W<+HdO$YTVt*Rwysv=|;RCn=q%&SVZcpiq z>|ITJ5A23ruovR@SbG{bo3)A(@mAf`d#C(4&3${+iCyjbvGi?Vt?lZx!zN>grl)PO zquU0hL7OTS3ys0yLdGmDv^2C7yp|~iFVkJ{(t`!Bd#K \ No newline at end of file diff --git a/public/index.php b/public/index.php new file mode 100755 index 0000000..ee8f07e --- /dev/null +++ b/public/index.php @@ -0,0 +1,20 @@ +handleRequest(Request::capture()); diff --git a/public/robots.txt b/public/robots.txt new file mode 100755 index 0000000..eb05362 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: diff --git a/resources/css/app.css b/resources/css/app.css new file mode 100755 index 0000000..232663b --- /dev/null +++ b/resources/css/app.css @@ -0,0 +1,143 @@ +@import 'tailwindcss'; + +@import 'tw-animate-css'; + +@source '../views'; +@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php'; + +@custom-variant dark (&:is(.dark *)); + +@theme { + --font-sans: + 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, + 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', + 'Noto Color Emoji'; + + --radius-lg: var(--radius); + --radius-md: calc(var(--radius) - 2px); + --radius-sm: calc(var(--radius) - 4px); + + --color-background: var(--background); + --color-foreground: var(--foreground); + + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + + --color-chart-1: var(--chart-1); + --color-chart-2: var(--chart-2); + --color-chart-3: var(--chart-3); + --color-chart-4: var(--chart-4); + --color-chart-5: var(--chart-5); + + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); +} + +:root { + --background: oklch(1 0 0); + --foreground: oklch(0.145 0 0); + --card: oklch(1 0 0); + --card-foreground: oklch(0.145 0 0); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.145 0 0); + --primary: oklch(0.205 0 0); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.97 0 0); + --secondary-foreground: oklch(0.205 0 0); + --muted: oklch(0.97 0 0); + --muted-foreground: oklch(0.556 0 0); + --accent: oklch(0.97 0 0); + --accent-foreground: oklch(0.205 0 0); + --destructive: oklch(0.577 0.245 27.325); + --destructive-foreground: oklch(0.577 0.245 27.325); + --border: oklch(0.922 0 0); + --input: oklch(0.922 0 0); + --ring: oklch(0.87 0 0); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --radius: 0.625rem; + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.145 0 0); + --sidebar-primary: oklch(0.205 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.97 0 0); + --sidebar-accent-foreground: oklch(0.205 0 0); + --sidebar-border: oklch(0.922 0 0); + --sidebar-ring: oklch(0.87 0 0); +} + +.dark { + --background: oklch(0.145 0 0); + --foreground: oklch(0.985 0 0); + --card: oklch(0.145 0 0); + --card-foreground: oklch(0.985 0 0); + --popover: oklch(0.145 0 0); + --popover-foreground: oklch(0.985 0 0); + --primary: oklch(0.985 0 0); + --primary-foreground: oklch(0.205 0 0); + --secondary: oklch(0.269 0 0); + --secondary-foreground: oklch(0.985 0 0); + --muted: oklch(0.269 0 0); + --muted-foreground: oklch(0.708 0 0); + --accent: oklch(0.269 0 0); + --accent-foreground: oklch(0.985 0 0); + --destructive: oklch(0.396 0.141 25.723); + --destructive-foreground: oklch(0.637 0.237 25.331); + --border: oklch(0.269 0 0); + --input: oklch(0.269 0 0); + --ring: oklch(0.439 0 0); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: oklch(0.205 0 0); + --sidebar-foreground: oklch(0.985 0 0); + --sidebar-primary: oklch(0.985 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.269 0 0); + --sidebar-accent-foreground: oklch(0.985 0 0); + --sidebar-border: oklch(0.269 0 0); + --sidebar-ring: oklch(0.439 0 0); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + + body { + @apply bg-background text-foreground; + } +} diff --git a/resources/js/app.tsx b/resources/js/app.tsx new file mode 100755 index 0000000..651265c --- /dev/null +++ b/resources/js/app.tsx @@ -0,0 +1,38 @@ +import { createInertiaApp } from '@inertiajs/react'; +import { Toaster } from '@/components/ui/sonner'; +import { TooltipProvider } from '@/components/ui/tooltip'; +import { initializeTheme } from '@/hooks/use-appearance'; +import AppLayout from '@/layouts/app-layout'; +import AuthLayout from '@/layouts/auth-layout'; +import SettingsLayout from '@/layouts/settings/layout'; + +const appName = import.meta.env.VITE_APP_NAME || 'Vacation Planner'; + +void createInertiaApp({ + title: (title) => (title ? `${title} - ${appName}` : appName), + layout: (name) => { + switch (true) { + case name.startsWith('auth/'): + return AuthLayout; + case name.startsWith('settings/'): + return [AppLayout, SettingsLayout]; + default: + return AppLayout; + } + }, + strictMode: true, + withApp(app) { + return ( + + {app} + + + ); + }, + progress: { + color: '#4B5563', + }, +}); + +// This will set light / dark mode on load... +initializeTheme(); diff --git a/resources/js/components/alert-error.tsx b/resources/js/components/alert-error.tsx new file mode 100755 index 0000000..a9eacd3 --- /dev/null +++ b/resources/js/components/alert-error.tsx @@ -0,0 +1,24 @@ +import { AlertCircleIcon } from 'lucide-react'; +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; + +export default function AlertError({ + errors, + title, +}: { + errors: string[]; + title?: string; +}) { + return ( + + + {title || 'Something went wrong.'} + +
    + {Array.from(new Set(errors)).map((error, index) => ( +
  • {error}
  • + ))} +
+
+
+ ); +} diff --git a/resources/js/components/app-logo-icon.tsx b/resources/js/components/app-logo-icon.tsx new file mode 100755 index 0000000..bc4cce5 --- /dev/null +++ b/resources/js/components/app-logo-icon.tsx @@ -0,0 +1,26 @@ +import type { SVGAttributes } from 'react'; + +export default function AppLogoIcon(props: SVGAttributes) { + return ( + + + + + + + + + + + + ); +} diff --git a/resources/js/components/app-logo.tsx b/resources/js/components/app-logo.tsx new file mode 100755 index 0000000..14707c2 --- /dev/null +++ b/resources/js/components/app-logo.tsx @@ -0,0 +1,20 @@ +import { usePage } from '@inertiajs/react'; + +import AppLogoIcon from '@/components/app-logo-icon'; + +export default function AppLogo() { + const { name } = usePage().props; + + return ( + <> +
+ +
+
+ + {name} + +
+ + ); +} diff --git a/resources/js/components/appearance-tabs.tsx b/resources/js/components/appearance-tabs.tsx new file mode 100755 index 0000000..8d64e68 --- /dev/null +++ b/resources/js/components/appearance-tabs.tsx @@ -0,0 +1,45 @@ +import type { LucideIcon } from 'lucide-react'; +import { Monitor, Moon, Sun } from 'lucide-react'; +import type { HTMLAttributes } from 'react'; +import type { Appearance } from '@/hooks/use-appearance'; +import { useAppearance } from '@/hooks/use-appearance'; +import { cn } from '@/lib/utils'; + +export default function AppearanceToggleTab({ + className = '', + ...props +}: HTMLAttributes) { + const { appearance, updateAppearance } = useAppearance(); + + const tabs: { value: Appearance; icon: LucideIcon; label: string }[] = [ + { value: 'light', icon: Sun, label: 'Светлая' }, + { value: 'dark', icon: Moon, label: 'Тёмная' }, + { value: 'system', icon: Monitor, label: 'Системная' }, + ]; + + return ( +
+ {tabs.map(({ value, icon: Icon, label }) => ( + + ))} +
+ ); +} diff --git a/resources/js/components/delete-user.tsx b/resources/js/components/delete-user.tsx new file mode 100755 index 0000000..70704ad --- /dev/null +++ b/resources/js/components/delete-user.tsx @@ -0,0 +1,120 @@ +import { Form } from '@inertiajs/react'; +import { useRef } from 'react'; +import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController'; +import Heading from '@/components/heading'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { Label } from '@/components/ui/label'; + +export default function DeleteUser() { + const passwordInput = useRef(null); + + return ( +
+ +
+
+

Внимание

+

+ Это действие необратимо. Все маркеры и отметки будут + удалены. +

+
+ + + + + + + + Вы уверены, что хотите удалить аккаунт? + + + После удаления аккаунта все его данные будут + безвозвратно удалены. Введите пароль, чтобы + подтвердить удаление. + + +
passwordInput.current?.focus()} + resetOnSuccess + className="space-y-6" + > + {({ resetAndClearErrors, processing, errors }) => ( + <> +
+ + + + + +
+ + + + + + + + + + + )} +
+
+
+
+
+ ); +} diff --git a/resources/js/components/heading.tsx b/resources/js/components/heading.tsx new file mode 100755 index 0000000..515242d --- /dev/null +++ b/resources/js/components/heading.tsx @@ -0,0 +1,26 @@ +export default function Heading({ + title, + description, + variant = 'default', +}: { + title: string; + description?: string; + variant?: 'default' | 'small'; +}) { + return ( +
+

+ {title} +

+ {description && ( +

{description}

+ )} +
+ ); +} diff --git a/resources/js/components/input-error.tsx b/resources/js/components/input-error.tsx new file mode 100755 index 0000000..f323cee --- /dev/null +++ b/resources/js/components/input-error.tsx @@ -0,0 +1,17 @@ +import type { HTMLAttributes } from 'react'; +import { cn } from '@/lib/utils'; + +export default function InputError({ + message, + className = '', + ...props +}: HTMLAttributes & { message?: string }) { + return message ? ( +

+ {message} +

+ ) : null; +} diff --git a/resources/js/components/password-input.tsx b/resources/js/components/password-input.tsx new file mode 100755 index 0000000..797651f --- /dev/null +++ b/resources/js/components/password-input.tsx @@ -0,0 +1,37 @@ +import { Eye, EyeOff } from 'lucide-react'; +import type { ComponentProps, Ref } from 'react'; +import { useState } from 'react'; +import { Input } from '@/components/ui/input'; +import { cn } from '@/lib/utils'; + +export default function PasswordInput({ + className, + ref, + ...props +}: Omit, 'type'> & { ref?: Ref }) { + const [showPassword, setShowPassword] = useState(false); + + return ( +
+ + +
+ ); +} diff --git a/resources/js/components/planner/day-dialog.tsx b/resources/js/components/planner/day-dialog.tsx new file mode 100755 index 0000000..56bbd92 --- /dev/null +++ b/resources/js/components/planner/day-dialog.tsx @@ -0,0 +1,219 @@ +import { Pencil, Trash2 } from 'lucide-react'; +import { useState } from 'react'; +import type { DayInfo } from '@/components/planner/month-calendar'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { daysInclusive, formatRangeRu, formatRu } from '@/lib/calendar'; +import type { Marker, VacationPeriod } from '@/types/planner'; + +type Props = { + date: string | null; + entries: DayInfo[]; + markers: Marker[]; + onClose: () => void; + onDelete: (period: VacationPeriod) => void; + onReschedule: ( + period: VacationPeriod, + data: { start_date: string; end_date: string; marker_id: number }, + ) => void; +}; + +export function DayDialog({ + date, + entries, + markers, + onClose, + onDelete, + onReschedule, +}: Props) { + const [editing, setEditing] = useState(null); + const [start, setStart] = useState(''); + const [end, setEnd] = useState(''); + const [markerId, setMarkerId] = useState(null); + + const startEdit = (period: VacationPeriod) => { + setEditing(period); + setStart(period.start_date); + setEnd(period.end_date); + setMarkerId(period.marker_id); + }; + + const save = () => { + if (!editing || !markerId || end < start) { + return; + } + + onReschedule(editing, { + start_date: start, + end_date: end, + marker_id: markerId, + }); + setEditing(null); + }; + + const close = () => { + setEditing(null); + onClose(); + }; + + return ( + !open && close()}> + + + + {date ? formatRu(date, true) : ''} + + + {entries.length > 0 + ? 'Отметки на этот день' + : 'На этот день нет отметок'} + + + + {editing ? ( +
+
+
+ + setStart(e.target.value)} + /> +
+
+ + setEnd(e.target.value)} + /> +
+
+ +
+ + +
+ + {end < start && ( +

+ Дата окончания не может быть раньше начала. +

+ )} + +
+ + +
+
+ ) : ( +
+ {entries.map(({ marker, period }) => ( +
+ +
+
+ {marker.name} +
+
+ {formatRangeRu( + period.start_date, + period.end_date, + )}{' '} + ·{' '} + {daysInclusive( + period.start_date, + period.end_date, + )}{' '} + дн. +
+
+ + +
+ ))} +
+ )} +
+
+ ); +} diff --git a/resources/js/components/planner/marker-dialog.tsx b/resources/js/components/planner/marker-dialog.tsx new file mode 100755 index 0000000..ffcf096 --- /dev/null +++ b/resources/js/components/planner/marker-dialog.tsx @@ -0,0 +1,135 @@ +import { useForm } from '@inertiajs/react'; +import { useEffect } from 'react'; +import InputError from '@/components/input-error'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { MARKER_COLORS } from '@/lib/marker-colors'; +import { cn } from '@/lib/utils'; +import { store, update } from '@/routes/markers'; +import type { Marker } from '@/types/planner'; + +type Props = { + open: boolean; + onOpenChange: (open: boolean) => void; + marker: Marker | null; +}; + +export function MarkerDialog({ open, onOpenChange, marker }: Props) { + const form = useForm({ + name: marker?.name ?? '', + color: marker?.color ?? MARKER_COLORS[0], + }); + + useEffect(() => { + if (open) { + form.setData({ + name: marker?.name ?? '', + color: marker?.color ?? MARKER_COLORS[0], + }); + form.clearErrors(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open, marker]); + + const submit = (e: React.FormEvent) => { + e.preventDefault(); + + const options = { + preserveScroll: true, + only: ['markers'], + onSuccess: () => onOpenChange(false), + }; + + if (marker) { + form.patch(update.url(marker.id), options); + } else { + form.post(store().url, options); + } + }; + + return ( + + + + + {marker ? 'Изменить маркер' : 'Новый маркер'} + + + Маркер — это цвет и имя человека, которым вы отмечаете + отпуска. + + + +
+
+ + + form.setData('name', e.target.value) + } + placeholder="Например: Анна" + maxLength={50} + required + autoFocus + data-test="marker-name-input" + /> + +
+ +
+ +
+ {MARKER_COLORS.map((color) => ( +
+ +
+ + + + + +
+
+
+ ); +} diff --git a/resources/js/components/planner/marker-panel.tsx b/resources/js/components/planner/marker-panel.tsx new file mode 100755 index 0000000..0d6ce0c --- /dev/null +++ b/resources/js/components/planner/marker-panel.tsx @@ -0,0 +1,179 @@ +import { router } from '@inertiajs/react'; +import { Pencil, Plus, Trash2 } from 'lucide-react'; +import { useState } from 'react'; +import { MarkerDialog } from '@/components/planner/marker-dialog'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { daysInYear } from '@/lib/calendar'; +import { cn } from '@/lib/utils'; +import { destroy } from '@/routes/markers'; +import type { Marker, VacationPeriod } from '@/types/planner'; + +type Props = { + markers: Marker[]; + periods: VacationPeriod[]; + year: number; + activeMarkerId: number | null; + onSelect: (id: number | null) => void; +}; + +export function MarkerPanel({ + markers, + periods, + year, + activeMarkerId, + onSelect, +}: Props) { + const [dialogOpen, setDialogOpen] = useState(false); + const [editing, setEditing] = useState(null); + const [deleting, setDeleting] = useState(null); + + const dayCount = (markerId: number) => + periods + .filter((p) => p.marker_id === markerId) + .reduce( + (sum, p) => sum + daysInYear(p.start_date, p.end_date, year), + 0, + ); + + const confirmDelete = () => { + if (!deleting) { + return; + } + + router.delete(destroy.url(deleting.id), { + preserveScroll: true, + only: ['markers', 'periods'], + onSuccess: () => setDeleting(null), + }); + }; + + return ( +
+
+ {markers.map((marker) => { + const active = marker.id === activeMarkerId; + + return ( +
+ + + + +
+ ); + })} + + +
+ + + + !open && setDeleting(null)} + > + + + Удалить маркер? + + Маркер «{deleting?.name}» и все его отметки на + календарях будут удалены. Это действие необратимо. + + + + + + + + +
+ ); +} diff --git a/resources/js/components/planner/month-calendar.tsx b/resources/js/components/planner/month-calendar.tsx new file mode 100755 index 0000000..1fb65b0 --- /dev/null +++ b/resources/js/components/planner/month-calendar.tsx @@ -0,0 +1,154 @@ +import { memo } from 'react'; +import type { Selection } from '@/hooks/use-planner'; +import { + formatRu, + isWeekend, + monthGrid, + todayIso, + WEEKDAYS_RU, + MONTHS_RU, +} from '@/lib/calendar'; +import { stripes, tint } from '@/lib/marker-colors'; +import { cn } from '@/lib/utils'; +import type { Marker, VacationPeriod } from '@/types/planner'; + +export type DayInfo = { + marker: Marker; + period: VacationPeriod; +}; + +type Props = { + year: number; + month0: number; + dayMap: Map; + selection: Selection | null; + brushColor: string | null; + onDayPointerDown: (date: string, pointerType: string) => boolean; + onDayPointerEnter: (date: string) => void; + onDayTouchTap: (date: string) => void; + onDayInspect: (date: string) => void; +}; + +export const MonthCalendar = memo(function MonthCalendar({ + year, + month0, + dayMap, + selection, + brushColor, + onDayPointerDown, + onDayPointerEnter, + onDayTouchTap, + onDayInspect, +}: Props) { + const weeks = monthGrid(year, month0); + const today = todayIso(); + const selStart = + selection && selection.start <= selection.end + ? selection.start + : selection?.end; + const selEnd = + selection && selection.start <= selection.end + ? selection.end + : selection?.start; + + return ( +
+
+ {MONTHS_RU[month0]} +
+ +
+ {WEEKDAYS_RU.map((day, i) => ( +
= 5 && 'text-red-500/70 dark:text-red-400/70', + )} + > + {day} +
+ ))} + + {weeks.flat().map((date, i) => { + if (date === null) { + return ( +
+ ); + } + + const entries = dayMap.get(date) ?? []; + const inSelection = + selStart !== undefined && + selEnd !== undefined && + date >= selStart && + date <= selEnd; + + let background: string | undefined; + + if (entries.length === 1) { + background = tint(entries[0].marker.color); + } else if (entries.length > 1) { + background = stripes( + entries.map((e) => e.marker.color), + ); + } + + const markedNames = entries + .map((e) => e.marker.name) + .join(', '); + + return ( + + ); + })} +
+
+ ); +}); diff --git a/resources/js/components/planner/year-select.tsx b/resources/js/components/planner/year-select.tsx new file mode 100755 index 0000000..db7374d --- /dev/null +++ b/resources/js/components/planner/year-select.tsx @@ -0,0 +1,44 @@ +import { router } from '@inertiajs/react'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { planner } from '@/routes'; + +type Props = { + year: number; + years: number[]; +}; + +export function YearSelect({ year, years }: Props) { + return ( + + ); +} diff --git a/resources/js/components/text-link.tsx b/resources/js/components/text-link.tsx new file mode 100755 index 0000000..08ad269 --- /dev/null +++ b/resources/js/components/text-link.tsx @@ -0,0 +1,23 @@ +import { Link } from '@inertiajs/react'; +import type { ComponentProps } from 'react'; +import { cn } from '@/lib/utils'; + +type Props = ComponentProps; + +export default function TextLink({ + className = '', + children, + ...props +}: Props) { + return ( + + {children} + + ); +} diff --git a/resources/js/components/ui/alert.tsx b/resources/js/components/ui/alert.tsx new file mode 100755 index 0000000..6e6727a --- /dev/null +++ b/resources/js/components/ui/alert.tsx @@ -0,0 +1,66 @@ +import { cva, type VariantProps } from "class-variance-authority" +import * as React from "react" + +import { cn } from "@/lib/utils" + +const alertVariants = cva( + "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current", + { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: + "text-destructive-foreground [&>svg]:text-current *:data-[slot=alert-description]:text-destructive-foreground/80", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function Alert({ + className, + variant, + ...props +}: React.ComponentProps<"div"> & VariantProps) { + return ( +
+ ) +} + +function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function AlertDescription({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( +
+ ) +} + +export { Alert, AlertTitle, AlertDescription } diff --git a/resources/js/components/ui/avatar.tsx b/resources/js/components/ui/avatar.tsx new file mode 100755 index 0000000..5a6986a --- /dev/null +++ b/resources/js/components/ui/avatar.tsx @@ -0,0 +1,51 @@ +import * as AvatarPrimitive from "@radix-ui/react-avatar" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Avatar({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AvatarImage({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function AvatarFallback({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Avatar, AvatarImage, AvatarFallback } diff --git a/resources/js/components/ui/badge.tsx b/resources/js/components/ui/badge.tsx new file mode 100755 index 0000000..58294af --- /dev/null +++ b/resources/js/components/ui/badge.tsx @@ -0,0 +1,46 @@ +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" +import * as React from "react" + +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + "inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden", + { + variants: { + variant: { + default: + "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90", + secondary: + "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90", + destructive: + "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", + outline: + "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function Badge({ + className, + variant, + asChild = false, + ...props +}: React.ComponentProps<"span"> & + VariantProps & { asChild?: boolean }) { + const Comp = asChild ? Slot : "span" + + return ( + + ) +} + +export { Badge, badgeVariants } diff --git a/resources/js/components/ui/button.tsx b/resources/js/components/ui/button.tsx new file mode 100755 index 0000000..30d0ac0 --- /dev/null +++ b/resources/js/components/ui/button.tsx @@ -0,0 +1,58 @@ +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" +import * as React from "react" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-[color,box-shadow] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", + { + variants: { + variant: { + default: + "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", + destructive: + "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40", + outline: + "border border-input bg-background shadow-xs hover:bg-accent hover:text-accent-foreground", + secondary: + "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + sm: "h-8 rounded-md px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant, + size, + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/resources/js/components/ui/checkbox.tsx b/resources/js/components/ui/checkbox.tsx new file mode 100755 index 0000000..357d1b4 --- /dev/null +++ b/resources/js/components/ui/checkbox.tsx @@ -0,0 +1,30 @@ +import * as CheckboxPrimitive from "@radix-ui/react-checkbox" +import { CheckIcon } from "lucide-react" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Checkbox({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ) +} + +export { Checkbox } diff --git a/resources/js/components/ui/dialog.tsx b/resources/js/components/ui/dialog.tsx new file mode 100755 index 0000000..b0f63c0 --- /dev/null +++ b/resources/js/components/ui/dialog.tsx @@ -0,0 +1,133 @@ +import * as DialogPrimitive from "@radix-ui/react-dialog" +import { XIcon } from "lucide-react" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Dialog({ + ...props +}: React.ComponentProps) { + return +} + +function DialogTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function DialogPortal({ + ...props +}: React.ComponentProps) { + return +} + +function DialogClose({ + ...props +}: React.ComponentProps) { + return +} + +function DialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogContent({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + {children} + + + Закрыть + + + + ) +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function DialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} diff --git a/resources/js/components/ui/dropdown-menu.tsx b/resources/js/components/ui/dropdown-menu.tsx new file mode 100755 index 0000000..86cb1b1 --- /dev/null +++ b/resources/js/components/ui/dropdown-menu.tsx @@ -0,0 +1,255 @@ +import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" +import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function DropdownMenu({ + ...props +}: React.ComponentProps) { + return +} + +function DropdownMenuPortal({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DropdownMenuTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DropdownMenuContent({ + className, + sideOffset = 4, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +function DropdownMenuGroup({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DropdownMenuItem({ + className, + inset, + variant = "default", + ...props +}: React.ComponentProps & { + inset?: boolean + variant?: "default" | "destructive" +}) { + return ( + + ) +} + +function DropdownMenuCheckboxItem({ + className, + children, + checked, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function DropdownMenuRadioGroup({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DropdownMenuRadioItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function DropdownMenuLabel({ + className, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + ) +} + +function DropdownMenuSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DropdownMenuShortcut({ + className, + ...props +}: React.ComponentProps<"span">) { + return ( + + ) +} + +function DropdownMenuSub({ + ...props +}: React.ComponentProps) { + return +} + +function DropdownMenuSubTrigger({ + className, + inset, + children, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + {children} + + + ) +} + +function DropdownMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { + DropdownMenu, + DropdownMenuPortal, + DropdownMenuTrigger, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuLabel, + DropdownMenuItem, + DropdownMenuCheckboxItem, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubTrigger, + DropdownMenuSubContent, +} diff --git a/resources/js/components/ui/input.tsx b/resources/js/components/ui/input.tsx new file mode 100755 index 0000000..4bfe9cc --- /dev/null +++ b/resources/js/components/ui/input.tsx @@ -0,0 +1,21 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Input({ className, type, ...props }: React.ComponentProps<"input">) { + return ( + + ) +} + +export { Input } diff --git a/resources/js/components/ui/label.tsx b/resources/js/components/ui/label.tsx new file mode 100755 index 0000000..d330350 --- /dev/null +++ b/resources/js/components/ui/label.tsx @@ -0,0 +1,22 @@ +import * as LabelPrimitive from "@radix-ui/react-label" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Label({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Label } diff --git a/resources/js/components/ui/select.tsx b/resources/js/components/ui/select.tsx new file mode 100755 index 0000000..2655659 --- /dev/null +++ b/resources/js/components/ui/select.tsx @@ -0,0 +1,193 @@ +import * as SelectPrimitive from "@radix-ui/react-select" +import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Select({ + ...props +}: React.ComponentProps) { + return +} + +function SelectGroup({ + ...props +}: React.ComponentProps) { + return +} + +function SelectValue({ + ...props +}: React.ComponentProps) { + return +} + +function SelectTrigger({ + className, + size = "default", + children, + ...props +}: React.ComponentProps & { + size?: "sm" | "default" +}) { + return ( + + {children} + + + + + ) +} + +function SelectContent({ + className, + children, + position = "popper", + side = "bottom", + sideOffset = 4, + align = "center", + ...props +}: React.ComponentProps) { + return ( + + + + + {children} + + + + + ) +} + +function SelectLabel({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function SelectItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function SelectSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function SelectScrollUpButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +function SelectScrollDownButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectScrollDownButton, + SelectScrollUpButton, + SelectSeparator, + SelectTrigger, + SelectValue, +} diff --git a/resources/js/components/ui/separator.tsx b/resources/js/components/ui/separator.tsx new file mode 100755 index 0000000..c18404c --- /dev/null +++ b/resources/js/components/ui/separator.tsx @@ -0,0 +1,26 @@ +import * as SeparatorPrimitive from "@radix-ui/react-separator" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Separator({ + className, + orientation = "horizontal", + decorative = true, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Separator } diff --git a/resources/js/components/ui/sonner.tsx b/resources/js/components/ui/sonner.tsx new file mode 100755 index 0000000..fb45e58 --- /dev/null +++ b/resources/js/components/ui/sonner.tsx @@ -0,0 +1,27 @@ +import { useFlashToast } from '@/hooks/use-flash-toast'; +import { useAppearance } from '@/hooks/use-appearance'; +import { Toaster as Sonner, type ToasterProps } from 'sonner'; + +function Toaster({ ...props }: ToasterProps) { + const { appearance } = useAppearance(); + + useFlashToast(); + + return ( + + ); +} + +export { Toaster }; diff --git a/resources/js/components/ui/spinner.tsx b/resources/js/components/ui/spinner.tsx new file mode 100755 index 0000000..a70e713 --- /dev/null +++ b/resources/js/components/ui/spinner.tsx @@ -0,0 +1,16 @@ +import { Loader2Icon } from "lucide-react" + +import { cn } from "@/lib/utils" + +function Spinner({ className, ...props }: React.ComponentProps<"svg">) { + return ( + + ) +} + +export { Spinner } diff --git a/resources/js/components/ui/tooltip.tsx b/resources/js/components/ui/tooltip.tsx new file mode 100755 index 0000000..ffde41c --- /dev/null +++ b/resources/js/components/ui/tooltip.tsx @@ -0,0 +1,55 @@ +import * as TooltipPrimitive from "@radix-ui/react-tooltip" +import * as React from "react" + +import { cn } from "@/lib/utils" + +function TooltipProvider({ + delayDuration = 0, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function Tooltip({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function TooltipContent({ + className, + sideOffset = 4, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + ) +} + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } diff --git a/resources/js/components/user-info.tsx b/resources/js/components/user-info.tsx new file mode 100755 index 0000000..dd0848e --- /dev/null +++ b/resources/js/components/user-info.tsx @@ -0,0 +1,32 @@ +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { useInitials } from '@/hooks/use-initials'; +import type { User } from '@/types'; + +export function UserInfo({ + user, + showEmail = false, +}: { + user: User; + showEmail?: boolean; +}) { + const getInitials = useInitials(); + + return ( + <> + + + + {getInitials(user.name)} + + +
+ {user.name} + {showEmail && ( + + {user.email} + + )} +
+ + ); +} diff --git a/resources/js/components/user-menu-content.tsx b/resources/js/components/user-menu-content.tsx new file mode 100755 index 0000000..f2b10e5 --- /dev/null +++ b/resources/js/components/user-menu-content.tsx @@ -0,0 +1,58 @@ +import { Link, router } from '@inertiajs/react'; +import { LogOut, Settings } from 'lucide-react'; +import { + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, +} from '@/components/ui/dropdown-menu'; +import { UserInfo } from '@/components/user-info'; +import { logout } from '@/routes'; +import { edit } from '@/routes/profile'; +import type { User } from '@/types'; + +type Props = { + user: User; +}; + +export function UserMenuContent({ user }: Props) { + const handleLogout = () => { + router.flushAll(); + }; + + return ( + <> + +
+ +
+
+ + + + + + Настройки + + + + + + + + Выйти + + + + ); +} diff --git a/resources/js/hooks/use-appearance.tsx b/resources/js/hooks/use-appearance.tsx new file mode 100755 index 0000000..fa03f34 --- /dev/null +++ b/resources/js/hooks/use-appearance.tsx @@ -0,0 +1,115 @@ +import { useSyncExternalStore } from 'react'; + +export type ResolvedAppearance = 'light' | 'dark'; +export type Appearance = ResolvedAppearance | 'system'; + +export type UseAppearanceReturn = { + readonly appearance: Appearance; + readonly resolvedAppearance: ResolvedAppearance; + readonly updateAppearance: (mode: Appearance) => void; +}; + +const listeners = new Set<() => void>(); +let currentAppearance: Appearance = 'system'; + +const prefersDark = (): boolean => { + if (typeof window === 'undefined') { + return false; + } + + return window.matchMedia('(prefers-color-scheme: dark)').matches; +}; + +const setCookie = (name: string, value: string, days = 365): void => { + if (typeof document === 'undefined') { + return; + } + + const maxAge = days * 24 * 60 * 60; + document.cookie = `${name}=${value};path=/;max-age=${maxAge};SameSite=Lax`; +}; + +const getStoredAppearance = (): Appearance => { + if (typeof window === 'undefined') { + return 'system'; + } + + return (localStorage.getItem('appearance') as Appearance) || 'system'; +}; + +const isDarkMode = (appearance: Appearance): boolean => { + return appearance === 'dark' || (appearance === 'system' && prefersDark()); +}; + +const applyTheme = (appearance: Appearance): void => { + if (typeof document === 'undefined') { + return; + } + + const isDark = isDarkMode(appearance); + + document.documentElement.classList.toggle('dark', isDark); + document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'; +}; + +const subscribe = (callback: () => void) => { + listeners.add(callback); + + return () => listeners.delete(callback); +}; + +const notify = (): void => listeners.forEach((listener) => listener()); + +const mediaQuery = (): MediaQueryList | null => { + if (typeof window === 'undefined') { + return null; + } + + return window.matchMedia('(prefers-color-scheme: dark)'); +}; + +const handleSystemThemeChange = (): void => applyTheme(currentAppearance); + +export function initializeTheme(): void { + if (typeof window === 'undefined') { + return; + } + + if (!localStorage.getItem('appearance')) { + localStorage.setItem('appearance', 'system'); + setCookie('appearance', 'system'); + } + + currentAppearance = getStoredAppearance(); + applyTheme(currentAppearance); + + // Set up system theme change listener + mediaQuery()?.addEventListener('change', handleSystemThemeChange); +} + +export function useAppearance(): UseAppearanceReturn { + const appearance: Appearance = useSyncExternalStore( + subscribe, + () => currentAppearance, + () => 'system', + ); + + const resolvedAppearance: ResolvedAppearance = isDarkMode(appearance) + ? 'dark' + : 'light'; + + const updateAppearance = (mode: Appearance): void => { + currentAppearance = mode; + + // Store in localStorage for client-side persistence... + localStorage.setItem('appearance', mode); + + // Store in cookie for SSR... + setCookie('appearance', mode); + + applyTheme(mode); + notify(); + }; + + return { appearance, resolvedAppearance, updateAppearance } as const; +} diff --git a/resources/js/hooks/use-current-url.ts b/resources/js/hooks/use-current-url.ts new file mode 100755 index 0000000..ee8cd2b --- /dev/null +++ b/resources/js/hooks/use-current-url.ts @@ -0,0 +1,83 @@ +import type { InertiaLinkProps } from '@inertiajs/react'; +import { usePage } from '@inertiajs/react'; +import { toUrl } from '@/lib/utils'; + +export type IsCurrentUrlFn = ( + urlToCheck: NonNullable, + currentUrl?: string, + startsWith?: boolean, +) => boolean; + +export type IsCurrentOrParentUrlFn = ( + urlToCheck: NonNullable, + currentUrl?: string, +) => boolean; + +export type WhenCurrentUrlFn = ( + urlToCheck: NonNullable, + ifTrue: TIfTrue, + ifFalse?: TIfFalse, +) => TIfTrue | TIfFalse; + +export type UseCurrentUrlReturn = { + currentUrl: string; + isCurrentUrl: IsCurrentUrlFn; + isCurrentOrParentUrl: IsCurrentOrParentUrlFn; + whenCurrentUrl: WhenCurrentUrlFn; +}; + +export function useCurrentUrl(): UseCurrentUrlReturn { + const page = usePage(); + const currentUrlPath = new URL( + page.url, + typeof window !== 'undefined' + ? window.location.origin + : 'http://localhost', + ).pathname; + + const isCurrentUrl: IsCurrentUrlFn = ( + urlToCheck: NonNullable, + currentUrl?: string, + startsWith: boolean = false, + ) => { + const urlToCompare = currentUrl ?? currentUrlPath; + const urlString = toUrl(urlToCheck); + + const comparePath = (path: string): boolean => + startsWith ? urlToCompare.startsWith(path) : path === urlToCompare; + + if (!urlString.startsWith('http')) { + return comparePath(urlString); + } + + try { + const absoluteUrl = new URL(urlString); + + return comparePath(absoluteUrl.pathname); + } catch { + return false; + } + }; + + const isCurrentOrParentUrl: IsCurrentOrParentUrlFn = ( + urlToCheck: NonNullable, + currentUrl?: string, + ) => { + return isCurrentUrl(urlToCheck, currentUrl, true); + }; + + const whenCurrentUrl: WhenCurrentUrlFn = ( + urlToCheck: NonNullable, + ifTrue: TIfTrue, + ifFalse: TIfFalse = null as TIfFalse, + ): TIfTrue | TIfFalse => { + return isCurrentUrl(urlToCheck) ? ifTrue : ifFalse; + }; + + return { + currentUrl: currentUrlPath, + isCurrentUrl, + isCurrentOrParentUrl, + whenCurrentUrl, + }; +} diff --git a/resources/js/hooks/use-flash-toast.ts b/resources/js/hooks/use-flash-toast.ts new file mode 100755 index 0000000..755c210 --- /dev/null +++ b/resources/js/hooks/use-flash-toast.ts @@ -0,0 +1,19 @@ +import { router } from '@inertiajs/react'; +import { useEffect } from 'react'; +import { toast } from 'sonner'; +import type { FlashToast } from '@/types/ui'; + +export function useFlashToast(): void { + useEffect(() => { + return router.on('flash', (event) => { + const flash = (event as CustomEvent).detail?.flash; + const data = flash?.toast as FlashToast | undefined; + + if (!data) { + return; + } + + toast[data.type](data.message); + }); + }, []); +} diff --git a/resources/js/hooks/use-initials.tsx b/resources/js/hooks/use-initials.tsx new file mode 100755 index 0000000..407309f --- /dev/null +++ b/resources/js/hooks/use-initials.tsx @@ -0,0 +1,26 @@ +import { useCallback } from 'react'; + +export type GetInitialsFn = (fullName: string) => string; + +function getInitial(name: string): string { + return Array.from(name)[0] ?? ''; +} + +export function useInitials(): GetInitialsFn { + return useCallback((fullName: string): string => { + const names = fullName.trim().split(/\s+/u).filter(Boolean); + + if (names.length === 0) { + return ''; + } + + if (names.length === 1) { + return getInitial(names[0]).toUpperCase(); + } + + const firstInitial = getInitial(names[0]); + const lastInitial = getInitial(names[names.length - 1]); + + return `${firstInitial}${lastInitial}`.toUpperCase(); + }, []); +} diff --git a/resources/js/hooks/use-planner.ts b/resources/js/hooks/use-planner.ts new file mode 100755 index 0000000..7438f77 --- /dev/null +++ b/resources/js/hooks/use-planner.ts @@ -0,0 +1,227 @@ +import { router } from '@inertiajs/react'; +import { useCallback, useEffect, useRef, useState } from 'react'; +import { toast } from 'sonner'; +import { addRangeOptimistic, toggleDayOptimistic } from '@/lib/periods'; +import { destroy, store, toggle, update } from '@/routes/periods'; +import type { Marker, VacationPeriod } from '@/types/planner'; + +export type Selection = { start: string; end: string }; + +type Options = { + markers: Marker[]; + periods: VacationPeriod[]; +}; + +export function usePlanner({ + markers: serverMarkers, + periods: serverPeriods, +}: Options) { + const [markers, setMarkers] = useState(serverMarkers); + const [periods, setPeriods] = useState(serverPeriods); + const [activeMarkerId, setActiveMarkerId] = useState(null); + const [selection, setSelectionState] = useState(null); + const selectionRef = useRef(null); + const [touchAnchor, setTouchAnchor] = useState(null); + const draggingRef = useRef(false); + + const setSelection = useCallback((s: Selection | null) => { + selectionRef.current = s; + setSelectionState(s); + }, []); + + useEffect(() => setMarkers(serverMarkers), [serverMarkers]); + useEffect(() => setPeriods(serverPeriods), [serverPeriods]); + + // Drop the brush if its marker was deleted. + useEffect(() => { + if ( + activeMarkerId !== null && + !markers.some((m) => m.id === activeMarkerId) + ) { + setActiveMarkerId(null); + } + }, [markers, activeMarkerId]); + + const activeMarker = markers.find((m) => m.id === activeMarkerId) ?? null; + + const rollback = (previous: VacationPeriod[]) => { + setPeriods(previous); + toast.error('Не удалось сохранить изменения. Попробуйте ещё раз.'); + }; + + const commitRange = useCallback( + (a: string, b: string) => { + if (activeMarkerId === null) { + return; + } + + const start = a <= b ? a : b; + const end = a <= b ? b : a; + const previous = periods; + + if (start === end) { + setPeriods(toggleDayOptimistic(periods, activeMarkerId, start)); + + router.post( + toggle().url, + { marker_id: activeMarkerId, date: start }, + { + preserveScroll: true, + only: ['periods'], + onError: () => rollback(previous), + }, + ); + } else { + setPeriods( + addRangeOptimistic(periods, activeMarkerId, start, end), + ); + + router.post( + store().url, + { + marker_id: activeMarkerId, + start_date: start, + end_date: end, + }, + { + preserveScroll: true, + only: ['periods'], + onError: () => rollback(previous), + }, + ); + } + }, + [activeMarkerId, periods], + ); + + /** + * Pointer down on a day cell while a brush is active. + * Mouse/pen: start drag. Touch: two-tap range selection. + * Returns true when the event was handled as marking. + */ + const dayPointerDown = useCallback( + (date: string, pointerType: string): boolean => { + if (activeMarkerId === null) { + return false; + } + + if (pointerType === 'touch') { + if (touchAnchor === null) { + setTouchAnchor(date); + setSelection({ start: date, end: date }); + } else { + commitRange(touchAnchor, date); + setTouchAnchor(null); + setSelection(null); + } + + return true; + } + + draggingRef.current = true; + setSelection({ start: date, end: date }); + + return true; + }, + [activeMarkerId, touchAnchor, commitRange], + ); + + const dayPointerEnter = useCallback( + (date: string) => { + if (draggingRef.current) { + const current = selectionRef.current; + + if (current) { + setSelection({ ...current, end: date }); + } + } + }, + [setSelection], + ); + + const finishDrag = useCallback(() => { + if (!draggingRef.current) { + return; + } + + draggingRef.current = false; + + const current = selectionRef.current; + setSelection(null); + + if (current) { + commitRange(current.start, current.end); + } + }, [commitRange, setSelection]); + + useEffect(() => { + window.addEventListener('pointerup', finishDrag); + window.addEventListener('pointercancel', finishDrag); + + return () => { + window.removeEventListener('pointerup', finishDrag); + window.removeEventListener('pointercancel', finishDrag); + }; + }, [finishDrag]); + + const cancelTouchAnchor = useCallback(() => { + setTouchAnchor(null); + setSelection(null); + }, []); + + const deletePeriod = useCallback( + (period: VacationPeriod) => { + const previous = periods; + setPeriods(periods.filter((p) => p.id !== period.id)); + + router.delete(destroy.url(period.id), { + preserveScroll: true, + only: ['periods'], + onError: () => rollback(previous), + }); + }, + [periods], + ); + + const reschedulePeriod = useCallback( + ( + period: VacationPeriod, + data: { start_date: string; end_date: string; marker_id: number }, + ) => { + const previous = periods; + const without = periods.filter((p) => p.id !== period.id); + setPeriods( + addRangeOptimistic( + without, + data.marker_id, + data.start_date, + data.end_date, + ), + ); + + router.patch(update.url(period.id), data, { + preserveScroll: true, + only: ['periods'], + onError: () => rollback(previous), + }); + }, + [periods], + ); + + return { + markers, + periods, + activeMarker, + activeMarkerId, + setActiveMarkerId, + selection, + touchAnchor, + cancelTouchAnchor, + dayPointerDown, + dayPointerEnter, + deletePeriod, + reschedulePeriod, + }; +} + +export type Planner = ReturnType; diff --git a/resources/js/layouts/app-layout.tsx b/resources/js/layouts/app-layout.tsx new file mode 100755 index 0000000..a2c621c --- /dev/null +++ b/resources/js/layouts/app-layout.tsx @@ -0,0 +1,53 @@ +import { Link, usePage } from '@inertiajs/react'; +import AppLogo from '@/components/app-logo'; +import { UserMenuContent } from '@/components/user-menu-content'; +import { Avatar, AvatarFallback } from '@/components/ui/avatar'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { useInitials } from '@/hooks/use-initials'; +import { useFlashToast } from '@/hooks/use-flash-toast'; +import type { Auth } from '@/types'; + +export default function AppLayout({ children }: { children: React.ReactNode }) { + const { auth } = usePage<{ auth: Auth }>().props; + const getInitials = useInitials(); + useFlashToast(); + + return ( +
+
+
+ + + + + {auth?.user && ( + + + + + {getInitials(auth.user.name)} + + + + + + + + )} +
+
+ +
+ {children} +
+
+ ); +} diff --git a/resources/js/layouts/auth-layout.tsx b/resources/js/layouts/auth-layout.tsx new file mode 100755 index 0000000..698dd75 --- /dev/null +++ b/resources/js/layouts/auth-layout.tsx @@ -0,0 +1,17 @@ +import AuthLayoutTemplate from '@/layouts/auth/auth-simple-layout'; + +export default function AuthLayout({ + title = '', + description = '', + children, +}: { + title?: string; + description?: string; + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} diff --git a/resources/js/layouts/auth/auth-simple-layout.tsx b/resources/js/layouts/auth/auth-simple-layout.tsx new file mode 100755 index 0000000..9dd4657 --- /dev/null +++ b/resources/js/layouts/auth/auth-simple-layout.tsx @@ -0,0 +1,38 @@ +import { Link } from '@inertiajs/react'; +import AppLogoIcon from '@/components/app-logo-icon'; +import { home } from '@/routes'; +import type { AuthLayoutProps } from '@/types'; + +export default function AuthSimpleLayout({ + children, + title, + description, +}: AuthLayoutProps) { + return ( +
+
+
+
+ +
+ +
+ {title} + + +
+

{title}

+

+ {description} +

+
+
+ {children} +
+
+
+ ); +} diff --git a/resources/js/layouts/settings/layout.tsx b/resources/js/layouts/settings/layout.tsx new file mode 100755 index 0000000..078af10 --- /dev/null +++ b/resources/js/layouts/settings/layout.tsx @@ -0,0 +1,78 @@ +import { Link } from '@inertiajs/react'; +import type { PropsWithChildren } from 'react'; +import Heading from '@/components/heading'; +import { Button } from '@/components/ui/button'; +import { Separator } from '@/components/ui/separator'; +import { useCurrentUrl } from '@/hooks/use-current-url'; +import { cn, toUrl } from '@/lib/utils'; +import { edit as editAppearance } from '@/routes/appearance'; +import { edit } from '@/routes/profile'; +import { edit as editSecurity } from '@/routes/security'; +import type { NavItem } from '@/types'; + +const sidebarNavItems: NavItem[] = [ + { + title: 'Профиль', + href: edit(), + icon: null, + }, + { + title: 'Безопасность', + href: editSecurity(), + icon: null, + }, + { + title: 'Оформление', + href: editAppearance(), + icon: null, + }, +]; + +export default function SettingsLayout({ children }: PropsWithChildren) { + const { isCurrentOrParentUrl } = useCurrentUrl(); + + return ( +
+ + +
+ + + + +
+
+ {children} +
+
+
+
+ ); +} diff --git a/resources/js/lib/calendar.ts b/resources/js/lib/calendar.ts new file mode 100755 index 0000000..be73280 --- /dev/null +++ b/resources/js/lib/calendar.ts @@ -0,0 +1,152 @@ +export const MONTHS_RU = [ + 'Январь', + 'Февраль', + 'Март', + 'Апрель', + 'Май', + 'Июнь', + 'Июль', + 'Август', + 'Сентябрь', + 'Октябрь', + 'Ноябрь', + 'Декабрь', +]; + +export const WEEKDAYS_RU = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']; + +const MONTHS_GENITIVE_RU = [ + 'января', + 'февраля', + 'марта', + 'апреля', + 'мая', + 'июня', + 'июля', + 'августа', + 'сентября', + 'октября', + 'ноября', + 'декабря', +]; + +/** Build an ISO date string (YYYY-MM-DD) without timezone pitfalls. */ +export function isoDate(year: number, month0: number, day: number): string { + const m = String(month0 + 1).padStart(2, '0'); + const d = String(day).padStart(2, '0'); + + return `${year}-${m}-${d}`; +} + +export function todayIso(): string { + const now = new Date(); + + return isoDate(now.getFullYear(), now.getMonth(), now.getDate()); +} + +/** Parse an ISO date string into parts. */ +export function parseIso(date: string): { + year: number; + month0: number; + day: number; +} { + const [year, month, day] = date.split('-').map(Number); + + return { year, month0: month - 1, day }; +} + +export function addDays(date: string, days: number): string { + const { year, month0, day } = parseIso(date); + const d = new Date(Date.UTC(year, month0, day + days)); + + return isoDate(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); +} + +export function daysInclusive(start: string, end: string): number { + const a = parseIso(start); + const b = parseIso(end); + const ms = + Date.UTC(b.year, b.month0, b.day) - Date.UTC(a.year, a.month0, a.day); + + return Math.round(ms / 86_400_000) + 1; +} + +/** + * Build a Monday-first month grid. Returns weeks of cells; + * each cell is an ISO date string or null (outside the month). + */ +export function monthGrid(year: number, month0: number): (string | null)[][] { + const first = new Date(Date.UTC(year, month0, 1)); + const offset = (first.getUTCDay() + 6) % 7; + const total = new Date(Date.UTC(year, month0 + 1, 0)).getUTCDate(); + + const cells: (string | null)[] = []; + + for (let i = 0; i < offset; i++) { + cells.push(null); + } + + for (let day = 1; day <= total; day++) { + cells.push(isoDate(year, month0, day)); + } + + while (cells.length % 7 !== 0) { + cells.push(null); + } + + const weeks: (string | null)[][] = []; + + for (let i = 0; i < cells.length; i += 7) { + weeks.push(cells.slice(i, i + 7)); + } + + return weeks; +} + +/** "6 июля" or "6 июля 2026" */ +export function formatRu(date: string, withYear = false): string { + const { year, month0, day } = parseIso(date); + + return `${day} ${MONTHS_GENITIVE_RU[month0]}${withYear ? ` ${year}` : ''}`; +} + +/** "6–19 июля 2026" / "28 декабря 2026 – 8 января 2027" */ +export function formatRangeRu(start: string, end: string): string { + if (start === end) { + return formatRu(start, true); + } + + const a = parseIso(start); + const b = parseIso(end); + + if (a.year === b.year && a.month0 === b.month0) { + return `${a.day}–${formatRu(end, true)}`; + } + + if (a.year === b.year) { + return `${formatRu(start)} – ${formatRu(end, true)}`; + } + + return `${formatRu(start, true)} – ${formatRu(end, true)}`; +} + +export function isWeekend(date: string): boolean { + const { year, month0, day } = parseIso(date); + const dow = new Date(Date.UTC(year, month0, day)).getUTCDay(); + + return dow === 0 || dow === 6; +} + +/** Clip a period to a year and count its days (0 if no overlap). */ +export function daysInYear(start: string, end: string, year: number): number { + const yearStart = `${year}-01-01`; + const yearEnd = `${year}-12-31`; + const s = start > yearStart ? start : yearStart; + const e = end < yearEnd ? end : yearEnd; + + if (s > e) { + return 0; + } + + return daysInclusive(s, e); +} diff --git a/resources/js/lib/marker-colors.ts b/resources/js/lib/marker-colors.ts new file mode 100755 index 0000000..852dd57 --- /dev/null +++ b/resources/js/lib/marker-colors.ts @@ -0,0 +1,35 @@ +/** Fixed palette: contrast-friendly colors that work in light & dark themes. */ +export const MARKER_COLORS = [ + '#2563eb', + '#db2777', + '#16a34a', + '#d97706', + '#7c3aed', + '#dc2626', + '#0891b2', + '#65a30d', + '#c026d3', + '#ea580c', + '#0d9488', + '#4f46e5', +] as const; + +/** Tinted background for a day marked with a single color. */ +export function tint(color: string, percent = 24): string { + return `color-mix(in srgb, ${color} ${percent}%, transparent)`; +} + +/** Diagonal stripes for a day marked with several colors. */ +export function stripes(colors: string[]): string { + const step = 100 / colors.length; + const stops = colors + .map((color, i) => { + const from = (step * i).toFixed(2); + const to = (step * (i + 1)).toFixed(2); + + return `${tint(color, 45)} ${from}% ${to}%`; + }) + .join(', '); + + return `repeating-linear-gradient(135deg, ${stops})`; +} diff --git a/resources/js/lib/periods.ts b/resources/js/lib/periods.ts new file mode 100755 index 0000000..fb7c260 --- /dev/null +++ b/resources/js/lib/periods.ts @@ -0,0 +1,91 @@ +import { addDays } from '@/lib/calendar'; +import type { VacationPeriod } from '@/types/planner'; + +let tempId = -1; + +/** + * Pure mirror of the backend PeriodService: add a range, merging + * overlapping/adjacent periods of the same marker. Used for optimistic UI. + */ +export function addRangeOptimistic( + periods: VacationPeriod[], + markerId: number, + start: string, + end: string, +): VacationPeriod[] { + const rest: VacationPeriod[] = []; + let mergedStart = start; + let mergedEnd = end; + + for (const period of periods) { + const touches = + period.marker_id === markerId && + period.start_date <= addDays(end, 1) && + period.end_date >= addDays(start, -1); + + if (touches) { + if (period.start_date < mergedStart) { + mergedStart = period.start_date; + } + + if (period.end_date > mergedEnd) { + mergedEnd = period.end_date; + } + } else { + rest.push(period); + } + } + + return [ + ...rest, + { + id: tempId--, + marker_id: markerId, + start_date: mergedStart, + end_date: mergedEnd, + }, + ]; +} + +/** Pure mirror of the backend toggleDay (remove / split / add). */ +export function toggleDayOptimistic( + periods: VacationPeriod[], + markerId: number, + date: string, +): VacationPeriod[] { + const covering = periods.find( + (p) => + p.marker_id === markerId && + p.start_date <= date && + p.end_date >= date, + ); + + if (!covering) { + return addRangeOptimistic(periods, markerId, date, date); + } + + const rest = periods.filter((p) => p.id !== covering.id); + + if (covering.start_date === date && covering.end_date === date) { + return rest; + } + + if (covering.start_date === date) { + return [...rest, { ...covering, start_date: addDays(date, 1) }]; + } + + if (covering.end_date === date) { + return [...rest, { ...covering, end_date: addDays(date, -1) }]; + } + + return [ + ...rest, + { ...covering, end_date: addDays(date, -1) }, + { + id: tempId--, + marker_id: markerId, + start_date: addDays(date, 1), + end_date: covering.end_date, + }, + ]; +} diff --git a/resources/js/lib/utils.ts b/resources/js/lib/utils.ts new file mode 100755 index 0000000..3ead67f --- /dev/null +++ b/resources/js/lib/utils.ts @@ -0,0 +1,12 @@ +import type { InertiaLinkProps } from '@inertiajs/react'; +import { clsx } from 'clsx'; +import type { ClassValue } from 'clsx'; +import { twMerge } from 'tailwind-merge'; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} + +export function toUrl(url: NonNullable): string { + return typeof url === 'string' ? url : url.url; +} diff --git a/resources/js/pages/auth/confirm-password.tsx b/resources/js/pages/auth/confirm-password.tsx new file mode 100755 index 0000000..72ceebe --- /dev/null +++ b/resources/js/pages/auth/confirm-password.tsx @@ -0,0 +1,51 @@ +import { Form, Head } from '@inertiajs/react'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { store } from '@/routes/password/confirm'; + +export default function ConfirmPassword() { + return ( + <> + + +
+ {({ processing, errors }) => ( +
+
+ + + + +
+ +
+ +
+
+ )} +
+ + ); +} + +ConfirmPassword.layout = { + title: 'Подтверждение пароля', + description: + 'Это защищённый раздел приложения. Подтвердите пароль, чтобы продолжить.', +}; diff --git a/resources/js/pages/auth/forgot-password.tsx b/resources/js/pages/auth/forgot-password.tsx new file mode 100755 index 0000000..932aac4 --- /dev/null +++ b/resources/js/pages/auth/forgot-password.tsx @@ -0,0 +1,68 @@ +import { Form, Head } from '@inertiajs/react'; +import { LoaderCircle } from 'lucide-react'; +import InputError from '@/components/input-error'; +import TextLink from '@/components/text-link'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { login } from '@/routes'; +import { email } from '@/routes/password'; + +export default function ForgotPassword({ status }: { status?: string }) { + return ( + <> + + + {status && ( +
+ {status} +
+ )} + +
+
+ {({ processing, errors }) => ( + <> +
+ + + + +
+ +
+ +
+ + )} +
+ +
+ Или вернитесь ко + входу +
+
+ + ); +} + +ForgotPassword.layout = { + title: 'Забыли пароль?', + description: 'Укажите email, и мы отправим ссылку для сброса пароля', +}; diff --git a/resources/js/pages/auth/login.tsx b/resources/js/pages/auth/login.tsx new file mode 100755 index 0000000..328d319 --- /dev/null +++ b/resources/js/pages/auth/login.tsx @@ -0,0 +1,114 @@ +import { Form, Head } from '@inertiajs/react'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import TextLink from '@/components/text-link'; +import { Button } from '@/components/ui/button'; +import { Checkbox } from '@/components/ui/checkbox'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { register } from '@/routes'; +import { store } from '@/routes/login'; +import { request } from '@/routes/password'; + +type Props = { + status?: string; + canResetPassword: boolean; +}; + +export default function Login({ status, canResetPassword }: Props) { + return ( + <> + + +
+ {({ processing, errors }) => ( + <> +
+
+ + + +
+ +
+
+ + {canResetPassword && ( + + Забыли пароль? + + )} +
+ + +
+ +
+ + +
+ + +
+ +
+ Нет аккаунта?{' '} + + Зарегистрироваться + +
+ + )} +
+ + {status && ( +
+ {status} +
+ )} + + ); +} + +Login.layout = { + title: 'Вход в аккаунт', + description: 'Введите email и пароль, чтобы войти', +}; diff --git a/resources/js/pages/auth/register.tsx b/resources/js/pages/auth/register.tsx new file mode 100755 index 0000000..fcf9fd0 --- /dev/null +++ b/resources/js/pages/auth/register.tsx @@ -0,0 +1,120 @@ +import { Form, Head } from '@inertiajs/react'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import TextLink from '@/components/text-link'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { login } from '@/routes'; +import { store } from '@/routes/register'; + +type Props = { + passwordRules: string; +}; + +export default function Register({ passwordRules }: Props) { + return ( + <> + +
+ {({ processing, errors }) => ( + <> +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ + +
+ +
+ Уже есть аккаунт?{' '} + + Войти + +
+ + )} +
+ + ); +} + +Register.layout = { + title: 'Создание аккаунта', + description: 'Заполните данные, чтобы создать аккаунт', +}; diff --git a/resources/js/pages/auth/reset-password.tsx b/resources/js/pages/auth/reset-password.tsx new file mode 100755 index 0000000..80f201d --- /dev/null +++ b/resources/js/pages/auth/reset-password.tsx @@ -0,0 +1,96 @@ +import { Form, Head } from '@inertiajs/react'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Spinner } from '@/components/ui/spinner'; +import { update } from '@/routes/password'; + +type Props = { + token: string; + email: string; + passwordRules: string; +}; + +export default function ResetPassword({ token, email, passwordRules }: Props) { + return ( + <> + + +
({ ...data, token, email })} + resetOnSuccess={['password', 'password_confirmation']} + > + {({ processing, errors }) => ( +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ + +
+ )} +
+ + ); +} + +ResetPassword.layout = { + title: 'Новый пароль', + description: 'Введите новый пароль ниже', +}; diff --git a/resources/js/pages/planner.tsx b/resources/js/pages/planner.tsx new file mode 100755 index 0000000..29eeffe --- /dev/null +++ b/resources/js/pages/planner.tsx @@ -0,0 +1,141 @@ +import { Head } from '@inertiajs/react'; +import { useMemo, useState } from 'react'; +import { DayDialog } from '@/components/planner/day-dialog'; +import { MarkerPanel } from '@/components/planner/marker-panel'; +import { + MonthCalendar, + type DayInfo, +} from '@/components/planner/month-calendar'; +import { YearSelect } from '@/components/planner/year-select'; +import { Button } from '@/components/ui/button'; +import { usePlanner } from '@/hooks/use-planner'; +import { addDays } from '@/lib/calendar'; +import type { PlannerPageProps } from '@/types/planner'; + +export default function Planner({ + year, + years, + markers, + periods, +}: PlannerPageProps) { + const planner = usePlanner({ markers, periods }); + const [inspectDate, setInspectDate] = useState(null); + + const dayMap = useMemo(() => { + const markerById = new Map(markers.map((m) => [m.id, m])); + const map = new Map(); + + for (const period of periods) { + const marker = markerById.get(period.marker_id); + + if (!marker) { + continue; + } + + let date = period.start_date; + let guard = 0; + + while (date <= period.end_date && guard < 400) { + const list = map.get(date) ?? []; + list.push({ marker, period }); + map.set(date, list); + date = addDays(date, 1); + guard++; + } + } + + return map; + }, [markers, periods]); + + const brushColor = planner.activeMarker?.color ?? null; + + return ( + <> + + +
+
+

+ План отпусков{' '} + {year} +

+ +
+ + + +
+ {planner.activeMarker ? ( + <> + + + Кисть «{planner.activeMarker.name}»: клик — один + день, протяжка — период. На сенсорном экране: + два касания — начало и конец. + + {planner.touchAnchor && ( + + )} + + ) : markers.length > 0 ? ( + + Выберите маркер, чтобы отмечать даты, или нажмите на + день, чтобы посмотреть отметки. + + ) : ( + + Добавьте первый маркер — цвет и имя человека, — + чтобы начать планирование. + + )} +
+ +
+ {Array.from({ length: 12 }, (_, month0) => ( + + planner.dayPointerDown(date, 'touch') + } + onDayInspect={setInspectDate} + /> + ))} +
+
+ + setInspectDate(null)} + onDelete={planner.deletePeriod} + onReschedule={planner.reschedulePeriod} + /> + + ); +} diff --git a/resources/js/pages/settings/appearance.tsx b/resources/js/pages/settings/appearance.tsx new file mode 100755 index 0000000..7e89a82 --- /dev/null +++ b/resources/js/pages/settings/appearance.tsx @@ -0,0 +1,22 @@ +import { Head } from '@inertiajs/react'; +import AppearanceTabs from '@/components/appearance-tabs'; +import Heading from '@/components/heading'; + +export default function Appearance() { + return ( + <> + + +

Настройки оформления

+ +
+ + +
+ + ); +} diff --git a/resources/js/pages/settings/profile.tsx b/resources/js/pages/settings/profile.tsx new file mode 100755 index 0000000..5629ff0 --- /dev/null +++ b/resources/js/pages/settings/profile.tsx @@ -0,0 +1,95 @@ +import { Form, Head, usePage } from '@inertiajs/react'; +import ProfileController from '@/actions/App/Http/Controllers/Settings/ProfileController'; +import DeleteUser from '@/components/delete-user'; +import Heading from '@/components/heading'; +import InputError from '@/components/input-error'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import type { Auth } from '@/types'; + +type PageProps = { + auth: Auth; +}; + +export default function Profile() { + const { auth } = usePage().props; + + return ( + <> + + +

Настройки профиля

+ +
+ + +
+ {({ processing, errors }) => ( + <> +
+ + + + + +
+ +
+ + + + + +
+ +
+ +
+ + )} +
+
+ + + + ); +} diff --git a/resources/js/pages/settings/security.tsx b/resources/js/pages/settings/security.tsx new file mode 100755 index 0000000..4bb054e --- /dev/null +++ b/resources/js/pages/settings/security.tsx @@ -0,0 +1,121 @@ +import { Form, Head } from '@inertiajs/react'; +import { useRef } from 'react'; +import SecurityController from '@/actions/App/Http/Controllers/Settings/SecurityController'; +import Heading from '@/components/heading'; +import InputError from '@/components/input-error'; +import PasswordInput from '@/components/password-input'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; + +type Props = { + passwordRules: string; +}; + +export default function Security(props: Props) { + const passwordInput = useRef(null); + const currentPasswordInput = useRef(null); + + return ( + <> + + +

Настройки безопасности

+ +
+ + +
{ + if (errors.password) { + passwordInput.current?.focus(); + } + + if (errors.current_password) { + currentPasswordInput.current?.focus(); + } + }} + className="space-y-6" + > + {({ errors, processing }) => ( + <> +
+ + + + + +
+ +
+ + + + + +
+ +
+ + + + + +
+ +
+ +
+ + )} +
+
+ + ); +} diff --git a/resources/js/types/auth.ts b/resources/js/types/auth.ts new file mode 100755 index 0000000..9c0e1d2 --- /dev/null +++ b/resources/js/types/auth.ts @@ -0,0 +1,13 @@ +export type User = { + id: number; + name: string; + email: string; + avatar?: string; + created_at: string; + updated_at: string; + [key: string]: unknown; +}; + +export type Auth = { + user: User; +}; diff --git a/resources/js/types/global.d.ts b/resources/js/types/global.d.ts new file mode 100755 index 0000000..c8058eb --- /dev/null +++ b/resources/js/types/global.d.ts @@ -0,0 +1,17 @@ +import type { Auth } from '@/types/auth'; + +declare module 'react' { + interface InputHTMLAttributes { + passwordrules?: string; + } +} + +declare module '@inertiajs/core' { + export interface InertiaConfig { + sharedPageProps: { + name: string; + auth: Auth; + [key: string]: unknown; + }; + } +} diff --git a/resources/js/types/index.ts b/resources/js/types/index.ts new file mode 100755 index 0000000..b1f0ee6 --- /dev/null +++ b/resources/js/types/index.ts @@ -0,0 +1,3 @@ +export type * from './auth'; +export type * from './navigation'; +export type * from './ui'; diff --git a/resources/js/types/navigation.ts b/resources/js/types/navigation.ts new file mode 100755 index 0000000..b7ccfe3 --- /dev/null +++ b/resources/js/types/navigation.ts @@ -0,0 +1,9 @@ +import type { InertiaLinkProps } from '@inertiajs/react'; +import type { LucideIcon } from 'lucide-react'; + +export type NavItem = { + title: string; + href: NonNullable; + icon?: LucideIcon | null; + isActive?: boolean; +}; diff --git a/resources/js/types/planner.ts b/resources/js/types/planner.ts new file mode 100755 index 0000000..0ed6be0 --- /dev/null +++ b/resources/js/types/planner.ts @@ -0,0 +1,19 @@ +export type Marker = { + id: number; + name: string; + color: string; +}; + +export type VacationPeriod = { + id: number; + marker_id: number; + start_date: string; + end_date: string; +}; + +export type PlannerPageProps = { + year: number; + years: number[]; + markers: Marker[]; + periods: VacationPeriod[]; +}; diff --git a/resources/js/types/ui.ts b/resources/js/types/ui.ts new file mode 100755 index 0000000..78e1a2b --- /dev/null +++ b/resources/js/types/ui.ts @@ -0,0 +1,13 @@ +import type { ReactNode } from 'react'; + +export type FlashToast = { + type: 'success' | 'info' | 'warning' | 'error'; + message: string; +}; + +export type AuthLayoutProps = { + children?: ReactNode; + name?: string; + title?: string; + description?: string; +}; diff --git a/resources/js/types/vite-env.d.ts b/resources/js/types/vite-env.d.ts new file mode 100755 index 0000000..11f02fe --- /dev/null +++ b/resources/js/types/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/resources/views/app.blade.php b/resources/views/app.blade.php new file mode 100755 index 0000000..20ce3be --- /dev/null +++ b/resources/views/app.blade.php @@ -0,0 +1,48 @@ + + ($appearance ?? 'system') == 'dark'])> + + + + + {{-- Inline script to detect system dark mode preference and apply it immediately --}} + + + {{-- Inline style to set the HTML background color based on our theme in app.css --}} + + + + + + + @fonts + + @viteReactRefresh + @vite(['resources/css/app.css', 'resources/js/app.tsx', "resources/js/pages/{$page['component']}.tsx"]) + + {{ config('app.name', 'Laravel') }} + + + + + + diff --git a/routes/console.php b/routes/console.php new file mode 100755 index 0000000..3c9adf1 --- /dev/null +++ b/routes/console.php @@ -0,0 +1,8 @@ +comment(Inspiring::quote()); +})->purpose('Display an inspiring quote'); diff --git a/routes/settings.php b/routes/settings.php new file mode 100755 index 0000000..e5390e0 --- /dev/null +++ b/routes/settings.php @@ -0,0 +1,24 @@ +group(function () { + Route::redirect('settings', '/settings/profile'); + + Route::get('settings/profile', [ProfileController::class, 'edit'])->name('profile.edit'); + Route::patch('settings/profile', [ProfileController::class, 'update'])->name('profile.update'); + Route::delete('settings/profile', [ProfileController::class, 'destroy'])->name('profile.destroy'); + + Route::get('settings/security', [SecurityController::class, 'edit']) + ->middleware(RequirePassword::class) + ->name('security.edit'); + + Route::put('settings/password', [SecurityController::class, 'update']) + ->middleware('throttle:6,1') + ->name('user-password.update'); + + Route::inertia('settings/appearance', 'settings/appearance')->name('appearance.edit'); +}); diff --git a/routes/web.php b/routes/web.php new file mode 100755 index 0000000..14f5285 --- /dev/null +++ b/routes/web.php @@ -0,0 +1,23 @@ +name('home'); + +Route::middleware(['auth'])->group(function () { + Route::get('planner', [PlannerController::class, 'index'])->name('planner'); + + Route::post('markers', [MarkerController::class, 'store'])->name('markers.store'); + Route::patch('markers/{marker}', [MarkerController::class, 'update'])->name('markers.update'); + Route::delete('markers/{marker}', [MarkerController::class, 'destroy'])->name('markers.destroy'); + + Route::post('periods', [VacationPeriodController::class, 'store'])->name('periods.store'); + Route::post('periods/toggle', [VacationPeriodController::class, 'toggle'])->name('periods.toggle'); + Route::patch('periods/{period}', [VacationPeriodController::class, 'update'])->name('periods.update'); + Route::delete('periods/{period}', [VacationPeriodController::class, 'destroy'])->name('periods.destroy'); +}); + +require __DIR__.'/settings.php'; diff --git a/storage/app/.gitignore b/storage/app/.gitignore new file mode 100755 index 0000000..fedb287 --- /dev/null +++ b/storage/app/.gitignore @@ -0,0 +1,4 @@ +* +!private/ +!public/ +!.gitignore diff --git a/storage/app/private/.gitignore b/storage/app/private/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/app/private/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/app/public/.gitignore b/storage/app/public/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/app/public/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/framework/.gitignore b/storage/framework/.gitignore new file mode 100755 index 0000000..7a0b408 --- /dev/null +++ b/storage/framework/.gitignore @@ -0,0 +1,10 @@ +compiled.php +config.php +down +events.scanned.php +lsp-*.php +maintenance.php +routes.php +routes.scanned.php +schedule-* +services.json diff --git a/storage/framework/cache/.gitignore b/storage/framework/cache/.gitignore new file mode 100755 index 0000000..d7852b8 --- /dev/null +++ b/storage/framework/cache/.gitignore @@ -0,0 +1,4 @@ +* +!data/ +!locks/ +!.gitignore diff --git a/storage/framework/cache/data/.gitignore b/storage/framework/cache/data/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/framework/cache/data/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/framework/cache/locks/.gitignore b/storage/framework/cache/locks/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/framework/cache/locks/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/framework/sessions/.gitignore b/storage/framework/sessions/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/framework/sessions/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/framework/testing/.gitignore b/storage/framework/testing/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/framework/testing/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/framework/views/.gitignore b/storage/framework/views/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/framework/views/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/storage/logs/.gitignore b/storage/logs/.gitignore new file mode 100755 index 0000000..d6b7ef3 --- /dev/null +++ b/storage/logs/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/tests/Feature/Auth/AuthenticationTest.php b/tests/Feature/Auth/AuthenticationTest.php new file mode 100755 index 0000000..98ac62c --- /dev/null +++ b/tests/Feature/Auth/AuthenticationTest.php @@ -0,0 +1,70 @@ +get(route('login')); + + $response->assertOk(); + } + + public function test_users_can_authenticate_using_the_login_screen() + { + $user = User::factory()->create(); + + $response = $this->post(route('login.store'), [ + 'email' => $user->email, + 'password' => 'password', + ]); + + $this->assertAuthenticated(); + $response->assertRedirect(route('planner', absolute: false)); + } + + public function test_users_can_not_authenticate_with_invalid_password() + { + $user = User::factory()->create(); + + $this->post(route('login.store'), [ + 'email' => $user->email, + 'password' => 'wrong-password', + ]); + + $this->assertGuest(); + } + + public function test_users_can_logout() + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post(route('logout')); + + $response->assertRedirect(route('home')); + + $this->assertGuest(); + } + + public function test_users_are_rate_limited() + { + $user = User::factory()->create(); + + RateLimiter::increment(md5('login'.implode('|', [$user->email, '127.0.0.1'])), amount: 5); + + $response = $this->post(route('login.store'), [ + 'email' => $user->email, + 'password' => 'wrong-password', + ]); + + $response->assertTooManyRequests(); + } +} diff --git a/tests/Feature/Auth/PasswordConfirmationTest.php b/tests/Feature/Auth/PasswordConfirmationTest.php new file mode 100755 index 0000000..41eadbe --- /dev/null +++ b/tests/Feature/Auth/PasswordConfirmationTest.php @@ -0,0 +1,33 @@ +create(); + + $response = $this->actingAs($user)->get(route('password.confirm')); + + $response->assertOk(); + + $response->assertInertia(fn (Assert $page) => $page + ->component('auth/confirm-password'), + ); + } + + public function test_password_confirmation_requires_authentication() + { + $response = $this->get(route('password.confirm')); + + $response->assertRedirect(route('login')); + } +} diff --git a/tests/Feature/Auth/PasswordResetTest.php b/tests/Feature/Auth/PasswordResetTest.php new file mode 100755 index 0000000..4e331e7 --- /dev/null +++ b/tests/Feature/Auth/PasswordResetTest.php @@ -0,0 +1,95 @@ +skipUnlessFortifyHas(Features::resetPasswords()); + } + + public function test_reset_password_link_screen_can_be_rendered() + { + $response = $this->get(route('password.request')); + + $response->assertOk(); + } + + public function test_reset_password_link_can_be_requested() + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.email'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class); + } + + public function test_reset_password_screen_can_be_rendered() + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.email'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) { + $response = $this->get(route('password.reset', $notification->token)); + + $response->assertOk(); + + return true; + }); + } + + public function test_password_can_be_reset_with_valid_token() + { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.email'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) { + $response = $this->post(route('password.update'), [ + 'token' => $notification->token, + 'email' => $user->email, + 'password' => 'password', + 'password_confirmation' => 'password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('login')); + + return true; + }); + } + + public function test_password_cannot_be_reset_with_invalid_token(): void + { + $user = User::factory()->create(); + + $response = $this->post(route('password.update'), [ + 'token' => 'invalid-token', + 'email' => $user->email, + 'password' => 'newpassword123', + 'password_confirmation' => 'newpassword123', + ]); + + $response->assertSessionHasErrors('email'); + } +} diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php new file mode 100755 index 0000000..28552e9 --- /dev/null +++ b/tests/Feature/Auth/RegistrationTest.php @@ -0,0 +1,39 @@ +skipUnlessFortifyHas(Features::registration()); + } + + public function test_registration_screen_can_be_rendered() + { + $response = $this->get(route('register')); + + $response->assertOk(); + } + + public function test_new_users_can_register() + { + $response = $this->post(route('register.store'), [ + 'name' => 'Test User', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + ]); + + $this->assertAuthenticated(); + $response->assertRedirect(route('planner', absolute: false)); + } +} diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php new file mode 100755 index 0000000..91454d5 --- /dev/null +++ b/tests/Feature/ExampleTest.php @@ -0,0 +1,20 @@ +get(route('home')); + + $response->assertRedirect(route('planner')); + + $this->get(route('planner'))->assertRedirect(route('login')); + } +} diff --git a/tests/Feature/MarkerTest.php b/tests/Feature/MarkerTest.php new file mode 100755 index 0000000..17c4f8e --- /dev/null +++ b/tests/Feature/MarkerTest.php @@ -0,0 +1,182 @@ +post(route('markers.store'), [])->assertRedirect(route('login')); + } + + public function test_user_can_create_marker(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post(route('markers.store'), [ + 'name' => 'Анна', + 'color' => '#db2777', + ]); + + $response->assertSessionHasNoErrors()->assertRedirect(); + + $this->assertDatabaseHas('markers', [ + 'user_id' => $user->id, + 'name' => 'Анна', + 'color' => '#db2777', + ]); + } + + public function test_marker_name_must_be_unique_per_user(): void + { + $user = User::factory()->create(); + Marker::factory()->for($user)->create(['name' => 'Анна']); + + $response = $this->actingAs($user)->post(route('markers.store'), [ + 'name' => 'Анна', + 'color' => '#db2777', + ]); + + $response->assertSessionHasErrors('name'); + + // Another user may use the same name. + $other = User::factory()->create(); + $this->actingAs($other)->post(route('markers.store'), [ + 'name' => 'Анна', + 'color' => '#db2777', + ])->assertSessionHasNoErrors(); + } + + public function test_marker_color_must_be_hex(): void + { + $user = User::factory()->create(); + + $response = $this->actingAs($user)->post(route('markers.store'), [ + 'name' => 'Анна', + 'color' => 'red', + ]); + + $response->assertSessionHasErrors('color'); + } + + public function test_marker_limit_is_enforced(): void + { + $user = User::factory()->create(); + Marker::factory()->for($user)->count(20)->create(); + + $response = $this->actingAs($user)->post(route('markers.store'), [ + 'name' => 'Лишний', + 'color' => '#123456', + ]); + + $response->assertSessionHasErrors('name'); + } + + public function test_user_can_update_own_marker(): void + { + $user = User::factory()->create(); + $marker = Marker::factory()->for($user)->create(); + + $response = $this->actingAs($user)->patch(route('markers.update', $marker), [ + 'name' => 'Новое имя', + 'color' => '#16a34a', + ]); + + $response->assertSessionHasNoErrors(); + $this->assertSame('Новое имя', $marker->refresh()->name); + } + + public function test_user_cannot_update_foreign_marker(): void + { + $owner = User::factory()->create(); + $marker = Marker::factory()->for($owner)->create(); + + $response = $this->actingAs(User::factory()->create()) + ->patch(route('markers.update', $marker), [ + 'name' => 'Взлом', + 'color' => '#000000', + ]); + + $response->assertForbidden(); + } + + public function test_deleting_marker_cascades_periods(): void + { + $user = User::factory()->create(); + $marker = Marker::factory()->for($user)->create(); + VacationPeriod::factory()->for($user)->for($marker)->create(); + + $response = $this->actingAs($user)->delete(route('markers.destroy', $marker)); + + $response->assertSessionHasNoErrors(); + $this->assertDatabaseMissing('markers', ['id' => $marker->id]); + $this->assertDatabaseCount('vacation_periods', 0); + } + + public function test_user_cannot_delete_foreign_marker(): void + { + $owner = User::factory()->create(); + $marker = Marker::factory()->for($owner)->create(); + + $this->actingAs(User::factory()->create()) + ->delete(route('markers.destroy', $marker)) + ->assertForbidden(); + } + + public function test_planner_page_contains_only_own_data(): void + { + $user = User::factory()->create(); + $marker = Marker::factory()->for($user)->create(); + VacationPeriod::factory()->for($user)->for($marker)->create([ + 'start_date' => '2026-07-06', + 'end_date' => '2026-07-19', + ]); + + $foreign = User::factory()->create(); + Marker::factory()->for($foreign)->create(); + + $this->actingAs($user) + ->get(route('planner', ['year' => 2026])) + ->assertOk() + ->assertInertia(fn (Assert $page) => $page + ->component('planner') + ->where('year', 2026) + ->has('markers', 1) + ->has('periods', 1) + ->where('periods.0.start_date', '2026-07-06') + ->where('periods.0.end_date', '2026-07-19'), + ); + } + + public function test_planner_includes_cross_year_periods(): void + { + $user = User::factory()->create(); + $marker = Marker::factory()->for($user)->create(); + VacationPeriod::factory()->for($user)->for($marker)->create([ + 'start_date' => '2026-12-28', + 'end_date' => '2027-01-08', + ]); + + $this->actingAs($user) + ->get(route('planner', ['year' => 2027])) + ->assertInertia(fn (Assert $page) => $page->has('periods', 1)); + } + + public function test_planner_rejects_out_of_range_year(): void + { + $user = User::factory()->create(); + + $this->actingAs($user) + ->get(route('planner', ['year' => 1900])) + ->assertInertia(fn (Assert $page) => $page->where('year', (int) date('Y'))); + } +} diff --git a/tests/Feature/Settings/ProfileUpdateTest.php b/tests/Feature/Settings/ProfileUpdateTest.php new file mode 100755 index 0000000..b30d5bc --- /dev/null +++ b/tests/Feature/Settings/ProfileUpdateTest.php @@ -0,0 +1,123 @@ +create(); + + $response = $this + ->actingAs($user) + ->get(route('profile.edit')); + + $response->assertOk(); + } + + public function test_profile_information_can_be_updated() + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->patch(route('profile.update'), [ + 'name' => 'Test User', + 'email' => 'test@example.com', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('profile.edit')); + + $user->refresh(); + + $this->assertSame('Test User', $user->name); + $this->assertSame('test@example.com', $user->email); + } + + public function test_email_is_stored_in_lowercase_so_the_user_can_still_log_in() + { + $user = User::factory()->create(); + + $this + ->actingAs($user) + ->patch(route('profile.update'), [ + 'name' => 'Test User', + 'email' => 'Test@Example.com', + ]) + ->assertSessionHasNoErrors(); + + $this->assertSame('test@example.com', $user->refresh()->email); + + $this->post(route('logout')); + + $this->post(route('login.store'), [ + 'email' => 'Test@Example.com', + 'password' => 'password', + ]); + + $this->assertAuthenticatedAs($user); + } + + public function test_email_must_be_unique_regardless_of_case() + { + User::factory()->create(['email' => 'taken@example.com']); + + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from(route('profile.edit')) + ->patch(route('profile.update'), [ + 'name' => 'Test User', + 'email' => 'Taken@Example.com', + ]); + + $response + ->assertSessionHasErrors('email') + ->assertRedirect(route('profile.edit')); + } + + public function test_user_can_delete_their_account() + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->delete(route('profile.destroy'), [ + 'password' => 'password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('home')); + + $this->assertGuest(); + $this->assertNull($user->fresh()); + } + + public function test_correct_password_must_be_provided_to_delete_account() + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from(route('profile.edit')) + ->delete(route('profile.destroy'), [ + 'password' => 'wrong-password', + ]); + + $response + ->assertSessionHasErrors('password') + ->assertRedirect(route('profile.edit')); + + $this->assertNotNull($user->fresh()); + } +} diff --git a/tests/Feature/Settings/SecurityTest.php b/tests/Feature/Settings/SecurityTest.php new file mode 100755 index 0000000..b5f711d --- /dev/null +++ b/tests/Feature/Settings/SecurityTest.php @@ -0,0 +1,75 @@ +create(); + + $this->actingAs($user) + ->withSession(['auth.password_confirmed_at' => time()]) + ->get(route('security.edit')) + ->assertInertia(fn (Assert $page) => $page + ->component('settings/security') + ->has('passwordRules'), + ); + } + + public function test_security_page_requires_password_confirmation() + { + $user = User::factory()->create(); + + $response = $this->actingAs($user) + ->get(route('security.edit')); + + $response->assertRedirect(route('password.confirm')); + } + + public function test_password_can_be_updated() + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from(route('security.edit')) + ->put(route('user-password.update'), [ + 'current_password' => 'password', + 'password' => 'new-password', + 'password_confirmation' => 'new-password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('security.edit')); + + $this->assertTrue(Hash::check('new-password', $user->refresh()->password)); + } + + public function test_correct_password_must_be_provided_to_update_password() + { + $user = User::factory()->create(); + + $response = $this + ->actingAs($user) + ->from(route('security.edit')) + ->put(route('user-password.update'), [ + 'current_password' => 'wrong-password', + 'password' => 'new-password', + 'password_confirmation' => 'new-password', + ]); + + $response + ->assertSessionHasErrors('current_password') + ->assertRedirect(route('security.edit')); + } +} diff --git a/tests/Feature/VacationPeriodTest.php b/tests/Feature/VacationPeriodTest.php new file mode 100755 index 0000000..b1f81a7 --- /dev/null +++ b/tests/Feature/VacationPeriodTest.php @@ -0,0 +1,159 @@ +user = User::factory()->create(); + $this->marker = Marker::factory()->for($this->user)->create(); + } + + public function test_guests_cannot_manage_periods(): void + { + $this->post(route('periods.store'), [])->assertRedirect(route('login')); + $this->post(route('periods.toggle'), [])->assertRedirect(route('login')); + } + + public function test_user_can_add_range(): void + { + $response = $this->actingAs($this->user)->post(route('periods.store'), [ + 'marker_id' => $this->marker->id, + 'start_date' => '2026-07-06', + 'end_date' => '2026-07-19', + ]); + + $response->assertSessionHasNoErrors(); + + $this->assertDatabaseHas('vacation_periods', [ + 'user_id' => $this->user->id, + 'marker_id' => $this->marker->id, + 'start_date' => '2026-07-06', + 'end_date' => '2026-07-19', + ]); + } + + public function test_end_date_must_not_be_before_start_date(): void + { + $response = $this->actingAs($this->user)->post(route('periods.store'), [ + 'marker_id' => $this->marker->id, + 'start_date' => '2026-07-19', + 'end_date' => '2026-07-06', + ]); + + $response->assertSessionHasErrors('end_date'); + } + + public function test_cannot_use_foreign_marker(): void + { + $foreign = Marker::factory()->create(); + + $response = $this->actingAs($this->user)->post(route('periods.store'), [ + 'marker_id' => $foreign->id, + 'start_date' => '2026-07-06', + 'end_date' => '2026-07-19', + ]); + + $response->assertSessionHasErrors('marker_id'); + } + + public function test_range_length_is_limited(): void + { + $response = $this->actingAs($this->user)->post(route('periods.store'), [ + 'marker_id' => $this->marker->id, + 'start_date' => '2026-01-01', + 'end_date' => '2027-12-31', + ]); + + $response->assertSessionHasErrors('end_date'); + } + + public function test_toggle_adds_and_removes_day(): void + { + $payload = [ + 'marker_id' => $this->marker->id, + 'date' => '2026-07-06', + ]; + + $this->actingAs($this->user) + ->post(route('periods.toggle'), $payload) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseCount('vacation_periods', 1); + + $this->actingAs($this->user) + ->post(route('periods.toggle'), $payload) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseCount('vacation_periods', 0); + } + + public function test_user_can_delete_own_period(): void + { + $period = VacationPeriod::factory()->for($this->user)->for($this->marker)->create(); + + $this->actingAs($this->user) + ->delete(route('periods.destroy', $period)) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseMissing('vacation_periods', ['id' => $period->id]); + } + + public function test_user_cannot_delete_foreign_period(): void + { + $period = VacationPeriod::factory()->create(); + + $this->actingAs($this->user) + ->delete(route('periods.destroy', $period)) + ->assertForbidden(); + } + + public function test_user_can_reschedule_period(): void + { + $period = VacationPeriod::factory()->for($this->user)->for($this->marker)->create([ + 'start_date' => '2026-07-06', + 'end_date' => '2026-07-12', + ]); + + $this->actingAs($this->user) + ->patch(route('periods.update', $period), [ + 'start_date' => '2026-08-01', + 'end_date' => '2026-08-10', + ]) + ->assertSessionHasNoErrors(); + + $this->assertDatabaseMissing('vacation_periods', ['id' => $period->id]); + $this->assertDatabaseHas('vacation_periods', [ + 'marker_id' => $this->marker->id, + 'start_date' => '2026-08-01', + 'end_date' => '2026-08-10', + ]); + } + + public function test_user_cannot_reschedule_foreign_period(): void + { + $period = VacationPeriod::factory()->create(); + + $this->actingAs($this->user) + ->patch(route('periods.update', $period), [ + 'start_date' => '2026-08-01', + 'end_date' => '2026-08-10', + ]) + ->assertForbidden(); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100755 index 0000000..a574f37 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,16 @@ +markTestSkipped($message ?? "Fortify feature [{$feature}] is not enabled."); + } + } +} diff --git a/tests/Unit/ExampleTest.php b/tests/Unit/ExampleTest.php new file mode 100755 index 0000000..2cc6866 --- /dev/null +++ b/tests/Unit/ExampleTest.php @@ -0,0 +1,16 @@ +assertTrue(true); + } +} diff --git a/tests/Unit/PeriodServiceTest.php b/tests/Unit/PeriodServiceTest.php new file mode 100755 index 0000000..5f8212f --- /dev/null +++ b/tests/Unit/PeriodServiceTest.php @@ -0,0 +1,178 @@ +service = new PeriodService; + $this->user = User::factory()->create(); + $this->marker = Marker::factory()->for($this->user)->create(); + } + + private function day(string $date): CarbonImmutable + { + return CarbonImmutable::parse($date); + } + + private function addRange(string $start, string $end): VacationPeriod + { + return $this->service->addRange($this->user, $this->marker, $this->day($start), $this->day($end)); + } + + /** + * @return array + */ + private function ranges(): array + { + return $this->marker->periods() + ->orderBy('start_date') + ->get(['start_date', 'end_date']) + ->map(fn (VacationPeriod $p) => [$p->start_date->format('Y-m-d'), $p->end_date->format('Y-m-d')]) + ->all(); + } + + public function test_add_range_creates_period(): void + { + $this->addRange('2026-07-06', '2026-07-19'); + + $this->assertSame([['2026-07-06', '2026-07-19']], $this->ranges()); + } + + public function test_add_range_merges_overlapping_periods(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + $this->addRange('2026-07-10', '2026-07-19'); + + $this->assertSame([['2026-07-06', '2026-07-19']], $this->ranges()); + } + + public function test_add_range_merges_adjacent_periods(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + $this->addRange('2026-07-13', '2026-07-19'); + + $this->assertSame([['2026-07-06', '2026-07-19']], $this->ranges()); + } + + public function test_add_range_keeps_distant_periods_separate(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + $this->addRange('2026-07-15', '2026-07-19'); + + $this->assertSame([['2026-07-06', '2026-07-12'], ['2026-07-15', '2026-07-19']], $this->ranges()); + } + + public function test_toggle_marks_unmarked_day(): void + { + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-06')); + + $this->assertSame([['2026-07-06', '2026-07-06']], $this->ranges()); + } + + public function test_toggle_extends_and_merges_with_neighbours(): void + { + $this->addRange('2026-07-06', '2026-07-08'); + $this->addRange('2026-07-10', '2026-07-12'); + + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-09')); + + $this->assertSame([['2026-07-06', '2026-07-12']], $this->ranges()); + } + + public function test_toggle_removes_single_day_period(): void + { + $this->addRange('2026-07-06', '2026-07-06'); + + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-06')); + + $this->assertSame([], $this->ranges()); + } + + public function test_toggle_trims_period_start(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-06')); + + $this->assertSame([['2026-07-07', '2026-07-12']], $this->ranges()); + } + + public function test_toggle_trims_period_end(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-12')); + + $this->assertSame([['2026-07-06', '2026-07-11']], $this->ranges()); + } + + public function test_toggle_splits_period_in_the_middle(): void + { + $this->addRange('2026-07-06', '2026-07-12'); + + $this->service->toggleDay($this->user, $this->marker, $this->day('2026-07-09')); + + $this->assertSame([['2026-07-06', '2026-07-08'], ['2026-07-10', '2026-07-12']], $this->ranges()); + } + + public function test_other_markers_periods_are_not_merged(): void + { + $other = Marker::factory()->for($this->user)->create(); + + $this->addRange('2026-07-06', '2026-07-12'); + $this->service->addRange($this->user, $other, $this->day('2026-07-08'), $this->day('2026-07-10')); + + $this->assertSame([['2026-07-06', '2026-07-12']], $this->ranges()); + $this->assertCount(1, $other->periods); + } + + public function test_leap_year_range(): void + { + $this->addRange('2028-02-27', '2028-03-02'); + + $this->assertSame([['2028-02-27', '2028-03-02']], $this->ranges()); + } + + public function test_cross_year_range(): void + { + $this->addRange('2026-12-28', '2027-01-08'); + + $this->assertSame([['2026-12-28', '2027-01-08']], $this->ranges()); + } + + public function test_reschedule_replaces_range_and_merges(): void + { + $period = $this->addRange('2026-07-06', '2026-07-12'); + $this->addRange('2026-07-20', '2026-07-25'); + + $this->service->reschedule( + $this->user, + $period, + $this->marker, + $this->day('2026-07-18'), + $this->day('2026-07-22'), + ); + + $this->assertSame([['2026-07-18', '2026-07-25']], $this->ranges()); + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100755 index 0000000..ca07426 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,120 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "ESNext" /* Specify what module code is generated. */, + // "rootDir": "./", /* Specify the root folder within your source files. */ + "moduleResolution": "bundler" /* Specify how TypeScript looks up a file from a given module specifier. */, + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */, + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + "noEmit": true /* Disable emitting files from a compilation. */, + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + "isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */, + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, + + /* Type Checking */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied 'any' type. */, + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */, + "paths": { + "@/*": ["./resources/js/*"] + }, + "jsx": "react-jsx" + }, + "include": [ + "resources/js/**/*.ts", + "resources/js/**/*.d.ts", + "resources/js/**/*.tsx" + ] +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100755 index 0000000..f93521c --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,77 @@ +import inertia from '@inertiajs/vite'; +import { wayfinder } from '@laravel/vite-plugin-wayfinder'; +import babel from '@rolldown/plugin-babel'; +import tailwindcss from '@tailwindcss/vite'; +import react, { reactCompilerPreset } from '@vitejs/plugin-react'; +import laravel from 'laravel-vite-plugin'; +import { bunny } from 'laravel-vite-plugin/fonts'; +import { defineConfig, lazyPlugins } from 'vite-plus'; + +export default defineConfig({ + plugins: lazyPlugins(() => [ + laravel({ + input: ['resources/css/app.css', 'resources/js/app.tsx'], + refresh: true, + fonts: [ + bunny('Instrument Sans', { + weights: [400, 500, 600], + }), + ], + }), + inertia(), + react(), + babel({ + presets: [reactCompilerPreset()], + }), + tailwindcss(), + wayfinder({ + formVariants: true, + }), + ]), + server: { + watch: { + ignored: [ + '**/.agents/**', + '**/.claude/**', + '**/.cursor/**', + '**/.junie/**', + '**/vendor/**', + ], + }, + }, + lint: { + ignorePatterns: [ + 'vendor/**', + 'node_modules/**', + 'public/**', + 'bootstrap/ssr/**', + 'tailwind.config.js', + 'resources/js/actions/**', + 'resources/js/components/ui/*', + 'resources/js/routes/**', + 'resources/js/wayfinder/**', + ], + options: { + denyWarnings: true, + typeAware: true, + }, + }, + fmt: { + printWidth: 80, + tabWidth: 4, + singleQuote: true, + semi: true, + singleAttributePerLine: false, + htmlWhitespaceSensitivity: 'css', + ignorePatterns: [ + '.github/**', + 'composer.json', + 'resources/js/components/ui/*', + 'resources/views/mail/*', + ], + sortTailwindcss: { + functions: ['clsx', 'cn', 'cva'], + stylesheet: 'resources/css/app.css', + }, + }, +});