From 4dd74efcd2a25d57bf1ade80c90c013b4f40d48f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Piskorski?= Date: Sun, 17 Jan 2021 17:06:06 +0100 Subject: [PATCH] TAK-77 TAK-79 company model & calculator manager --- app/app.R | 19 ++- app/calculator.R | 19 +-- app/calculator_view.R | 145 ++++++++++++++++++ app/login_module.R | 15 +- app/profil_module.R | 120 ++++++++++----- app/register_module.R | 24 ++- app/routing_module.R | 3 + .../main/java/project/DTO/CompanyDataDTO.java | 56 +++++++ .../java/project/DTO/CompanyProfileDTO.java | 36 +++++ .../java/project/DTO/PersonalDataDTO.java | 55 +++++++ .../java/project/DTO/PersonalProfileDTO.java | 36 +++++ .../main/java/project/DTO/PredictionDTO.java | 6 + .../src/main/java/project/DTO/UserDTO.java | 33 +--- .../controllers/AuthenticationController.java | 36 ++++- .../controllers/CompanyProfileController.java | 48 ++++++ .../controllers/PredictionController.java | 80 +++++++++- .../project/controllers/UserController.java | 130 +++++++++------- .../main/java/project/model/CompanyData.java | 52 +++++++ .../java/project/model/CompanyProfile.java | 60 ++++++++ .../main/java/project/model/PersonalData.java | 54 +++++++ .../java/project/model/PersonalProfile.java | 58 +++++++ .../main/java/project/model/Prediction.java | 6 + backend/src/main/java/project/model/User.java | 58 +++---- .../repositories/CompanyDataRepository.java | 11 ++ .../CompanyProfileRepository.java | 19 +++ .../repositories/PersonalDataRepository.java | 9 ++ .../PersonalProfileRepository.java | 16 ++ .../project/repositories/UserRepository.java | 2 +- .../project/services/CompanyDataService.java | 10 ++ .../services/CompanyDataServiceImpl.java | 37 +++++ .../services/CompanyProfileService.java | 17 ++ .../services/CompanyProfileServiceImpl.java | 54 +++++++ .../java/project/services/GeneratorDTO.java | 22 ++- .../project/services/PersonalDataService.java | 10 ++ .../services/PersonalDataServiceImpl.java | 38 +++++ .../services/PersonalProfileService.java | 12 ++ .../services/PersonalProfileServiceImpl.java | 42 +++++ .../project/services/PredictionService.java | 1 + .../services/PredictionServiceImpl.java | 11 ++ .../java/project/services/UserService.java | 3 +- .../project/services/UserServiceImpl.java | 12 +- .../project/services/UserServiceImplTest.java | 18 ++- 42 files changed, 1272 insertions(+), 221 deletions(-) create mode 100644 app/calculator_view.R create mode 100644 backend/src/main/java/project/DTO/CompanyDataDTO.java create mode 100644 backend/src/main/java/project/DTO/CompanyProfileDTO.java create mode 100644 backend/src/main/java/project/DTO/PersonalDataDTO.java create mode 100644 backend/src/main/java/project/DTO/PersonalProfileDTO.java create mode 100644 backend/src/main/java/project/controllers/CompanyProfileController.java create mode 100644 backend/src/main/java/project/model/CompanyData.java create mode 100644 backend/src/main/java/project/model/CompanyProfile.java create mode 100644 backend/src/main/java/project/model/PersonalData.java create mode 100644 backend/src/main/java/project/model/PersonalProfile.java create mode 100644 backend/src/main/java/project/repositories/CompanyDataRepository.java create mode 100644 backend/src/main/java/project/repositories/CompanyProfileRepository.java create mode 100644 backend/src/main/java/project/repositories/PersonalDataRepository.java create mode 100644 backend/src/main/java/project/repositories/PersonalProfileRepository.java create mode 100644 backend/src/main/java/project/services/CompanyDataService.java create mode 100644 backend/src/main/java/project/services/CompanyDataServiceImpl.java create mode 100644 backend/src/main/java/project/services/CompanyProfileService.java create mode 100644 backend/src/main/java/project/services/CompanyProfileServiceImpl.java create mode 100644 backend/src/main/java/project/services/PersonalDataService.java create mode 100644 backend/src/main/java/project/services/PersonalDataServiceImpl.java create mode 100644 backend/src/main/java/project/services/PersonalProfileService.java create mode 100644 backend/src/main/java/project/services/PersonalProfileServiceImpl.java diff --git a/app/app.R b/app/app.R index ad51499..db15f91 100644 --- a/app/app.R +++ b/app/app.R @@ -21,7 +21,11 @@ ui <- fluidPage( tags$script('var token = sessionStorage.getItem(\'token\'); $(document).on("shiny:sessioninitialized",function(event){ - Shiny.onInputChange("token", token);});'), + if(token!=null){ + Shiny.onInputChange("token", token); + Shiny.onInputChange("auth", 1); + } +});'), tags$script('Shiny.addCustomMessageHandler("tokenHandler", function(token) { sessionStorage.setItem(\'token\', token); @@ -31,16 +35,16 @@ tags$script('Shiny.addCustomMessageHandler("tokenHandler", );'), tags$script('Shiny.addCustomMessageHandler("tokenHandlerAccess", function(token) { - if(token=="#!/profil" || token=="#!/calculator"){ + if(token=="#!/profil" || token=="#!/calculator" || token=="#!/iota"){ let token = sessionStorage.getItem(\'token\'); if(token==null || token==undefined){ window.location.replace(\'/#!/home\'); }}} );'), -tags$script(' - -$(document).on("shiny:visualchange",function(event){ -Shiny.onInputChange("reload", new Date().getTime());});') +# tags$script(' +# +# $(document).on("shiny:visualchange",function(event){ +# Shiny.onInputChange("reload", new Date().getTime());});') ), uiOutput("logged"), @@ -150,7 +154,7 @@ server <- shinyServer(function(input, output, session){ output$logged<-renderUI({ - if(is.null(input$token)){ + if(is.null(input$auth)){ fluidRow( inlineCSS(list(.clicked = "background-color: #008375 !important")), @@ -201,6 +205,7 @@ server <- shinyServer(function(input, output, session){ shinyjs::runjs( 'sessionStorage.removeItem(\'token\'); Shiny.onInputChange("token", null); + Shiny.onInputChange("auth", null); window.location.replace(\'/#!/login\');') }) diff --git a/app/calculator.R b/app/calculator.R index 41cee49..e453374 100644 --- a/app/calculator.R +++ b/app/calculator.R @@ -56,16 +56,13 @@ calculatorServer <- function(input, output, session) { calculatorTV <-reactiveValues(value=NULL) output$report <- downloadHandler( - # For PDF output, change this to "report.pdf" + filename = "raport.pdf", content = function(file) { - # Copy the report file to a temporary directory before processing it, in - # case we don't have write permissions to the current working dir (which - # can happen when deployed). + tempReport <- file.path(tempdir(), "report.Rmd") file.copy("report.Rmd", tempReport, overwrite = TRUE) - - # Set up parameters to pass to Rmd document + p=0 if(as.numeric(input$slider2)>=50){ p=50 @@ -74,9 +71,7 @@ calculatorServer <- function(input, output, session) { x=round(1/(1+exp(-z)),3) params <- list(n = input$slider1,k=input$slider2,l=input$select1,m=input$select2,p=input$select3,r=input$select4,z=x) - # Knit the document, passing in the `params` list, and eval it in a - # child of the global environment (this isolates the code in the document - # from the code in this app). + rmarkdown::render(tempReport, output_file = file, params = params, envir = new.env(parent = globalenv()) @@ -179,10 +174,10 @@ calculatorServer <- function(input, output, session) { ) - r<-httr::POST("http://localhost:8080/api/prediction/save/ind",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),body=prediction,encode = 'json') + r<-httr::POST("http://localhost:8080/api/prediction/save",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),body=prediction,encode = 'json') # SPRAWDZENIE POBIERANIA JEDNEGO I WIELU POMIAROW - # r<-httr::GET("http://localhost:8080/api/prediction/get/13",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') + # r<-httr::GET("http://localhost:8080/api/prediction/get/7",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') # r<-httr::GET("http://localhost:8080/api/prediction/usersPredictions/ind",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') if (r$status_code==200){ @@ -190,7 +185,7 @@ calculatorServer <- function(input, output, session) { }else{ FALSE } - print(toJSON(content(r,as = "parsed"))) + # print(toJSON(content(r,as = "parsed"))) diff --git a/app/calculator_view.R b/app/calculator_view.R new file mode 100644 index 0000000..4d1d664 --- /dev/null +++ b/app/calculator_view.R @@ -0,0 +1,145 @@ +library(shiny) +library(magrittr) +library(ggplot2) +library(plotly) +library(DT) + +calculatorViewUI <- function(id){ + ns <- NS(id) + + uiOutput("view") + + +} + +calculatorViewServer <- function(input, output, session) { + + pl <- list( + emptyTable="Tabela jest pusta", + sSearch = "Szukaj", + sInfo="Wyniki od _START_ do _END_ z _TOTAL_ rekordow", + sZeroRecords="Brak rekordow", + sEmptyTable="Pusta tabela", + oPaginate= list( + sFirst="Pierwsza", sPrevious="Poprzednia",sLast="Ostatnia", sNext="Nastepna" + ), + sLengthMenu = "Pokaz _MENU_ rekordow na stronie" + ) + + component <- reactive({ + if (is.null(get_query_param()$id)) { + return(NULL) + }else{ + return(as.numeric(get_query_param()$id)) + } + + }) + + component2 <- reactive({ + if(length(get_query_param())==1 ){ + queryParam = as.numeric(get_query_param()) + r = httr::GET(paste("http://localhost:8080/api/prediction/get/",as.character(queryParam),sep = ""),add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') + r + + } + }) + component3<-eventReactive(input$pageIOTA,{ + + if(length(get_query_param())==1 ){ + queryParam = as.numeric(get_query_param()) + r = httr::GET(paste("http://localhost:8080/api/prediction/get/",as.character(queryParam),sep = ""),add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') + + r + }else{ + NULL + } + }) + + observe({ + + if(get_page()=="iota"){ + + shinyjs::runjs('Shiny.onInputChange("pageIOTA", "iota");') + + + + + + } + + + + }) + + output$view<-renderUI({ + response <- component3() + + if(is.null(response)){ + + }else{ + + + r = response + + if(r$status_code==200){ + z=-5.3718+0.0354*as.numeric(content(r)$prediction$parameterInts[[1]]$value)+1.6159*as.numeric(content(r)$prediction$parameterInts[[2]]$value)+1.1768*as.numeric(content(r)$prediction$parameterInts[[3]]$value)+0.0697*as.numeric(content(r)$prediction$parameterInts[[4]]$value)+0.9586*as.numeric(content(r)$prediction$parameterInts[[5]]$value)-2.9486*as.numeric(content(r)$prediction$parameterInts[[6]]$value) + x=seq(by=1,-8,8) + y=round(1/(1+exp(-x)),3) + d=data.frame(x,y) + + + g=ggplot(data=d,aes(x=x,y=y))+ + geom_line()+ + geom_point(aes(x=z,y=round(1/(1+exp(-z)),3)),color="red",size=4)+ + geom_hline(aes(yintercept=0.1),linetype = "dashed")+ + geom_text(aes(x=6,y=0.15),label="próg złośliwości: 0.1")+ + labs(x="Realność",y="Prognoza") + + + + + fluidPage( + fluidRow( + column(12, + tags$div("Kalkulator wskaźnika ryzyka nowotworu jajnika (IOTA LR2)") %>% tagAppendAttributes(class="panel-title"), + wellPanel( + p("Szczegółowy opis algorytmu znajduje się w artykule: Timmerman D, Testa AC, Bourne T, [i in.]. Model regresji logistycznej do rozróżniania łagodnych i złośliwych guzów przydatków przed operacją: wieloośrodkowe badanie przeprowadzone przez International Ovarian Tumor Analysis Group. J Clin Oncol. 2005, 23, 8794-8801."), + p("Ogólnie algorytm LR2 przewiduje, że nowotwór jest łagodny, gdy pacjent jest młody, lity składnik zmiany jest mały i występują cienie akustyczne. Możesz to sprawdzić empirycznie za pomocą różnych kombinacji wartości wejściowych."), + + HTML(paste("Surowa wartość predyktora (im niższa, tym lepiej): ", strong(content(r)$prediction$resultValue))), + br(), + HTML(content(r)$prediction$resultText), + + ggplotly(g), + disabled(sliderInput("vslider1", strong("Wiek pacjenta:"),min = 14, max = 100, value = content(r)$prediction$parameterInts[[1]]$value)), + disabled(selectInput("vselect1",strong("Obecność wodobrzusza:"),choices = list("Nie"=0,"Tak"=1),selected=content(r)$prediction$parameterInts[[2]]$value)), + disabled(selectInput("vselect2",strong("Obecność przepływu krwi w projekcji brodawkowatej:"),choices = list("Nie"=0,"Tak"=1),selected=content(r)$prediction$parameterInts[[3]]$value)), + disabled(sliderInput("vslider2", strong("Największa średnica elementu stałego (w mm):"),min = 0, max = 200, value =content(r)$prediction$parameterInts[[4]]$value)), + disabled(selectInput("vselect3",strong("Nieregularna wewnętrzna ściana torbieli:"),choices = list("Nie"=0,"Tak"=1),selected=content(r)$prediction$parameterInts[[5]]$value)), + disabled(selectInput("vselect4",strong("Obecność cieni akustycznych:"),choices = list("Nie"=0,"Tak"=1),selected=content(r)$prediction$parameterInts[[6]]$value)), + ))%>% tagAppendAttributes(id = 'column-content') + + ) %>% tagAppendAttributes(id = 'row-content'), + fluidRow( + column(12, + tags$span("© Copyright Wszystkie prawa zastrzeżone."))%>% tagAppendAttributes(id = 'column-copyright'), + )%>% tagAppendAttributes(id = 'row-footer') + + ) + + }else{ + shinyjs::runjs('window.location.replace(\'/#!/home\');') + + } + + + } + + + } + + ) + + +} + diff --git a/app/login_module.R b/app/login_module.R index 97ab8a5..19167e7 100644 --- a/app/login_module.R +++ b/app/login_module.R @@ -18,8 +18,9 @@ tags$script('Shiny.addCustomMessageHandler("tokenHandlerAfterLogin", function(token) { sessionStorage.setItem(\'token\', token); Shiny.onInputChange("token", token); + Shiny.onInputChange("auth", 1); - window.location.replace(\'/#!/profil\'); + window.location.href=\'/#!/profil\'; } );'), tags$style(HTML(" @@ -30,7 +31,7 @@ tags$script('Shiny.addCustomMessageHandler("tokenHandlerAfterLogin", "))), theme = "style.css", - + # window.location.replace(\'/#!/profil\'); # App title ---- fluidRow(column(12, @@ -93,10 +94,14 @@ loginServer <- function(input, output,session) { observe({ - if(((session$clientData)$url_hash=="#!/login") & (!is.null(input$token) & length(input$token)>0 )){ - - + + if((session$clientData)$url_hash=="#!/login"){ + if(!is.null(input$auth) & length(input$auth)>0 ){ + print("redirect from login page if token is set") shinyjs::runjs('window.location.replace(\'/#!/home\');') + } + + } }) diff --git a/app/profil_module.R b/app/profil_module.R index 1f9eb0f..66cea74 100644 --- a/app/profil_module.R +++ b/app/profil_module.R @@ -21,6 +21,14 @@ profilUI <- function(id) { Shiny.onInputChange("profileActiveTab", 1); } );'), + tags$script('Shiny.addCustomMessageHandler("viewPage", + function(page,token,auth) { + Shiny.onInputChange("token", token); + Shiny.onInputChange("auth", auth); + + window.location.href=page; + } +);'), tags$style(HTML(" @@ -52,6 +60,14 @@ profilUI <- function(id) { profilServer <- function(input, output,session) { + shinyInput <- function(FUN, len, id, ...) { + inputs <- character(len) + for (i in seq_len(len)) { + inputs[i] <- as.character(FUN(id, ...)) + } + inputs + } + getEditStatus <- eventReactive(input$editSubmit, { @@ -61,21 +77,28 @@ profilServer <- function(input, output,session) { datebirth<-input$editAge, gender<-input$editGender) - reg<-c(grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,15}$",editedPersonalData$name), - grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,20}$",editedPersonalData$surname), + # reg<-c(grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,15}$",editedPersonalData$name), + # grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,20}$",editedPersonalData$surname), + # grepl("^[a-z]+[0-9]*@([a-z]{2,10}\\.)+[a-z]{2,5}$",editedPersonalData$mail)) + + reg<-c(grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,15}$",editedPersonalData$name), + grepl("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,20}$",editedPersonalData$surname), grepl("^[a-z]+[0-9]*@([a-z]{2,10}\\.)+[a-z]{2,5}$",editedPersonalData$mail)) if(all(reg)){ - # status$status = register(result) + + personalData = list( + name = editedPersonalData$name, + surname = editedPersonalData$surname, + email = editedPersonalData$mail, + datebirth = editedPersonalData$datebirth, + gender =editedPersonalData$gender) - # status$first = FALSE + + to_send = list( + personalDataDTO = personalData) - to_send = list(name = editedPersonalData$name, - surname = editedPersonalData$surname, - email = editedPersonalData$mail, - datebirth = editedPersonalData$datebirth, - gender = editedPersonalData$gender) r<-httr::PUT("http://localhost:8080/api/profile",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),body=to_send,encode = 'json') @@ -97,7 +120,12 @@ profilServer <- function(input, output,session) { observe({ - session$sendCustomMessage(type='tokenHandlerAccess',(session$clientData)$url_hash) + currPage = get_page() + if(currPage=="profile" | currPage=="calculator" | currPage=="iota"){ + # print("tokenHandler") + session$sendCustomMessage(type='tokenHandlerAccess',(session$clientData)$url_hash) + } + @@ -106,7 +134,7 @@ profilServer <- function(input, output,session) { output$profileData<-renderUI({ activeTab=input$profileActiveTab session$clientData$url_hash - print(activeTab) + if(length(activeTab)==0 || is.null(activeTab) || activeTab!=1){ shinyjs::runjs('Shiny.onInputChange("profileActiveTab", 1);') @@ -114,27 +142,28 @@ profilServer <- function(input, output,session) { else if(activeTab==1){ r<-httr::GET("http://localhost:8080/api/profile",add_headers(Authorization=paste("Bearer",input$token,sep=" "))) - + if(r$status_code==200){ response<-(content(r)) + session$sendCustomMessage(type='tokenHandlerUpdate', response$token) fluidRow(column(12, wellPanel( - textInput("editName", label = strong("Imie"),value=response$profil$name), + textInput("editName", label = strong("Imie"),value=response$profil$personalDataDTO$name), uiOutput("editName"), - textInput("editSurname", label = strong("Nazwisko"),value=response$profil$surname), + textInput("editSurname", label = strong("Nazwisko"),value=response$profil$personalDataDTO$surname), uiOutput("editSurname"), - textInput("editMail", label = strong("Adres email"),value=response$profil$email), + textInput("editMail", label = strong("Adres email"),value=response$profil$personalDataDTO$email), uiOutput("editMail"), - dateInput("editAge", label = strong("Data urodzenia") ,value=response$profil$datebirth), + dateInput("editAge", label = strong("Data urodzenia") ,value=response$profil$personalDataDTO$datebirth), selectInput("editGender", label = strong("Plec"), choices = list("Zenska" = 0, "meska" = 1), - selected = as.numeric(response$profil$gender)), + selected = as.numeric(response$profil$personalDataDTO$gender)), ), @@ -145,7 +174,7 @@ profilServer <- function(input, output,session) { } - # shinyjs::runjs('Shiny.onInputChange("profileActiveTab", 1);') + } @@ -163,7 +192,7 @@ profilServer <- function(input, output,session) { output$afterLogin<-renderUI({ - if(!is.null(input$token) & length(input$token)>0 ){ + if(!is.null(input$auth) & length(input$auth)>0 ){ @@ -178,10 +207,10 @@ profilServer <- function(input, output,session) { tabsetPanel(type = "tabs", tabPanel("Dane profilowe", tags$div(uiOutput("profileData") )%>% tagAppendAttributes(class = 'content-wrapper')), - tabPanel("Historia pomiarów",value='profileTabs', tags$div(DT::dataTableOutput("historyTable",height = "auto"))%>% tagAppendAttributes(id="profileTabs",class = 'content-wrapper')), - tabPanel("Zakladka 3", tags$div(plotlyOutput("plot3",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')), - tabPanel("Zakladka 4", tags$div(plotlyOutput("plot4",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')), - tabPanel("Zakladka 5", tags$div(DT::dataTableOutput("table1",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')) + tabPanel("Historia pomiarów",value='profileTabs', tags$div(DT::dataTableOutput("historyTable",height = "auto"))%>% tagAppendAttributes(id="profileTabs",class = 'content-wrapper')) + # tabPanel("Zakladka 3", tags$div(plotlyOutput("plot3",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')), + # tabPanel("Zakladka 4", tags$div(plotlyOutput("plot4",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')), + # tabPanel("Zakladka 5", tags$div(DT::dataTableOutput("table1",height = "auto"))%>% tagAppendAttributes(class = 'content-wrapper')) ))%>% tagAppendAttributes(id = 'column-content') ) %>% tagAppendAttributes(id = 'row-content') @@ -193,7 +222,7 @@ profilServer <- function(input, output,session) { }) observeEvent(input$profileTabs, { - shinyjs::runjs(' window.location.reload();')}) + shinyjs::runjs('window.location.reload();')}) output$plot1 <- renderPlotly({ @@ -209,27 +238,47 @@ profilServer <- function(input, output,session) { }) + observeEvent(input$view_button,{ + + change_page(paste("?id=",input$view_button,"#!/iota",sep=""), session = session, mode = "push") + + }) + observeEvent(input$del_button,{ + r<-httr::DELETE(paste("http://localhost:8080/api/prediction/delete/",input$del_button,sep = ""),add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') + # print(r$status_code) + if(r$status_code==200){ + shinyjs::runjs('Shiny.onInputChange("profileActiveTab", "");') + shinyjs::runjs('Shiny.onInputChange("profileActiveTab", 2);') + } + + }) output$historyTable <- DT::renderDataTable({ activeTab = input$profileActiveTab session$clientData$url_hash - print(activeTab) + if(activeTab!=2){ shinyjs::runjs('Shiny.onInputChange("profileActiveTab", 2);') } else{ r<-httr::GET("http://localhost:8080/api/prediction/usersPredictions/ind",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),encode = 'json') - - # print(typeof(do.call(c,(content(r)$predictions)))) - # v<-do.call(c,(content(r)$predictions)) + if(is.null(content(r)$predictions)){ DT::datatable(data.frame(Nazwa=character(),Wynik=numeric(),Data=character()),options = list(scrollX = TRUE,language=pl)) }else{ df_historyTable<-as.data.frame(do.call(rbind, (content(r)$predictions))) + + + historyTableButtons = list() + + for(r in 1:nrow(df_historyTable)){ + + # print(as.numeric(df_historyTable[r,]$id[1])) + historyTableButtons[[length(historyTableButtons)+1]] <- list(shinyInput(actionButton, 1, as.character(df_historyTable[r,]$id[1]), label = "Pokaż", onclick = 'Shiny.onInputChange(\"view_button\", this.id)' ), + shinyInput(actionButton, 1, as.character(df_historyTable[r,]$id[1]), label = "Usuń", onclick = 'Shiny.onInputChange(\"del_button\", this.id)')) + } - # print(typeof(df_historyTable)) - # print(df_historyTable) df_historyTable<-df_historyTable %>% - select(name,resultValue,localDateTime) %>% - mutate(Akcja="TODO")%>% + mutate(Akcja=historyTableButtons)%>% + select(name,resultValue,localDateTime,Akcja) %>% rename( Nazwa = name, Wynik = resultValue, @@ -239,12 +288,7 @@ profilServer <- function(input, output,session) { df_historyTable$Nazwa<-do.call(c, df_historyTable$Nazwa) df_historyTable$Wynik<-do.call(c, df_historyTable$Wynik) df_historyTable$Data<-do.call(c, df_historyTable$Data) - print(df_historyTable) - print(df_historyTable$Nazwa) - - # as.character(df_historyTable$Nazwa) - # as.numeric(df_historyTable$Wynik) - # as.Date(df_historyTable$Data) + DT::datatable(df_historyTable,options = list(scrollX = TRUE,language=pl))} } diff --git a/app/register_module.R b/app/register_module.R index 7a8c42b..5018f13 100644 --- a/app/register_module.R +++ b/app/register_module.R @@ -71,16 +71,24 @@ registerServer <- function(input, output,session) { status$first = FALSE + personalData = list( + name = result$name, + surname = result$surname, + email = result$mail, + datebirth = result$datebirth, + gender = result$gender) + roleData = list(name="IND") - to_send = list(name = result$name, - surname = result$surname, - email = result$mail, - datebirth = result$datebirth, - gender = result$gender, - login = result$login, - password= result$password, - roleDTO= "IND") + userData = list( + login = result$login, + password= result$password, + roleDTO= roleData) + + to_send = list( + personalDataDTO = personalData, + userDTO = userData) r<-httr::POST("http://localhost:8080/api/register",body=to_send,encode = 'json') + # print(content(r)) if (r$status_code==200){ status$status = TRUE diff --git a/app/routing_module.R b/app/routing_module.R index 86dd044..156b271 100644 --- a/app/routing_module.R +++ b/app/routing_module.R @@ -11,6 +11,7 @@ source("profil_module.R",encoding="utf-8") source("login_module.R",encoding="utf-8") source("register_module.R",encoding="utf-8") source("calculator.R", encoding = "utf-8") +source("calculator_view.R", encoding = "utf-8") source("firmy_module.R", encoding = "utf-8") @@ -21,6 +22,7 @@ profil_page <-profilUI(id="profil") login_page <-loginUI(id="login") register_page <-registerUI(id="register") calculator_page <- calculatorUI(id="calculator") +calculatorView_page <- calculatorViewUI(id="calculatorView") firmy_page <- firmyUI(id="firms") router <- make_router( @@ -30,6 +32,7 @@ router <- make_router( route("login", login_page,loginServer), route("register", register_page,registerServer), route("calculator", calculator_page, calculatorServer), + route("iota", calculatorView_page, calculatorViewServer), route("firms", firmy_page, firmyServer) ) diff --git a/backend/src/main/java/project/DTO/CompanyDataDTO.java b/backend/src/main/java/project/DTO/CompanyDataDTO.java new file mode 100644 index 0000000..02097b1 --- /dev/null +++ b/backend/src/main/java/project/DTO/CompanyDataDTO.java @@ -0,0 +1,56 @@ +package project.DTO; + +import lombok.Getter; +import lombok.Setter; +import project.model.CompanyData; + +import javax.persistence.*; +import java.io.Serializable; + + +public class CompanyDataDTO implements Serializable { + + @Getter + @Setter + private int id; + + @Getter + @Setter + private String name; + + @Getter + @Setter + private String email; + + @Getter + @Setter + private String address; + + @Getter + @Setter + private double longitude; + + @Getter + @Setter + private double latitude; + + + public CompanyDataDTO(){}; + + public CompanyDataDTO(String name, String email, String address, double longitude, double latitude) { + this.name = name; + this.email = email; + this.address = address; + this.longitude = longitude; + this.latitude = latitude; + } + + public CompanyDataDTO(CompanyData companyData){ + this.id = companyData.getId(); + this.name = companyData.getName(); + this.email = companyData.getEmail(); + this.address = companyData.getAddress(); + this.longitude = companyData.getLongitude(); + this.latitude = companyData.getLatitude(); + }; +} diff --git a/backend/src/main/java/project/DTO/CompanyProfileDTO.java b/backend/src/main/java/project/DTO/CompanyProfileDTO.java new file mode 100644 index 0000000..12565eb --- /dev/null +++ b/backend/src/main/java/project/DTO/CompanyProfileDTO.java @@ -0,0 +1,36 @@ +package project.DTO; + +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.Table; +import project.model.User; + +import javax.persistence.*; +import java.io.Serializable; + + +public class CompanyProfileDTO implements Serializable { + @Getter + @Setter + private int id; + + @Getter + @Setter + private CompanyDataDTO companyData; + + + @Getter + @Setter + private UserDTO userDTO; + + public CompanyProfileDTO(){}; + + public CompanyProfileDTO(CompanyDataDTO companyData, UserDTO userDTO) { + this.companyData = companyData; + this.userDTO = userDTO; + } + + public CompanyProfileDTO(CompanyDataDTO companyData) { + this.companyData = companyData; + } +} diff --git a/backend/src/main/java/project/DTO/PersonalDataDTO.java b/backend/src/main/java/project/DTO/PersonalDataDTO.java new file mode 100644 index 0000000..de5608c --- /dev/null +++ b/backend/src/main/java/project/DTO/PersonalDataDTO.java @@ -0,0 +1,55 @@ +package project.DTO; + +import lombok.Getter; +import lombok.Setter; +import project.model.PersonalData; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + + +public class PersonalDataDTO implements Serializable { + + @Getter + @Setter + private int id; + + @Getter + @Setter + private String name; + + @Getter + @Setter + private String surname; + + @Getter + @Setter + private String email; + + @Getter + @Setter + private String gender; + + @Getter + @Setter + private Date datebirth; + + public PersonalDataDTO(){}; + + public PersonalDataDTO(String name, String surname, String email, String gender, Date datebirth) { + this.name = name; + this.surname = surname; + this.email = email; + this.gender = gender; + this.datebirth = datebirth; + } + + public PersonalDataDTO(PersonalData personalData){ + this.name = personalData.getName(); + this.surname = personalData.getSurname(); + this.email = personalData.getEmail(); + this.gender = personalData.getGender(); + this.datebirth = personalData.getDatebirth(); + }; +} diff --git a/backend/src/main/java/project/DTO/PersonalProfileDTO.java b/backend/src/main/java/project/DTO/PersonalProfileDTO.java new file mode 100644 index 0000000..01dc818 --- /dev/null +++ b/backend/src/main/java/project/DTO/PersonalProfileDTO.java @@ -0,0 +1,36 @@ +package project.DTO; + +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.Table; +import project.model.User; + +import javax.persistence.*; +import java.io.Serializable; + + +public class PersonalProfileDTO implements Serializable { + + @Getter + @Setter + private int id; + + @Getter + @Setter + private PersonalDataDTO personalDataDTO; + + @Getter + @Setter + private UserDTO userDTO; + + public PersonalProfileDTO(){}; + + public PersonalProfileDTO(PersonalDataDTO personalDataDTO, UserDTO userDTO) { + this.personalDataDTO = personalDataDTO; + this.userDTO = userDTO; + } + + public PersonalProfileDTO(PersonalDataDTO personalDataDTO) { + this.personalDataDTO = personalDataDTO; + } +} diff --git a/backend/src/main/java/project/DTO/PredictionDTO.java b/backend/src/main/java/project/DTO/PredictionDTO.java index 8aae569..901f37f 100644 --- a/backend/src/main/java/project/DTO/PredictionDTO.java +++ b/backend/src/main/java/project/DTO/PredictionDTO.java @@ -27,6 +27,10 @@ public class PredictionDTO implements Serializable { @Setter private int user; + @Getter + @Setter + private int creator; + @Getter @Setter private List parameterDoubles; @@ -54,6 +58,7 @@ public class PredictionDTO implements Serializable { this.id = predictionDTO.getId(); this.name = predictionDTO.getName(); this.user = predictionDTO.getUser(); + this.creator = predictionDTO.getCreator(); this.parameterDoubles = predictionDTO.getParameterDoubles(); this.parameterInts = predictionDTO.getParameterInts(); this.resultValue = predictionDTO.getResultValue(); @@ -67,6 +72,7 @@ public class PredictionDTO implements Serializable { this.id = prediction.getId(); this.name = prediction.getName(); this.user = prediction.getUser().getId(); + this.creator = prediction.getCreator().getId(); this.parameterDoubles = prediction.getParameterDoubles(); this.parameterInts = prediction.getParameterInts(); this.resultValue = prediction.getResultValue(); diff --git a/backend/src/main/java/project/DTO/UserDTO.java b/backend/src/main/java/project/DTO/UserDTO.java index efbb6d6..5820ce0 100644 --- a/backend/src/main/java/project/DTO/UserDTO.java +++ b/backend/src/main/java/project/DTO/UserDTO.java @@ -13,23 +13,8 @@ public class UserDTO implements Serializable { @Getter @Setter - private String name; + private int id; - @Getter - @Setter - private String surname; - - @Getter - @Setter - private String email; - - @Getter - @Setter - private String gender; - - @Getter - @Setter - private Date datebirth; @Getter @Setter @@ -44,8 +29,6 @@ public class UserDTO implements Serializable { private RoleDTO roleDTO; - - public UserDTO(){ } @@ -56,23 +39,17 @@ public class UserDTO implements Serializable { } public UserDTO(UserDTO userDTO) { - this.name = userDTO.getName(); - this.surname = userDTO.getSurname(); - this.email = userDTO.getEmail(); - this.gender = userDTO.getGender(); - this.datebirth = userDTO.getDatebirth(); + this.login = userDTO.getLogin(); this.password = userDTO.getPassword(); this.roleDTO= userDTO.getRoleDTO(); } public UserDTO(User user) { - this.name = user.getName(); - this.surname = user.getSurname(); - this.email = user.getEmail(); - this.gender = user.getGender(); - this.datebirth = user.getDatebirth(); + + this.id = user.getId(); this.login = user.getLogin(); + this.roleDTO= new RoleDTO(user.getRole().getName()); } diff --git a/backend/src/main/java/project/controllers/AuthenticationController.java b/backend/src/main/java/project/controllers/AuthenticationController.java index 53041c2..3c745f6 100644 --- a/backend/src/main/java/project/controllers/AuthenticationController.java +++ b/backend/src/main/java/project/controllers/AuthenticationController.java @@ -1,7 +1,9 @@ package project.controllers; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -12,7 +14,11 @@ import org.springframework.web.bind.annotation.*; import project.DTO.UserDTO; import project.config.TokenHelper; +import project.model.CompanyProfile; +import project.model.PersonalProfile; import project.model.User; +import project.services.CompanyProfileService; +import project.services.PersonalProfileService; import project.services.UserService; import javax.servlet.http.HttpServletRequest; @@ -35,15 +41,21 @@ public class AuthenticationController { @Autowired UserService userService; + @Autowired + PersonalProfileService personalProfileService; + + @Autowired + CompanyProfileService companyProfileService; + @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @PreAuthorize("isAnonymous()") @RequestMapping(value = "/login",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public Map generateToken(@RequestBody UserDTO loginForm, - HttpServletRequest request, - HttpServletResponse httpServletResponse){ + public ResponseEntity> generateToken(@RequestBody UserDTO loginForm, + HttpServletRequest request, + HttpServletResponse httpServletResponse){ String token=null; @@ -65,15 +77,23 @@ public class AuthenticationController { User authUser = userFromDatabase.get(); token = this.tokenHelper.generateToken(authUser); map.put("token",token); - map.put("message","Jesteś zalogowany jako "+authUser.getName()+" "+authUser.getSurname()); - httpServletResponse.setStatus(200); - return map; + if(authUser.getRole().getName()=="COMP"){ + CompanyProfile companyProfile = companyProfileService.getCompanyProfileByUserId(authUser.getId()); + map.put("message","Jesteś zalogowany jako "+companyProfile.getCompanyData().getName()); + + }else if(authUser.getRole().getName()=="IND"){ + PersonalProfile personalProfile = personalProfileService.getPersonalProfileByUserId(authUser.getId()); + map.put("message","Jesteś zalogowany jako "+personalProfile.getPersonalData().getName()+" "+personalProfile.getPersonalData().getSurname()); + + } + + return new ResponseEntity<>(map, HttpStatus.OK); } else{ map.put("message","Niepoprawne login lub hasło"); map.put("token",token); - httpServletResponse.setStatus(460); - return map; + return new ResponseEntity<>(map, HttpStatus.UNAUTHORIZED); + } diff --git a/backend/src/main/java/project/controllers/CompanyProfileController.java b/backend/src/main/java/project/controllers/CompanyProfileController.java new file mode 100644 index 0000000..bd77d72 --- /dev/null +++ b/backend/src/main/java/project/controllers/CompanyProfileController.java @@ -0,0 +1,48 @@ +package project.controllers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import project.DTO.PredictionDTO; +import project.services.CompanyProfileService; +import project.services.GeneratorDTO; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("/api/firms") +public class CompanyProfileController { + @Autowired + private CompanyProfileService companyProfileService; + + @Autowired + private GeneratorDTO generatorDTO; + + + + @RequestMapping(value = "/all",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE) + @ResponseBody + public ResponseEntity> getAllCompanies(HttpServletRequest request, + HttpServletResponse httpServletResponse){ + + Map map = new HashMap<>(); + try{ + map.put("companies",companyProfileService.getAllCompanies()); + return new ResponseEntity<>(map, HttpStatus.OK); + }catch(Exception e){ + map.put("companies",null); + map.put("message","Błąd zapytania"); + return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST); + } + + + } +} diff --git a/backend/src/main/java/project/controllers/PredictionController.java b/backend/src/main/java/project/controllers/PredictionController.java index 3d11144..2caaebd 100644 --- a/backend/src/main/java/project/controllers/PredictionController.java +++ b/backend/src/main/java/project/controllers/PredictionController.java @@ -11,11 +11,11 @@ import org.springframework.web.bind.annotation.*; import project.DTO.PredictionDTO; import project.DTO.UserDTO; import project.config.TokenHelper; +import project.model.CompanyProfile; +import project.model.PersonalProfile; import project.model.Prediction; import project.model.User; -import project.services.GeneratorDTO; -import project.services.PredictionService; -import project.services.UserService; +import project.services.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,6 +35,11 @@ public class PredictionController { private PredictionService predictionService; @Autowired private UserService userService; + @Autowired + private PersonalProfileService personalProfileService; + + @Autowired + private CompanyProfileService companyProfileService; @Autowired private GeneratorDTO generatorDTO; @@ -45,8 +50,8 @@ public class PredictionController { - @PreAuthorize("hasAnyAuthority('IND')") - @RequestMapping(value = "/save/ind",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) + @PreAuthorize("hasAnyAuthority('COMP','IND')") + @RequestMapping(value = "/save",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map addPrediction(@RequestBody @Valid @NotNull PredictionDTO predictionDTO, HttpServletRequest request, @@ -64,7 +69,22 @@ public class PredictionController { map.put("token", tokenHelper.refreshToken(token.toString())); - predictionDTO.setUser(currentUser.getId()); + if(currentUser.getRole().getName()=="COMP"){ + CompanyProfile companyProfile = companyProfileService.getCompanyProfileByUserId(currentUser.getId()); + PersonalProfile personalProfile = personalProfileService.getPersonalProfileByUserId(predictionDTO.getUser()); + if(!companyProfileService.isCompanyAuthorized(companyProfile.getId(),personalProfile.getId())){ + httpServletResponse.setStatus(400); + }else{ + predictionDTO.setUser(predictionDTO.getUser()); + predictionDTO.setCreator(currentUser.getId()); + } + + }else{ + predictionDTO.setUser(currentUser.getId()); + predictionDTO.setCreator(currentUser.getId()); + } + + Prediction predictionSaved = this.predictionService.savePrediction(predictionDTO); if (predictionSaved!=null){ @@ -106,8 +126,14 @@ public class PredictionController { Prediction prediction = this.predictionService.getPrediction(id); if (prediction!=null){ - map.put("prediction", new PredictionDTO(prediction)); - return new ResponseEntity>(map, HttpStatus.ACCEPTED); + if(prediction.getUser().getId()==currentUser.getId() || prediction.getCreator().getId()==currentUser.getId()){ + map.put("prediction", new PredictionDTO(prediction)); + return new ResponseEntity>(map, HttpStatus.OK); + }else{ + map.put("prediction", null); + return new ResponseEntity>(map, HttpStatus.BAD_REQUEST); + } + }else{ map.put("prediction", null); return new ResponseEntity>(map, HttpStatus.BAD_REQUEST); @@ -124,6 +150,44 @@ public class PredictionController { } + @PreAuthorize("hasAnyAuthority('COMP','IND')") + @RequestMapping(value = "delete/{id}",method = RequestMethod.DELETE,produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> deletePrediction(@PathVariable int id,HttpServletRequest request, + HttpServletResponse httpServletResponse){ + + Map map = new HashMap<>(); + UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + Optional user = userService.getUsersByLogin(userDetails.getUsername()); + + if (user.isPresent()) { + User currentUser = user.get(); + + Object token = request.getAttribute("token"); + + map.put("token", tokenHelper.refreshToken(token.toString())); + + + boolean isDeleted = this.predictionService.deletePrediction(currentUser.getId(),id); + if (isDeleted){ + + return new ResponseEntity>(map, HttpStatus.OK); + }else{ + + return new ResponseEntity>(map, HttpStatus.BAD_REQUEST); + } + + } + + else { + + map.put("message", "Błąd autoryzacji"); + return new ResponseEntity>(map, HttpStatus.UNAUTHORIZED); + + } + + } + + @PreAuthorize("hasAnyAuthority('IND')") @RequestMapping(value = "/usersPredictions/ind",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getUsersPredictions(HttpServletRequest request, diff --git a/backend/src/main/java/project/controllers/UserController.java b/backend/src/main/java/project/controllers/UserController.java index 3f3c17c..a64bc23 100644 --- a/backend/src/main/java/project/controllers/UserController.java +++ b/backend/src/main/java/project/controllers/UserController.java @@ -1,5 +1,6 @@ package project.controllers; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.type.filter.RegexPatternTypeFilter; import org.springframework.data.domain.PageRequest; @@ -11,12 +12,12 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.*; +import project.DTO.PersonalDataDTO; +import project.DTO.PersonalProfileDTO; import project.DTO.UserDTO; import project.config.TokenHelper; import project.model.*; -import project.services.GeneratorDTO; -import project.services.RoleService; -import project.services.UserService; +import project.services.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -38,6 +39,11 @@ public class UserController { private RoleService roleService; @Autowired private GeneratorDTO generatorDTO; + @Autowired + private PersonalDataService personalDataService; + + @Autowired + private PersonalProfileService personalProfileService; @Autowired private TokenHelper tokenHelper; @@ -49,72 +55,83 @@ public class UserController { @PreAuthorize("isAnonymous()") @RequestMapping(value = "/register",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public Map addUser(@RequestBody @Valid @NotNull UserDTO userDTO, + public ResponseEntity> addUser(@RequestBody @Valid @NotNull PersonalProfileDTO personalProfileDTO, HttpServletRequest request, HttpServletResponse httpServletResponse){ + ObjectMapper mapper = new ObjectMapper(); + try { + String jsonString = mapper.writeValueAsString(personalProfileDTO); + System.out.println(jsonString); + }catch(Exception e){ + e.printStackTrace(); + + } Map map = new HashMap<>(); Object token = request.getAttribute("token"); map.put("token",token); - - Optional users = this.userService.getUsersByLogin(userDTO.getLogin()); - - + Optional users = this.userService.getUsersByLogin(personalProfileDTO.getUserDTO().getLogin()); if(users.isPresent()){ - map.put("message","Wprowadzony użytkownik już istnieje"); - httpServletResponse.setStatus(462); - return map; - + return new ResponseEntity>(map, HttpStatus.BAD_REQUEST); } - else if(!userService.checkIfCorrect(userDTO,false)){ - - - map.put("message","Niepoprawny login lub hasło"); - - httpServletResponse.setStatus(461); - return map;} - + else if(!userService.checkIfCorrect(personalProfileDTO,false)) { + map.put("message", "Niepoprawny login lub hasło"); + return new ResponseEntity>(map, HttpStatus.UNAUTHORIZED); + } else{ User registerUser = new User(); + PersonalData personalData = new PersonalData(); - registerUser.setName(userDTO.getName()); - registerUser.setSurname(userDTO.getSurname()); - registerUser.setEmail(userDTO.getEmail()); - registerUser.setGender(userDTO.getGender()); - registerUser.setDatebirth(userDTO.getDatebirth()); - registerUser.setLogin(userDTO.getLogin()); + personalData.setName(personalProfileDTO.getPersonalDataDTO().getName()); + personalData.setSurname(personalProfileDTO.getPersonalDataDTO().getSurname()); + personalData.setEmail(personalProfileDTO.getPersonalDataDTO().getEmail()); + personalData.setGender(personalProfileDTO.getPersonalDataDTO().getGender()); + personalData.setDatebirth(personalProfileDTO.getPersonalDataDTO().getDatebirth()); - String pass = this.bCryptPasswordEncoder.encode(userDTO.getPassword()); + registerUser.setLogin(personalProfileDTO.getUserDTO().getLogin()); + + String pass = this.bCryptPasswordEncoder.encode(personalProfileDTO.getUserDTO().getPassword()); registerUser.setPassword(pass); - Role role = this.roleService.getRoleByName(userDTO.getRoleDTO().getName()); + Role role = this.roleService.getRoleByName(personalProfileDTO.getUserDTO().getRoleDTO().getName()); registerUser.setRole(role); - this.userService.addUser(registerUser); - map.put("message", "Zostałeś pomyślnie zarejestrowany"); - httpServletResponse.setStatus(200); - return map; + try { + User userSaved = this.userService.addUser(registerUser); + PersonalData personalDataSaved = this.personalDataService.addPersonalData(personalData); + + PersonalProfile personalProfile = new PersonalProfile(personalDataSaved, userSaved); + this.personalProfileService.addPersonalProfile(personalProfile); + + map.put("message", "Zostałeś pomyślnie zarejestrowany"); + return new ResponseEntity>(map, HttpStatus.OK); + }catch (Exception e){ + map.put("message", "Błąd rejestracji"); + + return new ResponseEntity>(map, HttpStatus.BAD_REQUEST); + } + } - } + @PreAuthorize("hasAnyAuthority('COMP','IND')") @RequestMapping(value="/profile",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public Map getMyProfile(HttpServletRequest request,HttpServletResponse httpServletResponse){ + public ResponseEntity> getMyProfile(HttpServletRequest request,HttpServletResponse httpServletResponse){ Map map = new HashMap<>(); @@ -124,32 +141,32 @@ public class UserController { if (user.isPresent()) { User currentUser = user.get(); + PersonalProfile personalProfile= personalProfileService.getPersonalProfileByUserId(currentUser.getId()); + Object token = request.getAttribute("token"); map.put("token", tokenHelper.refreshToken(token.toString())); - map.put("profil", this.generatorDTO.generateUserDTO(currentUser)); - httpServletResponse.setStatus(200); - - + map.put("profil", this.generatorDTO.generatePersonalProfileDTO(personalProfile)); + return new ResponseEntity<>(map,HttpStatus.OK); } else { map.put("message", "Profil nie istnieje"); - httpServletResponse.setStatus(404); + return new ResponseEntity<>(map,HttpStatus.NOT_FOUND); } - return map; + } @PreAuthorize("hasAnyAuthority('COMP','IND')") @RequestMapping(value="/profile",method = RequestMethod.PUT,produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public Map editMyProfile(@RequestBody @Valid @NotNull UserDTO userDTO,HttpServletRequest request,HttpServletResponse httpServletResponse){ + public ResponseEntity> editMyProfile(@RequestBody @Valid @NotNull PersonalProfileDTO personalProfileDTO,HttpServletRequest request,HttpServletResponse httpServletResponse){ Map map = new HashMap<>(); UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); @@ -158,27 +175,34 @@ public class UserController { if (user.isPresent()) { User currentUser = user.get(); - + PersonalProfile personalProfile = this.personalProfileService.getPersonalProfileByUserId(currentUser.getId()); + PersonalData personalData = personalProfile.getPersonalData(); Object token = request.getAttribute("token"); map.put("token", tokenHelper.refreshToken(token.toString())); - if(userService.checkIfCorrect(userDTO,true)){ + if(userService.checkIfCorrect(personalProfileDTO,true)){ + PersonalDataDTO personalDataDTO = personalProfileDTO.getPersonalDataDTO(); - currentUser.setName(userDTO.getName()); - currentUser.setSurname(userDTO.getSurname()); - currentUser.setDatebirth(userDTO.getDatebirth()); - currentUser.setGender(userDTO.getGender()); - currentUser.setEmail(userDTO.getEmail()); + personalData.setName(personalDataDTO.getName()); + personalData.setSurname(personalDataDTO.getSurname()); + personalData.setDatebirth(personalDataDTO.getDatebirth()); + personalData.setGender(personalDataDTO.getGender()); + personalData.setEmail(personalDataDTO.getEmail()); + + PersonalData personalDataSaved = personalDataService.addPersonalData(personalData); + personalProfile.setPersonalData(personalDataSaved); + + PersonalProfile personalProfileSaved = personalProfileService.addPersonalProfile(personalProfile); + map.put("profil", this.generatorDTO.generatePersonalProfileDTO(personalProfileSaved)); + return new ResponseEntity<>(map,HttpStatus.OK); - map.put("profil", this.generatorDTO.generateUserDTO(userService.addUser(currentUser))); - httpServletResponse.setStatus(200); } else{ map.put("message", "Błędne dane"); - httpServletResponse.setStatus(404); + return new ResponseEntity<>(map,HttpStatus.BAD_REQUEST); } } @@ -186,10 +210,10 @@ public class UserController { else { map.put("message", "Profil nie istnieje"); - httpServletResponse.setStatus(404); + return new ResponseEntity<>(map,HttpStatus.NOT_FOUND); } - return map; + } diff --git a/backend/src/main/java/project/model/CompanyData.java b/backend/src/main/java/project/model/CompanyData.java new file mode 100644 index 0000000..825bcbc --- /dev/null +++ b/backend/src/main/java/project/model/CompanyData.java @@ -0,0 +1,52 @@ +package project.model; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +@Entity +@Table(name="CompanyData") +public class CompanyData implements Serializable { + + @Getter + @Setter + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id",nullable = false) + private int id; + + @Getter + @Setter + @Column(name="name",nullable = false) + private String name; + + @Getter + @Setter + @Column(name="email",nullable = false) + private String email; + + @Getter + @Setter + @Column(name="address",nullable = false) + private String address; + + @Getter + @Setter + @Column(name="longitude",nullable = false) + private double longitude; + + @Getter + @Setter + @Column(name="latitude",nullable = false) + private double latitude; + + @Getter + @Setter + @OneToOne(mappedBy = "companyData") + private CompanyProfile companyProfile; + + public CompanyData(){}; + +} diff --git a/backend/src/main/java/project/model/CompanyProfile.java b/backend/src/main/java/project/model/CompanyProfile.java new file mode 100644 index 0000000..3e7abaa --- /dev/null +++ b/backend/src/main/java/project/model/CompanyProfile.java @@ -0,0 +1,60 @@ +package project.model; + +import lombok.Getter; +import lombok.Setter; + + +import javax.persistence.*; +import java.io.Serializable; +import java.util.List; + +@Entity +@Table(name="CompanyProfile") +public class CompanyProfile implements Serializable { + @Getter + @Setter + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id",nullable = false) + private int id; + + @Getter + @Setter + @OneToOne(cascade=CascadeType.PERSIST) + @JoinColumn(name="companyDataId",referencedColumnName = "id") + private CompanyData companyData; + + @Getter + @Setter + @ManyToMany + @JoinTable( + name="company_part", + joinColumns = @JoinColumn(name = "companyId"), + inverseJoinColumns = @JoinColumn(name="personalId") + ) + private List personalProfiles; + + + @Getter + @Setter + @OneToOne(cascade=CascadeType.PERSIST) + @JoinColumn(name="userId",referencedColumnName = "id") + private User user; + + public CompanyProfile(){}; + + public CompanyProfile(CompanyData companyData, List personalProfiles, User user) { + this.companyData = companyData; + this.personalProfiles = personalProfiles; + this.user = user; + } + + public CompanyProfile(CompanyData companyData, User user) { + this.companyData = companyData; + this.user = user; + } + + public CompanyProfile(CompanyData companyData) { + this.companyData = companyData; + } +} diff --git a/backend/src/main/java/project/model/PersonalData.java b/backend/src/main/java/project/model/PersonalData.java new file mode 100644 index 0000000..f2307b3 --- /dev/null +++ b/backend/src/main/java/project/model/PersonalData.java @@ -0,0 +1,54 @@ +package project.model; + +import lombok.Getter; +import lombok.Setter; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + +@Entity +@Table(name="PersonalData") +public class PersonalData implements Serializable { + + @Getter + @Setter + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id",nullable = false) + private int id; + + @Getter + @Setter + @Column(name="name",nullable = false) + private String name; + + @Getter + @Setter + @Column(name="surname",nullable = false) + private String surname; + + @Getter + @Setter + @Column(name="email",nullable = false) + private String email; + + @Getter + @Setter + @Column(name="gender",nullable = false) + private String gender; + + @Getter + @Setter + @Column(name="datebirth",nullable = false) + @Basic + @Temporal(TemporalType.DATE) + private Date datebirth; + + @Getter + @Setter + @OneToOne(mappedBy = "personalData") + private PersonalProfile personalProfile; + + public PersonalData(){}; +} diff --git a/backend/src/main/java/project/model/PersonalProfile.java b/backend/src/main/java/project/model/PersonalProfile.java new file mode 100644 index 0000000..a24db39 --- /dev/null +++ b/backend/src/main/java/project/model/PersonalProfile.java @@ -0,0 +1,58 @@ +package project.model; + +import lombok.Getter; +import lombok.Setter; + + +import javax.persistence.*; +import java.io.Serializable; +import java.util.List; + +@Entity +@Table(name="PersonalProfile") +public class PersonalProfile implements Serializable { + + @Getter + @Setter + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id",nullable=false) + private int id; + + @Getter + @Setter + @OneToOne(cascade=CascadeType.PERSIST) + @JoinColumn(name="personalDateId",referencedColumnName = "id") + private PersonalData personalData; + + @Getter + @Setter + @OneToOne(cascade=CascadeType.PERSIST) + @JoinColumn(name="userId",referencedColumnName = "id") + private User user; + + @Getter + @Setter + @ManyToMany(mappedBy = "personalProfiles") + List companyProfileList; + + + + + public PersonalProfile(){}; + + public PersonalProfile(PersonalData personalData, User user) { + this.personalData = personalData; + this.user = user; + } + + public PersonalProfile(PersonalData personalData) { + this.personalData = personalData; + } + + public PersonalProfile(PersonalData personalData, User user, List companyProfileList) { + this.personalData = personalData; + this.user = user; + this.companyProfileList = companyProfileList; + } +} diff --git a/backend/src/main/java/project/model/Prediction.java b/backend/src/main/java/project/model/Prediction.java index f89c6e3..2702afd 100644 --- a/backend/src/main/java/project/model/Prediction.java +++ b/backend/src/main/java/project/model/Prediction.java @@ -33,6 +33,12 @@ public class Prediction implements Serializable { @JoinColumn(name = "user_id", referencedColumnName = "id") private User user; + @Getter + @Setter + @ManyToOne + @JoinColumn(name = "creator_id", referencedColumnName = "id") + private User creator; + @Getter @Setter diff --git a/backend/src/main/java/project/model/User.java b/backend/src/main/java/project/model/User.java index 5bdd3d3..dab0f48 100644 --- a/backend/src/main/java/project/model/User.java +++ b/backend/src/main/java/project/model/User.java @@ -25,33 +25,6 @@ public class User implements Serializable { @Column(name="id",nullable = false) private int id; - @Getter - @Setter - @Column(name="name",nullable = false) - private String name; - - @Getter - @Setter - @Column(name="surname",nullable = false) - private String surname; - - @Getter - @Setter - @Column(name="email",nullable = false) - private String email; - - @Getter - @Setter - @Column(name="gender",nullable = false) - private String gender; - - @Getter - @Setter - @Column(name="datebirth",nullable = false) - @Basic - @Temporal(TemporalType.DATE) - private Date datebirth; - @Getter @Setter @Column(name="login",nullable = false,unique = true) @@ -79,31 +52,42 @@ public class User implements Serializable { @JsonIgnore private List predictions; + @Getter + @Setter + @OneToMany(mappedBy = "creator",orphanRemoval = true,cascade = CascadeType.PERSIST) + @JsonIgnore + private List predictionsCreated; + + @Getter + @Setter + @OneToOne(mappedBy = "user") + private CompanyProfile companyProfile; + + @Getter + @Setter + @OneToOne(mappedBy = "user") + private PersonalProfile personalProfile; + public User(){ } public User(String name, String surname, String email, String gender, Date datebirth, String login, String password, Role role) { - this.name = name; - this.surname = surname; - this.email = email; - this.gender = gender; - this.datebirth = datebirth; + this.login = login; this.password = password; this.role = role; } public User(User user) { - this.name = user.getName(); - this.surname = user.getSurname(); - this.email = user.getEmail(); - this.gender = user.getGender(); - this.datebirth = user.getDatebirth(); + this.login = user.getLogin(); this.password = user.getPassword(); this.role = user.getRole(); this.predictions = user.getPredictions(); + this.predictionsCreated = user.getPredictionsCreated(); + this.personalProfile=user.getPersonalProfile(); + this.companyProfile=user.getCompanyProfile(); } diff --git a/backend/src/main/java/project/repositories/CompanyDataRepository.java b/backend/src/main/java/project/repositories/CompanyDataRepository.java new file mode 100644 index 0000000..303b10c --- /dev/null +++ b/backend/src/main/java/project/repositories/CompanyDataRepository.java @@ -0,0 +1,11 @@ +package project.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import project.model.CompanyData; +import project.model.PersonalData; + +@Repository +public interface CompanyDataRepository extends JpaRepository { + +} diff --git a/backend/src/main/java/project/repositories/CompanyProfileRepository.java b/backend/src/main/java/project/repositories/CompanyProfileRepository.java new file mode 100644 index 0000000..6c91791 --- /dev/null +++ b/backend/src/main/java/project/repositories/CompanyProfileRepository.java @@ -0,0 +1,19 @@ +package project.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import project.model.CompanyProfile; +import project.model.PersonalData; +import project.model.PersonalProfile; + +@Repository +public interface CompanyProfileRepository extends JpaRepository { + + @Query(value="SELECT * FROM company_profile cp WHERE cp.user_id=:userId", nativeQuery = true) + public CompanyProfile findByUserId(@Param("userId") int userId); + + @Query(value="SELECT COUNT(*) FROM company_part cp WHERE cp.company_id=:companyId AND cp.personal_id=:personalId", nativeQuery = true) + public int countCompanyPart(@Param("companyId") int companyId,@Param("personalId") int personalId); +} diff --git a/backend/src/main/java/project/repositories/PersonalDataRepository.java b/backend/src/main/java/project/repositories/PersonalDataRepository.java new file mode 100644 index 0000000..b667dc5 --- /dev/null +++ b/backend/src/main/java/project/repositories/PersonalDataRepository.java @@ -0,0 +1,9 @@ +package project.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import project.model.PersonalData; + +@Repository +public interface PersonalDataRepository extends JpaRepository { +} diff --git a/backend/src/main/java/project/repositories/PersonalProfileRepository.java b/backend/src/main/java/project/repositories/PersonalProfileRepository.java new file mode 100644 index 0000000..dd80387 --- /dev/null +++ b/backend/src/main/java/project/repositories/PersonalProfileRepository.java @@ -0,0 +1,16 @@ +package project.repositories; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import project.model.PersonalProfile; +import project.model.Role; +import project.model.User; + +@Repository +public interface PersonalProfileRepository extends JpaRepository { + + @Query(value="SELECT * FROM personal_profile pp WHERE pp.user_id=:userId", nativeQuery = true) + public PersonalProfile findByUserId(@Param("userId") int userId); +} diff --git a/backend/src/main/java/project/repositories/UserRepository.java b/backend/src/main/java/project/repositories/UserRepository.java index a5847a0..1d928ac 100644 --- a/backend/src/main/java/project/repositories/UserRepository.java +++ b/backend/src/main/java/project/repositories/UserRepository.java @@ -15,5 +15,5 @@ public interface UserRepository extends JpaRepository { public Optional findByLogin(String login); public Optional findByLoginAndPassword(String login,String password); - public User findOneByName(String username); +// public User findOneByName(String username); } diff --git a/backend/src/main/java/project/services/CompanyDataService.java b/backend/src/main/java/project/services/CompanyDataService.java new file mode 100644 index 0000000..37fbe01 --- /dev/null +++ b/backend/src/main/java/project/services/CompanyDataService.java @@ -0,0 +1,10 @@ +package project.services; + +import project.model.CompanyData; + +public interface CompanyDataService { + + public CompanyData getCompanyData(int id); + public CompanyData addCompanyData(CompanyData companyData); +// public boolean deleteCompanyData(int id); +} diff --git a/backend/src/main/java/project/services/CompanyDataServiceImpl.java b/backend/src/main/java/project/services/CompanyDataServiceImpl.java new file mode 100644 index 0000000..bbb0cce --- /dev/null +++ b/backend/src/main/java/project/services/CompanyDataServiceImpl.java @@ -0,0 +1,37 @@ +package project.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import project.model.CompanyData; +import project.model.CompanyProfile; +import project.repositories.CompanyDataRepository; + +import java.util.Optional; + +@Service +public class CompanyDataServiceImpl implements CompanyDataService { + + + @Autowired + private CompanyDataRepository companyDataRepository; + + @Override + public CompanyData getCompanyData(int id) { + Optional optionalCompanyData = companyDataRepository.findById(id); + if(optionalCompanyData.isPresent()){ + return optionalCompanyData.get(); + }else{ + return null; + } + } + + @Override + public CompanyData addCompanyData(CompanyData companyData) { + return companyDataRepository.save(companyData); + } + +// @Override +// public boolean deleteCompanyData(int id) { +// companyDataRepository.deleteById(id); +// } +} diff --git a/backend/src/main/java/project/services/CompanyProfileService.java b/backend/src/main/java/project/services/CompanyProfileService.java new file mode 100644 index 0000000..5f220e4 --- /dev/null +++ b/backend/src/main/java/project/services/CompanyProfileService.java @@ -0,0 +1,17 @@ +package project.services; + +import project.model.CompanyData; +import project.model.CompanyProfile; +import project.model.PersonalProfile; + +import java.util.List; + +public interface CompanyProfileService { + + public CompanyProfile getCompanyProfile(int id); + public CompanyProfile addCompanyProfile(CompanyProfile companyProfile); +// public boolean deleteCompanyProfile(int id); + public CompanyProfile getCompanyProfileByUserId(int userId); + public boolean isCompanyAuthorized(int companyId,int personalId); + public List getAllCompanies(); +} diff --git a/backend/src/main/java/project/services/CompanyProfileServiceImpl.java b/backend/src/main/java/project/services/CompanyProfileServiceImpl.java new file mode 100644 index 0000000..081ac24 --- /dev/null +++ b/backend/src/main/java/project/services/CompanyProfileServiceImpl.java @@ -0,0 +1,54 @@ +package project.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import project.model.CompanyProfile; +import project.model.PersonalProfile; +import project.repositories.CompanyProfileRepository; + +import java.util.List; +import java.util.Optional; + +@Service +public class CompanyProfileServiceImpl implements CompanyProfileService { + + @Autowired + private CompanyProfileRepository companyProfileRepository; + + @Override + public CompanyProfile getCompanyProfile(int id) { + Optional optionalCompanyProfile = companyProfileRepository.findById(id); + if(optionalCompanyProfile.isPresent()){ + return optionalCompanyProfile.get(); + }else{ + return null; + } + } + + @Override + public CompanyProfile addCompanyProfile(CompanyProfile companyProfile) { + return companyProfileRepository.save(companyProfile); + } + + @Override + public CompanyProfile getCompanyProfileByUserId(int userId) { + return companyProfileRepository.findByUserId(userId); + } + + @Override + public boolean isCompanyAuthorized(int companyId, int personalId) { + int c = companyProfileRepository.countCompanyPart(companyId,personalId); + if (c==0){return false;} + else {return true;} + } + + @Override + public List getAllCompanies() { + return companyProfileRepository.findAll(); + } + // @Override +// public boolean deleteCompanyProfile(int id) { +// companyProfileRepository.deleteById(id); +// return true; +// } +} diff --git a/backend/src/main/java/project/services/GeneratorDTO.java b/backend/src/main/java/project/services/GeneratorDTO.java index 2483271..1f673a0 100644 --- a/backend/src/main/java/project/services/GeneratorDTO.java +++ b/backend/src/main/java/project/services/GeneratorDTO.java @@ -2,9 +2,9 @@ package project.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import project.DTO.PredictionDTO; -import project.DTO.RoleDTO; -import project.DTO.UserDTO; +import project.DTO.*; +import project.model.CompanyProfile; +import project.model.PersonalProfile; import project.model.Prediction; import project.model.User; @@ -28,6 +28,7 @@ public class GeneratorDTO implements Serializable { List predictionDTOS = new ArrayList<>(); for (Prediction prediction:predictionList) { PredictionDTO predictionDTO = new PredictionDTO(); + predictionDTO.setId(prediction.getId()); predictionDTO.setName(prediction.getName()); predictionDTO.setLocalDateTime(prediction.getLocalDateTime()); predictionDTO.setResultValue(prediction.getResultValue()); @@ -36,4 +37,19 @@ public class GeneratorDTO implements Serializable { return predictionDTOS; } + + public PersonalProfileDTO generatePersonalProfileDTO(PersonalProfile personalProfile){ + PersonalDataDTO personalDataDTO = new PersonalDataDTO(personalProfile.getPersonalData()); + UserDTO userDTO = generateUserDTO(personalProfile.getUser()); + + PersonalProfileDTO personalProfileDTO = new PersonalProfileDTO(personalDataDTO,userDTO); + return personalProfileDTO; + + } + public CompanyProfileDTO generateCompanyProfileDTO(CompanyProfile companyProfile){ + CompanyDataDTO companyDataDTO = new CompanyDataDTO(companyProfile.getCompanyData()); + UserDTO userDTO = generateUserDTO(companyProfile.getUser()); + + return new CompanyProfileDTO(companyDataDTO,userDTO); + } } diff --git a/backend/src/main/java/project/services/PersonalDataService.java b/backend/src/main/java/project/services/PersonalDataService.java new file mode 100644 index 0000000..dbe011c --- /dev/null +++ b/backend/src/main/java/project/services/PersonalDataService.java @@ -0,0 +1,10 @@ +package project.services; + +import project.model.CompanyProfile; +import project.model.PersonalData; + +public interface PersonalDataService { + public PersonalData getPersonalData(int id); + public PersonalData addPersonalData(PersonalData personalData); +// public boolean deletePersonalData(int id); +} diff --git a/backend/src/main/java/project/services/PersonalDataServiceImpl.java b/backend/src/main/java/project/services/PersonalDataServiceImpl.java new file mode 100644 index 0000000..714df90 --- /dev/null +++ b/backend/src/main/java/project/services/PersonalDataServiceImpl.java @@ -0,0 +1,38 @@ +package project.services; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import project.model.PersonalData; +import project.model.PersonalProfile; +import project.repositories.PersonalDataRepository; + +import java.util.Optional; + +@Service +public class PersonalDataServiceImpl implements PersonalDataService { + + @Autowired + private PersonalDataRepository personalDataRepository; + + @Override + public PersonalData getPersonalData(int id) { + Optional optionalPersonalData = personalDataRepository.findById(id); + if(optionalPersonalData.isPresent()){ + return optionalPersonalData.get(); + }else{ + return null; + } + } + + @Override + public PersonalData addPersonalData(PersonalData personalData) { + return personalDataRepository.save(personalData); + } + +// @Override +// public boolean deletePersonalData(int id) { +// +// personalDataRepository.deleteById(id); +// +// } +} diff --git a/backend/src/main/java/project/services/PersonalProfileService.java b/backend/src/main/java/project/services/PersonalProfileService.java new file mode 100644 index 0000000..36fcb2e --- /dev/null +++ b/backend/src/main/java/project/services/PersonalProfileService.java @@ -0,0 +1,12 @@ +package project.services; + +import project.model.PersonalData; +import project.model.PersonalProfile; + +public interface PersonalProfileService { + + public PersonalProfile getPersonalProfile(int id); + public PersonalProfile addPersonalProfile(PersonalProfile personalProfile); +// public boolean deletePersonalProfile(int id); + public PersonalProfile getPersonalProfileByUserId(int userId); +} diff --git a/backend/src/main/java/project/services/PersonalProfileServiceImpl.java b/backend/src/main/java/project/services/PersonalProfileServiceImpl.java new file mode 100644 index 0000000..47015a2 --- /dev/null +++ b/backend/src/main/java/project/services/PersonalProfileServiceImpl.java @@ -0,0 +1,42 @@ +package project.services; + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import project.model.PersonalProfile; +import project.repositories.PersonalProfileRepository; + +import java.util.Optional; + +@Service +public class PersonalProfileServiceImpl implements PersonalProfileService { + + @Autowired + private PersonalProfileRepository personalProfileRepository; + + @Override + public PersonalProfile getPersonalProfile(int id) { + Optional optionalPersonalProfile = personalProfileRepository.findById(id); + if(optionalPersonalProfile.isPresent()){ + return optionalPersonalProfile.get(); + }else{ + return null; + } + } + + @Override + public PersonalProfile addPersonalProfile(PersonalProfile personalProfile) { + return personalProfileRepository.save(personalProfile); + } + +// @Override +// public boolean deletePersonalProfile(int id) { +// personalProfileRepository.deleteById(id); +// } + + @Override + public PersonalProfile getPersonalProfileByUserId(int userId) { + return personalProfileRepository.findByUserId(userId); + + } +} diff --git a/backend/src/main/java/project/services/PredictionService.java b/backend/src/main/java/project/services/PredictionService.java index 59452ff..38da888 100644 --- a/backend/src/main/java/project/services/PredictionService.java +++ b/backend/src/main/java/project/services/PredictionService.java @@ -10,4 +10,5 @@ public interface PredictionService { public Prediction savePrediction(PredictionDTO predictionDTO); public Prediction getPrediction(int id); public List getAllPredictionsForUser(int userId); + public boolean deletePrediction(int userId,int id); } diff --git a/backend/src/main/java/project/services/PredictionServiceImpl.java b/backend/src/main/java/project/services/PredictionServiceImpl.java index ff08840..1a4aa0d 100644 --- a/backend/src/main/java/project/services/PredictionServiceImpl.java +++ b/backend/src/main/java/project/services/PredictionServiceImpl.java @@ -39,6 +39,7 @@ public class PredictionServiceImpl implements PredictionService { prediction.setLocalDateTime(LocalDateTime.now()); prediction.setUser(userService.getUserById(predictionDTO.getUser())); + prediction.setCreator(userService.getUserById(predictionDTO.getCreator())); Prediction savedPrediction = this.predictionRepository.save(prediction); List parameterInts = new ArrayList<>(); @@ -76,6 +77,16 @@ public class PredictionServiceImpl implements PredictionService { } return null; } + + public boolean deletePrediction(int userId,int id){ + Prediction pred = getPrediction(id); + if(pred.getCreator().getId()==userId){ + this.predictionRepository.deleteById(id); + return true; + } + return false; + + } public List getAllPredictionsForUser(int userId){ Optional> optionalPredictions = predictionRepository.findByUserId(userId); if(optionalPredictions.isPresent()){ diff --git a/backend/src/main/java/project/services/UserService.java b/backend/src/main/java/project/services/UserService.java index f54f92d..8f5d65b 100644 --- a/backend/src/main/java/project/services/UserService.java +++ b/backend/src/main/java/project/services/UserService.java @@ -1,5 +1,6 @@ package project.services; +import project.DTO.PersonalProfileDTO; import project.DTO.UserDTO; import project.model.Prediction; import project.model.User; @@ -17,7 +18,7 @@ public interface UserService { public void deleteUser(int id); public User getUserById(int id); public List getAllUsers(); - public boolean checkIfCorrect(UserDTO userDTO,boolean edit); + public boolean checkIfCorrect(PersonalProfileDTO personalProfileDTO, boolean edit); diff --git a/backend/src/main/java/project/services/UserServiceImpl.java b/backend/src/main/java/project/services/UserServiceImpl.java index 00d2d16..99bbf4f 100644 --- a/backend/src/main/java/project/services/UserServiceImpl.java +++ b/backend/src/main/java/project/services/UserServiceImpl.java @@ -11,8 +11,10 @@ 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 project.DTO.PersonalProfileDTO; import project.DTO.UserDTO; import project.model.CustomUserDetails; +import project.model.PersonalProfile; import project.model.Prediction; import project.model.User; import project.repositories.UserRepository; @@ -81,20 +83,20 @@ public class UserServiceImpl implements UserService,UserDetailsService { } - public boolean checkIfCorrect(UserDTO userDTO,boolean edit){ + public boolean checkIfCorrect(PersonalProfileDTO personalProfileDTO, boolean edit){ Pattern pName =Pattern.compile("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,15}$"); Pattern pSurname =Pattern.compile("^[A-Z][a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{2,20}$"); Pattern pEmail =Pattern.compile("^[a-z]+[0-9]*@([a-z]{2,10}\\.)+[a-z]{2,5}$"); Pattern pLogin =Pattern.compile("^([a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]+[0-9\\-\\_]*){5,20}$"); Pattern pPassword =Pattern.compile("^([a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż]{5,}[0-9]{5,}[a-zA-ZĄąĆćĘꣳŃńÓ󌜏źŻż0-9]*)+$"); - if(!pName.matcher(userDTO.getName()).matches() | !pSurname.matcher(userDTO.getSurname()).matches() | - !pEmail.matcher(userDTO.getEmail()).matches() ) { + if(!pName.matcher(personalProfileDTO.getPersonalDataDTO().getName()).matches() | !pSurname.matcher(personalProfileDTO.getPersonalDataDTO().getSurname()).matches() | + !pEmail.matcher(personalProfileDTO.getPersonalDataDTO().getEmail()).matches() ) { return false; }else if(!edit){ - if(!pLogin.matcher(userDTO.getLogin()).matches() | - !pPassword.matcher(userDTO.getPassword()).matches()){ + if(!pLogin.matcher(personalProfileDTO.getUserDTO().getLogin()).matches() | + !pPassword.matcher(personalProfileDTO.getUserDTO().getPassword()).matches()){ return false; }else { return true; diff --git a/backend/src/test/java/project/services/UserServiceImplTest.java b/backend/src/test/java/project/services/UserServiceImplTest.java index 1a5203e..cb1d078 100644 --- a/backend/src/test/java/project/services/UserServiceImplTest.java +++ b/backend/src/test/java/project/services/UserServiceImplTest.java @@ -7,6 +7,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import project.DTO.PersonalDataDTO; +import project.DTO.PersonalProfileDTO; import project.DTO.UserDTO; import project.repositories.UserRepository; @@ -17,19 +19,21 @@ public class UserServiceImplTest { @Autowired public UserServiceImpl userServiceImpl; - public UserDTO generateUserDTO(){ + public PersonalProfileDTO generatePersonalProfileDTO(){ UserDTO userDTO = new UserDTO(); - userDTO.setName(" "); - userDTO.setSurname(" "); - userDTO.setEmail(" "); - return userDTO; + PersonalDataDTO personalDataDTO = new PersonalDataDTO(); + + personalDataDTO.setName(" "); + personalDataDTO.setSurname(" "); + personalDataDTO.setEmail(" "); + return new PersonalProfileDTO(personalDataDTO,userDTO); } @Test public void checkIfCorrectTest(){ - UserDTO userDTO = generateUserDTO(); + PersonalProfileDTO personalProfileDTO = generatePersonalProfileDTO(); UserServiceImpl userService = new UserServiceImpl(); - boolean response = userService.checkIfCorrect(userDTO,false); + boolean response = userService.checkIfCorrect(personalProfileDTO,false); Assert.assertTrue(response==false); }