commit 12.01
This commit is contained in:
@@ -5,61 +5,31 @@ namespace App\Http\Controllers;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
|
||||
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)
|
||||
{
|
||||
$credentials = $request->only('email', 'password');
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'password' => 'required'
|
||||
]);
|
||||
|
||||
if (!Auth::attempt($credentials)) {
|
||||
return response()->json([
|
||||
'message' => 'Неверный email или пароль'
|
||||
], 401);
|
||||
}
|
||||
$user = \App\Models\User::where('email', $request->email)->first();
|
||||
|
||||
$user = Auth::user();
|
||||
$token = $user->createToken('main-token')->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Успешный вход',
|
||||
'user' => $user,
|
||||
'token' => $token
|
||||
]);
|
||||
if (!$user || !Hash::check($request->password, $user->password)) {
|
||||
return response()->json(['message' => 'Неверный email или пароль'], 401);
|
||||
}
|
||||
|
||||
$token = $user->createToken('auth_token')->plainTextToken;
|
||||
|
||||
return response()->json([
|
||||
'access_token' => $token,
|
||||
'token_type' => 'Bearer',
|
||||
'user' => $user
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,168 +2,92 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\EmployeeAvailability;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\EmployeeAvailability;
|
||||
|
||||
class AvailabilitiesController extends Controller
|
||||
{
|
||||
// GET api/admin/availabilities?employee_id=5&date=2025-06-15
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = EmployeeAvailability::query();
|
||||
|
||||
if ($request->employee_id) {
|
||||
$query->where('employee_id', $request->employee_id);
|
||||
}
|
||||
if ($request->date) {
|
||||
$query->where('date', $request->date);
|
||||
}
|
||||
|
||||
$availabilities = $query->get();
|
||||
$availabilities = EmployeeAvailability::with('employee')
|
||||
->when($request->has('employee_id'), function ($query) use ($request) {
|
||||
$query->where('employee_id', $request->employee_id);
|
||||
})
|
||||
->when($request->has('date'), function ($query) use ($request) {
|
||||
$query->where('date', $request->date);
|
||||
})
|
||||
->get();
|
||||
|
||||
return response()->json($availabilities);
|
||||
}
|
||||
|
||||
// POST api/admin/availabilities - создать один слот
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
$validated = $request->validate([
|
||||
'employee_id' => 'required|exists:users,id',
|
||||
'date' => 'required|date',
|
||||
'starttime' => 'required',
|
||||
'endtime' => 'required|after:starttime',
|
||||
'isavailable' => 'boolean'
|
||||
'start_time' => 'required|date_format:H:i:s',
|
||||
'end_time' => 'required|date_format:H:i:s|after:start_time',
|
||||
'is_available' => 'boolean'
|
||||
]);
|
||||
|
||||
$availability = EmployeeAvailability::create($request->all());
|
||||
|
||||
$availability = EmployeeAvailability::create($validated);
|
||||
|
||||
return response()->json($availability, 201);
|
||||
}
|
||||
|
||||
// POST api/admin/availabilities/bulk - создать несколько слотов
|
||||
|
||||
public function bulkStore(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
$validated = $request->validate([
|
||||
'employee_id' => 'required|exists:users,id',
|
||||
'date' => 'required|date',
|
||||
'intervals' => 'required|array|min:1'
|
||||
'intervals' => 'required|array'
|
||||
]);
|
||||
|
||||
$availabilities = [];
|
||||
|
||||
foreach ($request->intervals as $interval) {
|
||||
$availability = EmployeeAvailability::create([
|
||||
EmployeeAvailability::create([
|
||||
'employee_id' => $request->employee_id,
|
||||
'date' => $request->date,
|
||||
'starttime' => $interval['start'],
|
||||
'endtime' => $interval['end'],
|
||||
'isavailable' => true
|
||||
'start_time' => $interval['start'],
|
||||
'end_time' => $interval['end'],
|
||||
'is_available' => true
|
||||
]);
|
||||
$availabilities[] = $availability;
|
||||
}
|
||||
|
||||
return response()->json($availabilities, 201);
|
||||
|
||||
return response()->json(['message' => 'Расписание добавлено']);
|
||||
}
|
||||
|
||||
// DELETE api/admin/availabilities/{id} - удалить слот (брони остаются!)
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$availability = EmployeeAvailability::findOrFail($id);
|
||||
$availability->delete();
|
||||
|
||||
return response()->json(['message' => 'Слот удален из расписания (брони сохранены)']);
|
||||
|
||||
return response()->json(['message' => 'Слот удалён']);
|
||||
}
|
||||
|
||||
// ✅ Единственный метод publicAvailability
|
||||
public function publicAvailability(Request $request)
|
||||
{
|
||||
$serviceId = $request->query('service_id');
|
||||
$date = $request->query('date');
|
||||
|
||||
if (!$serviceId || !$date) {
|
||||
return response()->json(['error' => 'service_id и date обязательны'], 400);
|
||||
}
|
||||
|
||||
// Найти услугу и получить длительность
|
||||
$service = \App\Models\Services::find($serviceId);
|
||||
if (!$service) {
|
||||
return response()->json(['error' => 'Услуга не найдена'], 404);
|
||||
}
|
||||
|
||||
$durationMinutes = $service->durationminutes;
|
||||
|
||||
// Найти сотрудников с расписанием на эту дату
|
||||
$availabilities = \App\Models\EmployeeAvailability::where('date', $date)
|
||||
->where('isavailable', true)
|
||||
->with('employee') // связь с User
|
||||
->get();
|
||||
|
||||
$freeSlots = [];
|
||||
|
||||
foreach ($availabilities as $availability) {
|
||||
$employeeId = $availability->employee_id;
|
||||
|
||||
// Найти занятые слоты этого сотрудника
|
||||
$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 мин
|
||||
{
|
||||
$serviceId = $request->query('service_id');
|
||||
$date = $request->query('date');
|
||||
|
||||
if (!$serviceId || !$date) {
|
||||
return response()->json([]);
|
||||
}
|
||||
|
||||
$availabilities = EmployeeAvailability::where('date', $date)
|
||||
->where('is_available', true)
|
||||
->get();
|
||||
|
||||
$slots = [];
|
||||
foreach ($availabilities as $avail) {
|
||||
$slots[] = [
|
||||
'employee_id' => $avail->employee_id,
|
||||
'start' => substr($avail->start_time, 0, 5),
|
||||
'end' => substr($avail->end_time, 0, 5),
|
||||
];
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Services;
|
||||
use App\Models\EmployeeAvailability;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Service;
|
||||
use App\Models\User;
|
||||
|
||||
class BookingsController extends Controller
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
$validated = $request->validate([
|
||||
'service_id' => 'required|exists:services,id',
|
||||
'employee_id' => 'required|exists:users,id',
|
||||
'date' => 'required|date',
|
||||
'starttime' => 'required'
|
||||
'start_time' => 'required|date_format:H:i:s'
|
||||
]);
|
||||
|
||||
$clientId = auth()->id();
|
||||
if (!$clientId) {
|
||||
return response()->json(['error' => 'Авторизация обязательна'], 401);
|
||||
}
|
||||
// Получаем длительность услуги
|
||||
$service = Service::findOrFail($validated['service_id']);
|
||||
$duration = $service->duration_minutes;
|
||||
|
||||
$service = Services::where('id', $request->service_id)
|
||||
->where('isactive', true)
|
||||
->first();
|
||||
if (!$service) {
|
||||
return response()->json(['error' => 'Услуга неактивна или не найдена'], 400);
|
||||
}
|
||||
// Вычисляем end_time
|
||||
$start = new \DateTime($validated['start_time']);
|
||||
$end = clone $start;
|
||||
$end->modify("+$duration minutes");
|
||||
$end_time = $end->format('H:i:s');
|
||||
|
||||
$durationMinutes = $service->durationminutes;
|
||||
$endtime = date('H:i:s', strtotime($request->starttime . " +{$durationMinutes} minutes"));
|
||||
|
||||
$availability = EmployeeAvailability::where('employee_id', $request->employee_id)
|
||||
->where('date', $request->date)
|
||||
->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'])
|
||||
// Проверяем, свободен ли слот
|
||||
$conflict = Booking::where('employee_id', $validated['employee_id'])
|
||||
->where('booking_date', $validated['date'])
|
||||
->where('start_time', '<', $end_time)
|
||||
->where('end_time', '>', $validated['start_time'])
|
||||
->exists();
|
||||
|
||||
if ($bookingExists) {
|
||||
return response()->json(['error' => 'Слот уже забронирован'], 400);
|
||||
if ($conflict) {
|
||||
return response()->json(['message' => 'Слот занят'], 400);
|
||||
}
|
||||
|
||||
$bookingNumber = 'CL-' . date('Y') . '-' . str_pad(Booking::count() + 1, 4, '0', STR_PAD_LEFT);
|
||||
|
||||
// Создаём бронирование
|
||||
$booking = Booking::create([
|
||||
'bookingnumber' => $bookingNumber,
|
||||
'client_id' => $clientId,
|
||||
'employee_id' => $request->employee_id,
|
||||
'service_id' => $request->service_id,
|
||||
'bookingdate' => $request->date,
|
||||
'starttime' => $request->starttime,
|
||||
'endtime' => $endtime,
|
||||
'booking_number' => 'CL-' . date('Y') . '-' . str_pad(Booking::count() + 1, 4, '0', STR_PAD_LEFT),
|
||||
'client_id' => auth()->id(),
|
||||
'employee_id' => $validated['employee_id'],
|
||||
'service_id' => $validated['service_id'],
|
||||
'booking_date' => $validated['date'],
|
||||
'start_time' => $validated['start_time'],
|
||||
'end_time' => $end_time,
|
||||
'status' => 'confirmed'
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'booking' => $booking,
|
||||
'message' => 'Бронирование создано №' . $bookingNumber
|
||||
], 201);
|
||||
return response()->json($booking, 201);
|
||||
}
|
||||
|
||||
public function cancel(Request $request, $id)
|
||||
public function clientIndex()
|
||||
{
|
||||
$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
|
||||
]);
|
||||
}
|
||||
|
||||
public function adminCancel(Request $request, $id)
|
||||
{
|
||||
$booking = Booking::findOrFail($id);
|
||||
|
||||
if (!auth()->user()->isEmployeeOrAdmin()) {
|
||||
return response()->json(['error' => 'Доступ только для админов/сотрудников'], 403);
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => 'cancelled',
|
||||
'cancelledby' => 'admin',
|
||||
'cancelreason' => $request->reason ?? null
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Бронь отменена администратором',
|
||||
'booking' => $booking
|
||||
]);
|
||||
}
|
||||
|
||||
public function clientIndex(Request $request)
|
||||
{
|
||||
$clientId = auth()->id();
|
||||
|
||||
$query = Booking::where('client_id', $clientId);
|
||||
|
||||
if ($request->date) {
|
||||
$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();
|
||||
|
||||
$bookings = Booking::where('client_id', auth()->id())->get();
|
||||
return response()->json($bookings);
|
||||
}
|
||||
|
||||
public function adminIndex(Request $request)
|
||||
// adminIndex
|
||||
public function adminIndex()
|
||||
{
|
||||
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')
|
||||
$bookings = Booking::with(['client', 'employee', 'service'])
|
||||
->orderBy('booking_date', 'desc')
|
||||
->get();
|
||||
|
||||
return response()->json($bookings);
|
||||
}
|
||||
|
||||
public function cancel($id)
|
||||
{
|
||||
$booking = Booking::findOrFail($id);
|
||||
|
||||
if ($booking->client_id !== auth()->id()) {
|
||||
return response()->json(['message' => 'Нет прав'], 403);
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => 'cancelled',
|
||||
'cancelled_by' => 'client',
|
||||
'cancel_reason' => request('reason')
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'Бронь отменена']);
|
||||
}
|
||||
|
||||
// adminCancel
|
||||
public function adminCancel($id)
|
||||
{
|
||||
$booking = Booking::findOrFail($id);
|
||||
$booking->update([
|
||||
'status' => 'cancelled',
|
||||
'cancelled_by' => 'admin',
|
||||
'cancel_reason' => request('reason')
|
||||
]);
|
||||
|
||||
return response()->json(['message' => 'Бронь отменена администратором']);
|
||||
}
|
||||
|
||||
// Назначение сотрудника
|
||||
public function assignEmployee(Request $request, $id)
|
||||
{
|
||||
$request->validate(['employee_id' => 'required|exists:users,id']);
|
||||
|
||||
$booking = Booking::findOrFail($id);
|
||||
$booking->employee_id = $request->employee_id;
|
||||
$booking->save();
|
||||
|
||||
return response()->json($booking);
|
||||
}
|
||||
}
|
||||
@@ -2,78 +2,60 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Services;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Service;
|
||||
|
||||
class ServicesController extends Controller
|
||||
{
|
||||
// GET api/admin/services - список активных услуг
|
||||
public function index()
|
||||
{
|
||||
$services = Services::where('isactive', true)->get();
|
||||
$services = Service::all();
|
||||
return response()->json($services);
|
||||
}
|
||||
|
||||
// POST api/admin/services - создать услугу
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'required|string',
|
||||
'durationminutes' => 'required|integer|min:1|max:500',
|
||||
'price' => 'required|numeric|min:0'
|
||||
'description' => 'nullable|string',
|
||||
'duration_minutes' => 'required|integer',
|
||||
'price' => 'required|numeric',
|
||||
'is_active' => 'boolean'
|
||||
]);
|
||||
|
||||
$service = Services::create([
|
||||
'name' => $request->name,
|
||||
'description' => $request->description,
|
||||
'durationminutes' => $request->durationminutes,
|
||||
'price' => $request->price,
|
||||
'isactive' => true // по умолчанию активна
|
||||
]);
|
||||
|
||||
|
||||
$service = Service::create($validated);
|
||||
|
||||
return response()->json($service, 201);
|
||||
}
|
||||
|
||||
// PUT api/admin/services/{id} - обновить услугу
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$service = Services::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
$service = Service::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'required|string',
|
||||
'durationminutes' => 'required|integer|min:1|max:500',
|
||||
'price' => 'required|numeric|min:0'
|
||||
'description' => 'nullable|string',
|
||||
'duration_minutes' => 'required|integer',
|
||||
'price' => 'required|numeric',
|
||||
'is_active' => 'boolean'
|
||||
]);
|
||||
|
||||
$service->update([
|
||||
'name' => $request->name,
|
||||
'description' => $request->description,
|
||||
'durationminutes' => $request->durationminutes,
|
||||
'price' => $request->price,
|
||||
]);
|
||||
|
||||
|
||||
$service->update($validated);
|
||||
|
||||
return response()->json($service);
|
||||
}
|
||||
|
||||
// DELETE api/admin/services/{id} - только если нет активных броней
|
||||
public function destroy($id)
|
||||
{
|
||||
$service = Services::findOrFail($id);
|
||||
|
||||
// ПРОВЕРКА: нельзя удалить услугу с активными бронями
|
||||
$activeBookings = \App\Models\Booking::where('service_id', $id)
|
||||
->where('status', '!=', 'cancelled')
|
||||
->exists();
|
||||
|
||||
if ($activeBookings) {
|
||||
return response()->json([
|
||||
'error' => 'Нельзя удалить услугу с активными бронями'
|
||||
], 400);
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$service = Service::findOrFail($id);
|
||||
$service->delete();
|
||||
|
||||
return response()->json(['message' => 'Услуга удалена']);
|
||||
}
|
||||
|
||||
$service->delete();
|
||||
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
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -7,10 +9,14 @@ class CheckRole
|
||||
{
|
||||
public function handle(Request $request, Closure $next, $role)
|
||||
{
|
||||
if (!auth()->check() || !auth()->user()->isEmployeeOrAdmin()) {
|
||||
return response()->json(['error' => 'Доступ запрещен'], 403);
|
||||
if (!$request->user()) {
|
||||
return response()->json(['message' => 'Unauthorized'], 401);
|
||||
}
|
||||
|
||||
if ($request->user()->role !== $role) {
|
||||
return response()->json(['message' => 'Access denied'], 403);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
// бронирование клиентов
|
||||
class Booking extends Model {
|
||||
|
||||
class Booking extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'bookings';
|
||||
|
||||
|
||||
protected $fillable = [
|
||||
'bookingnumber',
|
||||
'booking_number',
|
||||
'client_id',
|
||||
'employee_id',
|
||||
'service_id',
|
||||
'bookingdate',
|
||||
'starttime',
|
||||
'endtime',
|
||||
'booking_date',
|
||||
'start_time',
|
||||
'end_time',
|
||||
'status',
|
||||
'cancelledby',
|
||||
'cancelreason'
|
||||
'cancelled_by',
|
||||
'cancel_reason'
|
||||
];
|
||||
|
||||
// списки броней
|
||||
public function service()
|
||||
{
|
||||
return $this->belongsTo(Services::class);
|
||||
}
|
||||
|
||||
// Связь с клиентом
|
||||
public function client()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'client_id');
|
||||
}
|
||||
|
||||
|
||||
// Связь со сотрудником
|
||||
public function employee()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'employee_id');
|
||||
}
|
||||
}
|
||||
|
||||
// Связь с услугой
|
||||
public function service()
|
||||
{
|
||||
return $this->belongsTo(Service::class);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
// расписание сотрудниĸов
|
||||
class EmployeeAvailability extends Model {
|
||||
use HasFactory;
|
||||
protected $table = 'employee_availabilities';
|
||||
protected $fillable = ['employee_id','date','starttime','endtime','isavailable'];
|
||||
}
|
||||
|
||||
class EmployeeAvailability extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'employee_id',
|
||||
'date',
|
||||
'start_time',
|
||||
'end_time',
|
||||
'is_available'
|
||||
];
|
||||
}
|
||||
@@ -2,24 +2,24 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
|
||||
class Services extends Model // услуги ĸлининга
|
||||
class Service extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'description',
|
||||
'durationminutes',
|
||||
'duration_minutes',
|
||||
'price',
|
||||
'isactive',
|
||||
'is_active'
|
||||
];
|
||||
|
||||
// Простая связь с bookings, если нужно
|
||||
// Связь с бронированиями
|
||||
public function bookings()
|
||||
{
|
||||
return $this->hasMany(Booking::class);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,44 +2,24 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Sanctum\HasApiTokens;
|
||||
|
||||
class User extends Authenticatable // все пользователи системы
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
use HasApiTokens, Notifiable;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'role',
|
||||
'role',
|
||||
'phone'
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'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": {
|
||||
"php": "^8.2",
|
||||
"laravel/framework": "^12.0",
|
||||
"laravel/sanctum": "^4.0",
|
||||
"laravel/sanctum": "^4.2",
|
||||
"laravel/tinker": "^2.10.1"
|
||||
},
|
||||
"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",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "d3c16cb86c42230c6c023d9a5d9bcf42",
|
||||
"content-hash": "8f387a0734f3bf879214e4aa2fca6e2f",
|
||||
"packages": [
|
||||
{
|
||||
"name": "brick/math",
|
||||
|
||||
@@ -6,45 +6,21 @@ use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
public function up()
|
||||
{
|
||||
//таблица user
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->string('password');
|
||||
$table->enum('role',['client','admin'])->default('client');
|
||||
$table->enum('role', ['client', 'employee', 'admin'])->default('client');
|
||||
$table->string('phone')->nullable();
|
||||
$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();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('users');
|
||||
Schema::dropIfExists('password_reset_tokens');
|
||||
Schema::dropIfExists('sessions');
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -6,30 +6,21 @@ use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
public function up()
|
||||
{
|
||||
Schema::create('services', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
$table->text('description')->nullable();
|
||||
$table->decimal('price', 10, 2);
|
||||
$table->integer('duration_minutes');
|
||||
$table->unsignedBigInteger('category_id');
|
||||
$table->string('image_url')->nullable();
|
||||
$table->decimal('price', 10, 2);
|
||||
$table->boolean('is_active')->default(true);
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('services');
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,24 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up() {
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
Schema::create('employee_availabilities', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('employee_id');
|
||||
$table->date('date');
|
||||
$table->time('starttime');
|
||||
$table->time('endtime');
|
||||
$table->boolean('isavailable')->default(true);
|
||||
$table->timestamps(); // автоматическое создание created_at и updated_at
|
||||
|
||||
$table->time('start_time');
|
||||
$table->time('end_time');
|
||||
$table->boolean('is_available')->default(true);
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('employee_id')->references('id')->on('users');
|
||||
});
|
||||
}
|
||||
|
||||
public function down() {
|
||||
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('employee_availabilities');
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,35 +1,37 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up() {
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
Schema::create('bookings', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('bookingnumber');
|
||||
$table->string('booking_number')->unique();
|
||||
$table->unsignedBigInteger('client_id');
|
||||
$table->unsignedBigInteger('employee_id');
|
||||
$table->unsignedBigInteger('employee_id');
|
||||
$table->unsignedBigInteger('service_id');
|
||||
$table->date('bookingdate');
|
||||
$table->time('starttime');
|
||||
$table->time('endtime');
|
||||
$table->date('booking_date');
|
||||
$table->time('start_time');
|
||||
$table->time('end_time');
|
||||
$table->enum('status', ['confirmed', 'cancelled', 'completed'])->default('confirmed');
|
||||
$table->enum('cancelledby', ['client', 'admin'])->nullable();
|
||||
$table->text('cancelreason')->nullable();
|
||||
$table->enum('cancelled_by', ['client', 'admin'])->nullable();
|
||||
$table->text('cancel_reason')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
// Внешние ключи
|
||||
|
||||
$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->unique(['employee_id', 'bookingdate', 'starttime'], 'unique_booking_slot');
|
||||
|
||||
$table->unique(['employee_id', 'booking_date', 'start_time']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down() {
|
||||
|
||||
public function down()
|
||||
{
|
||||
Schema::dropIfExists('bookings');
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -2,24 +2,71 @@
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
|
||||
use Illuminate\Database\Seeder;
|
||||
use App\Models\User;
|
||||
use App\Models\Service;
|
||||
use App\Models\EmployeeAvailability;
|
||||
use App\Models\Booking;
|
||||
|
||||
class DatabaseSeeder extends Seeder
|
||||
{
|
||||
use WithoutModelEvents;
|
||||
|
||||
/**
|
||||
* Seed the application's database.
|
||||
*/
|
||||
public function run(): void
|
||||
public function run()
|
||||
{
|
||||
// User::factory(10)->create();
|
||||
// Создаём админа
|
||||
User::create([
|
||||
'name' => 'Админ',
|
||||
'email' => 'admin@example.com',
|
||||
'password' => bcrypt('123'),
|
||||
'role' => 'admin'
|
||||
]);
|
||||
|
||||
User::factory()->create([
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
// Создаём сотрудника
|
||||
User::create([
|
||||
'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>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Все брони - КлинСервис Админка</title>
|
||||
<title>Админка — Бронирования</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: Arial, sans-serif; background: #f8f9fa; }
|
||||
|
||||
/* Хедер */
|
||||
header {
|
||||
background: #2c3e50; color: white; padding: 20px 50px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1); position: sticky; top: 0;
|
||||
background: white; padding: 20px 50px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
position: sticky; top: 0; z-index: 100;
|
||||
}
|
||||
.header-content {
|
||||
max-width: 1400px; margin: 0 auto;
|
||||
max-width: 1200px; margin: 0 auto;
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
.logo { font-size: 24px; font-weight: bold; }
|
||||
.header-nav { display: flex; gap: 20px; }
|
||||
.logo { font-size: 24px; font-weight: bold; color: #667eea; }
|
||||
.btn {
|
||||
padding: 12px 25px; border: none; border-radius: 25px;
|
||||
cursor: pointer; font-size: 16px; text-decoration: none;
|
||||
display: inline-block; transition: all 0.3s; color: white;
|
||||
padding: 10px 20px; border: none; border-radius: 25px;
|
||||
cursor: pointer; font-size: 14px; text-decoration: none;
|
||||
display: inline-block; transition: all 0.3s;
|
||||
}
|
||||
.btn-primary { background: #667eea; }
|
||||
.btn-primary:hover { background: #5a67d8; }
|
||||
.btn-secondary { background: #6c757d; }
|
||||
.btn-secondary:hover { background: #5a6268; }
|
||||
.btn-primary { background: #667eea; color: white; }
|
||||
.btn-secondary { background: transparent; color: #667eea; border: 2px solid #667eea; }
|
||||
|
||||
/* Контейнер */
|
||||
.container { max-width: 1400px; margin: 40px auto; padding: 0 20px; }
|
||||
h1 { text-align: center; color: #333; margin-bottom: 40px; font-size: 32px; }
|
||||
.container { max-width: 1200px; margin: 40px auto; padding: 0 20px; }
|
||||
h1 { text-align: center; margin-bottom: 30px; color: #333; }
|
||||
|
||||
/* Фильтры */
|
||||
.filters {
|
||||
background: white; padding: 30px; border-radius: 20px;
|
||||
box-shadow: 0 20px 40px rgba(0,0,0,0.1); margin-bottom: 30px;
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
@media (max-width: 768px) { .filters { grid-template-columns: 1fr; } }
|
||||
table { width: 100%; border-collapse: collapse; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
|
||||
th, td { padding: 15px; text-align: left; border-bottom: 1px solid #eee; }
|
||||
th { background: #667eea; color: white; }
|
||||
tr:hover { background: #f9f9f9; }
|
||||
|
||||
.filter-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #555; }
|
||||
.filter-group input, .filter-group select {
|
||||
width: 100%; padding: 12px; border: 2px solid #e9ecef;
|
||||
border-radius: 10px; font-size: 16px;
|
||||
}
|
||||
.filter-group input:focus, .filter-group select:focus { border-color: #667eea; outline: none; }
|
||||
select, input { padding: 8px; border: 1px solid #ccc; border-radius: 5px; }
|
||||
.actions { display: flex; gap: 10px; margin-top: 10px; }
|
||||
.btn-sm { padding: 5px 10px; font-size: 12px; }
|
||||
.status { padding: 4px 8px; border-radius: 10px; font-size: 12px; }
|
||||
.confirmed { background: #d4edda; color: #155724; }
|
||||
.cancelled { background: #f8d7da; color: #721c24; }
|
||||
.completed { background: #d1ecf1; color: #0c5460; }
|
||||
|
||||
.filter-btn {
|
||||
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; }
|
||||
}
|
||||
.no-data { text-align: center; padding: 40px; color: #666; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Хедер -->
|
||||
<header>
|
||||
<div class="header-content">
|
||||
<div class="logo">🧹 КлинСервис - Админка</div>
|
||||
<div class="header-nav">
|
||||
<a href="admin-services.html" class="btn btn-secondary">Услуги</a>
|
||||
<a href="admin-schedule.html" class="btn btn-secondary">Расписание</a>
|
||||
<a href="index.html" class="btn btn-primary">На главную</a>
|
||||
<button class="btn btn-secondary" onclick="logout()">Выйти</button>
|
||||
<div class="logo">🧹 Админка — КлинСервис</div>
|
||||
<div>
|
||||
<a href="index.html" class="btn btn-secondary">Главная</a>
|
||||
<button class="btn btn-primary" onclick="logout()">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="container">
|
||||
<h1>📋 Все бронирования</h1>
|
||||
|
||||
<!-- Фильтры -->
|
||||
<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>
|
||||
<tr>
|
||||
<th>Код брони</th>
|
||||
<th>Клиент (email)</th>
|
||||
<th>Услуга</th>
|
||||
<th>Сотрудник</th>
|
||||
<th>Дата и время</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="bookingsTable">
|
||||
<tr>
|
||||
<td colspan="7" class="no-bookings">Загрузка броней...</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</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>
|
||||
<table id="bookingsTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Клиент</th>
|
||||
<th>Услуга</th>
|
||||
<th>Дата и время</th>
|
||||
<th>Сотрудник</th>
|
||||
<th>Статус</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td colspan="7" class="no-data">Загрузка...</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let token = localStorage.getItem('token');
|
||||
let allBookings = [];
|
||||
let filteredBookings = [];
|
||||
let selectedBookingId = null;
|
||||
let bookings = [];
|
||||
let employees = [];
|
||||
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// Загрузка при старте
|
||||
// Загрузка данных при старте
|
||||
window.onload = async function() {
|
||||
await loadBookings();
|
||||
await loadEmployeesForFilter();
|
||||
try {
|
||||
await loadEmployees();
|
||||
await loadBookings();
|
||||
} 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() {
|
||||
try {
|
||||
const response = await fetch('/api/admin/bookings', {
|
||||
const res = await fetch('/api/admin/bookings', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
allBookings = await response.json();
|
||||
filteredBookings = [...allBookings];
|
||||
renderBookings();
|
||||
} else {
|
||||
alert('Ошибка доступа');
|
||||
window.location.href = 'register-login.html';
|
||||
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}`);
|
||||
}
|
||||
|
||||
bookings = await res.json();
|
||||
renderBookings();
|
||||
} catch (error) {
|
||||
document.getElementById('bookingsTable').innerHTML =
|
||||
'<tr><td colspan="7" class="no-bookings">Ошибка загрузки</td></tr>';
|
||||
console.error('Ошибка загрузки бронирований:', error);
|
||||
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() {
|
||||
const tbody = document.getElementById('bookingsTable');
|
||||
|
||||
if (filteredBookings.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="no-bookings">Нет броней по фильтрам</td></tr>';
|
||||
const tbody = document.querySelector('#bookingsTable tbody');
|
||||
if (bookings.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="7" class="no-data">Нет бронирований</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
tbody.innerHTML = '';
|
||||
|
||||
for (let booking of filteredBookings) {
|
||||
const row = document.createElement('tr');
|
||||
const statusClass = booking.status;
|
||||
|
||||
row.innerHTML = `
|
||||
<td><strong>${booking.bookingnumber}</strong></td>
|
||||
<td>${booking.client ? booking.client.email : 'Неизвестно'}</td>
|
||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
||||
<td>${booking.bookingdate}<br>${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
${booking.status !== 'completed' ?
|
||||
`<button class="btn-small btn-cancel-admin" onclick="showCancelModal(${booking.id}, '${booking.bookingnumber}')">
|
||||
❌ Отменить
|
||||
</button>` : ''}
|
||||
${booking.status === 'confirmed' ?
|
||||
`<button class="btn-small btn-complete" onclick="markAsCompleted(${booking.id})">
|
||||
✅ Выполнено
|
||||
</button>` : ''}
|
||||
</div>
|
||||
</td>
|
||||
bookings.forEach(b => {
|
||||
const employeeSelect = document.createElement('select');
|
||||
employeeSelect.className = 'employee-select';
|
||||
employeeSelect.dataset.bookingId = b.id;
|
||||
|
||||
if (!employees.length) {
|
||||
const option = document.createElement('option');
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
const status = b.status || 'confirmed';
|
||||
const statusClass = status;
|
||||
|
||||
const row = `
|
||||
<tr>
|
||||
<td>${b.booking_number || '—'}</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>
|
||||
${employeeSelect.outerHTML}
|
||||
<div class="actions">
|
||||
<button class="btn-sm btn-primary" onclick="saveEmployee(${b.id})">Сохранить</button>
|
||||
</div>
|
||||
</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.appendChild(row);
|
||||
tbody.innerHTML += row;
|
||||
});
|
||||
}
|
||||
|
||||
// Сохранить сотрудника
|
||||
async function saveEmployee(bookingId) {
|
||||
const select = document.querySelector(`.employee-select[data-booking-id="${bookingId}"]`);
|
||||
if (!select || !select.value) {
|
||||
alert('Выберите сотрудника');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Показать модальное окно отмены
|
||||
function showCancelModal(bookingId, bookingNumber) {
|
||||
selectedBookingId = bookingId;
|
||||
document.getElementById('cancelBookingInfo').innerHTML =
|
||||
`Бронь <strong>${bookingNumber}</strong>`;
|
||||
document.getElementById('cancelReason').value = '';
|
||||
document.getElementById('cancelModal').style.display = 'block';
|
||||
}
|
||||
|
||||
// Закрыть модальное окно
|
||||
function closeCancelModal() {
|
||||
document.getElementById('cancelModal').style.display = 'none';
|
||||
}
|
||||
|
||||
// Админская отмена
|
||||
async function adminCancelBooking() {
|
||||
const reason = document.getElementById('cancelReason').value;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/bookings/${selectedBookingId}/cancel`, {
|
||||
const res = await fetch(`/api/admin/bookings/${bookingId}/assign`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reason: reason || null })
|
||||
body: JSON.stringify({ employee_id: select.value })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
alert('✅ Бронь отменена администратором');
|
||||
closeCancelModal();
|
||||
|
||||
if (res.ok) {
|
||||
alert('✅ Сотрудник назначен!');
|
||||
loadBookings();
|
||||
} else {
|
||||
alert('Ошибка: ' + data.error);
|
||||
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||
alert('Ошибка: ' + (err.message || 'Не удалось назначить сотрудника'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети');
|
||||
alert('Ошибка сети: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Пометить как выполнено
|
||||
async function markAsCompleted(bookingId) {
|
||||
if (confirm('Пометить бронь как выполненную?')) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/bookings/${bookingId}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ status: 'completed' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert('✅ Бронь отмечена как выполненная');
|
||||
loadBookings();
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка');
|
||||
// Отменить бронь
|
||||
async function cancelBooking(bookingId) {
|
||||
const reason = prompt('Причина отмены:');
|
||||
if (reason === null) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/admin/bookings/${bookingId}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reason: reason.trim() || null })
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
alert('✅ Бронь отменена!');
|
||||
loadBookings();
|
||||
} else {
|
||||
const err = await res.json().catch(() => ({ message: 'Неизвестная ошибка' }));
|
||||
alert('Ошибка: ' + (err.message || 'Не удалось отменить бронь'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,17 +267,6 @@
|
||||
localStorage.removeItem('token');
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -171,21 +171,53 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('auth_token');
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
if (!token) {
|
||||
window.location.href = '/register-login.html';
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
fetch('/api/admin/availabilities', {
|
||||
headers: { 'Authorization': 'Bearer ' + token }
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const list = document.getElementById('schedule-list');
|
||||
data.forEach(avail => {
|
||||
list.innerHTML += `<p>${avail.employee_id} — ${avail.date} ${avail.starttime} - ${avail.endtime}</p>`;
|
||||
});
|
||||
});
|
||||
window.onload = loadSchedule;
|
||||
|
||||
async function loadSchedule() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/availabilities', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
const availabilities = await res.json();
|
||||
|
||||
const list = document.getElementById('schedule-list');
|
||||
availabilities.forEach(a => {
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -180,45 +180,105 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Получаем токен из localStorage
|
||||
const token = localStorage.getItem('auth_token');
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Если нет токена — перенаправляем на вход
|
||||
if (!token) {
|
||||
alert('Доступ только для администраторов!');
|
||||
window.location.href = '/register-login.html';
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// Загружаем услуги
|
||||
fetch('/api/admin/services', {
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + token,
|
||||
'Accept': 'application/json'
|
||||
window.onload = loadServices;
|
||||
|
||||
async function loadServices() {
|
||||
try {
|
||||
const res = await fetch('/api/admin/services', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
const services = await res.json();
|
||||
|
||||
const list = document.getElementById('services-list');
|
||||
services.forEach(s => {
|
||||
list.innerHTML += `
|
||||
<div>
|
||||
<p><strong>${s.name}</strong> — ${s.price}₽ — ${s.is_active ? 'Активна' : 'Неактивна'}</p>
|
||||
<button onclick="editService(${s.id})">Редактировать</button>
|
||||
<button onclick="toggleService(${s.id}, ${s.is_active})">${s.is_active ? '❌ Деактивировать' : '✅ Активировать'}</button>
|
||||
<button onclick="deleteService(${s.id})">🗑️ Удалить</button>
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} catch (err) {
|
||||
alert('Ошибка загрузки услуг');
|
||||
}
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Ошибка сервера: ' + response.status);
|
||||
}
|
||||
|
||||
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('Ошибка добавления');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
const servicesList = document.getElementById('services-list');
|
||||
data.forEach(service => {
|
||||
const item = document.createElement('div');
|
||||
item.innerHTML = `
|
||||
<h3>${service.name}</h3>
|
||||
<p>Цена: ${service.price} ₽</p>
|
||||
<p>Описание: ${service.description || 'Нет описания'}</p>
|
||||
<hr>
|
||||
`;
|
||||
servicesList.appendChild(item);
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Ошибка:', error);
|
||||
document.body.innerHTML = `<h2 style="color: red;">Ошибка загрузки данных: ${error.message}</h2>`;
|
||||
});
|
||||
}
|
||||
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -128,28 +128,56 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Получить данные брони из localStorage (передается из services.html)
|
||||
const bookingData = JSON.parse(localStorage.getItem('lastBooking') || '{}');
|
||||
|
||||
if (bookingData.booking) {
|
||||
const booking = bookingData.booking;
|
||||
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 || '???'} ₽`;
|
||||
}
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Очистка localStorage через 30 секунд
|
||||
setTimeout(() => {
|
||||
localStorage.removeItem('lastBooking');
|
||||
}, 30000);
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
window.onload = loadBookings;
|
||||
|
||||
async function loadBookings() {
|
||||
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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -152,19 +152,20 @@
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
// прокрутка к секции услуг
|
||||
document.querySelector('.hero-buttons .btn-secondary').onclick = function(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById('services').scrollIntoView({
|
||||
behavior: 'smooth'
|
||||
});
|
||||
};
|
||||
const token = localStorage.getItem('token');
|
||||
|
||||
// Проверка авторизации
|
||||
if (localStorage.getItem('token')) {
|
||||
// Пользователь авторизован - можно добавить кнопку "Личный кабинет"
|
||||
console.log('Пользователь авторизован');
|
||||
}
|
||||
if (token) {
|
||||
// Если авторизован — показываем кнопки "Личный кабинет" и "Выход"
|
||||
document.querySelector('.auth-buttons').innerHTML = `
|
||||
<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>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
@@ -212,11 +212,12 @@
|
||||
|
||||
const canCancel = booking.status === 'confirmed';
|
||||
|
||||
// ИСПРАВЛЕНО: используем правильные имена полей с подчёркиваниями
|
||||
row.innerHTML = `
|
||||
<td><strong>${booking.bookingnumber}</strong></td>
|
||||
<td>${booking.bookingdate} ${booking.starttime.slice(0,5)}–${booking.endtime.slice(0,5)}</td>
|
||||
<td>${booking.service ? booking.service.name : 'Удалена'}</td>
|
||||
<td>${booking.employee ? booking.employee.name : 'Не назначен'}</td>
|
||||
<td><strong>${booking.booking_number}</strong></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.employee ? booking.employee.name : 'Сотрудник не назначен'}</td>
|
||||
<td><span class="status ${statusClass}">${booking.status}</span></td>
|
||||
<td>
|
||||
${canCancel ?
|
||||
@@ -266,7 +267,7 @@
|
||||
closeModal();
|
||||
loadBookings(); // Перезагрузить список
|
||||
} else {
|
||||
alert('Ошибка: ' + data.error);
|
||||
alert('Ошибка: ' + (data.message || data.error || 'Не удалось отменить бронь'));
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка сети');
|
||||
@@ -288,4 +289,4 @@
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
@@ -75,7 +75,6 @@
|
||||
<body>
|
||||
|
||||
<div class="container">
|
||||
<!-- Форма входа -->
|
||||
<div id="loginSection">
|
||||
<h2>Вход</h2>
|
||||
<div id="loginResult"></div>
|
||||
@@ -91,7 +90,6 @@
|
||||
<div class="toggle" onclick="showRegisterForm()">Нет аккаунта? Зарегистрироваться</div>
|
||||
</div>
|
||||
|
||||
<!-- Форма регистрации -->
|
||||
<div id="registerSection" style="display: none;">
|
||||
<h2>Регистрация</h2>
|
||||
<div id="registerResult"></div>
|
||||
@@ -117,106 +115,75 @@
|
||||
</div>
|
||||
|
||||
<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() {
|
||||
document.getElementById('loginSection').style.display = 'none';
|
||||
document.getElementById('registerSection').style.display = 'block';
|
||||
}
|
||||
|
||||
// Показать форму входа
|
||||
function showLoginForm() {
|
||||
document.getElementById('registerSection').style.display = 'none';
|
||||
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>
|
||||
|
||||
</body>
|
||||
|
||||
@@ -142,11 +142,8 @@
|
||||
<label>Длительность</label>
|
||||
<input type="text" id="duration" readonly placeholder="Выберите услугу">
|
||||
</div>
|
||||
</div>
|
||||
<button class="book-btn" id="bookBtn" onclick="bookService()" disabled>
|
||||
Выбрать время →
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
|
||||
<!-- Календарь -->
|
||||
<div class="calendar-section">
|
||||
@@ -173,46 +170,242 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let services = [];
|
||||
let selectedServiceId = null;
|
||||
let selectedDate = null;
|
||||
let currentMonth = new Date().getMonth();
|
||||
let currentYear = new Date().getFullYear();
|
||||
let availableSlots = [];
|
||||
let token = localStorage.getItem('token');
|
||||
let services = [];
|
||||
let selectedServiceId = null;
|
||||
let selectedDate = null;
|
||||
let currentMonth = new Date().getMonth();
|
||||
let currentYear = new Date().getFullYear();
|
||||
let availableSlots = [];
|
||||
let token = localStorage.getItem('token');
|
||||
let selectedSlot = null;
|
||||
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
throw new Error('Нужна авторизация');
|
||||
}
|
||||
updateHeader();
|
||||
// Проверка авторизации
|
||||
if (!token) {
|
||||
window.location.href = 'register-login.html';
|
||||
}
|
||||
|
||||
// 1. Загрузить услуги при загрузке страницы
|
||||
window.onload = async function() {
|
||||
await loadServices();
|
||||
initCalendar();
|
||||
};
|
||||
// Загрузка страницы
|
||||
window.onload = async function() {
|
||||
// Убедимся, что элементы существуют
|
||||
if (!document.getElementById('serviceSelect')) {
|
||||
console.error('Элемент #serviceSelect не найден');
|
||||
return;
|
||||
}
|
||||
|
||||
// Загрузка услуг из API (только isactive=true)
|
||||
async function loadServices() {
|
||||
try {
|
||||
const response = await fetch('/api/admin/services', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
services = data.filter(service => service.isactive);
|
||||
const select = document.getElementById('serviceSelect');
|
||||
|
||||
select.innerHTML = '<option value="">Выберите услугу</option>';
|
||||
for (let service of services) {
|
||||
select.innerHTML += `<option value="${service.id}" data-duration="${service.durationminutes}">${service.name} (${service.durationminutes} мин) - ${service.price}₽</option>`;
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Ошибка загрузки услуг');
|
||||
try {
|
||||
await loadServices();
|
||||
initCalendar();
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки:', error);
|
||||
alert('Не удалось загрузить данные');
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ 1. ЗАГРУЗКА УСЛУГ (публичный API)
|
||||
async function loadServices() {
|
||||
try {
|
||||
const response = await fetch('/api/services');
|
||||
const data = await response.json();
|
||||
|
||||
services = data.filter(service => service.is_active); // ← is_active, не isactive
|
||||
|
||||
const select = document.getElementById('serviceSelect');
|
||||
select.innerHTML = '<option value="">Выберите услугу</option>';
|
||||
|
||||
for (let service of services) {
|
||||
const option = document.createElement('option');
|
||||
option.value = service.id;
|
||||
option.textContent = `${service.name} (${service.duration_minutes} мин) - ${service.price}₽`;
|
||||
select.appendChild(option);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error('Ошибка загрузки услуг: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. При выборе услуги — показываем длительность
|
||||
document.getElementById('serviceSelect').onchange = function() {
|
||||
const serviceId = this.value;
|
||||
if (!serviceId) {
|
||||
document.getElementById('duration').value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Изменение услуги
|
||||
//document.getElementById('serviceSelect').onchange = function()//
|
||||
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
|
||||
|
||||
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\Support\Facades\Route;
|
||||
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) {
|
||||
return $request->user();
|
||||
})->middleware('auth:sanctum');
|
||||
|
||||
// РЕГИСТРАЦИЯ ТОЛЬКО КЛИЕНТОВ (публичный)
|
||||
Route::post('/register', [UserController::class, 'register']);
|
||||
|
||||
Route::post('/login', [AuthController::class, 'login']);
|
||||
|
||||
// Существующие роуты categories
|
||||
Route::get('/categories', [CategoriesController::class, 'index'])->middleware('auth:sanctum');
|
||||
// === ПУБЛИЧНЫЕ РОУТЫ ===
|
||||
Route::post('/register', [AuthController::class, 'register']);
|
||||
Route::post('/login', [AuthController::class, 'login'])->name('login');
|
||||
Route::get('/services', [ServicesController::class, 'publicIndex']);
|
||||
Route::get('/availability', [AvailabilitiesController::class, 'publicAvailability']);
|
||||
Route::get('/categories/{id}', [CategoriesController::class, 'show']);
|
||||
Route::post('/categories', [CategoriesController::class, 'create']);
|
||||
|
||||
// ПУБЛИЧНЫЙ API доступности (без авторизации)
|
||||
Route::get('/availability', [AvailabilitiesController::class, 'publicAvailability']);
|
||||
|
||||
// КЛИЕНТСКИЕ РОУТЫ БРОНИРОВАНИЙ (auth:sanctum)
|
||||
Route::middleware('auth:sanctum', 'role:admin')->group(function () {
|
||||
Route::post('/bookings', [BookingsController::class, 'store']);
|
||||
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'cancel']);
|
||||
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'adminCancel']);
|
||||
// === ЗАЩИЩЁННЫЕ РОУТЫ ===
|
||||
Route::middleware('auth:sanctum')->group(function () {
|
||||
Route::get('/categories', [CategoriesController::class, 'index']);
|
||||
Route::get('/bookings', [BookingsController::class, 'clientIndex']);
|
||||
Route::get('/bookings', [BookingsController::class, 'adminIndex']);
|
||||
Route::post('/bookings', [BookingsController::class, 'store']);
|
||||
Route::post('/bookings/{id}/cancel', [BookingsController::class, 'cancel']);
|
||||
|
||||
// Получить сотрудников
|
||||
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 () {
|
||||
// CRUD услуги
|
||||
// === АДМИНСКИЕ РОУТЫ ===
|
||||
Route::middleware(['auth:sanctum', 'role:admin'])->prefix('admin')->group(function () {
|
||||
// Услуги
|
||||
Route::get('/services', [ServicesController::class, 'index']);
|
||||
Route::post('/services', [ServicesController::class, 'store']);
|
||||
Route::put('/services/{id}', [ServicesController::class, 'update']);
|
||||
Route::delete('/services/{id}', [ServicesController::class, 'destroy']);
|
||||
|
||||
// CRUD расписание
|
||||
// Расписание
|
||||
Route::get('/availabilities', [AvailabilitiesController::class, 'index']);
|
||||
Route::post('/availabilities', [AvailabilitiesController::class, 'store']);
|
||||
Route::post('/availabilities/bulk', [AvailabilitiesController::class, 'bulkStore']);
|
||||
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