Skip to content

Commit

Permalink
Merge pull request #27 from LuongXuanNhat/11.Post_Extension
Browse files Browse the repository at this point in the history
#28 | Update post table, add subId , fix some bug in post
  • Loading branch information
LuongXuanNhat authored Nov 16, 2023
2 parents 921203c + fd206a0 commit 99ab056
Show file tree
Hide file tree
Showing 33 changed files with 2,106 additions and 89 deletions.
16 changes: 5 additions & 11 deletions VNH.Application/Common/Contants/SystemConstants.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VNH.Application.Common.Contants
namespace VNH.Application.Common.Contants
{
public static class SystemConstants
{
public const string Token = "Token";
public const string BaseAddress = "BaseAddress";
public const string UrlWeb = "https://vuanhpham25-001-site1.gtempurl.com/";
//// public const string UrlWeb = "https://localhost:7138/";
public const string ConnectString = "Data Source=SQL5110.site4now.net;Initial Catalog=db_aa121e_vuanhpham25;User Id=db_aa121e_vuanhpham25_admin;Password=30102002Mai";
public const string ConnectStringDevelop = "Data Source=.;Initial Catalog=VietNamHistory_2;Integrated Security=True;Encrypt=true;TrustServerCertificate=true;";
// public const string UrlWeb = "https://vuanhpham25-001-site1.gtempurl.com/";
public const string UrlWeb = "https://localhost:7138/";
// public const string ConnectString = "Data Source=SQL5111.site4now.net;Initial Catalog=db_aa121e_vuanhpham25;User Id=db_aa121e_vuanhpham25_admin;Password=30102002Mai";
public const string ConnectString = "Data Source=.;Initial Catalog=VietNamHistory_2;Integrated Security=True;Encrypt=true;TrustServerCertificate=true;";
}
}
11 changes: 6 additions & 5 deletions VNH.Application/DTOs/Catalog/Posts/CreatePostDto.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
using Microsoft.AspNetCore.Http;
using System.ComponentModel.DataAnnotations;

namespace VNH.Application.DTOs.Catalog.Posts
{
public class CreatePostDto
{
public string Id { get; set; } = string.Empty;
public string Title { get; set; }
public string Content { get; set; }
public IFormFile Image { get; set; }
public string? Id { get; set; } = Guid.NewGuid().ToString();
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public IFormFile? Image { get; set; }
public Guid TopicId { get; set; }
public List<string> Tag { get; set; }
public List<string>? Tag { get; set; }
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@

namespace VNH.Application.DTOs.Catalog.Posts
{
public class PostResponsetDto
public class PostResponseDto
{
public string Id { get; set; } = string.Empty;
public string SubId { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Content { get; set; } = string.Empty;
public string Image { get; set; } = string.Empty;
Expand Down
2 changes: 1 addition & 1 deletion VNH.Application/DTOs/Catalog/Posts/ReportPostDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace VNH.Application.DTOs.Catalog.Posts
{
public class ReportPostDto
{
public string PostId { get; set; } = string.Empty;
public string PostId { get; set; }
public Guid UserId { get; set; }
public Guid ReportId { get; set; }
public string Description { get; set; } = string.Empty;
Expand Down
13 changes: 8 additions & 5 deletions VNH.Application/Interfaces/Catalog/Posts/IPostService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ namespace VNH.Application.Interfaces.Posts
{
public interface IPostService
{
Task<ApiResult<PostResponsetDto>> Create(CreatePostDto requestDto, string name);
Task<ApiResult<PostResponsetDto>> Update(CreatePostDto requestDto, string name);
Task<ApiResult<PostResponsetDto>> Detail(string Id);
Task<ApiResult<List<PostResponsetDto>>> GetAll();
Task<ApiResult<string>> Delete(string id);
Task<ApiResult<PostResponseDto>> Create(CreatePostDto requestDto, string name);
Task<ApiResult<PostResponseDto>> Update(CreatePostDto requestDto, string name);
Task<ApiResult<PostResponseDto>> Detail(string Id);
Task<ApiResult<List<PostResponseDto>>> GetAll();
Task<ApiResult<string>> Delete(string id, string email);
Task<ApiResult<string>> DeleteAdmin(string id);


Task<ApiResult<string>> AddOrUnLikePost(string id, string userId);
Task<ApiResult<string>> AddOrRemoveSavePost(string postId, string userId);
Task<ApiResult<string>> ReportPost(ReportPostDto reportPostDto);
Task<List<ReportPostDto>> GetReport();

}
}
2 changes: 1 addition & 1 deletion VNH.Application/Mappers/PostMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public PostMapper()
CreateMap<CreatePostDto, Post>()
.ForMember(dest => dest.Image, opt => opt.Ignore());

CreateMap<Post, PostResponsetDto>()
CreateMap<Post, PostResponseDto>()
.ForMember(dest => dest.Image, opt => opt.Ignore());

CreateMap<ReportPostDto, PostReportDetail>().ReverseMap();
Expand Down
1 change: 1 addition & 0 deletions VNH.Application/VNH.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="5.0.17" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
7 changes: 4 additions & 3 deletions VNH.Domain/Entities/Post.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@ public Post()
[Key]
[StringLength(255)]
public string Id { get; set; }
[Required]
[StringLength(300)]
public string SubId { get; set; } = string.Empty;
[StringLength(255)]
public string Title { get; set; }
public string Content { get; set; }
public Guid TopicId { get; set; }
[Column(TypeName = "datetime")]
public DateTime? CreatedAt { get; set; }
public DateTime CreatedAt { get; set; }
[Column(TypeName = "datetime")]
public DateTime? UpdatedAt { get; set; }
public Guid? UserId { get; set; }
public Guid UserId { get; set; }
public string Image { get; set; } = string.Empty;
public int ViewNumber { get; set; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ public async Task<ApiResult<string>> Register(RegisterRequest request)
{
Id = Guid.NewGuid(),
UserName = request.Email,
Fullname = request.Email,
Email = request.Email,
NumberConfirm = confirmNumber,
LockoutEnabled = false
Expand Down
113 changes: 74 additions & 39 deletions VNH.Infrastructure/Implement/Catalog/Posts/PostService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using VNH.Application.DTOs.Catalog.HashTags;
using VNH.Application.DTOs.Catalog.Posts;
using VNH.Application.DTOs.Catalog.Users;
Expand Down Expand Up @@ -34,39 +36,42 @@ public PostService(UserManager<User> userManager, IMapper mapper, IImageService
_dataContext = vietNamHistoryContext;
_storageService = storageService;
}
public async Task<ApiResult<PostResponsetDto>> Create(CreatePostDto requestDto, string name)
public async Task<ApiResult<PostResponseDto>> Create(CreatePostDto requestDto, string name)
{
var user = await _userManager.FindByEmailAsync(name);
var post = _mapper.Map<Post>(requestDto);
post.Image = await _image.SaveFile(requestDto.Image);
post.CreatedAt = DateTime.Now;
post.UserId = user.Id;
post.TopicId = requestDto.TopicId;
var Id = RemoveDiacritics(post.Title);
post.Id = Id.Trim().Replace(" ","-") + "-" + Guid.NewGuid().ToString();
string formattedDateTime = post.CreatedAt.ToString("HH:mm:ss.fff-dd-MM-yyyy");
var Id = SanitizeString(post.Title);
post.SubId = Id + "-" + formattedDateTime;
try
{
_dataContext.Posts.Add(post);
await _dataContext.SaveChangesAsync();

foreach (var item in requestDto.Tag)
if (!requestDto.Tag.IsNullOrEmpty())
{
var tag = new Tag()
{
Id = Guid.NewGuid(),
Name = item
};
var postTag = new PostTag()
foreach (var item in requestDto.Tag)
{
PostId = post.Id,
TagId = tag.Id
};
_dataContext.PostTags.Add(postTag);
_dataContext.Tags.Add(tag);
var tag = new Tag()
{
Id = Guid.NewGuid(),
Name = item
};
var postTag = new PostTag()
{
PostId = post.Id,
TagId = tag.Id
};
_dataContext.PostTags.Add(postTag);
_dataContext.Tags.Add(tag);
}
await _dataContext.SaveChangesAsync();
}
await _dataContext.SaveChangesAsync();

var postReponse = _mapper.Map<PostResponsetDto>(post);
var postReponse = _mapper.Map<PostResponseDto>(post);

postReponse.Image = post.Image;
var useDto = new UserShortDto()
Expand All @@ -93,11 +98,11 @@ public async Task<ApiResult<PostResponsetDto>> Create(CreatePostDto requestDto,
var topic = await _dataContext.Topics.FirstAsync(x => x.Id == post.TopicId);
postReponse.TopicName = topic.Title;

return new ApiSuccessResult<PostResponsetDto>(postReponse);
return new ApiSuccessResult<PostResponseDto>(postReponse);
}
catch (Exception ex)
{
return new ApiErrorResult<PostResponsetDto>("Lỗi lưu bài viết : " + ex.Message);
return new ApiErrorResult<PostResponseDto>("Lỗi lưu bài viết : " + ex.Message);
}
}

Expand All @@ -116,15 +121,22 @@ private static string RemoveDiacritics(string input)

return stringBuilder.ToString().Normalize(NormalizationForm.FormC);
}
private static string SanitizeString(string input)
{
string withoutDiacritics = RemoveDiacritics(input).Trim().Replace(" ", "-");
string sanitizedString = Regex.Replace(withoutDiacritics, "[^a-zA-Z0-9-]", "");

return sanitizedString;
}

public async Task<ApiResult<PostResponsetDto>> Update(CreatePostDto requestDto, string name)
public async Task<ApiResult<PostResponseDto>> Update(CreatePostDto requestDto, string name)
{
var user = await _userManager.FindByEmailAsync(name);

var updatePost = _dataContext.Posts.First(x=>x.Id.Equals(requestDto.Id));
if (updatePost is null)
{
return new ApiErrorResult<PostResponsetDto>("Lỗi :Bài viết không được cập nhập (không tìm thấy bài viết)");
return new ApiErrorResult<PostResponseDto>("Lỗi :Bài viết không được cập nhập (không tìm thấy bài viết)");
}
if (updatePost.Image != string.Empty)
{
Expand All @@ -134,15 +146,16 @@ public async Task<ApiResult<PostResponsetDto>> Update(CreatePostDto requestDto,
updatePost.UpdatedAt = DateTime.Now;
updatePost.TopicId = requestDto.TopicId;
updatePost.Content = requestDto.Content;

string formattedDateTime = DateTime.Now.ToString("HH:mm:ss.fff-dd-MM-yyyy");
var Id = SanitizeString(updatePost.Title);
updatePost.SubId = Id.Trim().Replace(" ", "-") + "-" + formattedDateTime;
try
{
_dataContext.Posts.Update(updatePost);
await _dataContext.SaveChangesAsync();

var tagOfPost = await _dataContext.PostTags.Where(x => x.PostId.Equals(updatePost.Id)).ToListAsync();
_dataContext.PostTags.RemoveRange(tagOfPost);
await _dataContext.SaveChangesAsync();

foreach (var item in requestDto.Tag)
{
Expand All @@ -161,7 +174,7 @@ public async Task<ApiResult<PostResponsetDto>> Update(CreatePostDto requestDto,
}
await _dataContext.SaveChangesAsync();

var postReponse = _mapper.Map<PostResponsetDto>(updatePost);
var postReponse = _mapper.Map<PostResponseDto>(updatePost);

postReponse.Image = updatePost.Image;
var useDto = new UserShortDto()
Expand All @@ -188,23 +201,23 @@ public async Task<ApiResult<PostResponsetDto>> Update(CreatePostDto requestDto,
var topic = await _dataContext.Topics.FirstAsync(x => x.Id == updatePost.TopicId);
postReponse.TopicName = topic.Title;

return new ApiSuccessResult<PostResponsetDto>(postReponse);
return new ApiSuccessResult<PostResponseDto>(postReponse);
}
catch (Exception ex)
{
return new ApiErrorResult<PostResponsetDto>("Lỗi lưu bài viết : " + ex.Message);
return new ApiErrorResult<PostResponseDto>("Lỗi lưu bài viết : " + ex.Message);
}
}

public async Task<ApiResult<PostResponsetDto>> Detail(string Id)
public async Task<ApiResult<PostResponseDto>> Detail(string Id)
{
var post = await _dataContext.Posts.FirstOrDefaultAsync(x=>x.Id.Equals(Id));
var post = await _dataContext.Posts.FirstOrDefaultAsync(x=>x.SubId.Equals(Id));
if (post is null)
{
return new ApiErrorResult<PostResponsetDto>("Không tìm thấy bài viết");
return new ApiErrorResult<PostResponseDto>("Không tìm thấy bài viết");
}
var user = await _userManager.FindByIdAsync(post.UserId.ToString());
var postResponse = _mapper.Map<PostResponsetDto>(post);
var postResponse = _mapper.Map<PostResponseDto>(post);
postResponse.Image = post.Image;

var listPostTag = await _dataContext.PostTags.Where(x => x.PostId.Equals(postResponse.Id)).Select(x => x.TagId).ToListAsync();
Expand All @@ -225,27 +238,29 @@ public async Task<ApiResult<PostResponsetDto>> Detail(string Id)
Id = user.Id,
Image = user.Image
};

var topic = await _dataContext.Topics.FirstAsync(x => x.Id == post.TopicId);
postResponse.TopicName = topic.Title;

postResponse.ViewNumber = post.ViewNumber += 1;
postResponse.SaveNumber = await _dataContext.PostSaves.Where(x=>x.PostId.Equals(Id)).CountAsync();
postResponse.CommentNumber = await _dataContext.PostComments.Where(x => x.PostId.Equals(Id)).CountAsync();
postResponse.LikeNumber = await _dataContext.PostLikes.Where(x=>x.PostId.Equals(x.PostId)).CountAsync();

return new ApiSuccessResult<PostResponsetDto>(postResponse);
_dataContext.Posts.Update(post);
await _dataContext.SaveChangesAsync();
return new ApiSuccessResult<PostResponseDto>(postResponse);
}

public async Task<ApiResult<List<PostResponsetDto>>> GetAll()
public async Task<ApiResult<List<PostResponseDto>>> GetAll()
{
var posts = await _dataContext.Posts.ToListAsync();
var topics = await _dataContext.Topics.ToListAsync();
var users = await _dataContext.User.ToListAsync();

var result = new List<PostResponsetDto>();
var result = new List<PostResponseDto>();
foreach (var item in posts)
{
var post = _mapper.Map<PostResponsetDto>(item);
var post = _mapper.Map<PostResponseDto>(item);
var userShort = users.First(x => x.Id == item.UserId);
if (userShort is not null)
{
Expand All @@ -270,10 +285,28 @@ public async Task<ApiResult<List<PostResponsetDto>>> GetAll()
result.Add(post);
}

return new ApiSuccessResult<List<PostResponsetDto>>(result);
return new ApiSuccessResult<List<PostResponseDto>>(result);
}

public async Task<ApiResult<string>> Delete(string id)
public async Task<ApiResult<string>> Delete(string id, string userId)
{
var post = await _dataContext.Posts.FirstOrDefaultAsync(x => x.Id.Equals(id) && x.UserId.ToString().Equals(userId));
if (post is null)
{
return new ApiErrorResult<string>("Không tìm thấy bài viết");
}
if (post.Image != string.Empty)
{
await _storageService.DeleteFileAsync(post.Image);
}
_dataContext.Posts.Remove(post);

await _dataContext.SaveChangesAsync();

return new ApiSuccessResult<string>("Đã xóa bài viết");
}

public async Task<ApiResult<string>> DeleteAdmin(string id)
{
var post = await _dataContext.Posts.FirstOrDefaultAsync(x => x.Id.Equals(id));
if (post is null)
Expand Down Expand Up @@ -375,5 +408,7 @@ public async Task<List<ReportPostDto>> GetReport()
}
return results;
}


}
}
5 changes: 0 additions & 5 deletions VNH.Infrastructure/Implement/Common/StorageService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VNH.Application.Interfaces.Common;

namespace VNH.Infrastructure.Implement.Common
Expand Down
Loading

0 comments on commit 99ab056

Please sign in to comment.