Compare commits

...

8 Commits

Author SHA1 Message Date
Илья
9e0a6d0e18 Версия после сдачи 2024-06-07 21:22:07 +04:00
Илья
093212138f lab4/5_code 2024-06-07 14:21:27 +04:00
Илья
631b60fc4b Полностью готовая 3 лаба 2024-05-10 14:37:56 +04:00
Илья
bb3b42bf2d Добавил ограничение для столбца count в таблице связи 2024-04-20 13:59:17 +04:00
Илья
f48ad34121 lab3_code 2024-04-20 00:25:54 +04:00
Илья
a0f3b16491 Исправление обновления заказов и добавление методов вычисления суммы в тесты 2024-04-01 16:26:42 +04:00
Илья
88b46e2ee3 lab2_code 2024-03-31 21:02:30 +04:00
Илья
2404d337cd lab1_code 2024-03-04 18:52:40 +04:00
114 changed files with 7174 additions and 60 deletions

91
.gitignore vendored
View File

@ -1,63 +1,36 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> Gradle
HELP.md
.gradle
**/build/
!src/**/build/
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
data.*.db

12
.vscode/extensions.json vendored Normal file
View 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
View 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
View 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"
],
}

View File

@ -1,2 +1,15 @@
# Internet_Programming_PIbd-21_Rodionov_I_A_Backend
H2 Console: \
http://localhost:8080/h2-console
JDBC URL: jdbc:h2:file:./data \
User Name: sa \
Password: password
Почитать:
- 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/

51
build.gradle Normal file
View File

@ -0,0 +1,51 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.0'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
defaultTasks 'bootRun'
jar {
enabled = false
}
bootJar {
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
}
assert System.properties['java.specification.version'] == '17' || '21'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
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'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
gradlew vendored Normal file
View File

@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = 'backend'

View File

@ -0,0 +1,98 @@
package com.example.backend;
import java.util.Arrays;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.backend.books.model.BookEntity;
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;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final CategoryService categoryService;
private final BookService bookService;
private final UserService userService;
private final OrderService orderService;
public DemoApplication(CategoryService categoryService, BookService bookService, UserService userService,
OrderService orderService) {
this.categoryService = categoryService;
this.bookService = bookService;
this.userService = userService;
this.orderService = orderService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
log.info("Create default categories values");
final var category1 = categoryService.create(new CategoryEntity("Фэнтези"));
final var category2 = categoryService.create(new CategoryEntity("Художественная литература"));
final var category3 = categoryService.create(new CategoryEntity("Книги для подростков"));
log.info("Create default books values");
final var book1 = bookService.create(new BookEntity(category1, "Шестерка воронов", "Ли Бардуго",
700.00,
"Триша Левенселлер — американская писательница, подарившая вам роман «Тени между нами», который стал бестселлером Amazon в разделе «Фэнтези YA», вновь радует своих фанатов новой магической историей «Клинок тайн».\n\nЕще до выхода в свет книгу добавили в раздел «Хочу прочитать» более 10 тысяч человек на портале Goodreads.com.\n\Клинок тайн» — первая часть захватывающей дилогии про девушку, которая благодаря магии крови создает самое опасное в мире оружие, и ослепительного юношу, что составляет ей компанию в этом непростом приключении.",
"Юная Зива предпочитает проводить время с оружием, а не с людьми. Она кузнец и ей предстоит создать самое могущественное оружие на земле.\n\евушка демонстрирует меч, способный от одной капли крови врага раскрыть все тайные замыслы его обладателю.\n\nОднако у заказчика на оружие другие планы: заставить Зиву вооружить мечами свое войско и поработить весь мир. Когда девушка понимает, что меч, созданный благодаря магии крови, невозможно уничтожить и рано или поздно на нее объявят охоту, ей остается только одно бежать, не оглядываясь. Зиве теперь суждено спасти мир от собственного творения. Но как бы далеко она ни старалась убежать, все ловушки уже расставлены.",
"2946447", "Эксмо", "Young Adult. Бестселлеры Триши Левенселлер", 2022, 480, "20.7x13x2.5",
"Мягкий переплёт", 1500, 440, ""));
final var book2 = bookService.create(new BookEntity(category2, "Форсайт", "Сергей Лукъяненко", 775.00,
"Новый долгожданный роман от автора бестселлеров «Ночной дозор» и «Черновик». Увлекательная история о Мире После и мире настоящего, где 5 процентов людей знают о надвигающемся апокалипсисе больше, чем кто-либо может представить.",
"Людям порой снится прошлое. Иногда хорошее, иногда не очень. Но что делать, если тебе начинает сниться будущее? И в нём ничего хорошего нет совсем.",
"3001249", "АСТ", "Книги Сергея Лукьяненко", 2023, 352, "20.5x13x2", "Твердый переплёт", 20000,
350, ""));
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, "", "", "2996776", "", "", 2022, null,
"", "", null, null, ""));
final var book5 = bookService.create(new BookEntity(category3, "Путешествие в Элевсин",
"Пелевин Виктор Олегович", 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 superAdmin = new UserEntity("chief", "forum98761@gmail.com", "bth4323", "Александр", "Мельников");
superAdmin.setRole(UserRole.SUPERADMIN);
userService.create(superAdmin);
log.info("Create default orders values");
orderService
.create(superAdmin.getId(), new OrderEntity(),
Map.of(book1.getId(), 3, book3.getId(), 1, book5.getId(), 2));
orderService
.create(superAdmin.getId(),
new OrderEntity(),
Map.of(book4.getId(), 5));
orderService
.create(superAdmin.getId(),
new OrderEntity(),
Map.of(book2.getId(), 1, book4.getId(), 1));
}
}
}

View File

@ -0,0 +1,195 @@
package com.example.backend.books.api;
import java.text.ParseException;
import java.util.Date;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
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.PageAttributesMapper;
import com.example.backend.core.configuration.Constants;
import com.example.backend.core.utils.Formatter;
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 jakarta.validation.Valid;
@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;
public BookController(BookService bookService, CategoryService categoryService, ModelMapper modelMapper) {
this.bookService = bookService;
this.categoryService = categoryService;
this.modelMapper = modelMapper;
}
private BookDto toDto(BookEntity entity) {
final BookDto dto = modelMapper.map(entity, BookDto.class);
dto.setCategoryName(entity.getCategory().getName());
dto.setDate(Formatter.format(entity.getDate()));
return dto;
}
private BookEntity toEntity(BookDto dto) throws ParseException {
final BookEntity entity = modelMapper.map(dto, BookEntity.class);
entity.setCategory(categoryService.get(dto.getCategoryId()));
entity.setDate(Formatter.parse(dto.getDate()));
return entity;
}
private CategoryDto toCategoryDto(CategoryEntity entity) {
return modelMapper.map(entity, CategoryDto.class);
}
@GetMapping
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("/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("/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) throws ParseException {
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);
book.setDate(Formatter.format(new Date()));
bookService.create(toEntity(book));
return Constants.REDIRECT_VIEW + URL;
}
@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;
}
@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) throws ParseException {
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;
}
}

View File

@ -0,0 +1,188 @@
package com.example.backend.books.api;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
public class BookDto {
private Long id;
@NotNull
@Min(1)
private Long categoryId;
private String categoryName;
@NotBlank
private String title;
@NotBlank
private String author;
@NotNull
@Min(1)
private Double price;
private String description;
private String annotation;
@NotBlank
private String bookCode;
private String publisher;
private String series;
@NotNull
@Min(1950)
private Integer publicationYear;
private Integer pagesNum;
private String size;
private String coverType;
private Integer circulation;
private Integer weight;
private String image;
private String date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Integer getPublicationYear() {
return publicationYear;
}
public void setPublicationYear(Integer publicationYear) {
this.publicationYear = publicationYear;
}
public Integer getPagesNum() {
return pagesNum;
}
public void setPagesNum(Integer pagesNum) {
this.pagesNum = pagesNum;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getCoverType() {
return coverType;
}
public void setCoverType(String coverType) {
this.coverType = coverType;
}
public Integer getCirculation() {
return circulation;
}
public void setCirculation(Integer circulation) {
this.circulation = circulation;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,49 @@
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;
import com.example.backend.core.utils.Formatter;
@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) {
final BookDto dto = modelMapper.map(entity, BookDto.class);
dto.setDate(Formatter.format(entity.getDate()));
return dto;
}
@GetMapping
public String getMainPage(Model model) {
model.addAttribute(
"novelties",
bookService.getNewest(6));
model.addAttribute(
"promotions",
bookService.getByIds(List.of(4L, 44L, 45L, 65L, 66L, 67L)).stream()
.map(this::toDto)
.toList());
model.addAttribute(
"recommendations",
bookService.getByIds(List.of(68L, 69L, 70L, 71L, 72L, 75L)).stream()
.map(this::toDto)
.toList());
return MAIN_VIEW;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,261 @@
package com.example.backend.books.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.Date;
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;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "books")
public class BookEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "categoryId", nullable = false)
private CategoryEntity category;
@Column(nullable = false)
private String title;
@Column(nullable = false)
private String author;
@Column(nullable = false)
private Double price;
@Lob
private String description;
@Lob
private String annotation;
@Column(nullable = false, unique = true)
private String bookCode;
private String publisher;
private String series;
@Column(nullable = false)
private Integer publicationYear;
private Integer pagesNum;
private String size;
private String coverType;
private Integer circulation;
private Integer weight;
@Lob
private String image;
private Date date = new Date();
@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,
String description, String annotation, String bookCode, String publisher, String series,
Integer publicationYear, Integer pagesNum, String size, String coverType, Integer circulation,
Integer weight, String image) {
this.category = category;
this.title = title;
this.author = author;
this.price = price;
this.description = description;
this.annotation = annotation;
this.bookCode = bookCode;
this.publisher = publisher;
this.series = series;
this.publicationYear = publicationYear;
this.pagesNum = pagesNum;
this.size = size;
this.coverType = coverType;
this.circulation = circulation;
this.weight = weight;
this.image = image;
date = new Date();
}
public CategoryEntity getCategory() {
return category;
}
public void setCategory(CategoryEntity category) {
this.category = category;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getSeries() {
return series;
}
public void setSeries(String series) {
this.series = series;
}
public Integer getPublicationYear() {
return publicationYear;
}
public void setPublicationYear(Integer publicationYear) {
this.publicationYear = publicationYear;
}
public Integer getPagesNum() {
return pagesNum;
}
public void setPagesNum(Integer pagesNum) {
this.pagesNum = pagesNum;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getCoverType() {
return coverType;
}
public void setCoverType(String coverType) {
this.coverType = coverType;
}
public Integer getCirculation() {
return circulation;
}
public void setCirculation(Integer circulation) {
this.circulation = circulation;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Set<OrderBookEntity> getOrderBooks() {
return orderBooks;
}
public void addOrder(OrderBookEntity orderBook) {
if (orderBook.getBook() != this) {
orderBook.setBook(this);
}
orderBooks.add(orderBook);
}
@Override
public int hashCode() {
return Objects.hash(id, category, title, author, price, description, annotation, bookCode, publisher,
series, publicationYear, pagesNum, size, coverType, circulation, weight, image);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final BookEntity other = (BookEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getCategory(), category)
&& Objects.equals(other.getTitle(), title)
&& Objects.equals(other.getAuthor(), author)
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getDescription(), description)
&& Objects.equals(other.getAnnotation(), annotation)
&& Objects.equals(other.getBookCode(), bookCode)
&& Objects.equals(other.getPublisher(), publisher)
&& Objects.equals(other.getSeries(), series)
&& Objects.equals(other.getPublicationYear(), publicationYear)
&& Objects.equals(other.getPagesNum(), pagesNum)
&& Objects.equals(other.getSize(), size)
&& Objects.equals(other.getCoverType(), coverType)
&& Objects.equals(other.getCirculation(), circulation)
&& Objects.equals(other.getWeight(), weight)
&& Objects.equals(other.getImage(), image);
}
}

View File

@ -0,0 +1,31 @@
package com.example.backend.books.repository;
import java.util.List;
import org.springframework.data.domain.Limit;
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);
@Query("SELECT b FROM BookEntity b ORDER BY b.date desc")
List<BookEntity> findSomeNewest(Limit limit);
}

View File

@ -0,0 +1,146 @@
package com.example.backend.books.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Limit;
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;
import com.example.backend.books.model.BookEntity;
import com.example.backend.books.repository.BookRepository;
import com.example.backend.core.error.NotFoundException;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<BookEntity> getAll(long categoryId) {
if (categoryId <= 0L) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return repository.findByCategoryId(categoryId);
}
@Transactional(readOnly = true)
public Page<BookEntity> getAll(long categoryId, int page, int size) {
final Pageable pageRequest = PageRequest.of(page, size);
if (categoryId <= 0L) {
return repository.findAll(pageRequest);
}
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 List<BookEntity> getNewest(int limit) {
if (limit > 0) {
return repository.findSomeNewest(Limit.of(limit));
}
return Collections.emptyList();
}
@Transactional(readOnly = true)
public BookEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(BookEntity.class, id));
}
@Transactional
public BookEntity create(BookEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public BookEntity update(Long id, BookEntity entity) {
final BookEntity existsEntity = get(id);
existsEntity.setCategory(entity.getCategory());
existsEntity.setTitle(entity.getTitle());
existsEntity.setAuthor(entity.getAuthor());
existsEntity.setPrice(entity.getPrice());
existsEntity.setDescription(entity.getDescription());
existsEntity.setAnnotation(entity.getAnnotation());
existsEntity.setBookCode(entity.getBookCode());
existsEntity.setPublisher(entity.getPublisher());
existsEntity.setSeries(entity.getSeries());
existsEntity.setPublicationYear(entity.getPublicationYear());
existsEntity.setPagesNum(entity.getPagesNum());
existsEntity.setSize(entity.getSize());
existsEntity.setCoverType(entity.getCoverType());
existsEntity.setCirculation(entity.getCirculation());
existsEntity.setWeight(entity.getWeight());
existsEntity.setImage(entity.getImage());
return repository.save(existsEntity);
}
@Transactional
public BookEntity delete(Long id) {
final BookEntity existsEntity = get(id);
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:
return new Order(Sort.Direction.DESC, "publicationYear");
}
}
}

View File

@ -0,0 +1,104 @@
package com.example.backend.categories.api;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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;
@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;
public CategoryController(CategoryService categoryService, ModelMapper modelMapper) {
this.categoryService = categoryService;
this.modelMapper = modelMapper;
}
private CategoryDto toDto(CategoryEntity entity) {
return modelMapper.map(entity, CategoryDto.class);
}
private CategoryEntity toEntity(CategoryDto dto) {
return modelMapper.map(dto, CategoryEntity.class);
}
@GetMapping
public String getAll(Model model) {
model.addAttribute(
"categories",
categoryService.getAll().stream()
.map(this::toDto)
.toList());
return CATEGORY_VIEW;
}
@GetMapping("/edit/")
public String create(Model model) {
model.addAttribute(CATEGORY_ATTRIBUTE, new CategoryDto());
return CATEGORY_EDIT_VIEW;
}
@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;
}
@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;
}
@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;
}
}

View File

@ -0,0 +1,27 @@
package com.example.backend.categories.api;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class CategoryDto {
private Long id;
@NotBlank
@Size(min = 3, max = 50)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,48 @@
package com.example.backend.categories.model;
import java.util.Objects;
import com.example.backend.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "categories")
public class CategoryEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
public CategoryEntity() {
}
public CategoryEntity(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final CategoryEntity other = (CategoryEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +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);
}

View File

@ -0,0 +1,62 @@
package com.example.backend.categories.service;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.backend.categories.model.CategoryEntity;
import com.example.backend.categories.repository.CategoryRepository;
import com.example.backend.core.error.NotFoundException;
@Service
public class CategoryService {
private final CategoryRepository repository;
public CategoryService(CategoryRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Category with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<CategoryEntity> getAll() {
Sort sortById = Sort.by(Sort.Direction.ASC, "id");
return repository.findAll(sortById);
}
@Transactional(readOnly = true)
public CategoryEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(CategoryEntity.class, id));
}
@Transactional
public CategoryEntity create(CategoryEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public CategoryEntity update(long id, CategoryEntity entity) {
final CategoryEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}
@Transactional
public CategoryEntity delete(long id) {
final CategoryEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -0,0 +1,19 @@
package com.example.backend.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final int DEFAULT_PAGE_SIZE = 8;
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() {
}
}

View File

@ -0,0 +1,26 @@
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;
@Configuration
public class MapperConfiguration {
@Bean
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;
}
}

View File

@ -0,0 +1,13 @@
package com.example.backend.core.configuration;
import org.springframework.context.annotation.Configuration;
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 addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,7 @@
package com.example.backend.core.error;
public class NotFoundException extends RuntimeException {
public <T> NotFoundException(Class<T> clazz, Long id) {
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
}
}

View File

@ -0,0 +1,28 @@
package com.example.backend.core.model;
import com.example.backend.core.configuration.Constants;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.SequenceGenerator;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
protected Long id;
protected BaseEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -0,0 +1,20 @@
package com.example.backend.core.utils;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public final class Formatter {
private Formatter() {
}
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String format(Date date) {
return dateFormatter.format(date);
}
public static Date parse(String date) throws ParseException {
return dateFormatter.parse(date);
}
}

View 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;
}
}

View 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 "";
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,22 @@
package com.example.backend.orders.api;
public class OrderBookDto {
private Long bookId;
private Integer count;
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}

View File

@ -0,0 +1,92 @@
package com.example.backend.orders.api;
import java.util.Map;
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.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.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;
@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;
public OrderController(OrderService orderService, ModelMapper modelMapper) {
this.orderService = orderService;
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()));
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 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("/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("/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;
}
}

View File

@ -0,0 +1,60 @@
package com.example.backend.orders.api;
import java.util.List;
public class OrderDto {
private Long id;
private Double sum;
private Integer count;
private String date;
private List<OrderBookDto> orderInfo;
private List<BookCountDto> books;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getSum() {
return sum;
}
public void setSum(Double sum) {
this.sum = sum;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<OrderBookDto> getOrderInfo() {
return orderInfo;
}
public void setOrderInfo(List<OrderBookDto> orderInfo) {
this.orderInfo = orderInfo;
}
public List<BookCountDto> getBooks() {
return books;
}
public void setBooks(List<BookCountDto> books) {
this.books = books;
}
}

View File

@ -0,0 +1,89 @@
package com.example.backend.orders.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.example.backend.users.model.UserEntity;
import com.example.backend.core.model.BaseEntity;
import com.example.backend.ordersbooks.model.OrderBookEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders")
public class OrderEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false)
private Date date = new Date();
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private Set<OrderBookEntity> orderBooks = new HashSet<>();
public OrderEntity() {
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
if (!user.getOrders().contains(this)) {
user.getOrders().add(this);
}
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Set<OrderBookEntity> getOrderBooks() {
return orderBooks;
}
public void addBook(OrderBookEntity orderBook) {
if (orderBook.getOrder() != this) {
orderBook.setOrder(this);
}
orderBooks.add(orderBook);
}
public void deleteBook(OrderBookEntity orderBook) {
if (orderBook.getOrder() != this) {
return;
}
orderBooks.remove(orderBook);
}
@Override
public int hashCode() {
return Objects.hash(id, user.getId(), date);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getDate(), date);
}
}

View File

@ -0,0 +1,20 @@
package com.example.backend.orders.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.backend.orders.model.OrderEntity;
public interface OrderRepository
extends CrudRepository<OrderEntity, Long>, PagingAndSortingRepository<OrderEntity, Long> {
Optional<OrderEntity> findOneByUserIdAndId(long userId, long id);
List<OrderEntity> findByUserId(long userId);
Page<OrderEntity> findByUserId(long userId, Pageable pageable);
}

View File

@ -0,0 +1,113 @@
package com.example.backend.orders.service;
import java.util.List;
import java.util.Map;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.backend.core.error.NotFoundException;
import com.example.backend.orders.model.OrderEntity;
import com.example.backend.orders.repository.OrderRepository;
import com.example.backend.books.model.BookEntity;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
import com.example.backend.ordersbooks.model.OrderBookEntity;
import com.example.backend.books.service.BookService;
@Service
public class OrderService {
private final OrderRepository repository;
private final UserService userService;
private final BookService bookService;
public OrderService(OrderRepository repository, UserService userService, BookService bookService) {
this.repository = repository;
this.userService = userService;
this.bookService = bookService;
}
@Transactional(readOnly = true)
public List<OrderEntity> getAll(Long userId) {
userService.get(userId);
return repository.findByUserId(userId);
}
@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));
}
@Transactional
public OrderEntity create(long userId, OrderEntity entity, Map<Long, Integer> booksIdsCount) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final UserEntity existsUser = userService.get(userId);
entity.setUser(existsUser);
List<BookEntity> result = bookService.getAll(0L).stream()
.filter(book -> booksIdsCount.containsKey(book.getId()))
.toList();
result.forEach(book -> {
final OrderBookEntity orderBook = new OrderBookEntity(entity, book, booksIdsCount.get(book.getId()));
orderBook.setOrder(entity);
orderBook.setBook(book);
});
return repository.save(entity);
}
@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);
return existsEntity;
}
@Transactional(readOnly = true)
public Double getSum(long userId, long id) {
userService.get(userId);
return get(userId, id).getOrderBooks().stream()
.mapToDouble(orderBook -> orderBook.getCount() * orderBook.getBook().getPrice())
.sum();
}
@Transactional(readOnly = true)
public Integer getFullCount(long userId, long id) {
userService.get(userId);
return get(userId, id).getOrderBooks().stream()
.mapToInt(OrderBookEntity::getCount)
.sum();
}
@Transactional(readOnly = true)
public List<OrderBookEntity> getOrderBooks(long userId, long id) {
userService.get(userId);
return get(userId, id).getOrderBooks().stream()
.toList();
}
}

View File

@ -0,0 +1,96 @@
package com.example.backend.ordersbooks.model;
import java.util.Objects;
import com.example.backend.books.model.BookEntity;
import com.example.backend.orders.model.OrderEntity;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MapsId;
import jakarta.persistence.Table;
@Entity
@Table(name = "orders_books")
public class OrderBookEntity {
@EmbeddedId
private OrderBookId id = new OrderBookId();
@ManyToOne
@MapsId("orderId")
@JoinColumn(name = "order_id")
private OrderEntity order;
@ManyToOne
@MapsId("bookId")
@JoinColumn(name = "book_id")
private BookEntity book;
@Column(nullable = false)
private Integer count;
public OrderBookEntity() {
}
public OrderBookEntity(OrderEntity order, BookEntity book, Integer count) {
this.order = order;
this.book = book;
this.count = count;
}
public OrderBookId getId() {
return id;
}
public void setId(OrderBookId id) {
this.id = id;
}
public OrderEntity getOrder() {
return order;
}
public void setOrder(OrderEntity order) {
this.order = order;
if (!order.getOrderBooks().contains(this)) {
order.getOrderBooks().add(this);
}
}
public BookEntity getBook() {
return book;
}
public void setBook(BookEntity book) {
this.book = book;
if (!book.getOrderBooks().contains(this)) {
book.getOrderBooks().add(this);
}
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public int hashCode() {
return Objects.hash(id, order.getId(), book.getId(), count);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
OrderBookEntity other = (OrderBookEntity) obj;
return Objects.equals(id, other.id)
&& Objects.equals(order.getId(), other.order.getId())
&& Objects.equals(book.getId(), other.book.getId())
&& count == other.count;
}
}

View File

@ -0,0 +1,55 @@
package com.example.backend.ordersbooks.model;
import java.util.Objects;
import java.util.Optional;
import jakarta.persistence.Embeddable;
@Embeddable
public class OrderBookId {
private Long orderId;
private Long bookId;
public OrderBookId() {
}
public OrderBookId(Long orderId, Long bookId) {
this.orderId = orderId;
this.bookId = bookId;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Long getBookId() {
return bookId;
}
public void setBookId(Long bookId) {
this.bookId = bookId;
}
@Override
public int hashCode() {
return Objects.hash(
Optional.ofNullable(orderId).orElse(0L),
Optional.ofNullable(bookId).orElse(0L));
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
OrderBookId other = (OrderBookId) obj;
return Objects.equals(orderId, other.orderId)
&& Objects.equals(bookId, other.bookId);
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,102 @@
package com.example.backend.users.api;
import java.util.Map;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
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 jakarta.validation.Valid;
@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;
public UserController(UserService userService, ModelMapper modelMapper) {
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
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("/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("/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;
}
@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;
}
}

View File

@ -0,0 +1,78 @@
package com.example.backend.users.api;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
private Long id;
@NotBlank
@Size(min = 3, max = 20)
private String login;
@NotBlank
@Size(min = 5, max = 254)
private String email;
@NotBlank
@Size(min = 6, max = 60)
private String password;
@NotBlank
private String firstname;
@NotBlank
private String lastname;
private String role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String name) {
this.login = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}

View File

@ -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;
}
}

View File

@ -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";
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,126 @@
package com.example.backend.users.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import com.example.backend.core.model.BaseEntity;
import com.example.backend.orders.model.OrderEntity;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 20)
private String login;
@Column(nullable = false, unique = true, length = 254)
private String email;
@Column(nullable = false, length = 60)
private String password;
@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<>();
public UserEntity() {
}
public UserEntity(String login, String email, String password, String firstname, String lastname) {
this.login = login;
this.email = email;
this.password = password;
this.firstname = firstname;
this.lastname = lastname;
this.role = UserRole.USER;
}
public String getLogin() {
return login;
}
public void setLogin(String name) {
this.login = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
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() {
return orders;
}
public void addOrder(OrderEntity order) {
if (order.getUser() != this) {
order.setUser(this);
}
orders.add(order);
}
@Override
public int hashCode() {
return Objects.hash(id, login, email, password, lastname, firstname, role);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getLogin(), login)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getFirstname(), firstname)
&& Objects.equals(other.getLastname(), lastname)
&& Objects.equals(other.getRole(), role);
}
}

View 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();
}
}

View File

@ -0,0 +1,13 @@
package com.example.backend.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.backend.users.model.UserEntity;
public interface UserRepository
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,110 @@
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 implements UserDetailsService {
private final UserRepository repository;
private final PasswordEncoder passwordEncoder;
public UserService(UserRepository repository, PasswordEncoder passwordEncoder) {
this.repository = repository;
this.passwordEncoder = passwordEncoder;
}
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));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.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(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);
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());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
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);
}
}

View File

@ -0,0 +1,24 @@
# Server
spring.main.banner-mode=off
server.port=8080
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.open-in-view=false
# spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# H2 console
spring.h2.console.enabled=true
# Multipart file upload settings
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

View 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;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 520 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 501 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 950 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 800 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 709 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1019 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 714 B

View 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>

View 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>

View File

@ -0,0 +1,91 @@
<!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>
<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 th:text="${book.date}"></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>

View 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">
В корзине&nbsp;[[${count}]]&nbsp;[[${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')}]]&nbsp;р.</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')}]]&nbsp;р.
</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')}]]&nbsp;р.</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')}]]&nbsp;р.
</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>

View 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>

View 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"> &gt; </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')}]]&nbsp;
</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>

View 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>

View 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>

View 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>

View 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">&nbsp;/&nbsp;</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>

View 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>

View 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>

View 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>

View 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')}]] &#8381;
* [[${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>

Some files were not shown because too many files have changed in this diff Show More