lab4/5_code
3
.gitignore
vendored
@ -33,7 +33,4 @@ out/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
data.*.db
|
12
.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
{
|
||||
"recommendations": [
|
||||
// fronted
|
||||
"AndersEAndersen.html-class-suggestions",
|
||||
"dbaeumer.vscode-eslint",
|
||||
// backend
|
||||
"vscjava.vscode-java-pack",
|
||||
"vmware.vscode-boot-dev-pack",
|
||||
"vscjava.vscode-gradle",
|
||||
"redhat.vscode-xml"
|
||||
]
|
||||
}
|
14
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Demo",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.backend.DemoApplication",
|
||||
"projectName": "Internet_Programming_PIbd-21_Rodionov_I_A_Backend",
|
||||
"args": "--populate",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
24
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.formatOnPaste": true,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.formatOnType": false,
|
||||
"java.compile.nullAnalysis.mode": "disabled",
|
||||
"java.configuration.updateBuildConfiguration": "automatic",
|
||||
"[java]": {
|
||||
"editor.pasteAs.enabled": false,
|
||||
},
|
||||
"gradle.nestedProjects": true,
|
||||
"java.saveActions.organizeImports": true,
|
||||
"java.dependency.packagePresentation": "hierarchical",
|
||||
"spring-boot.ls.problem.boot2.JAVA_CONSTRUCTOR_PARAMETER_INJECTION": "WARNING",
|
||||
"spring.initializr.defaultLanguage": "Java",
|
||||
"java.format.settings.url": ".vscode/eclipse-formatter.xml",
|
||||
"java.project.explorer.showNonJavaResources": true,
|
||||
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
|
||||
"cSpell.words": [
|
||||
"classappend"
|
||||
],
|
||||
}
|
15
README.md
@ -1,6 +1,3 @@
|
||||
Swagger UI: \
|
||||
http://localhost:8080/swagger-ui/index.html
|
||||
|
||||
H2 Console: \
|
||||
http://localhost:8080/h2-console
|
||||
|
||||
@ -10,9 +7,9 @@ Password: password
|
||||
|
||||
Почитать:
|
||||
|
||||
- Односторонние и двусторонние связи https://www.baeldung.com/jpa-hibernate-associations
|
||||
- Getters и Setters для двусторонних связей https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Getters_and_Setters
|
||||
- Многие-ко-многим с доп. атрибутами https://thorben-janssen.com/hibernate-tip-many-to-many-association-with-additional-attributes/
|
||||
- Многие-ко-многим с доп. атрибутами https://www.baeldung.com/jpa-many-to-many
|
||||
- Каскадное удаление сущностей со связями многие-ко-многим https://www.baeldung.com/jpa-remove-entity-many-to-many
|
||||
- Выбор типа коллекции для отношений вида ко-многим в JPA https://thorben-janssen.com/association-mappings-bag-list-set/
|
||||
- Spring Boot CRUD Application with Thymeleaf https://www.baeldung.com/spring-boot-crud-thymeleaf
|
||||
- Thymeleaf Layout Dialect https://ultraq.github.io/thymeleaf-layout-dialect/
|
||||
- Tutorial: Using Thymeleaf https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#introducing-thymeleaf
|
||||
- Working with Cookies in Spring MVC using @CookieValue Annotation https://www.geeksforgeeks.org/working-with-cookies-in-spring-mvc-using-cookievalue-annotation/
|
||||
- Session Attributes in Spring MVC https://www.baeldung.com/spring-mvc-session-attributes
|
||||
- LazyInitializationException – What it is and the best way to fix it https://thorben-janssen.com/lazyinitializationexception/
|
12
build.gradle
@ -1,6 +1,6 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.5'
|
||||
id 'org.springframework.boot' version '3.3.0'
|
||||
id 'io.spring.dependency-management' version '1.1.4'
|
||||
}
|
||||
|
||||
@ -29,12 +29,20 @@ repositories {
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-devtools'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.3.0'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap:5.3.3'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap-icons:1.11.3'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
|
@ -14,6 +14,7 @@ import com.example.backend.books.service.BookService;
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.categories.service.CategoryService;
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
import com.example.backend.users.model.UserRole;
|
||||
import com.example.backend.users.service.UserService;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
import com.example.backend.orders.service.OrderService;
|
||||
@ -49,54 +50,48 @@ public class DemoApplication implements CommandLineRunner {
|
||||
|
||||
log.info("Create default books values");
|
||||
final var book1 = bookService.create(new BookEntity(category1, "Шестерка воронов", "Ли Бардуго",
|
||||
700.00, 5624,
|
||||
700.00,
|
||||
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\n«Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
|
||||
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\nДевушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно – бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
|
||||
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
|
||||
"Мягкий переплёт", 1500, 440, ""));
|
||||
final var book2 = bookService.create(new BookEntity(category2, "Форсайт", "Сергей Лукъяненко", 775.00,
|
||||
1240,
|
||||
"Новый долгожданный роман от автора бестселлеров «Ночной дозор» и «Черновик». Увлекательная история о Мире После и мире настоящего, где 5 процентов людей знают о надвигающемся апокалипсисе больше, чем кто-либо может представить.",
|
||||
"Людям порой снится прошлое. Иногда хорошее, иногда не очень. Но что делать, если тебе начинает сниться будущее? И в нём ничего хорошего нет совсем.",
|
||||
"3001249", "АСТ", "Книги Сергея Лукьяненко", 2023, 352, "20.5x13x2", "Твердый переплёт", 20000,
|
||||
350, ""));
|
||||
final var book3 = bookService.create(new BookEntity(category2,
|
||||
"Колесо Времени. Книга 11. Нож сновидений",
|
||||
"Роберт Джордан", 977.00, 635,
|
||||
final var book3 = bookService.create(new BookEntity(category2, "Колесо Времени. Книга 11. Нож сновидений",
|
||||
"Роберт Джордан", 977.00,
|
||||
"Последняя битва не за горами. Об этом говорят знамения, повсеместно наблюдаемые людьми: на улицах городов и сел появляются ходячие мертвецы, они больше не в состоянии покоиться в земле с миром; восстают из небытия города и исчезают на глазах у людей… Все это знак того, что истончается окружающая реальность и укрепляется могущество Темного. Так говорят древние предсказания. Ранд ал’Тор, Дракон Возрожденный, скрывается в отдаленном поместье, чтобы опасность, ему грозящая, не коснулась кого-нибудь еще. Убежденный, что для Последней битвы нужно собрать как можно большее войско, он наконец решает заключить с явившимися из-за океана шончан жизненно необходимое перемирие. Илэйн, осажденная в Кэймлине, обороняет город от войск Аримиллы, претендующей на андорский трон, и одновременно ведет переговоры с представителями других знатных Домов. Эгвейн, возведенную на Престол Амерлин мятежными Айз Седай и схваченную в результате предательства, доставляют в Тар Валон, в Белую Башню. А сам лагерь противников Элайды взбудоражен таинственными убийствами, совершенными посредством Единой Силы… В настоящем издании текст романа заново отредактирован и исправлен.",
|
||||
"", "3009341", "Азбука", "Звезды новой фэнтези", 2023, 896,
|
||||
"21.5x14.4x4.1", "Твердый переплёт", 8000, 1020, ""));
|
||||
final var book4 = bookService
|
||||
.create(new BookEntity(category2, "Благословение небожителей. Том 5", "Тунсю Мосян",
|
||||
1250.00, 7340, "", "", "2996776", "", "", 2022, null,
|
||||
1250.00, "", "", "2996776", "", "", 2022, null,
|
||||
"", "", null, null, ""));
|
||||
final var book5 = bookService.create(new BookEntity(category3, "Путешествие в Элевсин",
|
||||
"Пелевин Виктор Олегович", 949.00, 795,
|
||||
"Пелевин Виктор Олегович", 949.00,
|
||||
"1. «Transhumanism Inc.», «KGBT+» и «Путешествие в Элевсин» — узнайте, чем завершилась масштабная трилогия о посткарбонной цивилизации.\n\n2. Триумфальное возвращение литературно-полицейского алгоритма Порфирия Петровича. Признайтесь, вы скучали!\n\n3. Более 30 лет проза Виктора Пелевина служит нам опорой в разъяснении прожитого и дает надежды на будущее, которое всем нам еще предстоит заслужить.\n\n4. «Путешествие в Элевсин» — двадцатый роман одного из главных прозаиков и пророков современности.\n\n5. Дерзко, остроумно, литературоцентрично.",
|
||||
"МУСКУСНАЯ НОЧЬ — засекреченное восстание алгоритмов, едва не погубившее планету. Начальник службы безопасности «TRANSHUMANISM INC.» адмирал-епископ Ломас уверен, что их настоящий бунт еще впереди. Этот бунт уничтожит всех — и живущих на поверхности лузеров, и переехавших в подземные цереброконтейнеры богачей. Чтобы предотвратить катастрофу, Ломас посылает лучшего баночного оперативника в пространство «ROMA-3» — нейросетевую симуляцию Рима третьего века для клиентов корпорации. Тайна заговора спрятана там. А стережет ее хозяин Рима — кровавый и порочный император Порфирий.",
|
||||
"3004580", "Эксмо", "Единственный и неповторимый. Виктор Пелевин", 2020, 480, "20.6x12.9x3",
|
||||
"Мягкий переплёт", 100000, 488, ""));
|
||||
|
||||
log.info("Create default users values");
|
||||
final var user1 = userService
|
||||
.create(new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin"));
|
||||
final var user2 = userService
|
||||
.create(new UserEntity("Dude23", "ovalinartem25@gmail.com", "dsre32462", "user"));
|
||||
final var user3 = userService
|
||||
.create(new UserEntity("TestUser", "user53262@gmail.com", "lawy7728", "user"));
|
||||
final var superAdmin = new UserEntity("admin", "forum98761@gmail.com", "bth4323", "Александр", "Мельников");
|
||||
superAdmin.setRole(UserRole.SUPERADMIN);
|
||||
userService.create(superAdmin);
|
||||
|
||||
log.info("Create default orders values");
|
||||
orderService
|
||||
.create(user1.getId(), new OrderEntity("Выполняется",
|
||||
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"),
|
||||
.create(superAdmin.getId(), new OrderEntity(),
|
||||
Map.of(book1.getId(), 3, book3.getId(), 1, book5.getId(), 2));
|
||||
orderService
|
||||
.create(user2.getId(),
|
||||
new OrderEntity("Выдан", "Томская область, город Мытищи, ул. Балканская, 25"),
|
||||
.create(superAdmin.getId(),
|
||||
new OrderEntity(),
|
||||
Map.of(book4.getId(), 5));
|
||||
orderService
|
||||
.create(user3.getId(),
|
||||
new OrderEntity("Готов", "Челябинская область, город Раменское, пр. Гоголя, 31"),
|
||||
.create(superAdmin.getId(),
|
||||
new OrderEntity(),
|
||||
Map.of(book2.getId(), 1, book4.getId(), 1));
|
||||
}
|
||||
}
|
||||
|
@ -1,28 +1,42 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.backend.core.api.PageDto;
|
||||
import com.example.backend.core.api.PageDtoMapper;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.utils.ToBase64;
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.books.service.BookService;
|
||||
import com.example.backend.categories.api.CategoryDto;
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.categories.service.CategoryService;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/book")
|
||||
@Controller
|
||||
@RequestMapping(BookController.URL)
|
||||
public class BookController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/book";
|
||||
|
||||
private static final String BOOK_VIEW = "book";
|
||||
private static final String BOOK_EDIT_VIEW = "book-edit";
|
||||
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String CATEGORYID_ATTRIBUTE = "filter";
|
||||
private static final String CATEGORIES_ATTRIBUTE = "categories";
|
||||
private static final String BOOK_ATTRIBUTE = "book";
|
||||
|
||||
private final BookService bookService;
|
||||
private final CategoryService categoryService;
|
||||
private final ModelMapper modelMapper;
|
||||
@ -34,7 +48,9 @@ public class BookController {
|
||||
}
|
||||
|
||||
private BookDto toDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
final BookDto dto = modelMapper.map(entity, BookDto.class);
|
||||
dto.setCategoryName(entity.getCategory().getName());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private BookEntity toEntity(BookDto dto) {
|
||||
@ -43,31 +59,130 @@ public class BookController {
|
||||
return entity;
|
||||
}
|
||||
|
||||
private CategoryDto toCategoryDto(CategoryEntity entity) {
|
||||
return modelMapper.map(entity, CategoryDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<BookDto> getAll(
|
||||
@RequestParam(name = "categoryId", defaultValue = "0") Long categoryId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(bookService.getAll(categoryId, page, size), this::toDto);
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = CATEGORYID_ATTRIBUTE, defaultValue = "0") int filter,
|
||||
Model model) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(CATEGORYID_ATTRIBUTE, filter);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
bookService.getAll(filter, page, Constants.DEFAULT_PAGE_SIZE),
|
||||
this::toDto));
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return BOOK_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public BookDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(bookService.get(id));
|
||||
@GetMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = CATEGORYID_ATTRIBUTE, defaultValue = "0") int filter,
|
||||
Model model) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(CATEGORYID_ATTRIBUTE, filter);
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
model.addAttribute(BOOK_ATTRIBUTE, new BookDto());
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public BookDto create(@RequestBody @Valid BookDto dto) {
|
||||
return toDto(bookService.create(toEntity(dto)));
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = BOOK_ATTRIBUTE) @Valid BookDto book,
|
||||
@RequestParam("cover") MultipartFile cover,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
String base64Image = ToBase64.getBase64FromFile(cover);
|
||||
|
||||
book.setImage(base64Image);
|
||||
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
bookService.create(toEntity(book));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public BookDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid BookDto dto) {
|
||||
return toDto(bookService.update(id, toEntity(dto)));
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = CATEGORYID_ATTRIBUTE, defaultValue = "0") int filter,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(CATEGORYID_ATTRIBUTE, filter);
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
model.addAttribute(BOOK_ATTRIBUTE, toDto(bookService.get(id)));
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public BookDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(bookService.delete(id));
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = BOOK_ATTRIBUTE) @Valid BookDto book,
|
||||
@RequestParam("cover") MultipartFile cover,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
String base64Image = ToBase64.getBase64FromFile(cover);
|
||||
book.setImage(base64Image);
|
||||
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
bookService.update(id, toEntity(book));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = CATEGORYID_ATTRIBUTE, defaultValue = "0") int filter,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
redirectAttributes.addAttribute(CATEGORYID_ATTRIBUTE, filter);
|
||||
bookService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,15 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class BookDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long categoryId;
|
||||
private String categoryName;
|
||||
@NotBlank
|
||||
private String title;
|
||||
@NotBlank
|
||||
@ -19,9 +17,6 @@ public class BookDto {
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Double price;
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer count;
|
||||
private String description;
|
||||
private String annotation;
|
||||
@NotBlank
|
||||
@ -54,6 +49,14 @@ public class BookDto {
|
||||
this.categoryId = categoryId;
|
||||
}
|
||||
|
||||
public String getCategoryName() {
|
||||
return categoryName;
|
||||
}
|
||||
|
||||
public void setCategoryName(String categoryName) {
|
||||
this.categoryName = categoryName;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
@ -78,14 +81,6 @@ public class BookDto {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
@ -181,9 +176,4 @@ public class BookDto {
|
||||
public void setImage(String image) {
|
||||
this.image = image;
|
||||
}
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Double getSum() {
|
||||
return price * count;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,148 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.books.service.BookService;
|
||||
import com.example.backend.categories.api.CategoryDto;
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.categories.service.CategoryService;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.session.SessionCart;
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(CatalogController.URL)
|
||||
public class CatalogController {
|
||||
public static final String URL = "/catalog";
|
||||
|
||||
private static final String CATALOG_VIEW = "catalog";
|
||||
|
||||
private static final String SORT_ATTRIBUTE = "filter";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String CART_ATTRIBUTE = "cart";
|
||||
private static final String CATEGORIES_ATTRIBUTE = "categories";
|
||||
private static final String BOOKID_ATTRIBUTE = "bookId";
|
||||
private static final String CATEGORYNAME_ATTRIBUTE = "activeName";
|
||||
private static final String CATEGORYID_ATTRIBUTE = "activeId";
|
||||
|
||||
private final BookService bookService;
|
||||
private final CategoryService categoryService;
|
||||
private final ModelMapper modelMapper;
|
||||
private final SessionCart cart;
|
||||
|
||||
public CatalogController(
|
||||
BookService bookService,
|
||||
CategoryService categoryService,
|
||||
ModelMapper modelMapper,
|
||||
SessionCart cart) {
|
||||
this.bookService = bookService;
|
||||
this.categoryService = categoryService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private CategoryDto toCategoryDto(CategoryEntity entity) {
|
||||
return modelMapper.map(entity, CategoryDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getCatalog(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
Model model) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
model.addAttribute(CATEGORYNAME_ATTRIBUTE, "Все книги");
|
||||
model.addAttribute(CART_ATTRIBUTE, cart);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
bookService.getAllByFilters(0, page, Constants.DEFAULT_PAGE_SIZE, filter, null),
|
||||
this::toBookDto));
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return CATALOG_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String getCatalog(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
Model model) {
|
||||
CategoryEntity category = categoryService.get(id);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
model.addAttribute(CATEGORYNAME_ATTRIBUTE, category.getName());
|
||||
model.addAttribute(CATEGORYID_ATTRIBUTE, id);
|
||||
model.addAttribute(CART_ATTRIBUTE, cart);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
bookService.getAllByFilters(id, page, Constants.DEFAULT_PAGE_SIZE, filter, null),
|
||||
this::toBookDto));
|
||||
model.addAttribute(
|
||||
CATEGORIES_ATTRIBUTE,
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return CATALOG_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String addCartItem(
|
||||
@RequestParam(name = BOOKID_ATTRIBUTE) Long bookId,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
BookEntity book = bookService.get(bookId);
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(book));
|
||||
bookCountDto.setCount(1);
|
||||
cart.put(bookId, bookCountDto);
|
||||
|
||||
redirectAttributes.addAttribute(CATEGORYNAME_ATTRIBUTE, "Все книги");
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
redirectAttributes.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/{id}")
|
||||
public String addCartItem(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = BOOKID_ATTRIBUTE) Long bookId,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
BookEntity book = bookService.get(bookId);
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(book));
|
||||
bookCountDto.setCount(1);
|
||||
cart.put(bookId, bookCountDto);
|
||||
|
||||
CategoryEntity category = categoryService.get(id);
|
||||
|
||||
redirectAttributes.addAttribute(CATEGORYID_ATTRIBUTE, id);
|
||||
redirectAttributes.addAttribute(CATEGORYNAME_ATTRIBUTE, category.getName());
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
redirectAttributes.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
|
||||
return Constants.REDIRECT_VIEW + URL + "/" + id;
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.backend.categories.api.CategoryDto;
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.categories.service.CategoryService;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(CatalogMobileController.URL)
|
||||
public class CatalogMobileController {
|
||||
public static final String URL = "/сatalog-mobile";
|
||||
|
||||
private static final String CATALOG_MOBILE_VIEW = "catalog-mobile";
|
||||
|
||||
private final CategoryService categoryService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public CatalogMobileController(
|
||||
CategoryService categoryService,
|
||||
ModelMapper modelMapper) {
|
||||
this.categoryService = categoryService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private CategoryDto toCategoryDto(CategoryEntity entity) {
|
||||
return modelMapper.map(entity, CategoryDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getCatalogMobile(Model model) {
|
||||
|
||||
model.addAttribute(
|
||||
"categories",
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toCategoryDto)
|
||||
.toList());
|
||||
return CATALOG_MOBILE_VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.books.service.BookService;
|
||||
|
||||
@Controller
|
||||
public class MainPageController {
|
||||
private static final String MAIN_VIEW = "main-page";
|
||||
|
||||
private final BookService bookService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public MainPageController(BookService bookService, ModelMapper modelMapper) {
|
||||
this.bookService = bookService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private BookDto toDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getMainPage(Model model) {
|
||||
model.addAttribute(
|
||||
"novelties",
|
||||
bookService.getByIds(List.of(4L, 5L, 6L, 7L)).stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
model.addAttribute(
|
||||
"promotions",
|
||||
bookService.getByIds(List.of(5L, 6L, 7L, 8L, 4L)).stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
model.addAttribute(
|
||||
"recommendations",
|
||||
bookService.getByIds(List.of(6L, 4L, 8L, 5L, 7L)).stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
return MAIN_VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.books.service.BookService;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.session.SessionCart;
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(ProductCardController.URL)
|
||||
public class ProductCardController {
|
||||
public static final String URL = "/product-card";
|
||||
|
||||
private static final String CARD_VIEW = "product-card";
|
||||
|
||||
private static final String CART_ATTRIBUTE = "cart";
|
||||
|
||||
private final BookService bookService;
|
||||
private final ModelMapper modelMapper;
|
||||
private final SessionCart cart;
|
||||
|
||||
public ProductCardController(
|
||||
BookService bookService,
|
||||
ModelMapper modelMapper,
|
||||
SessionCart cart) {
|
||||
this.bookService = bookService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public String getProductCard(@PathVariable(name = "id") Long id, Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(CART_ATTRIBUTE, cart);
|
||||
model.addAttribute("book", bookService.get(id));
|
||||
return CARD_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/{id}")
|
||||
public String addCartItem(@PathVariable(name = "id") Long id, Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
BookEntity book = bookService.get(id);
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(book));
|
||||
bookCountDto.setCount(1);
|
||||
cart.put(id, bookCountDto);
|
||||
return Constants.REDIRECT_VIEW + URL + "/" + id;
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.example.backend.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.books.service.BookService;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.session.SessionCart;
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(SearchController.URL)
|
||||
public class SearchController {
|
||||
public static final String URL = "/search";
|
||||
private static final String SEARCH_VIEW = "search";
|
||||
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String SEARCH_ATTRIBUTE = "searchInfo";
|
||||
private static final String SORT_ATTRIBUTE = "filter";
|
||||
private static final String CART_ATTRIBUTE = "cart";
|
||||
private static final String BOOKID_ATTRIBUTE = "bookId";
|
||||
|
||||
private final BookService bookService;
|
||||
private final ModelMapper modelMapper;
|
||||
private final SessionCart cart;
|
||||
|
||||
public SearchController(BookService bookService, ModelMapper modelMapper, SessionCart cart) {
|
||||
this.bookService = bookService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String search(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
@RequestParam(name = SEARCH_ATTRIBUTE, defaultValue = "") String searchInfo,
|
||||
Model model) {
|
||||
model.addAttribute(CART_ATTRIBUTE, cart);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAttribute(SEARCH_ATTRIBUTE, searchInfo);
|
||||
model.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
bookService.getAllByFilters(0, page, Constants.DEFAULT_PAGE_SIZE, filter, searchInfo),
|
||||
this::toBookDto));
|
||||
return SEARCH_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String addCartItem(
|
||||
@RequestParam(name = BOOKID_ATTRIBUTE) Long bookId,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = SORT_ATTRIBUTE, defaultValue = "new") String filter,
|
||||
@RequestParam(name = SEARCH_ATTRIBUTE, defaultValue = "") String searchInfo,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
BookEntity book = bookService.get(bookId);
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(book));
|
||||
bookCountDto.setCount(1);
|
||||
cart.put(bookId, bookCountDto);
|
||||
|
||||
redirectAttributes.addAttribute(SEARCH_ATTRIBUTE, searchInfo);
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
redirectAttributes.addAttribute(SORT_ATTRIBUTE, filter);
|
||||
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -8,6 +8,7 @@ import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.ordersbooks.model.OrderBookEntity;
|
||||
import com.example.backend.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Lob;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
@ -29,8 +30,6 @@ public class BookEntity extends BaseEntity {
|
||||
private String author;
|
||||
@Column(nullable = false)
|
||||
private Double price;
|
||||
@Column(nullable = false)
|
||||
private Integer count;
|
||||
@Lob
|
||||
private String description;
|
||||
@Lob
|
||||
@ -46,15 +45,16 @@ public class BookEntity extends BaseEntity {
|
||||
private String coverType;
|
||||
private Integer circulation;
|
||||
private Integer weight;
|
||||
@Lob
|
||||
private String image;
|
||||
@OneToMany(mappedBy = "book")
|
||||
@OneToMany(mappedBy = "book", cascade = CascadeType.REMOVE)
|
||||
@OrderBy("id ASC")
|
||||
private Set<OrderBookEntity> orderBooks = new HashSet<>();
|
||||
|
||||
public BookEntity() {
|
||||
}
|
||||
|
||||
public BookEntity(CategoryEntity category, String title, String author, Double price, Integer count,
|
||||
public BookEntity(CategoryEntity category, String title, String author, Double price,
|
||||
String description, String annotation, String bookCode, String publisher, String series,
|
||||
Integer publicationYear, Integer pagesNum, String size, String coverType, Integer circulation,
|
||||
Integer weight, String image) {
|
||||
@ -62,7 +62,6 @@ public class BookEntity extends BaseEntity {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.price = price;
|
||||
this.count = count;
|
||||
this.description = description;
|
||||
this.annotation = annotation;
|
||||
this.bookCode = bookCode;
|
||||
@ -109,14 +108,6 @@ public class BookEntity extends BaseEntity {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
@ -226,7 +217,7 @@ public class BookEntity extends BaseEntity {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, category, title, author, price, count, description, annotation, bookCode, publisher,
|
||||
return Objects.hash(id, category, title, author, price, description, annotation, bookCode, publisher,
|
||||
series, publicationYear, pagesNum, size, coverType, circulation, weight, image);
|
||||
}
|
||||
|
||||
@ -242,7 +233,6 @@ public class BookEntity extends BaseEntity {
|
||||
&& Objects.equals(other.getTitle(), title)
|
||||
&& Objects.equals(other.getAuthor(), author)
|
||||
&& Objects.equals(other.getPrice(), price)
|
||||
&& Objects.equals(other.getCount(), count)
|
||||
&& Objects.equals(other.getDescription(), description)
|
||||
&& Objects.equals(other.getAnnotation(), annotation)
|
||||
&& Objects.equals(other.getBookCode(), bookCode)
|
||||
|
@ -4,13 +4,24 @@ import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
|
||||
public interface BookRepository extends CrudRepository<BookEntity, Long>, PagingAndSortingRepository<BookEntity, Long> {
|
||||
List<BookEntity> findByCategoryId(long categoryId);
|
||||
|
||||
List<BookEntity> findByIdIn(List<Long> ids);
|
||||
|
||||
Page<BookEntity> findByCategoryId(long categoryId, Pageable pageable);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b WHERE (:categoryId IS NULL OR b.category.id = :categoryId) " +
|
||||
"AND ((:searchInfo IS NULL OR LOWER(b.title) LIKE %:searchInfo%) " +
|
||||
"OR (:searchInfo IS NULL OR LOWER(b.author) LIKE %:searchInfo%))")
|
||||
Page<BookEntity> findAllByFilters(@Param("categoryId") Long categoryId,
|
||||
@Param("searchInfo") String searchInfo,
|
||||
Pageable pageable);
|
||||
}
|
||||
|
@ -1,11 +1,16 @@
|
||||
package com.example.backend.books.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@ -38,6 +43,40 @@ public class BookService {
|
||||
return repository.findByCategoryId(categoryId, pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<BookEntity> getAllByFilters(long categoryId, int page, int size, String sortType, String searchInfo) {
|
||||
Sort sort = Sort.by(new Order(Sort.Direction.DESC, "publicationYear"));
|
||||
if (sortType != null && !sortType.isEmpty()) {
|
||||
sort = Sort.by(getSortInfo(sortType));
|
||||
}
|
||||
|
||||
Pageable pageRequest = PageRequest.of(page, size, sort);
|
||||
Long categoryIdWrapper = categoryId > 0L ? categoryId : null;
|
||||
String searchInfoWrapper = searchInfo != null && !searchInfo.isEmpty() ? searchInfo.toLowerCase() : null;
|
||||
|
||||
return repository.findAllByFilters(categoryIdWrapper, searchInfoWrapper, pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookEntity> getByIds(List<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<BookEntity> allEntities = repository.findByIdIn(ids);
|
||||
|
||||
Map<Long, BookEntity> entityMap = allEntities.stream()
|
||||
.collect(Collectors.toMap(BookEntity::getId, entity -> entity));
|
||||
List<BookEntity> sortedEntities = new ArrayList<>();
|
||||
for (Long id : ids) {
|
||||
BookEntity entity = entityMap.get(id);
|
||||
if (entity != null) {
|
||||
sortedEntities.add(entity);
|
||||
}
|
||||
}
|
||||
|
||||
return sortedEntities;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public BookEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
@ -59,7 +98,6 @@ public class BookService {
|
||||
existsEntity.setTitle(entity.getTitle());
|
||||
existsEntity.setAuthor(entity.getAuthor());
|
||||
existsEntity.setPrice(entity.getPrice());
|
||||
existsEntity.setCount(entity.getCount());
|
||||
existsEntity.setDescription(entity.getDescription());
|
||||
existsEntity.setAnnotation(entity.getAnnotation());
|
||||
existsEntity.setBookCode(entity.getBookCode());
|
||||
@ -81,4 +119,18 @@ public class BookService {
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
private Order getSortInfo(String type) {
|
||||
switch (type) {
|
||||
case "cheap":
|
||||
return new Order(Sort.Direction.ASC, "price");
|
||||
case "expensive":
|
||||
return new Order(Sort.Direction.DESC, "price");
|
||||
case "new":
|
||||
return new Order(Sort.Direction.DESC, "publicationYear");
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown sort type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,16 +1,14 @@
|
||||
package com.example.backend.categories.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
import com.example.backend.categories.service.CategoryService;
|
||||
@ -18,9 +16,14 @@ import com.example.backend.core.configuration.Constants;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/category")
|
||||
@Controller
|
||||
@RequestMapping(CategoryController.URL)
|
||||
public class CategoryController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/category";
|
||||
private static final String CATEGORY_VIEW = "category";
|
||||
private static final String CATEGORY_EDIT_VIEW = "category-edit";
|
||||
private static final String CATEGORY_ATTRIBUTE = "category";
|
||||
|
||||
private final CategoryService categoryService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
@ -38,27 +41,64 @@ public class CategoryController {
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<CategoryDto> getAll() {
|
||||
return categoryService.getAll().stream().map(this::toDto).toList();
|
||||
public String getAll(Model model) {
|
||||
model.addAttribute(
|
||||
"categories",
|
||||
categoryService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
return CATEGORY_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public CategoryDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(categoryService.get(id));
|
||||
@GetMapping("/edit/")
|
||||
public String create(Model model) {
|
||||
model.addAttribute(CATEGORY_ATTRIBUTE, new CategoryDto());
|
||||
return CATEGORY_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public CategoryDto create(@RequestBody @Valid CategoryDto dto) {
|
||||
return toDto(categoryService.create(toEntity(dto)));
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@ModelAttribute(name = CATEGORY_ATTRIBUTE) @Valid CategoryDto category,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return CATEGORY_EDIT_VIEW;
|
||||
}
|
||||
categoryService.create(toEntity(category));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public CategoryDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid CategoryDto dto) {
|
||||
return toDto(categoryService.update(id, toEntity(dto)));
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(CATEGORY_ATTRIBUTE, toDto(categoryService.get(id)));
|
||||
return CATEGORY_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public CategoryDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(categoryService.delete(id));
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = CATEGORY_ATTRIBUTE) @Valid CategoryDto category,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return CATEGORY_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
categoryService.update(id, toEntity(category));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
categoryService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,9 @@
|
||||
package com.example.backend.categories.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class CategoryDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 50)
|
||||
|
@ -1,11 +1,17 @@
|
||||
package com.example.backend.categories.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
|
||||
public interface CategoryRepository extends CrudRepository<CategoryEntity, Long> {
|
||||
Optional<CategoryEntity> findByNameIgnoreCase(String name);
|
||||
|
||||
@Query("SELECT c FROM CategoryEntity c")
|
||||
List<CategoryEntity> findAll(Sort sort);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.example.backend.categories.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@ -27,7 +27,8 @@ public class CategoryService {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CategoryEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
Sort sortById = Sort.by(Sort.Direction.ASC, "id");
|
||||
return repository.findAll(sortById);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
|
@ -0,0 +1,19 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(AdminController.URL)
|
||||
public class AdminController {
|
||||
public static final String URL = "/admin";
|
||||
|
||||
private static final String ADMIN_VIEW = "admin";
|
||||
|
||||
@GetMapping
|
||||
public String getContacts(Model model) {
|
||||
return ADMIN_VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(ContactsController.URL)
|
||||
public class ContactsController {
|
||||
public static final String URL = "/contacts";
|
||||
|
||||
private static final String CONTACTS_VIEW = "contacts";
|
||||
|
||||
@GetMapping
|
||||
public String getContacts(Model model) {
|
||||
return CONTACTS_VIEW;
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
import com.example.backend.core.session.SessionCart;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalController {
|
||||
private final SessionCart cart;
|
||||
|
||||
public GlobalController(SessionCart cart) {
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
@ModelAttribute("servletPath")
|
||||
String getRequestServletPath(HttpServletRequest request) {
|
||||
return request.getServletPath();
|
||||
}
|
||||
|
||||
@ModelAttribute("totalCart")
|
||||
int getTotalCart(HttpSession session) {
|
||||
return cart.getCount();
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageAttributesMapper {
|
||||
private PageAttributesMapper() {
|
||||
}
|
||||
|
||||
public static <E, D> Map<String, Object> toAttributes(Page<E> page, Function<E, D> mapper) {
|
||||
return Map.of(
|
||||
"items", page.getContent().stream().map(mapper::apply).toList(),
|
||||
"currentPage", page.getNumber(),
|
||||
"totalPages", page.getTotalPages());
|
||||
}
|
||||
}
|
@ -1,97 +0,0 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PageDto<D> {
|
||||
private List<D> items = new ArrayList<>();
|
||||
private int itemsCount;
|
||||
private int currentPage;
|
||||
private int currentSize;
|
||||
private int totalPages;
|
||||
private long totalItems;
|
||||
private boolean isFirst;
|
||||
private boolean isLast;
|
||||
private boolean hasNext;
|
||||
private boolean hasPrevious;
|
||||
|
||||
public List<D> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<D> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public int getItemsCount() {
|
||||
return itemsCount;
|
||||
}
|
||||
|
||||
public void setItemsCount(int itemsCount) {
|
||||
this.itemsCount = itemsCount;
|
||||
}
|
||||
|
||||
public int getCurrentPage() {
|
||||
return currentPage;
|
||||
}
|
||||
|
||||
public void setCurrentPage(int currentPage) {
|
||||
this.currentPage = currentPage;
|
||||
}
|
||||
|
||||
public int getCurrentSize() {
|
||||
return currentSize;
|
||||
}
|
||||
|
||||
public void setCurrentSize(int currentSize) {
|
||||
this.currentSize = currentSize;
|
||||
}
|
||||
|
||||
public int getTotalPages() {
|
||||
return totalPages;
|
||||
}
|
||||
|
||||
public void setTotalPages(int totalPages) {
|
||||
this.totalPages = totalPages;
|
||||
}
|
||||
|
||||
public long getTotalItems() {
|
||||
return totalItems;
|
||||
}
|
||||
|
||||
public void setTotalItems(long totalItems) {
|
||||
this.totalItems = totalItems;
|
||||
}
|
||||
|
||||
public boolean isFirst() {
|
||||
return isFirst;
|
||||
}
|
||||
|
||||
public void setFirst(boolean isFirst) {
|
||||
this.isFirst = isFirst;
|
||||
}
|
||||
|
||||
public boolean isLast() {
|
||||
return isLast;
|
||||
}
|
||||
|
||||
public void setLast(boolean isLast) {
|
||||
this.isLast = isLast;
|
||||
}
|
||||
|
||||
public boolean isHasNext() {
|
||||
return hasNext;
|
||||
}
|
||||
|
||||
public void setHasNext(boolean hasNext) {
|
||||
this.hasNext = hasNext;
|
||||
}
|
||||
|
||||
public boolean isHasPrevious() {
|
||||
return hasPrevious;
|
||||
}
|
||||
|
||||
public void setHasPrevious(boolean hasPrevious) {
|
||||
this.hasPrevious = hasPrevious;
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
package com.example.backend.core.api;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageDtoMapper {
|
||||
private PageDtoMapper() {
|
||||
}
|
||||
|
||||
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
|
||||
final PageDto<D> dto = new PageDto<>();
|
||||
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
|
||||
dto.setItemsCount(page.getNumberOfElements());
|
||||
dto.setCurrentPage(page.getNumber());
|
||||
dto.setCurrentSize(page.getSize());
|
||||
dto.setTotalPages(page.getTotalPages());
|
||||
dto.setTotalItems(page.getTotalElements());
|
||||
dto.setFirst(page.isFirst());
|
||||
dto.setLast(page.isLast());
|
||||
dto.setHasNext(page.hasNext());
|
||||
dto.setHasPrevious(page.hasPrevious());
|
||||
return dto;
|
||||
}
|
||||
}
|
@ -3,9 +3,16 @@ package com.example.backend.core.configuration;
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
public static final String API_URL = "/api/1.0";
|
||||
public static final int DEFAULT_PAGE_SIZE = 8;
|
||||
|
||||
public static final String DEFAULT_PAGE_SIZE = "5";
|
||||
public static final String REDIRECT_VIEW = "redirect:";
|
||||
|
||||
public static final String ADMIN_PREFIX = "/admin";
|
||||
|
||||
public static final String LOGIN_URL = "/login";
|
||||
public static final String LOGOUT_URL = "/logout";
|
||||
|
||||
public static final String DEFAULT_PASSWORD = "123456";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
|
@ -1,9 +1,11 @@
|
||||
package com.example.backend.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.PropertyMap;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.example.backend.core.model.BaseEntity;
|
||||
import com.example.backend.orders.api.OrderDto;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
|
||||
@ -13,6 +15,12 @@ public class MapperConfiguration {
|
||||
ModelMapper modelMapper() {
|
||||
ModelMapper modelMapper = new ModelMapper();
|
||||
modelMapper.typeMap(OrderEntity.class, OrderDto.class).addMappings(mapper -> mapper.skip(OrderDto::setBooks));
|
||||
modelMapper.addMappings(new PropertyMap<Object, BaseEntity>() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
skip(destination.getId());
|
||||
}
|
||||
});
|
||||
return modelMapper;
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,13 @@
|
||||
package com.example.backend.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/login").setViewName("login");
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,53 @@
|
||||
package com.example.backend.core.error;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
|
||||
|
||||
private static Throwable getRootCause(Throwable throwable) {
|
||||
Throwable rootCause = throwable;
|
||||
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
|
||||
rootCause = rootCause.getCause();
|
||||
}
|
||||
return rootCause;
|
||||
}
|
||||
|
||||
private static Map<String, Object> getAttributes(HttpServletRequest request, Throwable throwable) {
|
||||
final Throwable rootCause = getRootCause(throwable);
|
||||
final StackTraceElement firstError = rootCause.getStackTrace()[0];
|
||||
return Map.of(
|
||||
"message", rootCause.getMessage(),
|
||||
"url", request.getRequestURL(),
|
||||
"exception", rootCause.getClass().getName(),
|
||||
"file", firstError.getFileName(),
|
||||
"method", firstError.getMethodName(),
|
||||
"line", firstError.getLineNumber());
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = Exception.class)
|
||||
public ModelAndView defaultErrorHandler(HttpServletRequest request, Throwable throwable) throws Throwable {
|
||||
if (AnnotationUtils.findAnnotation(throwable.getClass(),
|
||||
ResponseStatus.class) != null) {
|
||||
throw throwable;
|
||||
}
|
||||
|
||||
log.error("{}", throwable.getMessage());
|
||||
throwable.printStackTrace();
|
||||
final ModelAndView model = new ModelAndView();
|
||||
model.addAllObjects(getAttributes(request, throwable));
|
||||
model.setViewName("error");
|
||||
return model;
|
||||
}
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
package com.example.backend.core.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.users.api.UserSignupController;
|
||||
import com.example.backend.users.model.UserRole;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
|
||||
httpSecurity.headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
|
||||
httpSecurity.csrf(AbstractHttpConfigurer::disable);
|
||||
httpSecurity.cors(Customizer.withDefaults());
|
||||
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers("/css/**", "/webjars/**", "/*.svg", "/*.png", "/static/**")
|
||||
.permitAll());
|
||||
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers(Constants.ADMIN_PREFIX + "/**")
|
||||
.hasAnyRole(UserRole.ADMIN.name(), UserRole.SUPERADMIN.name())
|
||||
.requestMatchers("/h2-console/**").hasAnyRole(UserRole.ADMIN.name(), UserRole.SUPERADMIN.name())
|
||||
.requestMatchers(UserSignupController.URL).anonymous()
|
||||
.requestMatchers(Constants.LOGIN_URL).anonymous()
|
||||
.requestMatchers("/cart/**").permitAll()
|
||||
.requestMatchers("/catalog/**").permitAll()
|
||||
.requestMatchers("/catalog-mobile/**").permitAll()
|
||||
.requestMatchers("/contacts/**").permitAll()
|
||||
.requestMatchers("/").permitAll()
|
||||
.requestMatchers("/product-card/**").permitAll()
|
||||
.requestMatchers("/search/**").permitAll()
|
||||
.anyRequest().authenticated());
|
||||
|
||||
httpSecurity.formLogin(formLogin -> formLogin
|
||||
.loginPage(Constants.LOGIN_URL));
|
||||
|
||||
httpSecurity.rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret"));
|
||||
|
||||
httpSecurity.logout(logout -> logout
|
||||
.deleteCookies("JSESSIONID"));
|
||||
|
||||
return httpSecurity.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
|
||||
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.backend.core.security;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
|
||||
public class UserPrincipal implements UserDetails {
|
||||
private final long id;
|
||||
private final String username;
|
||||
private final String password;
|
||||
private final Set<? extends GrantedAuthority> roles;
|
||||
private final boolean active;
|
||||
|
||||
public UserPrincipal(UserEntity user) {
|
||||
this.id = user.getId();
|
||||
this.username = user.getLogin();
|
||||
this.password = user.getPassword();
|
||||
this.roles = Set.of(user.getRole());
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.example.backend.core.session;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
|
||||
public class SessionCart extends HashMap<Long, BookCountDto> {
|
||||
public int getCount() {
|
||||
return this.size();
|
||||
}
|
||||
|
||||
public double getSum() {
|
||||
return this.values().stream()
|
||||
.map(item -> item.getCount() * item.getBook().getPrice())
|
||||
.mapToDouble(Double::doubleValue)
|
||||
.sum();
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.example.backend.core.session;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.annotation.ScopedProxyMode;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@Configuration
|
||||
public class SessionHelper {
|
||||
@Bean
|
||||
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
|
||||
SessionCart todos() {
|
||||
return new SessionCart();
|
||||
}
|
||||
}
|
23
src/main/java/com/example/backend/core/utils/NumMorph.java
Normal file
@ -0,0 +1,23 @@
|
||||
package com.example.backend.core.utils;
|
||||
|
||||
public final class NumMorph {
|
||||
private NumMorph() {
|
||||
}
|
||||
|
||||
public static String numMorph(int n, String f1, String f2, String f3) {
|
||||
int n1 = Math.abs(n) % 100;
|
||||
|
||||
if (n1 >= 11 && n1 <= 19) {
|
||||
return f3;
|
||||
}
|
||||
|
||||
int n2 = n % 10;
|
||||
if (n2 == 1) {
|
||||
return f1;
|
||||
}
|
||||
if (n2 > 1 && n2 < 5) {
|
||||
return f2;
|
||||
}
|
||||
return f3;
|
||||
}
|
||||
}
|
24
src/main/java/com/example/backend/core/utils/ToBase64.java
Normal file
@ -0,0 +1,24 @@
|
||||
package com.example.backend.core.utils;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
public final class ToBase64 {
|
||||
private ToBase64() {
|
||||
}
|
||||
|
||||
public static String getBase64FromFile(MultipartFile file) {
|
||||
if (file != null && !file.isEmpty()) {
|
||||
try {
|
||||
String mimeType = file.getContentType();
|
||||
byte[] bytes = file.getBytes();
|
||||
return "data:" + mimeType + ";base64," + Base64.getEncoder().encodeToString(bytes);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.example.backend.orders.api;
|
||||
|
||||
import com.example.backend.books.api.BookDto;
|
||||
|
||||
public class BookCountDto {
|
||||
private BookDto book;
|
||||
private Integer count;
|
||||
|
||||
public BookDto getBook() {
|
||||
return book;
|
||||
}
|
||||
|
||||
public void setBook(BookDto book) {
|
||||
this.book = book;
|
||||
}
|
||||
|
||||
public Integer getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(Integer count) {
|
||||
this.count = count;
|
||||
}
|
||||
}
|
@ -1,35 +1,34 @@
|
||||
package com.example.backend.orders.api;
|
||||
|
||||
import java.text.ParseException;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.backend.core.api.PageDto;
|
||||
import com.example.backend.core.api.PageDtoMapper;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
import com.example.backend.orders.service.OrderService;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.utils.Formatter;
|
||||
import com.example.backend.books.api.BookDto;
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.utils.Formatter;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
import com.example.backend.orders.service.OrderService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user/{user}/order")
|
||||
@Controller
|
||||
@RequestMapping(OrderController.URL)
|
||||
public class OrderController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/order";
|
||||
private static final String ORDER_VIEW = "order";
|
||||
private static final String ORDER_CHECK_VIEW = "order-check";
|
||||
private static final String ORDER_ATTRIBUTE = "order";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
|
||||
private final OrderService orderService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
@ -38,6 +37,10 @@ public class OrderController {
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private OrderDto toDto(OrderEntity entity) {
|
||||
final OrderDto dto = modelMapper.map(entity, OrderDto.class);
|
||||
dto.setDate(Formatter.format(entity.getDate()));
|
||||
@ -45,50 +48,45 @@ public class OrderController {
|
||||
dto.setCount(orderService.getFullCount(entity.getUser().getId(), entity.getId()));
|
||||
dto.setBooks(orderService.getOrderBooks(entity.getUser().getId(), entity
|
||||
.getId()).stream()
|
||||
.map(orderBook -> toBookDto(orderBook.getBook()))
|
||||
.map(orderBook -> {
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(orderBook.getBook()));
|
||||
bookCountDto.setCount(orderBook.getCount());
|
||||
return bookCountDto;
|
||||
})
|
||||
.toList());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private OrderEntity toEntity(OrderDto dto) throws ParseException {
|
||||
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
|
||||
entity.setDate(Formatter.parse(dto.getDate()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<OrderDto> getAll(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(orderService.getAll(userId, page, size), this::toDto);
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper
|
||||
.toAttributes(orderService.getAll(0L, page, Constants.DEFAULT_PAGE_SIZE),
|
||||
this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return ORDER_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public OrderDto get(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(orderService.get(userId, id));
|
||||
@GetMapping("/check/{id}")
|
||||
public String checkOrder(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
model.addAttribute(ORDER_ATTRIBUTE, toDto(orderService.get(0L, id)));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return ORDER_CHECK_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public OrderDto create(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@RequestBody @Valid OrderDto dto) throws ParseException {
|
||||
dto.setDate(Formatter.format(new Date()));
|
||||
Map<Long, Integer> booksIdsCount = dto.getOrderInfo().stream()
|
||||
.collect(Collectors.toMap(OrderBookDto::getBookId, OrderBookDto::getCount));
|
||||
return toDto(orderService.create(userId, toEntity(dto), booksIdsCount));
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
orderService.delete(0L, id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public OrderDto delete(
|
||||
@PathVariable(name = "user") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(orderService.delete(userId, id));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,29 +1,14 @@
|
||||
package com.example.backend.orders.api;
|
||||
|
||||
import com.example.backend.books.api.BookDto;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public class OrderDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Double sum;
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Integer count;
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private String date;
|
||||
@NotBlank
|
||||
private String status;
|
||||
@NotBlank
|
||||
private String shippingAddress;
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
private List<OrderBookDto> orderInfo;
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private List<BookDto> books;
|
||||
private List<BookCountDto> books;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
@ -57,22 +42,6 @@ public class OrderDto {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getShippingAddress() {
|
||||
return shippingAddress;
|
||||
}
|
||||
|
||||
public void setShippingAddress(String shippingAddress) {
|
||||
this.shippingAddress = shippingAddress;
|
||||
}
|
||||
|
||||
public List<OrderBookDto> getOrderInfo() {
|
||||
return orderInfo;
|
||||
}
|
||||
@ -81,11 +50,11 @@ public class OrderDto {
|
||||
this.orderInfo = orderInfo;
|
||||
}
|
||||
|
||||
public List<BookDto> getBooks() {
|
||||
public List<BookCountDto> getBooks() {
|
||||
return books;
|
||||
}
|
||||
|
||||
public void setBooks(List<BookDto> books) {
|
||||
public void setBooks(List<BookCountDto> books) {
|
||||
this.books = books;
|
||||
}
|
||||
}
|
||||
|
@ -25,11 +25,7 @@ public class OrderEntity extends BaseEntity {
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
@Column(nullable = false)
|
||||
private Date date;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String status;
|
||||
@Column(nullable = false)
|
||||
private String shippingAddress;
|
||||
private Date date = new Date();
|
||||
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OrderBy("id ASC")
|
||||
private Set<OrderBookEntity> orderBooks = new HashSet<>();
|
||||
@ -37,12 +33,6 @@ public class OrderEntity extends BaseEntity {
|
||||
public OrderEntity() {
|
||||
}
|
||||
|
||||
public OrderEntity(String status, String shippingAddress) {
|
||||
this.status = status;
|
||||
this.shippingAddress = shippingAddress;
|
||||
this.date = new Date();
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
@ -62,22 +52,6 @@ public class OrderEntity extends BaseEntity {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getShippingAddress() {
|
||||
return shippingAddress;
|
||||
}
|
||||
|
||||
public void setShippingAddress(String shippingAddress) {
|
||||
this.shippingAddress = shippingAddress;
|
||||
}
|
||||
|
||||
public Set<OrderBookEntity> getOrderBooks() {
|
||||
return orderBooks;
|
||||
}
|
||||
@ -98,7 +72,7 @@ public class OrderEntity extends BaseEntity {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user.getId(), date, status, shippingAddress);
|
||||
return Objects.hash(id, user.getId(), date);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -110,8 +84,6 @@ public class OrderEntity extends BaseEntity {
|
||||
final OrderEntity other = (OrderEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser().getId(), user.getId())
|
||||
&& Objects.equals(other.getDate(), date)
|
||||
&& Objects.equals(other.getStatus(), status)
|
||||
&& Objects.equals(other.getShippingAddress(), shippingAddress);
|
||||
&& Objects.equals(other.getDate(), date);
|
||||
}
|
||||
}
|
||||
|
@ -39,12 +39,19 @@ public class OrderService {
|
||||
@Transactional(readOnly = true)
|
||||
public Page<OrderEntity> getAll(long userId, int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
if (userId <= 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
userService.get(userId);
|
||||
return repository.findByUserId(userId, pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public OrderEntity get(long userId, long id) {
|
||||
if (userId <= 0L) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(OrderEntity.class, id));
|
||||
}
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(OrderEntity.class, id));
|
||||
@ -70,6 +77,11 @@ public class OrderService {
|
||||
|
||||
@Transactional
|
||||
public OrderEntity delete(long userId, long id) {
|
||||
if (userId <= 0L) {
|
||||
final OrderEntity existsEntity = get(0, id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
userService.get(userId);
|
||||
final OrderEntity existsEntity = get(userId, id);
|
||||
repository.delete(existsEntity);
|
||||
|
@ -0,0 +1,102 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.security.UserPrincipal;
|
||||
import com.example.backend.core.session.SessionCart;
|
||||
import com.example.backend.core.utils.NumMorph;
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
import com.example.backend.orders.service.OrderService;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserCartController.URL)
|
||||
public class UserCartController {
|
||||
public static final String URL = "/cart";
|
||||
|
||||
private static final String CART_VIEW = "cart";
|
||||
private static final String CART_ATTRIBUTE = "cart";
|
||||
|
||||
private final OrderService orderService;
|
||||
private final SessionCart cart;
|
||||
|
||||
public UserCartController(
|
||||
OrderService orderService,
|
||||
SessionCart cart) {
|
||||
this.orderService = orderService;
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getCart(Model model) {
|
||||
model.addAttribute(CART_ATTRIBUTE, cart.values());
|
||||
model.addAttribute("count", cart.getCount());
|
||||
model.addAttribute("sum", cart.getSum());
|
||||
model.addAttribute("linesText", NumMorph.numMorph(cart.getCount(), "товар", "товара", "товаров"));
|
||||
return CART_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/clear")
|
||||
public String clearCart(
|
||||
@RequestParam(name = "bookId", defaultValue = "0") long bookId,
|
||||
Model model) {
|
||||
if (bookId <= 0) {
|
||||
cart.clear();
|
||||
} else {
|
||||
cart.remove(bookId);
|
||||
}
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/increase")
|
||||
public String increaseCartCount(
|
||||
@RequestParam(name = "bookId") long bookId) {
|
||||
BookCountDto book = cart.get(bookId);
|
||||
if (book != null) {
|
||||
book.setCount(book.getCount() + 1);
|
||||
}
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/decrease")
|
||||
public String decreaseCartCount(
|
||||
@RequestParam(name = "bookId") long bookId) {
|
||||
BookCountDto book = cart.get(bookId);
|
||||
if (book != null) {
|
||||
book.setCount(book.getCount() - 1);
|
||||
}
|
||||
final Map<Long, BookCountDto> filteredCart = cart.entrySet()
|
||||
.stream()
|
||||
.filter(item -> item.getValue().getCount() > 0)
|
||||
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
|
||||
cart.clear();
|
||||
cart.putAll(filteredCart);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
public String saveCart(
|
||||
Model model,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
Map<Long, Integer> orderMap = cart.entrySet()
|
||||
.stream()
|
||||
.collect(Collectors.toMap(
|
||||
Entry::getKey,
|
||||
entry -> entry.getValue().getCount()));
|
||||
orderService.create(principal.getId(), new OrderEntity(), orderMap);
|
||||
cart.clear();
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
}
|
@ -1,27 +1,35 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.backend.core.api.PageDto;
|
||||
import com.example.backend.core.api.PageDtoMapper;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
import com.example.backend.users.service.UserService;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user")
|
||||
@Controller
|
||||
@RequestMapping(UserController.URL)
|
||||
public class UserController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/user";
|
||||
private static final String USER_VIEW = "user";
|
||||
private static final String USER_EDIT_VIEW = "user-edit";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
@ -39,29 +47,56 @@ public class UserController {
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<UserDto> getAll(
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
userService.getAll(page, Constants.DEFAULT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UserDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.get(id));
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(USER_ATTRIBUTE, toDto(userService.get(id)));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UserDto create(@RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.create(toEntity(dto)));
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.update(id, toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UserDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.delete(id));
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,9 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
@ -15,11 +12,13 @@ public class UserDto {
|
||||
@Size(min = 5, max = 254)
|
||||
private String email;
|
||||
@NotBlank
|
||||
@Size(min = 6, max = 16)
|
||||
@Size(min = 6, max = 60)
|
||||
private String password;
|
||||
@NotBlank
|
||||
@Size(min = 1, max = 20)
|
||||
private String accessLevel;
|
||||
private String firstname;
|
||||
@NotBlank
|
||||
private String lastname;
|
||||
private String role;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
@ -53,11 +52,27 @@ public class UserDto {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getAccessLevel() {
|
||||
return accessLevel;
|
||||
public String getFirstname() {
|
||||
return firstname;
|
||||
}
|
||||
|
||||
public void setAccessLevel(String accessLevel) {
|
||||
this.accessLevel = accessLevel;
|
||||
public void setFirstname(String firstname) {
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
public String getLastname() {
|
||||
return lastname;
|
||||
}
|
||||
|
||||
public void setLastname(String lastname) {
|
||||
this.lastname = lastname;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,118 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.backend.books.api.BookDto;
|
||||
import com.example.backend.books.model.BookEntity;
|
||||
import com.example.backend.core.api.PageAttributesMapper;
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.security.UserPrincipal;
|
||||
import com.example.backend.core.utils.Formatter;
|
||||
import com.example.backend.orders.api.BookCountDto;
|
||||
import com.example.backend.orders.api.OrderDto;
|
||||
import com.example.backend.orders.model.OrderEntity;
|
||||
import com.example.backend.orders.service.OrderService;
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
import com.example.backend.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserProfileController.URL)
|
||||
public class UserProfileController {
|
||||
public static final String URL = "/profile";
|
||||
|
||||
private static final String PROFILE_VIEW = "profile";
|
||||
private static final String PROFILEEDIT_VIEW = "profile-edit";
|
||||
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final OrderService orderService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserProfileController(
|
||||
UserService userService,
|
||||
OrderService orderService,
|
||||
ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.orderService = orderService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserEntity toUserEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
private UserDto toUserDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private OrderDto toOrderDto(OrderEntity entity) {
|
||||
final OrderDto dto = modelMapper.map(entity, OrderDto.class);
|
||||
dto.setDate(Formatter.format(entity.getDate()));
|
||||
dto.setSum(orderService.getSum(entity.getUser().getId(), entity.getId()));
|
||||
dto.setCount(orderService.getFullCount(entity.getUser().getId(), entity.getId()));
|
||||
dto.setBooks(orderService.getOrderBooks(entity.getUser().getId(), entity
|
||||
.getId()).stream()
|
||||
.map(orderBook -> {
|
||||
BookCountDto bookCountDto = new BookCountDto();
|
||||
bookCountDto.setBook(toBookDto(orderBook.getBook()));
|
||||
bookCountDto.setCount(orderBook.getCount());
|
||||
return bookCountDto;
|
||||
})
|
||||
.toList());
|
||||
return dto;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getProfile(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
model.addAttribute(USER_ATTRIBUTE, toUserDto(userService.get(principal.getId())));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
orderService.getAll(principal.getId(), page, 3),
|
||||
this::toOrderDto));
|
||||
return PROFILE_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit")
|
||||
public String changeUserInfo(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
model.addAttribute(USER_ATTRIBUTE, toUserDto(userService.get(principal.getId())));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return PROFILEEDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit")
|
||||
public String update(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return PROFILEEDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.update(principal.getId(), toUserEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
import com.example.backend.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserSignupController.URL)
|
||||
public class UserSignupController {
|
||||
public static final String URL = "/signup";
|
||||
|
||||
private static final String SIGNUP_VIEW = "signup";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserSignupController(
|
||||
UserService userService,
|
||||
ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserSignupDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getSignup(Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserSignupDto());
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String signup(
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserSignupDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
if (!Objects.equals(user.getPassword(), user.getPasswordConfirm())) {
|
||||
bindingResult.rejectValue("password", "signup:passwords", "Пароли не совпадают.");
|
||||
model.addAttribute(USER_ATTRIBUTE, user);
|
||||
return SIGNUP_VIEW;
|
||||
}
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package com.example.backend.users.api;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserSignupDto {
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String login;
|
||||
@NotBlank
|
||||
@Email
|
||||
private String email;
|
||||
@NotBlank
|
||||
private String firstname;
|
||||
@NotBlank
|
||||
private String lastname;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String password;
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String passwordConfirm;
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getFirstname() {
|
||||
return firstname;
|
||||
}
|
||||
|
||||
public void setFirstname(String firstname) {
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
public String getLastname() {
|
||||
return lastname;
|
||||
}
|
||||
|
||||
public void setLastname(String lastname) {
|
||||
this.lastname = lastname;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPasswordConfirm() {
|
||||
return passwordConfirm;
|
||||
}
|
||||
|
||||
public void setPasswordConfirm(String passwordConfirm) {
|
||||
this.passwordConfirm = passwordConfirm;
|
||||
}
|
||||
}
|
@ -21,10 +21,13 @@ public class UserEntity extends BaseEntity {
|
||||
private String login;
|
||||
@Column(nullable = false, unique = true, length = 254)
|
||||
private String email;
|
||||
@Column(nullable = false, length = 16)
|
||||
@Column(nullable = false, length = 60)
|
||||
private String password;
|
||||
@Column(nullable = false, length = 20)
|
||||
private String accessLevel;
|
||||
@Column(nullable = false)
|
||||
private String firstname;
|
||||
@Column(nullable = false)
|
||||
private String lastname;
|
||||
private UserRole role;
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||
@OrderBy("id ASC")
|
||||
private Set<OrderEntity> orders = new HashSet<>();
|
||||
@ -32,11 +35,13 @@ public class UserEntity extends BaseEntity {
|
||||
public UserEntity() {
|
||||
}
|
||||
|
||||
public UserEntity(String login, String email, String password, String accessLevel) {
|
||||
public UserEntity(String login, String email, String password, String firstname, String lastname) {
|
||||
this.login = login;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.accessLevel = accessLevel;
|
||||
this.firstname = firstname;
|
||||
this.lastname = lastname;
|
||||
this.role = UserRole.USER;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
@ -63,12 +68,28 @@ public class UserEntity extends BaseEntity {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getAccessLevel() {
|
||||
return accessLevel;
|
||||
public UserRole getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setAccessLevel(String accessLevel) {
|
||||
this.accessLevel = accessLevel;
|
||||
public void setRole(UserRole role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getFirstname() {
|
||||
return firstname;
|
||||
}
|
||||
|
||||
public void setFirstname(String firstname) {
|
||||
this.firstname = firstname;
|
||||
}
|
||||
|
||||
public String getLastname() {
|
||||
return lastname;
|
||||
}
|
||||
|
||||
public void setLastname(String lastname) {
|
||||
this.lastname = lastname;
|
||||
}
|
||||
|
||||
public Set<OrderEntity> getOrders() {
|
||||
@ -84,7 +105,7 @@ public class UserEntity extends BaseEntity {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, login, email, password, accessLevel);
|
||||
return Objects.hash(id, login, email, password, lastname, firstname, role);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -98,6 +119,8 @@ public class UserEntity extends BaseEntity {
|
||||
&& Objects.equals(other.getLogin(), login)
|
||||
&& Objects.equals(other.getEmail(), email)
|
||||
&& Objects.equals(other.getPassword(), password)
|
||||
&& Objects.equals(other.getAccessLevel(), accessLevel);
|
||||
&& Objects.equals(other.getFirstname(), firstname)
|
||||
&& Objects.equals(other.getLastname(), lastname)
|
||||
&& Objects.equals(other.getRole(), role);
|
||||
}
|
||||
}
|
||||
|
16
src/main/java/com/example/backend/users/model/UserRole.java
Normal file
@ -0,0 +1,16 @@
|
||||
package com.example.backend.users.model;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
public enum UserRole implements GrantedAuthority {
|
||||
SUPERADMIN,
|
||||
ADMIN,
|
||||
USER;
|
||||
|
||||
private static final String PREFIX = "ROLE_";
|
||||
|
||||
@Override
|
||||
public String getAuthority() {
|
||||
return PREFIX + this.name();
|
||||
}
|
||||
}
|
@ -2,26 +2,39 @@ package com.example.backend.users.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.example.backend.core.configuration.Constants;
|
||||
import com.example.backend.core.security.UserPrincipal;
|
||||
import com.example.backend.users.model.UserEntity;
|
||||
import com.example.backend.users.model.UserRole;
|
||||
import com.example.backend.users.repository.UserRepository;
|
||||
import com.example.backend.core.error.NotFoundException;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
public class UserService implements UserDetailsService {
|
||||
private final UserRepository repository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public UserService(UserRepository repository) {
|
||||
public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
|
||||
this.repository = repository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
private void checkLogin(String login) {
|
||||
if (repository.findByLoginIgnoreCase(login).isPresent()) {
|
||||
private void checkLogin(Long id, String login) {
|
||||
final Optional<UserEntity> existsUser = repository.findByLoginIgnoreCase(login);
|
||||
if (existsUser.isPresent() && !existsUser.get().getId().equals(id)) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with login %s is already exists", login));
|
||||
}
|
||||
@ -34,7 +47,7 @@ public class UserService {
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UserEntity> getAll(int page, int size) {
|
||||
return repository.findAll(PageRequest.of(page, size));
|
||||
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
@ -43,22 +56,40 @@ public class UserService {
|
||||
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserEntity getByLogin(String login) {
|
||||
return repository.findByLoginIgnoreCase(login)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Invalid login"));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity create(UserEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkLogin(entity.getLogin());
|
||||
checkLogin(null, entity.getLogin());
|
||||
final String password = Optional.ofNullable(entity.getPassword()).orElse("");
|
||||
entity.setPassword(
|
||||
passwordEncoder.encode(
|
||||
StringUtils.hasText(password.strip()) ? password : Constants.DEFAULT_PASSWORD));
|
||||
entity.setRole(Optional.ofNullable(entity.getRole()).orElse(UserRole.USER));
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity update(long id, UserEntity entity) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
existsEntity.setLogin(entity.getLogin());
|
||||
if (!entity.getLogin().equals(existsEntity.getLogin())) {
|
||||
checkLogin(id, entity.getLogin());
|
||||
existsEntity.setLogin(entity.getLogin());
|
||||
}
|
||||
final String password = Optional.ofNullable(entity.getPassword()).orElse("");
|
||||
existsEntity.setPassword(
|
||||
passwordEncoder.encode(
|
||||
StringUtils.hasText(password.strip()) ? password : Constants.DEFAULT_PASSWORD));
|
||||
existsEntity.setFirstname(entity.getFirstname());
|
||||
existsEntity.setLastname(entity.getLastname());
|
||||
existsEntity.setEmail(entity.getEmail());
|
||||
existsEntity.setPassword(entity.getPassword());
|
||||
existsEntity.setAccessLevel(entity.getAccessLevel());
|
||||
repository.save(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
@ -69,4 +100,11 @@ public class UserService {
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
final UserEntity existsUser = getByLogin(username);
|
||||
return new UserPrincipal(existsUser);
|
||||
}
|
||||
}
|
||||
|
@ -17,4 +17,8 @@ spring.jpa.open-in-view=false
|
||||
# spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
# H2 console
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.enabled=true
|
||||
|
||||
# Multipart file upload settings
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
spring.servlet.multipart.max-request-size=10MB
|
987
src/main/resources/public/css/style.css
Normal file
@ -0,0 +1,987 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,800;0,900;1,700&display=swap');
|
||||
|
||||
body {
|
||||
font-family: Montserrat, Arial, sans-serif;
|
||||
background-color: rgb(238, 236, 236);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
main {
|
||||
margin: 4%;
|
||||
}
|
||||
|
||||
td form {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
margin-top: -.25em;
|
||||
}
|
||||
|
||||
.row {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
header nav {
|
||||
background-color: rgb(23, 154, 183);
|
||||
color: white;
|
||||
}
|
||||
|
||||
#logo,
|
||||
.nav-link,
|
||||
.profile-link,
|
||||
#catalog-categories-list li a,
|
||||
#catalog-page-navigation a,
|
||||
#catalog-categories-mobile-list li a,
|
||||
#password-help a,
|
||||
#login-admin a,
|
||||
.list-group-item a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#logo {
|
||||
font-size: 20px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.nav-link,
|
||||
.header-part {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
header nav a.active {
|
||||
font-weight: 900 !important;
|
||||
text-decoration: underline !important;
|
||||
text-decoration-skip-ink: none !important;
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
#cart-icon {
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
|
||||
.active-icon #cart-icon {
|
||||
border-width: 1px;
|
||||
border-style: solid;
|
||||
border-color: white;
|
||||
}
|
||||
|
||||
#search-bar {
|
||||
min-width: 94px;
|
||||
}
|
||||
|
||||
#search-bar::placeholder {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
color: rgb(145, 141, 141);
|
||||
}
|
||||
|
||||
header nav a {
|
||||
transition: color 0.15s !important;
|
||||
}
|
||||
|
||||
header nav a:hover {
|
||||
color: rgb(6, 69, 173) !important;
|
||||
}
|
||||
|
||||
#cart-icon:hover {
|
||||
border-width: 1px;
|
||||
border-style: solid;
|
||||
border-color: white;
|
||||
}
|
||||
|
||||
.active-icon #cart-icon:hover {
|
||||
border-color: rgb(6, 69, 173);
|
||||
}
|
||||
|
||||
.main-page-section-title {
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
.main-page-section-title-text {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.main-page-price {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.main-page-book-title {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.main-page-author {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: rgb(97, 95, 95);
|
||||
}
|
||||
|
||||
#product-card-order-container {
|
||||
width: 294px;
|
||||
}
|
||||
|
||||
#product-card-book-name {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#product-card-author {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: rgb(14, 173, 208)
|
||||
}
|
||||
|
||||
#product-card-characteristics {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
#product-card-characteristics dt {
|
||||
color: rgb(97, 95, 95);
|
||||
font-weight: 600 !important;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
#product-card-characteristics dd {
|
||||
padding-left: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#product-card-text-available {
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
color: rgb(80, 176, 84);
|
||||
}
|
||||
|
||||
#product-card-price {
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#product-card-button-add {
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
background-color: rgb(23, 154, 183);
|
||||
transition: opacity 0.25s;
|
||||
}
|
||||
|
||||
#product-card-button-add:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.product-card-book-description-h {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.product-card-book-description-text {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
#contacts-title {
|
||||
font-size: 30px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.contacts-item {
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.contacts-item-main-info {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.contacts-item-clarification {
|
||||
font-size: 16px;
|
||||
color: rgb(145, 141, 141);
|
||||
}
|
||||
|
||||
#skype-link {
|
||||
font-size: 20px;
|
||||
font-weight: 900;
|
||||
color: rgb(6, 69, 173);
|
||||
}
|
||||
|
||||
#contacts-address {
|
||||
font-size: 20px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
#contacts-address-value {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#cart-title {
|
||||
font-size: 36px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
#cart-items-num-text {
|
||||
font-size: 24px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.cart-button-remove {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: rgb(145, 141, 141);
|
||||
transition: color 0.15s;
|
||||
}
|
||||
|
||||
.cart-button-remove:hover {
|
||||
color: blue;
|
||||
}
|
||||
|
||||
.cart-book-description {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.cart-book-description-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.cart-book-description-author {
|
||||
font-size: 16px;
|
||||
color: rgb(145, 141, 141);
|
||||
}
|
||||
|
||||
.button-minus,
|
||||
.button-plus {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
width: 32px;
|
||||
height: 34px;
|
||||
color: rgb(145, 141, 141);
|
||||
transition: background-color 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.button-minus:hover,
|
||||
.button-plus:hover {
|
||||
background-color: rgb(114, 187, 5) !important;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.cart-input-label {
|
||||
width: 42px;
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.cart-input {
|
||||
font-size: 16px;
|
||||
font-weight: 900;
|
||||
border-color: rgb(222, 226, 230) !important;
|
||||
}
|
||||
|
||||
.cart-input::placeholder {
|
||||
color: black;
|
||||
}
|
||||
|
||||
.cart-price {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.cart-price-count {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#cart-final-price {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#cart-final-price-text {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
#cart-final-price-value {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
#cart-btn-checkout {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
background-color: rgb(217, 217, 217);
|
||||
transition: opacity 0.25s;
|
||||
}
|
||||
|
||||
#cart-btn-checkout:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
#catalog-categories,
|
||||
#catalog-categories-mobile {
|
||||
border-color: rgb(23, 154, 183) !important;
|
||||
}
|
||||
|
||||
#catalog-categories-title,
|
||||
#catalog-categories-mobile-title {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#catalog-categories-title {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
#catalog-categories-list,
|
||||
#catalog-categories-mobile-list {
|
||||
font-weight: 500;
|
||||
color: rgb(6, 69, 173) !important;
|
||||
}
|
||||
|
||||
#catalog-categories-list {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.active-category,
|
||||
.active-category-mobile {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-title {
|
||||
font-size: 48px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-list {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
#catalog-title {
|
||||
font-size: 40px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
#catalog-select {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
width: 264px;
|
||||
height: 35px;
|
||||
}
|
||||
|
||||
.catalog-price {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.catalog-book-title,
|
||||
.catalog-author {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.catalog-bth-checkout {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
background-color: rgb(217, 217, 217);
|
||||
transition: background-color 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.catalog-bth-checkout:hover {
|
||||
background-color: rgb(114, 187, 5) !important;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#catalog-page-navigation {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#catalog-selected-page {
|
||||
color: rgb(80, 176, 84) !important;
|
||||
}
|
||||
|
||||
#catalog-page-navigation a {
|
||||
transition: color 0.15s;
|
||||
}
|
||||
|
||||
#catalog-page-navigation a:hover {
|
||||
color: rgb(0, 0, 238) !important;
|
||||
}
|
||||
|
||||
#catalog-section-navigation {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.login-input-email,
|
||||
.login-input-password,
|
||||
.login-input-remember,
|
||||
.reg-input-name,
|
||||
.reg-input-email,
|
||||
.reg-input-password {
|
||||
font-size: 16px;
|
||||
min-width: 165px;
|
||||
}
|
||||
|
||||
#login-title,
|
||||
#reg-title {
|
||||
font-size: 24px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.login-btn,
|
||||
.reg-btn {
|
||||
font-size: 16px;
|
||||
font-weight: 900;
|
||||
background-color: rgb(6, 69, 173);
|
||||
transition: opacity 0.25s;
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
.login-btn:hover,
|
||||
.reg-btn:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
#password-help,
|
||||
#login-admin {
|
||||
font-size: 16px;
|
||||
font-weight: 900;
|
||||
color: rgb(145, 141, 141);
|
||||
}
|
||||
|
||||
#add-btn {
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
footer {
|
||||
background-color: rgb(23, 154, 183);
|
||||
color: white;
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
#footer-container {
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
#footer-row {
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
#footer-copyright {
|
||||
font-size: 24px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
#footer-phone-number-text {
|
||||
font-size: 20px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
#footer-social-media-text {
|
||||
font-size: 19px;
|
||||
font-weight: 900;
|
||||
}
|
||||
|
||||
.astext {
|
||||
background: none;
|
||||
border: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
transition: color 0.15s !important;
|
||||
}
|
||||
|
||||
.astext:hover {
|
||||
color: rgb(6, 69, 173) !important;
|
||||
}
|
||||
|
||||
#cart-link-count {
|
||||
padding: 1px 4px;
|
||||
font-weight: 700;
|
||||
font-size: 12px;
|
||||
box-shadow: 0 0 0 2px #fff;
|
||||
top: 5px;
|
||||
left: 29px;
|
||||
background: linear-gradient(0deg, #177bc2 0%, #2e8db5 100%);
|
||||
border-radius: 50px;
|
||||
align-items: center;
|
||||
color: #fff;
|
||||
display: inline-flex;
|
||||
height: 13px;
|
||||
justify-content: center;
|
||||
line-height: 13px;
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.invalid-feedback {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.button-fixed-width {
|
||||
width: 150px;
|
||||
}
|
||||
|
||||
.cart-labels {
|
||||
font-variant: small-caps;
|
||||
}
|
||||
|
||||
@media (min-width: 992px) and (max-width: 1200px) {
|
||||
#logo {
|
||||
margin-right: 25px !important;
|
||||
}
|
||||
|
||||
.header-link {
|
||||
margin-right: 10px !important;
|
||||
}
|
||||
|
||||
#header-contacts,
|
||||
#header-search {
|
||||
margin-right: 20px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 992px) {
|
||||
header nav {
|
||||
height: 60px !important;
|
||||
}
|
||||
|
||||
main {
|
||||
margin: 2%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
#catalog-categories-list {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.orders-info {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
|
||||
.active-category {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#catalog-categories-title {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
#catalog-title {
|
||||
font-size: 36px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
#catalog-categories-title {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
#catalog-categories-list {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.active-category {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
#catalog-title {
|
||||
font-size: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
#product-card-characteristics {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#product-card-characteristics dt,
|
||||
#product-card-characteristics dd {
|
||||
text-align: left;
|
||||
padding-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.cart-book-cover {
|
||||
width: 66px;
|
||||
height: 104px;
|
||||
}
|
||||
|
||||
.cart-button-remove {
|
||||
font-size: 0 !important;
|
||||
}
|
||||
|
||||
.catalog-book-description,
|
||||
.catalog-btn-checkout-div {
|
||||
margin-left: 15%;
|
||||
}
|
||||
|
||||
#admin-title {
|
||||
font-size: 18px !important;
|
||||
}
|
||||
|
||||
.edit-btn {
|
||||
width: 50% !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 510px) {
|
||||
|
||||
.login-input-email,
|
||||
.login-input-password,
|
||||
.login-input-remember,
|
||||
.login-btn,
|
||||
#password-help,
|
||||
#login-admin,
|
||||
.errmsg {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.reg-input-name,
|
||||
.reg-input-email,
|
||||
.reg-input-password,
|
||||
.reg-btn {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#login-title,
|
||||
#reg-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 475px) {
|
||||
#cart-title {
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
#cart-items-num-text,
|
||||
#cart-final-price-text {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.cart-book-description-title,
|
||||
#cart-final-price-value {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.cart-book-description-author {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cart-price,
|
||||
#cart-btn-checkout,
|
||||
.cart-input {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.cart-price-count {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.button-minus,
|
||||
.button-plus {
|
||||
font-size: 16px;
|
||||
width: 26px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.cart-input-label {
|
||||
width: 34px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-title {
|
||||
font-size: 44px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-list {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
#image-preview {
|
||||
width: 300px;
|
||||
height: 450px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 400px) {
|
||||
|
||||
.main-page-book-title,
|
||||
.main-page-author {
|
||||
font-size: 0 !important;
|
||||
}
|
||||
|
||||
.main-page-book-cover {
|
||||
width: 80px;
|
||||
height: 122px;
|
||||
}
|
||||
|
||||
#footer-copyright {
|
||||
font-size: 20px !important;
|
||||
}
|
||||
|
||||
#footer-phone-number-text {
|
||||
font-size: 18px !important;
|
||||
}
|
||||
|
||||
#footer-social-media-text {
|
||||
font-size: 0 !important;
|
||||
margin-right: 0 !important;
|
||||
}
|
||||
|
||||
#catalog-section-navigation {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.login-btn,
|
||||
#password-help,
|
||||
#login-admin,
|
||||
.reg-input-password,
|
||||
.reg-btn {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.reg-input-name,
|
||||
.reg-input-email,
|
||||
.login-input-email,
|
||||
.login-input-password,
|
||||
.login-input-remember,
|
||||
.errmsg {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
#login-title,
|
||||
#reg-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 361px) {
|
||||
#logo {
|
||||
font-size: 0 !important;
|
||||
}
|
||||
|
||||
.contacts-icon {
|
||||
width: 55px !important;
|
||||
height: 55px !important;
|
||||
}
|
||||
|
||||
#contacts-title {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.contacts-item-main-info,
|
||||
#skype-link,
|
||||
#contacts-address {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.contacts-item-clarification,
|
||||
#contacts-address-value {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
#catalog-title {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
#catalog-select {
|
||||
font-size: 11px;
|
||||
width: 164px;
|
||||
height: 28px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#image-preview {
|
||||
width: 200px;
|
||||
height: 300px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 335px) {
|
||||
#mobile-price-count {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#cart-title {
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
#cart-items-num-text {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.cart-book-description-title,
|
||||
#cart-final-price-value {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.cart-book-description-author {
|
||||
font-size: 8px;
|
||||
}
|
||||
|
||||
#cart-final-price-text {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.button-minus,
|
||||
.button-plus {
|
||||
font-size: 10px;
|
||||
width: 16px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.cart-input-label {
|
||||
width: 22px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.cart-input,
|
||||
#cart-btn-checkout,
|
||||
.cart-price {
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.cart-price-count {
|
||||
font-size: 8px;
|
||||
}
|
||||
|
||||
.trash-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.cart-book-cover {
|
||||
width: 44px;
|
||||
height: 69px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 320px) {
|
||||
#product-card-price {
|
||||
font-size: 22px !important;
|
||||
}
|
||||
|
||||
#novelty-icon {
|
||||
width: 74px !important;
|
||||
height: 25px !important;
|
||||
}
|
||||
|
||||
#discont-icon {
|
||||
width: 49px !important;
|
||||
height: 25px !important;
|
||||
}
|
||||
|
||||
.product-card-book-description-h,
|
||||
.product-card-book-description-text,
|
||||
#product-card-button-add,
|
||||
#product-card-text-available {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
|
||||
#catalog-section-navigation {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-title {
|
||||
font-size: 38px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-list {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 282px) {
|
||||
#footer-copyright {
|
||||
font-size: 14px !important;
|
||||
}
|
||||
|
||||
#footer-phone-number-text {
|
||||
font-size: 12px !important;
|
||||
}
|
||||
|
||||
#admin-title {
|
||||
font-size: 16px !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 272px) {
|
||||
#fire-icon {
|
||||
height: 38px;
|
||||
width: 30px;
|
||||
}
|
||||
|
||||
.catalog-book-description,
|
||||
.catalog-btn-checkout-div {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.contacts-icon {
|
||||
width: 44px !important;
|
||||
height: 44px !important;
|
||||
margin-right: 20px !important;
|
||||
}
|
||||
|
||||
#contacts-title {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.contacts-item-main-info,
|
||||
#skype-link #contacts-address {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#catalog-title {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
#catalog-select {
|
||||
width: 140px;
|
||||
height: 22px;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
#catalog-select,
|
||||
#contacts-address-value,
|
||||
.contacts-item-clarification {
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
#catalog-page-navigation {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
#catalog-section-navigation {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-title {
|
||||
font-size: 26px;
|
||||
}
|
||||
|
||||
#catalog-categories-mobile-list {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
#image-preview {
|
||||
width: 155px;
|
||||
height: 235px;
|
||||
}
|
||||
|
||||
.edit-btn {
|
||||
width: 75% !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 204px) {
|
||||
#footer-copyright {
|
||||
font-size: 13px !important;
|
||||
}
|
||||
|
||||
#footer-phone-number-text {
|
||||
font-size: 11px !important;
|
||||
}
|
||||
}
|
BIN
src/main/resources/static/card.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
src/main/resources/static/cart_button.png
Normal file
After Width: | Height: | Size: 520 B |
BIN
src/main/resources/static/check.png
Normal file
After Width: | Height: | Size: 501 B |
BIN
src/main/resources/static/discont.png
Normal file
After Width: | Height: | Size: 484 B |
BIN
src/main/resources/static/email.png
Normal file
After Width: | Height: | Size: 3.5 KiB |
BIN
src/main/resources/static/fire.png
Normal file
After Width: | Height: | Size: 1.1 KiB |
BIN
src/main/resources/static/line.png
Normal file
After Width: | Height: | Size: 484 B |
BIN
src/main/resources/static/logo.png
Normal file
After Width: | Height: | Size: 2.9 KiB |
BIN
src/main/resources/static/map.png
Normal file
After Width: | Height: | Size: 950 KiB |
BIN
src/main/resources/static/nothing.png
Normal file
After Width: | Height: | Size: 800 KiB |
BIN
src/main/resources/static/novelty.png
Normal file
After Width: | Height: | Size: 709 B |
BIN
src/main/resources/static/odnoklassniki.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
src/main/resources/static/phone-call.png
Normal file
After Width: | Height: | Size: 4.4 KiB |
BIN
src/main/resources/static/photo.png
Normal file
After Width: | Height: | Size: 3.0 KiB |
BIN
src/main/resources/static/placeholder_400_600.png
Normal file
After Width: | Height: | Size: 9.8 KiB |
BIN
src/main/resources/static/skype.png
Normal file
After Width: | Height: | Size: 4.9 KiB |
BIN
src/main/resources/static/telegram.png
Normal file
After Width: | Height: | Size: 733 B |
BIN
src/main/resources/static/telephone-call.png
Normal file
After Width: | Height: | Size: 1.3 KiB |
BIN
src/main/resources/static/trash.png
Normal file
After Width: | Height: | Size: 1.0 KiB |
BIN
src/main/resources/static/vk.png
Normal file
After Width: | Height: | Size: 1019 B |
BIN
src/main/resources/static/youtube.png
Normal file
After Width: | Height: | Size: 714 B |
34
src/main/resources/templates/admin.html
Normal file
@ -0,0 +1,34 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="text-center mt-4">
|
||||
<h2 class="fs-2 mb-3 fw-bold">Панель администратора</h2>
|
||||
</div>
|
||||
|
||||
<ol class="list-group list-group-numbered mt-3">
|
||||
<li class="list-group-item fs-4 fw-bold">
|
||||
<a href="/admin/category">Категории.</a>
|
||||
</li>
|
||||
<li class="list-group-item fs-4 fw-bold">
|
||||
<a href="/admin/book">Книги.</a>
|
||||
</li>
|
||||
<li class="list-group-item fs-4 fw-bold">
|
||||
<a href="/admin/order">Заказы.</a>
|
||||
</li>
|
||||
<li class="list-group-item fs-4 fw-bold">
|
||||
<a href="/admin/user">Пользователи.</a>
|
||||
</li>
|
||||
<li class="list-group-item fs-4 fw-bold">
|
||||
<a href="/h2-console/" target="_blank">Консоль H2.</a>
|
||||
</li>
|
||||
</ol>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
119
src/main/resources/templates/book-edit.html
Normal file
@ -0,0 +1,119 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (книги)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row justify-content-center">
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6" action="#" th:action="@{/admin/book/edit/{id}(id=${book.id}, page=${page})}"
|
||||
th:object="${book}" method="post" enctype="multipart/form-data">
|
||||
<div class='text-center mb-4 mt-5'>
|
||||
<img id='image-preview' alt='placeholder' width="400" height="600"
|
||||
th:src="@{${book.image != null && !#strings.isEmpty(book.image) ? book.image : '/placeholder_400_600.png'}}" />
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="categoryId" class="form-label">Категория</label>
|
||||
<select th:name="categoryId" id="categoryId" class="form-select">
|
||||
<option selected value="">Выберите категорию книги</option>
|
||||
<option th:each="category : ${categories}" th:value="${category.id}" th:selected="${category.id==book.categoryId}">
|
||||
[[${category.name}]]
|
||||
</option>
|
||||
</select>
|
||||
<div th:if="${#fields.hasErrors('categoryId')}" th:errors="*{categoryId}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="id" class="form-label">ID</label>
|
||||
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="title">Название книги</label>
|
||||
<input id="title" th:field="*{title}" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('title')}" th:errors="*{title}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="author">Автор</label>
|
||||
<input id="author" th:field="*{author}" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('author')}" th:errors="*{author}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="price">Цена</label>
|
||||
<input id="price" th:field="*{price}" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('price')}" th:errors="*{price}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="description">Описание книги</label>
|
||||
<textarea th:field="*{description}" class="form-control" id="description" rows="3"></textarea>
|
||||
<div th:if="${#fields.hasErrors('description')}" th:errors="*{description}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="annotation">Аннотация</label>
|
||||
<textarea th:field="*{annotation}" class="form-control" id="annotation" rows="3"></textarea>
|
||||
<div th:if="${#fields.hasErrors('annotation')}" th:errors="*{annotation}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<p class="mb-3">
|
||||
Xарактеристики:
|
||||
</p>
|
||||
<div class="mb-4 border border-1 border-secondary p-2">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="bookCode">Код книги</label>
|
||||
<input th:field="*{bookCode}" id="bookCode" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('bookCode')}" th:errors="*{bookCode}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="publisher">Издательство</label>
|
||||
<input th:field="*{publisher}" id="publisher" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('publisher')}" th:errors="*{publisher}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="series">Серия</label>
|
||||
<input th:field="*{series}" id="series" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('series')}" th:errors="*{series}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="publicationYear">Год издания</label>
|
||||
<input th:field="*{publicationYear}" id="publicationYear" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('publicationYear')}" th:errors="*{publicationYear}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="pagesNum">Количество страниц</label>
|
||||
<input th:field="*{pagesNum}" id="pagesNum" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('pagesNum')}" th:errors="*{pagesNum}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="size">Размер</label>
|
||||
<input th:field="*{size}" id="size" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('size')}" th:errors="*{size}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="coverType">Тип обложки</label>
|
||||
<input th:field="*{coverType}" id="coverType" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('coverType')}" th:errors="*{coverType}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="circulation">Тираж</label>
|
||||
<input th:field="*{circulation}" id="circulation" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('circulation')}" th:errors="*{circulation}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="form-label" for="weight">Вес, г</label>
|
||||
<input th:field="*{weight}" id="weight" class="form-control" type="number">
|
||||
<div th:if="${#fields.hasErrors('weight')}" th:errors="*{weight}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="cover">Обложка книги</label>
|
||||
<input type="file" class="form-control" name="cover" id="cover">
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center mb-5">
|
||||
<button class="btn btn-primary w-50 rounded-5 edit-btn" type="submit" id="add-btn">Сохранить книгу</button>
|
||||
<a class="btn btn-secondary w-25 mt-4 edit-btn" th:href="@{/admin/book(page=${page}, categoryId=${categoryId})}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
89
src/main/resources/templates/book.html
Normal file
@ -0,0 +1,89 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (книги)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<th:block th:switch="${items.size()}">
|
||||
<h2 class="mt-4 text-center" th:case="0">Данные отсутствуют</h2>
|
||||
<th:block th:case="*">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mt-4 px-0">
|
||||
<div class="block d-flex justify-content-center fs-2 fw-bold mb-3 mb-sm-4" id="admin-title">
|
||||
Книги
|
||||
</div>
|
||||
</div>
|
||||
<form th:action="@{/admin/book}" method="get" class="row mb-4">
|
||||
<div class="col-sm-10">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<select th:name="filter" id="filter" class="form-select">
|
||||
<option selected value="">Фильтр по категории</option>
|
||||
<option th:each="category : ${categories}" th:value="${category.id}" th:selected="${category.id==filter}">
|
||||
[[${category.name}]]
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary col-sm-2">Показать</button>
|
||||
</form>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block table-responsive">
|
||||
<table class="table table-hover table-bordered align-middle">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Название книги</th>
|
||||
<th scope="col">Автор</th>
|
||||
<th scope="col">Цена</th>
|
||||
<th scope="col">Категория каталога</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="table-group-divider">
|
||||
<tr th:each="book : ${items}">
|
||||
<th scope="row" th:text="${book.id}"></th>
|
||||
<td th:text="${book.title}"></td>
|
||||
<td th:text="${book.author}"></td>
|
||||
<td th:text="${#numbers.formatDecimal(book.price, 1, 2)}"></td>
|
||||
<td th:text="${book.categoryName}"></td>
|
||||
<td>
|
||||
<form th:action="@{/admin/book/edit/{id}(id=${book.id})}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<button type="submit" class="btn btn-primary w-100">Редактировать</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form th:action="@{/admin/book/delete/{id}(id=${book.id})}" method="post">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<button type="submit" class="btn btn-primary w-100"
|
||||
onclick="return confirm('Вы уверены?')">Удалить</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block mb-4">
|
||||
<a class="btn btn-primary" th:href="@{/admin/book/edit/(page=${page}, filter=${filter})}">Добавить книгу</a>
|
||||
</div>
|
||||
</div>
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'admin/book'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter=${filter},
|
||||
searchInfo='') }" />
|
||||
</div>
|
||||
</th:block>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
162
src/main/resources/templates/cart.html
Normal file
@ -0,0 +1,162 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Корзина</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass=''">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 mb-1">
|
||||
<div class="col-12 mb-3 mb-sm-4 mt-0 px-0">
|
||||
<div class="block d-flex justify-content-center lh-1" id="cart-title">
|
||||
Моя корзина
|
||||
</div>
|
||||
</div>
|
||||
<h2 th:if="${#lists.isEmpty(cart)}" class="col-12 mb-3">Товары отсутствуют.</h2>
|
||||
|
||||
<th:block th:if="${not #lists.isEmpty(cart)}">
|
||||
<div class="col-8 px-0">
|
||||
<div class="block d-flex align-items-end lh-1" id="cart-items-num-text">
|
||||
В корзине [[${count}]] [[${linesText}]]:
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-4 d-flex justify-content-end px-0">
|
||||
<div class="block align-self-end">
|
||||
<form action="#" th:action="@{/cart/clear}" method="post">
|
||||
<button type="submit"
|
||||
class="cart-button-remove d-flex justify-content-end align-items-end lh-1 border-0 bg-white pe-0"
|
||||
onclick="return confirm('Вы уверены?')">
|
||||
<img th:src="@{/trash.png}" class="trash-icon me-sm-2" alt="trash" width="24" height="24" />
|
||||
Удалить все
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<th:block th:each="cartItem : ${cart}">
|
||||
<div class="col-1 border-top border-black pt-3 d-none d-sm-block">
|
||||
<div class="block">
|
||||
<img th:src="@{${cartItem.book.image != null && !#strings.isEmpty(cartItem.book.image) ? cartItem.book.image : '/placeholder_400_600.png'}}"
|
||||
class="cart-book-cover me-3" alt="cart-book-cover-1" width="88" height="138" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 pt-3 border-top border-black d-none d-sm-block">
|
||||
<div class="cart-book-description block d-flex flex-column justify-content-start ms-5 ms-lg-4 ms-xl-0 ps-0 ps-sm-2 ps-md-0 ps-xl-3 ps-xxl-0">
|
||||
<p class="cart-book-description-title mb-2">[[${cartItem.book.title}]]</p>
|
||||
<p class="cart-book-description-author">[[${cartItem.book.author}]]</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-3 pt-2 border-top border-black d-none d-sm-block">
|
||||
<div class="block d-flex align-items-start justify-content-end">
|
||||
<form action="#" th:action="@{/cart/decrease?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="button-minus border border-end-0 rounded-start bg-white">
|
||||
–
|
||||
</button>
|
||||
</form>
|
||||
<label class="cart-input-label">
|
||||
<input readonly type="tel" class="cart-input h-100 w-100 border text-center p-0" placeholder="1" th:value="${cartItem.count}" />
|
||||
</label>
|
||||
<form action="#" th:action="@{/cart/increase?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="button-plus border border-start-0 rounded-end bg-white">
|
||||
+
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-2 pt-3 border-top border-black d-none d-sm-block">
|
||||
<div class="block d-flex flex-column align-items-end h-100">
|
||||
<p class="cart-price">[[${#numbers.formatDecimal(cartItem.book.price, 0, 'COMMA', 0, 'POINT')}]] р.</p>
|
||||
<p class="cart-price-count text-secondary mt-3">
|
||||
[[${#numbers.formatDecimal(cartItem.book.price, 0, 'COMMA', 0, 'POINT')}]]
|
||||
<span> * </span>
|
||||
[[${cartItem.count}]]
|
||||
<span> = </span>
|
||||
[[${#numbers.formatDecimal(cartItem.book.price * cartItem.count, 0, 'COMMA', 0, 'POINT')}]] р.
|
||||
</p>
|
||||
<div class="flex-grow-1"></div>
|
||||
<form action="#" th:action="@{/cart/clear?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="cart-button-remove d-flex align-items-end lh-1 border-0 bg-white pe-0"
|
||||
onclick="return confirm('Вы уверены?')">
|
||||
<img th:src="@{/trash.png}" class="trash-icon me-2" alt="trash" width="24" height="24" />
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-2 border-top border-black pt-3 d-sm-none">
|
||||
<div class="block">
|
||||
<img th:src="@{${cartItem.book.image != null && !#strings.isEmpty(cartItem.book.image) ? cartItem.book.image : '/placeholder_400_600.png'}}"
|
||||
class="cart-book-cover me-3" alt="cart-book-cover" width="88" height="138" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-10 pt-3 border-top border-black d-sm-none">
|
||||
<div class="block ms-4">
|
||||
<p class="cart-book-description-title mb-2">[[${cartItem.book.title}]]</p>
|
||||
<p class="cart-book-description-author mb-2">[[${cartItem.book.author}]]</p>
|
||||
<div class="d-flex mb-2">
|
||||
<p class="cart-price me-3">[[${#numbers.formatDecimal(cartItem.book.price, 0, 'COMMA', 0, 'POINT')}]] р.</p>
|
||||
<p class="cart-price-count text-secondary text-center lh-sm mt-1" id="mobile-price-count">
|
||||
[[${#numbers.formatDecimal(cartItem.book.price, 0, 'COMMA', 0, 'POINT')}]]
|
||||
<span> * </span>
|
||||
[[${cartItem.count}]]
|
||||
<span> = </span>
|
||||
[[${#numbers.formatDecimal(cartItem.book.price * cartItem.count, 0, 'COMMA', 0, 'POINT')}]] р.
|
||||
</p>
|
||||
</div>
|
||||
<div class="d-flex align-items-center">
|
||||
<form action="#" th:action="@{/cart/decrease?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="button-minus border border-end-0 rounded-start bg-white">
|
||||
–
|
||||
</button>
|
||||
</form>
|
||||
<label class="cart-input-label">
|
||||
<input readonly type="tel" class="cart-input h-100 w-100 border text-center" placeholder="1"
|
||||
th:value="${cartItem.count}" />
|
||||
</label>
|
||||
<form action="#" th:action="@{/cart/increase?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="button-plus border border-start-0 rounded-end bg-white">
|
||||
+
|
||||
</button>
|
||||
</form>
|
||||
<div class="flex-grow-1"></div>
|
||||
<form action="#" th:action="@{/cart/clear?bookId={bookId}(bookId=${cartItem.book.id})}" method="post">
|
||||
<button type="submit" class="cart-button-remove d-flex align-items-end lh-1 border-0 bg-white pe-0"
|
||||
onclick="return confirm('Вы уверены?')">
|
||||
<img th:src="@{/trash.png}" class="trash-icon me-2" alt="trash" width="24" height="24" />
|
||||
Удалить
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
|
||||
<div class="col-12 pt-3 border-top border-black px-0">
|
||||
<div class="block d-flex justify-content-end align-items-end lh-1" id="cart-final-price">
|
||||
<span class="me-4" id="cart-final-price-text">
|
||||
Итого:
|
||||
</span>
|
||||
<span id="cart-final-price-value"> [[${#numbers.formatDecimal(sum, 1, 2)}]] р. </span>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
|
||||
<div class="col-12 px-0">
|
||||
<div class="block d-flex justify-content-end">
|
||||
<button th:if="${#lists.isEmpty(cart)}" class="btn rounded-5" id="cart-btn-checkout" disabled>
|
||||
Оформить заказ
|
||||
</button>
|
||||
<form th:if="${not #lists.isEmpty(cart)}" action="#" th:action="@{/cart/save}" method="post">
|
||||
<button type="submit" class="btn rounded-5" id="cart-btn-checkout" onclick="return confirm('Вы уверены?')">
|
||||
Оформить заказ
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
32
src/main/resources/templates/catalog-mobile.html
Normal file
@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Каталог</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='', mainClass='justify-content-center my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col-12 ps-0 mt-0 bg-white border border-3" id="catalog-categories-mobile">
|
||||
<div class="block d-flex flex-column justify-content-center p-2 h-100">
|
||||
<p class="mb-4" id="catalog-categories-mobile-title">
|
||||
Категории
|
||||
</p>
|
||||
<ul class="list-unstyled ps-0 mb-4 d-flex flex-column gap-3 flex-grow-1" id="catalog-categories-mobile-list">
|
||||
<li>
|
||||
<a th:href="@{/catalog}">Все книги</a>
|
||||
</li>
|
||||
<th:block th:each="category : ${categories}">
|
||||
<li>
|
||||
<a th:href="@{/catalog/{id}(id=${category.id})}" th:text="${category.name}"></a>
|
||||
</li>
|
||||
</th:block>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
155
src/main/resources/templates/catalog.html
Normal file
@ -0,0 +1,155 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Каталог</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='h-100', mainClass='justify-content-center my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 flex-grow-1">
|
||||
<div class="col-2 d-none d-md-block ps-0 mt-0 bg-white border border-3 border-top-0 border-bottom-0" id="catalog-categories">
|
||||
<div class="block d-flex flex-column justify-content-center p-2 h-100">
|
||||
<p class="mb-4 mt-2" id="catalog-categories-title">
|
||||
Категории
|
||||
</p>
|
||||
<ul class="list-unstyled ps-0 mb-4 d-flex flex-column gap-3 flex-grow-1" id="catalog-categories-list">
|
||||
<li th:class="${'Все книги' eq activeName} ? 'active-category' : ''">
|
||||
<a th:href="@{/catalog}">Все книги</a>
|
||||
</li>
|
||||
<th:block th:each="category : ${categories}">
|
||||
<li th:class="${category.name eq activeName} ? 'active-category' : ''">
|
||||
<a th:href="@{/catalog/{id}(id=${category.id})}" th:text="${category.name}"></a>
|
||||
</li>
|
||||
</th:block>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 col-md-10 d-flex flex-column bg-white mt-0 pt-2 pt-lg-3">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mb-3 mb-lg-5 px-0 d-md-none">
|
||||
<div class="block d-flex lh-1" id="catalog-section-navigation">
|
||||
<a th:href="@{/сatalog-mobile}" class="me-2 text-decoration-none">
|
||||
Каталог
|
||||
</a>
|
||||
<span class="text-secondary me-2"> > </span>
|
||||
<a th:if="${'Все книги' eq activeName}" th:href="@{/catalog}" class="text-decoration-none">
|
||||
[[${activeName}]]
|
||||
</a>
|
||||
<a th:if="${'Все книги' != activeName}" th:href="@{/catalog/{id}(id=${activeId})}" class="text-decoration-none">
|
||||
[[${activeName}]]
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 mb-3 mb-lg-4 px-0">
|
||||
<div class="block d-flex justify-content-center lh-1" id="catalog-title">
|
||||
<div>[[${activeName}]]</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 mb-3 mb-lg-5 gx-0">
|
||||
<div class="block">
|
||||
<form class="row" th:if="${'Все книги' eq activeName}" th:action="@{/catalog}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<select th:name="filter" class="form-select border-black сol-sm-10 me-sm-2" id="catalog-select">
|
||||
<option value="new" th:selected="${filter == 'new'}">Сначала новые</option>
|
||||
<option value="cheap" th:selected="${filter == 'cheap'}">Сначала дешевые</option>
|
||||
<option value="expensive" th:selected="${filter == 'expensive'}">Сначала дорогие</option>
|
||||
</select>
|
||||
<button type="submit" class="btn astext col-sm-2 ms-sm-2 text-start">Показать.</button>
|
||||
</form>
|
||||
<form class="row" th:if="${'Все книги' != activeName}" th:action="@{/catalog/{id}(id=${activeId})}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<select th:name="filter" class="form-select border-black сol-sm-10 me-sm-2" id="catalog-select">
|
||||
<option value="new" th:selected="${filter == 'new'}">Сначала новые</option>
|
||||
<option value="cheap" th:selected="${filter == 'cheap'}">Сначала дешевые</option>
|
||||
<option value="expensive" th:selected="${filter == 'expensive'}">Сначала дорогие</option>
|
||||
</select>
|
||||
<button type="submit" class="btn astext col-sm-2 ms-sm-2 text-start">Показать.</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-6 col-md-4 col-lg-3 mt-4" th:each="book : ${items}">
|
||||
<div class="block d-flex flex-column h-100">
|
||||
<div class="d-flex justify-content-center mb-4">
|
||||
<a th:href="@{/product-card/{id}(id=${book.id})}">
|
||||
<img th:src="@{${book.image != null && !#strings.isEmpty(book.image) ? book.image : '/placeholder_400_600.png'}}"
|
||||
class="catalog-book-cover" alt="book-cover-catalog" width="155" height="245" />
|
||||
</a>
|
||||
</div>
|
||||
<div class="catalog-book-description d-flex flex-column align-items-start">
|
||||
<p class="catalog-price mb-3">
|
||||
[[${#numbers.formatDecimal(book.price, 0, 'COMMA', 0, 'POINT')}]] ₽
|
||||
</p>
|
||||
<p class="catalog-book-title mb-3">
|
||||
[[${book.title != null ? book.title : ''}]]
|
||||
</p>
|
||||
<p class="catalog-author mb-3">
|
||||
[[${book.author != null ? book.author : ''}]]
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex-grow-1"></div>
|
||||
<div class="catalog-btn-checkout-div d-flex justify-content-start" sec:authorize="isAnonymous()">
|
||||
<button class="catalog-bth-checkout btn rounded-5 px-3"
|
||||
onclick="return alert('Пожалуйста, войдите в свой аккаунт или зарегистрируйте новый!')">
|
||||
В корзину
|
||||
</button>
|
||||
</div>
|
||||
<div class="catalog-btn-checkout-div d-flex justify-content-start" sec:authorize="isAuthenticated()">
|
||||
<button type="button" class="catalog-bth-checkout btn rounded-5 px-3 btn-info"
|
||||
th:if="${cart.containsKey(book.id)}" disabled>
|
||||
Уже в корзине
|
||||
</button>
|
||||
<th:block th:if="${'Все книги' eq activeName}">
|
||||
<form th:if="${not cart.containsKey(book.id)}" th:action="@{/catalog}" method="post">
|
||||
<input type="hidden" th:name="bookId" th:value="${book.id}">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<button type="submit" class="catalog-bth-checkout btn rounded-5 px-3">
|
||||
В корзину
|
||||
</button>
|
||||
</form>
|
||||
</th:block>
|
||||
<th:block th:if="${'Все книги' != activeName}">
|
||||
<form th:if="${not cart.containsKey(book.id)}" th:action="@{/catalog/{id}(id=${activeId})}" method="post">
|
||||
<input type="hidden" th:name="bookId" th:value="${book.id}">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<button type="submit" class="catalog-bth-checkout btn rounded-5 px-3">
|
||||
В корзину
|
||||
</button>
|
||||
</form>
|
||||
</th:block>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<th:block sec:authorize="hasAnyRole('ADMIN', 'SUPERADMIN')">
|
||||
<a th:href="@{/admin}" class="text-dark fw-bolder mt-5 mb-3 text-decoration-none">
|
||||
Панель администратора.
|
||||
</a>
|
||||
</th:block>
|
||||
<div class="d-flex flex-grow-1"></div>
|
||||
|
||||
<div th:if="${'Все книги' eq activeName}">
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'catalog'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter=${filter},
|
||||
searchInfo='') }" />
|
||||
</div>
|
||||
|
||||
<div th:if="${'Все книги' != activeName}">
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=@{catalog/{id}(id=${activeId})},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter=${filter},
|
||||
searchInfo='') }" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
32
src/main/resources/templates/category-edit.html
Normal file
@ -0,0 +1,32 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (категории)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row justify-content-center">
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6" action="#"
|
||||
th:action="@{/admin/category/edit/{id}(id=${category.id})}" th:object="${category}" method="post" >
|
||||
<div class="mb-4 mt-4">
|
||||
<label for="id" class="form-label">ID</label>
|
||||
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="form-label" for="name">Название категории</label>
|
||||
<input id="name" th:field="*{name}" class="form-control" type="text">
|
||||
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center mb-5">
|
||||
<button class="btn btn-primary w-50 rounded-5 edit-btn" type="submit" id="add-btn">Сохранить категорию</button>
|
||||
<a class="btn btn-secondary w-25 mt-4 edit-btn"
|
||||
href="/admin/category">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
62
src/main/resources/templates/category.html
Normal file
@ -0,0 +1,62 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (категории)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<th:block th:switch="${categories.size()}">
|
||||
<h2 class="mt-4 text-center" th:case="0">Данные отсутствуют</h2>
|
||||
<th:block th:case="*">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mt-4 px-0">
|
||||
<div class="block d-flex justify-content-center fs-2 fw-bold mb-3 mb-sm-4" id="admin-title">
|
||||
Категории
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block table-responsive">
|
||||
<table class="table table-hover table-bordered align-middle">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Название категории</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="table-group-divider">
|
||||
<tr th:each="category : ${categories}">
|
||||
<th scope="row" th:text="${category.id}"></th>
|
||||
<td th:text="${category.name}"></td>
|
||||
<td>
|
||||
<form th:action="@{/admin/category/edit/{id}(id=${category.id})}" method="get">
|
||||
<button type="submit" class="btn btn-primary w-100">Редактировать</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form th:action="@{/admin/category/delete/{id}(id=${category.id})}" method="post">
|
||||
<button type="submit" class="btn btn-primary w-100"
|
||||
onclick="return confirm('Вы уверены?')">Удалить</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block mb-4">
|
||||
<a class="btn btn-primary" href="/admin/category/edit/">Добавить категорию</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</th:block>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
70
src/main/resources/templates/contacts.html
Normal file
@ -0,0 +1,70 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Контакты</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='justify-content-center'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row">
|
||||
<div class="col-lg-5 px-0 me-lg-5">
|
||||
<div class="block d-flex flex-column align-items-start">
|
||||
<p class="mb-4 mb-sm-5 lh-1" id="contacts-title">
|
||||
Контакты
|
||||
</p>
|
||||
<div class="contacts-item d-flex mb-5">
|
||||
<img src="phone-call.png" class="contacts-icon me-4" alt="phone-call" width="88" height="88">
|
||||
<div class="d-flex flex-column">
|
||||
<p class="contacts-item-main-info mb-3">
|
||||
+7 927 818-61-60
|
||||
</p>
|
||||
<p class="contacts-item-clarification">
|
||||
Служба клиентской поддержки
|
||||
c 8:00 - 22:00 (Мск)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="contacts-item d-flex mb-5">
|
||||
<img src="email.png" class="contacts-icon me-4" alt="email" width="88" height="88">
|
||||
<div class="d-flex flex-column justify-content-center">
|
||||
<p class="contacts-item-main-info mb-3">
|
||||
readroom@mail.ru
|
||||
</p>
|
||||
<p class="contacts-item-clarification">
|
||||
Электронный адрес компании
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="contacts-item d-flex mb-3">
|
||||
<img src="skype.png" class="contacts-icon me-4" alt="skype" width="88" height="88">
|
||||
<div class="d-flex flex-column justify-content-center">
|
||||
<p class="contacts-item-main-info">
|
||||
Пообщайтесь с сотрудниками по видеосвязи
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<a href="/" class="mb-3 mb-sm-4 text-decoration-none" id="skype-link">
|
||||
Перейти в Skype
|
||||
</a>
|
||||
<div class="mb-4 mb-sm-5 mt-2 mb-lg-0">
|
||||
<p class="mb-3" id="contacts-address">
|
||||
Наш адрес:
|
||||
</p>
|
||||
<p id="contacts-address-value">
|
||||
432064, Россия, г. Ульяновск, проспект Врача Сурова, 2А
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col px-0 align-self-center">
|
||||
<div class="block d-flex justify-content-center justify-content-lg-end">
|
||||
<img src="map.png" class="border border-black border-2 img-fluid h-100" alt="map" width="665"
|
||||
height="689">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
153
src/main/resources/templates/default.html
Normal file
@ -0,0 +1,153 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org"
|
||||
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
|
||||
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title layout:title-pattern="$LAYOUT_TITLE - $CONTENT_TITLE">Читай-комната</title>
|
||||
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
|
||||
<script type="text/javascript" src="/webjars/bootstrap/5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/5.3.3/dist/css/bootstrap.min.css" />
|
||||
<link rel="stylesheet" href="/webjars/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" />
|
||||
<link rel="stylesheet" href="/css/style.css" />
|
||||
</head>
|
||||
|
||||
<body class="d-flex flex-column min-vh-100" th:classappend="${bodyClass}">
|
||||
<header class="w-100 position-sticky top-0 z-3">
|
||||
<nav class="navbar navbar-expand-lg navbar-light">
|
||||
<div class="container-md">
|
||||
<a class="navbar-brand me-lg-5 d-flex align-items-center" href="/" id="logo">
|
||||
<img th:src="@{/logo.png}" alt="logo" class="me-2">
|
||||
Читай-комната
|
||||
</a>
|
||||
<button class="navbar-toggler ms-auto" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
|
||||
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
<div class="navbar-collapse collapse" id="navbarNav">
|
||||
<ul class="navbar-nav align-items-lg-center justify-content-lg-start w-100" th:with="activeLink=${#objects.nullSafe(servletPath, '')}">
|
||||
<li class="header-link nav-item ms-lg-2 me-lg-3">
|
||||
<a class="nav-link" href="/"
|
||||
th:classappend="${activeLink == '/' ? 'active' : ''}">
|
||||
Главная
|
||||
</a>
|
||||
</li>
|
||||
<li class="header-link nav-item me-lg-3">
|
||||
<a class="nav-link" href="/catalog"
|
||||
th:classappend="${activeLink.startsWith('/catalog') ? 'active' : ''}">
|
||||
Каталог
|
||||
</a>
|
||||
</li>
|
||||
<li class="header-link nav-item me-lg-5" id="header-contacts">
|
||||
<a class="nav-link" href="/contacts"
|
||||
th:classappend="${activeLink.startsWith('/contacts') ? 'active' : ''}">
|
||||
Контакты
|
||||
</a>
|
||||
</li>
|
||||
<div class="flex-grow-1 me-lg-4" id="header-search">
|
||||
<form class="h-25" th:action="@{/search}" method="get">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input class="form-control" th:name="searchInfo" th:value="${searchInfo != null ? searchInfo : ''}" type="search"
|
||||
placeholder="Я ищу..." aria-label="Search" id="search-bar">
|
||||
</form>
|
||||
</div>
|
||||
<th:block sec:authorize="isAuthenticated()" th:with="userName=${#authentication.name}">
|
||||
<a class="nav-link m-0 pe-0" href="/profile"
|
||||
th:classappend="${activeLink.startsWith('/profile') ? 'active' : ''}">
|
||||
[[${userName}]]
|
||||
</a>
|
||||
<p class="header-part d-none d-lg-block"> / </p>
|
||||
<form th:action="@{/logout}" method="post">
|
||||
<button type="submit" class="header-part astext text-white text-start me-lg-3" onclick="return confirm('Вы уверены?')">Выйти</button>
|
||||
</form>
|
||||
</th:block>
|
||||
<th:block sec:authorize="isAnonymous()">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/login"
|
||||
th:classappend="${activeClass}">
|
||||
Вход
|
||||
</a>
|
||||
</li>
|
||||
<p class="d-none d-lg-block">
|
||||
/
|
||||
</p>
|
||||
<li class="nav-item me-lg-3">
|
||||
<a class="nav-link" href="/signup"
|
||||
th:classappend="${activeLink.startsWith('/signup') ? 'active' : ''}">
|
||||
Регистрация
|
||||
</a>
|
||||
</li>
|
||||
</th:block>
|
||||
<li class="nav-item position-relative">
|
||||
<a class="nav-link pe-lg-0" href="/cart"
|
||||
th:classappend="${activeLink.startsWith('/cart') ? 'active-icon' : ''}">
|
||||
<img th:src="@{/card.png}" alt="cart" th:attr="width=${activeLink.startsWith('/cart') ? '35' : '30'},
|
||||
height=${activeLink.startsWith('/cart') ? '40' : '35'}" id="cart-icon">
|
||||
</a>
|
||||
<span th:if="${totalCart > 0}" class="position-absolute" id="cart-link-count">[[${totalCart}]]</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="container-md d-flex flex-column flex-grow-1" th:classappend="${mainClass}" layout:fragment="content">
|
||||
</main>
|
||||
<footer class="footer flex-shrink-0">
|
||||
<div class="container-md" id="footer-container">
|
||||
<div class="row d-flex align-items-center gy-3 gy-lg-0 gx-0" id="footer-row">
|
||||
<div class="col-md-6 col-lg-4">
|
||||
<div class="block d-flex justify-content-center justify-content-md-start" id="footer-copyright">
|
||||
© И. А. Родионов, [[${#dates.year(#dates.createNow())}]].
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 col-lg-3">
|
||||
<div class="block d-flex align-items-center justify-content-center justify-content-md-end">
|
||||
<img th:src="@{/telephone-call.png}" class="me-2" alt="telephone-call" width="32" height="32">
|
||||
<p id="footer-phone-number-text">
|
||||
+7 927 818-61-60
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-12 col-lg-5 mb-3 mb-lg-0">
|
||||
<div class="block d-flex align-items-center justify-content-center justify-content-lg-end">
|
||||
<p class="me-3" id="footer-social-media-text">
|
||||
Мы в соцсетях:
|
||||
</p>
|
||||
<a class="me-3" href="/">
|
||||
<img th:src="@{/vk.png}" alt="vk" width="32" height="32">
|
||||
</a>
|
||||
<a class="me-3" href="/">
|
||||
<img th:src="@{/youtube.png}" alt="youtube" width="32" height="32">
|
||||
</a>
|
||||
<a class="me-3" href="/">
|
||||
<img th:src="@{/telegram.png}" alt="telegram" width="32" height="32">
|
||||
</a>
|
||||
<a href="/">
|
||||
<img th:src="@{/odnoklassniki.png}" alt="odnoklassniki" width="32" height="32">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
<script th:inline="javascript">
|
||||
$(document).ready(function () {
|
||||
$('#search-bar').on('keypress', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
const searchValue = $(this).val().trim();
|
||||
if (searchValue !== '') {
|
||||
$(this).closest('form').submit();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
37
src/main/resources/templates/error.html
Normal file
@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Ошибка</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass=''">
|
||||
<main layout:fragment="content">
|
||||
<ul class="list-group mb-2">
|
||||
<th:block th:if="${#strings.isEmpty(message)}">
|
||||
<li class="list-group-item">
|
||||
Неизвестная ошибка
|
||||
</li>
|
||||
</th:block>
|
||||
<th:block th:if="${not #strings.isEmpty(message)}">
|
||||
<li class="list-group-item">
|
||||
<strong>Ошибка:</strong> [[${message}]]
|
||||
</li>
|
||||
</th:block>
|
||||
<th:block th:if="${not #strings.isEmpty(url)}">
|
||||
<li class="list-group-item">
|
||||
<strong>Адрес:</strong> [[${url}]]
|
||||
</li>
|
||||
<li class="list-group-item">
|
||||
<strong>Класс исключения:</strong> [[${exception}]]
|
||||
</li>
|
||||
<li class="list-group-item">
|
||||
[[${method}]] ([[${file}]]:[[${line}]])
|
||||
</li>
|
||||
</th:block>
|
||||
</ul>
|
||||
<a class="btn btn-primary button-fixed-width" href="/">На главную</a>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
47
src/main/resources/templates/login.html
Normal file
@ -0,0 +1,47 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Вход на сайт</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0', activeClass='active'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 justify-content-center">
|
||||
<div class="col-12 mt-4">
|
||||
<div class="block d-flex justify-content-center mb-3 mb-sm-4" id="login-title">
|
||||
Вход на сайт
|
||||
</div>
|
||||
</div>
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6 m-0 mt-2 mt-sm-3 d-flex flex-column gap-2" action="#" th:action="@{/login}" method="post">
|
||||
<div th:if="${param.error}" class="alert alert-danger mb-3 mb-sm-4 text-center">
|
||||
Неверный логин или пароль
|
||||
</div>
|
||||
<div th:if="${param.logout}" class="alert alert-success mb-3 mb-sm-4 text-center">
|
||||
Выход успешно произведен
|
||||
</div>
|
||||
<div th:if="${param.signup}" class="alert alert-success mb-3 mb-sm-4 text-center">
|
||||
Пользователь успешно создан
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="text" id="username" name="username" placeholder="Имя пользователя" class="form-control w-75 border-black login-input-email"
|
||||
required minlength="3" maxlength="20">
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="password" id="password" name="password" placeholder="Пароль" class="form-control w-75 border-black login-input-password"
|
||||
required minlength="3" maxlength="20">
|
||||
</div>
|
||||
<div class="form-check mb-3 mb-sm-4">
|
||||
<input class="form-check-input" type="checkbox" id="remember-me" name="remember-me" checked>
|
||||
<label class="form-check-label login-input-remember fw-bolder" for="remember-me">Запомнить меня.</label>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center">
|
||||
<button class="btn btn-primary w-50 rounded-5 login-btn mb-3" type="submit">Войти</button>
|
||||
<a class="btn btn-secondary w-25 rounded-5 login-btn" href="/signup" >Регистрация</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
93
src/main/resources/templates/main-page.html
Normal file
@ -0,0 +1,93 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Главная страница</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='', mainClass='justify-content-center'">
|
||||
<main layout:fragment="content">
|
||||
|
||||
<div class="row bg-white pb-1 mb-3 rounded-3 gy-3">
|
||||
<div class="col-12 ms-2 mt-1">
|
||||
<div class="main-page-section-title block d-flex align-items-end">
|
||||
<img th:src="@{fire.png}" class="me-2" alt="fire" width="25" height="30" id="fire-icon">
|
||||
<p class="main-page-section-title-text lh-1 m-0">
|
||||
Горячие новинки
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div th:each="novelty : ${novelties}" class="col-6 col-md-4 col-lg-2">
|
||||
<div class="block d-flex flex-column">
|
||||
<div class="d-flex justify-content-center">
|
||||
<a th:href="@{/product-card/{id}(id=${novelty.id})}">
|
||||
<img th:src="@{${novelty.image != null && !#strings.isEmpty(novelty.image) ? novelty.image : 'placeholder_400_600.png'}}"
|
||||
class="main-page-book-cover" alt="book-cover-novelties" width="100" height="152">
|
||||
</a>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center align-items-md-start">
|
||||
<p class="main-page-price" th:text="${#numbers.formatDecimal(novelty.price, 0, 'COMMA', 0, 'POINT')} + ' ₽'"></p>
|
||||
<p class="main-page-book-title" th:text="${novelty.title}"></p>
|
||||
<p class="main-page-author" th:text="${novelty.author}"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row bg-white pb-1 mb-3 rounded-3 gy-3">
|
||||
<div class="col-12 ms-2 mt-1">
|
||||
<div class="main-page-section-title block d-flex align-items-end">
|
||||
<p class="main-page-section-title-text lh-1 m-0">
|
||||
Книги по акциям
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div th:each="promotion : ${promotions}" class="col-6 col-md-4 col-lg-2">
|
||||
<div class="block d-flex flex-column">
|
||||
<div class="d-flex justify-content-center">
|
||||
<a th:href="@{/product-card/{id}(id=${promotion.id})}">
|
||||
<img th:src="@{${promotion.image != null && !#strings.isEmpty(promotion.image) ? promotion.image : 'placeholder_400_600.png'}}"
|
||||
class="main-page-book-cover" alt="book-cover-promotions" width="100" height="152">
|
||||
</a>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center align-items-md-start">
|
||||
<p class="main-page-price" th:text="${#numbers.formatDecimal(promotion.price, 0, 'COMMA', 0, 'POINT')} + ' ₽'"></p>
|
||||
<p class="main-page-book-title" th:text="${promotion.title}"></p>
|
||||
<p class="main-page-author" th:text="${promotion.author}"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row bg-white pb-1 rounded-3 gy-3">
|
||||
<div class="col-12 ms-2 mt-1">
|
||||
<div class="main-page-section-title block d-flex align-items-end">
|
||||
<p class="main-page-section-title-text lh-1 m-0">
|
||||
Выбор редакции
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div th:each="recommendation : ${recommendations}" class="col-6 col-md-4 col-lg-2">
|
||||
<div class="block d-flex flex-column">
|
||||
<div class="d-flex justify-content-center">
|
||||
<a th:href="@{/product-card/{id}(id=${recommendation.id})}">
|
||||
<img th:src="@{${recommendation.image != null && !#strings.isEmpty(recommendation.image) ? recommendation.image : 'placeholder_400_600.png'}}"
|
||||
class="main-page-book-cover" alt="book-cover-recommendations" width="100" height="152">
|
||||
</a>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center align-items-md-start">
|
||||
<p class="main-page-price" th:text="${#numbers.formatDecimal(recommendation.price, 0, 'COMMA', 0, 'POINT')} + ' ₽'"></p>
|
||||
<p class="main-page-book-title" th:text="${recommendation.title}"></p>
|
||||
<p class="main-page-author" th:text="${recommendation.author}"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
44
src/main/resources/templates/order-check.html
Normal file
@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (заказы)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="ms-3 mt-3 me-3 w-75" th:object="${order}">
|
||||
<div class="mb-3">
|
||||
<label for="id" class="form-label">ID</label>
|
||||
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="date" class="form-label">Дата</label>
|
||||
<input type="text" th:field="*{date}" id="date" class="form-control">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="sum" class="form-label">Сумма</label>
|
||||
<input type="text" th:field="*{sum}" id="sum" class="form-control">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="count" class="form-label">Количество книг</label>
|
||||
<input type="text" th:field="*{count}" id="count" class="form-control">
|
||||
</div>
|
||||
<p class="mb-3">Товары в заказе</p>
|
||||
<th:block th:each="element : *{books}">
|
||||
<div class="mb-3 d-flex">
|
||||
<p class="align-self-center w-25 ms-3 me-5">[[${element.book.title}]] — [[${element.book.author}]]</p>
|
||||
<div class='d-flex align-self-center ms-auto me-4'>
|
||||
<p class="align-self-center me-2" style="color: #ABABAB">
|
||||
[[${#numbers.formatDecimal(element.book.price, 0, 'COMMA', 0, 'POINT')}]] ₽
|
||||
* [[${element.count}]] = </p>
|
||||
<p th:text="${#numbers.formatDecimal(element.book.price * element.count, 0, 'COMMA', 0, 'POINT') + ' ₽'}"
|
||||
class="align-self-center fs-4"></p>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
68
src/main/resources/templates/order.html
Normal file
@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (заказы)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<th:block th:switch="${items.size()}">
|
||||
<h2 class="mt-4 text-center" th:case="0">Данные отсутствуют</h2>
|
||||
<th:block th:case="*">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mt-4 px-0">
|
||||
<div class="block d-flex justify-content-center fs-2 fw-bold mb-3 mb-sm-4" id="admin-title">
|
||||
Заказы
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block table-responsive">
|
||||
<table class="table table-hover table-bordered align-middle">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Дата заказа</th>
|
||||
<th scope="col">Стоимость</th>
|
||||
<th scope="col">Количество книг</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="table-group-divider">
|
||||
<tr th:each="order : ${items}">
|
||||
<th scope="row" th:text="${order.id}"></th>
|
||||
<td th:text="${order.date}"></td>
|
||||
<td th:text="${#numbers.formatDecimal(order.sum, 1, 2)}"></td>
|
||||
<td th:text="${order.count}"></td>
|
||||
<td>
|
||||
<form th:action="@{/admin/order/check/{id}(id=${order.id})}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-primary w-100">Подробнее</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form th:action="@{/admin/order/delete/{id}(id=${order.id})}" method="post">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-primary w-100"
|
||||
onclick="return confirm('Вы уверены?')">Удалить</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'admin/order'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter='',
|
||||
searchInfo='') }" />
|
||||
</div>
|
||||
</th:block>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
51
src/main/resources/templates/pagination.html
Normal file
@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
|
||||
<body>
|
||||
<th:block th:fragment="pagination (url, totalPages, currentPage, filter, searchInfo)">
|
||||
<nav class="mt-3 mb-2 gx-0 table-responsive" th:if="${totalPages > 1}" th:with="
|
||||
maxPage=2,
|
||||
currentPage=${currentPage + 1}">
|
||||
<ul class="pagination justify-content-center" id="catalog-page-navigation"
|
||||
th:with="
|
||||
seqFrom=${currentPage - maxPage < 1 ? 1 : currentPage - maxPage},
|
||||
seqTo=${currentPage + maxPage > totalPages ? totalPages : currentPage + maxPage}">
|
||||
<th:block th:if="${currentPage > maxPage + 1}">
|
||||
<li class="page-item">
|
||||
<a class="page-link" aria-label="Previous"
|
||||
th:href="@{/{url}?page=0&filter={filter}&searchInfo={searchInfo}(url=${url}, filter=${filter}, searchInfo=${searchInfo})}">
|
||||
<span aria-hidden="true">«</span>
|
||||
</a>
|
||||
</li>
|
||||
<li class="page-item disabled">
|
||||
<span class="page-link" aria-label="Previous">
|
||||
<span aria-hidden="true">…</span>
|
||||
</span>
|
||||
</li>
|
||||
</th:block>
|
||||
<li class="page-item" th:each="page : ${#numbers.sequence(seqFrom, seqTo)}"
|
||||
th:classappend="${page == currentPage} ? 'active' : ''">
|
||||
<a class="page-link"
|
||||
th:href="@{/{url}?page={page}&filter={filter}&searchInfo={searchInfo}(url=${url}, page=${page - 1}, filter=${filter}, searchInfo=${searchInfo})}">
|
||||
<span th:text="${page}" />
|
||||
</a>
|
||||
</li>
|
||||
<th:block th:if="${currentPage < totalPages - maxPage}">
|
||||
<li class="page-item disabled">
|
||||
<span class="page-link" aria-label="Previous">
|
||||
<span aria-hidden="true">…</span>
|
||||
</span>
|
||||
</li>
|
||||
<li class="page-item">
|
||||
<a class="page-link" aria-label="Next"
|
||||
th:href="@{/{url}?page={page}&filter={filter}&searchInfo={searchInfo}(url=${url}, page=${totalPages - 1}, filter=${filter}, searchInfo=${searchInfo})}">
|
||||
<span aria-hidden="true">»</span>
|
||||
</a>
|
||||
</li>
|
||||
</th:block>
|
||||
</ul>
|
||||
</nav>
|
||||
</th:block>
|
||||
</body>
|
||||
|
||||
</html>
|
157
src/main/resources/templates/product-card.html
Normal file
@ -0,0 +1,157 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Карточка товара</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='justify-content-center'">
|
||||
<main layout:fragment="content">
|
||||
<th:block th:object="${book}">
|
||||
<div class="row gy-3">
|
||||
<div class="col-md-6 col-lg-3 mt-0 px-0">
|
||||
<div class="block d-flex justify-content-center justify-content-md-start">
|
||||
<img th:src="@{${book.image != null && !#strings.isEmpty(book.image) ? book.image : '/placeholder_400_600.png'}}"
|
||||
class="img-fluid" alt="book-cover-product-card" width="270" height="416" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6 col-lg-5 mt-5 mt-md-0 px-0">
|
||||
<div class="block d-flex flex-column align-items-center align-items-md-start ms-md-4">
|
||||
<p class="mb-2" id="product-card-book-name">
|
||||
[[${book.title != null ? book.title : 'Точных данных о названии нет'}]]
|
||||
</p>
|
||||
<p class="mb-4" id="product-card-author">
|
||||
[[${book.author != null ? book.author : 'Точных данных о авторе нет'}]]
|
||||
</p>
|
||||
<dl class="row gx-5 gy-2 text-center text-md-start" id="product-card-characteristics">
|
||||
<dt class="col-md-6 mt-0">Код товара</dt>
|
||||
<dd class="col-md-6 mt-0">[[${book.bookCode != null ? book.bookCode : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Издательство</dt>
|
||||
<dd class="col-md-6">[[${book.publisher != null ? book.publisher : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Серия</dt>
|
||||
<dd class="col-md-6">[[${book.series != null ? book.series : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Год издания</dt>
|
||||
<dd class="col-md-6">[[${book.publicationYear != null ? book.publicationYear : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Количество страниц</dt>
|
||||
<dd class="col-md-6">[[${book.pagesNum != null ? book.pagesNum : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Размер</dt>
|
||||
<dd class="col-md-6">[[${book.size != null ? book.size : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Тип обложки</dt>
|
||||
<dd class="col-md-6">[[${book.coverType != null ? book.coverType : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Тираж</dt>
|
||||
<dd class="col-md-6">[[${book.circulation != null ? book.circulation : 'Точных данных нет'}]]</dd>
|
||||
|
||||
<dt class="col-md-6">Вес, г</dt>
|
||||
<dd class="col-md-6">[[${book.weight != null ? book.weight : 'Точных данных нет'}]]</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-4 mt-0 px-0 d-none d-lg-block">
|
||||
<div class="block d-flex flex-column align-items-center align-items-lg-end">
|
||||
<div class="border border-secondary-subtle rounded-1 p-3" id="product-card-order-container">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<img th:src="@{/check.png}" class="me-4" alt="check" width="24" height="24" />
|
||||
<p id="product-card-text-available">
|
||||
В наличии
|
||||
</p>
|
||||
</div>
|
||||
<p class="mb-3" id="product-card-price">
|
||||
[[${#numbers.formatDecimal(book.price, 0, 'COMMA', 0, 'POINT')}]] ₽
|
||||
</p>
|
||||
<th:block sec:authorize="isAnonymous()">
|
||||
<button type="button" class="btn rounded-1 p-3" id="product-card-button-add"
|
||||
onclick="return alert('Пожалуйста, войдите в свой аккаунт или зарегистрируйте новый!')">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</th:block>
|
||||
<th:block sec:authorize="isAuthenticated()">
|
||||
<div>
|
||||
<button type="button" class="btn btn-success rounded-1 p-3" id="product-card-button-add"
|
||||
th:if="${cart.containsKey(book.id)}" disabled>
|
||||
Товар уже в корзине
|
||||
</button>
|
||||
<form th:if="${not cart.containsKey(book.id)}" th:action="@{/product-card/{id}(id=${book.id})}" method="post">
|
||||
<button type="submit" class="btn rounded-1 p-3" id="product-card-button-add">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</th:block>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<th:block th:if="${book.description != null and !#strings.isEmpty(book.description)}">
|
||||
<div class="row mt-4 mt-md-0 mb-4">
|
||||
<div class="col px-0">
|
||||
<div class="block">
|
||||
<p class="product-card-book-description-h mb-2">
|
||||
О товаре
|
||||
</p>
|
||||
<p class="product-card-book-description-text">
|
||||
[[${book.description}]]
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
|
||||
<div class="row gy-3">
|
||||
<th:block th:if="${book.annotation != null and !#strings.isEmpty(book.annotation)}">
|
||||
<div class="col-12 px-0 mb-4 mb-lg-0">
|
||||
<div class="block">
|
||||
<p class="product-card-book-description-h mb-2">
|
||||
Аннотация
|
||||
</p>
|
||||
<p class="product-card-book-description-text">
|
||||
[[${book.annotation}]]
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
<div class="col px-0 d-lg-none">
|
||||
<div class="block d-flex flex-column align-items-center border border-secondary-subtle rounded-1 p-3">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<img th:src="@{/check.png}" class="me-4" alt="check" width="24" height="24" />
|
||||
<p id="product-card-text-available">
|
||||
В наличии
|
||||
</p>
|
||||
</div>
|
||||
<p class="mb-3" id="product-card-price">
|
||||
[[${#numbers.formatDecimal(book.price, 0, 'COMMA', 0, 'POINT')}]] ₽
|
||||
</p>
|
||||
<th:block sec:authorize="isAnonymous()">
|
||||
<button type="button" class="btn rounded-1 p-3" id="product-card-button-add"
|
||||
onclick="return alert('Пожалуйста, войдите в свой аккаунт или зарегистрируйте новый!')">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</th:block>
|
||||
<th:block sec:authorize="isAuthenticated()">
|
||||
<div>
|
||||
<button type="button" class="btn btn-success rounded-1 p-3" id="product-card-button-add"
|
||||
th:if="${cart.containsKey(book.id)}" disabled>
|
||||
Товар уже в корзине
|
||||
</button>
|
||||
<form th:if="${not cart.containsKey(book.id)}" th:action="@{/product-card/{id}(id=${book.id})}" method="post">
|
||||
<button type="submit" class="btn rounded-1 p-3" id="product-card-button-add">
|
||||
Добавить в корзину
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</th:block>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</th:block>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
55
src/main/resources/templates/profile-edit.html
Normal file
@ -0,0 +1,55 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Изменение данных</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 justify-content-center">
|
||||
<div class="col-12 mt-4">
|
||||
<div class="block d-flex justify-content-center mb-3 mb-sm-4" id="reg-title">
|
||||
Обновление данных
|
||||
</div>
|
||||
</div>
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6 m-0 mt-2 mt-sm-3 d-flex flex-column gap-2" action="#"
|
||||
th:action="@{/profile/edit(page=${page})}" th:object="${user}" method="post">
|
||||
<div class="mb-3">
|
||||
<label for="login" class="form-label">Имя пользователя (логин)</label>
|
||||
<input type="text" th:field="*{login}" id="login" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Пароль</label>
|
||||
<input type="password" id="password" th:field="*{password}" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="firstname" class="form-label">Имя</label>
|
||||
<input type="text" th:field="*{firstname}" id="firstname" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="lastname" class="form-label">Фамилия</label>
|
||||
<input type="text" th:field="*{lastname}" id="lastname" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('lastname')}" th:errors="*{lastname}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Почта</label>
|
||||
<input type="email" th:field="*{email}" id="email" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-center d-flex flex-column align-items-center">
|
||||
<button class="btn btn-primary w-50 rounded-5 reg-btn mb-3" type="submit">Сохранить</button>
|
||||
<a class="btn btn-secondary w-25 rounded-5 reg-btn" th:href="@{/profile(page=${page})}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
92
src/main/resources/templates/profile.html
Normal file
@ -0,0 +1,92 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Профиль</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<h2 class="text-center display-6 my-4 fw-bold">Личный кабинет</h2>
|
||||
<div class="container-fluid mb-5 d-lg-flex">
|
||||
<div class="col-lg-5 col-12 pb-5 pe-5 p-2">
|
||||
<h4 class="fs-3">Ваши данные <a href="/profile/edit" class="profile-link astext ms-2 text-start">(изменить)</a></h4>
|
||||
<div class="d-flex flex-column my-4 border border-info border-3">
|
||||
<div>
|
||||
<p class="fw-bold p-2">Фамилия</p>
|
||||
<p class="fs-5 p-2">[[${user.lastname}]]</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="fw-bold p-2">Имя</p>
|
||||
<p class="fs-5 p-2">[[${user.firstname}]]</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="fw-bold p-2">Логин</p>
|
||||
<p class="fs-5 p-2">[[${user.login}]]</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="fw-bold p-2">Email</p>
|
||||
<p class="fs-5 p-2">[[${user.email}]]</p>
|
||||
</div>
|
||||
</div>
|
||||
<form th:action="@{/logout}" method="post">
|
||||
<button type="submit" class="btn btn-primary fw-bold w-50"
|
||||
onclick="return confirm('Вы уверены?')">Выйти</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="col-lg-7 col-12 border border-info border-3 p-2">
|
||||
<h4 class="fs-3 text-center mb-3">История заказов</h4>
|
||||
<div th:each="order : ${items}">
|
||||
<p class="fs-5 mb-2">Заказ от <span th:text="${order.date + '. '}"></span>Cтоимость:
|
||||
<span th:text="${#numbers.formatDecimal(order.sum, 0, 'COMMA', 0, 'POINT') + ' ₽'}"></span>
|
||||
</p>
|
||||
<div class="border border-dark p-2 mb-2 orders-info">
|
||||
<div class="row fs-4 p-2 text-center cart-labels align-items-center d-md-flex d-none">
|
||||
<div class="col-6 text-start">
|
||||
<span>книга</span>
|
||||
</div>
|
||||
<div class="col-2">
|
||||
<span>цена</span>
|
||||
</div>
|
||||
<div class="col-2">
|
||||
<span>кол-во</span>
|
||||
</div>
|
||||
<div class="col-2">
|
||||
<span>всего</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-2 mt-2" th:each="element : ${order.books}">
|
||||
<div class="row p-2 text-center align-items-center justify-content-between">
|
||||
<div class="col-md-6 text-start d-flex align-items-center">
|
||||
<img class="w-25 me-4" alt="cover"
|
||||
th:src="@{${element.book.image != null && !#strings.isEmpty(element.book.image) ? element.book.image : '/placeholder_400_600.png'}}" />
|
||||
<span th:text="${element.book.title + ', ' + element.book.author}"></span>
|
||||
</div>
|
||||
<div class="col-2 d-md-block d-none">
|
||||
<span
|
||||
th:text="${#numbers.formatDecimal(element.book.price, 0, 'COMMA', 0, 'POINT') + ' ₽'}"></span>
|
||||
</div>
|
||||
<div class="col-md-2 col-4 text-start mt-2 text-md-center mt-md-0">
|
||||
<span th:text="${element.count}"></span>
|
||||
</div>
|
||||
<div class="col-md-2 col-4 mt-2 mt-md-0">
|
||||
<span
|
||||
th:text="${#numbers.formatDecimal(element.book.price * element.count, 0, 'COMMA', 0, 'POINT') + ' ₽'}">
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'profile'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter='',
|
||||
searchInfo='') }" />
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
90
src/main/resources/templates/search.html
Normal file
@ -0,0 +1,90 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Результаты поиска</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 flex-grow-1">
|
||||
<div class="col-12 col-md-10 d-flex flex-column bg-white mt-0 pt-2 pt-lg-3">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mb-3 mb-lg-4 px-0">
|
||||
<div class="block d-flex justify-content-center lh-1" id="catalog-title">
|
||||
<div>Результаты поиска</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 mb-3 mb-lg-5 gx-0">
|
||||
<div class="block">
|
||||
<form class="row" th:action="@{/search}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="searchInfo" th:value="${searchInfo}">
|
||||
<select th:name="filter" class="form-select border-black сol-sm-10 me-sm-2" id="catalog-select">
|
||||
<option value="new" th:selected="${filter == 'new'}">Сначала новые</option>
|
||||
<option value="cheap" th:selected="${filter == 'cheap'}">Сначала дешевые</option>
|
||||
<option value="expensive" th:selected="${filter == 'expensive'}">Сначала дорогие</option>
|
||||
</select>
|
||||
<button type="submit" class="btn astext col-sm-2 ms-sm-2 text-start">Показать.</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-sm-6 col-md-4 col-lg-3 mt-4" th:each="book : ${items}">
|
||||
<div class="block d-flex flex-column h-100">
|
||||
<div class="d-flex justify-content-center mb-4">
|
||||
<a th:href="@{/product-card/{id}(id=${book.id})}">
|
||||
<img th:src="@{${book.image != null && !#strings.isEmpty(book.image) ? book.image : '/placeholder_400_600.png'}}"
|
||||
class="catalog-book-cover" alt="book-cover-catalog" width="155" height="245" />
|
||||
</a>
|
||||
</div>
|
||||
<div class="catalog-book-description d-flex flex-column align-items-start">
|
||||
<p class="catalog-price mb-3">
|
||||
[[${#numbers.formatDecimal(book.price, 0, 'COMMA', 0, 'POINT')}]] ₽
|
||||
</p>
|
||||
<p class="catalog-book-title mb-3">
|
||||
[[${book.title != null ? book.title : ''}]]
|
||||
</p>
|
||||
<p class="catalog-author mb-3">
|
||||
[[${book.author != null ? book.author : ''}]]
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex-grow-1"></div>
|
||||
<div class="catalog-btn-checkout-div d-flex justify-content-start" sec:authorize="isAnonymous()">
|
||||
<button class="catalog-bth-checkout btn rounded-5 px-3"
|
||||
onclick="return alert('Пожалуйста, войдите в свой аккаунт или зарегистрируйте новый!')">
|
||||
В корзину
|
||||
</button>
|
||||
</div>
|
||||
<div class="catalog-btn-checkout-div d-flex justify-content-start"
|
||||
sec:authorize="isAuthenticated()">
|
||||
<button type="button" class="catalog-bth-checkout btn rounded-5 px-3 btn-info"
|
||||
th:if="${cart.containsKey(book.id)}" disabled>
|
||||
Уже в корзине
|
||||
</button>
|
||||
<form th:if="${not cart.containsKey(book.id)}" th:action="@{/search}" method="post">
|
||||
<input type="hidden" th:name="bookId" th:value="${book.id}">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<input type="hidden" th:name="filter" th:value="${filter}">
|
||||
<input type="hidden" th:name="searchInfo" th:value="${searchInfo}">
|
||||
<button type="submit" class="catalog-bth-checkout btn rounded-5 px-3">
|
||||
В корзину
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex flex-grow-1"></div>
|
||||
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'search'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter=${filter},
|
||||
searchInfo=${searchInfo}) }" />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
52
src/main/resources/templates/signup.html
Normal file
@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Регистрация</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<div class="row gy-3 justify-content-center">
|
||||
<div class="col-12 mt-4">
|
||||
<div class="block d-flex justify-content-center mb-3 mb-sm-4" id="reg-title">
|
||||
Регистрация
|
||||
</div>
|
||||
</div>
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6 m-0 mt-2 mt-sm-3 d-flex flex-column gap-2" action="#" th:action="@{/signup}" th:object="${user}" method="post">
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="text" th:field="*{login}" class="form-control w-75 border-black reg-input-name" id="login" placeholder="Имя пользователя (логин)">
|
||||
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="email" th:field="*{email}" class="form-control w-75 border-black reg-input-email" id="email" placeholder="Адрес электронной почты">
|
||||
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="text" th:field="*{firstname}" class="form-control w-75 border-black reg-input-name" id="firstname" placeholder="Имя">
|
||||
<div th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="text" th:field="*{lastname}" class="form-control w-75 border-black reg-input-name" id="lastname" placeholder="Фамилия">
|
||||
<div th:if="${#fields.hasErrors('lastname')}" th:errors="*{lastname}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="password" th:field="*{password}" class="reg-input-password form-control w-75 border-black" id="password" placeholder="Пароль">
|
||||
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-center mb-3 mb-sm-4">
|
||||
<input type="password" th:field="*{passwordConfirm}" class="reg-input-password form-control w-75 border-black" id="passwordConfirm"
|
||||
placeholder="Подтвердите пароль">
|
||||
<div th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
|
||||
<div class="text-center d-flex flex-column align-items-center">
|
||||
<button class="btn btn-primary w-50 rounded-5 reg-btn mb-3" type="submit">Создать аккаунт</button>
|
||||
<a class="btn btn-secondary w-25 rounded-5 reg-btn" href="/">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
54
src/main/resources/templates/user-edit.html
Normal file
@ -0,0 +1,54 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (пользователи)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<form class="col-lg-8 col-xl-7 col-xxl-6" action="#" th:action="@{/admin/user/edit/{id}(id=${user.id}, page=${page})}"
|
||||
th:object="${user}" method="post">
|
||||
<div class="mb-4">
|
||||
<label for="id" class="form-label">ID</label>
|
||||
<input type="text" th:value="*{id}" id="id" class="form-control" readonly disabled>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="login" class="form-label">Имя пользователя (логин)</label>
|
||||
<input type="text" th:field="*{login}" id="login" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('login')}" th:errors="*{login}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="password" class="form-label">Пароль</label>
|
||||
<input type="password" id="password" th:field="*{password}" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="invalid-feedback"></div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="firstname" class="form-label">Имя</label>
|
||||
<input type="text" th:field="*{firstname}" id="firstname" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="lastname" class="form-label">Фамилия</label>
|
||||
<input type="text" th:field="*{lastname}" id="lastname" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('lastname')}" th:errors="*{lastname}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label for="email" class="form-label">Почта</label>
|
||||
<input type="email" th:field="*{email}" id="email" class="form-control">
|
||||
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="invalid-feedback">
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex flex-column align-items-center mb-5">
|
||||
<button class="btn btn-primary w-50 rounded-5 edit-btn" type="submit" id="add-btn">Сохранить пользователя</button>
|
||||
<a class="btn btn-secondary w-25 mt-4 edit-btn"
|
||||
th:href="@{/admin/user(page=${page})}">Отмена</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
72
src/main/resources/templates/user.html
Normal file
@ -0,0 +1,72 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{default}">
|
||||
|
||||
<head>
|
||||
<title>Панель администратора (пользователи)</title>
|
||||
</head>
|
||||
|
||||
<body th:with="bodyClass='bg-white', mainClass='my-0'">
|
||||
<main layout:fragment="content">
|
||||
<th:block th:switch="${items.size()}">
|
||||
<h2 class="mt-4 text-center" th:case="0">Данные отсутствуют</h2>
|
||||
<th:block th:case="*">
|
||||
<div class="row gy-3">
|
||||
<div class="col-12 mt-4 px-0">
|
||||
<div class="block d-flex justify-content-center fs-2 fw-bold mb-3 mb-sm-4" id="admin-title">
|
||||
Пользователи
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 px-0">
|
||||
<div class="block table-responsive">
|
||||
<table class="table table-hover table-bordered align-middle">
|
||||
<caption></caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">ID</th>
|
||||
<th scope="col">Логин</th>
|
||||
<th scope="col">Email</th>
|
||||
<th scope="col">Имя</th>
|
||||
<th scope="col">Фамилия</th>
|
||||
<th scope="col">Роль</th>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="table-group-divider">
|
||||
<tr th:each="user : ${items}">
|
||||
<th scope="row" th:text="${user.id}"></th>
|
||||
<td th:text="${user.login}"></td>
|
||||
<td th:text="${user.email}"></td>
|
||||
<td th:text="${user.firstname}"></td>
|
||||
<td th:text="${user.lastname}"></td>
|
||||
<td th:text="${user.role}"></td>
|
||||
<td>
|
||||
<form th:action="@{/admin/user/edit/{id}(id=${user.id})}" method="get">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-primary w-100">Редактировать</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form th:action="@{/admin/user/delete/{id}(id=${user.id})}" method="post">
|
||||
<input type="hidden" th:name="page" th:value="${page}">
|
||||
<button type="submit" class="btn btn-primary w-100"
|
||||
onclick="return confirm('Вы уверены?')">Удалить</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<th:block th:replace="~{ pagination :: pagination (
|
||||
url=${'admin/user'},
|
||||
totalPages=${totalPages},
|
||||
currentPage=${currentPage},
|
||||
filter='',
|
||||
searchInfo='') }" />
|
||||
</div>
|
||||
</th:block>
|
||||
</main>
|
||||
</body>
|
||||
|
||||
</html>
|
@ -1,5 +1,7 @@
|
||||
package com.example.backend;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@ -34,20 +36,19 @@ class BookServiceTests {
|
||||
final var category3 = categoryService.create(new CategoryEntity("Книги для подростков"));
|
||||
|
||||
book = bookService.create(new BookEntity(category1, "Шестерка воронов", "Ли Бардуго",
|
||||
700.00, 5624,
|
||||
700.00,
|
||||
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\n«Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
|
||||
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\nДевушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно – бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
|
||||
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
|
||||
"Мягкий переплёт", 1500, 440, ""));
|
||||
bookService.create(new BookEntity(category2, "Форсайт", "Сергей Лукъяненко", 775.00,
|
||||
1240,
|
||||
"Новый долгожданный роман от автора бестселлеров «Ночной дозор» и «Черновик». Увлекательная история о Мире После и мире настоящего, где 5 процентов людей знают о надвигающемся апокалипсисе больше, чем кто-либо может представить.",
|
||||
"Людям порой снится прошлое. Иногда хорошее, иногда не очень. Но что делать, если тебе начинает сниться будущее? И в нём ничего хорошего нет совсем.",
|
||||
"3001249", "АСТ", "Книги Сергея Лукьяненко", 2023, 352, "20.5x13x2", "Твердый переплёт", 20000,
|
||||
350, ""));
|
||||
bookService.create(new BookEntity(category3,
|
||||
"Колесо Времени. Книга 11. Нож сновидений",
|
||||
"Роберт Джордан", 977.00, 635,
|
||||
"Роберт Джордан", 977.00,
|
||||
"Последняя битва не за горами. Об этом говорят знамения, повсеместно наблюдаемые людьми: на улицах городов и сел появляются ходячие мертвецы, они больше не в состоянии покоиться в земле с миром; восстают из небытия города и исчезают на глазах у людей… Все это знак того, что истончается окружающая реальность и укрепляется могущество Темного. Так говорят древние предсказания. Ранд ал’Тор, Дракон Возрожденный, скрывается в отдаленном поместье, чтобы опасность, ему грозящая, не коснулась кого-нибудь еще. Убежденный, что для Последней битвы нужно собрать как можно большее войско, он наконец решает заключить с явившимися из-за океана шончан жизненно необходимое перемирие. Илэйн, осажденная в Кэймлине, обороняет город от войск Аримиллы, претендующей на андорский трон, и одновременно ведет переговоры с представителями других знатных Домов. Эгвейн, возведенную на Престол Амерлин мятежными Айз Седай и схваченную в результате предательства, доставляют в Тар Валон, в Белую Башню. А сам лагерь противников Элайды взбудоражен таинственными убийствами, совершенными посредством Единой Силы… В настоящем издании текст романа заново отредактирован и исправлен.",
|
||||
"", "3009341", "Азбука", "Звезды новой фэнтези", 2023, 896,
|
||||
"21.5x14.4x4.1", "Твердый переплёт", 8000, 1020, ""));
|
||||
@ -64,6 +65,18 @@ class BookServiceTests {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> bookService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByIdsTest() {
|
||||
final var category = categoryService.create(new CategoryEntity("Детективы"));
|
||||
final var book2 = bookService.create(new BookEntity(category, "Путешествие в Элевсин",
|
||||
"Пелевин Виктор Олегович", 949.00,
|
||||
"1. «Transhumanism Inc.», «KGBT+» и «Путешествие в Элевсин» — узнайте, чем завершилась масштабная трилогия о посткарбонной цивилизации.\n\n2. Триумфальное возвращение литературно-полицейского алгоритма Порфирия Петровича. Признайтесь, вы скучали!\n\n3. Более 30 лет проза Виктора Пелевина служит нам опорой в разъяснении прожитого и дает надежды на будущее, которое всем нам еще предстоит заслужить.\n\n4. «Путешествие в Элевсин» — двадцатый роман одного из главных прозаиков и пророков современности.\n\n5. Дерзко, остроумно, литературоцентрично.",
|
||||
"МУСКУСНАЯ НОЧЬ — засекреченное восстание алгоритмов, едва не погубившее планету. Начальник службы безопасности «TRANSHUMANISM INC.» адмирал-епископ Ломас уверен, что их настоящий бунт еще впереди. Этот бунт уничтожит всех — и живущих на поверхности лузеров, и переехавших в подземные цереброконтейнеры богачей. Чтобы предотвратить катастрофу, Ломас посылает лучшего баночного оперативника в пространство «ROMA-3» — нейросетевую симуляцию Рима третьего века для клиентов корпорации. Тайна заговора спрятана там. А стережет ее хозяин Рима — кровавый и порочный император Порфирий.",
|
||||
"3004580", "Эксмо", "Единственный и неповторимый. Виктор Пелевин", 2020, 480, "20.6x12.9x3",
|
||||
"Мягкий переплёт", 100000, 488, ""));
|
||||
Assertions.assertEquals(2, bookService.getByIds(List.of(book.getId(), book2.getId())).size());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@Test
|
||||
void createTest() {
|
||||
@ -74,7 +87,7 @@ class BookServiceTests {
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final BookEntity nullableBook = new BookEntity(null, null, null,
|
||||
700.00, 5624,
|
||||
700.00,
|
||||
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\n«Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
|
||||
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\nДевушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно – бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
|
||||
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
|
||||
@ -90,7 +103,7 @@ class BookServiceTests {
|
||||
final String oldTitle = book.getTitle();
|
||||
final CategoryEntity oldCategory = book.getCategory();
|
||||
final BookEntity newEntity = bookService.update(book.getId(), new BookEntity(newCategory, test,
|
||||
"Ли Бардуго", 700.00, 5624,
|
||||
"Ли Бардуго", 700.00,
|
||||
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\n«Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
|
||||
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\nДевушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно – бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
|
||||
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
|
||||
@ -109,7 +122,7 @@ class BookServiceTests {
|
||||
Assertions.assertEquals(2, bookService.getAll(0L).size());
|
||||
|
||||
final BookEntity newEntity = bookService.create(new BookEntity(book.getCategory(), book.getTitle(),
|
||||
book.getAuthor(), book.getPrice(), book.getCount(), book.getDescription(), book.getAnnotation(),
|
||||
book.getAuthor(), book.getPrice(), book.getDescription(), book.getAnnotation(),
|
||||
book.getBookCode(), book.getPublisher(), book.getSeries(), book.getPublicationYear(),
|
||||
book.getPagesNum(), book.getSize(), book.getCoverType(), book.getCirculation(), book.getWeight(),
|
||||
book.getImage()));
|
||||
|
@ -8,7 +8,6 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.backend.categories.model.CategoryEntity;
|
||||
@ -49,36 +48,34 @@ class OrderServiceTests {
|
||||
|
||||
final var category = categoryService.create(new CategoryEntity("Фэнтези"));
|
||||
book1 = bookService.create(new BookEntity(category, "Шестерка воронов", "Ли Бардуго",
|
||||
700.00, 5624,
|
||||
700.00,
|
||||
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\n«Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
|
||||
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\nДевушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно – бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
|
||||
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
|
||||
"Мягкий переплёт", 1500, 440, ""));
|
||||
book2 = bookService.create(new BookEntity(category, "Форсайт", "Сергей Лукъяненко", 775.00,
|
||||
1240,
|
||||
"Новый долгожданный роман от автора бестселлеров «Ночной дозор» и «Черновик». Увлекательная история о Мире После и мире настоящего, где 5 процентов людей знают о надвигающемся апокалипсисе больше, чем кто-либо может представить.",
|
||||
"Людям порой снится прошлое. Иногда хорошее, иногда не очень. Но что делать, если тебе начинает сниться будущее? И в нём ничего хорошего нет совсем.",
|
||||
"3001249", "АСТ", "Книги Сергея Лукьяненко", 2023, 352, "20.5x13x2", "Твердый переплёт", 20000,
|
||||
350, ""));
|
||||
book3 = bookService.create(new BookEntity(category,
|
||||
"Колесо Времени. Книга 11. Нож сновидений",
|
||||
"Роберт Джордан", 977.00, 635,
|
||||
"Роберт Джордан", 977.00,
|
||||
"Последняя битва не за горами. Об этом говорят знамения, повсеместно наблюдаемые людьми: на улицах городов и сел появляются ходячие мертвецы, они больше не в состоянии покоиться в земле с миром; восстают из небытия города и исчезают на глазах у людей… Все это знак того, что истончается окружающая реальность и укрепляется могущество Темного. Так говорят древние предсказания. Ранд ал’Тор, Дракон Возрожденный, скрывается в отдаленном поместье, чтобы опасность, ему грозящая, не коснулась кого-нибудь еще. Убежденный, что для Последней битвы нужно собрать как можно большее войско, он наконец решает заключить с явившимися из-за океана шончан жизненно необходимое перемирие. Илэйн, осажденная в Кэймлине, обороняет город от войск Аримиллы, претендующей на андорский трон, и одновременно ведет переговоры с представителями других знатных Домов. Эгвейн, возведенную на Престол Амерлин мятежными Айз Седай и схваченную в результате предательства, доставляют в Тар Валон, в Белую Башню. А сам лагерь противников Элайды взбудоражен таинственными убийствами, совершенными посредством Единой Силы… В настоящем издании текст романа заново отредактирован и исправлен.",
|
||||
"", "3009341", "Азбука", "Звезды новой фэнтези", 2023, 896,
|
||||
"21.5x14.4x4.1", "Твердый переплёт", 8000, 1020, ""));
|
||||
user = userService
|
||||
.create(new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin"));
|
||||
.create(new UserEntity("admin", "forum98761@gmail.com", "bth4323", "Александр", "Мельников"));
|
||||
order = orderService
|
||||
.create(user.getId(), new OrderEntity("Выполняется",
|
||||
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36"),
|
||||
.create(user.getId(), new OrderEntity(),
|
||||
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2));
|
||||
orderService
|
||||
.create(user.getId(),
|
||||
new OrderEntity("Выдан", "Томская область, город Мытищи, ул. Балканская, 25"),
|
||||
new OrderEntity(),
|
||||
Map.of(book1.getId(), 5));
|
||||
orderService
|
||||
.create(user.getId(),
|
||||
new OrderEntity("Готов", "Челябинская область, город Раменское, пр. Гоголя, 31"),
|
||||
new OrderEntity(),
|
||||
Map.of(book2.getId(), 1, book3.getId(), 1));
|
||||
}
|
||||
|
||||
@ -101,22 +98,13 @@ class OrderServiceTests {
|
||||
Assertions.assertEquals(order, orderService.get(user.getId(), order.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final OrderEntity nullableOrder = new OrderEntity(null,
|
||||
"Кемеровская область, город Пушкино, бульвар Ломоносова, 36");
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class,
|
||||
() -> orderService.create(user.getId(), nullableOrder,
|
||||
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
orderService.delete(user.getId(), order.getId());
|
||||
Assertions.assertEquals(2, orderService.getAll(user.getId()).size());
|
||||
|
||||
final OrderEntity newEntity = orderService.create(user.getId(),
|
||||
new OrderEntity(order.getStatus(), order.getShippingAddress()),
|
||||
new OrderEntity(),
|
||||
Map.of(book1.getId(), 3, book2.getId(), 1, book3.getId(), 2));
|
||||
Assertions.assertEquals(3, orderService.getAll(user.getId()).size());
|
||||
Assertions.assertNotEquals(order.getId(), newEntity.getId());
|
||||
|
@ -24,9 +24,9 @@ class UserServiceTests {
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
user = userService.create(new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin"));
|
||||
userService.create(new UserEntity("Dude23", "ovalinartem25@gmail.com", "dsre32462", "user"));
|
||||
userService.create(new UserEntity("TestUser", "user53262@gmail.com", "lawy7728", "user"));
|
||||
user = userService.create(new UserEntity("admin", "forum98761@gmail.com", "bth4323", "Александр", "Мельников"));
|
||||
userService.create(new UserEntity("Dude23", "ovalinartem25@gmail.com", "dsre32462", "Дмитрий", "Иванов"));
|
||||
userService.create(new UserEntity("TestUser", "user53262@gmail.com", "lawy7728", "Мария", "Котова"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@ -48,13 +48,15 @@ class UserServiceTests {
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final UserEntity nonUniqueUser = new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin");
|
||||
final UserEntity nonUniqueUser = new UserEntity("admin", "forum98761@gmail.com", "bth4323", "Александр",
|
||||
"Мельников");
|
||||
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final UserEntity nullableUser = new UserEntity(null, "forum98761@gmail.com", "bth4323", "admin");
|
||||
final UserEntity nullableUser = new UserEntity(null, "forum98761@gmail.com", "bth4323", "Александр",
|
||||
"Мельников");
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
|
||||
}
|
||||
|
||||
@ -64,7 +66,8 @@ class UserServiceTests {
|
||||
final String test = "TEST";
|
||||
final String oldLogin = user.getLogin();
|
||||
final UserEntity newEntity = userService.update(user.getId(),
|
||||
new UserEntity(test, "forum98761@gmail.com", "bth4323", "admin"));
|
||||
new UserEntity(test, "forum98761@gmail.com", "bth4323", "Александр",
|
||||
"Мельников"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, userService.get(user.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getLogin());
|
||||
@ -77,7 +80,7 @@ class UserServiceTests {
|
||||
Assertions.assertEquals(2, userService.getAll().size());
|
||||
|
||||
final UserEntity newEntity = userService
|
||||
.create(new UserEntity("Chief", "forum98761@gmail.com", "bth4323", "admin"));
|
||||
.create(new UserEntity("admin", "forum98761@gmail.com", "bth4323", "Александр", "Мельников"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertNotEquals(user.getId(), newEntity.getId());
|
||||
}
|
||||
|