commit 12.01
This commit is contained in:
@@ -5,61 +5,31 @@ namespace App\Http\Controllers;
|
|||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\Validator;
|
use Illuminate\Support\Facades\Validator;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
|
||||||
|
|
||||||
class AuthController extends Controller
|
class AuthController extends Controller
|
||||||
{
|
{
|
||||||
// Регистрация нового пользователя
|
|
||||||
public function register(Request $request)
|
|
||||||
{
|
|
||||||
$validator = Validator::make($request->all(), [
|
|
||||||
'name' => 'required|string|max:255',
|
|
||||||
'email' => 'required|email|unique:users,email',
|
|
||||||
'password' => 'required|string|min:6',
|
|
||||||
]);
|
|
||||||
|
|
||||||
if ($validator->fails()) {
|
|
||||||
return response()->json([
|
|
||||||
'message' => 'Ошибка валидации',
|
|
||||||
'errors' => $validator->errors()
|
|
||||||
], 422);
|
|
||||||
}
|
|
||||||
|
|
||||||
$user = \App\Models\User::create([
|
|
||||||
'name' => $request->name,
|
|
||||||
'email' => $request->email,
|
|
||||||
'password' => bcrypt($request->password),
|
|
||||||
'phone' => $request->phone ?? null,
|
|
||||||
'role' => 'client', // по умолчанию клиент
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Создаём токен для Sanctum
|
|
||||||
$token = $user->createToken('main-token')->plainTextToken;
|
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'message' => 'Пользователь создан',
|
|
||||||
'user' => $user,
|
|
||||||
'token' => $token
|
|
||||||
], 201);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Вход
|
|
||||||
public function login(Request $request)
|
public function login(Request $request)
|
||||||
{
|
{
|
||||||
$credentials = $request->only('email', 'password');
|
$request->validate([
|
||||||
|
'email' => 'required|email',
|
||||||
|
'password' => 'required'
|
||||||
|
]);
|
||||||
|
|
||||||
if (!Auth::attempt($credentials)) {
|
$user = \App\Models\User::where('email', $request->email)->first();
|
||||||
return response()->json([
|
|
||||||
'message' => 'Неверный email или пароль'
|
if (!$user || !Hash::check($request->password, $user->password)) {
|
||||||
], 401);
|
return response()->json(['message' => 'Неверный email или пароль'], 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
$user = Auth::user();
|
$token = $user->createToken('auth_token')->plainTextToken;
|
||||||
$token = $user->createToken('main-token')->plainTextToken;
|
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'message' => 'Успешный вход',
|
'access_token' => $token,
|
||||||
'user' => $user,
|
'token_type' => 'Bearer',
|
||||||
'token' => $token
|
'user' => $user
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,168 +2,92 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\EmployeeAvailability;
|
|
||||||
use App\Models\User;
|
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use App\Models\EmployeeAvailability;
|
||||||
|
|
||||||
class AvailabilitiesController extends Controller
|
class AvailabilitiesController extends Controller
|
||||||
{
|
{
|
||||||
// GET api/admin/availabilities?employee_id=5&date=2025-06-15
|
|
||||||
public function index(Request $request)
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$query = EmployeeAvailability::query();
|
$availabilities = EmployeeAvailability::with('employee')
|
||||||
|
->when($request->has('employee_id'), function ($query) use ($request) {
|
||||||
if ($request->employee_id) {
|
|
||||||
$query->where('employee_id', $request->employee_id);
|
$query->where('employee_id', $request->employee_id);
|
||||||
}
|
})
|
||||||
if ($request->date) {
|
->when($request->has('date'), function ($query) use ($request) {
|
||||||
$query->where('date', $request->date);
|
$query->where('date', $request->date);
|
||||||
}
|
})
|
||||||
|
->get();
|
||||||
|
|
||||||
$availabilities = $query->get();
|
|
||||||
return response()->json($availabilities);
|
return response()->json($availabilities);
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST api/admin/availabilities - создать один слот
|
|
||||||
public function store(Request $request)
|
public function store(Request $request)
|
||||||
{
|
{
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'employee_id' => 'required|exists:users,id',
|
'employee_id' => 'required|exists:users,id',
|
||||||
'date' => 'required|date',
|
'date' => 'required|date',
|
||||||
'starttime' => 'required',
|
'start_time' => 'required|date_format:H:i:s',
|
||||||
'endtime' => 'required|after:starttime',
|
'end_time' => 'required|date_format:H:i:s|after:start_time',
|
||||||
'isavailable' => 'boolean'
|
'is_available' => 'boolean'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$availability = EmployeeAvailability::create($request->all());
|
$availability = EmployeeAvailability::create($validated);
|
||||||
|
|
||||||
return response()->json($availability, 201);
|
return response()->json($availability, 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST api/admin/availabilities/bulk - создать несколько слотов
|
|
||||||
public function bulkStore(Request $request)
|
public function bulkStore(Request $request)
|
||||||
{
|
{
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'employee_id' => 'required|exists:users,id',
|
'employee_id' => 'required|exists:users,id',
|
||||||
'date' => 'required|date',
|
'date' => 'required|date',
|
||||||
'intervals' => 'required|array|min:1'
|
'intervals' => 'required|array'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$availabilities = [];
|
|
||||||
foreach ($request->intervals as $interval) {
|
foreach ($request->intervals as $interval) {
|
||||||
$availability = EmployeeAvailability::create([
|
EmployeeAvailability::create([
|
||||||
'employee_id' => $request->employee_id,
|
'employee_id' => $request->employee_id,
|
||||||
'date' => $request->date,
|
'date' => $request->date,
|
||||||
'starttime' => $interval['start'],
|
'start_time' => $interval['start'],
|
||||||
'endtime' => $interval['end'],
|
'end_time' => $interval['end'],
|
||||||
'isavailable' => true
|
'is_available' => true
|
||||||
]);
|
]);
|
||||||
$availabilities[] = $availability;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json($availabilities, 201);
|
return response()->json(['message' => 'Расписание добавлено']);
|
||||||
}
|
}
|
||||||
|
|
||||||
// DELETE api/admin/availabilities/{id} - удалить слот (брони остаются!)
|
|
||||||
public function destroy($id)
|
public function destroy($id)
|
||||||
{
|
{
|
||||||
$availability = EmployeeAvailability::findOrFail($id);
|
$availability = EmployeeAvailability::findOrFail($id);
|
||||||
$availability->delete();
|
$availability->delete();
|
||||||
|
|
||||||
return response()->json(['message' => 'Слот удален из расписания (брони сохранены)']);
|
return response()->json(['message' => 'Слот удалён']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ✅ Единственный метод publicAvailability
|
||||||
public function publicAvailability(Request $request)
|
public function publicAvailability(Request $request)
|
||||||
{
|
{
|
||||||
$serviceId = $request->query('service_id');
|
$serviceId = $request->query('service_id');
|
||||||
$date = $request->query('date');
|
$date = $request->query('date');
|
||||||
|
|
||||||
if (!$serviceId || !$date) {
|
if (!$serviceId || !$date) {
|
||||||
return response()->json(['error' => 'service_id и date обязательны'], 400);
|
return response()->json([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Найти услугу и получить длительность
|
$availabilities = EmployeeAvailability::where('date', $date)
|
||||||
$service = \App\Models\Services::find($serviceId);
|
->where('is_available', true)
|
||||||
if (!$service) {
|
|
||||||
return response()->json(['error' => 'Услуга не найдена'], 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
$durationMinutes = $service->durationminutes;
|
|
||||||
|
|
||||||
// Найти сотрудников с расписанием на эту дату
|
|
||||||
$availabilities = \App\Models\EmployeeAvailability::where('date', $date)
|
|
||||||
->where('isavailable', true)
|
|
||||||
->with('employee') // связь с User
|
|
||||||
->get();
|
->get();
|
||||||
|
|
||||||
$freeSlots = [];
|
$slots = [];
|
||||||
|
foreach ($availabilities as $avail) {
|
||||||
foreach ($availabilities as $availability) {
|
$slots[] = [
|
||||||
$employeeId = $availability->employee_id;
|
'employee_id' => $avail->employee_id,
|
||||||
|
'start' => substr($avail->start_time, 0, 5),
|
||||||
// Найти занятые слоты этого сотрудника
|
'end' => substr($avail->end_time, 0, 5),
|
||||||
$bookings = \App\Models\Booking::where('employee_id', $employeeId)
|
|
||||||
->where('bookingdate', $date)
|
|
||||||
->where('status', '!=', 'cancelled')
|
|
||||||
->pluck('starttime', 'endtime');
|
|
||||||
|
|
||||||
// Генерировать возможные слоты с учетом duration
|
|
||||||
$start = new \DateTime($availability->starttime);
|
|
||||||
$end = new \DateTime($availability->endtime);
|
|
||||||
|
|
||||||
$current = clone $start;
|
|
||||||
while ($current < $end) {
|
|
||||||
$slotEnd = clone $current;
|
|
||||||
$slotEnd->modify("+{$durationMinutes} minutes");
|
|
||||||
|
|
||||||
// Проверить пересечение с бронями
|
|
||||||
$isFree = true;
|
|
||||||
foreach ($bookings as $bookingStart => $bookingEnd) {
|
|
||||||
$bookingStartTime = new \DateTime($bookingStart);
|
|
||||||
$bookingEndTime = new \DateTime($bookingEnd);
|
|
||||||
|
|
||||||
if ($current < $bookingEndTime && $slotEnd > $bookingStartTime) {
|
|
||||||
$isFree = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($isFree && $slotEnd <= $end) {
|
|
||||||
$freeSlots[] = [
|
|
||||||
'employee_id' => $employeeId,
|
|
||||||
'start' => $current->format('H:i'),
|
|
||||||
'end' => $slotEnd->format('H:i')
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
$current->modify('+30 minutes'); // шаг 30 мин
|
return response()->json($slots);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return response()->json($freeSlots);
|
|
||||||
}
|
|
||||||
public function cancel(Request $request, $id)
|
|
||||||
{
|
|
||||||
$booking = Booking::findOrFail($id);
|
|
||||||
|
|
||||||
// Проверка: только автор брони может отменить
|
|
||||||
if ($booking->client_id != auth()->id()) {
|
|
||||||
return response()->json(['error' => 'Можете отменить только свою бронь'], 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Проверка: нельзя отменить уже отмененную/выполненную
|
|
||||||
if ($booking->status != 'confirmed') {
|
|
||||||
return response()->json(['error' => 'Можно отменить только подтвержденные брони'], 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Обновить статус
|
|
||||||
$booking->update([
|
|
||||||
'status' => 'cancelled',
|
|
||||||
'cancelledby' => 'client',
|
|
||||||
'cancelreason' => $request->reason ?? null
|
|
||||||
]);
|
|
||||||
|
|
||||||
return response()->json([
|
|
||||||
'message' => 'Бронь отменена',
|
|
||||||
'booking' => $booking
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,165 +2,112 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\Booking;
|
|
||||||
use App\Models\Services;
|
|
||||||
use App\Models\EmployeeAvailability;
|
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Str;
|
use App\Models\Booking;
|
||||||
|
use App\Models\Service;
|
||||||
|
use App\Models\User;
|
||||||
|
|
||||||
class BookingsController extends Controller
|
class BookingsController extends Controller
|
||||||
{
|
{
|
||||||
public function store(Request $request)
|
public function store(Request $request)
|
||||||
{
|
{
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'service_id' => 'required|exists:services,id',
|
'service_id' => 'required|exists:services,id',
|
||||||
'employee_id' => 'required|exists:users,id',
|
'employee_id' => 'required|exists:users,id',
|
||||||
'date' => 'required|date',
|
'date' => 'required|date',
|
||||||
'starttime' => 'required'
|
'start_time' => 'required|date_format:H:i:s'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$clientId = auth()->id();
|
// Получаем длительность услуги
|
||||||
if (!$clientId) {
|
$service = Service::findOrFail($validated['service_id']);
|
||||||
return response()->json(['error' => 'Авторизация обязательна'], 401);
|
$duration = $service->duration_minutes;
|
||||||
}
|
|
||||||
|
|
||||||
$service = Services::where('id', $request->service_id)
|
// Вычисляем end_time
|
||||||
->where('isactive', true)
|
$start = new \DateTime($validated['start_time']);
|
||||||
->first();
|
$end = clone $start;
|
||||||
if (!$service) {
|
$end->modify("+$duration minutes");
|
||||||
return response()->json(['error' => 'Услуга неактивна или не найдена'], 400);
|
$end_time = $end->format('H:i:s');
|
||||||
}
|
|
||||||
|
|
||||||
$durationMinutes = $service->durationminutes;
|
// Проверяем, свободен ли слот
|
||||||
$endtime = date('H:i:s', strtotime($request->starttime . " +{$durationMinutes} minutes"));
|
$conflict = Booking::where('employee_id', $validated['employee_id'])
|
||||||
|
->where('booking_date', $validated['date'])
|
||||||
$availability = EmployeeAvailability::where('employee_id', $request->employee_id)
|
->where('start_time', '<', $end_time)
|
||||||
->where('date', $request->date)
|
->where('end_time', '>', $validated['start_time'])
|
||||||
->where('starttime', '<=', $request->starttime)
|
|
||||||
->where('endtime', '>=', $endtime)
|
|
||||||
->where('isavailable', true)
|
|
||||||
->first();
|
|
||||||
|
|
||||||
if (!$availability) {
|
|
||||||
return response()->json(['error' => 'Сотрудник недоступен в это время'], 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$bookingExists = Booking::where('employee_id', $request->employee_id)
|
|
||||||
->where('bookingdate', $request->date)
|
|
||||||
->where('starttime', $request->starttime)
|
|
||||||
->whereIn('status', ['confirmed', 'completed'])
|
|
||||||
->exists();
|
->exists();
|
||||||
|
|
||||||
if ($bookingExists) {
|
if ($conflict) {
|
||||||
return response()->json(['error' => 'Слот уже забронирован'], 400);
|
return response()->json(['message' => 'Слот занят'], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
$bookingNumber = 'CL-' . date('Y') . '-' . str_pad(Booking::count() + 1, 4, '0', STR_PAD_LEFT);
|
// Создаём бронирование
|
||||||
|
|
||||||
$booking = Booking::create([
|
$booking = Booking::create([
|
||||||
'bookingnumber' => $bookingNumber,
|
'booking_number' => 'CL-' . date('Y') . '-' . str_pad(Booking::count() + 1, 4, '0', STR_PAD_LEFT),
|
||||||
'client_id' => $clientId,
|
'client_id' => auth()->id(),
|
||||||
'employee_id' => $request->employee_id,
|
'employee_id' => $validated['employee_id'],
|
||||||
'service_id' => $request->service_id,
|
'service_id' => $validated['service_id'],
|
||||||
'bookingdate' => $request->date,
|
'booking_date' => $validated['date'],
|
||||||
'starttime' => $request->starttime,
|
'start_time' => $validated['start_time'],
|
||||||
'endtime' => $endtime,
|
'end_time' => $end_time,
|
||||||
'status' => 'confirmed'
|
'status' => 'confirmed'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json($booking, 201);
|
||||||
'booking' => $booking,
|
|
||||||
'message' => 'Бронирование создано №' . $bookingNumber
|
|
||||||
], 201);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function cancel(Request $request, $id)
|
public function clientIndex()
|
||||||
|
{
|
||||||
|
$bookings = Booking::where('client_id', auth()->id())->get();
|
||||||
|
return response()->json($bookings);
|
||||||
|
}
|
||||||
|
|
||||||
|
// adminIndex
|
||||||
|
public function adminIndex()
|
||||||
|
{
|
||||||
|
$bookings = Booking::with(['client', 'employee', 'service'])
|
||||||
|
->orderBy('booking_date', 'desc')
|
||||||
|
->get();
|
||||||
|
return response()->json($bookings);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cancel($id)
|
||||||
{
|
{
|
||||||
$booking = Booking::findOrFail($id);
|
$booking = Booking::findOrFail($id);
|
||||||
|
|
||||||
if ($booking->client_id != auth()->id()) {
|
if ($booking->client_id !== auth()->id()) {
|
||||||
return response()->json(['error' => 'Можете отменить только свою бронь'], 403);
|
return response()->json(['message' => 'Нет прав'], 403);
|
||||||
}
|
|
||||||
|
|
||||||
if ($booking->status != 'confirmed') {
|
|
||||||
return response()->json(['error' => 'Можно отменить только подтвержденные'], 400);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$booking->update([
|
$booking->update([
|
||||||
'status' => 'cancelled',
|
'status' => 'cancelled',
|
||||||
'cancelledby' => 'client',
|
'cancelled_by' => 'client',
|
||||||
'cancelreason' => $request->reason ?? null
|
'cancel_reason' => request('reason')
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json(['message' => 'Бронь отменена']);
|
||||||
'message' => 'Бронь отменена',
|
|
||||||
'booking' => $booking
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function adminCancel(Request $request, $id)
|
// adminCancel
|
||||||
|
public function adminCancel($id)
|
||||||
{
|
{
|
||||||
$booking = Booking::findOrFail($id);
|
$booking = Booking::findOrFail($id);
|
||||||
|
|
||||||
if (!auth()->user()->isEmployeeOrAdmin()) {
|
|
||||||
return response()->json(['error' => 'Доступ только для админов/сотрудников'], 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$booking->update([
|
$booking->update([
|
||||||
'status' => 'cancelled',
|
'status' => 'cancelled',
|
||||||
'cancelledby' => 'admin',
|
'cancelled_by' => 'admin',
|
||||||
'cancelreason' => $request->reason ?? null
|
'cancel_reason' => request('reason')
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json(['message' => 'Бронь отменена администратором']);
|
||||||
'message' => 'Бронь отменена администратором',
|
|
||||||
'booking' => $booking
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function clientIndex(Request $request)
|
// Назначение сотрудника
|
||||||
|
public function assignEmployee(Request $request, $id)
|
||||||
{
|
{
|
||||||
$clientId = auth()->id();
|
$request->validate(['employee_id' => 'required|exists:users,id']);
|
||||||
|
|
||||||
$query = Booking::where('client_id', $clientId);
|
$booking = Booking::findOrFail($id);
|
||||||
|
$booking->employee_id = $request->employee_id;
|
||||||
|
$booking->save();
|
||||||
|
|
||||||
if ($request->date) {
|
return response()->json($booking);
|
||||||
$query->where('bookingdate', $request->date);
|
|
||||||
}
|
|
||||||
if ($request->status) {
|
|
||||||
$query->where('status', $request->status);
|
|
||||||
}
|
|
||||||
|
|
||||||
$bookings = $query->with(['service', 'employee'])
|
|
||||||
->orderBy('bookingdate', 'desc')
|
|
||||||
->orderBy('starttime', 'asc')
|
|
||||||
->get();
|
|
||||||
|
|
||||||
return response()->json($bookings);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function adminIndex(Request $request)
|
|
||||||
{
|
|
||||||
if (!auth()->user()->isEmployeeOrAdmin()) {
|
|
||||||
return response()->json(['error' => 'Доступ запрещен'], 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$query = Booking::with(['service', 'client', 'employee']);
|
|
||||||
|
|
||||||
if ($request->date) {
|
|
||||||
$query->where('bookingdate', $request->date);
|
|
||||||
}
|
|
||||||
if ($request->status) {
|
|
||||||
$query->where('status', $request->status);
|
|
||||||
}
|
|
||||||
if ($request->employee_id) {
|
|
||||||
$query->where('employee_id', $request->employee_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
$bookings = $query->orderBy('bookingdate', 'desc')
|
|
||||||
->orderBy('starttime', 'asc')
|
|
||||||
->get();
|
|
||||||
|
|
||||||
return response()->json($bookings);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,78 +2,60 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\Services;
|
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
use App\Models\Service;
|
||||||
|
|
||||||
class ServicesController extends Controller
|
class ServicesController extends Controller
|
||||||
{
|
{
|
||||||
// GET api/admin/services - список активных услуг
|
|
||||||
public function index()
|
public function index()
|
||||||
{
|
{
|
||||||
$services = Services::where('isactive', true)->get();
|
$services = Service::all();
|
||||||
return response()->json($services);
|
return response()->json($services);
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST api/admin/services - создать услугу
|
|
||||||
public function store(Request $request)
|
public function store(Request $request)
|
||||||
{
|
{
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'name' => 'required|string|max:255',
|
'name' => 'required|string|max:255',
|
||||||
'description' => 'required|string',
|
'description' => 'nullable|string',
|
||||||
'durationminutes' => 'required|integer|min:1|max:500',
|
'duration_minutes' => 'required|integer',
|
||||||
'price' => 'required|numeric|min:0'
|
'price' => 'required|numeric',
|
||||||
|
'is_active' => 'boolean'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$service = Services::create([
|
$service = Service::create($validated);
|
||||||
'name' => $request->name,
|
|
||||||
'description' => $request->description,
|
|
||||||
'durationminutes' => $request->durationminutes,
|
|
||||||
'price' => $request->price,
|
|
||||||
'isactive' => true // по умолчанию активна
|
|
||||||
]);
|
|
||||||
|
|
||||||
return response()->json($service, 201);
|
return response()->json($service, 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PUT api/admin/services/{id} - обновить услугу
|
|
||||||
public function update(Request $request, $id)
|
public function update(Request $request, $id)
|
||||||
{
|
{
|
||||||
$service = Services::findOrFail($id);
|
$service = Service::findOrFail($id);
|
||||||
|
|
||||||
$request->validate([
|
$validated = $request->validate([
|
||||||
'name' => 'required|string|max:255',
|
'name' => 'required|string|max:255',
|
||||||
'description' => 'required|string',
|
'description' => 'nullable|string',
|
||||||
'durationminutes' => 'required|integer|min:1|max:500',
|
'duration_minutes' => 'required|integer',
|
||||||
'price' => 'required|numeric|min:0'
|
'price' => 'required|numeric',
|
||||||
|
'is_active' => 'boolean'
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$service->update([
|
$service->update($validated);
|
||||||
'name' => $request->name,
|
|
||||||
'description' => $request->description,
|
|
||||||
'durationminutes' => $request->durationminutes,
|
|
||||||
'price' => $request->price,
|
|
||||||
]);
|
|
||||||
|
|
||||||
return response()->json($service);
|
return response()->json($service);
|
||||||
}
|
}
|
||||||
|
|
||||||
// DELETE api/admin/services/{id} - только если нет активных броней
|
|
||||||
public function destroy($id)
|
public function destroy($id)
|
||||||
{
|
{
|
||||||
$service = Services::findOrFail($id);
|
$service = Service::findOrFail($id);
|
||||||
|
|
||||||
// ПРОВЕРКА: нельзя удалить услугу с активными бронями
|
|
||||||
$activeBookings = \App\Models\Booking::where('service_id', $id)
|
|
||||||
->where('status', '!=', 'cancelled')
|
|
||||||
->exists();
|
|
||||||
|
|
||||||
if ($activeBookings) {
|
|
||||||
return response()->json([
|
|
||||||
'error' => 'Нельзя удалить услугу с активными бронями'
|
|
||||||
], 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
$service->delete();
|
$service->delete();
|
||||||
|
|
||||||
return response()->json(['message' => 'Услуга удалена']);
|
return response()->json(['message' => 'Услуга удалена']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function publicIndex()
|
||||||
|
{
|
||||||
|
$services = \App\Models\Service::where('is_active', true)->get();
|
||||||
|
return response()->json($services);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
48
app/Http/Kernel.php
Normal file
48
app/Http/Kernel.php
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||||
|
|
||||||
|
class Kernel extends HttpKernel
|
||||||
|
{
|
||||||
|
protected $middleware = [
|
||||||
|
\App\Http\Middleware\TrustProxies::class,
|
||||||
|
\Illuminate\Http\Middleware\HandleCors::class,
|
||||||
|
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||||
|
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||||
|
\App\Http\Middleware\TrimStrings::class,
|
||||||
|
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $middlewareGroups = [
|
||||||
|
'web' => [
|
||||||
|
\App\Http\Middleware\EncryptCookies::class,
|
||||||
|
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||||
|
\Illuminate\Session\Middleware\StartSession::class,
|
||||||
|
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||||
|
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||||
|
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||||
|
],
|
||||||
|
|
||||||
|
'api' => [
|
||||||
|
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
|
||||||
|
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $routeMiddleware = [
|
||||||
|
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||||
|
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||||
|
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||||
|
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||||
|
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||||
|
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||||
|
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||||
|
'signed' => \App\Http\Middleware\ValidateSignature::class,
|
||||||
|
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||||
|
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||||
|
|
||||||
|
'role' => \App\Http\Middleware\CheckRole::class,
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Http\Middleware;
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
use Closure;
|
use Closure;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
@@ -7,10 +9,14 @@ class CheckRole
|
|||||||
{
|
{
|
||||||
public function handle(Request $request, Closure $next, $role)
|
public function handle(Request $request, Closure $next, $role)
|
||||||
{
|
{
|
||||||
if (!auth()->check() || !auth()->user()->isEmployeeOrAdmin()) {
|
if (!$request->user()) {
|
||||||
return response()->json(['error' => 'Доступ запрещен'], 403);
|
return response()->json(['message' => 'Unauthorized'], 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($request->user()->role !== $role) {
|
||||||
|
return response()->json(['message' => 'Access denied'], 403);
|
||||||
|
}
|
||||||
|
|
||||||
return $next($request);
|
return $next($request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,39 +1,42 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
// бронирование клиентов
|
|
||||||
class Booking extends Model {
|
class Booking extends Model
|
||||||
|
{
|
||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
protected $table = 'bookings';
|
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'bookingnumber',
|
'booking_number',
|
||||||
'client_id',
|
'client_id',
|
||||||
'employee_id',
|
'employee_id',
|
||||||
'service_id',
|
'service_id',
|
||||||
'bookingdate',
|
'booking_date',
|
||||||
'starttime',
|
'start_time',
|
||||||
'endtime',
|
'end_time',
|
||||||
'status',
|
'status',
|
||||||
'cancelledby',
|
'cancelled_by',
|
||||||
'cancelreason'
|
'cancel_reason'
|
||||||
];
|
];
|
||||||
|
|
||||||
// списки броней
|
// Связь с клиентом
|
||||||
public function service()
|
|
||||||
{
|
|
||||||
return $this->belongsTo(Services::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function client()
|
public function client()
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class, 'client_id');
|
return $this->belongsTo(User::class, 'client_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Связь со сотрудником
|
||||||
public function employee()
|
public function employee()
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class, 'employee_id');
|
return $this->belongsTo(User::class, 'employee_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Связь с услугой
|
||||||
|
public function service()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Service::class);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
// расписание сотрудниĸов
|
class EmployeeAvailability extends Model
|
||||||
class EmployeeAvailability extends Model {
|
{
|
||||||
use HasFactory;
|
protected $fillable = [
|
||||||
protected $table = 'employee_availabilities';
|
'employee_id',
|
||||||
protected $fillable = ['employee_id','date','starttime','endtime','isavailable'];
|
'date',
|
||||||
|
'start_time',
|
||||||
|
'end_time',
|
||||||
|
'is_available'
|
||||||
|
];
|
||||||
}
|
}
|
||||||
@@ -2,22 +2,22 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
|
||||||
class Services extends Model // услуги ĸлининга
|
class Service extends Model
|
||||||
{
|
{
|
||||||
use HasFactory;
|
use HasFactory;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'name',
|
'name',
|
||||||
'description',
|
'description',
|
||||||
'durationminutes',
|
'duration_minutes',
|
||||||
'price',
|
'price',
|
||||||
'isactive',
|
'is_active'
|
||||||
];
|
];
|
||||||
|
|
||||||
// Простая связь с bookings, если нужно
|
// Связь с бронированиями
|
||||||
public function bookings()
|
public function bookings()
|
||||||
{
|
{
|
||||||
return $this->hasMany(Booking::class);
|
return $this->hasMany(Booking::class);
|
||||||
@@ -2,44 +2,24 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
||||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||||
use Illuminate\Notifications\Notifiable;
|
use Illuminate\Notifications\Notifiable;
|
||||||
use Laravel\Sanctum\HasApiTokens;
|
use Laravel\Sanctum\HasApiTokens;
|
||||||
|
|
||||||
class User extends Authenticatable // все пользователи системы
|
class User extends Authenticatable
|
||||||
{
|
{
|
||||||
use HasApiTokens, HasFactory, Notifiable;
|
use HasApiTokens, Notifiable;
|
||||||
|
|
||||||
protected $fillable = [
|
protected $fillable = [
|
||||||
'name',
|
'name',
|
||||||
'email',
|
'email',
|
||||||
'password',
|
'password',
|
||||||
'role',
|
'role',
|
||||||
|
'phone'
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $hidden = [
|
protected $hidden = [
|
||||||
'password',
|
'password',
|
||||||
'remember_token',
|
'remember_token',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected function casts(): array
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
'email_verified_at' => 'datetime',
|
|
||||||
'password' => 'hashed',
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Проверяет админ или сотрудник
|
|
||||||
public function isEmployeeOrAdmin()
|
|
||||||
{
|
|
||||||
return $this->role == 'employee' || $this->role == 'admin';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Для запросов - все сотрудники и админы
|
|
||||||
public static function scopeEmployeeOrAdmin($query)
|
|
||||||
{
|
|
||||||
return $query->whereIn('role', ['employee', 'admin']);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"require": {
|
"require": {
|
||||||
"php": "^8.2",
|
"php": "^8.2",
|
||||||
"laravel/framework": "^12.0",
|
"laravel/framework": "^12.0",
|
||||||
"laravel/sanctum": "^4.0",
|
"laravel/sanctum": "^4.2",
|
||||||
"laravel/tinker": "^2.10.1"
|
"laravel/tinker": "^2.10.1"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
|
|||||||
2
composer.lock
generated
2
composer.lock
generated
@@ -4,7 +4,7 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "d3c16cb86c42230c6c023d9a5d9bcf42",
|
"content-hash": "8f387a0734f3bf879214e4aa2fca6e2f",
|
||||||
"packages": [
|
"packages": [
|
||||||
{
|
{
|
||||||
"name": "brick/math",
|
"name": "brick/math",
|
||||||
|
|||||||
@@ -6,45 +6,21 @@ use Illuminate\Support\Facades\Schema;
|
|||||||
|
|
||||||
return new class extends Migration
|
return new class extends Migration
|
||||||
{
|
{
|
||||||
/**
|
public function up()
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
{
|
||||||
//таблица user
|
|
||||||
Schema::create('users', function (Blueprint $table) {
|
Schema::create('users', function (Blueprint $table) {
|
||||||
$table->id();
|
$table->id();
|
||||||
$table->string('name');
|
$table->string('name');
|
||||||
$table->string('email')->unique();
|
$table->string('email')->unique();
|
||||||
$table->string('password');
|
$table->string('password');
|
||||||
$table->enum('role',['client','admin'])->default('client');
|
$table->enum('role', ['client', 'employee', 'admin'])->default('client');
|
||||||
$table->string('phone')->nullable();
|
$table->string('phone')->nullable();
|
||||||
$table->timestamps();
|
$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();
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function down()
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
{
|
||||||
Schema::dropIfExists('users');
|
Schema::dropIfExists('users');
|
||||||
Schema::dropIfExists('password_reset_tokens');
|
|
||||||
Schema::dropIfExists('sessions');
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -6,29 +6,20 @@ use Illuminate\Support\Facades\Schema;
|
|||||||
|
|
||||||
return new class extends Migration
|
return new class extends Migration
|
||||||
{
|
{
|
||||||
/**
|
public function up()
|
||||||
* Run the migrations.
|
|
||||||
*/
|
|
||||||
public function up(): void
|
|
||||||
{
|
{
|
||||||
Schema::create('services', function (Blueprint $table) {
|
Schema::create('services', function (Blueprint $table) {
|
||||||
$table->id();
|
$table->id();
|
||||||
$table->string('name');
|
$table->string('name');
|
||||||
$table->text('description')->nullable();
|
$table->text('description')->nullable();
|
||||||
$table->decimal('price', 10, 2);
|
|
||||||
$table->integer('duration_minutes');
|
$table->integer('duration_minutes');
|
||||||
$table->unsignedBigInteger('category_id');
|
$table->decimal('price', 10, 2);
|
||||||
$table->string('image_url')->nullable();
|
$table->boolean('is_active')->default(true);
|
||||||
$table->timestamps();
|
$table->timestamps();
|
||||||
|
|
||||||
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function down()
|
||||||
* Reverse the migrations.
|
|
||||||
*/
|
|
||||||
public function down(): void
|
|
||||||
{
|
{
|
||||||
Schema::dropIfExists('services');
|
Schema::dropIfExists('services');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,28 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
use Illuminate\Database\Migrations\Migration;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
return new class extends Migration {
|
return new class extends Migration
|
||||||
public function up() {
|
{
|
||||||
|
public function up()
|
||||||
|
{
|
||||||
Schema::create('employee_availabilities', function (Blueprint $table) {
|
Schema::create('employee_availabilities', function (Blueprint $table) {
|
||||||
$table->id();
|
$table->id();
|
||||||
$table->unsignedBigInteger('employee_id');
|
$table->unsignedBigInteger('employee_id');
|
||||||
$table->date('date');
|
$table->date('date');
|
||||||
$table->time('starttime');
|
$table->time('start_time');
|
||||||
$table->time('endtime');
|
$table->time('end_time');
|
||||||
$table->boolean('isavailable')->default(true);
|
$table->boolean('is_available')->default(true);
|
||||||
$table->timestamps(); // автоматическое создание created_at и updated_at
|
$table->timestamps();
|
||||||
|
|
||||||
$table->foreign('employee_id')->references('id')->on('users');
|
$table->foreign('employee_id')->references('id')->on('users');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function down() {
|
public function down()
|
||||||
|
{
|
||||||
Schema::dropIfExists('employee_availabilities');
|
Schema::dropIfExists('employee_availabilities');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,35 +1,37 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use Illuminate\Database\Migrations\Migration;
|
use Illuminate\Database\Migrations\Migration;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
return new class extends Migration {
|
return new class extends Migration
|
||||||
public function up() {
|
{
|
||||||
|
public function up()
|
||||||
|
{
|
||||||
Schema::create('bookings', function (Blueprint $table) {
|
Schema::create('bookings', function (Blueprint $table) {
|
||||||
$table->id();
|
$table->id();
|
||||||
$table->string('bookingnumber');
|
$table->string('booking_number')->unique();
|
||||||
$table->unsignedBigInteger('client_id');
|
$table->unsignedBigInteger('client_id');
|
||||||
$table->unsignedBigInteger('employee_id');
|
$table->unsignedBigInteger('employee_id');
|
||||||
$table->unsignedBigInteger('service_id');
|
$table->unsignedBigInteger('service_id');
|
||||||
$table->date('bookingdate');
|
$table->date('booking_date');
|
||||||
$table->time('starttime');
|
$table->time('start_time');
|
||||||
$table->time('endtime');
|
$table->time('end_time');
|
||||||
$table->enum('status', ['confirmed', 'cancelled', 'completed'])->default('confirmed');
|
$table->enum('status', ['confirmed', 'cancelled', 'completed'])->default('confirmed');
|
||||||
$table->enum('cancelledby', ['client', 'admin'])->nullable();
|
$table->enum('cancelled_by', ['client', 'admin'])->nullable();
|
||||||
$table->text('cancelreason')->nullable();
|
$table->text('cancel_reason')->nullable();
|
||||||
$table->timestamps();
|
$table->timestamps();
|
||||||
|
|
||||||
// Внешние ключи
|
|
||||||
$table->foreign('client_id')->references('id')->on('users');
|
$table->foreign('client_id')->references('id')->on('users');
|
||||||
$table->foreign('employee_id')->references('id')->on('users');
|
$table->foreign('employee_id')->references('id')->on('users');
|
||||||
$table->foreign('service_id')->references('id')->on('services');
|
$table->foreign('service_id')->references('id')->on('services');
|
||||||
|
|
||||||
// УНИКАЛЬНЫЙ ИНДЕКС
|
$table->unique(['employee_id', 'booking_date', 'start_time']);
|
||||||
$table->unique(['employee_id', 'bookingdate', 'starttime'], 'unique_booking_slot');
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function down() {
|
public function down()
|
||||||
|
{
|
||||||
Schema::dropIfExists('bookings');
|
Schema::dropIfExists('bookings');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -2,24 +2,71 @@
|
|||||||
|
|
||||||
namespace Database\Seeders;
|
namespace Database\Seeders;
|
||||||
|
|
||||||
use App\Models\User;
|
|
||||||
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
|
|
||||||
use Illuminate\Database\Seeder;
|
use Illuminate\Database\Seeder;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Service;
|
||||||
|
use App\Models\EmployeeAvailability;
|
||||||
|
use App\Models\Booking;
|
||||||
|
|
||||||
class DatabaseSeeder extends Seeder
|
class DatabaseSeeder extends Seeder
|
||||||
{
|
{
|
||||||
use WithoutModelEvents;
|
public function run()
|
||||||
|
|
||||||
/**
|
|
||||||
* Seed the application's database.
|
|
||||||
*/
|
|
||||||
public function run(): void
|
|
||||||
{
|
{
|
||||||
// User::factory(10)->create();
|
// Создаём админа
|
||||||
|
User::create([
|
||||||
|
'name' => 'Админ',
|
||||||
|
'email' => 'admin@example.com',
|
||||||
|
'password' => bcrypt('123'),
|
||||||
|
'role' => 'admin'
|
||||||
|
]);
|
||||||
|
|
||||||
User::factory()->create([
|
// Создаём сотрудника
|
||||||
'name' => 'Test User',
|
User::create([
|
||||||
'email' => 'test@example.com',
|
'name' => 'Иван Петров',
|
||||||
|
'email' => 'ivan@example.com',
|
||||||
|
'password' => bcrypt('2001'),
|
||||||
|
'role' => 'employee'
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Создаём клиента
|
||||||
|
User::create([
|
||||||
|
'name' => 'Мария Иванова',
|
||||||
|
'email' => 'maria@example.com',
|
||||||
|
'password' => bcrypt('2002'),
|
||||||
|
'role' => 'client'
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Создаём услугу
|
||||||
|
Service::create([
|
||||||
|
'name' => 'Генеральная уборка',
|
||||||
|
'description' => 'Полная уборка помещения.',
|
||||||
|
'duration_minutes' => 180,
|
||||||
|
'price' => 5000.00,
|
||||||
|
'is_active' => true
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Создаём расписание для сотрудника
|
||||||
|
EmployeeAvailability::create([
|
||||||
|
'employee_id' => 2, // Иван Петров
|
||||||
|
'date' => '2026-02-10',
|
||||||
|
'start_time' => '09:00:00',
|
||||||
|
'end_time' => '18:00:00',
|
||||||
|
'is_available' => true
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Создаём бронирование
|
||||||
|
Booking::create([
|
||||||
|
'booking_number' => 'CL-2026-0001',
|
||||||
|
'client_id' => 3, // Мария Иванова
|
||||||
|
'employee_id' => 2, // Иван Петров
|
||||||
|
'service_id' => 1, // Генеральная уборка
|
||||||
|
'booking_date' => '2026-01-15',
|
||||||
|
'start_time' => '10:00:00',
|
||||||
|
'end_time' => '13:00:00',
|
||||||
|
'status' => 'confirmed'
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,393 +3,263 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Все брони - КлинСервис Админка</title>
|
<title>Админка — Бронирования</title>
|
||||||
<style>
|
<style>
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
body { font-family: Arial, sans-serif; background: #f8f9fa; }
|
body { font-family: Arial, sans-serif; background: #f8f9fa; }
|
||||||
|
|
||||||
/* Хедер */
|
|
||||||
header {
|
header {
|
||||||
background: #2c3e50; color: white; padding: 20px 50px;
|
background: white; padding: 20px 50px;
|
||||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0;
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||||
|
position: sticky; top: 0; z-index: 100;
|
||||||
}
|
}
|
||||||
.header-content {
|
.header-content {
|
||||||
max-width: 1400px; margin: 0 auto;
|
max-width: 1200px; margin: 0 auto;
|
||||||
display: flex; justify-content: space-between; align-items: center;
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
}
|
}
|
||||||
.logo { font-size: 24px; font-weight: bold; }
|
.logo { font-size: 24px; font-weight: bold; color: #667eea; }
|
||||||
.header-nav { display: flex; gap: 20px; }
|
|
||||||
.btn {
|
.btn {
|
||||||
padding: 12px 25px; border: none; border-radius: 25px;
|
padding: 10px 20px; border: none; border-radius: 25px;
|
||||||
cursor: pointer; font-size: 16px; text-decoration: none;
|
cursor: pointer; font-size: 14px; text-decoration: none;
|
||||||
display: inline-block; transition: all 0.3s; color: white;
|
display: inline-block; transition: all 0.3s;
|
||||||
}
|
}
|
||||||
.btn-primary { background: #667eea; }
|
.btn-primary { background: #667eea; color: white; }
|
||||||
.btn-primary:hover { background: #5a67d8; }
|
.btn-secondary { background: transparent; color: #667eea; border: 2px solid #667eea; }
|
||||||
.btn-secondary { background: #6c757d; }
|
|
||||||
.btn-secondary:hover { background: #5a6268; }
|
|
||||||
|
|
||||||
/* Контейнер */
|
.container { max-width: 1200px; margin: 40px auto; padding: 0 20px; }
|
||||||
.container { max-width: 1400px; margin: 40px auto; padding: 0 20px; }
|
h1 { text-align: center; margin-bottom: 30px; color: #333; }
|
||||||
h1 { text-align: center; color: #333; margin-bottom: 40px; font-size: 32px; }
|
|
||||||
|
|
||||||
/* Фильтры */
|
table { width: 100%; border-collapse: collapse; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
|
||||||
.filters {
|
th, td { padding: 15px; text-align: left; border-bottom: 1px solid #eee; }
|
||||||
background: white; padding: 30px; border-radius: 20px;
|
th { background: #667eea; color: white; }
|
||||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1); margin-bottom: 30px;
|
tr:hover { background: #f9f9f9; }
|
||||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
|
||||||
gap: 20px;
|
|
||||||
}
|
|
||||||
@media (max-width: 768px) { .filters { grid-template-columns: 1fr; } }
|
|
||||||
|
|
||||||
.filter-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #555; }
|
select, input { padding: 8px; border: 1px solid #ccc; border-radius: 5px; }
|
||||||
.filter-group input, .filter-group select {
|
.actions { display: flex; gap: 10px; margin-top: 10px; }
|
||||||
width: 100%; padding: 12px; border: 2px solid #e9ecef;
|
.btn-sm { padding: 5px 10px; font-size: 12px; }
|
||||||
border-radius: 10px; font-size: 16px;
|
.status { padding: 4px 8px; border-radius: 10px; font-size: 12px; }
|
||||||
}
|
.confirmed { background: #d4edda; color: #155724; }
|
||||||
.filter-group input:focus, .filter-group select:focus { border-color: #667eea; outline: none; }
|
.cancelled { background: #f8d7da; color: #721c24; }
|
||||||
|
.completed { background: #d1ecf1; color: #0c5460; }
|
||||||
|
|
||||||
.filter-btn {
|
.no-data { text-align: center; padding: 40px; color: #666; }
|
||||||
padding: 15px 30px; background: #667eea; color: white;
|
|
||||||
border: none; border-radius: 10px; font-size: 16px;
|
|
||||||
cursor: pointer; grid-column: span 2;
|
|
||||||
}
|
|
||||||
.filter-btn:hover { background: #5a67d8; }
|
|
||||||
|
|
||||||
/* Таблица */
|
|
||||||
.bookings-table {
|
|
||||||
background: white; border-radius: 20px;
|
|
||||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1); overflow: hidden;
|
|
||||||
}
|
|
||||||
table { width: 100%; border-collapse: collapse; }
|
|
||||||
th, td { padding: 18px 15px; text-align: left; border-bottom: 1px solid #e9ecef; }
|
|
||||||
th { background: #667eea; color: white; font-weight: bold; position: sticky; top: 0; }
|
|
||||||
tr:hover { background: #f8f9fa; }
|
|
||||||
|
|
||||||
/* Статусы */
|
|
||||||
.status { padding: 6px 12px; border-radius: 15px; font-size: 14px; font-weight: bold; }
|
|
||||||
.status.confirmed { background: #d4edda; color: #155724; }
|
|
||||||
.status.completed { background: #d1ecf1; color: #0c5460; }
|
|
||||||
.status.cancelled { background: #f8d7da; color: #721c24; }
|
|
||||||
|
|
||||||
/* Действия */
|
|
||||||
.action-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
||||||
.btn-small {
|
|
||||||
padding: 8px 14px; font-size: 13px; border-radius: 12px;
|
|
||||||
text-decoration: none; border: none; cursor: pointer; font-weight: 500;
|
|
||||||
}
|
|
||||||
.btn-complete { background: #28a745; color: white; }
|
|
||||||
.btn-complete:hover { background: #218838; }
|
|
||||||
.btn-cancel-admin { background: #dc3545; color: white; }
|
|
||||||
.btn-cancel-admin:hover { background: #c82333; }
|
|
||||||
|
|
||||||
/* Модальное окно */
|
|
||||||
.modal {
|
|
||||||
display: none; position: fixed; top: 0; left: 0;
|
|
||||||
width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;
|
|
||||||
}
|
|
||||||
.modal-content {
|
|
||||||
background: white; margin: 10% auto; padding: 40px;
|
|
||||||
border-radius: 20px; max-width: 500px; width: 90%; position: relative;
|
|
||||||
}
|
|
||||||
.close {
|
|
||||||
position: absolute; top: 15px; right: 20px; font-size: 28px;
|
|
||||||
cursor: pointer; color: #999;
|
|
||||||
}
|
|
||||||
.close:hover { color: #333; }
|
|
||||||
.modal textarea {
|
|
||||||
width: 100%; height: 100px; padding: 15px;
|
|
||||||
border: 2px solid #e9ecef; border-radius: 10px;
|
|
||||||
font-family: Arial, sans-serif; resize: vertical; margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
.modal-buttons { display: flex; gap: 15px; }
|
|
||||||
.btn-modal { flex: 1; padding: 15px; border: none; border-radius: 10px; font-size: 16px; cursor: pointer; }
|
|
||||||
.btn-confirm { background: #dc3545; color: white; }
|
|
||||||
.btn-confirm:hover { background: #c82333; }
|
|
||||||
|
|
||||||
.no-bookings { text-align: center; padding: 80px 40px; color: #666; font-size: 18px; }
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
th, td { padding: 12px 8px; font-size: 14px; }
|
|
||||||
.action-buttons { flex-direction: column; }
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- Хедер -->
|
|
||||||
<header>
|
<header>
|
||||||
<div class="header-content">
|
<div class="header-content">
|
||||||
<div class="logo">🧹 КлинСервис - Админка</div>
|
<div class="logo">🧹 Админка — КлинСервис</div>
|
||||||
<div class="header-nav">
|
<div>
|
||||||
<a href="admin-services.html" class="btn btn-secondary">Услуги</a>
|
<a href="index.html" class="btn btn-secondary">Главная</a>
|
||||||
<a href="admin-schedule.html" class="btn btn-secondary">Расписание</a>
|
<button class="btn btn-primary" onclick="logout()">Выйти</button>
|
||||||
<a href="index.html" class="btn btn-primary">На главную</a>
|
|
||||||
<button class="btn btn-secondary" onclick="logout()">Выйти</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<h1>📋 Все бронирования</h1>
|
<h1>📋 Все бронирования</h1>
|
||||||
|
<table id="bookingsTable">
|
||||||
<!-- Фильтры -->
|
|
||||||
<div class="filters">
|
|
||||||
<div class="filter-group">
|
|
||||||
<label>Дата:</label>
|
|
||||||
<input type="date" id="filterDate">
|
|
||||||
</div>
|
|
||||||
<div class="filter-group">
|
|
||||||
<label>Статус:</label>
|
|
||||||
<select id="filterStatus">
|
|
||||||
<option value="">Все</option>
|
|
||||||
<option value="confirmed">Подтверждена</option>
|
|
||||||
<option value="completed">Выполнена</option>
|
|
||||||
<option value="cancelled">Отменена</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="filter-group">
|
|
||||||
<label>Сотрудник:</label>
|
|
||||||
<select id="filterEmployee">
|
|
||||||
<option value="">Все сотрудники</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="filter-group">
|
|
||||||
<label>Клиент (email):</label>
|
|
||||||
<input type="email" id="filterClient" placeholder="ivan@example.com">
|
|
||||||
</div>
|
|
||||||
<button class="filter-btn" onclick="applyFilters()">🔍 Применить фильтры</button>
|
|
||||||
<button class="filter-btn" onclick="clearFilters()" style="background: #6c757d;">Очистить</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Таблица броней -->
|
|
||||||
<div class="bookings-table">
|
|
||||||
<table>
|
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Код брони</th>
|
<th>№</th>
|
||||||
<th>Клиент (email)</th>
|
<th>Клиент</th>
|
||||||
<th>Услуга</th>
|
<th>Услуга</th>
|
||||||
<th>Сотрудник</th>
|
|
||||||
<th>Дата и время</th>
|
<th>Дата и время</th>
|
||||||
|
<th>Сотрудник</th>
|
||||||
<th>Статус</th>
|
<th>Статус</th>
|
||||||
<th>Действия</th>
|
<th>Действия</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="bookingsTable">
|
<tbody>
|
||||||
<tr>
|
<tr><td colspan="7" class="no-data">Загрузка...</td></tr>
|
||||||
<td colspan="7" class="no-bookings">Загрузка броней...</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Модальное окно отмены -->
|
|
||||||
<div id="cancelModal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<span class="close" onclick="closeCancelModal()">×</span>
|
|
||||||
<h3>Отменить бронь администратором?</h3>
|
|
||||||
<p id="cancelBookingInfo"></p>
|
|
||||||
<p>Укажите причину отмены (необязательно):</p>
|
|
||||||
<textarea id="cancelReason" placeholder="Сотрудник заболел, клиент не вышел на связь..."></textarea>
|
|
||||||
<div class="modal-buttons">
|
|
||||||
<button class="btn-modal" onclick="closeCancelModal()">Отмена</button>
|
|
||||||
<button class="btn-modal btn-confirm" id="confirmCancelBtn" onclick="adminCancelBooking()">Отменить</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
let token = localStorage.getItem('token');
|
let token = localStorage.getItem('token');
|
||||||
let allBookings = [];
|
let bookings = [];
|
||||||
let filteredBookings = [];
|
let employees = [];
|
||||||
let selectedBookingId = null;
|
|
||||||
|
|
||||||
// Проверка авторизации
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
window.location.href = 'register-login.html';
|
window.location.href = 'register-login.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Загрузка при старте
|
// Загрузка данных при старте
|
||||||
window.onload = async function() {
|
window.onload = async function() {
|
||||||
|
try {
|
||||||
|
await loadEmployees();
|
||||||
await loadBookings();
|
await loadBookings();
|
||||||
await loadEmployeesForFilter();
|
} catch (err) {
|
||||||
|
alert('Ошибка загрузки данных: ' + err.message);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Загрузить сотрудников
|
||||||
|
async function loadEmployees() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/users?role=employee', {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Проверяем тип ответа
|
||||||
|
const contentType = res.headers.get('content-type');
|
||||||
|
if (!contentType || !contentType.includes('application/json')) {
|
||||||
|
throw new Error('Сервер вернул HTML вместо JSON (проверьте роль пользователя)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errorText = await res.text();
|
||||||
|
throw new Error(`HTTP ${res.status}: ${errorText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
employees = await res.json();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка загрузки сотрудников:', error);
|
||||||
|
alert('Ошибка загрузки сотрудников: ' + error.message);
|
||||||
|
employees = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Загрузить все брони
|
// Загрузить все брони
|
||||||
async function loadBookings() {
|
async function loadBookings() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/admin/bookings', {
|
const res = await fetch('/api/admin/bookings', {
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.ok) {
|
const contentType = res.headers.get('content-type');
|
||||||
allBookings = await response.json();
|
if (!contentType || !contentType.includes('application/json')) {
|
||||||
filteredBookings = [...allBookings];
|
throw new Error('Сервер вернул HTML вместо JSON (проверьте роль пользователя)');
|
||||||
renderBookings();
|
|
||||||
} else {
|
|
||||||
alert('Ошибка доступа');
|
|
||||||
window.location.href = 'register-login.html';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errorText = await res.text();
|
||||||
|
throw new Error(`HTTP ${res.status}: ${errorText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
bookings = await res.json();
|
||||||
|
renderBookings();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
document.getElementById('bookingsTable').innerHTML =
|
console.error('Ошибка загрузки бронирований:', error);
|
||||||
'<tr><td colspan="7" class="no-bookings">Ошибка загрузки</td></tr>';
|
document.querySelector('#bookingsTable tbody').innerHTML =
|
||||||
|
`<tr><td colspan="7" class="no-data">Ошибка: ${error.message}</td></tr>`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Загрузить сотрудников для фильтра
|
// Отобразить таблицу
|
||||||
async function loadEmployeesForFilter() {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/admin/users?role=employee', {
|
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
const employees = await response.json();
|
|
||||||
const select = document.getElementById('filterEmployee');
|
|
||||||
|
|
||||||
for (let employee of employees.filter(e => e.role === 'employee')) {
|
|
||||||
select.innerHTML += `<option value="${employee.id}">${employee.name}</option>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Ошибка загрузки сотрудников');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Применить фильтры
|
|
||||||
function applyFilters() {
|
|
||||||
const date = document.getElementById('filterDate').value;
|
|
||||||
const status = document.getElementById('filterStatus').value;
|
|
||||||
const employeeId = document.getElementById('filterEmployee').value;
|
|
||||||
const clientEmail = document.getElementById('filterClient').value.toLowerCase();
|
|
||||||
|
|
||||||
filteredBookings = allBookings.filter(booking => {
|
|
||||||
let match = true;
|
|
||||||
|
|
||||||
if (date && booking.bookingdate !== date) match = false;
|
|
||||||
if (status && booking.status !== status) match = false;
|
|
||||||
if (employeeId && booking.employee_id != employeeId) match = false;
|
|
||||||
if (clientEmail && (!booking.client || !booking.client.email.toLowerCase().includes(clientEmail))) match = false;
|
|
||||||
|
|
||||||
return match;
|
|
||||||
});
|
|
||||||
|
|
||||||
renderBookings();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Очистить фильтры
|
|
||||||
function clearFilters() {
|
|
||||||
document.getElementById('filterDate').value = '';
|
|
||||||
document.getElementById('filterStatus').value = '';
|
|
||||||
document.getElementById('filterEmployee').value = '';
|
|
||||||
document.getElementById('filterClient').value = '';
|
|
||||||
filteredBookings = [...allBookings];
|
|
||||||
renderBookings();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Отобразить брони
|
|
||||||
function renderBookings() {
|
function renderBookings() {
|
||||||
const tbody = document.getElementById('bookingsTable');
|
const tbody = document.querySelector('#bookingsTable tbody');
|
||||||
|
if (bookings.length === 0) {
|
||||||
if (filteredBookings.length === 0) {
|
tbody.innerHTML = '<tr><td colspan="7" class="no-data">Нет бронирований</td></tr>';
|
||||||
tbody.innerHTML = '<tr><td colspan="7" class="no-bookings">Нет броней по фильтрам</td></tr>';
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
tbody.innerHTML = '';
|
tbody.innerHTML = '';
|
||||||
|
bookings.forEach(b => {
|
||||||
|
const employeeSelect = document.createElement('select');
|
||||||
|
employeeSelect.className = 'employee-select';
|
||||||
|
employeeSelect.dataset.bookingId = b.id;
|
||||||
|
|
||||||
for (let booking of filteredBookings) {
|
if (!employees.length) {
|
||||||
const row = document.createElement('tr');
|
const option = document.createElement('option');
|
||||||
const statusClass = booking.status;
|
option.value = '';
|
||||||
|
option.textContent = '—';
|
||||||
|
employeeSelect.appendChild(option);
|
||||||
|
} else {
|
||||||
|
employees.forEach(emp => {
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = emp.id;
|
||||||
|
option.textContent = emp.name;
|
||||||
|
if ((b.employee && b.employee.id == emp.id) || b.employee_id == emp.id) {
|
||||||
|
option.selected = true;
|
||||||
|
}
|
||||||
|
employeeSelect.appendChild(option);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
row.innerHTML = `
|
const status = b.status || 'confirmed';
|
||||||
<td><strong>${booking.bookingnumber}</strong></td>
|
const statusClass = status;
|
||||||
<td>${booking.client ? booking.client.email : 'Неизвестно'}</td>
|
|
||||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
const row = `
|
||||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
<tr>
|
||||||
<td>${booking.bookingdate}<br>${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
<td>${b.booking_number || '—'}</td>
|
||||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
<td>${(b.client && b.client.name) ? b.client.name : '—'}</td>
|
||||||
|
<td>${(b.service && b.service.name) ? b.service.name : '—'}</td>
|
||||||
|
<td>${b.booking_date || '—'} ${b.start_time ? b.start_time.slice(0,5) : '—'}</td>
|
||||||
<td>
|
<td>
|
||||||
<div class="action-buttons">
|
${employeeSelect.outerHTML}
|
||||||
${booking.status !== 'completed' ?
|
<div class="actions">
|
||||||
`<button class="btn-small btn-cancel-admin" onclick="showCancelModal(${booking.id}, '${booking.bookingnumber}')">
|
<button class="btn-sm btn-primary" onclick="saveEmployee(${b.id})">Сохранить</button>
|
||||||
❌ Отменить
|
|
||||||
</button>` : ''}
|
|
||||||
${booking.status === 'confirmed' ?
|
|
||||||
`<button class="btn-small btn-complete" onclick="markAsCompleted(${booking.id})">
|
|
||||||
✅ Выполнено
|
|
||||||
</button>` : ''}
|
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
<td><span class="status ${statusClass}">${status}</span></td>
|
||||||
|
<td>
|
||||||
|
${status === 'confirmed' ?
|
||||||
|
`<button class="btn-sm btn-danger" onclick="cancelBooking(${b.id})">Отменить</button>` :
|
||||||
|
`<button class="btn-sm btn-secondary" disabled>Отменено</button>`
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
`;
|
`;
|
||||||
|
tbody.innerHTML += row;
|
||||||
tbody.appendChild(row);
|
});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Показать модальное окно отмены
|
// Сохранить сотрудника
|
||||||
function showCancelModal(bookingId, bookingNumber) {
|
async function saveEmployee(bookingId) {
|
||||||
selectedBookingId = bookingId;
|
const select = document.querySelector(`.employee-select[data-booking-id="${bookingId}"]`);
|
||||||
document.getElementById('cancelBookingInfo').innerHTML =
|
if (!select || !select.value) {
|
||||||
`Бронь <strong>${bookingNumber}</strong>`;
|
alert('Выберите сотрудника');
|
||||||
document.getElementById('cancelReason').value = '';
|
return;
|
||||||
document.getElementById('cancelModal').style.display = 'block';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Закрыть модальное окно
|
|
||||||
function closeCancelModal() {
|
|
||||||
document.getElementById('cancelModal').style.display = 'none';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Админская отмена
|
|
||||||
async function adminCancelBooking() {
|
|
||||||
const reason = document.getElementById('cancelReason').value;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/admin/bookings/${selectedBookingId}/cancel`, {
|
const res = await fetch(`/api/admin/bookings/${bookingId}/assign`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${token}`
|
'Authorization': `Bearer ${token}`
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ reason: reason || null })
|
body: JSON.stringify({ employee_id: select.value })
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
if (res.ok) {
|
||||||
|
alert('✅ Сотрудник назначен!');
|
||||||
if (response.ok) {
|
|
||||||
alert('✅ Бронь отменена администратором');
|
|
||||||
closeCancelModal();
|
|
||||||
loadBookings();
|
loadBookings();
|
||||||
} else {
|
} else {
|
||||||
alert('Ошибка: ' + data.error);
|
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||||
|
alert('Ошибка: ' + (err.message || 'Не удалось назначить сотрудника'));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Ошибка сети');
|
alert('Ошибка сети: ' + error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Пометить как выполнено
|
// Отменить бронь
|
||||||
async function markAsCompleted(bookingId) {
|
async function cancelBooking(bookingId) {
|
||||||
if (confirm('Пометить бронь как выполненную?')) {
|
const reason = prompt('Причина отмены:');
|
||||||
|
if (reason === null) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/admin/bookings/${bookingId}`, {
|
const res = await fetch(`/api/admin/bookings/${bookingId}/cancel`, {
|
||||||
method: 'PUT',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Authorization': `Bearer ${token}`
|
'Authorization': `Bearer ${token}`
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ status: 'completed' })
|
body: JSON.stringify({ reason: reason.trim() || null })
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.ok) {
|
if (res.ok) {
|
||||||
alert('✅ Бронь отмечена как выполненная');
|
alert('✅ Бронь отменена!');
|
||||||
loadBookings();
|
loadBookings();
|
||||||
|
} else {
|
||||||
|
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||||
|
alert('Ошибка: ' + (err.message || 'Не удалось отменить бронь'));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Ошибка');
|
alert('Ошибка сети: ' + error.message);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,17 +267,6 @@
|
|||||||
localStorage.removeItem('token');
|
localStorage.removeItem('token');
|
||||||
window.location.href = 'index.html';
|
window.location.href = 'index.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enter для фильтров
|
|
||||||
document.addEventListener('keypress', function(e) {
|
|
||||||
if (e.key === 'Enter') applyFilters();
|
|
||||||
});
|
|
||||||
|
|
||||||
// Клик вне модального окна
|
|
||||||
window.onclick = function(event) {
|
|
||||||
const modal = document.getElementById('cancelModal');
|
|
||||||
if (event.target === modal) closeCancelModal();
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -171,21 +171,53 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const token = localStorage.getItem('auth_token');
|
const token = localStorage.getItem('token');
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
window.location.href = '/register-login.html';
|
window.location.href = 'register-login.html';
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch('/api/admin/availabilities', {
|
window.onload = loadSchedule;
|
||||||
headers: { 'Authorization': 'Bearer ' + token }
|
|
||||||
})
|
async function loadSchedule() {
|
||||||
.then(r => r.json())
|
try {
|
||||||
.then(data => {
|
const res = await fetch('/api/admin/availabilities', {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
const availabilities = await res.json();
|
||||||
|
|
||||||
const list = document.getElementById('schedule-list');
|
const list = document.getElementById('schedule-list');
|
||||||
data.forEach(avail => {
|
availabilities.forEach(a => {
|
||||||
list.innerHTML += `<p>${avail.employee_id} — ${avail.date} ${avail.starttime} - ${avail.endtime}</p>`;
|
list.innerHTML += `
|
||||||
|
<div>
|
||||||
|
<p>Сотрудник: ${a.employee_id} — ${a.date} ${a.start_time}–${a.end_time} — ${a.is_available ? 'Доступен' : 'Недоступен'}</p>
|
||||||
|
<button onclick="deleteSlot(${a.id})">Удалить</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
});
|
});
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка загрузки расписания');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteSlot(id) {
|
||||||
|
if (confirm('Удалить слот?')) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/availabilities/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert('Слот удалён');
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -180,45 +180,105 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Получаем токен из localStorage
|
const token = localStorage.getItem('token');
|
||||||
const token = localStorage.getItem('auth_token');
|
|
||||||
|
|
||||||
// Если нет токена — перенаправляем на вход
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
alert('Доступ только для администраторов!');
|
window.location.href = 'register-login.html';
|
||||||
window.location.href = '/register-login.html';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Загружаем услуги
|
window.onload = loadServices;
|
||||||
fetch('/api/admin/services', {
|
|
||||||
headers: {
|
async function loadServices() {
|
||||||
'Authorization': 'Bearer ' + token,
|
try {
|
||||||
'Accept': 'application/json'
|
const res = await fetch('/api/admin/services', {
|
||||||
}
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
})
|
});
|
||||||
.then(response => {
|
|
||||||
if (!response.ok) {
|
const services = await res.json();
|
||||||
throw new Error('Ошибка сервера: ' + response.status);
|
|
||||||
}
|
const list = document.getElementById('services-list');
|
||||||
return response.json();
|
services.forEach(s => {
|
||||||
})
|
list.innerHTML += `
|
||||||
.then(data => {
|
<div>
|
||||||
const servicesList = document.getElementById('services-list');
|
<p><strong>${s.name}</strong> — ${s.price}₽ — ${s.is_active ? 'Активна' : 'Неактивна'}</p>
|
||||||
data.forEach(service => {
|
<button onclick="editService(${s.id})">Редактировать</button>
|
||||||
const item = document.createElement('div');
|
<button onclick="toggleService(${s.id}, ${s.is_active})">${s.is_active ? '❌ Деактивировать' : '✅ Активировать'}</button>
|
||||||
item.innerHTML = `
|
<button onclick="deleteService(${s.id})">🗑️ Удалить</button>
|
||||||
<h3>${service.name}</h3>
|
</div>
|
||||||
<p>Цена: ${service.price} ₽</p>
|
|
||||||
<p>Описание: ${service.description || 'Нет описания'}</p>
|
|
||||||
<hr>
|
|
||||||
`;
|
`;
|
||||||
servicesList.appendChild(item);
|
|
||||||
});
|
});
|
||||||
})
|
} catch (err) {
|
||||||
.catch(error => {
|
alert('Ошибка загрузки услуг');
|
||||||
console.error('Ошибка:', error);
|
}
|
||||||
document.body.innerHTML = `<h2 style="color: red;">Ошибка загрузки данных: ${error.message}</h2>`;
|
}
|
||||||
|
|
||||||
|
async function addService(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const formData = {
|
||||||
|
name: document.getElementById('serviceName').value,
|
||||||
|
description: document.getElementById('serviceDescription').value,
|
||||||
|
duration_minutes: parseInt(document.getElementById('serviceDuration').value),
|
||||||
|
price: parseFloat(document.getElementById('servicePrice').value),
|
||||||
|
is_active: true
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/admin/services', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify(formData)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert('Услуга добавлена');
|
||||||
|
document.getElementById('addServiceForm').reset();
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка добавления');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleService(id, isActive) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/services/${id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ is_active: !isActive })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert(`Услуга ${!isActive ? 'активирована' : 'деактивирована'}`);
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteService(id) {
|
||||||
|
if (confirm('Удалить услугу?')) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/admin/services/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert('Услуга удалена');
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -128,28 +128,56 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Получить данные брони из localStorage (передается из services.html)
|
const token = localStorage.getItem('token');
|
||||||
const bookingData = JSON.parse(localStorage.getItem('lastBooking') || '{}');
|
|
||||||
|
|
||||||
if (bookingData.booking) {
|
if (!token) {
|
||||||
const booking = bookingData.booking;
|
window.location.href = 'register-login.html';
|
||||||
document.getElementById('bookingNumber').textContent = booking.bookingnumber;
|
|
||||||
|
|
||||||
// Заполнить детали (простые циклы для поиска)
|
|
||||||
const services = JSON.parse(localStorage.getItem('services') || '[]');
|
|
||||||
const service = services.find(s => s.id == booking.service_id);
|
|
||||||
|
|
||||||
document.querySelector('#bookingDetails .detail-row:nth-child(1) span:last-child').textContent = service ? service.name : 'Услуга';
|
|
||||||
document.querySelector('#bookingDetails .detail-row:nth-child(4) span:last-child').textContent =
|
|
||||||
`${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}`;
|
|
||||||
document.querySelector('#bookingDetails .detail-row:nth-child(5) span:last-child').textContent =
|
|
||||||
`${booking.service.price || '???'} ₽`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Очистка localStorage через 30 секунд
|
window.onload = loadBookings;
|
||||||
setTimeout(() => {
|
|
||||||
localStorage.removeItem('lastBooking');
|
async function loadBookings() {
|
||||||
}, 30000);
|
try {
|
||||||
|
const res = await fetch('/api/bookings', {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
const bookings = await res.json();
|
||||||
|
|
||||||
|
const list = document.getElementById('bookings-list');
|
||||||
|
bookings.forEach(b => {
|
||||||
|
list.innerHTML += `
|
||||||
|
<div>
|
||||||
|
<p><strong>${b.booking_number}</strong> — ${b.service.name} (${b.booking_date} ${b.start_time}) — ${b.status}</p>
|
||||||
|
${b.status === 'confirmed' ? `<button onclick="cancelBooking(${b.id})">Отменить</button>` : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка загрузки бронирований');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelBooking(id) {
|
||||||
|
try {
|
||||||
|
const reason = prompt('Причина отмены (необязательно):');
|
||||||
|
const res = await fetch(`/api/bookings/${id}/cancel`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ reason })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert('Бронь отменена');
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка отмены');
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -152,18 +152,19 @@
|
|||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// прокрутка к секции услуг
|
const token = localStorage.getItem('token');
|
||||||
document.querySelector('.hero-buttons .btn-secondary').onclick = function(e) {
|
|
||||||
e.preventDefault();
|
|
||||||
document.getElementById('services').scrollIntoView({
|
|
||||||
behavior: 'smooth'
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
// Проверка авторизации
|
if (token) {
|
||||||
if (localStorage.getItem('token')) {
|
// Если авторизован — показываем кнопки "Личный кабинет" и "Выход"
|
||||||
// Пользователь авторизован - можно добавить кнопку "Личный кабинет"
|
document.querySelector('.auth-buttons').innerHTML = `
|
||||||
console.log('Пользователь авторизован');
|
<a href="my-bookings.html" class="btn btn-secondary">Личный кабинет</a>
|
||||||
|
<a href="#" onclick="logout()" class="btn btn-primary">Выход</a>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logout() {
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
window.location.href = 'register-login.html';
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -212,11 +212,12 @@
|
|||||||
|
|
||||||
const canCancel = booking.status === 'confirmed';
|
const canCancel = booking.status === 'confirmed';
|
||||||
|
|
||||||
|
// ИСПРАВЛЕНО: используем правильные имена полей с подчёркиваниями
|
||||||
row.innerHTML = `
|
row.innerHTML = `
|
||||||
<td><strong>${booking.bookingnumber}</strong></td>
|
<td><strong>${booking.booking_number}</strong></td>
|
||||||
<td>${booking.bookingdate} ${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
<td>${booking.booking_date} ${booking.start_time.slice(0,5)}–${booking.end_time.slice(0,5)}</td>
|
||||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
<td>${booking.service ? booking.service.name : 'Услуга удалена'}</td>
|
||||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
<td>${booking.employee ? booking.employee.name : 'Сотрудник не назначен'}</td>
|
||||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
||||||
<td>
|
<td>
|
||||||
${canCancel ?
|
${canCancel ?
|
||||||
@@ -266,7 +267,7 @@
|
|||||||
closeModal();
|
closeModal();
|
||||||
loadBookings(); // Перезагрузить список
|
loadBookings(); // Перезагрузить список
|
||||||
} else {
|
} else {
|
||||||
alert('Ошибка: ' + data.error);
|
alert('Ошибка: ' + (data.message || data.error || 'Не удалось отменить бронь'));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Ошибка сети');
|
alert('Ошибка сети');
|
||||||
|
|||||||
@@ -75,7 +75,6 @@
|
|||||||
<body>
|
<body>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<!-- Форма входа -->
|
|
||||||
<div id="loginSection">
|
<div id="loginSection">
|
||||||
<h2>Вход</h2>
|
<h2>Вход</h2>
|
||||||
<div id="loginResult"></div>
|
<div id="loginResult"></div>
|
||||||
@@ -91,7 +90,6 @@
|
|||||||
<div class="toggle" onclick="showRegisterForm()">Нет аккаунта? Зарегистрироваться</div>
|
<div class="toggle" onclick="showRegisterForm()">Нет аккаунта? Зарегистрироваться</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Форма регистрации -->
|
|
||||||
<div id="registerSection" style="display: none;">
|
<div id="registerSection" style="display: none;">
|
||||||
<h2>Регистрация</h2>
|
<h2>Регистрация</h2>
|
||||||
<div id="registerResult"></div>
|
<div id="registerResult"></div>
|
||||||
@@ -117,106 +115,75 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// Показать форму регистрации
|
let token = localStorage.getItem('token');
|
||||||
|
|
||||||
|
// Проверка авторизации
|
||||||
|
if (token) {
|
||||||
|
window.location.href = 'index.html'; // ← ИСПРАВЛЕНО!
|
||||||
|
}
|
||||||
|
|
||||||
|
// Регистрация
|
||||||
|
async function registerUser() {
|
||||||
|
const name = document.getElementById('nameReg').value;
|
||||||
|
const email = document.getElementById('emailReg').value;
|
||||||
|
const password = document.getElementById('passwordReg').value;
|
||||||
|
const phone = document.getElementById('phoneReg').value || null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/register', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ name, email, password, phone })
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
alert('Регистрация успешна!');
|
||||||
|
showLoginForm();
|
||||||
|
} else {
|
||||||
|
alert(data.message || 'Ошибка регистрации');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка сети');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вход
|
||||||
|
async function loginUser() {
|
||||||
|
const email = document.getElementById('emailLogin').value;
|
||||||
|
const password = document.getElementById('passwordLogin').value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, password })
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
localStorage.setItem('token', data.access_token);
|
||||||
|
window.location.href = 'index.html'; // ← ИСПРАВЛЕНО!
|
||||||
|
} else {
|
||||||
|
alert(data.message || 'Неверный email или пароль');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
alert('Ошибка сети');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Переключение форм
|
||||||
function showRegisterForm() {
|
function showRegisterForm() {
|
||||||
document.getElementById('loginSection').style.display = 'none';
|
document.getElementById('loginSection').style.display = 'none';
|
||||||
document.getElementById('registerSection').style.display = 'block';
|
document.getElementById('registerSection').style.display = 'block';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Показать форму входа
|
|
||||||
function showLoginForm() {
|
function showLoginForm() {
|
||||||
document.getElementById('registerSection').style.display = 'none';
|
document.getElementById('registerSection').style.display = 'none';
|
||||||
document.getElementById('loginSection').style.display = 'block';
|
document.getElementById('loginSection').style.display = 'block';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Функция регистрации
|
|
||||||
function registerUser() {
|
|
||||||
// Собираем данные из формы
|
|
||||||
var name = document.getElementById('nameReg').value;
|
|
||||||
var email = document.getElementById('emailReg').value;
|
|
||||||
var password = document.getElementById('passwordReg').value;
|
|
||||||
var phone = document.getElementById('phoneReg').value || null;
|
|
||||||
|
|
||||||
// Подготавливаем данные для отправки
|
|
||||||
var data = {
|
|
||||||
name: name,
|
|
||||||
email: email,
|
|
||||||
password: password,
|
|
||||||
phone: phone
|
|
||||||
};
|
|
||||||
|
|
||||||
// Отправляем POST-запрос на сервер
|
|
||||||
var xhr = new XMLHttpRequest();
|
|
||||||
xhr.open("POST", "/api/register", true);
|
|
||||||
xhr.setRequestHeader("Content-Type", "application/json");
|
|
||||||
|
|
||||||
xhr.onreadystatechange = function () {
|
|
||||||
if (xhr.readyState === 4) {
|
|
||||||
var resultDiv = document.getElementById('registerResult');
|
|
||||||
if (xhr.status === 200 || xhr.status === 201) {
|
|
||||||
resultDiv.className = "message success";
|
|
||||||
resultDiv.innerHTML = "Регистрация прошла успешно! Теперь войдите.";
|
|
||||||
// Через 2 секунды переключим на форму входа
|
|
||||||
setTimeout(function() {
|
|
||||||
showLoginForm();
|
|
||||||
resultDiv.innerHTML = "";
|
|
||||||
}, 2000);
|
|
||||||
} else {
|
|
||||||
resultDiv.className = "message error";
|
|
||||||
try {
|
|
||||||
var response = JSON.parse(xhr.responseText);
|
|
||||||
resultDiv.innerHTML = response.message || "Ошибка при регистрации";
|
|
||||||
} catch (e) {
|
|
||||||
resultDiv.innerHTML = "Неизвестная ошибка сервера";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.send(JSON.stringify(data));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Функция входа
|
|
||||||
function loginUser() {
|
|
||||||
var email = document.getElementById('emailLogin').value;
|
|
||||||
var password = document.getElementById('passwordLogin').value;
|
|
||||||
|
|
||||||
var data = {
|
|
||||||
email: email,
|
|
||||||
password: password
|
|
||||||
};
|
|
||||||
|
|
||||||
var xhr = new XMLHttpRequest();
|
|
||||||
xhr.open("POST", "/api/login", true);
|
|
||||||
xhr.setRequestHeader("Content-Type", "application/json");
|
|
||||||
|
|
||||||
xhr.onreadystatechange = function () {
|
|
||||||
if (xhr.readyState === 4) {
|
|
||||||
var resultDiv = document.getElementById('loginResult');
|
|
||||||
if (xhr.status === 200) {
|
|
||||||
resultDiv.className = "message success";
|
|
||||||
resultDiv.innerHTML = "Вход выполнен!";
|
|
||||||
// Сохраняем токен в localStorage (чтобы потом использовать)
|
|
||||||
var response = JSON.parse(xhr.responseText);
|
|
||||||
localStorage.setItem('auth_token', response.token);
|
|
||||||
// Перенаправляем на главную
|
|
||||||
setTimeout(function() {
|
|
||||||
window.location.href = "/";
|
|
||||||
}, 1000);
|
|
||||||
} else {
|
|
||||||
resultDiv.className = "message error";
|
|
||||||
try {
|
|
||||||
var response = JSON.parse(xhr.responseText);
|
|
||||||
resultDiv.innerHTML = response.message || "Неверный email или пароль";
|
|
||||||
} catch (e) {
|
|
||||||
resultDiv.innerHTML = "Ошибка при входе";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.send(JSON.stringify(data));
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -143,10 +143,7 @@
|
|||||||
<input type="text" id="duration" readonly placeholder="Выберите услугу">
|
<input type="text" id="duration" readonly placeholder="Выберите услугу">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button class="book-btn" id="bookBtn" onclick="bookService()" disabled>
|
<div>
|
||||||
Выбрать время →
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Календарь -->
|
<!-- Календарь -->
|
||||||
<div class="calendar-section">
|
<div class="calendar-section">
|
||||||
@@ -180,39 +177,235 @@
|
|||||||
let currentYear = new Date().getFullYear();
|
let currentYear = new Date().getFullYear();
|
||||||
let availableSlots = [];
|
let availableSlots = [];
|
||||||
let token = localStorage.getItem('token');
|
let token = localStorage.getItem('token');
|
||||||
|
let selectedSlot = null;
|
||||||
|
|
||||||
// Проверка авторизации
|
// Проверка авторизации
|
||||||
if (!token) {
|
if (!token) {
|
||||||
window.location.href = 'register-login.html';
|
window.location.href = 'register-login.html';
|
||||||
throw new Error('Нужна авторизация');
|
|
||||||
}
|
}
|
||||||
updateHeader();
|
|
||||||
|
|
||||||
// 1. Загрузить услуги при загрузке страницы
|
// Загрузка страницы
|
||||||
window.onload = async function() {
|
window.onload = async function() {
|
||||||
|
// Убедимся, что элементы существуют
|
||||||
|
if (!document.getElementById('serviceSelect')) {
|
||||||
|
console.error('Элемент #serviceSelect не найден');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
await loadServices();
|
await loadServices();
|
||||||
initCalendar();
|
initCalendar();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка загрузки:', error);
|
||||||
|
alert('Не удалось загрузить данные');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Загрузка услуг из API (только isactive=true)
|
// ✅ 1. ЗАГРУЗКА УСЛУГ (публичный API)
|
||||||
async function loadServices() {
|
async function loadServices() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/admin/services', {
|
const response = await fetch('/api/services');
|
||||||
headers: { 'Authorization': `Bearer ${token}` }
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
services = data.filter(service => service.isactive);
|
services = data.filter(service => service.is_active); // ← is_active, не isactive
|
||||||
const select = document.getElementById('serviceSelect');
|
|
||||||
|
|
||||||
|
const select = document.getElementById('serviceSelect');
|
||||||
select.innerHTML = '<option value="">Выберите услугу</option>';
|
select.innerHTML = '<option value="">Выберите услугу</option>';
|
||||||
|
|
||||||
for (let service of services) {
|
for (let service of services) {
|
||||||
select.innerHTML += `<option value="${service.id}" data-duration="${service.durationminutes}">${service.name} (${service.durationminutes} мин) - ${service.price}₽</option>`;
|
const option = document.createElement('option');
|
||||||
|
option.value = service.id;
|
||||||
|
option.textContent = `${service.name} (${service.duration_minutes} мин) - ${service.price}₽`;
|
||||||
|
select.appendChild(option);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
alert('Ошибка загрузки услуг');
|
throw new Error('Ошибка загрузки услуг: ' + error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Изменение услуги
|
// 2. При выборе услуги — показываем длительность
|
||||||
//document.getElementById('serviceSelect').onchange = function()//
|
document.getElementById('serviceSelect').onchange = function() {
|
||||||
|
const serviceId = this.value;
|
||||||
|
if (!serviceId) {
|
||||||
|
document.getElementById('duration').value = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectedServiceId = parseInt(serviceId);
|
||||||
|
const service = services.find(s => s.id == serviceId);
|
||||||
|
document.getElementById('duration').value = service ? service.duration_minutes + ' минут' : '';
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Календарь
|
||||||
|
function initCalendar() {
|
||||||
|
renderCalendar();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCalendar() {
|
||||||
|
const monthYear = document.getElementById('monthYear');
|
||||||
|
const calendarDays = document.getElementById('calendarDays');
|
||||||
|
|
||||||
|
if (!monthYear || !calendarDays) {
|
||||||
|
console.error('Элементы календаря не найдены');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const months = ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'];
|
||||||
|
monthYear.textContent = `${months[currentMonth]} ${currentYear}`;
|
||||||
|
|
||||||
|
calendarDays.innerHTML = '';
|
||||||
|
|
||||||
|
const firstDay = new Date(currentYear, currentMonth, 1).getDay();
|
||||||
|
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
|
||||||
|
|
||||||
|
// Добавляем "серые" дни предыдущего месяца
|
||||||
|
for (let i = 0; i < (firstDay === 0 ? 6 : firstDay - 1); i++) {
|
||||||
|
const dayEl = document.createElement('div');
|
||||||
|
dayEl.className = 'calendar-day other-month';
|
||||||
|
calendarDays.appendChild(dayEl);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Добавляем дни текущего месяца
|
||||||
|
const today = new Date();
|
||||||
|
for (let day = 1; day <= daysInMonth; day++) {
|
||||||
|
const dayEl = document.createElement('div');
|
||||||
|
dayEl.className = 'calendar-day';
|
||||||
|
dayEl.textContent = day;
|
||||||
|
|
||||||
|
const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
||||||
|
const dateObj = new Date(dateStr);
|
||||||
|
|
||||||
|
if (dateObj < today.setHours(0,0,0,0)) {
|
||||||
|
dayEl.classList.add('disabled');
|
||||||
|
} else {
|
||||||
|
dayEl.onclick = () => selectDate(dateStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
calendarDays.appendChild(dayEl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function prevMonth() {
|
||||||
|
if (currentMonth === 0) {
|
||||||
|
currentMonth = 11;
|
||||||
|
currentYear--;
|
||||||
|
} else {
|
||||||
|
currentMonth--;
|
||||||
|
}
|
||||||
|
renderCalendar();
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextMonth() {
|
||||||
|
if (currentMonth === 11) {
|
||||||
|
currentMonth = 0;
|
||||||
|
currentYear++;
|
||||||
|
} else {
|
||||||
|
currentMonth++;
|
||||||
|
}
|
||||||
|
renderCalendar();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Выбор даты → загрузка слотов
|
||||||
|
async function selectDate(dateStr) {
|
||||||
|
if (!selectedServiceId) {
|
||||||
|
alert('Сначала выберите услугу');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectedDate = dateStr;
|
||||||
|
document.querySelectorAll('.calendar-day').forEach(el => el.classList.remove('selected'));
|
||||||
|
event.target.classList.add('selected');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `/api/availability?service_id=${selectedServiceId}&date=${dateStr}`;
|
||||||
|
const response = await fetch(url);
|
||||||
|
availableSlots = await response.json();
|
||||||
|
|
||||||
|
showSlots(availableSlots);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка загрузки слотов:', error);
|
||||||
|
alert('Не удалось загрузить доступное время');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSlots(slots) {
|
||||||
|
const slotsSection = document.getElementById('slotsSection');
|
||||||
|
const slotsGrid = document.getElementById('slotsGrid');
|
||||||
|
const confirmBtn = document.getElementById('confirmBookingBtn');
|
||||||
|
|
||||||
|
slotsSection.style.display = 'block';
|
||||||
|
slotsGrid.innerHTML = '';
|
||||||
|
|
||||||
|
if (slots.length === 0) {
|
||||||
|
slotsGrid.innerHTML = '<div class="no-slots">В этот день нет доступных слотов</div>';
|
||||||
|
confirmBtn.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectedSlot = null; // ← Сбросьте перед новым выбором
|
||||||
|
|
||||||
|
slots.forEach(slot => {
|
||||||
|
const slotEl = document.createElement('div');
|
||||||
|
slotEl.className = 'slot';
|
||||||
|
slotEl.textContent = `${slot.start} - ${slot.end}`;
|
||||||
|
slotEl.onclick = () => {
|
||||||
|
document.querySelectorAll('.slot').forEach(s => s.classList.remove('selected'));
|
||||||
|
slotEl.classList.add('selected');
|
||||||
|
selectedSlot = slot; // ← Присвойте значение
|
||||||
|
confirmBtn.style.display = 'block';
|
||||||
|
};
|
||||||
|
slotsGrid.appendChild(slotEl);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Подтверждение бронирования
|
||||||
|
async function confirmBooking() {
|
||||||
|
if (!selectedServiceId || !selectedDate || !selectedSlot) {
|
||||||
|
alert('Выберите всё: услугу, дату и время');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/bookings', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
service_id: selectedServiceId,
|
||||||
|
employee_id: selectedSlot.employee_id,
|
||||||
|
date: selectedDate,
|
||||||
|
start_time: selectedSlot.start
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
alert('✅ Бронирование успешно создано!');
|
||||||
|
window.location.href = 'my-bookings.html';
|
||||||
|
} else {
|
||||||
|
const err = await response.json();
|
||||||
|
alert('Ошибка: ' + (err.message || 'Не удалось создать бронь'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Ошибка бронирования:', error);
|
||||||
|
alert('Ошибка сети');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateHeader() {
|
||||||
|
if (token) {
|
||||||
|
document.getElementById('profileBtn').style.display = 'inline-block';
|
||||||
|
document.getElementById('logoutBtn').style.display = 'inline-block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function logout() {
|
||||||
|
localStorage.removeItem('token');
|
||||||
|
window.location.href = 'index.html';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
@@ -1,51 +1,57 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Http\Controllers\UserController;
|
|
||||||
use App\Http\Controllers\ServicesController;
|
|
||||||
use App\Http\Controllers\BookingsController;
|
|
||||||
use App\Http\Controllers\AvailabilitiesController;
|
|
||||||
use App\Http\Controllers\CategoriesController;
|
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use App\Http\Controllers\AuthController;
|
use App\Http\Controllers\AuthController;
|
||||||
|
use App\Http\Controllers\ServicesController;
|
||||||
|
use App\Http\Controllers\BookingsController; // ← ДОЛЖЕН БЫТЬ!
|
||||||
|
use App\Http\Controllers\AvailabilitiesController;
|
||||||
|
use App\Http\Controllers\CategoriesController;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Route::get('/user', function (Request $request) {
|
Route::get('/user', function (Request $request) {
|
||||||
return $request->user();
|
return $request->user();
|
||||||
})->middleware('auth:sanctum');
|
})->middleware('auth:sanctum');
|
||||||
|
|
||||||
// РЕГИСТРАЦИЯ ТОЛЬКО КЛИЕНТОВ (публичный)
|
// === ПУБЛИЧНЫЕ РОУТЫ ===
|
||||||
Route::post('/register', [UserController::class, 'register']);
|
Route::post('/register', [AuthController::class, 'register']);
|
||||||
|
Route::post('/login', [AuthController::class, 'login'])->name('login');
|
||||||
Route::post('/login', [AuthController::class, 'login']);
|
Route::get('/services', [ServicesController::class, 'publicIndex']);
|
||||||
|
Route::get('/availability', [AvailabilitiesController::class, 'publicAvailability']);
|
||||||
// Существующие роуты categories
|
|
||||||
Route::get('/categories', [CategoriesController::class, 'index'])->middleware('auth:sanctum');
|
|
||||||
Route::get('/categories/{id}', [CategoriesController::class, 'show']);
|
Route::get('/categories/{id}', [CategoriesController::class, 'show']);
|
||||||
Route::post('/categories', [CategoriesController::class, 'create']);
|
Route::post('/categories', [CategoriesController::class, 'create']);
|
||||||
|
|
||||||
// ПУБЛИЧНЫЙ API доступности (без авторизации)
|
// === ЗАЩИЩЁННЫЕ РОУТЫ ===
|
||||||
Route::get('/availability', [AvailabilitiesController::class, 'publicAvailability']);
|
Route::middleware('auth:sanctum')->group(function () {
|
||||||
|
Route::get('/categories', [CategoriesController::class, 'index']);
|
||||||
// КЛИЕНТСКИЕ РОУТЫ БРОНИРОВАНИЙ (auth:sanctum)
|
Route::get('/bookings', [BookingsController::class, 'clientIndex']);
|
||||||
Route::middleware('auth:sanctum', 'role:admin')->group(function () {
|
|
||||||
Route::post('/bookings', [BookingsController::class, 'store']);
|
Route::post('/bookings', [BookingsController::class, 'store']);
|
||||||
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'cancel']);
|
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'cancel']);
|
||||||
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'adminCancel']);
|
|
||||||
Route::get('/bookings', [BookingsController::class, 'clientIndex']);
|
// Получить сотрудников
|
||||||
Route::get('/bookings', [BookingsController::class, 'adminIndex']);
|
Route::get('/users', function (Request $request) {
|
||||||
|
$role = $request->query('role', 'employee');
|
||||||
|
return \App\Models\User::where('role', $role)->get();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// АДМИН РОУТЫ - ТОЛЬКО employee/admin (role:employee)
|
// === АДМИНСКИЕ РОУТЫ ===
|
||||||
Route::middleware(['auth:sanctum', 'role:employee'])->prefix('admin')->group(function () {
|
Route::middleware(['auth:sanctum', 'role:admin'])->prefix('admin')->group(function () {
|
||||||
// CRUD услуги
|
// Услуги
|
||||||
Route::get('/services', [ServicesController::class, 'index']);
|
Route::get('/services', [ServicesController::class, 'index']);
|
||||||
Route::post('/services', [ServicesController::class, 'store']);
|
Route::post('/services', [ServicesController::class, 'store']);
|
||||||
Route::put('/services/{id}', [ServicesController::class, 'update']);
|
Route::put('/services/{id}', [ServicesController::class, 'update']);
|
||||||
Route::delete('/services/{id}', [ServicesController::class, 'destroy']);
|
Route::delete('/services/{id}', [ServicesController::class, 'destroy']);
|
||||||
|
|
||||||
// CRUD расписание
|
// Расписание
|
||||||
Route::get('/availabilities', [AvailabilitiesController::class, 'index']);
|
Route::get('/availabilities', [AvailabilitiesController::class, 'index']);
|
||||||
Route::post('/availabilities', [AvailabilitiesController::class, 'store']);
|
Route::post('/availabilities', [AvailabilitiesController::class, 'store']);
|
||||||
Route::post('/availabilities/bulk', [AvailabilitiesController::class, 'bulkStore']);
|
Route::post('/availabilities/bulk', [AvailabilitiesController::class, 'bulkStore']);
|
||||||
Route::delete('/availabilities/{id}', [AvailabilitiesController::class, 'destroy']);
|
Route::delete('/availabilities/{id}', [AvailabilitiesController::class, 'destroy']);
|
||||||
|
|
||||||
|
// Бронирования админа ← ЭТОТ БЛОК ОБЯЗАТЕЛЕН!
|
||||||
|
Route::get('/bookings', [BookingsController::class, 'adminIndex']);
|
||||||
|
Route::post('/bookings/{id}/assign', [BookingsController::class, 'assignEmployee']);
|
||||||
|
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'adminCancel']);
|
||||||
});
|
});
|
||||||
Reference in New Issue
Block a user