-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.yaml
More file actions
775 lines (746 loc) · 29.2 KB
/
Copy pathapi.yaml
File metadata and controls
775 lines (746 loc) · 29.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
openapi: 3.0.3
info:
title: Room Booking Service (Test Task)
description: Сервис бронирования переговорок
version: "1.0.0"
servers:
- url: http://localhost:8080
tags:
- name: Auth
- name: Rooms
- name: Schedules
- name: Slots
- name: Bookings
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
parameters:
RoomIdPath:
name: roomId
in: path
required: true
schema:
type: string
format: uuid
description: Идентификатор переговорки
BookingIdPath:
name: bookingId
in: path
required: true
schema:
type: string
format: uuid
description: Идентификатор брони
schemas:
ErrorResponse:
type: object
required: [error]
properties:
error:
type: object
required: [code, message]
properties:
code:
type: string
enum:
- INVALID_REQUEST
- UNAUTHORIZED
- NOT_FOUND
- ROOM_NOT_FOUND
- SLOT_NOT_FOUND
- SLOT_ALREADY_BOOKED
- BOOKING_NOT_FOUND
- FORBIDDEN
- SCHEDULE_EXISTS
- INTERNAL_ERROR
message:
type: string
example:
error:
code: INVALID_REQUEST
message: invalid request
InternalErrorResponse:
type: object
required: [error]
properties:
error:
type: object
required: [code, message]
properties:
code:
type: string
example: INTERNAL_ERROR
message:
type: string
example:
error:
code: INTERNAL_ERROR
message: internal server error
Token:
type: object
required: [token]
properties:
token:
type: string
description: JWT для заголовка Authorization Bearer
User:
type: object
required: [id, email, role]
properties:
id:
type: string
format: uuid
email:
type: string
format: email
role:
type: string
enum: [admin, user]
createdAt:
type: string
format: date-time
nullable: true
Room:
type: object
required: [id, name]
properties:
id:
type: string
format: uuid
name:
type: string
description:
type: string
nullable: true
capacity:
type: integer
nullable: true
createdAt:
type: string
format: date-time
nullable: true
Schedule:
type: object
required: [roomId, daysOfWeek, startTime, endTime]
properties:
id:
type: string
format: uuid
roomId:
type: string
format: uuid
daysOfWeek:
type: array
items:
type: integer
minimum: 1
maximum: 7
description: "1=Пн .. 7=Вс, дни доступности. Каждое значение должно быть в диапазоне 1–7."
startTime:
type: string
pattern: "^([01]?[0-9]|2[0-3]):[0-5][0-9]$"
description: Время начала (HH:MM) в рамках дня. Интерпретируется как UTC.
endTime:
type: string
pattern: "^([01]?[0-9]|2[0-3]):[0-5][0-9]$"
description: Время окончания (HH:MM) в рамках дня. Интерпретируется как UTC.
Slot:
type: object
required: [id, roomId, start, end]
properties:
id:
type: string
format: uuid
roomId:
type: string
format: uuid
start:
type: string
format: date-time
description: Время начала слота в UTC (ISO 8601, например 2024-06-10T09:00:00Z)
end:
type: string
format: date-time
description: Время окончания слота в UTC (ISO 8601, например 2024-06-10T09:30:00Z)
Booking:
type: object
required: [id, slotId, userId, status]
properties:
id:
type: string
format: uuid
slotId:
type: string
format: uuid
userId:
type: string
format: uuid
status:
type: string
enum: [active, cancelled]
conferenceLink:
type: string
format: uri
nullable: true
createdAt:
type: string
format: date-time
nullable: true
Pagination:
type: object
required: [page, pageSize, total]
properties:
page:
type: integer
description: Текущая страница (начиная с 1)
pageSize:
type: integer
description: Размер страницы
total:
type: integer
description: Общее количество записей
paths:
# ──────────────────────────────────────────────────────────────
# Auth
# ──────────────────────────────────────────────────────────────
/register:
post:
tags: [Auth]
summary: "Регистрация пользователя (ДОПОЛНИТЕЛЬНОЕ ЗАДАНИЕ — необязательно)"
description: >
Создаёт нового пользователя и возвращает его данные.
Реализация этого эндпоинта является **дополнительным заданием**.
Для авторизации в рамках обязательной части используйте `/dummyLogin`.
Доступен без авторизации.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [email, password, role]
properties:
email:
type: string
format: email
password:
type: string
role:
type: string
enum: [admin, user]
responses:
'201':
description: Пользователь создан
content:
application/json:
schema:
type: object
properties:
user:
$ref: '#/components/schemas/User'
'400':
description: Неверный запрос или email уже занят
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/login:
post:
tags: [Auth]
summary: "Авторизация по email и паролю (ДОПОЛНИТЕЛЬНОЕ ЗАДАНИЕ — необязательно)"
description: >
Авторизует пользователя по email и паролю, возвращает JWT.
Реализация этого эндпоинта является **дополнительным заданием**.
Для авторизации в рамках обязательной части используйте `/dummyLogin`.
Доступен без авторизации.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [email, password]
properties:
email:
type: string
format: email
password:
type: string
responses:
'200':
description: Успешная авторизация
content:
application/json:
schema:
$ref: '#/components/schemas/Token'
'401':
description: Неверные учётные данные
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/dummyLogin:
post:
tags: [Auth]
summary: Получить тестовый JWT по роли (ОБЯЗАТЕЛЬНО). Доступен без авторизации.
description: >
Выдаёт тестовый JWT для указанной роли (admin / user).
Для каждой роли возвращается **фиксированный UUID** пользователя:
один и тот же UUID для всех запросов с ролью admin и один и тот же UUID для роли user.
Это обеспечивает стабильность при тестировании сценариев, требующих проверки владельца брони.
JWT должен содержать как минимум `user_id` (UUID) и `role`.
Этот эндпоинт является **обязательным** и должен быть реализован в любом случае,
независимо от реализации `/register` и `/login`.
Принимает только допустимые значения роли: `admin` или `user`; иные значения — 400.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [role]
properties:
role:
type: string
enum: [admin, user]
responses:
'200':
description: Тестовый токен
content:
application/json:
schema:
$ref: '#/components/schemas/Token'
'400':
description: Неверный запрос (недопустимое значение роли)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
# ──────────────────────────────────────────────────────────────
# Rooms
# ──────────────────────────────────────────────────────────────
/rooms/list:
get:
tags: [Rooms]
summary: Список переговорок (admin и user)
security: [{ BearerAuth: [] }]
responses:
'200':
description: Список переговорок
content:
application/json:
schema:
type: object
properties:
rooms:
type: array
items:
$ref: '#/components/schemas/Room'
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/rooms/create:
post:
tags: [Rooms]
summary: Создать переговорку (только admin)
security: [{ BearerAuth: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [name]
properties:
name:
type: string
description:
type: string
nullable: true
capacity:
type: integer
nullable: true
responses:
'201':
description: Переговорка создана
content:
application/json:
schema:
type: object
properties:
room:
$ref: '#/components/schemas/Room'
'400':
description: Неверный запрос
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Доступ запрещён (требуется роль admin)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
# ──────────────────────────────────────────────────────────────
# Schedules
# ──────────────────────────────────────────────────────────────
/rooms/{roomId}/schedule/create:
post:
tags: [Schedules]
summary: Создать расписание переговорки (только admin, только один раз). Длительность слота 30 мин. После создания расписание изменить нельзя.
description: >
Доступно только роли admin.
Расписание можно создать только один раз для каждой переговорки.
Поле `daysOfWeek` должно содержать значения от 1 до 7 (1=Пн, 7=Вс).
При передаче значений вне этого диапазона возвращается 400.
security: [{ BearerAuth: [] }]
parameters:
- $ref: '#/components/parameters/RoomIdPath'
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Schedule'
responses:
'201':
description: Расписание сохранено
content:
application/json:
schema:
type: object
properties:
schedule:
$ref: '#/components/schemas/Schedule'
'400':
description: Неверный запрос (в т.ч. недопустимые значения daysOfWeek)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Доступ запрещён (требуется роль admin)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'404':
description: Переговорка не найдена
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'409':
description: Расписание для переговорки уже создано, изменение не допускается
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
example:
error:
code: SCHEDULE_EXISTS
message: schedule for this room already exists and cannot be changed
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
# ──────────────────────────────────────────────────────────────
# Slots
# ──────────────────────────────────────────────────────────────
/rooms/{roomId}/slots/list:
get:
tags: [Slots]
summary: Список доступных для бронирования слотов по переговорке и дате (admin и user). Наиболее нагруженный эндпоинт.
description: >
Возвращает слоты, не занятые активной бронью, для указанной переговорки на указанную дату.
Все даты и время передаются и возвращаются в UTC.
Параметр `date` является обязательным; при его отсутствии возвращается 400.
Если у переговорки нет расписания — возвращается пустой список (переговорка считается всегда недоступной).
security: [{ BearerAuth: [] }]
parameters:
- $ref: '#/components/parameters/RoomIdPath'
- name: date
in: query
required: true
description: "Дата в формате ISO 8601 (например: 2024-06-10). Обязательный параметр; при отсутствии — 400."
schema:
type: string
format: date
responses:
'200':
description: Список доступных слотов (не занятых активной бронью). Пустой список, если у переговорки нет расписания или на эту дату нет слотов.
content:
application/json:
schema:
type: object
properties:
slots:
type: array
items:
$ref: '#/components/schemas/Slot'
'400':
description: Неверный запрос (отсутствует или некорректен параметр date)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'404':
description: Переговорка не найдена
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
# ──────────────────────────────────────────────────────────────
# Bookings
# ──────────────────────────────────────────────────────────────
/bookings/create:
post:
tags: [Bookings]
summary: Создать бронь на слот (только user). Опционально — запросить ссылку на конференцию.
description: >
Доступно только роли user. Администратор не может создавать брони (403).
`userId` берётся из JWT-токена, а не из тела запроса.
Если временной слот находится в прошлом (start < now), возвращается 400 (INVALID_REQUEST).
security: [{ BearerAuth: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [slotId]
properties:
slotId:
type: string
format: uuid
createConferenceLink:
type: boolean
default: false
responses:
'201':
description: Бронь создана
content:
application/json:
schema:
type: object
properties:
booking:
$ref: '#/components/schemas/Booking'
'400':
description: Неверный запрос
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Доступ запрещён (бронирование доступно только роли user)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'404':
description: Слот не найден
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'409':
description: Слот уже занят
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
example:
error:
code: SLOT_ALREADY_BOOKED
message: slot is already booked
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/bookings/list:
get:
tags: [Bookings]
summary: Список всех броней с пагинацией (только admin)
description: >
Доступно только роли admin.
Поддерживает пагинацию через параметры `page` и `pageSize`.
Оба параметра опциональны; значения по умолчанию: `page=1`, `pageSize=20`.
Максимальное значение `pageSize` — 100.
security: [{ BearerAuth: [] }]
parameters:
- name: page
in: query
description: Номер страницы (начиная с 1). По умолчанию 1.
schema:
type: integer
minimum: 1
default: 1
- name: pageSize
in: query
description: Количество записей на странице. По умолчанию 20, максимум 100.
schema:
type: integer
minimum: 1
maximum: 100
default: 20
responses:
'200':
description: Список всех броней
content:
application/json:
schema:
type: object
properties:
bookings:
type: array
items:
$ref: '#/components/schemas/Booking'
pagination:
$ref: '#/components/schemas/Pagination'
'400':
description: Неверный запрос (некорректные параметры пагинации)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Доступ запрещён (только admin)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/bookings/my:
get:
tags: [Bookings]
summary: Список броней текущего пользователя (только user)
description: >
Доступно только роли user.
Возвращает брони пользователя, чей `user_id` содержится в JWT-токене.
Возвращаются только брони на будущие слоты (start >= now); брони на уже прошедшие слоты в ответ не включаются.
security: [{ BearerAuth: [] }]
responses:
'200':
description: Список броней текущего пользователя
content:
application/json:
schema:
type: object
properties:
bookings:
type: array
items:
$ref: '#/components/schemas/Booking'
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Доступ запрещён (только user)
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }
/bookings/{bookingId}/cancel:
post:
tags: [Bookings]
summary: Отменить бронь (только своя бронь, только user)
description: >
Доступно только роли user. Пользователь может отменить только свою бронь.
Операция **идемпотентна**: повторный вызов на уже отменённой брони не является ошибкой
и возвращает 200 с актуальным состоянием брони (status: cancelled).
При попытке отменить чужую бронь — 403.
При отсутствии брони с указанным ID — 404.
security: [{ BearerAuth: [] }]
parameters:
- $ref: '#/components/parameters/BookingIdPath'
responses:
'200':
description: Бронь отменена (или уже была отменена ранее)
content:
application/json:
schema:
type: object
properties:
booking:
$ref: '#/components/schemas/Booking'
'401':
description: Не авторизован
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'403':
description: Не своя бронь или роль не user
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
example:
error:
code: FORBIDDEN
message: cannot cancel another user's booking
'404':
description: Бронь не найдена
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'500':
description: Внутренняя ошибка сервера
content:
application/json:
schema: { $ref: '#/components/schemas/InternalErrorResponse' }