File size: 7,396 Bytes
d76f93d
 
 
 
 
 
 
 
 
 
2200342
 
d76f93d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2200342
 
 
 
 
 
 
 
 
d76f93d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
   Controller,
   Get,
   Route,
   Tags,
   Post,
   Body,
   Patch,
   Delete,
   Path,
   Response,
   Produces,
} from "tsoa";
import {
   Book,
   BookStatus,
   BorrowBookRequest,
   CreateBookRequest,
   ReturnBookRequest,
} from "../models/Book";
import { readMyData, writeMyData } from "../utils/fileStorage";
import { wrapResponse, ApiResponse } from "../utils/responseWrapper";
import { v4 as uuidv4 } from "uuid";
import { NotFoundError, BadRequestError } from "../utils/apiErrors";
import { BookValidator } from "../validators/bookValidator";
import { Visitor } from "../models/Visitor";
import { Employee } from "../models/Employee";
import { DateUtils } from "../utils/dateUtils";
import { bookLinkManager } from "../models/Book";
import { Link } from "../models/Link";

@Route("books")
@Tags("Books")
export class BookController extends Controller {
   private file = "books.sea";
   private visitorsFile = "visitors.sea";
   private employeesFile = "employees.sea";

   @Get("/")
   public async getBooks(): Promise<ApiResponse<Book[]>> {
      const books = await readMyData<Book>(this.file);
      return wrapResponse(books);
   }

   @Post("/")
   public async addBook(
      @Body() body: CreateBookRequest
   ): Promise<ApiResponse<Book>> {
      BookValidator.validate(body);

      const books = await readMyData<Book>(this.file);
      const newBook: Book = {
         id: uuidv4(),
         ...body,
         status: BookStatus.AVAILABLE,
      };
      books.push(newBook);

      await writeMyData(this.file, books);

      return wrapResponse(newBook);
   }

   @Get("/{id}")
   public async getBook(id: string): Promise<ApiResponse<Book>> {
      const books = await readMyData<Book>(this.file);
      const book = books.find((b) => b.id === id);

      if (!book) {
         throw new NotFoundError(`Book with id ${id} not found`);
      }

      return wrapResponse(book);
   }

   @Patch("/{id}")
   public async updateBook(
      @Path() id: string,
      @Body() body: Partial<CreateBookRequest>
   ): Promise<ApiResponse<Book>> {
      BookValidator.validateForUpdate(body);

      const books = await readMyData<Book>(this.file);
      const bookIndex = books.findIndex((b) => b.id === id);

      if (bookIndex === -1) {
         throw new NotFoundError(`Book with id ${id} not found`);
      }

      books[bookIndex] = { ...books[bookIndex], ...body };
      await writeMyData(this.file, books);

      return wrapResponse(books[bookIndex]);
   }

   @Delete("/{id}")
   public async deleteBook(
      @Path() id: string
   ): Promise<ApiResponse<{ message: string }>> {
      const books = await readMyData<Book>(this.file);
      const index = books.findIndex((b) => b.id === id);

      if (index === -1) {
         throw new NotFoundError(`Book with id ${id} not found`);
      }

      books.splice(index, 1);
      await writeMyData(this.file, books);

      return wrapResponse({
         message: `Book with id ${id} deleted successfully`,
      });
   }

   @Get("/{id}/download")
   @Produces("application/json")
   public async downloadBook(
      @Path() id: string
   ): Promise<string> {
      const book = await this.getBook(id);
      return JSON.stringify(book.data, null, 2);
   }

   @Post("/borrow")
   public async borrowBook(
      @Body() body: BorrowBookRequest
   ): Promise<ApiResponse<{ message: string }>> {
      const books = await readMyData<Book>(this.file);
      const visitors = await readMyData<Visitor>(this.visitorsFile);
      const employees = await readMyData<Employee>(this.employeesFile);

      const visitorIndex = visitors.findIndex((v) => v.id === body.visitorId);
      if (visitorIndex === -1) {
         throw new NotFoundError(`Visitor with id ${body.visitorId} not found`);
      }

      const employee = employees.find((e) => e.id === body.employeeId);
      if (!employee) {
         throw new NotFoundError(
            `Employee with id ${body.employeeId} not found`
         );
      }

      if (!DateUtils.isWorkingDay(body.borrowDate, employee.workDays)) {
         throw new BadRequestError("Library is closed on this day");
      }

      const borrowedBooks: string[] = [];

      for (const bookId of body.bookIds) {
         const bookIndex = books.findIndex((b) => b.id === bookId);

         if (bookIndex === -1) {
            throw new NotFoundError(`Book with id ${bookId} not found`);
         }

         if (books[bookIndex].status === BookStatus.BORROWED) {
            throw new BadRequestError(
               `Book "${books[bookIndex].title}" is already borrowed`
            );
         }

         books[bookIndex].status = BookStatus.BORROWED;

            
         const bookLink = bookLinkManager.toLink(bookId);
         visitors[visitorIndex].currentBooks.push(bookLink);

         borrowedBooks.push(bookId);
      }

      await writeMyData(this.file, books);
      await writeMyData(this.visitorsFile, visitors);

      return wrapResponse({
         message: `Successfully borrowed ${borrowedBooks.length} book(s)`,
      });
   }

   @Post("/return")
   public async returnBook(
      @Body() body: ReturnBookRequest
   ): Promise<ApiResponse<{ message: string }>> {
      const books = await readMyData<Book>(this.file);
      const visitors = await readMyData<Visitor>(this.visitorsFile);
      const employees = await readMyData<Employee>(this.employeesFile);

      const visitorIndex = visitors.findIndex((v) => v.id === body.visitorId);
      if (visitorIndex === -1) {
         throw new NotFoundError(`Visitor with id ${body.visitorId} not found`);
      }

      const employee = employees.find((e) => e.id === body.employeeId);
      if (!employee) {
         throw new NotFoundError(
            `Employee with id ${body.employeeId} not found`
         );
      }

      if (!DateUtils.isWorkingDay(body.returnDate, employee.workDays)) {
         throw new BadRequestError("Library is closed on this day");
      }

      const returnedBooks: string[] = [];

      for (const bookId of body.bookIds) {
         const bookIndex = books.findIndex((b) => b.id === bookId);

         if (bookIndex === -1) {
            throw new NotFoundError(`Book with id ${bookId} not found`);
         }

         if (books[bookIndex].status === BookStatus.AVAILABLE) {
            throw new BadRequestError(
               `Book "${books[bookIndex].title}" is not borrowed`
            );
         }

         // Ищем Link объект в currentBooks
         const linkIndex = visitors[visitorIndex].currentBooks.findIndex(
            (link) => (link).id === bookId
         );

         if (linkIndex === -1) {
            throw new BadRequestError(
               `Visitor does not have book "${books[bookIndex].title}"`
            );
         }

         books[bookIndex].status = BookStatus.AVAILABLE;

         // Удаляем из currentBooks и добавляем в history как Link объект
         const bookLink = visitors[visitorIndex].currentBooks.splice(
            linkIndex,
            1
         )[0];
         visitors[visitorIndex].history.push(bookLink);

         returnedBooks.push(bookId);
      }

      await writeMyData(this.file, books);
      await writeMyData(this.visitorsFile, visitors);

      return wrapResponse({
         message: `Successfully returned ${returnedBooks.length} book(s)`,
      });
   }
}