5 работает (город бы добавить и над оформление поработать)

This commit is contained in:
Ismailov_Rovshan 2023-05-24 17:19:18 +04:00
parent 93464f7382
commit 0e637791ef
13 changed files with 244 additions and 80 deletions

View File

@ -14,12 +14,22 @@ repositories {
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210' implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.hibernate.validator:hibernate-validator:7.0.1.Final'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }
tasks.named('test') { tasks.named('test') {

Binary file not shown.

View File

@ -6,7 +6,8 @@ import DataService from "../../services/DataService"
let headers = [ let headers = [
{label: "name", text: "Имя"}, {label: "name", text: "Имя"},
{label: "music", text: "Музыка"}, {label: "music", text: "Музыка"},
{label: "fullNames", text: "Группы"} {label: "community", text: "Группы"},
{ label: "city", text: "Город" }
] ]
export default function CatalogUsers() { export default function CatalogUsers() {
const url = "/users"; const url = "/users";
@ -14,7 +15,8 @@ export default function CatalogUsers() {
const [data, setData] = useState({ const [data, setData] = useState({
name: "", name: "",
music: [], music: [],
fullNames: [] community: [],
city: ""
}); });
const [selectedData, setSelectedData] = useState({ const [selectedData, setSelectedData] = useState({
@ -58,12 +60,12 @@ export default function CatalogUsers() {
} }
function addCommunity() { function addCommunity() {
for(let a of data.fullNames) { for(let a of data.community) {
if(a == selectedData.community) return; if(a == selectedData.community) return;
} }
let temp = data.fullNames.slice(0); let temp = data.community.slice(0);
temp.push(selectedData.community); temp.push(selectedData.community);
setData({...data, fullNames: temp}); setData({...data, community: temp});
} }
function deleteMusic(e) { function deleteMusic(e) {
@ -74,12 +76,12 @@ export default function CatalogUsers() {
function deleteCommunity(e) { function deleteCommunity(e) {
let communityName = e.target.previousSibling.textContent; let communityName = e.target.previousSibling.textContent;
let temp = data.fullNames.filter(x => (x != communityName)); let temp = data.community.filter(x => (x != communityName));
setData({...data, fullNames: temp}) setData({...data, community: temp})
} }
function onAdd() { function onAdd() {
setData({name: "", music: [], fullNames: []}); setData({name: "", music: [], community: []});
} }
@ -96,50 +98,72 @@ export default function CatalogUsers() {
<Catalog url={url} headers={headers} data={data} onAdd={onAdd} onChange={onChange} validate={validate}> <Catalog url={url} headers={headers} data={data} onAdd={onAdd} onChange={onChange} validate={validate}>
<div> <div>
<div className="mb-3"> <div className="mb-3">
<label htmlFor="name" className="form-label">Название</label> <label htmlFor="name" className="form-label">Название</label>
<input type="text" value={data.name} id="name" className="form-control" required autoComplete="off" <input
onChange={handleFormChange}/> type="text"
value={data.name}
id="name"
className="form-control"
required
autoComplete="off"
onChange={handleFormChange}
/>
</div> </div>
<select id="music" className="form-select" required <div className="mb-3">
value={selectedData.music} onChange={handleChangeSelected}> <label htmlFor="city" className="form-label">Город</label>
<option disabled value="">Укажите музыку</option> <input
{ type="text"
musics.map(({name, id}) => value={data.city}
<option key={id} value={name}>{name}</option> id="city"
) className="form-control"
} required
autoComplete="off"
onChange={handleFormChange}
/>
</div>
<select
id="music"
className="form-select mb-3"
required
value={selectedData.music}
onChange={handleChangeSelected}
>
<option disabled value="">Укажите музыку</option>
{musics.map(({ name, id }) => (
<option key={id} value={name}>{name}</option>
))}
</select> </select>
{ {data.music.map(value => (
data.music.map(value => ( <div className="badge bg-secondary mb-3" key={value}>
<div className="badge bg-secondary m-1" key={value}> <span>{value}</span>
<span>{value}</span> <button className="btn-close bg-danger" onClick={deleteMusic}></button>
<button className="btn-close bg-danger m-1" onClick={deleteMusic}></button> </div>
</div> ))}
))
}
<br></br>
<button onClick={addMusic} className="btn btn-success">Добавить музыку</button>
<select id="community" className="form-select" required
value={selectedData.community} onChange={handleChangeSelected}>
<option disabled value="">Укажите группу</option>
{
communities.map(({name, id}) =>
<option key={id} value={name}>{name}</option>
)
}
</select>
{
data.fullNames.map(value => (
<div className="badge bg-secondary m-1" key={value}>
<span>{value}</span>
<button className="btn-close bg-danger m-1" onClick={deleteCommunity}></button>
</div>
))
}
<br></br> <br></br>
<button onClick={addCommunity} className="btn btn-success">Добавить группу</button> <button onClick={addMusic} className="btn btn-success mb-3">Добавить музыку</button>
</div>
<select
id="community"
className="form-select mb-3"
required
value={selectedData.community}
onChange={handleChangeSelected}
>
<option disabled value="">Укажите группу</option>
{communities.map(({ name, id }) => (
<option key={id} value={name}>{name}</option>
))}
</select>
{data.community.map(value => (
<div className="badge bg-secondary mb-3" key={value}>
<span>{value}</span>
<button className="btn-close bg-danger" onClick={deleteCommunity}></button>
</div>
))}
<br></br>
<button onClick={addCommunity} className="btn btn-success mb-3">Добавить группу</button>
</div>
</Catalog> </Catalog>
) )
} }

View File

@ -2,6 +2,8 @@ package ru.ulstu.is.sbapp;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
@ -10,4 +12,18 @@ public class WebConfiguration implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*"); registry.addMapping("/**").allowedMethods("*");
} }
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("users");
registry.addViewController("contacts");
registry.addViewController("catalogs");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/css/**").addResourceLocations("/static/css/");
}
} }

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.socialNetwork.controller; package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.socialNetwork.dto.CommunityDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.CommunityDTO;
import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService; import ru.ulstu.is.sbapp.socialNetwork.services.CommunityService;
@ -8,7 +9,7 @@ import javax.validation.Valid;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/communities") @RequestMapping(WebConfiguration.REST_API + "/communities")
public class CommunityController { public class CommunityController {
private final CommunityService communityService; private final CommunityService communityService;
@ -23,7 +24,7 @@ public class CommunityController {
@GetMapping("") @GetMapping("")
public List<CommunityDTO> getCommunities() { public List<CommunityDTO> getCommunities() {
return communityService.findAllCommunitys().stream().map(CommunityDTO::new).toList(); return communityService.findAllCommunities().stream().map(CommunityDTO::new).toList();
} }
@PostMapping("") @PostMapping("")

View File

@ -2,24 +2,30 @@ package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.socialNetwork.dto.MusicDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.MusicDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.Music; import ru.ulstu.is.sbapp.socialNetwork.models.Music;
import ru.ulstu.is.sbapp.socialNetwork.services.MusicService; import ru.ulstu.is.sbapp.socialNetwork.services.MusicService;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/musics") @RequestMapping(WebConfiguration.REST_API + "/musics")
public class MusicController { public class MusicController {
private final MusicService musicService; private final MusicService musicService;
public MusicController(MusicService musicService){ public MusicController(MusicService musicService){
this.musicService = musicService; this.musicService = musicService;
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public MusicDTO getMusic(@PathVariable Long id){ public MusicDTO getMusic(@PathVariable Long id){
return new MusicDTO(musicService.findMusic(id)); return new MusicDTO(musicService.findMusic(id));
} }
@GetMapping("") @GetMapping("")
public List<MusicDTO> getMusics() { public List<MusicDTO> getMusics() {
return musicService.findAllMusics().stream().map(MusicDTO::new).toList(); return musicService.findAllMusics().stream().map(MusicDTO::new).toList();

View File

@ -1,15 +1,18 @@
package ru.ulstu.is.sbapp.socialNetwork.controller; package ru.ulstu.is.sbapp.socialNetwork.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.socialNetwork.dto.UserDTO; import ru.ulstu.is.sbapp.socialNetwork.dto.UserDTO;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService; import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/users") @RequestMapping(WebConfiguration.REST_API + "/users")
public class UserController { public class UserController {
private final UserService userService; private final UserService userService;
@ -27,6 +30,39 @@ public class UserController {
return userService.findAllUsers().stream().map(UserDTO::new).toList(); return userService.findAllUsers().stream().map(UserDTO::new).toList();
} }
@PostMapping("")
public UserDTO createUser(@RequestBody @Valid UserDTO user) {
UserModel result = userService.addUser(user.getName(), user.getCity());
userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic()));
}
@PatchMapping("/{id}")
public UserDTO updateUser(@PathVariable Long id,
@RequestBody @Valid UserDTO user) {
UserModel result = userService.updateUser(id, user.getName());
userService.updateCommunities(result.getId(), user.getCommunity());
return new UserDTO(userService.updateMusics(result.getId(), user.getMusic()));
}
@PatchMapping("/add_music/{id}")
public UserDTO addMusic(@PathVariable Long id, @RequestParam Long music_id) {
return new UserDTO(userService.addMusic(id, music_id));
}
@PatchMapping("/add_community/{id}")
public UserDTO addCommunity(@PathVariable Long id, @RequestParam Long community_id) {
return new UserDTO(userService.addCommunity(id, community_id));
}
@GetMapping("/search")
public List<UserDTO> searchUsers(@RequestParam("city") String city) {
List<UserModel> users = userService.findUserByCity(city);
return users.stream().map(UserDTO::new).toList();
}
@DeleteMapping("/{id}")
public UserDTO deleteUser(@PathVariable Long id) {
return new UserDTO(userService.deleteUser(id));
}
} }

View File

@ -14,39 +14,61 @@ public class UserDTO {
public UserDTO(){} public UserDTO(){}
public UserDTO(UserModel user){ public UserDTO(UserModel user){
this.id = user.getId(); this.id = user.getId();
this.name = user.getName(); this.name = user.getName();
this.city = user.getCity(); this.city = user.getCity();
if(user.getMusics() != null) {
this.music = user.getMusics().stream().map(Music::getName).toList();
}
if(user.getGroups() != null) {
this.community = user.getGroups().stream().map(Community::getName).toList();
}
} }
private List<Music> musics; public UserDTO(Long id, String name) {
private List<Community> communities; this.id = id;
this.name = name;
}
private List<String> music;
private List<String> community;
public Long getId(){return id;} public Long getId(){return id;}
public String getName(){return name;} public String getName(){return name;}
public void setName(String firstName){this.name = firstName;} public void setName(String firstName){this.name = firstName;}
public void addMusic(Music g) { public List<String> getMusic() {
musics.add(g); return music;
}
public List<Music> getMusics() {
return musics;
} }
public void addCommunity(Community g) { public List<String> getCommunity() {
communities.add(g); return community;
} }
public List<Community> getGroups() {
return communities; public void setCommunities(List<String> communities) {
this.community = communities;
}
public void setMusics(List<String> musics) {
this.music = musics;
} }
public void setCity(String city){ public void setCity(String city){
this.city = city; this.city = city;
} }
public String getCity(){ public String getCity(){
return city; return city;
} }
public void setMusic(List<String> music) {
this.music = music;
}
public void setCommunity(List<String> community) {
this.community = community;
}
@Override @Override
public String toString() { public String toString() {
return "User{" + return "User{" +
@ -55,4 +77,5 @@ public class UserDTO {
", city='" + city + '\'' + ", city='" + city + '\'' +
'}'; '}';
} }
} }

View File

@ -3,6 +3,7 @@ import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption; import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*; import javax.persistence.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Entity @Entity
@ -35,6 +36,7 @@ public class UserModel {
} }
public UserModel(String name){ public UserModel(String name){
this.name = name; this.name = name;
this.city = "Mosscow";
} }
public UserModel(String name, String city){ public UserModel(String name, String city){
this.name = name; this.name = name;
@ -53,6 +55,7 @@ public class UserModel {
public void setName(String firstName){this.name = firstName;} public void setName(String firstName){this.name = firstName;}
public void addMusic(Music g) { public void addMusic(Music g) {
if(musics == null) musics = new ArrayList<>();
musics.add(g); musics.add(g);
} }
public List<Music> getMusics() { public List<Music> getMusics() {
@ -60,6 +63,7 @@ public class UserModel {
} }
public void addCommunity(Community g) { public void addCommunity(Community g) {
if(communities == null) communities = new ArrayList<>();
communities.add(g); communities.add(g);
} }
public List<Community> getGroups() { public List<Community> getGroups() {

View File

@ -3,5 +3,8 @@ package ru.ulstu.is.sbapp.socialNetwork.repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.socialNetwork.models.UserModel; import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import java.util.List;
public interface UserRepository extends JpaRepository<UserModel, Long> { public interface UserRepository extends JpaRepository<UserModel, Long> {
List<UserModel> findByCity(String city);
} }

View File

@ -40,10 +40,11 @@ public class CommunityService {
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Community> findAllCommunitys() { public List<Community> findAllCommunities() {
return repo.findAll(); return repo.findAll();
} }
@Transactional @Transactional
public Community updateCommunity(Long id, String name) { public Community updateCommunity(Long id, String name) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
@ -79,7 +80,7 @@ public class CommunityService {
} }
@Transactional @Transactional
public void deleteAllCommunitys() { public void deleteAllCommunities() {
repo.deleteAll(); repo.deleteAll();
} }

View File

@ -9,6 +9,7 @@ import ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.repository.UserRepository; import ru.ulstu.is.sbapp.socialNetwork.repository.UserRepository;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -34,12 +35,26 @@ public class UserService {
UserModel user = new UserModel(name, city); UserModel user = new UserModel(name, city);
return repo.save(user); return repo.save(user);
} }
@Transactional
public UserModel addUser(String name, String city, List<String> musics, List<String> communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Name is null or empty");
}
UserModel user = new UserModel(name, city);
UserModel result = repo.save(user);
updateMusics(result.getId(), musics);
return updateCommunities(user.getId(), communities);
}
@Transactional @Transactional
public UserModel addMusic(Long userId, Long musicId) { public UserModel addMusic(Long userId, Long musicId) {
final Optional<UserModel> userOpt= repo.findById(userId); final Optional<UserModel> userOpt= repo.findById(userId);
if (userOpt.isEmpty()) { if (userOpt.isEmpty()) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", musicId)); throw new EntityNotFoundException(String.format("User with id [%s] is not found", musicId));
} }
UserModel user = userOpt.get(); UserModel user = userOpt.get();
@ -83,11 +98,16 @@ public class UserService {
// @Transactional(readOnly = true) // @Transactional(readOnly = true)
// public List<UserModel> findUserByCity(String city){ // public List<UserModel> findUserByCity(String city){
// Query query = em.createQuery("select u from UserModel u where u.city = :city", // Query query = repo.createQuery("select u from UserModel u where u.city = :city",
// UserModel.class).setParameter("city", city); // UserModel.class).setParameter("city", city);
// List<UserModel> result = query.getResultList(); // List<UserModel> result = query.getResultList();
// return result; // return result;
// } // }
@Transactional(readOnly = true)
public List<UserModel> findUserByCity(String city){
List<UserModel> result = repo.findByCity(city);
return result;
}
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<UserModel> findAllUsers() { public List<UserModel> findAllUsers() {
@ -112,6 +132,26 @@ public class UserService {
return repo.save(currentUser); return repo.save(currentUser);
} }
//update community, musics //update community, musics
@Transactional
public UserModel updateUser(Long id, String name,String city, List<String> musics, List<String> Communities) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("User name is null or empty");
}
final Optional<UserModel> currentUserOpt = repo.findById(id);
if(currentUserOpt.isEmpty()) {
return null;
}
final UserModel currentUser = currentUserOpt.get();
currentUser.setName(name);
currentUser.setCity(city);
repo.save(currentUser);
updateMusics(id, musics);
return updateCommunities(id, Communities);
}
@Transactional @Transactional
public UserModel updateCommunities(Long userId , List<String> communities) { public UserModel updateCommunities(Long userId , List<String> communities) {

View File

@ -26,7 +26,7 @@ public class JpaCommunityTest {
@Test @Test
void testUserCreate() { void testUserCreate() {
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
final Community community = communityService.addCommunity("CodeGPT"); final Community community = communityService.addCommunity("CodeGPT");
log.info(community.toString()); log.info(community.toString());
Assertions.assertNotNull(community.getId()); Assertions.assertNotNull(community.getId());
@ -34,13 +34,13 @@ public class JpaCommunityTest {
@Test @Test
void testUserReadNotFound() { void testUserReadNotFound() {
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
Assertions.assertThrows(EntityNotFoundException.class, () -> communityService.findCommunity(-1L)); Assertions.assertThrows(EntityNotFoundException.class, () -> communityService.findCommunity(-1L));
} }
@Test @Test
void findUser() { void findUser() {
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
final Community community = communityService.addCommunity("CodeGPT"); final Community community = communityService.addCommunity("CodeGPT");
log.info(community.toString()); log.info(community.toString());
final Community findCommunity = communityService.findCommunity(community.getId()); final Community findCommunity = communityService.findCommunity(community.getId());
@ -50,18 +50,18 @@ public class JpaCommunityTest {
@Test @Test
void testReadAll() { void testReadAll() {
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
userService.deleteAllUsers(); userService.deleteAllUsers();
final Community community = communityService.addCommunity("CodeGPT"); final Community community = communityService.addCommunity("CodeGPT");
log.info(community.toString()); log.info(community.toString());
final List<Community> communitys = communityService.findAllCommunitys(); final List<Community> communities = communityService.findAllCommunities();
Assertions.assertEquals(communitys.size(), 1); Assertions.assertEquals(communities.size(), 1);
} }
@Test @Test
void updateCommunity() { void updateCommunity() {
userService.deleteAllUsers(); userService.deleteAllUsers();
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
final Community community = communityService.addCommunity("CodeGPT 2"); final Community community = communityService.addCommunity("CodeGPT 2");
communityService.updateCommunity(community.getId(), "CodeGPT 3"); communityService.updateCommunity(community.getId(), "CodeGPT 3");
final Community findCommunity = communityService.findCommunity(community.getId()); final Community findCommunity = communityService.findCommunity(community.getId());
@ -72,7 +72,7 @@ public class JpaCommunityTest {
@Test @Test
void deleteCommunity() { void deleteCommunity() {
userService.deleteAllUsers(); userService.deleteAllUsers();
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
final Community community = communityService.addCommunity("CodeGPT"); final Community community = communityService.addCommunity("CodeGPT");
log.info(community.toString()); log.info(community.toString());
communityService.deleteCommunity(community.getId()); communityService.deleteCommunity(community.getId());
@ -83,7 +83,7 @@ public class JpaCommunityTest {
@Test @Test
void addUser() { void addUser() {
userService.deleteAllUsers(); userService.deleteAllUsers();
communityService.deleteAllCommunitys(); communityService.deleteAllCommunities();
userService.findAllUsers(); userService.findAllUsers();
final Community community = communityService.addCommunity("CodeGPT"); final Community community = communityService.addCommunity("CodeGPT");
final UserModel user = userService.addUser("its_mailov", "Moscow"); final UserModel user = userService.addUser("its_mailov", "Moscow");