- $book = $this->entityRepo->getBySlug('book', $bookSlug);
- $bookChildren = $this->entityRepo->getBookChildren($book);
- return view('books/sort-box', ['book' => $book, 'bookChildren' => $bookChildren]);
- }
-
- /**
- * Saves an array of sort mapping to pages and chapters.
- * @param string $bookSlug
- * @param Request $request
- * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
- */
- public function saveSort($bookSlug, Request $request)
- {
- $book = $this->entityRepo->getBySlug('book', $bookSlug);
- $this->checkOwnablePermission('book-update', $book);
-
- // Return if no map sent
- if (!$request->has('sort-tree')) {
- return redirect($book->getUrl());
- }
-
- // Sort pages and chapters
- $sortedBooks = [];
- $updatedModels = collect();
- $sortMap = json_decode($request->get('sort-tree'));
- $defaultBookId = $book->id;
-
- // Loop through contents of provided map and update entities accordingly
- foreach ($sortMap as $bookChild) {
- $priority = $bookChild->sort;
- $id = intval($bookChild->id);
- $isPage = $bookChild->type == 'page';
- $bookId = $this->entityRepo->exists('book', $bookChild->book) ? intval($bookChild->book) : $defaultBookId;
- $chapterId = ($isPage && $bookChild->parentChapter === false) ? 0 : intval($bookChild->parentChapter);
- $model = $this->entityRepo->getById($isPage?'page':'chapter', $id);
-
- // Update models only if there's a change in parent chain or ordering.
- if ($model->priority !== $priority || $model->book_id !== $bookId || ($isPage && $model->chapter_id !== $chapterId)) {
- $this->entityRepo->changeBook($isPage?'page':'chapter', $bookId, $model);
- $model->priority = $priority;
- if ($isPage) $model->chapter_id = $chapterId;
- $model->save();
- $updatedModels->push($model);
- }
-
- // Store involved books to be sorted later
- if (!in_array($bookId, $sortedBooks)) {
- $sortedBooks[] = $bookId;
- }
- }
-
- // Add activity for books
- foreach ($sortedBooks as $bookId) {
- /** @var Book $updatedBook */
- $updatedBook = $this->entityRepo->getById('book', $bookId);
- $this->entityRepo->buildJointPermissionsForBook($updatedBook);
- Activity::add($updatedBook, 'book_sort', $updatedBook->id);
- }