TAK-77 TAK-79 company model & calculator manager

This commit is contained in:
Rafał Piskorski 2021-01-17 17:06:06 +01:00
parent aa5a9218d7
commit 4dd74efcd2
42 changed files with 1272 additions and 221 deletions

View File

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

View File

@ -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")))

145
app/calculator_view.R Normal file
View File

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

View File

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

View File

@ -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,22 +77,29 @@ 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)
# status$first = FALSE
to_send = list(name = editedPersonalData$name,
personalData = list(
name = editedPersonalData$name,
surname = editedPersonalData$surname,
email = editedPersonalData$mail,
datebirth = editedPersonalData$datebirth,
gender =editedPersonalData$gender)
to_send = list(
personalDataDTO = personalData)
r<-httr::PUT("http://localhost:8080/api/profile",add_headers(Authorization=paste("Bearer",input$token,sep=" ")),body=to_send,encode = 'json')
if (r$status_code==200){
@ -97,7 +120,12 @@ profilServer <- function(input, output,session) {
observe({
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);')
@ -119,22 +147,23 @@ profilServer <- function(input, output,session) {
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')
@ -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)))
# print(typeof(df_historyTable))
# print(df_historyTable)
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)'))
}
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))}
}

View File

@ -71,16 +71,24 @@ registerServer <- function(input, output,session) {
status$first = FALSE
to_send = list(name = result$name,
personalData = list(
name = result$name,
surname = result$surname,
email = result$mail,
datebirth = result$datebirth,
gender = result$gender,
gender = result$gender)
roleData = list(name="IND")
userData = list(
login = result$login,
password= result$password,
roleDTO= "IND")
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

View File

@ -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)
)

View File

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

View File

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

View File

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

View File

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

View File

@ -27,6 +27,10 @@ public class PredictionDTO implements Serializable {
@Setter
private int user;
@Getter
@Setter
private int creator;
@Getter
@Setter
private List<ParameterDouble> 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();

View File

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

View File

@ -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,13 +41,19 @@ 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<String,Object> generateToken(@RequestBody UserDTO loginForm,
public ResponseEntity<Map<String,Object>> generateToken(@RequestBody UserDTO loginForm,
HttpServletRequest request,
HttpServletResponse httpServletResponse){
@ -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);
}

View File

@ -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<Map<String,Object>> getAllCompanies(HttpServletRequest request,
HttpServletResponse httpServletResponse){
Map<String,Object> 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);
}
}
}

View File

@ -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<String,Object> addPrediction(@RequestBody @Valid @NotNull PredictionDTO predictionDTO,
HttpServletRequest request,
@ -64,7 +69,22 @@ public class PredictionController {
map.put("token", tokenHelper.refreshToken(token.toString()));
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){
if(prediction.getUser().getId()==currentUser.getId() || prediction.getCreator().getId()==currentUser.getId()){
map.put("prediction", new PredictionDTO(prediction));
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.ACCEPTED);
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
}else{
map.put("prediction", null);
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.BAD_REQUEST);
}
}else{
map.put("prediction", null);
return new ResponseEntity<Map<String,Object>>(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<Map<String,Object>> deletePrediction(@PathVariable int id,HttpServletRequest request,
HttpServletResponse httpServletResponse){
Map<String,Object> map = new HashMap<>();
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Optional<User> 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<String,Object>>(map, HttpStatus.OK);
}else{
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.BAD_REQUEST);
}
}
else {
map.put("message", "Błąd autoryzacji");
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.UNAUTHORIZED);
}
}
@PreAuthorize("hasAnyAuthority('IND')")
@RequestMapping(value = "/usersPredictions/ind",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String,Object>> getUsersPredictions(HttpServletRequest request,

View File

@ -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,61 +55,71 @@ public class UserController {
@PreAuthorize("isAnonymous()")
@RequestMapping(value = "/register",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> addUser(@RequestBody @Valid @NotNull UserDTO userDTO,
public ResponseEntity<Map<String,Object>> 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<String,Object> map = new HashMap<>();
Object token = request.getAttribute("token");
map.put("token",token);
Optional<User> users = this.userService.getUsersByLogin(userDTO.getLogin());
Optional<User> 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<String,Object>>(map, HttpStatus.BAD_REQUEST);
}
else if(!userService.checkIfCorrect(userDTO,false)){
else if(!userService.checkIfCorrect(personalProfileDTO,false)) {
map.put("message", "Niepoprawny login lub hasło");
httpServletResponse.setStatus(461);
return map;}
return new ResponseEntity<Map<String, Object>>(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);
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");
httpServletResponse.setStatus(200);
return map;
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
}catch (Exception e){
map.put("message", "Błąd rejestracji");
return new ResponseEntity<Map<String,Object>>(map, HttpStatus.BAD_REQUEST);
}
}
}
@ -111,10 +127,11 @@ public class UserController {
@PreAuthorize("hasAnyAuthority('COMP','IND')")
@RequestMapping(value="/profile",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String,Object> getMyProfile(HttpServletRequest request,HttpServletResponse httpServletResponse){
public ResponseEntity<Map<String,Object>> getMyProfile(HttpServletRequest request,HttpServletResponse httpServletResponse){
Map<String,Object> 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<String,Object> editMyProfile(@RequestBody @Valid @NotNull UserDTO userDTO,HttpServletRequest request,HttpServletResponse httpServletResponse){
public ResponseEntity<Map<String,Object>> editMyProfile(@RequestBody @Valid @NotNull PersonalProfileDTO personalProfileDTO,HttpServletRequest request,HttpServletResponse httpServletResponse){
Map<String,Object> 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;
}

View File

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

View File

@ -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<PersonalProfile> personalProfiles;
@Getter
@Setter
@OneToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="userId",referencedColumnName = "id")
private User user;
public CompanyProfile(){};
public CompanyProfile(CompanyData companyData, List<PersonalProfile> 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;
}
}

View File

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

View File

@ -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<CompanyProfile> 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<CompanyProfile> companyProfileList) {
this.personalData = personalData;
this.user = user;
this.companyProfileList = companyProfileList;
}
}

View File

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

View File

@ -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<Prediction> predictions;
@Getter
@Setter
@OneToMany(mappedBy = "creator",orphanRemoval = true,cascade = CascadeType.PERSIST)
@JsonIgnore
private List<Prediction> 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();
}

View File

@ -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<CompanyData,Integer> {
}

View File

@ -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<CompanyProfile,Integer> {
@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);
}

View File

@ -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<PersonalData,Integer> {
}

View File

@ -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<PersonalProfile,Integer> {
@Query(value="SELECT * FROM personal_profile pp WHERE pp.user_id=:userId", nativeQuery = true)
public PersonalProfile findByUserId(@Param("userId") int userId);
}

View File

@ -15,5 +15,5 @@ public interface UserRepository extends JpaRepository<User,Integer> {
public Optional<User> findByLogin(String login);
public Optional<User> findByLoginAndPassword(String login,String password);
public User findOneByName(String username);
// public User findOneByName(String username);
}

View File

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

View File

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

View File

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

View File

@ -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<CompanyProfile> 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<CompanyProfile> getAllCompanies() {
return companyProfileRepository.findAll();
}
// @Override
// public boolean deleteCompanyProfile(int id) {
// companyProfileRepository.deleteById(id);
// return true;
// }
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,4 +10,5 @@ public interface PredictionService {
public Prediction savePrediction(PredictionDTO predictionDTO);
public Prediction getPrediction(int id);
public List<Prediction> getAllPredictionsForUser(int userId);
public boolean deletePrediction(int userId,int id);
}

View File

@ -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<ParameterInt> 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<Prediction> getAllPredictionsForUser(int userId){
Optional<List<Prediction>> optionalPredictions = predictionRepository.findByUserId(userId);
if(optionalPredictions.isPresent()){

View File

@ -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<User> getAllUsers();
public boolean checkIfCorrect(UserDTO userDTO,boolean edit);
public boolean checkIfCorrect(PersonalProfileDTO personalProfileDTO, boolean edit);

View File

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

View File

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