All files / book book.service.ts

99.33% Statements 148/149
99.36% Branches 155/156
100% Functions 17/17
99.32% Lines 146/147

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          18x 18x 18x 18x 18x 18x 18x 18x     18x                                                                                             18x           18x   34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x                   21x     21x     21x       21x       21x     21x     21x 21x   21x   21x   21x 20x       20x 20x       19x       18x       17x       16x         15x       15x 14x         13x   12x       12x 11x       11x                                 11x       11x   1x         1x         1x         1x     1x         1x         1x         1x         1x               1x                             12x     12x       12x         12x       12x       12x       12x         12x       12x   12x       11x         10x         9x         8x           7x           7x 6x         5x   4x           4x 3x 3x 3x   3x 1x           3x                       3x 27x   9x 1x 8x 1x 7x 1x   6x     9x     3x 2x           1x     1x         1x         1x         1x     1x         1x         1x         1x         1x                         13x 13x                   26x   26x 25x   1x                     2x       2x 2x   2x 1x   1x                     11x   11x 1x 1x     11x 11x                             8x       8x 7x       6x       6x 5x 5x   5x       5x       5x     5x   5x                         5x           5x   1x     1x     1x        
/**
 * Book service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { ResourceService } from '../resource/resource.service';
import { ImageService } from '../image/image.service';
import { UserService, userTableName } from '../user/user.service';
import { DepartmentService } from '../department/department.service';
import { BookConditionService } from '../book-condition/book-condition.service';
import { SearchSortService } from '../search-sort/search-sort.service';
import { NBBook } from './book.interface';
import { NBUser } from '../user/user.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Options passed in creating a book.
 */
interface CreateBookOptions {
  userID: string;
  title: string;
  author: string;
  description: string;
  ISBN10?: string;
  ISBN13?: string;
  imageData: string;
  departmentID: number;
  courseNumber?: number;
  price: number;
  conditionID: number;
}
 
/**
 * Options passed in editing a book.
 */
interface EditBookOptions {
  title?: string;
  author?: string;
  description?: string;
  ISBN10?: string | null;
  ISBN13?: string | null;
  imageData?: string;
  departmentID?: number;
  courseNumber?: number | null;
  price?: number;
  conditionID?: number;
}
 
/**
 * Options passed in searching books.
 */
interface SearchBooksOptions {
  query?: string;
  departmentID?: number;
  courseNumber?: number;
}
 
/**
 * Book table name.
 */
export const bookTableName = 'NB_BOOK';
 
/**
 * Book table service.
 */
@Injectable()
export class BookService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => ImageService))
    private readonly imageService: ImageService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @Inject(forwardRef(() => DepartmentService))
    private readonly departmentService: DepartmentService,
    @Inject(forwardRef(() => BookConditionService))
    private readonly bookConditionService: BookConditionService,
    @Inject(forwardRef(() => SearchSortService))
    private readonly searchSortService: SearchSortService,
  ) {}
 
  /**
   * Create a new book.
   *
   * @param options The new book options.
   * @returns The new book record.
   */
  public async createBook(options: CreateBookOptions): Promise<NBBook> {
    const userMaxBooks = await this.resourceService.getResource<number>(
      'USER_MAX_BOOKS',
    );
    const bookTitleMaxLength = await this.resourceService.getResource<number>(
      'BOOK_TITLE_MAX_LENGTH',
    );
    const bookAuthorMaxLength = await this.resourceService.getResource<number>(
      'BOOK_AUTHOR_MAX_LENGTH',
    );
    const bookDescriptionMaxLength =
      await this.resourceService.getResource<number>(
        'BOOK_DESCRIPTION_MAX_LENGTH',
      );
 
    const ISBN10 = !options.ISBN10
      ? undefined
      : options.ISBN10.replace(/[- ]/g, '');
    const ISBN13 = !options.ISBN13
      ? undefined
      : options.ISBN13.replace(/[- ]/g, '');
    const ISBN10Num = !options.ISBN10 ? undefined : parseInt(ISBN10);
    const ISBN13Num = !options.ISBN13 ? undefined : parseInt(ISBN13);
 
    const price = Math.round(options.price * 100) / 100;
 
    const userExists = await this.userService.userExists(options.userID);
 
    if (userExists) {
      const currentBooks = await this.userService.getCurrentBooks(
        options.userID,
      );
 
      Eif (currentBooks.length < userMaxBooks) {
        if (
          options.title.length >= 1 &&
          options.title.length <= bookTitleMaxLength
        ) {
          if (
            options.author.length >= 1 &&
            options.author.length <= bookTitleMaxLength
          ) {
            if (
              options.description.length >= 1 &&
              options.description.length <= bookDescriptionMaxLength
            ) {
              if (
                ISBN10 === undefined ||
                (ISBN10.length === 10 && !isNaN(ISBN10Num))
              ) {
                if (
                  ISBN13 === undefined ||
                  (ISBN13.length === 13 && !isNaN(ISBN13Num))
                ) {
                  const departmentExists =
                    await this.departmentService.departmentExists(
                      options.departmentID,
                    );
 
                  if (departmentExists) {
                    if (
                      options.courseNumber === undefined ||
                      (options.courseNumber >= 101 &&
                        options.courseNumber <= 499)
                    ) {
                      if (price >= 0 && price <= 999.99) {
                        const bookConditionExists =
                          await this.bookConditionService.bookConditionExists(
                            options.conditionID,
                          );
 
                        if (bookConditionExists) {
                          const bookImage = await this.imageService.createImage(
                            options.imageData,
                          );
 
                          const book = await this.dbService.create<NBBook>(
                            bookTableName,
                            {
                              userID: options.userID,
                              title: options.title,
                              author: options.author,
                              description: options.description,
                              ISBN10,
                              ISBN13,
                              imageID: bookImage.id,
                              departmentID: options.departmentID,
                              courseNumber: options.courseNumber,
                              price,
                              conditionID: options.conditionID,
                            },
                          );
 
                          await this.userService.incrementBooksListed(
                            options.userID,
                          );
 
                          return book;
                        } else {
                          throw new ServiceException(
                            'Book condition does not exist',
                          );
                        }
                      } else {
                        throw new ServiceException(
                          'Price must be between $0 and $999.99',
                        );
                      }
                    } else {
                      throw new ServiceException(
                        'Course number must be between 101 and 499',
                      );
                    }
                  } else {
                    throw new ServiceException('Department does not exist');
                  }
                } else {
                  throw new ServiceException(
                    'ISBN 13 must contain 13 numeric characters',
                  );
                }
              } else {
                throw new ServiceException(
                  'ISBN 10 must contain 10 numeric characters',
                );
              }
            } else {
              throw new ServiceException(
                `Book description must be between 1 and ${bookDescriptionMaxLength} characters`,
              );
            }
          } else {
            throw new ServiceException(
              `Book author must be between 1 and ${bookAuthorMaxLength} characters`,
            );
          }
        } else {
          throw new ServiceException(
            `Book title must be between 1 and ${bookTitleMaxLength} characters`,
          );
        }
      } else {
        throw new ServiceException('Maximum number of books exceeded');
      }
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Edit an existing book.
   *
   * @param bookID The book's ID.
   * @param options The updated book options.
   * @returns The updated book record.
   */
  public async editBook(
    bookID: string,
    options: EditBookOptions,
  ): Promise<NBBook> {
    const bookTitleMaxLength = await this.resourceService.getResource<number>(
      'BOOK_TITLE_MAX_LENGTH',
    );
    const bookAuthorMaxLength = await this.resourceService.getResource<number>(
      'BOOK_AUTHOR_MAX_LENGTH',
    );
    const bookDescriptionMaxLength =
      await this.resourceService.getResource<number>(
        'BOOK_DESCRIPTION_MAX_LENGTH',
      );
 
    const ISBN10 =
      options.ISBN10 === undefined || options.ISBN10 === null
        ? options.ISBN10
        : options.ISBN10.replace(/[- ]/g, '');
    const ISBN13 =
      options.ISBN13 === undefined || options.ISBN13 === null
        ? options.ISBN13
        : options.ISBN13.replace(/[- ]/g, '');
    const ISBN10Num =
      options.ISBN10 === undefined || options.ISBN10 === null
        ? undefined
        : parseInt(ISBN10);
    const ISBN13Num =
      options.ISBN13 === undefined || options.ISBN13 === null
        ? undefined
        : parseInt(ISBN13);
 
    const price =
      options.price === undefined
        ? undefined
        : Math.round(options.price * 100) / 100;
 
    const book = await this.getBook(bookID);
 
    if (
      options.title === undefined ||
      (options.title.length >= 1 && options.title.length <= bookTitleMaxLength)
    ) {
      if (
        options.author === undefined ||
        (options.author.length >= 1 &&
          options.author.length <= bookTitleMaxLength)
      ) {
        if (
          options.description === undefined ||
          (options.description.length >= 1 &&
            options.description.length <= bookDescriptionMaxLength)
        ) {
          if (
            ISBN10 === undefined ||
            ISBN10 === null ||
            (ISBN10.length === 10 && !isNaN(ISBN10Num))
          ) {
            if (
              ISBN13 === undefined ||
              ISBN13 === null ||
              (ISBN13.length === 13 && !isNaN(ISBN13Num))
            ) {
              const departmentExists =
                options.departmentID === undefined
                  ? true
                  : await this.departmentService.departmentExists(
                      options.departmentID,
                    );
 
              if (departmentExists) {
                if (
                  options.courseNumber === undefined ||
                  options.courseNumber === null ||
                  (options.courseNumber >= 101 && options.courseNumber <= 499)
                ) {
                  if (price === undefined || (price >= 0 && price <= 999.99)) {
                    const bookConditionExists =
                      options.conditionID === undefined
                        ? true
                        : await this.bookConditionService.bookConditionExists(
                            options.conditionID,
                          );
 
                    if (bookConditionExists) {
                      const sql = `UPDATE "${bookTableName}" SET "editTime" = NOW() WHERE id = ?;`;
                      const params = [book.id];
                      await this.dbService.execute(sql, params);
 
                      if (options.imageData !== undefined) {
                        await this.imageService.setImageData(
                          book.imageID,
                          options.imageData,
                        );
                      }
 
                      const editOptions = [
                        'title',
                        'author',
                        'description',
                        'ISBN10',
                        'ISBN13',
                        'departmentID',
                        'courseNumber',
                        'price',
                        'conditionID',
                      ];
 
                      const updateFields = editOptions
                        .filter((option) => options[option] !== undefined)
                        .reduce((acc, current) => {
                          if (current === 'ISBN10') {
                            acc['ISBN10'] = ISBN10;
                          } else if (current === 'ISBN13') {
                            acc['ISBN13'] = ISBN13;
                          } else if (current === 'price') {
                            acc['price'] = price;
                          } else {
                            acc[current] = options[current];
                          }
 
                          return acc;
                        }, {});
 
                      if (Object.keys(updateFields).length > 0) {
                        return this.dbService.updateByID<NBBook>(
                          bookTableName,
                          bookID,
                          updateFields,
                        );
                      } else {
                        return this.getBook(bookID);
                      }
                    } else {
                      throw new ServiceException(
                        'Book condition does not exist',
                      );
                    }
                  } else {
                    throw new ServiceException(
                      'Price must be between $0 and $999.99',
                    );
                  }
                } else {
                  throw new ServiceException(
                    'Course number must be between 101 and 499',
                  );
                }
              } else {
                throw new ServiceException('Department does not exist');
              }
            } else {
              throw new ServiceException(
                'ISBN 13 must contain 13 numeric characters',
              );
            }
          } else {
            throw new ServiceException(
              'ISBN 10 must contain 10 numeric characters',
            );
          }
        } else {
          throw new ServiceException(
            `Book description must be between 1 and ${bookDescriptionMaxLength} characters`,
          );
        }
      } else {
        throw new ServiceException(
          `Book author must be between 1 and ${bookAuthorMaxLength} characters`,
        );
      }
    } else {
      throw new ServiceException(
        `Book title must be between 1 and ${bookTitleMaxLength} characters`,
      );
    }
  }
 
  /**
   * Determine whether or not a book exists.
   *
   * @param bookID The book's ID.
   * @returns Whether or not the book exists.
   */
  public async bookExists(bookID: string): Promise<boolean> {
    const book = await this.dbService.getByID<NBBook>(bookTableName, bookID);
    return !!book;
  }
 
  /**
   * Get a book.
   *
   * @param bookID The book's ID.
   * @returns The book record.
   */
  public async getBook(bookID: string): Promise<NBBook> {
    const book = await this.dbService.getByID<NBBook>(bookTableName, bookID);
 
    if (book) {
      return book;
    } else {
      throw new ServiceException('Book does not exist');
    }
  }
 
  /**
   * Get the user who listed a book.
   *
   * @param bookID The book's ID.
   * @returns The user who listed the book.
   */
  public async getBookUser(bookID: string): Promise<NBUser> {
    const sql = `
      SELECT * FROM "${userTableName}" WHERE id = (
        SELECT "userID" FROM "${bookTableName}" WHERE id = ?
      );`;
    const params = [bookID];
    const res = await this.dbService.execute<NBUser>(sql, params);
 
    if (res.length === 1) {
      return res[0];
    } else {
      throw new ServiceException('Book does not exist');
    }
  }
 
  /**
   * Delete a book.
   *
   * @param bookID The book's ID.
   * @param sold Whether or not the book was sold.
   */
  public async deleteBook(bookID: string, sold: boolean): Promise<void> {
    const book = await this.getBook(bookID);
 
    if (sold) {
      await this.userService.incrementBooksSold(book.userID);
      await this.userService.addMoneyMade(book.userID, book.price);
    }
 
    await this.imageService.deleteImage(book.imageID);
    await this.dbService.deleteByID(bookTableName, book.id);
  }
 
  /**
   * Search for books.
   *
   * @param options The search options.
   * @param sortID The ID of the search sort option.
   * @returns All books matching the search parameters.
   */
  public async searchBooks(
    options: SearchBooksOptions,
    sortID: number,
  ): Promise<NBBook[]> {
    const departmentExists =
      options.departmentID === undefined
        ? true
        : await this.departmentService.departmentExists(options.departmentID);
 
    if (departmentExists) {
      if (
        options.courseNumber === undefined ||
        (options.courseNumber >= 101 && options.courseNumber <= 499)
      ) {
        const sortOptionExists = await this.searchSortService.sortOptionExists(
          sortID,
        );
 
        if (sortOptionExists) {
          const query = options.query ?? '';
          const searchLike = `%${query}%`;
          const isbnSearch =
            options.query === undefined
              ? ''
              : options.query.replace(/[- ]/g, '');
          const departmentQuery =
            options.departmentID === undefined
              ? ''
              : ' "departmentID" = ? AND ';
          const courseNumberQuery =
            options.courseNumber === undefined
              ? ''
              : ' "courseNumber" = ? AND ';
          const sortQuery = await this.searchSortService.getSortOption(sortID);
 
          const sql = `
            SELECT *
            FROM "${bookTableName}"
            WHERE
              ${departmentQuery} ${courseNumberQuery} (
                   LOWER("title")       LIKE LOWER(?)
                OR LOWER("author")      LIKE LOWER(?)
                OR LOWER("description") LIKE LOWER(?)
                OR "ISBN10"             LIKE ?
                OR "ISBN13"             LIKE ?
              )
            ORDER BY ${sortQuery.query};
          `;
          const params = [].concat(
            options.departmentID ?? [],
            options.courseNumber ?? [],
            Array(3).fill(searchLike),
            Array(2).fill(isbnSearch),
          );
          return this.dbService.execute<NBBook>(sql, params);
        } else {
          throw new ServiceException('Search sort option does not exist');
        }
      } else {
        throw new ServiceException('Course number must be between 101 and 499');
      }
    } else {
      throw new ServiceException('Department does not exist');
    }
  }
}