Skip to content

Commit

Permalink
feat: add trigger route to start syncing users from userService to ca…
Browse files Browse the repository at this point in the history
…lcom

Signed-off-by: PhilippFruh <[email protected]>
  • Loading branch information
PhilippFr committed Jul 6, 2022
1 parent 79c347b commit 4b56314
Show file tree
Hide file tree
Showing 10 changed files with 199 additions and 77 deletions.
4 changes: 2 additions & 2 deletions api/appointmentService.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ paths:
content:
application/json:
schema:
$ref: './../services/userservice.yaml#/components/schemas/UserDTO'
$ref: './../services/useradminservice.yaml#/components/schemas/ConsultantDTO'
required: true
responses:
'200':
Expand All @@ -50,7 +50,7 @@ paths:
content:
application/json:
schema:
$ref: './../services/userservice.yaml#/components/schemas/UserDTO'
$ref: './../services/useradminservice.yaml#/components/schemas/ConsultantDTO'
required: true
responses:
'200':
Expand Down
52 changes: 52 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,32 @@
<output>target/generated-sources/userservice</output>
</configuration>
</execution>
<execution>
<id>user-admin-service-client-model</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<configOptions>
<sourceFolder>/</sourceFolder>
<library>resttemplate</library>
<dateLibrary>java8</dateLibrary>
</configOptions>
<inputSpec>${project.basedir}/services/useradminservice.yaml</inputSpec>
<generatorName>java</generatorName>
<generateApis>true</generateApis>
<generateApiTests>false</generateApiTests>
<generateModelTests>false</generateModelTests>
<apiPackage>
${project.groupId}.${project.artifactId}.useradminservice.generated.web
</apiPackage>
<modelPackage>
${project.groupId}.${project.artifactId}.useradminservice.generated.web.model
</modelPackage>
<output>target/generated-sources/useradminservice</output>
</configuration>
</execution>
<execution>
<id>agency-service-client-model</id>
<phase>generate-sources</phase>
Expand All @@ -224,6 +250,32 @@
<output>target/generated-sources/agencyservice</output>
</configuration>
</execution>
<execution>
<id>agency-admin-service-client-model</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<configOptions>
<sourceFolder>/</sourceFolder>
<library>resttemplate</library>
<dateLibrary>java8</dateLibrary>
</configOptions>
<inputSpec>${project.basedir}/services/agencyadminservice.yaml</inputSpec>
<generatorName>java</generatorName>
<generateApis>true</generateApis>
<generateApiTests>false</generateApiTests>
<generateModelTests>false</generateModelTests>
<apiPackage>
${project.groupId}.${project.artifactId}.agencyadminservice.generated.web
</apiPackage>
<modelPackage>
${project.groupId}.${project.artifactId}.agencyadminservice.generated.web.model
</modelPackage>
<output>target/generated-sources/agencyadminservice</output>
</configuration>
</execution>
<execution>
<id>keycloak-extension</id>
<phase>generate-sources</phase>
Expand Down
4 changes: 2 additions & 2 deletions services/useradminservice.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ components:
agencies:
type: array
items:
$ref: './../services/agencyadminservice.yaml#/components/schemas/AgencyAdminResponseDTO'
$ref: './agencyadminservice.yaml#/components/schemas/AgencyAdminResponseDTO'

ConsultantAdminResponseDTO:
type: object
Expand Down Expand Up @@ -793,7 +793,7 @@ components:
_embedded:
type: array
items:
$ref: './../services/agencyadminservice.yaml#/components/schemas/AgencyAdminFullResponseDTO'
$ref: './agencyadminservice.yaml#/components/schemas/AgencyAdminFullResponseDTO'
_links:
$ref: '#/components/schemas/ConsultantAgencyLinks'
total:
Expand Down
2 changes: 1 addition & 1 deletion services/userservice.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2434,7 +2434,7 @@ components:
agencies:
type: array
items:
$ref: './../services/agencyservice.yaml#/components/schemas/AgencyResponseDTO'
$ref: './agencyservice.yaml#/components/schemas/AgencyResponseDTO'

PasswordDTO:
type: object
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ protected void configure(HttpSecurity http) throws Exception {
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and().authorizeRequests()
.antMatchers(WHITE_LIST).permitAll()
.antMatchers("/agencies", "/agencies/**").permitAll()
.antMatchers("/consultants", "/consultants/**").permitAll()
.antMatchers("/askers", "/askers/**").permitAll()
//.antMatchers("/agencies", "/agencies/**").permitAll()
//.antMatchers("/consultants", "/consultants/**").permitAll()
//.antMatchers("/askers", "/askers/**").permitAll()
.anyRequest().permitAll();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.vi.appointmentservice.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vi.appointmentservice.api.model.*;
Expand All @@ -10,7 +11,7 @@
import com.vi.appointmentservice.service.CalComTeamService;
import com.vi.appointmentservice.service.CalComUserService;
import com.vi.appointmentservice.service.UserService;
import com.vi.appointmentservice.userservice.generated.web.model.ConsultantDTO;
import com.vi.appointmentservice.api.model.ConsultantDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
Expand All @@ -23,6 +24,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
Expand All @@ -37,17 +39,10 @@ public class ConsultantController implements ConsultantsApi {
private final @NonNull CalComUserService calComUserService;
private final @NonNull CalComTeamService calComTeamService;
private final @NonNull UserService userService;
private final @NonNull ObjectMapper objectMapper;
private final @NonNull CalcomUserToConsultantRepository calcomUserToConsultantRepository;
private final @NonNull TeamToAgencyRepository teamToAgencyRepository;

/**
* TEMP Admin route to associate consultant to calcomUser
*
* @param consultantId
* @param requestBodyString
* @return
*/

@PostMapping(
value = "/consultant/{consultantId}/associateUser",
produces = {"application/json"},
Expand Down Expand Up @@ -80,66 +75,137 @@ ResponseEntity<String> getAllConsultants() {
value = "/updateConsultants",
produces = {"application/json"}
)
ResponseEntity<String> updateConsultants(){
ResponseEntity<String> updateConsultants() {
ObjectMapper objectMapper = new ObjectMapper();
JSONArray consultantsArray = this.userService.getAllConsultants();
List<CalcomUser> consultantsList = new ArrayList<>();
try {
for (int i = 0; i < consultantsArray.length(); i++) {
ConsultantDTO consultant = objectMapper.readValue(consultantsArray.getJSONObject(i).toString(), ConsultantDTO.class);

if(calcomUserToConsultantRepository.existsByConsultantId(consultant.getId())){
// TODO: If yes, update
if (calcomUserToConsultantRepository.existsByConsultantId(consultant.getId())) {
// Found user association
Long calComUserId = calcomUserToConsultantRepository.findByConsultantId(consultant.getId()).getCalComUserId();

// calComUserService.updateUser()
}else{
// TODO: If not, create

// Check if user really exists
CalcomUser foundUser = calComUserService.getUserById(calComUserId);
if (foundUser == null) {
// User missing, create
consultantsList.add(this.createCalcomUser(consultant));
} else {
// User exists, update
consultantsList.add(this.updateCalcomUser(consultant));
}
} else {
consultantsList.add(this.createCalcomUser(consultant));
}

}
}catch (Exception e){
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(consultantsArray.toString(), HttpStatus.OK);
return new ResponseEntity<>(new JSONObject(consultantsList).toString(), HttpStatus.OK);
}

@Override
public ResponseEntity<CalcomUser> createConsultant(UserDTO userDTO) {
CalcomUser creationUser = new CalcomUser();
creationUser.setName(userDTO.getUsername());
creationUser.setUsername(userDTO.getUsername());
// TODO: creationUser.setEmail();
// Default values
creationUser.setTimeZone("Europe/Berlin");
creationUser.setWeekStart("Monday");
creationUser.setLocale("de");
creationUser.setTimeFormat(24);
creationUser.setAllowDynamicBooking(false);
// TODO: Any more default values?

CalcomUser createdUser = calComUserService.createUser(creationUser);
// TODO: Add onber userID
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
// CalcomUserToUser userAssociation = new CalcomUserToUser(userDTO.getUserId(), createdUser.getId());

// Add user to team of agency
//Long teamId = teamToAgencyRepository.findByAgencyId(userDTO.getAgencyId()).get(0).getTeamid();
//calComTeamService.addUserToTeam(createdUser.getId(), teamId);


//return new ResponseEntity<>(createdUser, HttpStatus.OK);
public ResponseEntity<CalcomUser> createConsultant(ConsultantDTO consultant) {
try {
CalcomUser createdUser = this.createCalcomUser(consultant);
return new ResponseEntity<>(createdUser, HttpStatus.OK);
} catch (JsonProcessingException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}

private CalcomUser createCalcomUser(ConsultantDTO consultant) throws JsonProcessingException {
if (calcomUserToConsultantRepository.existsByConsultantId(consultant.getId())) {
// Already exists, update user
return this.updateCalcomUser(consultant);
} else {
CalcomUser creationUser = new CalcomUser();
creationUser.setName(consultant.getFirstname() + " " + consultant.getLastname());
creationUser.setUsername(consultant.getUsername().replace("enc.", ""));
creationUser.setEmail(consultant.getEmail());
// Default values
creationUser.setTimeZone("Europe/Berlin");
creationUser.setWeekStart("Monday");
creationUser.setLocale("de");
creationUser.setTimeFormat(24);
creationUser.setAllowDynamicBooking(false);
// TODO: Any more default values?
ObjectMapper objectMapper = new ObjectMapper();
// Ignore null values
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JSONObject createJson = new JSONObject(objectMapper.writeValueAsString(creationUser));
CalcomUser createdUser = calComUserService.createUser(createJson);
// Create association
calcomUserToConsultantRepository.save(new CalcomUserToConsultant(consultant.getId(), createdUser.getId()));
// Add user to team of teams of agencies
List<AgencyAdminResponseDTO> agencies = consultant.getAgencies();
for (AgencyAdminResponseDTO agency : agencies) {
if (teamToAgencyRepository.existsByAgencyId(agency.getId())) {
if (teamToAgencyRepository.existsByAgencyId(agency.getId())) {
Long teamId = teamToAgencyRepository.findByAgencyId(agency.getId()).get(0).getTeamid();
}else{
// TODO: Create team for agency
}
// TODO: Check if membership already exists (calcom route currently limited to memerships of api key creator)
// TODO: calComTeamService.addUserToTeam(updatedUser.getId(), teamId);
}
}
return createdUser;
}
}

private CalcomUser updateCalcomUser(ConsultantDTO consultant) throws JsonProcessingException {
if (calcomUserToConsultantRepository.existsByConsultantId(consultant.getId())) {
// Exists, update the user
Long calcomUserId = calcomUserToConsultantRepository.findByConsultantId(consultant.getId()).getCalComUserId();
CalcomUser updateUser = new CalcomUser();
updateUser.setId(calcomUserId);
updateUser.setName(consultant.getFirstname() + " " + consultant.getLastname());
updateUser.setUsername(consultant.getUsername().replace("enc.", ""));
updateUser.setEmail(consultant.getEmail());
// Default values
updateUser.setTimeZone("Europe/Berlin");
updateUser.setWeekStart("Monday");
updateUser.setLocale("de");
updateUser.setTimeFormat(24);
updateUser.setAllowDynamicBooking(false);
// TODO: Any more default values?
ObjectMapper objectMapper = new ObjectMapper();
// Ignore null values
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JSONObject updateJson = new JSONObject(objectMapper.writeValueAsString(updateUser));
CalcomUser updatedUser = calComUserService.updateUser(updateJson);
// Add user to team of teams of agencies
List<AgencyAdminResponseDTO> agencies = consultant.getAgencies();
for (AgencyAdminResponseDTO agency : agencies) {
if (teamToAgencyRepository.existsByAgencyId(agency.getId())) {
Long teamId = teamToAgencyRepository.findByAgencyId(agency.getId()).get(0).getTeamid();
}else{
// TODO: Create team for agency
}
// TODO: Check if membership already exists (calcom route currently limited to memerships of api key creator)
// TODO: calComTeamService.addUserToTeam(updatedUser.getId(), teamId);
}
return updatedUser;
} else {
// Doesnt exists, create the user
return this.createCalcomUser(consultant);
}
}

@Override
public ResponseEntity<Void> deleteConsultant(String userId) {
Long calcomUserId = calcomUserToConsultantRepository.findByConsultantId(userId).getCalComUserId();
public ResponseEntity<Void> deleteConsultant(String consultantId) {
Long calcomUserId = calcomUserToConsultantRepository.findByConsultantId(consultantId).getCalComUserId();
HttpStatus responseCode = calComUserService.deleteUser(calcomUserId);
if (responseCode == HttpStatus.OK) {
calcomUserToConsultantRepository.deleteByConsultantId(consultantId);
}
return new ResponseEntity<>(responseCode);
}

@Override
public ResponseEntity<CalcomUser> updateConsultant(String userId, UserDTO userDTO) {
return ConsultantsApi.super.updateConsultant(userId, userDTO);
public ResponseEntity<CalcomUser> updateConsultant(String userId, ConsultantDTO consultantDTO) {
return ConsultantsApi.super.updateConsultant(userId, consultantDTO);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ public interface CalcomUserToConsultantRepository extends JpaRepository<CalcomUs

boolean existsByConsultantId(String consultantId);

long deleteByConsultantId(String consultantId);



}
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@

public interface TeamToAgencyRepository extends JpaRepository<TeamToAgency, Long> {
List<TeamToAgency> findByAgencyId(Long agencyId);

boolean existsByAgencyId(Long agencyId);


}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public CalcomMembership addUserToTeam(Long calComUserId, Long calComTeamid){
membership.put("accepted", true);
membership.put("userId", "MEMBER");
HttpEntity<String> request = new HttpEntity<>(membership.toString(), headers);
return restTemplate.postForEntity(this.buildUri("/v1/teams"), request , CalcomMembership.class ).getBody();
return restTemplate.postForEntity(this.buildUri("/v1/memberships"), request , CalcomMembership.class ).getBody();
}


Expand Down
Loading

0 comments on commit 4b56314

Please sign in to comment.