commit e6629b550cec4a80361659d82d3bab7b8600c473 Author: KP9lK Date: Mon Jun 9 13:17:07 2025 +0300 finally api diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c426c32 --- /dev/null +++ b/.gitignore @@ -0,0 +1,36 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### 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/ + +### VS Code ### +.vscode/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3e9f00e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# Stage 1: Cache Gradle dependencies +FROM gradle:latest AS cache +RUN mkdir -p /home/gradle/cache_home +ENV GRADLE_USER_HOME=/home/gradle/cache_home +COPY build.gradle.* gradle.properties /home/gradle/app/ +COPY gradle /home/gradle/app/gradle +WORKDIR /home/gradle/app +RUN gradle clean build -i --stacktrace + +# Stage 2: Build Application +FROM gradle:latest AS build +COPY --from=cache /home/gradle/cache_home /home/gradle/.gradle +COPY --chown=gradle:gradle . /home/gradle/src +WORKDIR /home/gradle/src +# Build the fat JAR, Gradle also supports shadow +# and boot JAR by default. +RUN gradle buildFatJar --no-daemon + +# Stage 3: Create the Runtime Image +FROM amazoncorretto:22 AS runtime +EXPOSE 8080 +RUN mkdir /app +COPY --from=build /home/gradle/src/build/libs/*.jar /app/presence.jar +ENTRYPOINT ["java","-jar","/app/presence.jar"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..01ec05b --- /dev/null +++ b/README.md @@ -0,0 +1,44 @@ +# furnitureshop + +This project was created using the [Ktor Project Generator](https://start.ktor.io). + +Here are some useful links to get you started: + +- [Ktor Documentation](https://ktor.io/docs/home.html) +- [Ktor GitHub page](https://github.com/ktorio/ktor) +- The [Ktor Slack chat](https://app.slack.com/client/T09229ZC6/C0A974TJ9). You'll need to [request an invite](https://surveys.jetbrains.com/s3/kotlin-slack-sign-up) to join. + +## Features + +Here's a list of features included in this project: + +| Name | Description | +| ------------------------------------------------------------------------|------------------------------------------------------------------------------------ | +| [Content Negotiation](https://start.ktor.io/p/content-negotiation) | Provides automatic content conversion according to Content-Type and Accept headers | +| [Routing](https://start.ktor.io/p/routing) | Provides a structured routing DSL | +| [kotlinx.serialization](https://start.ktor.io/p/kotlinx-serialization) | Handles JSON serialization using kotlinx.serialization library | +| [Status Pages](https://start.ktor.io/p/status-pages) | Provides exception handling for routes | +| [Authentication](https://start.ktor.io/p/auth) | Provides extension point for handling the Authorization header | +| [Authentication JWT](https://start.ktor.io/p/auth-jwt) | Handles JSON Web Token (JWT) bearer authentication scheme | + +## Building & Running + +To build or run the project, use one of the following tasks: + +| Task | Description | +| -------------------------------|---------------------------------------------------------------------- | +| `./gradlew test` | Run the tests | +| `./gradlew build` | Build everything | +| `buildFatJar` | Build an executable JAR of the server with all dependencies included | +| `buildImage` | Build the docker image to use with the fat JAR | +| `publishImageToLocalRegistry` | Publish the docker image locally | +| `run` | Run the server | +| `runDocker` | Run using the local docker image | + +If the server starts successfully, you'll see the following output: + +``` +2024-12-04 14:32:45.584 [main] INFO Application - Application started in 0.303 seconds. +2024-12-04 14:32:45.682 [main] INFO Application - Responding at http://0.0.0.0:8080 +``` + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..62a8e26 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,37 @@ + +plugins { + alias(libs.plugins.kotlin.jvm) + alias(libs.plugins.ktor) + alias(libs.plugins.kotlin.plugin.serialization) +} + +group = "com.example" +version = "0.0.1" + +application { + mainClass = "io.ktor.server.netty.EngineMain" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.postgresql:postgresql:42.7.2") + implementation("org.jetbrains.exposed:exposed-core:1.0.0-beta-2") + implementation("org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0-beta-2") + implementation("org.jetbrains.exposed:exposed-r2dbc:1.0.0-beta-2") + implementation("org.jetbrains.exposed:exposed-jdbc:1.0.0-beta-2") + implementation(libs.ktor.server.content.negotiation) + implementation(libs.ktor.server.core) + implementation(libs.ktor.serialization.kotlinx.json) + implementation(libs.ktor.server.host.common) + implementation(libs.ktor.server.status.pages) + implementation(libs.ktor.server.auth) + implementation(libs.ktor.server.auth.jwt) + implementation(libs.ktor.server.netty) + implementation(libs.logback.classic) + implementation(libs.ktor.server.config.yaml) + testImplementation(libs.ktor.server.test.host) + testImplementation(libs.kotlin.test.junit) +} diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..df0f924 --- /dev/null +++ b/compose.yml @@ -0,0 +1,16 @@ +services: + web: + build: . + ports: + - "8080:8080" + depends_on: + - db + db: + image: postgres + volumes: + - ./postgres:/var/lib/postgresql/data + environment: + POSTGRES_DB: furnitureshop + POSTGRES_PASSWORD: ejSLqVRmzGTrWbcA6PNpXC + ports: + - "5454:5432" diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..3b81135 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,24 @@ + +[versions] +kotlin-version = "2.1.10" +ktor-version = "3.1.3" +logback-version = "1.4.14" + +[libraries] +ktor-server-content-negotiation = { module = "io.ktor:ktor-server-content-negotiation", version.ref = "ktor-version" } +ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor-version" } +ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor-version" } +ktor-server-host-common = { module = "io.ktor:ktor-server-host-common", version.ref = "ktor-version" } +ktor-server-status-pages = { module = "io.ktor:ktor-server-status-pages", version.ref = "ktor-version" } +ktor-server-auth = { module = "io.ktor:ktor-server-auth", version.ref = "ktor-version" } +ktor-server-auth-jwt = { module = "io.ktor:ktor-server-auth-jwt", version.ref = "ktor-version" } +ktor-server-netty = { module = "io.ktor:ktor-server-netty", version.ref = "ktor-version" } +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback-version" } +ktor-server-config-yaml = { module = "io.ktor:ktor-server-config-yaml", version.ref = "ktor-version" } +ktor-server-test-host = { module = "io.ktor:ktor-server-test-host", version.ref = "ktor-version" } +kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin-version" } + +[plugins] +kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin-version" } +ktor = { id = "io.ktor.plugin", version.ref = "ktor-version" } +kotlin-plugin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin-version" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7454180 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e411586 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/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/master/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..611681d --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "furnitureshop" diff --git a/src/main/kotlin/Application.kt b/src/main/kotlin/Application.kt new file mode 100644 index 0000000..51e59da --- /dev/null +++ b/src/main/kotlin/Application.kt @@ -0,0 +1,27 @@ +package com.example + +import com.example.data.database.DatabaseSettings +import com.example.route.* +import io.ktor.server.application.* +import io.ktor.server.routing.* + +fun main(args: Array) { + io.ktor.server.netty.EngineMain.main(args) +} + +fun Application.module() { + DatabaseSettings.initialize() + configureSerialization() + configureSecurity() + configureStatusPage() + routing { + userRoute() + cartRoute() + saleRoute() + orderRoute() + furnitureRoute() + shopCategoryRoute() + categoryRoute() + wishlistRoute() + } +} diff --git a/src/main/kotlin/configure/Routing.kt b/src/main/kotlin/configure/Routing.kt new file mode 100644 index 0000000..e56608b --- /dev/null +++ b/src/main/kotlin/configure/Routing.kt @@ -0,0 +1,15 @@ +package com.example + +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.plugins.statuspages.* +import io.ktor.server.response.* + +fun Application.configureStatusPage() { + install(StatusPages) { + exception { call, cause -> + call.respondText(text = "500: $cause" , status = HttpStatusCode.InternalServerError) + cause.printStackTrace() + } + } +} diff --git a/src/main/kotlin/configure/Security.kt b/src/main/kotlin/configure/Security.kt new file mode 100644 index 0000000..a209c29 --- /dev/null +++ b/src/main/kotlin/configure/Security.kt @@ -0,0 +1,17 @@ +package com.example + +import com.auth0.jwt.JWT +import com.auth0.jwt.algorithms.Algorithm +import io.ktor.http.* +import io.ktor.serialization.kotlinx.json.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.auth.jwt.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.statuspages.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Application.configureSecurity() { + +} diff --git a/src/main/kotlin/configure/Serialization.kt b/src/main/kotlin/configure/Serialization.kt new file mode 100644 index 0000000..b9e4a00 --- /dev/null +++ b/src/main/kotlin/configure/Serialization.kt @@ -0,0 +1,24 @@ +package com.example + +import com.auth0.jwt.JWT +import com.auth0.jwt.algorithms.Algorithm +import io.ktor.http.* +import io.ktor.serialization.kotlinx.json.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.auth.jwt.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.statuspages.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Application.configureSerialization() { + install(ContentNegotiation) { + json() + } + routing { + get("/json/kotlinx-serialization") { + call.respond(mapOf("hello" to "world")) + } + } +} diff --git a/src/main/kotlin/configure/Serializers.kt b/src/main/kotlin/configure/Serializers.kt new file mode 100644 index 0000000..5781b37 --- /dev/null +++ b/src/main/kotlin/configure/Serializers.kt @@ -0,0 +1,34 @@ +package com.example.configure + +import com.example.dto.response.FurnitureCategoryResponse +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import java.math.BigDecimal +import java.util.UUID + +object BigDecimalSerializer: KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): BigDecimal { + return BigDecimal(decoder.decodeString()) + } + + override fun serialize(encoder: Encoder, value: BigDecimal) { + encoder.encodeString(value.toString()) + } +} +object UuidSerializer: KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): UUID { + return UUID.fromString(decoder.decodeString()) + } + + override fun serialize(encoder: Encoder, value: UUID) { + encoder.encodeString(value.toString()) + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/Database.kt b/src/main/kotlin/data/database/Database.kt new file mode 100644 index 0000000..1f0da37 --- /dev/null +++ b/src/main/kotlin/data/database/Database.kt @@ -0,0 +1,41 @@ +package com.example.data.database + +import com.example.data.database.tables.* +import org.jetbrains.exposed.v1.jdbc.Database +import org.jetbrains.exposed.v1.jdbc.SchemaUtils +import org.jetbrains.exposed.v1.jdbc.transactions.transaction + +object DatabaseSettings { + + val db by lazy { + Database.connect( + url = "jdbc:postgresql://db:5432/furnitureshop", + driver = "org.postgresql.Driver", + user = "postgres", + password = "ejSLqVRmzGTrWbcA6PNpXC", + ) + } + fun initialize(){ + transaction(db = db) { + SchemaUtils.create( + UserTable, + ProfileTable, + AddressTable, + FurnitureCategory, + FurnitureTable, + ShopCategoryTable, + ShopCategoryFurnitureTable, + CartTable, + WishlistTable, + SaleTable, + OrderStatusTable, + OrderTable, + OrderSetTable, + ) + } + } + suspend fun dbQuery(block: () -> T): T = transaction(db = db) { + return@transaction block() + } + +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/mapper.kt b/src/main/kotlin/data/database/mapper.kt new file mode 100644 index 0000000..7d3373c --- /dev/null +++ b/src/main/kotlin/data/database/mapper.kt @@ -0,0 +1,78 @@ +package com.example.data.database + +import com.example.data.database.tables.* +import com.example.dto.response.* +import org.jetbrains.exposed.v1.core.ResultRow + +fun ResultRow.toFurniture(): FurnitureResponse { + return FurnitureResponse( + id = this[FurnitureTable.id], + name = this[FurnitureTable.name], + description = this[FurnitureTable.description], + category = toFurnitureCategory(), + price = this[FurnitureTable.price], + sale = this[FurnitureTable.sale], + shopCategories = emptyList(), + url = this[FurnitureTable.url], + + ) +} + +fun ResultRow.toFurnitureCategory(): FurnitureCategoryResponse { + return FurnitureCategoryResponse( + this[FurnitureCategory.id], + this[FurnitureCategory.name], + ) +} +fun ResultRow.toShopCategory(): ShopCategoryResponse { + return ShopCategoryResponse( + this[ShopCategoryTable.id], + this[ShopCategoryTable.name], + ) +} +fun ResultRow.toAllShopCategoryResponse(): AllShopCategoryResponse { + return AllShopCategoryResponse( + this[ShopCategoryTable.id], + this[ShopCategoryTable.name], + furnitureList = emptyList() + ) +} +fun ResultRow.toCartResponse(): CartResponse { + return CartResponse( + count = this[CartTable.count], + furnitureResponse = toFurniture(), + ) +} +fun ResultRow.toOrderResponse(): OrderResponse { + return OrderResponse( + id = this[OrderTable.orderId], + userUuid = this[OrderTable.userUuid], + addressId = this[OrderTable.userAddress], + dateTime = this[OrderTable.orderDateTime], + orderStatus = toOrderStatusResponse(), + orderTotalSum = this[OrderTable.orderTotalSum], + orderSet = emptyList() + ) +} +fun ResultRow.toOrderStatusResponse(): OrderStatusResponse { + return OrderStatusResponse( + this[OrderStatusTable.id], + this[OrderStatusTable.name], + ) +} +fun ResultRow.toSaleResponse(): SaleResponse { + return SaleResponse( + this[SaleTable.id], + this[SaleTable.name], + this[SaleTable.url] + ) +} +fun ResultRow.toOrderItemResponse(): OrderItemResponse { + return OrderItemResponse( + furnitureId = this[OrderSetTable.furnitureId], + orderId = this[OrderSetTable.orderId], + furniturePrice = this[OrderSetTable.furniturePrice], + count = this[OrderSetTable.count], + furnitureResponse = toFurniture(), + ) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/AddressTable.kt b/src/main/kotlin/data/database/tables/AddressTable.kt new file mode 100644 index 0000000..67a9e3f --- /dev/null +++ b/src/main/kotlin/data/database/tables/AddressTable.kt @@ -0,0 +1,13 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object AddressTable: Table("user_address") { + val id = long("address_id").autoIncrement() + val address = varchar("address_full", 255) + val entrance = integer("address_entrance") + val floor = integer("address_floor") + val apartment = integer("address_apartment") + val comment = text("address_comment") + override val primaryKey: PrimaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/CartTable.kt b/src/main/kotlin/data/database/tables/CartTable.kt new file mode 100644 index 0000000..619a8c9 --- /dev/null +++ b/src/main/kotlin/data/database/tables/CartTable.kt @@ -0,0 +1,10 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object CartTable: Table("cart") { + val userUuid = reference("user_uuid", UserTable.uuid) + val furnitureId = reference("furniture_id", FurnitureTable.id) + val count = integer("cart_count") + override val primaryKey: PrimaryKey = PrimaryKey(userUuid, furnitureId) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/FurnitureCategory.kt b/src/main/kotlin/data/database/tables/FurnitureCategory.kt new file mode 100644 index 0000000..643b887 --- /dev/null +++ b/src/main/kotlin/data/database/tables/FurnitureCategory.kt @@ -0,0 +1,9 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object FurnitureCategory: Table("furniture_category") { + val id = integer(name = "furniture_category_id").autoIncrement() + val name = varchar("furniture_category_name", 255) + override val primaryKey: PrimaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/FurnitureTable.kt b/src/main/kotlin/data/database/tables/FurnitureTable.kt new file mode 100644 index 0000000..8fce347 --- /dev/null +++ b/src/main/kotlin/data/database/tables/FurnitureTable.kt @@ -0,0 +1,14 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object FurnitureTable: Table("furniture") { + val id = long("furniture_id").autoIncrement() + val name = text("furniture_name") + val description = text("furniture_description") + val category = reference("furniture_category", FurnitureCategory.id) + val price = decimal("furniture_price", 17, 2) + val sale = decimal("furniture_sale", 2, 2) + val url = text("furniture_url") + override val primaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/OrderSetTable.kt b/src/main/kotlin/data/database/tables/OrderSetTable.kt new file mode 100644 index 0000000..636c923 --- /dev/null +++ b/src/main/kotlin/data/database/tables/OrderSetTable.kt @@ -0,0 +1,11 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object OrderSetTable: Table("order_set") { + val orderId = reference("order_id", OrderTable.orderId) + val furnitureId = reference("furniture_id", FurnitureTable.id) + val furniturePrice = decimal("furniture_price", 17, 2) + val count = integer("order_set_count") + override val primaryKey = PrimaryKey(orderId, furnitureId) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/OrderStatusTable.kt b/src/main/kotlin/data/database/tables/OrderStatusTable.kt new file mode 100644 index 0000000..9587842 --- /dev/null +++ b/src/main/kotlin/data/database/tables/OrderStatusTable.kt @@ -0,0 +1,13 @@ +package com.example.data.database.tables + +import com.example.data.database.tables.ShopCategoryTable.autoIncrement +import com.example.data.database.tables.ShopCategoryTable.integer +import com.example.data.database.tables.ShopCategoryTable.varchar +import org.jetbrains.exposed.v1.core.Table +import org.jetbrains.exposed.v1.core.Table.PrimaryKey + +object OrderStatusTable: Table("order_status") { + val id = integer(name = "order_status_id").autoIncrement() + val name = varchar("order_status_name", 255) + override val primaryKey: PrimaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/OrderTable.kt b/src/main/kotlin/data/database/tables/OrderTable.kt new file mode 100644 index 0000000..2b67f3f --- /dev/null +++ b/src/main/kotlin/data/database/tables/OrderTable.kt @@ -0,0 +1,15 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table +import org.jetbrains.exposed.v1.datetime.datetime + +object OrderTable: Table("order") { + val orderId = long("order_id").autoIncrement() + val userUuid = reference("user_uuid", UserTable.uuid) + val userAddress = reference("user_address_id", AddressTable.id) + val orderDateTime = datetime("order_date_time").defaultExpression(org.jetbrains.exposed.v1.datetime.CurrentDateTime) + val orderStatus = reference("order_status_id", OrderStatusTable.id) + val orderTotalSum = decimal("order_total_sum", 17, 2) + + override val primaryKey: PrimaryKey = PrimaryKey(orderId) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/ProfileTable.kt b/src/main/kotlin/data/database/tables/ProfileTable.kt new file mode 100644 index 0000000..b8a6a84 --- /dev/null +++ b/src/main/kotlin/data/database/tables/ProfileTable.kt @@ -0,0 +1,13 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.ReferenceOption +import org.jetbrains.exposed.v1.core.Table + +object ProfileTable: Table("profile") { + val uuid = reference("user_uuid", UserTable.uuid) + var firstName = varchar("profile_first_name", 255) + var lastName = varchar("profile_last_name", 255) + var imageUrl = text("profile_image").nullable() + val address = reference("address_id", AddressTable.id, ReferenceOption.CASCADE).nullable() + override val primaryKey: PrimaryKey = PrimaryKey(uuid) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/SaleTable.kt b/src/main/kotlin/data/database/tables/SaleTable.kt new file mode 100644 index 0000000..5749dc9 --- /dev/null +++ b/src/main/kotlin/data/database/tables/SaleTable.kt @@ -0,0 +1,10 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object SaleTable: Table("sale") { + val id = integer(name = "sales_id").autoIncrement() + val name = varchar("sales_name", 255) + val url = varchar("sales_url", 255) + override val primaryKey: PrimaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/ShopCategoryFurnitureTable.kt b/src/main/kotlin/data/database/tables/ShopCategoryFurnitureTable.kt new file mode 100644 index 0000000..b4c55aa --- /dev/null +++ b/src/main/kotlin/data/database/tables/ShopCategoryFurnitureTable.kt @@ -0,0 +1,9 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object ShopCategoryFurnitureTable: Table("shop_category_furniture") { + val shopCategoryId = reference("shop_category_id", ShopCategoryTable.id) + val furnitureId = reference("furniture_id", FurnitureTable.id) + override val primaryKey: PrimaryKey = PrimaryKey(shopCategoryId, furnitureId) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/ShopCategoryTable.kt b/src/main/kotlin/data/database/tables/ShopCategoryTable.kt new file mode 100644 index 0000000..5849497 --- /dev/null +++ b/src/main/kotlin/data/database/tables/ShopCategoryTable.kt @@ -0,0 +1,9 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object ShopCategoryTable: Table("shop_category") { + val id = long(name = "shop_category_id").autoIncrement() + val name = varchar("shop_category_name", 255) + override val primaryKey: PrimaryKey = PrimaryKey(id) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/UserTable.kt b/src/main/kotlin/data/database/tables/UserTable.kt new file mode 100644 index 0000000..6fa2915 --- /dev/null +++ b/src/main/kotlin/data/database/tables/UserTable.kt @@ -0,0 +1,10 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object UserTable: Table("user_table") { + val uuid = uuid("user_uuid").autoGenerate() + var email = varchar("user_email", 255) + var password = varchar("user_password", 255) + override val primaryKey: PrimaryKey = PrimaryKey(uuid) +} \ No newline at end of file diff --git a/src/main/kotlin/data/database/tables/WishlistTable.kt b/src/main/kotlin/data/database/tables/WishlistTable.kt new file mode 100644 index 0000000..7af27fd --- /dev/null +++ b/src/main/kotlin/data/database/tables/WishlistTable.kt @@ -0,0 +1,9 @@ +package com.example.data.database.tables + +import org.jetbrains.exposed.v1.core.Table + +object WishlistTable: Table("wishlist") { + val userUuid = reference("user_uuid", UserTable.uuid) + val furnitureId = reference("furniture_id", FurnitureTable.id) + override val primaryKey: PrimaryKey = PrimaryKey(userUuid, furnitureId) +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/CartRepository.kt b/src/main/kotlin/data/repository/CartRepository.kt new file mode 100644 index 0000000..d9be986 --- /dev/null +++ b/src/main/kotlin/data/repository/CartRepository.kt @@ -0,0 +1,61 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.CartTable +import com.example.data.database.tables.FurnitureCategory +import com.example.data.database.tables.FurnitureTable +import com.example.data.database.toCartResponse +import com.example.dto.request.AddToCartRequest +import com.example.dto.request.ChangeCountFromCartRequest +import com.example.dto.request.RemoveFromCartRequest +import com.example.dto.response.CartResponse +import org.jetbrains.exposed.v1.core.SqlExpressionBuilder.eq +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import org.jetbrains.exposed.v1.jdbc.update +import java.util.* + +class CartRepository { + suspend fun getCartByUuid(userUuid: UUID): List = DatabaseSettings.dbQuery { + val furniture = (CartTable innerJoin FurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { + CartTable.userUuid eq userUuid + } + .map { + it.toCartResponse() + } + return@dbQuery furniture + } + suspend fun addToCartByUuid(addToCartRequest: AddToCartRequest) = DatabaseSettings.dbQuery { + val result = CartTable.selectAll().where { CartTable.userUuid eq addToCartRequest.uuid and (CartTable.furnitureId eq addToCartRequest.furnitureId)}.firstOrNull() + result?.let { + CartTable.update(where = { CartTable.userUuid eq addToCartRequest.uuid and (CartTable.furnitureId eq addToCartRequest.furnitureId) }){ + it[count] = result[count] + 1 + } + return@dbQuery true + } + return@dbQuery CartTable.insert { + it[userUuid] = addToCartRequest.uuid + it[furnitureId] = addToCartRequest.furnitureId + it[count] = addToCartRequest.count + }.insertedCount > 0 + } + suspend fun removeFromCartByUuid(removeFromCartRequest: RemoveFromCartRequest) = DatabaseSettings.dbQuery { + return@dbQuery CartTable.deleteWhere { + userUuid eq removeFromCartRequest.uuid and (furnitureId eq removeFromCartRequest.furnitureId) + } > 0 + } + suspend fun changeCountFromCartByUuid(changeCountFromCartRequest: ChangeCountFromCartRequest) = DatabaseSettings.dbQuery { + if (changeCountFromCartRequest.count == 0){ + return@dbQuery CartTable.deleteWhere { + userUuid eq changeCountFromCartRequest.uuid and (furnitureId eq changeCountFromCartRequest.furnitureId) + } > 0 + } + return@dbQuery CartTable.update({ CartTable.userUuid eq changeCountFromCartRequest.uuid and (CartTable.furnitureId eq changeCountFromCartRequest.furnitureId) }) { + it[count] = changeCountFromCartRequest.count + } > 0 + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/CategoryRepository.kt b/src/main/kotlin/data/repository/CategoryRepository.kt new file mode 100644 index 0000000..0ed6254 --- /dev/null +++ b/src/main/kotlin/data/repository/CategoryRepository.kt @@ -0,0 +1,24 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.FurnitureCategory +import com.example.data.database.tables.FurnitureTable +import com.example.data.database.toFurniture +import com.example.data.database.toFurnitureCategory +import com.example.dto.request.RegisterRequest +import com.example.dto.response.FurnitureCategoryResponse +import com.example.dto.response.FurnitureResponse +import org.jetbrains.exposed.v1.jdbc.Database +import org.jetbrains.exposed.v1.jdbc.selectAll + +class CategoryRepository { + suspend fun getAllCategories(): List = DatabaseSettings.dbQuery { + return@dbQuery FurnitureCategory.selectAll().map { it.toFurnitureCategory() } + } + suspend fun getFurnitureByCategory(categoryId: Int): List = DatabaseSettings.dbQuery { + return@dbQuery (FurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { FurnitureTable.category eq categoryId } + .map { it.toFurniture() } + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/FurnitureRepository.kt b/src/main/kotlin/data/repository/FurnitureRepository.kt new file mode 100644 index 0000000..ac7ce5a --- /dev/null +++ b/src/main/kotlin/data/repository/FurnitureRepository.kt @@ -0,0 +1,55 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.FurnitureCategory +import com.example.data.database.tables.FurnitureTable +import com.example.data.database.tables.ShopCategoryFurnitureTable +import com.example.data.database.tables.ShopCategoryTable +import com.example.data.database.toFurniture +import com.example.data.database.toShopCategory +import com.example.dto.response.FurnitureResponse +import org.jetbrains.exposed.v1.core.SqlExpressionBuilder.eq +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.jdbc.andWhere +import org.jetbrains.exposed.v1.jdbc.selectAll + +class FurnitureRepository { + suspend fun getAllFurniture(): List = DatabaseSettings.dbQuery { + val furniture = (FurnitureTable innerJoin FurnitureCategory).selectAll().map { it.toFurniture() } + .map { furniture -> + furniture.shopCategories = (FurnitureTable innerJoin ShopCategoryFurnitureTable innerJoin ShopCategoryTable) + .selectAll() + .where { + FurnitureTable.id eq furniture.id } + .map { + it.toShopCategory() } + furniture + } + return@dbQuery furniture + } + suspend fun getFurnitureByCategory(categoryId: Long): List = DatabaseSettings.dbQuery { + val furniture = (FurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { FurnitureTable.id eq categoryId } + .map { it.toFurniture() } + .map { furniture -> + furniture.shopCategories = (FurnitureTable innerJoin ShopCategoryFurnitureTable innerJoin ShopCategoryTable) + .selectAll() + .where { + FurnitureTable.id eq furniture.id + }.map { + it.toShopCategory() } + furniture + } + return@dbQuery furniture + } + + suspend fun getFurnitureById(furnitureId: Long): FurnitureResponse = DatabaseSettings.dbQuery { + val furniture = (FurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { FurnitureTable.id eq furnitureId } + .firstOrNull() + if(furniture == null) throw NoSuchElementException() + return@dbQuery furniture.toFurniture() + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/OrderRepository.kt b/src/main/kotlin/data/repository/OrderRepository.kt new file mode 100644 index 0000000..a4c2c37 --- /dev/null +++ b/src/main/kotlin/data/repository/OrderRepository.kt @@ -0,0 +1,53 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.* +import com.example.data.database.tables.OrderTable.orderStatus +import com.example.data.database.toOrderItemResponse +import com.example.data.database.toOrderResponse +import com.example.dto.request.CreateOrderRequest +import com.example.dto.response.OrderResponse +import org.jetbrains.exposed.v1.core.SqlExpressionBuilder.eq +import org.jetbrains.exposed.v1.jdbc.* +import java.util.UUID + +class OrderRepository { + suspend fun createOrder(request: CreateOrderRequest): Boolean = DatabaseSettings.dbQuery { + val order = OrderTable.insertReturning { + it[orderTotalSum] = request.orderTotalSum + it[orderStatus] = request.orderStatus + it[userAddress]= request.addressId + it[userUuid] = request.userUuid + }.firstOrNull() + order?.let { + request.orderSet.forEach { orderSet -> + OrderSetTable.insert { + it[orderId] = order[OrderTable.orderId] + it[furnitureId] = orderSet.furnitureId + it[furniturePrice] = orderSet.furniturePrice + it[count] = orderSet.count + } + } + CartTable.deleteWhere { userUuid eq request.userUuid } + return@dbQuery true + } + return@dbQuery false + } + suspend fun getOrdersByUuid(userUUID: UUID): List = DatabaseSettings.dbQuery { + return@dbQuery (OrderTable innerJoin OrderStatusTable) + .selectAll() + .where { + OrderTable.userUuid eq userUUID + } + .map { it.toOrderResponse() } + .map { order -> + order.orderSet = (OrderSetTable innerJoin FurnitureTable innerJoin FurnitureCategory).selectAll() + .where { OrderSetTable.orderId eq order.id } + .map { + it.toOrderItemResponse() + } + order + } + .sortedBy { it.dateTime } + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/SalesRepository.kt b/src/main/kotlin/data/repository/SalesRepository.kt new file mode 100644 index 0000000..c1d2c0e --- /dev/null +++ b/src/main/kotlin/data/repository/SalesRepository.kt @@ -0,0 +1,12 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.SaleTable +import com.example.data.database.toSaleResponse +import org.jetbrains.exposed.v1.jdbc.selectAll + +class SalesRepository { + suspend fun getAllSales() = DatabaseSettings.dbQuery { + return@dbQuery SaleTable.selectAll().map { it.toSaleResponse() } + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/ShopCategoryRepository.kt b/src/main/kotlin/data/repository/ShopCategoryRepository.kt new file mode 100644 index 0000000..f762ace --- /dev/null +++ b/src/main/kotlin/data/repository/ShopCategoryRepository.kt @@ -0,0 +1,39 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.FurnitureCategory +import com.example.data.database.tables.FurnitureTable +import com.example.data.database.tables.ShopCategoryFurnitureTable +import com.example.data.database.tables.ShopCategoryTable +import com.example.data.database.toAllShopCategoryResponse +import com.example.data.database.toFurniture +import com.example.data.database.toShopCategory +import com.example.dto.response.AllShopCategoryResponse +import com.example.dto.response.FurnitureResponse +import org.jetbrains.exposed.v1.jdbc.selectAll + +class ShopCategoryRepository { + suspend fun getAllShopCategory(): List = DatabaseSettings.dbQuery { + val result = ShopCategoryTable + .selectAll() + .map { + it.toAllShopCategoryResponse() + }.map { category -> + category.furnitureList = (FurnitureTable innerJoin ShopCategoryFurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { ShopCategoryFurnitureTable.shopCategoryId eq category.id} + .map { + it.toFurniture() + } + category + } + return@dbQuery result + } + suspend fun getFurnitureByShopCategory(shopCategoryId: Long): List = DatabaseSettings.dbQuery { + val furniture = (ShopCategoryFurnitureTable innerJoin FurnitureTable innerJoin ShopCategoryTable innerJoin FurnitureCategory).selectAll() + .where { ShopCategoryFurnitureTable.shopCategoryId eq shopCategoryId } + .map { it.toFurniture() } + + return@dbQuery furniture + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/UserRepository.kt b/src/main/kotlin/data/repository/UserRepository.kt new file mode 100644 index 0000000..b264ef4 --- /dev/null +++ b/src/main/kotlin/data/repository/UserRepository.kt @@ -0,0 +1,100 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.AddressTable +import com.example.data.database.tables.ProfileTable +import com.example.data.database.tables.UserTable +import com.example.dto.request.AddAddressRequest +import com.example.dto.request.LoginRequest +import com.example.dto.request.RegisterRequest +import com.example.dto.response.AddressResponse +import com.example.dto.response.UserResponse +import org.jetbrains.exposed.v1.core.SqlExpressionBuilder.eq +import org.jetbrains.exposed.v1.jdbc.* +import java.util.UUID + +class UserRepository { + suspend fun register(registerRequest: RegisterRequest): UserResponse{ + return DatabaseSettings.dbQuery { + val user = UserTable.insertReturning { + it[email] = registerRequest.email + it[password] = registerRequest.password + }.firstOrNull() + + if(user == null) throw NullPointerException("User not created") + val result = ProfileTable.insertReturning { + it[uuid] = user[UserTable.uuid] + it[firstName] = registerRequest.firstName + it[lastName] = registerRequest.lastName + }.firstOrNull() + if(result == null) throw NullPointerException("Profile not created") + val userResponse = UserResponse( + userUuid = user[UserTable.uuid], + firstName = result[ProfileTable.firstName], + lastName = result[ProfileTable.lastName], + email = user[UserTable.email], + imageUrl = result[ProfileTable.imageUrl] + ) + return@dbQuery userResponse + } + } + + suspend fun login(loginRequest: LoginRequest): UserResponse { + return DatabaseSettings.dbQuery { + val user = (UserTable innerJoin ProfileTable).selectAll().where { UserTable.email eq loginRequest.email }.firstOrNull() + user?.let { + if(it[UserTable.password] != loginRequest.password) throw IllegalArgumentException("Uncorrected password") + return@dbQuery UserResponse( + userUuid = it[ProfileTable.uuid], + email = it[UserTable.email], + firstName = it[ProfileTable.firstName], + lastName = it[ProfileTable.lastName], + imageUrl = it[ProfileTable.imageUrl] + ) + } + throw NullPointerException("User not found") + } + } + + suspend fun getUserByUuid(uuid: UUID): UserResponse = DatabaseSettings.dbQuery{ + val user = (UserTable innerJoin ProfileTable innerJoin AddressTable).selectAll().where { UserTable.uuid eq uuid }.firstOrNull() + if(user == null) throw NullPointerException("User not found") + val userResponse = UserResponse( + userUuid = user[ProfileTable.uuid], + email = user[UserTable.email], + firstName = user[ProfileTable.firstName], + lastName = user[ProfileTable.lastName], + imageUrl = user[ProfileTable.imageUrl], + ) + if (user.hasValue(AddressTable.id)){ + userResponse.address = AddressResponse( + addressId = user[AddressTable.id], + entrance = user[AddressTable.entrance], + apartment = user[AddressTable.apartment], + floor = user[AddressTable.floor], + comment = user[AddressTable.comment], + address = user[AddressTable.address], + ) + } + return@dbQuery userResponse + } + + suspend fun addAddressByUuid(uuid: UUID, addAddressRequest: AddAddressRequest) = DatabaseSettings.dbQuery { + val user = (ProfileTable leftJoin AddressTable).selectAll().where { ProfileTable.uuid eq uuid }.firstOrNull() + if(user == null) throw NullPointerException("User not found") + val address = AddressTable.insertReturning { + it[comment] = addAddressRequest.comment + it[address] = addAddressRequest.address + it[apartment] = addAddressRequest.apartment + it[floor] = addAddressRequest.floor + it[entrance] = addAddressRequest.entrance + }.firstOrNull() + if(address == null) throw NullPointerException("Address not createad") + ProfileTable.update({ ProfileTable.uuid eq uuid }) { + it[ProfileTable.address] = address[AddressTable.id] + } + if(user.hasValue(AddressTable.id)){ + AddressTable.deleteWhere { id eq user[id] } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/data/repository/WishlistRepository.kt b/src/main/kotlin/data/repository/WishlistRepository.kt new file mode 100644 index 0000000..df3e16e --- /dev/null +++ b/src/main/kotlin/data/repository/WishlistRepository.kt @@ -0,0 +1,44 @@ +package com.example.data.repository + +import com.example.data.database.DatabaseSettings +import com.example.data.database.tables.FurnitureCategory +import com.example.data.database.tables.FurnitureTable +import com.example.data.database.tables.WishlistTable +import com.example.data.database.toFurniture +import com.example.dto.request.AddToWishlistRequest +import com.example.dto.request.RemoveFromWishlistRequest +import com.example.dto.response.FurnitureResponse +import org.jetbrains.exposed.v1.core.SqlExpressionBuilder.eq +import org.jetbrains.exposed.v1.core.and +import org.jetbrains.exposed.v1.jdbc.deleteReturning +import org.jetbrains.exposed.v1.jdbc.deleteWhere +import org.jetbrains.exposed.v1.jdbc.insert +import org.jetbrains.exposed.v1.jdbc.selectAll +import java.util.* + +class WishlistRepository { + suspend fun getWishListByUuid(userUuid: UUID): List = DatabaseSettings.dbQuery { + val furniture = (WishlistTable innerJoin FurnitureTable innerJoin FurnitureCategory) + .selectAll() + .where { + WishlistTable.userUuid eq userUuid + } + .map { + it.toFurniture() + } + return@dbQuery furniture + } + suspend fun addToWishListByUuid(addToWishlistRequest: AddToWishlistRequest): Boolean = DatabaseSettings.dbQuery { + val result = WishlistTable.insert { + it[userUuid] = addToWishlistRequest.uuid + it[furnitureId] = addToWishlistRequest.furnitureId + } + return@dbQuery result.insertedCount > 0 + } + + suspend fun removeFromWishlistByUuid(removeFromWishlistRequest: RemoveFromWishlistRequest): Boolean = DatabaseSettings.dbQuery { + return@dbQuery WishlistTable.deleteWhere { + userUuid eq removeFromWishlistRequest.uuid and (furnitureId eq removeFromWishlistRequest.furnitureId) + } > 0 + } +} \ No newline at end of file diff --git a/src/main/kotlin/dto/request/AddAddressRequest.kt b/src/main/kotlin/dto/request/AddAddressRequest.kt new file mode 100644 index 0000000..8138f4a --- /dev/null +++ b/src/main/kotlin/dto/request/AddAddressRequest.kt @@ -0,0 +1,12 @@ +package com.example.dto.request + +import kotlinx.serialization.Serializable + +@Serializable +data class AddAddressRequest( + val address: String, + val entrance: Int, + val floor: Int, + val apartment: Int, + val comment: String +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/AddToCartRequest.kt b/src/main/kotlin/dto/request/AddToCartRequest.kt new file mode 100644 index 0000000..20bd703 --- /dev/null +++ b/src/main/kotlin/dto/request/AddToCartRequest.kt @@ -0,0 +1,12 @@ +package com.example.dto.request + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.UUID +@Serializable +data class AddToCartRequest( + @Serializable(with = UuidSerializer::class) + val uuid: UUID, + val furnitureId: Long, + val count: Int, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/AddToWishlistRequest.kt b/src/main/kotlin/dto/request/AddToWishlistRequest.kt new file mode 100644 index 0000000..72cdae3 --- /dev/null +++ b/src/main/kotlin/dto/request/AddToWishlistRequest.kt @@ -0,0 +1,11 @@ +package com.example.dto.request + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.UUID +@Serializable +data class AddToWishlistRequest( + @Serializable(with = UuidSerializer::class) + val uuid: UUID, + val furnitureId: Long +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/ChangeCountFromCartRequest.kt b/src/main/kotlin/dto/request/ChangeCountFromCartRequest.kt new file mode 100644 index 0000000..8efa051 --- /dev/null +++ b/src/main/kotlin/dto/request/ChangeCountFromCartRequest.kt @@ -0,0 +1,12 @@ +package com.example.dto.request + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.UUID +@Serializable +data class ChangeCountFromCartRequest( + @Serializable(with = UuidSerializer::class) + val uuid: UUID, + val furnitureId: Long, + val count: Int, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/CreateOrderItemRequest.kt b/src/main/kotlin/dto/request/CreateOrderItemRequest.kt new file mode 100644 index 0000000..30c3cc9 --- /dev/null +++ b/src/main/kotlin/dto/request/CreateOrderItemRequest.kt @@ -0,0 +1,12 @@ +package com.example.dto.request + +import com.example.configure.BigDecimalSerializer +import kotlinx.serialization.Serializable +import java.math.BigDecimal +@Serializable +data class CreateOrderItemRequest( + val furnitureId : Long, + @Serializable(with = BigDecimalSerializer::class) + val furniturePrice: BigDecimal, + val count: Int +) diff --git a/src/main/kotlin/dto/request/CreateOrderRequest.kt b/src/main/kotlin/dto/request/CreateOrderRequest.kt new file mode 100644 index 0000000..9fd6f43 --- /dev/null +++ b/src/main/kotlin/dto/request/CreateOrderRequest.kt @@ -0,0 +1,17 @@ +package com.example.dto.request + +import com.example.configure.BigDecimalSerializer +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.math.BigDecimal +import java.util.UUID +@Serializable +data class CreateOrderRequest( + @Serializable(with = UuidSerializer::class) + val userUuid : UUID, + val addressId: Long, + val orderStatus : Int, + @Serializable(with = BigDecimalSerializer::class) + val orderTotalSum : BigDecimal, + val orderSet: List +) diff --git a/src/main/kotlin/dto/request/LoginRequest.kt b/src/main/kotlin/dto/request/LoginRequest.kt new file mode 100644 index 0000000..373918f --- /dev/null +++ b/src/main/kotlin/dto/request/LoginRequest.kt @@ -0,0 +1,6 @@ +package com.example.dto.request + +import kotlinx.serialization.Serializable + +@Serializable +data class LoginRequest(val email: String, val password: String) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/RegisterRequest.kt b/src/main/kotlin/dto/request/RegisterRequest.kt new file mode 100644 index 0000000..f456ca6 --- /dev/null +++ b/src/main/kotlin/dto/request/RegisterRequest.kt @@ -0,0 +1,11 @@ +package com.example.dto.request + +import kotlinx.serialization.Serializable + +@Serializable +data class RegisterRequest( + val firstName: String, + val lastName: String, + val email: String, + val password: String +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/RemoveFromCartRequest.kt b/src/main/kotlin/dto/request/RemoveFromCartRequest.kt new file mode 100644 index 0000000..8438633 --- /dev/null +++ b/src/main/kotlin/dto/request/RemoveFromCartRequest.kt @@ -0,0 +1,11 @@ +package com.example.dto.request + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.UUID +@Serializable +data class RemoveFromCartRequest( + @Serializable(with = UuidSerializer::class) + val uuid: UUID, + val furnitureId: Long, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/request/RemoveFromWishlistRequest.kt b/src/main/kotlin/dto/request/RemoveFromWishlistRequest.kt new file mode 100644 index 0000000..a67f331 --- /dev/null +++ b/src/main/kotlin/dto/request/RemoveFromWishlistRequest.kt @@ -0,0 +1,11 @@ +package com.example.dto.request + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.UUID +@Serializable +data class RemoveFromWishlistRequest( + @Serializable(with = UuidSerializer::class) + val uuid: UUID, + val furnitureId: Long +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/AddressResponse.kt b/src/main/kotlin/dto/response/AddressResponse.kt new file mode 100644 index 0000000..6fc0511 --- /dev/null +++ b/src/main/kotlin/dto/response/AddressResponse.kt @@ -0,0 +1,16 @@ +package com.example.dto.response + +import com.example.data.database.tables.AddressTable.integer +import com.example.data.database.tables.AddressTable.nullable +import com.example.data.database.tables.AddressTable.text +import kotlinx.serialization.Serializable + +@Serializable +data class AddressResponse( + val addressId: Long, + val entrance: Int, + val floor: Int, + val apartment: Int, + val comment: String, + val address: String, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/AllShopCategoryResponse.kt b/src/main/kotlin/dto/response/AllShopCategoryResponse.kt new file mode 100644 index 0000000..d1a972b --- /dev/null +++ b/src/main/kotlin/dto/response/AllShopCategoryResponse.kt @@ -0,0 +1,10 @@ +package com.example.dto.response + +import kotlinx.serialization.Serializable + +@Serializable +data class AllShopCategoryResponse( + val id: Long, + val name: String, + var furnitureList: List +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/CartResponse.kt b/src/main/kotlin/dto/response/CartResponse.kt new file mode 100644 index 0000000..839947d --- /dev/null +++ b/src/main/kotlin/dto/response/CartResponse.kt @@ -0,0 +1,11 @@ +package com.example.dto.response + +import com.example.configure.BigDecimalSerializer +import kotlinx.serialization.Serializable +import java.math.BigDecimal + +@Serializable +data class CartResponse( + val count: Int, + val furnitureResponse: FurnitureResponse +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/FurnitureCategoryResponse.kt b/src/main/kotlin/dto/response/FurnitureCategoryResponse.kt new file mode 100644 index 0000000..e07e9e9 --- /dev/null +++ b/src/main/kotlin/dto/response/FurnitureCategoryResponse.kt @@ -0,0 +1,9 @@ +package com.example.dto.response + +import kotlinx.serialization.Serializable + +@Serializable +data class FurnitureCategoryResponse( + val id: Int, + val name: String, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/FurnitureResponse.kt b/src/main/kotlin/dto/response/FurnitureResponse.kt new file mode 100644 index 0000000..0534203 --- /dev/null +++ b/src/main/kotlin/dto/response/FurnitureResponse.kt @@ -0,0 +1,19 @@ +package com.example.dto.response + +import com.example.configure.BigDecimalSerializer +import kotlinx.serialization.Serializable +import java.math.BigDecimal + +@Serializable +data class FurnitureResponse( + val id: Long, + val name: String, + val description: String, + val url: String, + val category: FurnitureCategoryResponse, + @Serializable(with = BigDecimalSerializer::class) + val price: BigDecimal, + @Serializable(with = BigDecimalSerializer::class) + val sale: BigDecimal, + var shopCategories: List, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/OrderItemResponse.kt b/src/main/kotlin/dto/response/OrderItemResponse.kt new file mode 100644 index 0000000..93d037a --- /dev/null +++ b/src/main/kotlin/dto/response/OrderItemResponse.kt @@ -0,0 +1,14 @@ +package com.example.dto.response + +import com.example.configure.BigDecimalSerializer +import kotlinx.serialization.Serializable +import java.math.BigDecimal +@Serializable +data class OrderItemResponse( + val furnitureId : Long, + val orderId : Long, + @Serializable(with = BigDecimalSerializer::class) + val furniturePrice: BigDecimal, + val count: Int, + val furnitureResponse: FurnitureResponse +) diff --git a/src/main/kotlin/dto/response/OrderResponse.kt b/src/main/kotlin/dto/response/OrderResponse.kt new file mode 100644 index 0000000..c6c4853 --- /dev/null +++ b/src/main/kotlin/dto/response/OrderResponse.kt @@ -0,0 +1,20 @@ +package com.example.dto.response + +import com.example.configure.BigDecimalSerializer +import com.example.configure.UuidSerializer +import kotlinx.datetime.LocalDateTime +import kotlinx.serialization.Serializable +import java.math.BigDecimal +import java.util.* +@Serializable +data class OrderResponse( + val id : Long, + @Serializable(with = UuidSerializer::class) + val userUuid : UUID, + val addressId: Long, + val dateTime: LocalDateTime, + val orderStatus : OrderStatusResponse, + @Serializable(with = BigDecimalSerializer::class) + val orderTotalSum : BigDecimal, + var orderSet: List +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/OrderStatusResponse.kt b/src/main/kotlin/dto/response/OrderStatusResponse.kt new file mode 100644 index 0000000..2a3718c --- /dev/null +++ b/src/main/kotlin/dto/response/OrderStatusResponse.kt @@ -0,0 +1,9 @@ +package com.example.dto.response + +import kotlinx.serialization.Serializable + +@Serializable +data class OrderStatusResponse( + val id: Int, + val name: String, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/SaleResponse.kt b/src/main/kotlin/dto/response/SaleResponse.kt new file mode 100644 index 0000000..fdc1fa7 --- /dev/null +++ b/src/main/kotlin/dto/response/SaleResponse.kt @@ -0,0 +1,10 @@ +package com.example.dto.response + +import kotlinx.serialization.Serializable + +@Serializable +data class SaleResponse( + val id: Int, + val name: String, + val url: String, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/ShopCategoryResponse.kt b/src/main/kotlin/dto/response/ShopCategoryResponse.kt new file mode 100644 index 0000000..fd3c72a --- /dev/null +++ b/src/main/kotlin/dto/response/ShopCategoryResponse.kt @@ -0,0 +1,9 @@ +package com.example.dto.response + +import kotlinx.serialization.Serializable + +@Serializable +data class ShopCategoryResponse( + val id: Long, + val name: String, +) \ No newline at end of file diff --git a/src/main/kotlin/dto/response/UserResponse.kt b/src/main/kotlin/dto/response/UserResponse.kt new file mode 100644 index 0000000..3aa7137 --- /dev/null +++ b/src/main/kotlin/dto/response/UserResponse.kt @@ -0,0 +1,15 @@ +package com.example.dto.response + +import com.example.configure.UuidSerializer +import kotlinx.serialization.Serializable +import java.util.* +@Serializable +data class UserResponse( + @Serializable(with = UuidSerializer::class) + val userUuid: UUID, + val email: String, + val firstName: String, + val lastName: String, + val imageUrl: String? = null, + var address: AddressResponse? = null, +) \ No newline at end of file diff --git a/src/main/kotlin/route/CartRoute.kt b/src/main/kotlin/route/CartRoute.kt new file mode 100644 index 0000000..6e1c155 --- /dev/null +++ b/src/main/kotlin/route/CartRoute.kt @@ -0,0 +1,31 @@ +package com.example.route + +import com.example.data.repository.CartRepository +import com.example.dto.request.AddToCartRequest +import com.example.dto.request.ChangeCountFromCartRequest +import com.example.dto.request.RemoveFromCartRequest +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.cartRoute(){ + val cartRepository = CartRepository() + route("/cart") { + post { + val addToCartRequest = call.receive() + val result = cartRepository.addToCartByUuid(addToCartRequest) + if (result) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) + } + delete { + val removeFromCartRequest = call.receive() + val result = cartRepository.removeFromCartByUuid(removeFromCartRequest) + if (result) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) + } + put{ + val changeCountFromCartRequest = call.receive() + val result = cartRepository.changeCountFromCartByUuid(changeCountFromCartRequest) + if (result) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/CategoryRoute.kt b/src/main/kotlin/route/CategoryRoute.kt new file mode 100644 index 0000000..8641bad --- /dev/null +++ b/src/main/kotlin/route/CategoryRoute.kt @@ -0,0 +1,21 @@ +package com.example.route + +import com.example.data.repository.CategoryRepository +import io.ktor.http.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.categoryRoute() { + val categoryRepository = CategoryRepository() + route("/category") { + get { + val result = categoryRepository.getAllCategories() + call.respond(HttpStatusCode.OK, result) + } + get("/{id}/furniture") { + val id = call.parameters["id"]?.toIntOrNull() ?: return@get call.respond(HttpStatusCode.BadRequest) + val result = categoryRepository.getFurnitureByCategory(id) + call.respond(HttpStatusCode.OK, result) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/FurnitureRoute.kt b/src/main/kotlin/route/FurnitureRoute.kt new file mode 100644 index 0000000..88fd5fb --- /dev/null +++ b/src/main/kotlin/route/FurnitureRoute.kt @@ -0,0 +1,41 @@ +package com.example.route + +import com.example.data.repository.FurnitureRepository +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.furnitureRoute() { + val furnitureRepository = FurnitureRepository() + route("/furniture") { + get { + val result = furnitureRepository.getAllFurniture() + call.respond(HttpStatusCode.OK, result) + } + get("{furnitureId}") { + val furnitureId = call.pathParameters["furnitureId"]?.toLong() + if (furnitureId == null) call.respond(HttpStatusCode.BadRequest) + furnitureId?.let { + try { + val result = furnitureRepository.getFurnitureById(it) + call.respond(HttpStatusCode.OK, result) + } + catch (e: Exception) { + call.respond(HttpStatusCode.NotFound) + } + } + } + get("/category/{categoryId}") { + val categoryId = call.pathParameters["categoryId"]?.toLong() + if (categoryId == null) call.respond(HttpStatusCode.BadRequest) + categoryId?.let { + val result = furnitureRepository.getFurnitureByCategory(it) + call.respond(HttpStatusCode.OK, result) + } + + } + + } + +} \ No newline at end of file diff --git a/src/main/kotlin/route/OrderRoute.kt b/src/main/kotlin/route/OrderRoute.kt new file mode 100644 index 0000000..cfc4a89 --- /dev/null +++ b/src/main/kotlin/route/OrderRoute.kt @@ -0,0 +1,19 @@ +package com.example.route + +import com.example.data.repository.OrderRepository +import com.example.dto.request.CreateOrderRequest +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.orderRoute() { + val orderRepository = OrderRepository() + route("/order") { + post { + val orderRequest = call.receive() + val result = orderRepository.createOrder(orderRequest) + if (result) call.respond(HttpStatusCode.Created) else call.respond(HttpStatusCode.Conflict) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/SaleRoute.kt b/src/main/kotlin/route/SaleRoute.kt new file mode 100644 index 0000000..9f2ca2a --- /dev/null +++ b/src/main/kotlin/route/SaleRoute.kt @@ -0,0 +1,17 @@ +package com.example.route + +import com.example.data.repository.SalesRepository +import io.ktor.http.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + + +fun Route.saleRoute() { + val salesRepository = SalesRepository() + route("/sale") { + get { + val result = salesRepository.getAllSales() + call.respond(HttpStatusCode.OK, result) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/ShopCategoryRoute.kt b/src/main/kotlin/route/ShopCategoryRoute.kt new file mode 100644 index 0000000..4ab79b7 --- /dev/null +++ b/src/main/kotlin/route/ShopCategoryRoute.kt @@ -0,0 +1,25 @@ +package com.example.route + +import com.example.data.repository.ShopCategoryRepository +import io.ktor.http.* +import io.ktor.http.content.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.shopCategoryRoute() { + val categoryRepository = ShopCategoryRepository() + route("/shop_category") { + get { + val result = categoryRepository.getAllShopCategory() + call.respond(HttpStatusCode.OK, result) + } + get("/{shopCategoryId}/furniture") { + val shopCategoryId = call.pathParameters["shopCategoryId"]?.toLong() + if (shopCategoryId == null) call.respond(HttpStatusCode.BadRequest) + shopCategoryId?.let { + val result = categoryRepository.getFurnitureByShopCategory(it) + call.respond(HttpStatusCode.OK, result) + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/UserRoute.kt b/src/main/kotlin/route/UserRoute.kt new file mode 100644 index 0000000..77b2752 --- /dev/null +++ b/src/main/kotlin/route/UserRoute.kt @@ -0,0 +1,77 @@ +package com.example.route + +import com.example.data.repository.CartRepository +import com.example.data.repository.OrderRepository +import com.example.data.repository.UserRepository +import com.example.data.repository.WishlistRepository +import com.example.dto.request.AddAddressRequest +import com.example.dto.request.AddToWishlistRequest +import com.example.dto.request.LoginRequest +import com.example.dto.request.RegisterRequest +import com.example.dto.response.AddressResponse +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import java.util.UUID + +fun Route.userRoute() { + val userRepository = UserRepository() + route("/auth") { + post("/login") { + val request = call.receive() + try { + val result = userRepository.login(request) + call.respond(HttpStatusCode.OK, result) + } + catch (e: Exception) { + call.respond(HttpStatusCode.NotFound) + } + } + post("/register") { + try { + val request = call.receive() + val result = userRepository.register(request) + call.respond(HttpStatusCode.OK, result) + } catch (e: Exception) { + call.respond(HttpStatusCode.NotFound) + } + } + } + route("/user"){ + val wishlistRepository = WishlistRepository() + val cartRepository = CartRepository() + val orderRepository = OrderRepository() + get("{uuid}/wishlist"){ + val uuid = call.parameters["uuid"] ?: return@get call.respond(HttpStatusCode.BadRequest) + val getByUuidCommand = UUID.fromString(uuid) + val result = wishlistRepository.getWishListByUuid(getByUuidCommand) + call.respond(HttpStatusCode.OK, result) + } + get("{uuid}/cart"){ + val uuid = call.parameters["uuid"] ?: return@get call.respond(HttpStatusCode.BadRequest) + val getByCartCommand = UUID.fromString(uuid) + val result = cartRepository.getCartByUuid(getByCartCommand) + call.respond(HttpStatusCode.OK, result) + } + get("{uuid}/order") { + val uuid = call.parameters["uuid"] ?: return@get call.respond(HttpStatusCode.BadRequest) + val getByOrderCommand = UUID.fromString(uuid) + val result = orderRepository.getOrdersByUuid(getByOrderCommand) + call.respond(HttpStatusCode.OK, result) + } + get("{uuid}/profile") { + val uuid = call.parameters["uuid"] ?: return@get call.respond(HttpStatusCode.BadRequest) + val getByOrderCommand = UUID.fromString(uuid) + val result = userRepository.getUserByUuid(getByOrderCommand) + call.respond(HttpStatusCode.OK, result) + } + post("{uuid}/address") { + val uuid = call.parameters["uuid"] ?: return@post call.respond(HttpStatusCode.BadRequest) + val getByOrderCommand = UUID.fromString(uuid) + val address = call.receive() + val result = userRepository.addAddressByUuid(getByOrderCommand, address) + call.respond(HttpStatusCode.OK, result) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/route/WishListRoute.kt b/src/main/kotlin/route/WishListRoute.kt new file mode 100644 index 0000000..5956123 --- /dev/null +++ b/src/main/kotlin/route/WishListRoute.kt @@ -0,0 +1,25 @@ +package com.example.route + +import com.example.data.repository.WishlistRepository +import com.example.dto.request.AddToWishlistRequest +import com.example.dto.request.RemoveFromWishlistRequest +import io.ktor.http.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import io.ktor.server.routing.* + +fun Route.wishlistRoute(){ + val wishlistRepository = WishlistRepository() + route("/wishlist"){ + post { + val addToWishlistRequest = call.receive() + val result = wishlistRepository.addToWishListByUuid(addToWishlistRequest) + if(result) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) + } + delete { + val removeFromWishlistRequest = call.receive() + val result = wishlistRepository.removeFromWishlistByUuid(removeFromWishlistRequest) + if(result) call.respond(HttpStatusCode.OK) else call.respond(HttpStatusCode.NotFound) + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..12b25cc --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,10 @@ +ktor: + application: + modules: + - com.example.ApplicationKt.module + deployment: + port: 8080 +jwt: + domain: "https://jwt-provider-domain/" + audience: "jwt-audience" + realm: "ktor sample app" diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..aadef5d --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/src/test/kotlin/ApplicationTest.kt b/src/test/kotlin/ApplicationTest.kt new file mode 100644 index 0000000..b30acd0 --- /dev/null +++ b/src/test/kotlin/ApplicationTest.kt @@ -0,0 +1,21 @@ +package com.example + +import io.ktor.client.request.* +import io.ktor.http.* +import io.ktor.server.testing.* +import kotlin.test.Test +import kotlin.test.assertEquals + +class ApplicationTest { + + @Test + fun testRoot() = testApplication { + application { + module() + } + client.get("/").apply { + assertEquals(HttpStatusCode.OK, status) + } + } + +}