commit 646a3ff7ff033e1eeae99a5e41d1420c853bfcab Author: llopez Date: Mon Mar 25 09:34:42 2024 -0500 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.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/ diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..5cdb0b3 --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: java -jar -Dspring.profiles.active=pdn build/libs/market-app-1.0.jar \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ddcca45 --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'org.springframework.boot' version '2.7.4' + id 'io.spring.dependency-management' version '1.0.14.RELEASE' + id 'java' +} + +group = 'com.cpro' +version = '1.0' +sourceCompatibility = '17' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-security' + + implementation 'io.springfox:springfox-swagger2:3.0.0' + implementation "io.springfox:springfox-boot-starter:3.0.0" + implementation 'io.springfox:springfox-swagger-ui:3.0.0' + runtimeOnly 'org.mariadb.jdbc:mariadb-java-client' + implementation 'org.mapstruct:mapstruct:1.5.2.Final' + implementation 'io.jsonwebtoken:jjwt:0.9.1' + annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.2.Final' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 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..8049c68 --- /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-7.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/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 \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..53a6b23 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@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% 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 diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..369602c --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'market-app' diff --git a/src/main/java/com/cpro/marketapp/MarketAppApplication.java b/src/main/java/com/cpro/marketapp/MarketAppApplication.java new file mode 100644 index 0000000..69a47eb --- /dev/null +++ b/src/main/java/com/cpro/marketapp/MarketAppApplication.java @@ -0,0 +1,13 @@ +package com.cpro.marketapp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MarketAppApplication { + + public static void main(String[] args) { + SpringApplication.run(MarketAppApplication.class, args); + } + +} diff --git a/src/main/java/com/cpro/marketapp/domain/Category.java b/src/main/java/com/cpro/marketapp/domain/Category.java new file mode 100644 index 0000000..89b450d --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/Category.java @@ -0,0 +1,31 @@ +package com.cpro.marketapp.domain; + +public class Category { + private int categoryId; + private String category; + private int active; + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public int getActive() { + return active; + } + + public void setActive(int active) { + this.active = active; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/Product.java b/src/main/java/com/cpro/marketapp/domain/Product.java new file mode 100644 index 0000000..659e1f8 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/Product.java @@ -0,0 +1,67 @@ +package com.cpro.marketapp.domain; + +public class Product { + private int productId; + private String name; + private int categoryId; + private double price; + private int stock; + private int active; + private Category category; + + public int getProductId() { + return productId; + } + + public void setProductId(int productId) { + this.productId = productId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getCategoryId() { + return categoryId; + } + + public void setCategoryId(int categoryId) { + this.categoryId = categoryId; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public int getStock() { + return stock; + } + + public void setStock(int stock) { + this.stock = stock; + } + + public int getActive() { + return active; + } + + public void setActive(int active) { + this.active = active; + } + + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/Purchase.java b/src/main/java/com/cpro/marketapp/domain/Purchase.java new file mode 100644 index 0000000..783fc2a --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/Purchase.java @@ -0,0 +1,70 @@ +package com.cpro.marketapp.domain; + +import java.time.LocalDateTime; +import java.util.List; + +public class Purchase { + private int purchaseId; + private String clientId; + private LocalDateTime date; + private String paymentMethod; + private String comment; + private String state; + private List item; + + public int getPurchaseId() { + return purchaseId; + } + + public void setPurchaseId(int purchaseId) { + this.purchaseId = purchaseId; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public LocalDateTime getDate() { + return date; + } + + public void setDate(LocalDateTime date) { + this.date = date; + } + + public String getPaymentMethod() { + return paymentMethod; + } + + public void setPaymentMethod(String paymentMethod) { + this.paymentMethod = paymentMethod; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public List getItem() { + return item; + } + + public void setItem(List item) { + this.item = item; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/PurchaseItem.java b/src/main/java/com/cpro/marketapp/domain/PurchaseItem.java new file mode 100644 index 0000000..5172617 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/PurchaseItem.java @@ -0,0 +1,46 @@ +package com.cpro.marketapp.domain; + + + +public class PurchaseItem { + private int productId; + private int quantity; + private double total; + private int active; + + public int getProductId() { + return productId; + } + + public void setProductId(int productId) { + this.productId = productId; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public double getTotal() { + return total; + } + + public void setTotal(double total) { + this.total = total; + } + + public int isActive() { + return active; + } + + public int getActive() { + return active; + } + + public void setActive(int active) { + this.active = active; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationRequest.java b/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationRequest.java new file mode 100644 index 0000000..f998d90 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationRequest.java @@ -0,0 +1,22 @@ +package com.cpro.marketapp.domain.dto; + +public class AuthenticationRequest { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationResponse.java b/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationResponse.java new file mode 100644 index 0000000..521b3cb --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/dto/AuthenticationResponse.java @@ -0,0 +1,16 @@ +package com.cpro.marketapp.domain.dto; + +public class AuthenticationResponse { + private String jwt; + public AuthenticationResponse(String jwt){ + this.jwt = jwt; + } + + public String getJwt() { + return jwt; + } + + public void setJwt(String jwt) { + this.jwt = jwt; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/repository/ProductRepository.java b/src/main/java/com/cpro/marketapp/domain/repository/ProductRepository.java new file mode 100644 index 0000000..9fa674c --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/repository/ProductRepository.java @@ -0,0 +1,17 @@ +package com.cpro.marketapp.domain.repository; + +import com.cpro.marketapp.domain.Product; +import com.cpro.marketapp.persistence.entity.Producto; + +import java.util.List; +import java.util.Optional; + +public interface ProductRepository { + List getAll(); + Optional> getByCategory(int categoryId); + Optional> getScerseProducts(int quantity); + Optional getProduct(int productId); + Product save(Product product); + void delete(int productId); + +} diff --git a/src/main/java/com/cpro/marketapp/domain/repository/PurchaseRepository.java b/src/main/java/com/cpro/marketapp/domain/repository/PurchaseRepository.java new file mode 100644 index 0000000..65c83a2 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/repository/PurchaseRepository.java @@ -0,0 +1,16 @@ +package com.cpro.marketapp.domain.repository; + +import com.cpro.marketapp.domain.Purchase; + +import java.util.List; +import java.util.Optional; + +public interface PurchaseRepository { + List getAll(); + Optional> getByClient(String clientId); + Optional getPurchase(int purchaseId); + + Purchase save(Purchase purchase); + + void delete(int purchaseId); +} diff --git a/src/main/java/com/cpro/marketapp/domain/service/ProductService.java b/src/main/java/com/cpro/marketapp/domain/service/ProductService.java new file mode 100644 index 0000000..f6e3083 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/service/ProductService.java @@ -0,0 +1,45 @@ +package com.cpro.marketapp.domain.service; + +import com.cpro.marketapp.domain.Product; +import com.cpro.marketapp.domain.repository.ProductRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class ProductService { + @Autowired + private ProductRepository productRepository; + + public List getAll(){ + return productRepository.getAll(); + } + + public Optional getProduct(int productId){ + return productRepository.getProduct(productId); + } + public Optional> getByCategory(int categoryId){ + return productRepository.getByCategory(categoryId); + } + public Product save(Product product){ + return productRepository.save(product); + } + public boolean delete(int productId){ + return getProduct(productId).map(product -> + { + productRepository.delete(productId); + return true; + }).orElse(false); + } + + public boolean delete2(int productId){ + boolean existe = false; + if(getProduct(productId).isPresent()){ + productRepository.delete(productId); + existe = true; + } + return existe; + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/service/PurchaseService.java b/src/main/java/com/cpro/marketapp/domain/service/PurchaseService.java new file mode 100644 index 0000000..f8d699b --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/service/PurchaseService.java @@ -0,0 +1,36 @@ +package com.cpro.marketapp.domain.service; + +import com.cpro.marketapp.domain.Purchase; +import com.cpro.marketapp.domain.repository.PurchaseRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class PurchaseService { + @Autowired + PurchaseRepository purchaseRepository; + + public List getAll(){ + return purchaseRepository.getAll(); + } + + public Optional> getByClientId(String clientId){ + return purchaseRepository.getByClient(clientId); + }; + public Purchase save(Purchase purchase){ + return purchaseRepository.save(purchase); + } + public Optional getPurchase(int purchaseId){ + return purchaseRepository.getPurchase(purchaseId); + } + public boolean delete(int purchaseId){ + return getPurchase(purchaseId).map(purchase -> { + purchaseRepository.delete(purchaseId); + return true; + + }).orElse(false); + } +} diff --git a/src/main/java/com/cpro/marketapp/domain/service/UserDetailService.java b/src/main/java/com/cpro/marketapp/domain/service/UserDetailService.java new file mode 100644 index 0000000..2942b69 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/domain/service/UserDetailService.java @@ -0,0 +1,18 @@ +package com.cpro.marketapp.domain.service; + +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; + +@Service +public class UserDetailService implements UserDetailsService { + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + return new User("paul","{noop}1234", new ArrayList<>()); + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/CompraRepository.java b/src/main/java/com/cpro/marketapp/persistence/CompraRepository.java new file mode 100644 index 0000000..58b3159 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/CompraRepository.java @@ -0,0 +1,48 @@ +package com.cpro.marketapp.persistence; + +import com.cpro.marketapp.domain.Purchase; +import com.cpro.marketapp.domain.repository.PurchaseRepository; +import com.cpro.marketapp.persistence.crud.CompraCrudRepository; +import com.cpro.marketapp.persistence.entity.Compra; +import com.cpro.marketapp.persistence.entity.Producto; +import com.cpro.marketapp.persistence.mapper.PurchaseMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public class CompraRepository implements PurchaseRepository { + @Autowired + private CompraCrudRepository compraCrudRepository; + @Autowired + private PurchaseMapper mapper; + + @Override + public List getAll() { + return mapper.toPurchases((List) compraCrudRepository.findAll()); + } + + @Override + public Optional> getByClient(String clientId) { + return compraCrudRepository.findByIdCliente(clientId) + .map(compras -> mapper.toPurchases(compras)); + } + + @Override + public Optional getPurchase(int purchaseId) { + return compraCrudRepository.findById(purchaseId).map(compra -> mapper.toPurchase(compra)); + } + + @Override + public Purchase save(Purchase purchase) { + Compra compra = mapper.toCompra(purchase); + compra.getLstComprasProductos().forEach(producto->producto.setCompra(compra)); + return mapper.toPurchase(compraCrudRepository.save(compra)); + } + @Override + public void delete(int purchaseId){ + compraCrudRepository.deleteById(purchaseId); + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/ProductoRepository.java b/src/main/java/com/cpro/marketapp/persistence/ProductoRepository.java new file mode 100644 index 0000000..df49fdf --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/ProductoRepository.java @@ -0,0 +1,58 @@ +package com.cpro.marketapp.persistence; + +import com.cpro.marketapp.domain.Product; +import com.cpro.marketapp.domain.repository.ProductRepository; +import com.cpro.marketapp.persistence.crud.ProductoCrudRepository; +import com.cpro.marketapp.persistence.entity.Producto; +import com.cpro.marketapp.persistence.mapper.ProductMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public class ProductoRepository implements ProductRepository { + @Autowired + private ProductoCrudRepository productoCrudRepository; + @Autowired + private ProductMapper mapper; + + @Override + public List getAll(){ + List productos = (List) productoCrudRepository.findAll(); + return mapper.toProducts(productos); + } + + @Override + public Optional> getByCategory(int categoryId) { + List productos = (List) productoCrudRepository.findByIdCategoriaOrderByNombreAsc(categoryId); + return Optional.of(mapper.toProducts(productos)); + } + + @Override + public Optional> getScerseProducts(int quantity) { + Optional> productos = productoCrudRepository.findByCantidadStockLessThanAndEstado(quantity, 1); + + return productos.map(prods-> mapper.toProducts(prods)); + } + + @Override + public Optional getProduct(int productId) { + return productoCrudRepository.findById(productId).map(producto -> mapper.toProduct(producto)); + } + + @Override + public Product save(Product product) { + return mapper.toProduct(productoCrudRepository.save(mapper.toProducto(product))); + } + + + public Producto save(Producto producto){ + return productoCrudRepository.save(producto); + } + @Override + public void delete(int idProducto){ + productoCrudRepository.deleteById(idProducto); + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/crud/CompraCrudRepository.java b/src/main/java/com/cpro/marketapp/persistence/crud/CompraCrudRepository.java new file mode 100644 index 0000000..16dd937 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/crud/CompraCrudRepository.java @@ -0,0 +1,11 @@ +package com.cpro.marketapp.persistence.crud; + +import com.cpro.marketapp.persistence.entity.Compra; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; +import java.util.Optional; + +public interface CompraCrudRepository extends CrudRepository { + Optional> findByIdCliente(String idCliente); +} diff --git a/src/main/java/com/cpro/marketapp/persistence/crud/ProductoCrudRepository.java b/src/main/java/com/cpro/marketapp/persistence/crud/ProductoCrudRepository.java new file mode 100644 index 0000000..2780c77 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/crud/ProductoCrudRepository.java @@ -0,0 +1,18 @@ +package com.cpro.marketapp.persistence.crud; + +import com.cpro.marketapp.persistence.entity.Producto; +import org.springframework.data.repository.CrudRepository; + +import java.util.List; +import java.util.Optional; + +public interface ProductoCrudRepository extends CrudRepository { + + //@Query(value = "SELECT * FROM PRODUCTOS WHERE id_categoria = ?", nativeQuery = true) + List findByIdCategoriaOrderByNombreAsc(int idCategoria); + + Optional> findByCantidadStockLessThanAndEstado(int cantidadStock, int estado ); + + + +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/Categoria.java b/src/main/java/com/cpro/marketapp/persistence/entity/Categoria.java new file mode 100644 index 0000000..e65a465 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/Categoria.java @@ -0,0 +1,51 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "CATEGORIAS") +public class Categoria { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_categoria") + private Integer idCategoria; + + private String descripcion; + + private Integer estado; + @OneToMany(mappedBy = "categoria") + private List lstProductos; + public Integer getIdCategoria() { + return idCategoria; + } + + public void setIdCategoria(Integer idCategoria) { + this.idCategoria = idCategoria; + } + + public String getDescripcion() { + return descripcion; + } + + public void setDescripcion(String descripcion) { + this.descripcion = descripcion; + } + + + public Integer getEstado() { + return estado; + } + + public void setEstado(Integer estado) { + this.estado = estado; + } + + public List getLstProductos() { + return lstProductos; + } + + public void setLstProductos(List lstProductos) { + this.lstProductos = lstProductos; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/Cliente.java b/src/main/java/com/cpro/marketapp/persistence/entity/Cliente.java new file mode 100644 index 0000000..eb7e4d9 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/Cliente.java @@ -0,0 +1,69 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.*; +import java.util.List; + +@Entity +@Table(name = "CLIENTES") +public class Cliente { + + @Id + private String id; + private String nombre; + private String apellidos; + private Double celular; + private String direccion; + @Column(name = "correo_electronico") + private String correoElectronico; + + @OneToMany(mappedBy = "cliente") + private List lstCompras; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellidos() { + return apellidos; + } + + public void setApellidos(String apellidos) { + this.apellidos = apellidos; + } + + public Double getCelular() { + return celular; + } + + public void setCelular(Double celular) { + this.celular = celular; + } + + public String getDireccion() { + return direccion; + } + + public void setDireccion(String direccion) { + this.direccion = direccion; + } + + public String getCorreoElectronico() { + return correoElectronico; + } + + public void setCorreoElectronico(String correoElectronico) { + this.correoElectronico = correoElectronico; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/Compra.java b/src/main/java/com/cpro/marketapp/persistence/entity/Compra.java new file mode 100644 index 0000000..5f1ff0c --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/Compra.java @@ -0,0 +1,97 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.*; +import java.time.LocalDateTime; +import java.util.List; + +@Entity +@Table(name = "COMPRAS") +public class Compra { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_compra") + private Integer idCompra; + + @Column(name = "id_cliente") + private String idCliente; + + private LocalDateTime fecha; + @Column(name = "medio_pago") + private String medioPago; + + private String comentario; + + private String estado; + + @ManyToOne + @JoinColumn(name = "id_cliente", insertable = false,updatable = false) + private Cliente cliente; + + @OneToMany(mappedBy = "compra", cascade = {CascadeType.ALL}) + private List lstComprasProductos; + + public Integer getIdCompra() { + return idCompra; + } + + public void setIdCompra(Integer idCompra) { + this.idCompra = idCompra; + } + + public String getIdCliente() { + return idCliente; + } + + public void setIdCliente(String id_cliente) { + this.idCliente = id_cliente; + } + + public LocalDateTime getFecha() { + return fecha; + } + + public void setFecha(LocalDateTime fecha) { + this.fecha = fecha; + } + + public String getMedioPago() { + return medioPago; + } + + public void setMedioPago(String medioPago) { + this.medioPago = medioPago; + } + + public String getComentario() { + return comentario; + } + + public void setComentario(String comentario) { + this.comentario = comentario; + } + + public String getEstado() { + return estado; + } + + public void setEstado(String estado) { + this.estado = estado; + } + + public Cliente getCliente() { + return cliente; + } + + public void setCliente(Cliente cliente) { + this.cliente = cliente; + } + + public List getLstComprasProductos() { + return lstComprasProductos; + } + + public void setLstComprasProductos(List lstComprasProductos) { + this.lstComprasProductos = lstComprasProductos; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProducto.java b/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProducto.java new file mode 100644 index 0000000..b7287e7 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProducto.java @@ -0,0 +1,69 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.*; + +@Entity +@Table(name="COMPRAS_PRODUCTOS") +public class ComprasProducto { + @EmbeddedId + private ComprasProductosPK id; + + private Integer cantidad; + + private Double total; + + private Integer estado; + + @ManyToOne + @MapsId("idCompra") + @JoinColumn(name = "id_compra", insertable = false,updatable = false) + private Compra compra; + + @ManyToOne + @JoinColumn(name = "id_producto", insertable = false,updatable = false) + private Producto producto; + + public ComprasProductosPK getId() { + return id; + } + + public void setId(ComprasProductosPK id) { + this.id = id; + } + + public Integer getCantidad() { + return cantidad; + } + + public void setCantidad(Integer cantidad) { + this.cantidad = cantidad; + } + + public Double getTotal() { + return total; + } + + public void setTotal(Double total) { + this.total = total; + } + + public Integer getEstado() { + return estado; + } + + public void setEstado(Integer estado) { + this.estado = estado; + } + + public Compra getCompra() { + return compra; + } + + public Producto getProducto() { + return producto; + } + + public void setCompra(Compra compra) { + this.compra = compra; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProductosPK.java b/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProductosPK.java new file mode 100644 index 0000000..6e9c517 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/ComprasProductosPK.java @@ -0,0 +1,29 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import java.io.Serializable; + +@Embeddable +public class ComprasProductosPK implements Serializable { + @Column(name="id_compra") + private Integer idCompra; + @Column(name="id_producto") + private Integer idProducto; + + public Integer getIdCompra() { + return idCompra; + } + + public void setIdCompra(Integer idCompra) { + this.idCompra = idCompra; + } + + public Integer getIdProducto() { + return idProducto; + } + + public void setIdProducto(Integer idProducto) { + this.idProducto = idProducto; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/entity/Producto.java b/src/main/java/com/cpro/marketapp/persistence/entity/Producto.java new file mode 100644 index 0000000..549bdfc --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/entity/Producto.java @@ -0,0 +1,97 @@ +package com.cpro.marketapp.persistence.entity; + +import javax.persistence.*; + +@Entity +@Table(name = "`PRODUCTOS`") +public class Producto { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_producto") + private Integer idProducto; + + private String nombre; + + @Column(name = "id_categoria") + private Integer idCategoria; + + @Column(name = "codigo_barras") + private String codigoBarras; + + @Column(name = "precio_venta") + private Double precioVenta; + + @Column(name = "cantidad_stock") + private Integer cantidadStock; + + private Integer estado; + + /** ++++++++++++++++++++++ relaciones +++++++++++++++++++++++=*/ + @ManyToOne + @JoinColumn(name = "id_categoria", insertable = false, updatable = false) + private Categoria categoria; + + public Integer getIdProducto() { + return idProducto; + } + + public void setIdProducto(Integer idProducto) { + this.idProducto = idProducto; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public Integer getIdCategoria() { + return idCategoria; + } + + public void setIdCategoria(Integer idCategoria) { + this.idCategoria = idCategoria; + } + + public String getCodigoBarras() { + return codigoBarras; + } + + public void setCodigoBarras(String codigoBarras) { + this.codigoBarras = codigoBarras; + } + + public Double getPrecioVenta() { + return precioVenta; + } + + public void setPrecioVenta(Double precioVenta) { + this.precioVenta = precioVenta; + } + + public Integer getCantidadStock() { + return cantidadStock; + } + + public void setCantidadStock(Integer cantidadStock) { + this.cantidadStock = cantidadStock; + } + + public Integer getEstado() { + return estado; + } + + public void setEstado(Integer estado) { + this.estado = estado; + } + + public Categoria getCategoria() { + return categoria; + } + + public void setCategoria(Categoria categoria) { + this.categoria = categoria; + } +} diff --git a/src/main/java/com/cpro/marketapp/persistence/mapper/CategoryMapper.java b/src/main/java/com/cpro/marketapp/persistence/mapper/CategoryMapper.java new file mode 100644 index 0000000..3b8e391 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/mapper/CategoryMapper.java @@ -0,0 +1,24 @@ +package com.cpro.marketapp.persistence.mapper; + +import com.cpro.marketapp.domain.Category; +import com.cpro.marketapp.persistence.entity.Categoria; +import org.mapstruct.InheritInverseConfiguration; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +@Mapper(componentModel = "spring") +public interface CategoryMapper { + + @Mappings({ + @Mapping(source = "idCategoria", target = "categoryId"), + @Mapping(source = "descripcion", target = "category"), + @Mapping(source = "estado", target = "active") + }) + Category toCategory(Categoria categoria); + + @InheritInverseConfiguration + @Mapping(target="lstProductos", ignore = true) + Categoria toCategoria(Category category); + +} diff --git a/src/main/java/com/cpro/marketapp/persistence/mapper/ProductMapper.java b/src/main/java/com/cpro/marketapp/persistence/mapper/ProductMapper.java new file mode 100644 index 0000000..f9d1b50 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/mapper/ProductMapper.java @@ -0,0 +1,30 @@ +package com.cpro.marketapp.persistence.mapper; + +import com.cpro.marketapp.domain.Product; +import com.cpro.marketapp.persistence.entity.Producto; +import org.mapstruct.InheritInverseConfiguration; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +import java.util.List; + +@Mapper(componentModel = "spring", uses = {CategoryMapper.class}) +public interface ProductMapper { + @Mappings({ + @Mapping(source = "idProducto", target="productId"), + @Mapping(source = "nombre", target="name"), + @Mapping(source = "idCategoria", target="categoryId"), + @Mapping(source = "precioVenta", target="price"), + @Mapping(source = "cantidadStock", target="stock"), + @Mapping(source = "estado", target="active"), + @Mapping(source = "categoria", target="category"), + }) + Product toProduct(Producto producto); + List toProducts(List productos); + @InheritInverseConfiguration + @Mapping(target="codigoBarras", ignore = true) + Producto toProducto(Product product); + + +} diff --git a/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseItemMapper.java b/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseItemMapper.java new file mode 100644 index 0000000..fdf22ec --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseItemMapper.java @@ -0,0 +1,26 @@ +package com.cpro.marketapp.persistence.mapper; + +import com.cpro.marketapp.domain.Purchase; +import com.cpro.marketapp.domain.PurchaseItem; +import com.cpro.marketapp.persistence.entity.ComprasProducto; +import org.mapstruct.*; + +@Mapper(componentModel = "spring", uses = {ProductMapper.class}) +public interface PurchaseItemMapper { + @Mappings({ + @Mapping(source="id.idProducto", target ="productId" ), + @Mapping(source="cantidad", target ="quantity" ), + @Mapping(source="estado", target ="active" ) + }) + + PurchaseItem toPorchaseItem(ComprasProducto producto); + @InheritInverseConfiguration + @Mappings( + { + @Mapping(target = "compra", ignore = true), + @Mapping(target = "producto", ignore = true), + @Mapping(target = "id.idCompra", ignore = true), + } + ) + ComprasProducto toComprasProducto(PurchaseItem item); +} diff --git a/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseMapper.java b/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseMapper.java new file mode 100644 index 0000000..af50061 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/persistence/mapper/PurchaseMapper.java @@ -0,0 +1,31 @@ +package com.cpro.marketapp.persistence.mapper; + +import com.cpro.marketapp.domain.Purchase; +import com.cpro.marketapp.domain.PurchaseItem; +import com.cpro.marketapp.persistence.entity.Compra; +import org.mapstruct.InheritInverseConfiguration; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.Mappings; + +import java.util.List; + +@Mapper(componentModel = "spring", uses = {PurchaseItemMapper.class}) +public interface PurchaseMapper { + @Mappings({ + @Mapping(source = "idCompra", target = "purchaseId"), + @Mapping(source = "idCliente", target = "clientId"), + @Mapping(source = "fecha", target = "date"), + @Mapping(source = "medioPago", target = "paymentMethod"), + @Mapping(source = "comentario", target = "comment"), + @Mapping(source = "estado", target = "state"), + @Mapping(source = "lstComprasProductos", target = "item") + + }) + Purchase toPurchase(Compra compra); + List toPurchases(List compras); + + @InheritInverseConfiguration + @Mapping(target = "cliente", ignore = true) + Compra toCompra(Purchase purchsae); +} diff --git a/src/main/java/com/cpro/marketapp/web/config/SwaggerConfig.java b/src/main/java/com/cpro/marketapp/web/config/SwaggerConfig.java new file mode 100644 index 0000000..44462af --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/config/SwaggerConfig.java @@ -0,0 +1,23 @@ +package com.cpro.marketapp.web.config; + +import org.apache.coyote.Request; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableWebMvc +@EnableSwagger2 +public class SwaggerConfig { + @Bean + public Docket apo(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("com.cpro.marketapp.web.controller")) + .build(); + } +} diff --git a/src/main/java/com/cpro/marketapp/web/controller/AuthController.java b/src/main/java/com/cpro/marketapp/web/controller/AuthController.java new file mode 100644 index 0000000..c4b01fe --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/controller/AuthController.java @@ -0,0 +1,42 @@ +package com.cpro.marketapp.web.controller; + +import com.cpro.marketapp.domain.dto.AuthenticationRequest; +import com.cpro.marketapp.domain.dto.AuthenticationResponse; +import com.cpro.marketapp.domain.service.UserDetailService; +import com.cpro.marketapp.web.security.JWTUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/auth") +public class AuthController { + @Autowired + private AuthenticationManager authenticationManager; + @Autowired + private UserDetailService userDetailService; + + @Autowired + private JWTUtil jwtUtil; + + @PostMapping("authenticate") + public ResponseEntity createToken(@RequestBody AuthenticationRequest request){ + try { + authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())); + UserDetails userDetails = userDetailService.loadUserByUsername(request.getUsername()); + String jwt = jwtUtil.generateToken(userDetails); + return new ResponseEntity<>(new AuthenticationResponse(jwt), HttpStatus.OK); + }catch (BadCredentialsException e){ + return new ResponseEntity<>(HttpStatus.FORBIDDEN); + } + + } +} diff --git a/src/main/java/com/cpro/marketapp/web/controller/ProductController.java b/src/main/java/com/cpro/marketapp/web/controller/ProductController.java new file mode 100644 index 0000000..4c45433 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/controller/ProductController.java @@ -0,0 +1,57 @@ +package com.cpro.marketapp.web.controller; + +import com.cpro.marketapp.domain.Product; +import com.cpro.marketapp.domain.service.ProductService; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.Optional; + +@RestController +@RequestMapping("/products") +public class ProductController { + @Autowired + private ProductService productService; + @GetMapping("/all") + @ApiOperation("Get all supermarket operations :-)") + @ApiResponse(code = 200, message = "OK") + public ResponseEntity>getAll(){ + return new ResponseEntity<>(productService.getAll(), HttpStatus.OK); + } + @GetMapping("/{id}") + @ApiOperation("Get producto by productId ") + @ApiResponses({ + @ApiResponse(code = 200, message = "OK"), + @ApiResponse(code = 404, message = "Product Not found") + }) + public ResponseEntity getProduct(@ApiParam(value = "the id of the product", required = true, example = "7") @PathVariable("id") int productId){ + return productService.getProduct(productId).map(product -> new ResponseEntity<>(product, HttpStatus.OK)) + .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + @GetMapping("/category/{id}") + public ResponseEntity> getByCategory(@PathVariable("id") int categoryId){ + return productService.getByCategory(categoryId) + .map(products -> new ResponseEntity<>(products, HttpStatus.OK)) + .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + @PostMapping("/save") + public ResponseEntity save(@RequestBody Product product){ + return new ResponseEntity<>(productService.save(product), HttpStatus.CREATED) ; + } + @DeleteMapping("/delete/{id}") + public ResponseEntity delete(@PathVariable("id") int productId){ + if(productService.delete(productId)){ + return new ResponseEntity(HttpStatus.OK); + }else { + return new ResponseEntity(HttpStatus.NOT_FOUND); + + } + } +} diff --git a/src/main/java/com/cpro/marketapp/web/controller/PurchaseController.java b/src/main/java/com/cpro/marketapp/web/controller/PurchaseController.java new file mode 100644 index 0000000..c86d9ff --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/controller/PurchaseController.java @@ -0,0 +1,40 @@ +package com.cpro.marketapp.web.controller; + +import com.cpro.marketapp.domain.Purchase; +import com.cpro.marketapp.domain.service.PurchaseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/purchase") +public class PurchaseController { + @Autowired + PurchaseService purchaseService; + + @GetMapping("/all") + public ResponseEntity> getAll(){ + return new ResponseEntity<>(purchaseService.getAll(), HttpStatus.OK); + } + @GetMapping("/{id}") + public ResponseEntity getPurchase(@PathVariable("id") int purchaseId){ + return purchaseService.getPurchase(purchaseId).map(purchase -> new ResponseEntity<>(purchase, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + @GetMapping("client/{id}") + public ResponseEntity> getByClient(@PathVariable("id") String clientId){ + return purchaseService.getByClientId(clientId).map(purchases -> new ResponseEntity<>(purchases, HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); + } + + @PostMapping("/save") + public ResponseEntity save(@RequestBody Purchase purchase){ + return new ResponseEntity<>(purchaseService.save(purchase),HttpStatus.CREATED); + } + @DeleteMapping("/delete/{id}") + public ResponseEntity delete(@PathVariable("id") int id){ + return purchaseService.delete(id) ? new ResponseEntity(HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); + } + +} diff --git a/src/main/java/com/cpro/marketapp/web/security/JWTUtil.java b/src/main/java/com/cpro/marketapp/web/security/JWTUtil.java new file mode 100644 index 0000000..c96ac3e --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/security/JWTUtil.java @@ -0,0 +1,38 @@ +package com.cpro.marketapp.web.security; + +import com.cpro.marketapp.domain.service.UserDetailService; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.util.Date; +@Component +public class JWTUtil { + private static final String KEY = "clave"; + public String generateToken(UserDetails userDetails){ + return Jwts.builder().setSubject(userDetails.getUsername()).setIssuedAt(new Date()) + .setExpiration(new Date(System.currentTimeMillis()+1000*60*60*10)) + .signWith(SignatureAlgorithm.HS256, KEY).compact(); + } + + /**Validar token si es correcto*/ + public boolean validateToken(String token, UserDetails userDetails){ + return userDetails.getUsername().equals(extractUsername(token)) && !isTokenExpired(token); + + } + + public String extractUsername(String token){ + return getClaims(token).getSubject(); + + } + public boolean isTokenExpired(String token){ + return getClaims(token).getExpiration().before(new Date()); + } + private Claims getClaims(String token){ + return Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody(); + + } +} diff --git a/src/main/java/com/cpro/marketapp/web/security/SecurityConfig.java b/src/main/java/com/cpro/marketapp/web/security/SecurityConfig.java new file mode 100644 index 0000000..534be25 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/security/SecurityConfig.java @@ -0,0 +1,42 @@ +package com.cpro.marketapp.web.security; + +import com.cpro.marketapp.domain.service.UserDetailService; +import com.cpro.marketapp.web.security.filter.JwtFilterRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +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.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + @Autowired + private UserDetailService userDetailService; + @Autowired + private JwtFilterRequest jwtFilterRequest; + + + @Override + protected void configure(HttpSecurity http)throws Exception{ + http.csrf().disable().authorizeRequests().antMatchers("/**/authenticate").permitAll() + .anyRequest().authenticated().and().sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS); + http.addFilterBefore(jwtFilterRequest, UsernamePasswordAuthenticationFilter.class); + } + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception{ + auth.userDetailsService(userDetailService); + } + +} diff --git a/src/main/java/com/cpro/marketapp/web/security/filter/JwtFilterRequest.java b/src/main/java/com/cpro/marketapp/web/security/filter/JwtFilterRequest.java new file mode 100644 index 0000000..76ead05 --- /dev/null +++ b/src/main/java/com/cpro/marketapp/web/security/filter/JwtFilterRequest.java @@ -0,0 +1,44 @@ +package com.cpro.marketapp.web.security.filter; + +import com.cpro.marketapp.domain.service.UserDetailService; +import com.cpro.marketapp.web.security.JWTUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class JwtFilterRequest extends OncePerRequestFilter { + @Autowired + private JWTUtil jwtUtil; + + @Autowired + private UserDetailService userDetailService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String authorizationHeader = request.getHeader("Authorization"); + if(authorizationHeader != null && authorizationHeader.startsWith("Bearer")){ + String jwt = authorizationHeader.substring(7); + String username = jwtUtil.extractUsername(jwt); + if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){ + UserDetails userDetails = userDetailService.loadUserByUsername(username); + if(jwtUtil.validateToken(jwt, userDetails)){ + UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authToken); + } + } + } + filterChain.doFilter(request, response); + } +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties new file mode 100644 index 0000000..a5e26d1 --- /dev/null +++ b/src/main/resources/application-dev.properties @@ -0,0 +1,6 @@ +server.port=8086 + +# ==================== DATABASE ==================== +spring.datasource.url=jdbc:mariadb://localhost:3306/market?useUnicode=true&characterEncoding=UTF8&useSSL=false +spring.datasource.username=market +spring.datasource.password=Cpro123db diff --git a/src/main/resources/application-pdn.properties b/src/main/resources/application-pdn.properties new file mode 100644 index 0000000..cf38506 --- /dev/null +++ b/src/main/resources/application-pdn.properties @@ -0,0 +1,5 @@ +server.port=80 +# ==================== DATABASE ==================== +spring.datasource.url=jdbc:mariadb://localhost:3306/market?useUnicode=true&characterEncoding=UTF8&useSSL=false +spring.datasource.username=market +spring.datasource.password=Cpro123db \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..fcd5bd9 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.profiles.active=dev +server.servlet.context-path=/market-app/api +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/src/test/java/com/cpro/marketapp/MarketAppApplicationTests.java b/src/test/java/com/cpro/marketapp/MarketAppApplicationTests.java new file mode 100644 index 0000000..d7a9614 --- /dev/null +++ b/src/test/java/com/cpro/marketapp/MarketAppApplicationTests.java @@ -0,0 +1,13 @@ +package com.cpro.marketapp; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MarketAppApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/system.properties b/system.properties new file mode 100644 index 0000000..0dc726c --- /dev/null +++ b/system.properties @@ -0,0 +1 @@ +java.runtime.version=17 \ No newline at end of file