add version 0.0.0.2

complete seed and product category controllers , coplete core commands , config for production
release
Amir Hossein Khademi 2024-01-13 13:05:37 +03:30
parent f4fa5e5e1b
commit 7c28710f12
68 changed files with 12032 additions and 678 deletions

View File

@ -1 +1 @@
0.0.0.1
0.0.0.2

View File

@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"Postgres": "Host=pg-0;port=5432;Username=postgres;Password=ub0J7sFFThkSBmkc0TzSKsCfheRnQpyu;Database=NetinaShopDB"
"PostgresServer": "User ID=postgres;Password=root;Host=localhost;Port=5432;Database=iGarsonDB;",
"Postgres": "Host=pg-0;Username=visabarterAgent;Password=xHTpBf4wC+bPEUpqxwPFfOc2YYTVwFQuHfsiqoVeT9+6;Database=NetinaShopDB;Application Name=NetinaShopApi"
},
"Logging": {
"LogLevel": {
@ -11,8 +12,11 @@
"Microsoft.AspNetCore.Http.Connections": "Debug"
}
},
"ShopSettings": {
"TaxesFee": 9
},
"SiteSettings": {
"BaseUrl": "https://api.brizco.io",
"BaseUrl": "https://api.vesmeh.visabartar.ir",
"KaveNegarApiKey": "3735494B4143727A794346457461576A2B4B6668414973424E333561505A694B",
"UserSetting": {
"Username": "netinashop",
@ -25,8 +29,8 @@
},
"JwtSettings": {
"SecretKey": "YAEMAMZAMAN_KHODET_NEGAHDAR_IN_KEY_BASH_nw+8E0EABj0Wg8c4mHg/bDBf5qGMhmBPb6u16DVe9/MzYva1e+/J1zImyIoQX2Lmra2kvzsIjGiwP7r3Znd_YA_JADE_NASABE_v+Ro/CDixScDv6EkpZnkBv9MFdPnSmFXNGMH9gA1BzQUoC1iSX9Aq+pMIw/cMKXI9WA==_YA_HUSEIN_SEYED_SHOHADA_BE_OMID_KHODET",
"Issuer": "NetinaShop",
"Audience": "NetinaShop",
"Issuer": "Brizco",
"Audience": "Brizco",
"ExpireAddDay": "15"
}
},

View File

@ -16,7 +16,7 @@
"TaxesFee": 9
},
"SiteSettings": {
"BaseUrl": "http://localhost:32770",
"BaseUrl": "http://192.168.88.12:32770",
"KaveNegarApiKey": "3735494B4143727A794346457461576A2B4B6668414973424E333561505A694B",
"UserSetting": {
"Username": "netinashop",

View File

@ -8,8 +8,7 @@ public class BlogCategoryController : ICarterModule
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi("BlogCategory")
.MapGroup($"api/blog/category")
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());
.MapGroup($"api/blog/category");
group.MapGet("", GetAllAsync)
.WithDisplayName("GetAllCategories")
@ -20,12 +19,15 @@ public class BlogCategoryController : ICarterModule
.HasApiVersion(1.0);
group.MapPost("", Post)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapPut("", Put)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapDelete("{id}", Delete)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
}

View File

@ -8,8 +8,7 @@ public class BlogController : ICarterModule
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi("Blog")
.MapGroup($"api/blog")
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());
.MapGroup($"api/blog");
group.MapGet("", GetAllAsync)
.WithDisplayName("GetAllBlogs")
@ -20,12 +19,15 @@ public class BlogController : ICarterModule
.HasApiVersion(1.0);
group.MapPost("", Post)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapPut("", Put)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapDelete("{id}", Delete)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
}

View File

@ -44,41 +44,14 @@ public class BrandController : ICarterModule
.FirstOrDefaultAsync(cancellationToken));
// POST:Create Entity
public async Task<IResult> Post([FromBody] BrandLDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
{
var ent = Brand.Create(dto.Name, dto.Description, dto.HasSpecialPage, dto.PageUrl);
foreach (var file in dto.Files)
{
ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
}
repositoryWrapper.SetRepository<Brand>().Add(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return TypedResults.Ok();
}
public async Task<IResult> Post([FromBody] CreateBrandCommand request, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(request, cancellationToken));
// PUT:Update Entity
public async Task<IResult> Put([FromBody] BrandLDto dto, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
{
var ent = await repositoryWrapper.SetRepository<Brand>().TableNoTracking
.FirstOrDefaultAsync(b => b.Id == dto.Id, cancellationToken);
if (ent == null)
throw new AppException("Brand not found");
var newEnt = Brand.Create(dto.Name, dto.Description, dto.HasSpecialPage, dto.PageUrl);
newEnt.Id = ent.Id;
repositoryWrapper.SetRepository<Brand>().Update(newEnt);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return TypedResults.Ok();
}
public async Task<IResult> Put([FromBody] UpdateBrandCommand request, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(request, cancellationToken));
// DELETE:Delete Entity
public async Task<IResult> Delete(Guid id, IRepositoryWrapper repositoryWrapper, CancellationToken cancellationToken)
{
var ent = await repositoryWrapper.SetRepository<Brand>().TableNoTracking
.FirstOrDefaultAsync(b => b.Id == id, cancellationToken);
if (ent == null)
throw new AppException("Brand not found");
repositoryWrapper.SetRepository<Brand>().Delete(ent);
await repositoryWrapper.SaveChangesAsync(cancellationToken);
return TypedResults.Ok();
}
public async Task<IResult> Delete(Guid id, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(new DeleteBrandCommand(id), cancellationToken));
}

View File

@ -6,8 +6,7 @@ public class ProductCategoryController : ICarterModule
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi("ProductCategory")
.MapGroup($"api/product/category")
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());
.MapGroup($"api/product/category");
group.MapGet("", GetAllAsync)
.WithDisplayName("GetAllCategories")
@ -18,32 +17,35 @@ public class ProductCategoryController : ICarterModule
.HasApiVersion(1.0);
group.MapPost("", Post)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapPut("", Put)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapDelete("{id}", Delete)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
}
// GET:Get All Entity
public async Task<IResult> GetAllAsync([FromQuery] int page, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(new GetCategoriesQuery(page),cancellationToken));
public async Task<IResult> GetAllAsync(IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(new GetProductCategoriesQuery(),cancellationToken));
// GET:Get An Entity By Id
public async Task<IResult> GetAsync(Guid id, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(new GetCategoryQuery(id),cancellationToken));
=> TypedResults.Ok(await mediator.Send(new GetProductCategoryQuery(id),cancellationToken));
// POST:Create Entity
public async Task<IResult> Post([FromBody] CreateCategoryCommand request, IMediator mediator, CancellationToken cancellationToken)
public async Task<IResult> Post([FromBody] ProductCreateCategoryCommand request, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(request, cancellationToken));
// PUT:Update Entity
public async Task<IResult> Put([FromBody] UpdateCategoryCommand request, IMediator mediator, CancellationToken cancellationToken)
public async Task<IResult> Put([FromBody] ProductUpdateCategoryCommand request, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(request, cancellationToken));
// DELETE:Delete Entity
public async Task<IResult> Delete(Guid id, IMediator mediator, CancellationToken cancellationToken)
=> TypedResults.Ok(await mediator.Send(new DeleteCategoryCommand(id), cancellationToken));
=> TypedResults.Ok(await mediator.Send(new ProductDeleteCategoryCommand(id), cancellationToken));
}

View File

@ -8,8 +8,7 @@ public class ProductController : ICarterModule
public virtual void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi("Product")
.MapGroup($"api/product")
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());
.MapGroup($"api/product");
group.MapGet("", GetAllAsync)
.WithDisplayName("GetAllProducts")
@ -20,12 +19,15 @@ public class ProductController : ICarterModule
.HasApiVersion(1.0);
group.MapPost("", Post)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapPut("", Put)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
group.MapDelete("{id}", Delete)
.RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
.HasApiVersion(1.0);
}

View File

@ -0,0 +1,76 @@
using NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
namespace NetinaShop.Api.Controller;
public class SeedController : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
var group = app.NewVersionedApi("Seed")
.MapGroup("api/seed");
group.MapPost("categories", SeedCategoriesAsync)
.WithDisplayName("SeedCategoriesAsync")
.HasApiVersion(1.0);
group.MapPost("brands", SeedBrandsAsync)
.WithDisplayName("SeedBrandsAsync")
.HasApiVersion(1.0);
group.MapPost("products",SeedProductsAsync)
.WithDisplayName("SeedProductsAsync")
.HasApiVersion(1.0);
}
public async Task<IResult> SeedProductsAsync([FromBody] List<CreateProductCommand> request, [FromQuery] string key, IMediator mediator, CancellationToken cancellationToken)
{
if (key != "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==")
throw new AppException("Key is not valid", ApiResultStatusCode.UnAuthorized);
foreach (var requestDto in request)
{
await mediator.Send(requestDto, cancellationToken);
}
return TypedResults.Ok();
}
public async Task<IResult> SeedCategoriesAsync([FromBody] List<SeedCategoryRequestDto> request, [FromQuery] string key, IMediator mediator,CancellationToken cancellationToken)
{
if (key != "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==")
throw new AppException("Key is not valid", ApiResultStatusCode.UnAuthorized);
Dictionary<int,Guid> categories = new Dictionary<int, Guid>();
var baseCat = await mediator.Send(new ProductCreateCategoryCommand("دسته بندی نشده", "محصولات دسته بندی نشده", default,
new List<StorageFileSDto>()));
categories.Add(0,baseCat.Id);
foreach (var requestDto in request)
{
var lDto = await mediator.Send(new ProductCreateCategoryCommand(requestDto.Name,requestDto.Description,default,new List<StorageFileSDto>()), cancellationToken);
categories.Add(requestDto.BaseCategoryId,lDto.Id);
}
return TypedResults.Ok(categories);
}
public async Task<IResult> SeedBrandsAsync([FromBody] List<SeedBrandRequestDto> request, [FromQuery] string key, IMediator mediator, CancellationToken cancellationToken)
{
if (key != "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==")
throw new AppException("Key is not valid", ApiResultStatusCode.UnAuthorized);
Dictionary<int, Guid> brands = new Dictionary<int, Guid>();
var baseBrand = await mediator.Send(new CreateBrandCommand("بدون برند", "محصولات بدون برند", false,string.Empty,
new List<StorageFileSDto>()));
brands.Add(0, baseBrand.Id);
foreach (var requestDto in request)
{
var sDto = await mediator.Send(new CreateBrandCommand(requestDto.Name, requestDto.Description, false,
string.Empty, new List<StorageFileSDto>()));
brands.Add(requestDto.BaseBrandId,sDto.Id);
}
return TypedResults.Ok(brands);
}
}

View File

@ -6,6 +6,8 @@
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<AssemblyVersion>0.0.0.2</AssemblyVersion>
<FileVersion>0.0.0.2</FileVersion>
</PropertyGroup>
<ItemGroup>
@ -80,8 +82,8 @@
<Using Include="NetinaShop.Domain.Dtos.LargDtos" />
<Using Include="NetinaShop.Domain.Dtos.RequestDtos" />
<Using Include="NetinaShop.Domain.Dtos.SmallDtos" />
<Using Include="NetinaShop.Domain.Entities.Categories" />
<Using Include="NetinaShop.Domain.Entities.Discounts" />
<Using Include="NetinaShop.Domain.Entities.ProductCategories" />
<Using Include="NetinaShop.Domain.Entities.Users" />
<Using Include="NetinaShop.Domain.Mappers" />
<Using Include="NetinaShop.Domain.Models.Settings" />

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -12,31 +12,70 @@ public class CalculateDiscountCommandHandler : IRequestHandler<CalculateDiscount
{
if (request.Order == null)
throw new AppException("Order is null", ApiResultStatusCode.BadRequest);
var discount = await _repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
if (discount == null)
throw new AppException("Discount not found", ApiResultStatusCode.NotFound);
double discountPrice = 0;
foreach (var orderProductGrouped in request.Order.OrderProducts.GroupBy(o=>o.ProductCategoryId))
{
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.CategoryId == orderProductGrouped.Key && d.HasCode == false && d.ExpireDate.Date > DateTime.Today.Date , cancellationToken);
if (categoryDiscount != null && !categoryDiscount.IsExpired())
{
var totalPrice = request.Order.OrderProducts.Where(op => op.ProductCategoryId == categoryDiscount.CategoryId)
.Sum(op => op.ProductCost);
discountPrice = categoryDiscount.AmountType == DiscountAmountType.Amount
? totalPrice - categoryDiscount.DiscountAmount
: totalPrice - ((totalPrice / 100) * categoryDiscount.DiscountAmount);
}
foreach (var orderProduct in orderProductGrouped)
{
var productDiscount = await _repositoryWrapper.SetRepository<ProductDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.HasCode == false && d.ProductId == orderProduct.ProductId && d.ExpireDate.Date > DateTime.Today.Date, cancellationToken);
if (productDiscount != null && !productDiscount.IsExpired())
{
var totalPrice = request.Order.OrderProducts.Where(op => op.ProductId == productDiscount.ProductId).Sum(op => op.ProductCost);
discountPrice = productDiscount.AmountType == DiscountAmountType.Amount
? totalPrice - productDiscount.DiscountAmount
: totalPrice - ((totalPrice / 100) * productDiscount.DiscountAmount);
}
}
}
if (discount.Type == DiscountType.All)
{
var totalPrice = request.Order.OrderProducts.Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
if (!discount.IsExpired())
{
var totalPrice = request.Order.OrderProducts.Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
}
}
else if (discount.Type == DiscountType.Category)
{
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
var totalPrice = request.Order.OrderProducts.Where(op=>op.ProductCategoryId == categoryDiscount!.CategoryId).Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
if ( categoryDiscount!=null && !categoryDiscount.IsExpired())
{
var totalPrice = request.Order.OrderProducts.Where(op => op.ProductCategoryId == categoryDiscount.CategoryId).Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
}
}
else if (discount.Type == DiscountType.Product)
{
@ -44,10 +83,13 @@ public class CalculateDiscountCommandHandler : IRequestHandler<CalculateDiscount
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
var totalPrice = request.Order.OrderProducts.Where(op => op.ProductId == productDiscount!.ProductId).Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
if (productDiscount != null && !productDiscount.IsExpired())
{
var totalPrice = request.Order.OrderProducts.Where(op => op.ProductId == productDiscount!.ProductId).Sum(op => op.ProductCost);
discountPrice = discount.AmountType == DiscountAmountType.Amount
? totalPrice - discount.DiscountAmount
: totalPrice - ((totalPrice / 100) * discount.DiscountAmount);
}
}
else if (discount.Type == DiscountType.Subscriber)
{

View File

@ -17,6 +17,11 @@ public class SubmitDiscountCommandHandler : IRequestHandler<SubmitDiscountComman
.FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
if (order == null)
throw new AppException("Order not found", ApiResultStatusCode.NotFound);
var discount = await _repositoryWrapper.SetRepository<Discount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.Code == request.DiscountCode, cancellationToken);
if (discount == null || discount.IsExpired())
throw new AppException("Discount is expired or not found", ApiResultStatusCode.NotFound);
order.SetDiscount(request.DiscountCode);
_repositoryWrapper.SetRepository<Order>().Update(order);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);

View File

@ -0,0 +1,8 @@
namespace NetinaShop.Domain.CommandQueries.Commands;
public sealed record CreateBrandCommand(string Name,string Description , bool HasSpecialPage , string PageUrl, List<StorageFileSDto> Files) : IRequest<BrandSDto>;
public sealed record UpdateBrandCommand(Guid Id, string Name, string Description, bool HasSpecialPage, string PageUrl, List<StorageFileSDto> Files) : IRequest<bool>;
public sealed record DeleteBrandCommand(Guid Id) : IRequest<bool>;

View File

@ -1,16 +0,0 @@
namespace NetinaShop.Domain.CommandQueries.Commands;
public sealed record CreateCategoryCommand(
string Name,
string Description,
Guid ParentId,
List<StorageFileSDto> Files) : IRequest<CategoryLDto>;
public sealed record UpdateCategoryCommand(
Guid Id,
string Name,
string Description,
Guid ParentId,
List<StorageFileSDto> Files) : IRequest<bool>;
public sealed record DeleteCategoryCommand(Guid Id) : IRequest<bool>;

View File

@ -0,0 +1,16 @@
namespace NetinaShop.Domain.CommandQueries.Commands;
public sealed record ProductCreateCategoryCommand(
string Name,
string Description,
Guid ParentId,
List<StorageFileSDto> Files) : IRequest<ProductCategoryLDto>;
public sealed record ProductUpdateCategoryCommand(
Guid Id,
string Name,
string Description,
Guid ParentId,
List<StorageFileSDto> Files) : IRequest<bool>;
public sealed record ProductDeleteCategoryCommand(Guid Id) : IRequest<bool>;

View File

@ -1,4 +0,0 @@
namespace NetinaShop.Domain.CommandQueries.Queries;
public record GetCategoryQuery(Guid Id) : IRequest<CategoryLDto>;
public record GetCategoriesQuery(int Page = 0) : IRequest<List<CategorySDto>>;

View File

@ -0,0 +1,4 @@
namespace NetinaShop.Domain.CommandQueries.Queries;
public record GetProductCategoryQuery(Guid Id) : IRequest<ProductCategoryLDto>;
public record GetProductCategoriesQuery() : IRequest<List<ProductCategorySDto>>;

View File

@ -1,10 +0,0 @@
namespace NetinaShop.Domain.Dtos.LargDtos;
public class CategoryLDto : BaseDto<CategoryLDto, Category>
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public Guid ParentId { get; set; }
public List<CategorySDto> Children { get; set; } = new();
public List<StorageFileSDto> Files { get; internal set; } = new();
}

View File

@ -0,0 +1,12 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Domain.Dtos.LargDtos;
public class ProductCategoryLDto : BaseDto<ProductCategoryLDto, ProductCategory>
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public Guid ParentId { get; set; }
public List<ProductCategorySDto> Children { get; set; } = new();
public List<StorageFileSDto> Files { get; internal set; } = new();
}

View File

@ -13,6 +13,6 @@ public class ProductLDto : BaseDto<ProductLDto,Product>
public List<SpecificationSDto> Specifications { get; set; } = new();
public List<ReviewSDto> Reviews { get; set; } = new();
public List<CategorySDto> Categories { get; set; } = new();
public List<ProductCategorySDto> Categories { get; set; } = new();
public List<StorageFileSDto> Files { get; set; } = new();
}

View File

@ -0,0 +1,8 @@
namespace NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
public class SeedBrandRequestDto
{
public int BaseBrandId { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}

View File

@ -0,0 +1,10 @@
using NetinaShop.Domain.CommandQueries.Commands;
namespace NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
public class SeedCategoryRequestDto
{
public int BaseCategoryId { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}

View File

@ -1,8 +0,0 @@
namespace NetinaShop.Domain.Dtos.SmallDtos;
public class CategorySDto : BaseDto<CategorySDto , Category>
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public Guid ParentId { get; set; }
}

View File

@ -0,0 +1,13 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Domain.Dtos.SmallDtos;
public class ProductCategorySDto : BaseDto<ProductCategorySDto , ProductCategory>
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsMain { get; set; }
public Guid ParentId { get; set; }
public List<ProductCategorySDto> Children { get; set; } = new();
}

View File

@ -9,6 +9,18 @@ public class ProductSDto : BaseDto<ProductSDto, Product>
public string ExpertCheck { get; set; } = string.Empty;
public string Tags { get; set; } = string.Empty;
public string Warranty { get; set; } = string.Empty;
public double Cost { get; set; }
public double DiscountPercent { get; set; }
public bool HasDiscount { get; set; }
public double CostWithDiscount { get; set; }
public bool IsEnable { get; set; }
public bool BeDisplayed { get; set; }
public double PackingCost { get; set; }
public float Rate { get; set; }
public int ReviewCount { get; set; }
public int Viewed { get; set; }
public Guid CategoryId { get; internal set; }
public Guid BrandId { get; set; }
public string BrandNames { get; set; } = string.Empty;
}

View File

@ -1,29 +0,0 @@
namespace NetinaShop.Domain.Entities.Categories;
public partial class Category
{
public static Category Create(string name, string description)
{
return new Category(name, description);
}
public void SetParent(Guid parentId)
{
ParentId = parentId;
}
public CategoryStorageFile AddFile(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType)
{
var file = CategoryStorageFile.Create(name, fileLocation, fileName, isHeader, isPrimary, fileType, this.Id);
Files.Add(file);
return file;
}
}
public partial class CategoryStorageFile
{
public static CategoryStorageFile Create(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType, Guid categoryId)
{
return new CategoryStorageFile(name, fileLocation, fileName, isHeader, isPrimary, fileType, categoryId);
}
}

View File

@ -1,17 +0,0 @@
namespace NetinaShop.Domain.Entities.Categories;
public partial class CategoryStorageFile : StorageFile
{
public CategoryStorageFile()
{
}
public CategoryStorageFile(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType, Guid categoryId) :
base(name, fileLocation, fileName, isHeader, isPrimary, fileType)
{
CategoryId = categoryId;
}
public Guid CategoryId { get; internal set; }
public Category? Category { get; internal set; }
}

View File

@ -1,4 +1,6 @@
namespace NetinaShop.Domain.Entities.Discounts;
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Domain.Entities.Discounts;
public partial class CategoryDiscount : Discount
{
@ -14,5 +16,5 @@ public partial class CategoryDiscount : Discount
CategoryId = categoryId;
}
public Guid CategoryId { get; internal set; }
public Category? Category { get; internal set; }
public ProductCategory? Category { get; internal set; }
}

View File

@ -8,6 +8,9 @@ public partial class Discount
expireDate, priceFloor, hasPriceFloor, priceCeiling, hasPriceCeiling, isInfinity, useCount,
isForInvitation);
}
public bool IsExpired()
=> ExpireDate.Date < DateTime.Today.Date;
}
public partial class ProductDiscount

View File

@ -0,0 +1,29 @@
namespace NetinaShop.Domain.Entities.ProductCategories;
public partial class ProductCategory
{
public static ProductCategory Create(string name, string description)
{
return new ProductCategory(name, description);
}
public void SetParent(Guid parentId)
{
ParentId = parentId;
}
public ProductCategoryStorageFile AddFile(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType)
{
var file = ProductCategoryStorageFile.Create(name, fileLocation, fileName, isHeader, isPrimary, fileType, this.Id);
Files.Add(file);
return file;
}
}
public partial class ProductCategoryStorageFile
{
public static ProductCategoryStorageFile Create(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType, Guid categoryId)
{
return new ProductCategoryStorageFile(name, fileLocation, fileName, isHeader, isPrimary, fileType, categoryId);
}
}

View File

@ -1,27 +1,28 @@
namespace NetinaShop.Domain.Entities.Categories;
namespace NetinaShop.Domain.Entities.ProductCategories;
[AdaptTwoWays("[name]LDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget | MapType.Projection)]
[AdaptTwoWays("[name]SDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget)]
[AdaptTo("[name]SDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Projection)]
[GenerateMapper]
public partial class Category : ApiEntity
public partial class ProductCategory : ApiEntity
{
public Category()
public ProductCategory()
{
}
public Category(string name, string description)
public ProductCategory(string name, string description)
{
Name = name;
Description = description;
}
public string Name { get; internal set; } = string.Empty;
public string Description { get; internal set; } = string.Empty;
public bool IsMain { get; set; }
public Guid ParentId { get; internal set; }
public Category? Parent { get; internal set; }
public Guid? ParentId { get; internal set; }
public ProductCategory? Parent { get; internal set; }
public List<Category> Children { get; internal set; } = new();
//public List<ProductCategory> Children { get; internal set; } = new();
public List<Product> Products { get; internal set; } = new();
public List<CategoryStorageFile> Files { get; internal set; } = new();
public List<ProductCategoryStorageFile> Files { get; internal set; } = new();
}

View File

@ -0,0 +1,17 @@
namespace NetinaShop.Domain.Entities.ProductCategories;
public partial class ProductCategoryStorageFile : StorageFile
{
public ProductCategoryStorageFile()
{
}
public ProductCategoryStorageFile(string name, string fileLocation, string fileName, bool isHeader, bool isPrimary, StorageFileType fileType, Guid categoryId) :
base(name, fileLocation, fileName, isHeader, isPrimary, fileType)
{
CategoryId = categoryId;
}
public Guid CategoryId { get; internal set; }
public ProductCategory? Category { get; internal set; }
}

View File

@ -1,4 +1,6 @@
namespace NetinaShop.Domain.Entities.Products;
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Domain.Entities.Products;
[AdaptTwoWays("[name]LDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget | MapType.Projection)]
[AdaptTwoWays("[name]SDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Map | MapType.MapToTarget)]
[AdaptTo("[name]SDto", IgnoreAttributes = new[] { typeof(AdaptIgnoreAttribute) }, MapType = MapType.Projection)]
@ -59,10 +61,11 @@ public partial class Product : ApiEntity
public Brand? Brand { get; internal set; }
public Guid CategoryId { get; internal set; }
public Category? Category { get; internal set; }
public ProductCategory? Category { get; internal set; }
public List<Specification> Specifications { get; internal set; } = new();
public List<Review> Reviews { get; internal set; } = new();
public List<ProductStorageFile> Files { get; internal set; } = new();
public List<OrderProduct> OrderProducts { get; internal set; } = new();
}

View File

@ -4,218 +4,178 @@ using System.Linq;
using System.Linq.Expressions;
using NetinaShop.Domain.Dtos.LargDtos;
using NetinaShop.Domain.Dtos.SmallDtos;
using NetinaShop.Domain.Entities.Categories;
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Domain.Mappers
{
public static partial class CategoryMapper
{
public static Category AdaptToCategory(this CategoryLDto p1)
public static ProductCategory AdaptToCategory(this ProductCategoryLDto p1)
{
return p1 == null ? null : new Category()
return p1 == null ? null : new ProductCategory()
{
Name = p1.Name,
Description = p1.Description,
ParentId = p1.ParentId,
Children = funcMain1(p1.Children),
Files = funcMain2(p1.Files),
ParentId = (Guid?)p1.ParentId,
Files = funcMain1(p1.Files),
Id = p1.Id
};
}
public static Category AdaptTo(this CategoryLDto p4, Category p5)
public static ProductCategory AdaptTo(this ProductCategoryLDto p3, ProductCategory p4)
{
if (p4 == null)
if (p3 == null)
{
return null;
}
Category result = p5 ?? new Category();
ProductCategory result = p4 ?? new ProductCategory();
result.Name = p4.Name;
result.Description = p4.Description;
result.ParentId = p4.ParentId;
result.Children = funcMain3(p4.Children, result.Children);
result.Files = funcMain4(p4.Files, result.Files);
result.Id = p4.Id;
result.Name = p3.Name;
result.Description = p3.Description;
result.ParentId = (Guid?)p3.ParentId;
result.Files = funcMain2(p3.Files, result.Files);
result.Id = p3.Id;
return result;
}
public static Expression<Func<CategoryLDto, Category>> ProjectToCategory => p10 => new Category()
public static Expression<Func<ProductCategoryLDto, ProductCategory>> ProjectToCategory => p7 => new ProductCategory()
{
Name = p10.Name,
Description = p10.Description,
ParentId = p10.ParentId,
Children = p10.Children.Select<CategorySDto, Category>(p11 => new Category()
Name = p7.Name,
Description = p7.Description,
ParentId = (Guid?)p7.ParentId,
Files = p7.Files.Select<StorageFileSDto, ProductCategoryStorageFile>(p8 => new ProductCategoryStorageFile()
{
Name = p11.Name,
Description = p11.Description,
ParentId = p11.ParentId,
Id = p11.Id
}).ToList<Category>(),
Files = p10.Files.Select<StorageFileSDto, CategoryStorageFile>(p12 => new CategoryStorageFile()
{
Name = p12.Name,
FileLocation = p12.FileLocation,
FileName = p12.FileName,
IsHeader = p12.IsHeader,
IsPrimary = p12.IsPrimary,
FileType = p12.FileType,
Id = p12.Id
}).ToList<CategoryStorageFile>(),
Id = p10.Id
Name = p8.Name,
FileLocation = p8.FileLocation,
FileName = p8.FileName,
IsHeader = p8.IsHeader,
IsPrimary = p8.IsPrimary,
FileType = p8.FileType,
Id = p8.Id
}).ToList<ProductCategoryStorageFile>(),
Id = p7.Id
};
public static CategoryLDto AdaptToLDto(this Category p13)
public static ProductCategoryLDto AdaptToLDto(this ProductCategory p9)
{
return p13 == null ? null : new CategoryLDto()
return p9 == null ? null : new ProductCategoryLDto()
{
Name = p13.Name,
Description = p13.Description,
ParentId = p13.ParentId,
Children = funcMain5(p13.Children),
Files = funcMain6(p13.Files),
Id = p13.Id
Name = p9.Name,
Description = p9.Description,
ParentId = p9.ParentId == null ? default(Guid) : (Guid)p9.ParentId,
Files = funcMain3(p9.Files),
Id = p9.Id
};
}
public static CategoryLDto AdaptTo(this Category p16, CategoryLDto p17)
public static ProductCategoryLDto AdaptTo(this ProductCategory p11, ProductCategoryLDto p12)
{
if (p16 == null)
if (p11 == null)
{
return null;
}
CategoryLDto result = p17 ?? new CategoryLDto();
ProductCategoryLDto result = p12 ?? new ProductCategoryLDto();
result.Name = p16.Name;
result.Description = p16.Description;
result.ParentId = p16.ParentId;
result.Children = funcMain7(p16.Children, result.Children);
result.Files = funcMain8(p16.Files, result.Files);
result.Id = p16.Id;
result.Name = p11.Name;
result.Description = p11.Description;
result.ParentId = p11.ParentId == null ? default(Guid) : (Guid)p11.ParentId;
result.Files = funcMain4(p11.Files, result.Files);
result.Id = p11.Id;
return result;
}
public static Expression<Func<Category, CategoryLDto>> ProjectToLDto => p22 => new CategoryLDto()
public static Expression<Func<ProductCategory, ProductCategoryLDto>> ProjectToLDto => p15 => new ProductCategoryLDto()
{
Name = p22.Name,
Description = p22.Description,
ParentId = p22.ParentId,
Children = p22.Children.Select<Category, CategorySDto>(p23 => new CategorySDto()
Name = p15.Name,
Description = p15.Description,
ParentId = p15.ParentId == null ? default(Guid) : (Guid)p15.ParentId,
Files = p15.Files.Select<ProductCategoryStorageFile, StorageFileSDto>(p16 => new StorageFileSDto()
{
Name = p23.Name,
Description = p23.Description,
ParentId = p23.ParentId,
Id = p23.Id
}).ToList<CategorySDto>(),
Files = p22.Files.Select<CategoryStorageFile, StorageFileSDto>(p24 => new StorageFileSDto()
{
Name = p24.Name,
FileLocation = p24.FileLocation,
FileName = p24.FileName,
IsHeader = p24.IsHeader,
IsPrimary = p24.IsPrimary,
FileType = p24.FileType,
Id = p24.Id
Name = p16.Name,
FileLocation = p16.FileLocation,
FileName = p16.FileName,
IsHeader = p16.IsHeader,
IsPrimary = p16.IsPrimary,
FileType = p16.FileType,
Id = p16.Id
}).ToList<StorageFileSDto>(),
Id = p22.Id
Id = p15.Id
};
public static Category AdaptToCategory(this CategorySDto p25)
public static ProductCategory AdaptToCategory(this ProductCategorySDto p17)
{
return p25 == null ? null : new Category()
return p17 == null ? null : new ProductCategory()
{
Name = p25.Name,
Description = p25.Description,
ParentId = p25.ParentId,
Id = p25.Id
Name = p17.Name,
Description = p17.Description,
IsMain = p17.IsMain,
ParentId = (Guid?)p17.ParentId,
Id = p17.Id
};
}
public static Category AdaptTo(this CategorySDto p26, Category p27)
public static ProductCategory AdaptTo(this ProductCategorySDto p18, ProductCategory p19)
{
if (p26 == null)
if (p18 == null)
{
return null;
}
Category result = p27 ?? new Category();
ProductCategory result = p19 ?? new ProductCategory();
result.Name = p26.Name;
result.Description = p26.Description;
result.ParentId = p26.ParentId;
result.Id = p26.Id;
result.Name = p18.Name;
result.Description = p18.Description;
result.IsMain = p18.IsMain;
result.ParentId = (Guid?)p18.ParentId;
result.Id = p18.Id;
return result;
}
public static CategorySDto AdaptToSDto(this Category p28)
public static ProductCategorySDto AdaptToSDto(this ProductCategory p20)
{
return p28 == null ? null : new CategorySDto()
return p20 == null ? null : new ProductCategorySDto()
{
Name = p28.Name,
Description = p28.Description,
ParentId = p28.ParentId,
Id = p28.Id
Name = p20.Name,
Description = p20.Description,
IsMain = p20.IsMain,
ParentId = p20.ParentId == null ? default(Guid) : (Guid)p20.ParentId,
Id = p20.Id
};
}
public static CategorySDto AdaptTo(this Category p29, CategorySDto p30)
public static ProductCategorySDto AdaptTo(this ProductCategory p21, ProductCategorySDto p22)
{
if (p29 == null)
if (p21 == null)
{
return null;
}
CategorySDto result = p30 ?? new CategorySDto();
ProductCategorySDto result = p22 ?? new ProductCategorySDto();
result.Name = p29.Name;
result.Description = p29.Description;
result.ParentId = p29.ParentId;
result.Id = p29.Id;
result.Name = p21.Name;
result.Description = p21.Description;
result.IsMain = p21.IsMain;
result.ParentId = p21.ParentId == null ? default(Guid) : (Guid)p21.ParentId;
result.Id = p21.Id;
return result;
}
public static Expression<Func<Category, CategorySDto>> ProjectToSDto => p31 => new CategorySDto()
public static Expression<Func<ProductCategory, ProductCategorySDto>> ProjectToSDto => p23 => new ProductCategorySDto()
{
Name = p31.Name,
Description = p31.Description,
ParentId = p31.ParentId,
Id = p31.Id
Name = p23.Name,
Description = p23.Description,
IsMain = p23.IsMain,
ParentId = p23.ParentId == null ? default(Guid) : (Guid)p23.ParentId,
Id = p23.Id
};
private static List<Category> funcMain1(List<CategorySDto> p2)
private static List<ProductCategoryStorageFile> funcMain1(List<StorageFileSDto> p2)
{
if (p2 == null)
{
return null;
}
List<Category> result = new List<Category>(p2.Count);
List<ProductCategoryStorageFile> result = new List<ProductCategoryStorageFile>(p2.Count);
int i = 0;
int len = p2.Count;
while (i < len)
{
CategorySDto item = p2[i];
result.Add(item == null ? null : new Category()
{
Name = item.Name,
Description = item.Description,
ParentId = item.ParentId,
Id = item.Id
});
i++;
}
return result;
}
private static List<CategoryStorageFile> funcMain2(List<StorageFileSDto> p3)
{
if (p3 == null)
{
return null;
}
List<CategoryStorageFile> result = new List<CategoryStorageFile>(p3.Count);
int i = 0;
int len = p3.Count;
while (i < len)
{
StorageFileSDto item = p3[i];
result.Add(item == null ? null : new CategoryStorageFile()
StorageFileSDto item = p2[i];
result.Add(item == null ? null : new ProductCategoryStorageFile()
{
Name = item.Name,
FileLocation = item.FileLocation,
@ -231,48 +191,21 @@ namespace NetinaShop.Domain.Mappers
}
private static List<Category> funcMain3(List<CategorySDto> p6, List<Category> p7)
private static List<ProductCategoryStorageFile> funcMain2(List<StorageFileSDto> p5, List<ProductCategoryStorageFile> p6)
{
if (p6 == null)
if (p5 == null)
{
return null;
}
List<Category> result = new List<Category>(p6.Count);
List<ProductCategoryStorageFile> result = new List<ProductCategoryStorageFile>(p5.Count);
int i = 0;
int len = p6.Count;
int len = p5.Count;
while (i < len)
{
CategorySDto item = p6[i];
result.Add(item == null ? null : new Category()
{
Name = item.Name,
Description = item.Description,
ParentId = item.ParentId,
Id = item.Id
});
i++;
}
return result;
}
private static List<CategoryStorageFile> funcMain4(List<StorageFileSDto> p8, List<CategoryStorageFile> p9)
{
if (p8 == null)
{
return null;
}
List<CategoryStorageFile> result = new List<CategoryStorageFile>(p8.Count);
int i = 0;
int len = p8.Count;
while (i < len)
{
StorageFileSDto item = p8[i];
result.Add(item == null ? null : new CategoryStorageFile()
StorageFileSDto item = p5[i];
result.Add(item == null ? null : new ProductCategoryStorageFile()
{
Name = item.Name,
FileLocation = item.FileLocation,
@ -288,47 +221,20 @@ namespace NetinaShop.Domain.Mappers
}
private static List<CategorySDto> funcMain5(List<Category> p14)
private static List<StorageFileSDto> funcMain3(List<ProductCategoryStorageFile> p10)
{
if (p14 == null)
if (p10 == null)
{
return null;
}
List<CategorySDto> result = new List<CategorySDto>(p14.Count);
List<StorageFileSDto> result = new List<StorageFileSDto>(p10.Count);
int i = 0;
int len = p14.Count;
int len = p10.Count;
while (i < len)
{
Category item = p14[i];
result.Add(item == null ? null : new CategorySDto()
{
Name = item.Name,
Description = item.Description,
ParentId = item.ParentId,
Id = item.Id
});
i++;
}
return result;
}
private static List<StorageFileSDto> funcMain6(List<CategoryStorageFile> p15)
{
if (p15 == null)
{
return null;
}
List<StorageFileSDto> result = new List<StorageFileSDto>(p15.Count);
int i = 0;
int len = p15.Count;
while (i < len)
{
CategoryStorageFile item = p15[i];
ProductCategoryStorageFile item = p10[i];
result.Add(item == null ? null : new StorageFileSDto()
{
Name = item.Name,
@ -345,47 +251,20 @@ namespace NetinaShop.Domain.Mappers
}
private static List<CategorySDto> funcMain7(List<Category> p18, List<CategorySDto> p19)
private static List<StorageFileSDto> funcMain4(List<ProductCategoryStorageFile> p13, List<StorageFileSDto> p14)
{
if (p18 == null)
if (p13 == null)
{
return null;
}
List<CategorySDto> result = new List<CategorySDto>(p18.Count);
List<StorageFileSDto> result = new List<StorageFileSDto>(p13.Count);
int i = 0;
int len = p18.Count;
int len = p13.Count;
while (i < len)
{
Category item = p18[i];
result.Add(item == null ? null : new CategorySDto()
{
Name = item.Name,
Description = item.Description,
ParentId = item.ParentId,
Id = item.Id
});
i++;
}
return result;
}
private static List<StorageFileSDto> funcMain8(List<CategoryStorageFile> p20, List<StorageFileSDto> p21)
{
if (p20 == null)
{
return null;
}
List<StorageFileSDto> result = new List<StorageFileSDto>(p20.Count);
int i = 0;
int len = p20.Count;
while (i < len)
{
CategoryStorageFile item = p20[i];
ProductCategoryStorageFile item = p13[i];
result.Add(item == null ? null : new StorageFileSDto()
{
Name = item.Name,

View File

@ -180,7 +180,15 @@ namespace NetinaShop.Domain.Mappers
ExpertCheck = p33.ExpertCheck,
Tags = p33.Tags,
Warranty = p33.Warranty,
Cost = p33.Cost,
IsEnable = p33.IsEnable,
BeDisplayed = p33.BeDisplayed,
PackingCost = p33.PackingCost,
Rate = p33.Rate,
ReviewCount = p33.ReviewCount,
Viewed = p33.Viewed,
BrandId = p33.BrandId,
CategoryId = p33.CategoryId,
Id = p33.Id
};
}
@ -198,7 +206,15 @@ namespace NetinaShop.Domain.Mappers
result.ExpertCheck = p34.ExpertCheck;
result.Tags = p34.Tags;
result.Warranty = p34.Warranty;
result.Cost = p34.Cost;
result.IsEnable = p34.IsEnable;
result.BeDisplayed = p34.BeDisplayed;
result.PackingCost = p34.PackingCost;
result.Rate = p34.Rate;
result.ReviewCount = p34.ReviewCount;
result.Viewed = p34.Viewed;
result.BrandId = p34.BrandId;
result.CategoryId = p34.CategoryId;
result.Id = p34.Id;
return result;
@ -213,6 +229,14 @@ namespace NetinaShop.Domain.Mappers
ExpertCheck = p36.ExpertCheck,
Tags = p36.Tags,
Warranty = p36.Warranty,
Cost = p36.Cost,
IsEnable = p36.IsEnable,
BeDisplayed = p36.BeDisplayed,
PackingCost = p36.PackingCost,
Rate = p36.Rate,
ReviewCount = p36.ReviewCount,
Viewed = p36.Viewed,
CategoryId = p36.CategoryId,
BrandId = p36.BrandId,
Id = p36.Id
};
@ -231,6 +255,14 @@ namespace NetinaShop.Domain.Mappers
result.ExpertCheck = p37.ExpertCheck;
result.Tags = p37.Tags;
result.Warranty = p37.Warranty;
result.Cost = p37.Cost;
result.IsEnable = p37.IsEnable;
result.BeDisplayed = p37.BeDisplayed;
result.PackingCost = p37.PackingCost;
result.Rate = p37.Rate;
result.ReviewCount = p37.ReviewCount;
result.Viewed = p37.Viewed;
result.CategoryId = p37.CategoryId;
result.BrandId = p37.BrandId;
result.Id = p37.Id;
return result;
@ -244,6 +276,14 @@ namespace NetinaShop.Domain.Mappers
ExpertCheck = p39.ExpertCheck,
Tags = p39.Tags,
Warranty = p39.Warranty,
Cost = p39.Cost,
IsEnable = p39.IsEnable,
BeDisplayed = p39.BeDisplayed,
PackingCost = p39.PackingCost,
Rate = p39.Rate,
ReviewCount = p39.ReviewCount,
Viewed = p39.Viewed,
CategoryId = p39.CategoryId,
BrandId = p39.BrandId,
Id = p39.Id
};

View File

@ -67,9 +67,9 @@
<Using Include="NetinaShop.Domain.Dtos.SmallDtos" />
<Using Include="NetinaShop.Domain.Entities.Blogs" />
<Using Include="NetinaShop.Domain.Entities.Brands" />
<Using Include="NetinaShop.Domain.Entities.Categories" />
<Using Include="NetinaShop.Domain.Entities.Discounts" />
<Using Include="NetinaShop.Domain.Entities.Orders" />
<Using Include="NetinaShop.Domain.Entities.ProductCategories" />
<Using Include="NetinaShop.Domain.Entities.Products" />
<Using Include="NetinaShop.Domain.Entities.StorageFiles" />
<Using Include="NetinaShop.Domain.Entities.Users" />

View File

@ -0,0 +1,24 @@
using NetinaShop.Domain.Entities.Brands;
namespace NetinaShop.Repository.Handlers.Brands;
public class CreateBrandCommandHandler : IRequestHandler<CreateBrandCommand , BrandSDto>
{
private IRepositoryWrapper _repositoryWrapper;
public CreateBrandCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<BrandSDto> Handle(CreateBrandCommand request, CancellationToken cancellationToken)
{
var ent = Brand.Create(request.Name, request.Description, request.HasSpecialPage, request.PageUrl);
foreach (var file in request.Files)
{
ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
}
_repositoryWrapper.SetRepository<Brand>().Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return ent.AdaptToSDto();
}
}

View File

@ -0,0 +1,24 @@
using NetinaShop.Domain.Entities.Brands;
namespace NetinaShop.Repository.Handlers.Brands;
public class DeleteBrandCommandHandler : IRequestHandler<DeleteBrandCommand,bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteBrandCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteBrandCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Brand>().TableNoTracking
.FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Brand not found");
_repositoryWrapper.SetRepository<Brand>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -0,0 +1,25 @@
using NetinaShop.Domain.Entities.Brands;
namespace NetinaShop.Repository.Handlers.Brands;
public class UpdateBrandCommandHandler : IRequestHandler<UpdateBrandCommand,bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public UpdateBrandCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(UpdateBrandCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Brand>().TableNoTracking
.FirstOrDefaultAsync(b => b.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Brand not found");
var newEnt = Brand.Create(request.Name, request.Description, request.HasSpecialPage, request.PageUrl);
newEnt.Id = ent.Id;
_repositoryWrapper.SetRepository<Brand>().Update(newEnt);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,24 +0,0 @@
namespace NetinaShop.Repository.Handlers.Categories;
public class CreateCategoryCommandHandler : IRequestHandler<CreateCategoryCommand,CategoryLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<CategoryLDto> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
{
var ent = Category.Create(request.Name, request.Description);
if (request.ParentId != default)
ent.SetParent(request.ParentId);
foreach (var file in request.Files)
{
ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
}
_repositoryWrapper.SetRepository<Category>().Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return ent.AdaptToLDto();
}
}

View File

@ -1,22 +0,0 @@
namespace NetinaShop.Repository.Handlers.Categories;
public class DeleteCategoryCommandHandler : IRequestHandler<DeleteCategoryCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(DeleteCategoryCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Category>().TableNoTracking
.FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Category not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<Category>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -1,18 +0,0 @@
namespace NetinaShop.Repository.Handlers.Categories;
public class GetCategoriesQueryHandler : IRequestHandler<GetCategoriesQuery, List<CategorySDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetCategoriesQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<CategorySDto>> Handle(GetCategoriesQuery request, CancellationToken cancellationToken)
{
return await _repositoryWrapper.SetRepository<Category>().TableNoTracking.OrderByDescending(b => b.CreatedAt)
.Skip(request.Page * 10).Take(10)
.Select(CategoryMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
}
}

View File

@ -1,21 +0,0 @@
namespace NetinaShop.Repository.Handlers.Categories;
public class GetCategoryQueryHandler : IRequestHandler<GetCategoryQuery, CategoryLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetCategoryQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<CategoryLDto> Handle(GetCategoryQuery request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Category>().TableNoTracking
.Where(b => b.Id == request.Id)
.Select(CategoryMapper.ProjectToLDto)
.FirstOrDefaultAsync(cancellationToken);
if (ent == null)
throw new AppException("Category not found", ApiResultStatusCode.NotFound);
return ent;
}
}

View File

@ -0,0 +1,26 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Repository.Handlers.ProductCategories;
public class CreateProductCategoryCommandHandler : IRequestHandler<ProductCreateCategoryCommand,ProductCategoryLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public CreateProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ProductCategoryLDto> Handle(ProductCreateCategoryCommand request, CancellationToken cancellationToken)
{
var ent = ProductCategory.Create(request.Name, request.Description);
if (request.ParentId != default)
ent.SetParent(request.ParentId);
foreach (var file in request.Files)
{
ent.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
}
_repositoryWrapper.SetRepository<ProductCategory>().Add(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return ent.AdaptToLDto();
}
}

View File

@ -0,0 +1,24 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Repository.Handlers.ProductCategories;
public class DeleteProductCategoryCommandHandler : IRequestHandler<ProductDeleteCategoryCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public DeleteProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(ProductDeleteCategoryCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<ProductCategory>().TableNoTracking
.FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("ProductCategory not found", ApiResultStatusCode.NotFound);
_repositoryWrapper.SetRepository<ProductCategory>().Delete(ent);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}
}

View File

@ -0,0 +1,23 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Repository.Handlers.ProductCategories;
public class GetCategoryQueryHandler : IRequestHandler<GetProductCategoryQuery, ProductCategoryLDto>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetCategoryQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<ProductCategoryLDto> Handle(GetProductCategoryQuery request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<ProductCategory>().TableNoTracking
.Where(b => b.Id == request.Id)
.Select(CategoryMapper.ProjectToLDto)
.FirstOrDefaultAsync(cancellationToken);
if (ent == null)
throw new AppException("ProductCategory not found", ApiResultStatusCode.NotFound);
return ent;
}
}

View File

@ -0,0 +1,27 @@
using NetinaShop.Domain.Entities.ProductCategories;
namespace NetinaShop.Repository.Handlers.ProductCategories;
public class GetProductCategoriesQueryHandler : IRequestHandler<GetProductCategoriesQuery, List<ProductCategorySDto>>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public GetProductCategoriesQueryHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<List<ProductCategorySDto>> Handle(GetProductCategoriesQuery request, CancellationToken cancellationToken)
{
var groupCats = await _repositoryWrapper.SetRepository<ProductCategory>()
.TableNoTracking
.Select(CategoryMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
foreach (var cat in groupCats)
cat.Children = groupCats.Where(c => c.ParentId == cat.Id).ToList();
var mainCats = groupCats.Where(c => c.IsMain).ToList();
return mainCats;
}
}

View File

@ -1,33 +1,35 @@
namespace NetinaShop.Repository.Handlers.Categories;
using NetinaShop.Domain.Entities.ProductCategories;
public class UpdateCategoryCommandHandler : IRequestHandler<UpdateCategoryCommand, bool>
namespace NetinaShop.Repository.Handlers.ProductCategories;
public class UpdateProductCategoryCommandHandler : IRequestHandler<ProductUpdateCategoryCommand, bool>
{
private readonly IRepositoryWrapper _repositoryWrapper;
public UpdateCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
public UpdateProductCategoryCommandHandler(IRepositoryWrapper repositoryWrapper)
{
_repositoryWrapper = repositoryWrapper;
}
public async Task<bool> Handle(UpdateCategoryCommand request, CancellationToken cancellationToken)
public async Task<bool> Handle(ProductUpdateCategoryCommand request, CancellationToken cancellationToken)
{
var ent = await _repositoryWrapper.SetRepository<Category>().TableNoTracking
var ent = await _repositoryWrapper.SetRepository<ProductCategory>().TableNoTracking
.FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken);
if (ent == null)
throw new AppException("Category not found", ApiResultStatusCode.NotFound);
throw new AppException("ProductCategory not found", ApiResultStatusCode.NotFound);
var newEnt = Category.Create(request.Name, request.Description);
var newEnt = ProductCategory.Create(request.Name, request.Description);
newEnt.Id = ent.Id;
if (request.ParentId != default)
newEnt.SetParent(request.ParentId);
var dbFiles = await _repositoryWrapper.SetRepository<CategoryStorageFile>().TableNoTracking
var dbFiles = await _repositoryWrapper.SetRepository<ProductCategoryStorageFile>().TableNoTracking
.Where(s => s.CategoryId == newEnt.Id).ToListAsync(cancellationToken);
foreach (var dbFile in dbFiles)
{
if (request.Files.Any(s => s.Id == dbFile.Id))
{
_repositoryWrapper.SetRepository<CategoryStorageFile>().Delete(dbFile);
_repositoryWrapper.SetRepository<ProductCategoryStorageFile>().Delete(dbFile);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
}
}
@ -35,7 +37,7 @@ public class UpdateCategoryCommandHandler : IRequestHandler<UpdateCategoryComman
{
newEnt.AddFile(file.Name, file.FileLocation, file.FileName, file.IsHeader, file.IsPrimary, file.FileType);
}
_repositoryWrapper.SetRepository<Category>().Add(newEnt);
_repositoryWrapper.SetRepository<ProductCategory>().Add(newEnt);
await _repositoryWrapper.SaveChangesAsync(cancellationToken);
return true;
}

View File

@ -14,6 +14,7 @@ public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand,
var ent = Product.Create(request.PersianName, request.EnglishName, request.Summery, request.ExpertCheck,
request.Tags, request.Warranty,request.BeDisplayed,request.Cost,request.PackingCost,0,0,0,
request.BrandId,request.CategoryId);
foreach (var specification in request.Specifications)
{
ent.AddSpecification(specification.Title, specification.Detail, specification.Value,

View File

@ -1,4 +1,6 @@
namespace NetinaShop.Repository.Handlers.Products;
using NetinaShop.Domain.Entities.Discounts;
namespace NetinaShop.Repository.Handlers.Products;
public class GetProductsQueryHandler : IRequestHandler<GetProductsQuery, List<ProductSDto>>
{
@ -21,26 +23,57 @@ public class GetProductsQueryHandler : IRequestHandler<GetProductsQuery, List<Pr
products = products.Where(p => p.Cost <= request.MaxPrice);
if (request.SortBy != QuerySortBy.None)
{
switch (request.SortBy)
products = request.SortBy switch
{
case QuerySortBy.Cheapest:
products = products.OrderBy(p => p.Cost);
break;
case QuerySortBy.MostExpensive:
products = products.OrderByDescending(p => p.Cost);
break;
case QuerySortBy.MostPopular:
products = products.OrderByDescending(p => p.Rate);
break;
case QuerySortBy.MostViewed:
products = products.OrderByDescending(p => p.Viewed);
break;
}
QuerySortBy.Cheapest => products.OrderBy(p => p.Cost),
QuerySortBy.MostExpensive => products.OrderByDescending(p => p.Cost),
QuerySortBy.MostPopular => products.OrderByDescending(p => p.Rate),
QuerySortBy.MostViewed => products.OrderByDescending(p => p.Viewed),
_ => products
};
}
return await products.Skip(request.Page * 10)
var productSDtos = await products.Skip(request.Page * 10)
.Take(10)
.Select(ProductMapper.ProjectToSDto)
.ToListAsync(cancellationToken);
foreach (var productSDto in productSDtos)
{
double discountPrice = 0;
productSDto.CostWithDiscount = productSDto.Cost;
var categoryDiscount = await _repositoryWrapper.SetRepository<CategoryDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.CategoryId == productSDto.CategoryId && d.HasCode == false && d.ExpireDate.Date > DateTime.Today.Date, cancellationToken);
if (categoryDiscount != null && !categoryDiscount.IsExpired())
{
var totalPrice = productSDto.Cost;
discountPrice = categoryDiscount.AmountType == DiscountAmountType.Amount
? totalPrice - categoryDiscount.DiscountAmount : totalPrice - ((totalPrice / 100) * categoryDiscount.DiscountAmount);
productSDto.CostWithDiscount = productSDto.CostWithDiscount - discountPrice;
productSDto.HasDiscount = true;
productSDto.DiscountPercent = (100 * productSDto.CostWithDiscount) / productSDto.Cost;
}
var productDiscount = await _repositoryWrapper.SetRepository<ProductDiscount>()
.TableNoTracking
.FirstOrDefaultAsync(d => d.HasCode == false && d.ProductId == productSDto.Id && d.ExpireDate.Date > DateTime.Today.Date, cancellationToken);
if (productDiscount != null && !productDiscount.IsExpired())
{
var totalPrice = productSDto.Cost;
discountPrice = productDiscount.AmountType == DiscountAmountType.Amount
? totalPrice - productDiscount.DiscountAmount
: totalPrice - ((totalPrice / 100) * productDiscount.DiscountAmount);
productSDto.CostWithDiscount = productSDto.CostWithDiscount - discountPrice;
productSDto.HasDiscount = true;
productSDto.DiscountPercent = (100 * productSDto.CostWithDiscount) / productSDto.Cost;
}
}
return productSDtos;
}
}

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace NetinaShop.Repository.Migrations
{
[DbContext(typeof(ApplicationContext))]
[Migration("20240101131008_Init")]
[Migration("20240109085213_Init")]
partial class Init
{
/// <inheritdoc />
@ -275,51 +275,6 @@ namespace NetinaShop.Repository.Migrations
b.ToTable("Brands", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsRemoved")
.HasColumnType("boolean");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ParentId")
.HasColumnType("uuid");
b.Property<DateTime>("RemovedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("RemovedBy")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("Categories", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.Discount", b =>
{
b.Property<Guid>("Id")
@ -622,6 +577,54 @@ namespace NetinaShop.Repository.Migrations
b.ToTable("OrderProducts", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsMain")
.HasColumnType("boolean");
b.Property<bool>("IsRemoved")
.HasColumnType("boolean");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ParentId")
.HasColumnType("uuid");
b.Property<DateTime>("RemovedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("RemovedBy")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("ProductCategories", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.Property<Guid>("Id")
@ -839,8 +842,8 @@ namespace NetinaShop.Repository.Migrations
b.Property<string>("Discriminator")
.IsRequired()
.HasMaxLength(21)
.HasColumnType("character varying(21)");
.HasMaxLength(34)
.HasColumnType("character varying(34)");
b.Property<string>("FileLocation")
.IsRequired()
@ -1213,7 +1216,7 @@ namespace NetinaShop.Repository.Migrations
b.HasDiscriminator().HasValue("BrandStorageFile");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.CategoryStorageFile", b =>
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategoryStorageFile", b =>
{
b.HasBaseType("NetinaShop.Domain.Entities.StorageFiles.StorageFile");
@ -1222,7 +1225,7 @@ namespace NetinaShop.Repository.Migrations
b.HasIndex("CategoryId");
b.HasDiscriminator().HasValue("CategoryStorageFile");
b.HasDiscriminator().HasValue("ProductCategoryStorageFile");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.ProductStorageFile", b =>
@ -1299,17 +1302,6 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Category");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Parent");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Orders.Order", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Discounts.Discount", null)
@ -1363,6 +1355,15 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Product");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Parent")
.WithMany()
.HasForeignKey("ParentId");
b.Navigation("Parent");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Brands.Brand", "Brand")
@ -1371,7 +1372,7 @@ namespace NetinaShop.Repository.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1452,7 +1453,7 @@ namespace NetinaShop.Repository.Migrations
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.CategoryDiscount", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1494,9 +1495,9 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Brand");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.CategoryStorageFile", b =>
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategoryStorageFile", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany("Files")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1533,15 +1534,6 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.Navigation("Children");
b.Navigation("Files");
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.Discount", b =>
{
b.Navigation("Orders");
@ -1554,6 +1546,13 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("OrderProducts");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.Navigation("Files");
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.Navigation("Files");

View File

@ -60,14 +60,15 @@ namespace NetinaShop.Repository.Migrations
});
migrationBuilder.CreateTable(
name: "Categories",
name: "ProductCategories",
schema: "public",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
ParentId = table.Column<Guid>(type: "uuid", nullable: false),
IsMain = table.Column<bool>(type: "boolean", nullable: false),
ParentId = table.Column<Guid>(type: "uuid", nullable: true),
RemovedAt = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
CreatedBy = table.Column<string>(type: "text", nullable: true),
@ -78,14 +79,13 @@ namespace NetinaShop.Repository.Migrations
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
table.PrimaryKey("PK_ProductCategories", x => x.Id);
table.ForeignKey(
name: "FK_Categories_Categories_ParentId",
name: "FK_ProductCategories_ProductCategories_ParentId",
column: x => x.ParentId,
principalSchema: "public",
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
principalTable: "ProductCategories",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
@ -236,10 +236,10 @@ namespace NetinaShop.Repository.Migrations
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Products_Categories_CategoryId",
name: "FK_Products_ProductCategories_CategoryId",
column: x => x.CategoryId,
principalSchema: "public",
principalTable: "Categories",
principalTable: "ProductCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
@ -431,10 +431,10 @@ namespace NetinaShop.Repository.Migrations
{
table.PrimaryKey("PK_Discounts", x => x.Id);
table.ForeignKey(
name: "FK_Discounts_Categories_CategoryId",
name: "FK_Discounts_ProductCategories_CategoryId",
column: x => x.CategoryId,
principalSchema: "public",
principalTable: "Categories",
principalTable: "ProductCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
@ -537,7 +537,7 @@ namespace NetinaShop.Repository.Migrations
IsHeader = table.Column<bool>(type: "boolean", nullable: false),
IsPrimary = table.Column<bool>(type: "boolean", nullable: false),
FileType = table.Column<int>(type: "integer", nullable: false),
Discriminator = table.Column<string>(type: "character varying(21)", maxLength: 21, nullable: false),
Discriminator = table.Column<string>(type: "character varying(34)", maxLength: 34, nullable: false),
BlogId = table.Column<Guid>(type: "uuid", nullable: true),
BrandId = table.Column<Guid>(type: "uuid", nullable: true),
CategoryId = table.Column<Guid>(type: "uuid", nullable: true),
@ -568,10 +568,10 @@ namespace NetinaShop.Repository.Migrations
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_StorageFiles_Categories_CategoryId",
name: "FK_StorageFiles_ProductCategories_CategoryId",
column: x => x.CategoryId,
principalSchema: "public",
principalTable: "Categories",
principalTable: "ProductCategories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
@ -755,12 +755,6 @@ namespace NetinaShop.Repository.Migrations
table: "Blogs",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Categories_ParentId",
schema: "public",
table: "Categories",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_Claims_UserId",
schema: "public",
@ -821,6 +815,12 @@ namespace NetinaShop.Repository.Migrations
table: "Orders",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_ProductCategories_ParentId",
schema: "public",
table: "ProductCategories",
column: "ParentId");
migrationBuilder.CreateIndex(
name: "IX_Products_BrandId",
schema: "public",
@ -1020,7 +1020,7 @@ namespace NetinaShop.Repository.Migrations
schema: "public");
migrationBuilder.DropTable(
name: "Categories",
name: "ProductCategories",
schema: "public");
}
}

View File

@ -272,51 +272,6 @@ namespace NetinaShop.Repository.Migrations
b.ToTable("Brands", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsRemoved")
.HasColumnType("boolean");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("ParentId")
.HasColumnType("uuid");
b.Property<DateTime>("RemovedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("RemovedBy")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("Categories", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.Discount", b =>
{
b.Property<Guid>("Id")
@ -619,6 +574,54 @@ namespace NetinaShop.Repository.Migrations
b.ToTable("OrderProducts", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("CreatedBy")
.HasColumnType("text");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsMain")
.HasColumnType("boolean");
b.Property<bool>("IsRemoved")
.HasColumnType("boolean");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("ModifiedBy")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid?>("ParentId")
.HasColumnType("uuid");
b.Property<DateTime>("RemovedAt")
.HasColumnType("timestamp without time zone");
b.Property<string>("RemovedBy")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ParentId");
b.ToTable("ProductCategories", "public");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.Property<Guid>("Id")
@ -836,8 +839,8 @@ namespace NetinaShop.Repository.Migrations
b.Property<string>("Discriminator")
.IsRequired()
.HasMaxLength(21)
.HasColumnType("character varying(21)");
.HasMaxLength(34)
.HasColumnType("character varying(34)");
b.Property<string>("FileLocation")
.IsRequired()
@ -1210,7 +1213,7 @@ namespace NetinaShop.Repository.Migrations
b.HasDiscriminator().HasValue("BrandStorageFile");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.CategoryStorageFile", b =>
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategoryStorageFile", b =>
{
b.HasBaseType("NetinaShop.Domain.Entities.StorageFiles.StorageFile");
@ -1219,7 +1222,7 @@ namespace NetinaShop.Repository.Migrations
b.HasIndex("CategoryId");
b.HasDiscriminator().HasValue("CategoryStorageFile");
b.HasDiscriminator().HasValue("ProductCategoryStorageFile");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.ProductStorageFile", b =>
@ -1296,17 +1299,6 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Category");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Parent");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Orders.Order", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Discounts.Discount", null)
@ -1360,6 +1352,15 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Product");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Parent")
.WithMany()
.HasForeignKey("ParentId");
b.Navigation("Parent");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Brands.Brand", "Brand")
@ -1368,7 +1369,7 @@ namespace NetinaShop.Repository.Migrations
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany("Products")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1449,7 +1450,7 @@ namespace NetinaShop.Repository.Migrations
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.CategoryDiscount", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany()
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1491,9 +1492,9 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Brand");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.CategoryStorageFile", b =>
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategoryStorageFile", b =>
{
b.HasOne("NetinaShop.Domain.Entities.Categories.Category", "Category")
b.HasOne("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", "Category")
.WithMany("Files")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Restrict)
@ -1530,15 +1531,6 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Categories.Category", b =>
{
b.Navigation("Children");
b.Navigation("Files");
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Discounts.Discount", b =>
{
b.Navigation("Orders");
@ -1551,6 +1543,13 @@ namespace NetinaShop.Repository.Migrations
b.Navigation("OrderProducts");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.ProductCategories.ProductCategory", b =>
{
b.Navigation("Files");
b.Navigation("Products");
});
modelBuilder.Entity("NetinaShop.Domain.Entities.Products.Product", b =>
{
b.Navigation("Files");

View File

@ -28,7 +28,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="Handlers\Categories\" />
<Folder Include="Handlers\Brands\" />
<Folder Include="Models\" />
<Folder Include="Extensions\" />
<Folder Include="Services\Abstracts\" />
@ -62,8 +62,8 @@
<Using Include="NetinaShop.Domain.Dtos.LargDtos" />
<Using Include="NetinaShop.Domain.Dtos.ResponseDtos" />
<Using Include="NetinaShop.Domain.Dtos.SmallDtos" />
<Using Include="NetinaShop.Domain.Entities.Categories" />
<Using Include="NetinaShop.Domain.Entities.Discounts" />
<Using Include="NetinaShop.Domain.Entities.ProductCategories" />
<Using Include="NetinaShop.Domain.Entities.Products" />
<Using Include="NetinaShop.Domain.Entities.Users" />
<Using Include="NetinaShop.Domain.Enums" />

View File

@ -20,6 +20,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ConfigFiles", "ConfigFiles"
.version = .version
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{4B7737FD-3BFC-4C21-AB47-4BFAF1CD1EDA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetinaShop.WordPressDBConverter", "Tools\NetinaShop.WordPressDBConverter\NetinaShop.WordPressDBConverter.csproj", "{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -50,10 +54,17 @@ Global
{4A25936E-275C-41EA-9ADC-4375E8AC5207}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A25936E-275C-41EA-9ADC-4375E8AC5207}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A25936E-275C-41EA-9ADC-4375E8AC5207}.Release|Any CPU.Build.0 = Release|Any CPU
{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{5112E6D9-FA93-4CE0-95EE-A5F6B1DD52B6} = {4B7737FD-3BFC-4C21-AB47-4BFAF1CD1EDA}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3740B4AA-7AFB-4DAC-87CB-13AD7D1DC814}
EndGlobalSection

View File

@ -0,0 +1,28 @@
namespace NetinaShop.WordPressDBConverter.Models;
public class WordPressPostDto
{
public string ID { get; set; }
public string post_author { get; set; }
public string post_date { get; set; }
public string post_date_gmt { get; set; }
public string post_content { get; set; }
public string post_title { get; set; }
public string post_excerpt { get; set; }
public string post_status { get; set; }
public string comment_status { get; set; }
public string ping_status { get; set; }
public string post_password { get; set; }
public string post_name { get; set; }
public string to_ping { get; set; }
public string pinged { get; set; }
public string post_modified { get; set; }
public string post_modified_gmt { get; set; }
public string post_content_filtered { get; set; }
public string post_parent { get; set; }
public string guid { get; set; }
public string menu_order { get; set; }
public string post_type { get; set; }
public string post_mime_type { get; set; }
public string comment_count { get; set; }
}

View File

@ -0,0 +1,9 @@
namespace NetinaShop.WordPressDBConverter.Models;
public class WordPressPostMetaDto
{
public string meta_id { get; set; }
public string post_id { get; set; }
public string meta_key { get; set; }
public string meta_value { get; set; }
}

View File

@ -0,0 +1,9 @@
namespace NetinaShop.WordPressDBConverter.Models;
public class WordPressTermDto
{
public string term_id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string term_group { get; set; }
}

View File

@ -0,0 +1,8 @@
namespace NetinaShop.WordPressDBConverter.Models;
public class WordPressTermRelationDto
{
public string object_id { get; set; }
public string term_taxonomy_id { get; set; }
public string term_order { get; set; }
}

View File

@ -0,0 +1,11 @@
namespace NetinaShop.WordPressDBConverter.Models;
public class WordPressTermTaxonomyDto
{
public string term_taxonomy_id { get; set; }
public string term_id { get; set; }
public string taxonomy { get; set; }
public string description { get; set; }
public string parent { get; set; }
public string count { get; set; }
}

View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Refit" Version="7.0.0" />
<PackageReference Include="Refit.Newtonsoft.Json" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\RestServices\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\NetinaShop.Domain\NetinaShop.Domain.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,132 @@
using NetinaShop.Common.Extensions;
using NetinaShop.Domain.CommandQueries.Commands;
using NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
using NetinaShop.Domain.Dtos.SmallDtos;
using NetinaShop.WordPressDBConverter.Models;
using NetinaShop.WordPressDBConverter.Services.RestServices;
using Newtonsoft.Json;
Console.ReadKey();
try
{
var termReader = new StreamReader("F:\\wp_terms.json");
var termJson = termReader.ReadToEnd();
Console.WriteLine("Terms File Read Success !");
var terms = JsonConvert.DeserializeObject<List<WordPressTermDto>>(termJson);
if (terms == null)
throw new Exception("Terms is null");
var termTaxonomyReader = new StreamReader("F:\\wp_term_taxonomy.json");
var termTaxonomyJson = termTaxonomyReader.ReadToEnd();
Console.WriteLine("Term Taxonomy File Read Success !");
var termTaxonomies = JsonConvert.DeserializeObject<List<WordPressTermTaxonomyDto>>(termTaxonomyJson);
if (termTaxonomies == null)
throw new Exception("Term Taxonomies is null");
var termRelationshipsReader = new StreamReader("F:\\wp_term_relationships.json");
var termRelationshipsJson = termRelationshipsReader.ReadToEnd();
Console.WriteLine("Term Relationships File Read Success !");
var termRelationships = JsonConvert.DeserializeObject<List<WordPressTermRelationDto>>(termRelationshipsJson);
if (termRelationships == null)
throw new Exception("Term Relationships is null");
var postReader = new StreamReader("F:\\wp_posts.json");
var json = postReader.ReadToEnd();
Console.WriteLine("Post File Read Success !");
var posts = JsonConvert.DeserializeObject<List<WordPressPostDto>>(json);
if (posts == null)
throw new Exception("Posts is null");
var metaReader = new StreamReader("F:\\wp_postmeta.json");
var metaJson = metaReader.ReadToEnd();
Console.WriteLine("Post Metas File Read Success !");
var postMetas = JsonConvert.DeserializeObject<List<WordPressPostMetaDto>>(metaJson);
if (postMetas == null)
throw new Exception("Post Metas is null");
//CREATE CATEGORY PART
List<SeedCategoryRequestDto> categories = new List<SeedCategoryRequestDto>();
foreach (var taxonomy in termTaxonomies)
{
if (taxonomy.taxonomy == "product_cat")
{
var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
if (term != null)
categories.Add(new SeedCategoryRequestDto
{ BaseCategoryId = term.term_id.ToInt(), Description = taxonomy.description, Name = term.name });
}
}
var categoriesRest = await RestWrapper.Instance.SeedRestApi.SeedCategoriesAsync(categories,"kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");
Console.WriteLine($"{categories.Count} ProductCategory Added Success !");
//CREATE BRAND PART
List<SeedBrandRequestDto> brands = new List<SeedBrandRequestDto>();
foreach (var taxonomy in termTaxonomies)
{
if (taxonomy.taxonomy == "pa_brand")
{
var term = terms.FirstOrDefault(t => t.term_id == taxonomy.term_id);
if (term != null)
brands.Add(new SeedBrandRequestDto{BaseBrandId = term.term_id.ToInt(),Description = taxonomy.description,Name = term.name});
}
}
var brandsRest = await RestWrapper.Instance.SeedRestApi.SeedBrandsAsync(brands, "kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");
Console.WriteLine($"{brands.Count} Brand Added Success !");
//CREATE PRODUCT PART
List<CreateProductCommand> products = new List<CreateProductCommand>();
foreach (var wordPressPostDto in posts.Where(p => p.post_type == "product"))
{
CreateProductCommand product;
Guid brandId = default;
Guid categoryId = default;
var postTermRelations = termRelationships.Where(p => p.object_id == wordPressPostDto.ID);
foreach (var postTermRelation in postTermRelations)
{
var taxanomy = termTaxonomies.FirstOrDefault(f => f.term_taxonomy_id == postTermRelation.term_taxonomy_id);
if (taxanomy != null)
{
if (taxanomy.taxonomy == "pa_brand")
brandId = brandsRest.FirstOrDefault(f => f.Key == taxanomy.term_id.ToInt()).Value;
if (taxanomy.taxonomy == "product_cat")
categoryId = categoriesRest.FirstOrDefault(c => c.Key == taxanomy.term_id.ToInt()).Value;
}
}
if (brandId == default)
brandId = brandsRest.FirstOrDefault(f => f.Key == 0).Value;
if (categoryId == default)
categoryId = categoriesRest.FirstOrDefault(c => c.Key == 0).Value;
var price = postMetas.FirstOrDefault(pm => pm.post_id == wordPressPostDto.ID && pm.meta_key == "_price");
if (price != null && double.TryParse(price.meta_value, out double dPrice))
product = new CreateProductCommand(wordPressPostDto.post_title, string.Empty, wordPressPostDto.post_content,
wordPressPostDto.post_excerpt, string.Empty, string.Empty, true, dPrice, 0,
brandId, string.Empty, categoryId,
new List<SpecificationSDto>(), new List<StorageFileSDto>());
else
product = new CreateProductCommand(wordPressPostDto.post_title, string.Empty, wordPressPostDto.post_content,
wordPressPostDto.post_excerpt, string.Empty, string.Empty, true, 0, 0,
brandId, string.Empty, categoryId,
new List<SpecificationSDto>(), new List<StorageFileSDto>());
products.Add(product);
}
for (int i = 0; i < products.Count / 50 ; i++)
{
await RestWrapper.Instance.SeedRestApi.SeedProductsAsync(products.Skip(i * 50).Take(50).ToList(),
"kKAYskyG8xPxKnJrHkuYxub4Ao2bnz7AOmNtwDT0RaqzaG7ZvbvaP29tCrC8wJ823RczJFXOIQT2bDOec4F38A==");
Console.WriteLine($"{i*50} / {products.Count} Product Added Success !");
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}

View File

@ -0,0 +1,17 @@
using NetinaShop.Domain.CommandQueries.Commands;
using NetinaShop.Domain.Dtos.RequestDtos.SeedDtos;
using Refit;
namespace NetinaShop.WordPressDBConverter.Services.RestServices;
public interface ISeedRestApi
{
[Post("/categories")]
Task<Dictionary<int, Guid>> SeedCategoriesAsync([Body] List<SeedCategoryRequestDto> request, [Query] string key);
[Post("/brands")]
Task<Dictionary<int, Guid>> SeedBrandsAsync([Body] List<SeedBrandRequestDto> request, [Query] string key);
[Post("/products")]
Task SeedProductsAsync([Body] List<CreateProductCommand> request, [Query] string key);
}

View File

@ -0,0 +1,11 @@
using Refit;
namespace NetinaShop.WordPressDBConverter.Services.RestServices;
public class RestWrapper
{
private static RestWrapper? _instance;
public static RestWrapper Instance => _instance = _instance ?? new RestWrapper();
public ISeedRestApi SeedRestApi => RestService.For<ISeedRestApi>("http://localhost:32770/api/seed");
}