Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,21 @@ public async Task<IActionResult> Post([FromBody] CustomerGroupDto model)
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CustomerGroupDto))]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Put([FromBody] CustomerGroupDto model)
{
if (string.IsNullOrEmpty(model.Id))
return BadRequest("Key is null or empty");

if (!await _permissionService.Authorize(PermissionSystemName.Customers)) return Forbid();

if (!model.IsSystem)
{
model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model });
return Ok(model);
}
var customerGroup = await _mediator.Send(new GetGenericQuery<CustomerGroupDto, CustomerGroup>(model.Id));
if (!customerGroup.Any()) return NotFound();

if (customerGroup.FirstOrDefault()!.IsSystem) return BadRequest(ModelState);

return BadRequest(ModelState);
model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model });
return Ok(model);
}

[EndpointDescription("Partially update entity in CustomerGroup")]
Expand All @@ -104,14 +108,11 @@ public async Task<IActionResult> Patch([FromRoute] string key, [FromBody] JsonPa
if (!customerGroup.Any()) return NotFound();

var cr = customerGroup.FirstOrDefault();
model.ApplyTo(cr);
if (cr is { IsSystem: false })
{
await _mediator.Send(new UpdateCustomerGroupCommand { Model = cr });
return Ok();
}
if (cr!.IsSystem) return BadRequest(ModelState);

return BadRequest(ModelState);
model.ApplyTo(cr);
await _mediator.Send(new UpdateCustomerGroupCommand { Model = cr });
return Ok();
}

[EndpointDescription("Delete entity in CustomerGroup")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public class CustomerGroupProfile : Profile, IAutoMapperProfile
public CustomerGroupProfile()
{
CreateMap<CustomerGroupDto, CustomerGroup>()
.ForMember(dest => dest.UserFields, mo => mo.Ignore());
.ForMember(dest => dest.UserFields, mo => mo.Ignore())
.ForMember(dest => dest.IsSystem, mo => mo.Ignore());

CreateMap<CustomerGroup, CustomerGroupDto>();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
{
CustomerId: cust-001,
ProductId: prod-001,
IsApproved: true,
Title: Great product,
ReviewText: Really impressed!,
ReplyText: Thank you!,
ConfirmedPurchase: false,
Rating: 5,
Id: ObjectId_1
}
Original file line number Diff line number Diff line change
Expand Up @@ -320,17 +320,28 @@ public Task PredefinedAttributeValue_ToProductAttributeValue()
public Task ProductReviewModel_ToDomain()
{
var model = new ProductReviewModel {
CustomerId = "cust-001",
ProductId = "prod-001",
IsApproved = true,
Title = "Great product",
ReviewText = "Really impressed!",
ReplyText = "Thank you!",
Rating = 5
ReplyText = "Thank you!"
};
return Verify(_mapper.Map<ProductReview>(model));
}

[TestMethod]
public void ProductReviewModel_ToDomain_KeepsStoredFacts()
{
var review = new ProductReview { ProductId = "prod-001", CustomerId = "cust-001", Rating = 4 };
var model = new ProductReviewModel { ProductId = "prod-002", CustomerId = "cust-002", Rating = 1, Title = "Edited" };

_mapper.Map(model, review);

Assert.AreEqual("prod-001", review.ProductId);
Assert.AreEqual("cust-001", review.CustomerId);
Assert.AreEqual(4, review.Rating);
Assert.AreEqual("Edited", review.Title);
}

// ── SpecificationAttribute ────────────────────────────────────────────────

[TestMethod]
Expand Down
19 changes: 19 additions & 0 deletions src/Tests/Grand.Mapping.Tests/AdminShared/CustomerMappingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,25 @@ public Task CustomerGroupModel_ToDomain()
return Verify(_mapper.Map<CustomerGroup>(model));
}

[TestMethod]
public void CustomerGroupModel_ToDomain_KeepsStoredIsSystem()
{
var group = new CustomerGroup { Id = "cg-001", Name = "Administrators", SystemName = "Administrators", IsSystem = true };
var model = new CustomerGroupModel { Id = "cg-001", Name = "Administrators", SystemName = "Administrators", IsSystem = false };

_mapper.Map(model, group);

Assert.IsTrue(group.IsSystem);
}

[TestMethod]
public void CustomerGroupModel_ToDomain_NewGroupIsNotSystem()
{
var model = new CustomerGroupModel { Name = "VIP Customers", SystemName = "vip", IsSystem = true };

Assert.IsFalse(_mapper.Map<CustomerGroup>(model).IsSystem);
}

// ── CustomerAttribute ─────────────────────────────────────────────────────

[TestMethod]
Expand Down
19 changes: 19 additions & 0 deletions src/Tests/Grand.Mapping.Tests/Api/ApiMappingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,25 @@ public Task CustomerGroupDto_ToEntity()
return Verify(_mapper.Map<CustomerGroup>(dto));
}

[TestMethod]
public void CustomerGroupDto_ToEntity_KeepsStoredIsSystem()
{
var group = new CustomerGroup { Id = "cg-1", Name = "Administrators", SystemName = "Administrators", IsSystem = true };
var dto = new CustomerGroupDto { Id = "cg-1", Name = "Administrators", SystemName = "Administrators", IsSystem = false };

_mapper.Map(dto, group);

Assert.IsTrue(group.IsSystem);
}

[TestMethod]
public void CustomerGroupDto_ToEntity_NewGroupIsNotSystem()
{
var dto = new CustomerGroupDto { Name = "VIP Customers", SystemName = "Vip", IsSystem = true };

Assert.IsFalse(_mapper.Map<CustomerGroup>(dto).IsSystem);
}

[TestMethod]
public Task CustomerGroup_ToDto()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Customers;
using Grand.Mediator;
using Grand.Module.Api.Commands.Models.Customers;
using Grand.Module.Api.Controllers;
using Grand.Module.Api.DTOs.Customers;
using Grand.Module.Api.Queries.Models.Common;
using Microsoft.AspNetCore.JsonPatch.SystemTextJson;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Module.Api.Tests.Controllers;

[TestClass]
public class CustomerGroupControllerTests
{
private Mock<IMediator> _mediatorMock;
private CustomerGroupController _controller;

[TestInitialize]
public void Init()
{
_mediatorMock = new Mock<IMediator>();
var permissionService = new Mock<IPermissionService>();
permissionService.Setup(p => p.Authorize(It.IsAny<string>())).ReturnsAsync(true);
_controller = new CustomerGroupController(_mediatorMock.Object, permissionService.Object);
}

private void SetupStoredGroup(CustomerGroupDto group)
{
_mediatorMock.Setup(m => m.Send(It.IsAny<GetGenericQuery<CustomerGroupDto, CustomerGroup>>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync((group is null ? [] : new[] { group }).AsQueryable());
}

[TestMethod]
public async Task Put_StoredSystemGroup_ReturnsBadRequestWithoutUpdating()
{
SetupStoredGroup(new CustomerGroupDto { Id = "cg-1", Name = "Administrators", IsSystem = true });

var result = await _controller.Put(new CustomerGroupDto { Id = "cg-1", Name = "Renamed", IsSystem = false });

Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
_mediatorMock.Verify(m => m.Send(It.IsAny<UpdateCustomerGroupCommand>(), It.IsAny<CancellationToken>()),
Times.Never);
}

[TestMethod]
public async Task Put_StoredGroupIsNotSystem_Updates()
{
SetupStoredGroup(new CustomerGroupDto { Id = "cg-2", Name = "VIP" });

var result = await _controller.Put(new CustomerGroupDto { Id = "cg-2", Name = "VIP Customers" });

Assert.IsInstanceOfType(result, typeof(OkObjectResult));
_mediatorMock.Verify(m => m.Send(It.Is<UpdateCustomerGroupCommand>(c => c.Model.Id == "cg-2"),
It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task Put_UnknownGroup_ReturnsNotFound()
{
SetupStoredGroup(null);

var result = await _controller.Put(new CustomerGroupDto { Id = "cg-missing", Name = "VIP" });

Assert.IsInstanceOfType(result, typeof(NotFoundResult));
}

[TestMethod]
public async Task Put_WithoutId_ReturnsBadRequest()
{
var result = await _controller.Put(new CustomerGroupDto { Name = "VIP" });

Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
_mediatorMock.Verify(m => m.Send(It.IsAny<UpdateCustomerGroupCommand>(), It.IsAny<CancellationToken>()),
Times.Never);
}

[TestMethod]
public async Task Patch_StoredSystemGroup_ReturnsBadRequestWithoutUpdating()
{
SetupStoredGroup(new CustomerGroupDto { Id = "cg-1", Name = "Administrators", IsSystem = true });
var patch = new JsonPatchDocument<CustomerGroupDto>();
patch.Replace(x => x.IsSystem, false);

var result = await _controller.Patch("cg-1", patch);

Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
_mediatorMock.Verify(m => m.Send(It.IsAny<UpdateCustomerGroupCommand>(), It.IsAny<CancellationToken>()),
Times.Never);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,41 @@ public async Task EditPost_Admin_DoesNotForceLimitedToStores()
Assert.IsFalse(saved.LimitedToStores);
}

[TestMethod]
public async Task EditPost_KeepsStoredNameRegardlessOfSubmittedModel()
{
var template = new MessageTemplate { Id = "mt-1", Name = "OrderPlaced.CustomerNotification" };
_messageTemplateService.Setup(s => s.GetMessageTemplateById("mt-1")).ReturnsAsync(template);
_scope.Setup(s => s.HasAccess(template)).ReturnsAsync(true);

MessageTemplate saved = null;
_messageTemplateService.Setup(s => s.UpdateMessageTemplate(It.IsAny<MessageTemplate>()))
.Callback<MessageTemplate>(t => saved = t)
.Returns(Task.CompletedTask);

var model = new MessageTemplateModel { Id = "mt-1", Name = "Customer.PasswordRecovery" };
await CreateController().Edit(model, false);

Assert.IsNotNull(saved);
Assert.AreEqual("OrderPlaced.CustomerNotification", saved.Name);
}

[TestMethod]
public async Task EditPost_InvalidModel_KeepsSubmittedAttachmentSwitch()
{
var template = new MessageTemplate { Id = "mt-1", Name = "N", AttachedDownloadId = "dl-1" };
_messageTemplateService.Setup(s => s.GetMessageTemplateById("mt-1")).ReturnsAsync(template);
_scope.Setup(s => s.HasAccess(template)).ReturnsAsync(true);

var controller = CreateController();
controller.ModelState.AddModelError("Subject", "required");
var model = new MessageTemplateModel { Id = "mt-1", AttachedDownloadId = "dl-1", HasAttachedDownload = false };
var result = await controller.Edit(model, false) as ViewResult;

Assert.IsNotNull(result);
Assert.IsFalse(((MessageTemplateModel)result.Model).HasAttachedDownload);
}

[TestMethod]
public async Task Delete_HasAccessFalse_DoesNotDelete()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Catalog;
using Grand.Mediator;
using Grand.Web.AdminShared.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Grand.Web.Admin.Tests.Services;

[TestClass]
public class ProductReviewViewModelServiceTests
{
private Mock<IMediator> _mediator;
private Mock<IProductReviewService> _productReviewService;
private Mock<IProductService> _productService;
private ProductReviewViewModelService _service;

[TestInitialize]
public void Init()
{
_mediator = new Mock<IMediator>();
_productReviewService = new Mock<IProductReviewService>();
_productService = new Mock<IProductService>();
_productService.Setup(x => x.GetProductById(It.IsAny<string>(), It.IsAny<bool>()))
.ReturnsAsync((string id, bool _) => new Product { Id = id });

_service = new ProductReviewViewModelService(_productService.Object, _productReviewService.Object,
Mock.Of<ICustomerService>(), Mock.Of<IStoreService>(), Mock.Of<IDateTimeService>(),
Mock.Of<ITranslationService>(), _mediator.Object);
}

[TestMethod]
public async Task ApproveSelected_UpdatesTotalsOfReviewsOwnProduct()
{
_productReviewService.Setup(x => x.GetProductReviewById("pr-1"))
.ReturnsAsync(new ProductReview { Id = "pr-1", ProductId = "prod-1", StoreId = "store-1" });

await _service.ApproveSelected(["pr-1:prod-other"], "store-1");

_mediator.Verify(x => x.Send(It.Is<UpdateProductReviewTotalsCommand>(c => c.Product.Id == "prod-1"),
It.IsAny<CancellationToken>()), Times.Once);
_productService.Verify(x => x.GetProductById("prod-other", It.IsAny<bool>()), Times.Never);
}

[TestMethod]
public async Task DisapproveSelected_UpdatesTotalsOfReviewsOwnProduct()
{
_productReviewService.Setup(x => x.GetProductReviewById("pr-1"))
.ReturnsAsync(new ProductReview { Id = "pr-1", ProductId = "prod-1", StoreId = "store-1", IsApproved = true });

await _service.DisapproveSelected(["pr-1"], "store-1");

_mediator.Verify(x => x.Send(It.Is<UpdateProductReviewTotalsCommand>(c => c.Product.Id == "prod-1"),
It.IsAny<CancellationToken>()), Times.Once);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
@model CustomerGroupModel
@* one card of two-column fields; IsSystem is not editable, so it reads as a fact and posts back
through its hidden input *@
@* one card of two-column fields; IsSystem is not editable, so it reads as a fact and is never posted *@
<admin-card>
<div class="grand-fields grand-fields--2col">
<admin-field asp-for="Name"/>
Expand All @@ -18,5 +17,4 @@
<div class="grand-fact__value">@Model.IsSystem.ToString()</div>
</div>
</div>
<input asp-for="IsSystem" type="hidden"/>
</admin-card>
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
</grid-column>
<grid-column field="Title" title="@Loc["Admin.Catalog.ProductReviews.Fields.Title"]" width="200">
<cell-template>
<a class="text-decoration-none" href="Edit/{{ Id }}?ProductId={{ ProductId }}">{{ Title }}</a>
<a class="text-decoration-none" href="Edit/{{ Id }}">{{ Title }}</a>
</cell-template>
</grid-column>
<grid-column field="Rating" title="@Loc["Admin.Catalog.ProductReviews.Fields.Rating"]" width="60" min-screen-width="750"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ public async Task<IActionResult> Edit(CustomerGroupModel model, bool continueEdi
}

//If we got this far, something failed, redisplay form
model.IsSystem = customerGroup.IsSystem;
return View(model);
}
catch (Exception exc)
Expand Down
Loading
Loading