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 {
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 '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') {

Binary file not shown.

View File

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

View File

@ -2,6 +2,8 @@ package ru.ulstu.is.sbapp;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@ -10,4 +12,18 @@ public class WebConfiguration implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
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;
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.services.CommunityService;
@ -8,7 +9,7 @@ import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/communities")
@RequestMapping(WebConfiguration.REST_API + "/communities")
public class CommunityController {
private final CommunityService communityService;
@ -23,7 +24,7 @@ public class CommunityController {
@GetMapping("")
public List<CommunityDTO> getCommunities() {
return communityService.findAllCommunitys().stream().map(CommunityDTO::new).toList();
return communityService.findAllCommunities().stream().map(CommunityDTO::new).toList();
}
@PostMapping("")

View File

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

View File

@ -1,15 +1,18 @@
package ru.ulstu.is.sbapp.socialNetwork.controller;
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.models.UserModel;
import ru.ulstu.is.sbapp.socialNetwork.services.UserService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/users")
@RequestMapping(WebConfiguration.REST_API + "/users")
public class UserController {
private final UserService userService;
@ -27,6 +30,39 @@ public class UserController {
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(UserModel user){
this.id = user.getId();
this.name = user.getName();
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;
private List<Community> communities;
public UserDTO(Long id, String name) {
this.id = id;
this.name = name;
}
private List<String> music;
private List<String> community;
public Long getId(){return id;}
public String getName(){return name;}
public void setName(String firstName){this.name = firstName;}
public void addMusic(Music g) {
musics.add(g);
}
public List<Music> getMusics() {
return musics;
public List<String> getMusic() {
return music;
}
public void addCommunity(Community g) {
communities.add(g);
public List<String> getCommunity() {
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){
this.city = city;
}
public String getCity(){
return city;
}
public void setMusic(List<String> music) {
this.music = music;
}
public void setCommunity(List<String> community) {
this.community = community;
}
@Override
public String toString() {
return "User{" +
@ -55,4 +77,5 @@ public class UserDTO {
", city='" + city + '\'' +
'}';
}
}

View File

@ -3,6 +3,7 @@ import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@ -35,6 +36,7 @@ public class UserModel {
}
public UserModel(String name){
this.name = name;
this.city = "Mosscow";
}
public UserModel(String name, String city){
this.name = name;
@ -53,6 +55,7 @@ public class UserModel {
public void setName(String firstName){this.name = firstName;}
public void addMusic(Music g) {
if(musics == null) musics = new ArrayList<>();
musics.add(g);
}
public List<Music> getMusics() {
@ -60,6 +63,7 @@ public class UserModel {
}
public void addCommunity(Community g) {
if(communities == null) communities = new ArrayList<>();
communities.add(g);
}
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 ru.ulstu.is.sbapp.socialNetwork.models.UserModel;
import java.util.List;
public interface UserRepository extends JpaRepository<UserModel, Long> {
List<UserModel> findByCity(String city);
}

View File

@ -40,10 +40,11 @@ public class CommunityService {
}
@Transactional(readOnly = true)
public List<Community> findAllCommunitys() {
public List<Community> findAllCommunities() {
return repo.findAll();
}
@Transactional
public Community updateCommunity(Long id, String name) {
if (!StringUtils.hasText(name)) {
@ -79,7 +80,7 @@ public class CommunityService {
}
@Transactional
public void deleteAllCommunitys() {
public void deleteAllCommunities() {
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 javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import java.util.List;
import java.util.Optional;
@ -34,12 +35,26 @@ public class UserService {
UserModel user = new UserModel(name, city);
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
public UserModel addMusic(Long userId, Long musicId) {
final Optional<UserModel> userOpt= repo.findById(userId);
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();
@ -83,11 +98,16 @@ public class UserService {
// @Transactional(readOnly = true)
// 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);
// 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)
public List<UserModel> findAllUsers() {
@ -112,6 +132,26 @@ public class UserService {
return repo.save(currentUser);
}
//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
public UserModel updateCommunities(Long userId , List<String> communities) {

View File

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