Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
ntruchsess committed Sep 8, 2023
1 parent 3fad491 commit ccecc86
Show file tree
Hide file tree
Showing 7 changed files with 171 additions and 63 deletions.
2 changes: 1 addition & 1 deletion src/mailing/Mailing.Service/IRoleBaseMailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Mailing.Service;

public interface IRoleBaseMailService
{
public Task RoleBaseSendMail(IEnumerable<UserRoleConfig> receiverRoles, IDictionary<string, string> parameters, IEnumerable<string> template, Guid companyId);
Task RoleBaseSendMail(IEnumerable<UserRoleConfig> receiverRoles, IEnumerable<(string ParameterName, string ParameterValue)> parameters, (string ParameterName, string ParameterValue)? userNameParameter, IEnumerable<string> template, Guid companyId);
}
20 changes: 14 additions & 6 deletions src/mailing/Mailing.Service/RoleBaseMailService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using Org.Eclipse.TractusX.Portal.Backend.Mailing.SendMail;
using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess;
using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories;
using System.Collections.Immutable;

namespace Org.Eclipse.TractusX.Portal.Backend.Mailing.Service;

Expand All @@ -37,7 +38,7 @@ public RoleBaseMailService(IPortalRepositories portalRepositories, IMailingServi
_portalRepositories = portalRepositories;
_mailingService = mailingService;
}
public async Task RoleBaseSendMail(IEnumerable<UserRoleConfig> receiverRoles, IDictionary<string, string> parameters, IEnumerable<string> template, Guid companyId)
public async Task RoleBaseSendMail(IEnumerable<UserRoleConfig> receiverRoles, IEnumerable<(string ParameterName, string ParameterValue)> parameters, (string ParameterName, string ParameterValue)? userNameParameter, IEnumerable<string> template, Guid companyId)
{
var receiverUserRoles = receiverRoles;
var userRolesRepository = _portalRepositories.GetInstance<IUserRolesRepository>();
Expand All @@ -53,16 +54,23 @@ public async Task RoleBaseSendMail(IEnumerable<UserRoleConfig> receiverRoles, ID

var companyUserWithRoleIdForCompany = _portalRepositories.GetInstance<IUserRepository>()
.GetCompanyUserEmailForCompanyAndRoleId(roleData, companyId);

await foreach (var (receiver, firstName, lastName) in companyUserWithRoleIdForCompany)
{
var userName = string.Join(" ", new[] { firstName, lastName }.Where(item => !string.IsNullOrWhiteSpace(item)));

if (!string.IsNullOrWhiteSpace(userName) && parameters.Keys.Contains("offerProviderName"))
IEnumerable<(string ParameterName, string ParameterValue)> ParametersWithUserName()
{
parameters["offerProviderName"] = userName;
if (userNameParameter.HasValue)
{
var userName = string.Join(" ", new[] { firstName, lastName }.Where(item => !string.IsNullOrWhiteSpace(item)));
return parameters.Append(
string.IsNullOrWhiteSpace(userName)
? userNameParameter.Value
: new(userNameParameter.Value.ParameterName, userName));
}
return parameters;
}

await _mailingService.SendMails(receiver, parameters, template).ConfigureAwait(false);
await _mailingService.SendMails(receiver, ParametersWithUserName().ToImmutableDictionary(x => x.ParameterName, x => x.ParameterValue), template).ConfigureAwait(false);
}
}
}
27 changes: 18 additions & 9 deletions src/marketplace/Offers.Library/Service/OfferService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -559,21 +559,30 @@ public async Task DeclineOfferAsync(Guid offerId, Guid userId, OfferDeclineReque
DeclineMessage = data.Message
};

var serializeNotificationContent = JsonSerializer.Serialize(notificationContent);
var content = Enumerable.Repeat(notificationTypeId, 1).Select(typeId => new ValueTuple<string?, NotificationTypeId>(serializeNotificationContent, typeId));
var content = new (string?, NotificationTypeId)[]
{
(JsonSerializer.Serialize(notificationContent), notificationTypeId)
};

await _notificationService.CreateNotifications(notificationRecipients, userId, content, declineData.CompanyId.Value).AwaitAll().ConfigureAwait(false);
await _notificationService.SetNotificationsForOfferToDone(catenaAdminRoles, submitOfferNotificationTypeIds, offerId).ConfigureAwait(false);

await _portalRepositories.SaveAsync().ConfigureAwait(false);

var mailParams = new Dictionary<string, string>
await _roleBaseMailService.RoleBaseSendMail(
notificationRecipients,
new[]
{
{ "offerName", declineData.OfferName },
{ "url", basePortalAddress },
{ "declineMessage", data.Message },
{ "offerProviderName", "Service Manager"},
};
await _roleBaseMailService.RoleBaseSendMail(notificationRecipients, mailParams, new List<string> { "offer-request-decline" }, declineData.CompanyId.Value).ConfigureAwait(false);
("offerName", declineData.OfferName),
("url", basePortalAddress),
("declineMessage", data.Message),
},
("offerProviderName", "Service Manager"),
new[]
{
"offer-request-decline"
},
declineData.CompanyId.Value).ConfigureAwait(false);
}

private async Task CheckLanguageCodesExist(IEnumerable<string> languageCodes)
Expand Down
19 changes: 13 additions & 6 deletions src/marketplace/Offers.Library/Service/OfferSubscriptionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,20 @@ public async Task<Guid> AddOfferSubscriptionAsync(Guid offerId, IEnumerable<Offe
CreateConsentsForSubscription(offerSubscription.Id, offerAgreementConsentData, companyInformation.CompanyId, identity.UserId);
await _portalRepositories.SaveAsync().ConfigureAwait(false);

var mailParams = new Dictionary<string, string>
await _roleBaseMailService.RoleBaseSendMail(
notificationRecipients,
new[]
{
{ "offerName", offerProviderDetails.OfferName! },
{ "offerProviderName", "User"},
{ "url", basePortalAddress }
};
await _roleBaseMailService.RoleBaseSendMail(notificationRecipients, mailParams, new List<string> { "subscription-request" }, offerProviderDetails.ProviderCompanyId.Value).ConfigureAwait(false);
("offerName", offerProviderDetails.OfferName!),
("url", basePortalAddress)
},
("offerProviderName", "User"),
new[]
{
"subscription-request"
},
offerProviderDetails.ProviderCompanyId.Value).ConfigureAwait(false);

return offerSubscription.Id;
}

Expand Down
69 changes: 42 additions & 27 deletions tests/mailing/Mailing.Service.Tests/RoleBaseMailServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,50 +57,65 @@ public RoleBaseMailServiceTests()
_sut = new RoleBaseMailService(_portalRepositories, _mailingService);
}

[Fact]
public async Task RoleBaseSendMail_ReturnsExpectedCalls()
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task RoleBaseSendMail_WithUserNameParameter_ReturnsExpectedCalls(bool hasUserNameParameter)
{
// Arrange
var template = new List<string> { "test-request" };
var mailParams = new Dictionary<string, string>
{
{ "offerName", _fixture.Create<string>() },
{ "url", BasePortalUrl},
{ "offerProviderName", "user"},
};
var receiverRoles = new[]{
new UserRoleConfig("ClientId", new [] { "TestApp Manager", "TestSale Manager" })
var template = new[] { "test-request" };
var offerName = _fixture.Create<string>();
var mailParams = new[]
{
("offerName", offerName),
("url", BasePortalUrl)
};
var userNameParam = hasUserNameParameter
? ("offerProviderName", "user")
: ((string, string)?)null;
var receiverRoles = new[]
{
new UserRoleConfig("ClientId", new[] { "TestApp Manager", "TestSale Manager" })
};
var companyUserData = new[]{
new ValueTuple<string, string?, string?>("TestApp@bmw","AppFirst","AppLast"),
new ValueTuple<string, string?, string?>("TestSale@bmw","SaleFirst","SaleLast")
var companyUserData = new (string, string?, string?)[]
{
("TestApp@bmw", "AppFirst", "AppLast"),
("TestSale@bmw", "SaleFirst", "SaleLast")
};

A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A<IEnumerable<UserRoleConfig>>.That.Matches(x => x.Any(y => y.ClientId == "ClientId"))))
A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A<IEnumerable<UserRoleConfig>>._))
.Returns(_userRoleIds.ToAsyncEnumerable());
A.CallTo(() => _userRepository.GetCompanyUserEmailForCompanyAndRoleId(A<IEnumerable<Guid>>.That.IsSameSequenceAs(_userRoleIds), _companyId))
A.CallTo(() => _userRepository.GetCompanyUserEmailForCompanyAndRoleId(A<IEnumerable<Guid>>._, A<Guid>._))
.Returns(companyUserData.ToAsyncEnumerable());

// Act
await _sut.RoleBaseSendMail(receiverRoles, mailParams, template, _companyId);
await _sut.RoleBaseSendMail(receiverRoles, mailParams, userNameParam, template, _companyId);

// Assert
A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A<IEnumerable<UserRoleConfig>>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => _userRepository.GetCompanyUserEmailForCompanyAndRoleId(A<IEnumerable<Guid>>._, _companyId)).MustHaveHappenedOnceExactly();
A.CallTo(() => _mailingService.SendMails(A<string>._, A<IDictionary<string, string>>._, A<IEnumerable<string>>._)).MustHaveHappenedTwiceExactly();
A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A<IEnumerable<UserRoleConfig>>.That.Matches(x => x.Any(y => y.ClientId == "ClientId")))).MustHaveHappenedOnceExactly();
A.CallTo(() => _userRepository.GetCompanyUserEmailForCompanyAndRoleId(A<IEnumerable<Guid>>.That.IsSameSequenceAs(_userRoleIds), _companyId)).MustHaveHappenedOnceExactly();
A.CallTo(() => _mailingService.SendMails(
"TestApp@bmw",
A<IDictionary<string, string>>.That.Matches(x => x.Count() == (hasUserNameParameter ? 3 : 2) && x["offerName"] == offerName && x["url"] == BasePortalUrl && (!hasUserNameParameter || x["offerProviderName"] == "AppFirst AppLast")),
A<IEnumerable<string>>.That.IsSameSequenceAs(template))).MustHaveHappenedOnceExactly();
A.CallTo(() => _mailingService.SendMails(
"TestSale@bmw",
A<IDictionary<string, string>>.That.Matches(x => x.Count() == (hasUserNameParameter ? 3 : 2) && x["offerName"] == offerName && x["url"] == BasePortalUrl && (!hasUserNameParameter || x["offerProviderName"] == "SaleFirst SaleLast")),
A<IEnumerable<string>>.That.IsSameSequenceAs(template))).MustHaveHappenedOnceExactly();
}

[Fact]
public async Task RoleBaseSendMail_ThrowsConfigurationException()
{
// Arrange
var template = new List<string> { "test-request" };
var mailParams = new Dictionary<string, string>
{
{ "offerName", _fixture.Create<string>() },
{ "url", BasePortalUrl},
{ "offerProviderName", "user"},
};
var mailParams = new[]
{
("offerName", _fixture.Create<string>()),
("url", BasePortalUrl),
};
var userNameParam = ("offerProviderName", "user");

var roleData = _fixture.CreateMany<Guid>(1);
var receiverRoles = new[]{
new UserRoleConfig("ClientId", new [] { "App Manager", "Sales Manager" })
Expand All @@ -110,7 +125,7 @@ public async Task RoleBaseSendMail_ThrowsConfigurationException()
.Returns(roleData.ToAsyncEnumerable());

// Act
async Task Action() => await _sut.RoleBaseSendMail(receiverRoles, mailParams, template, _companyId);
async Task Action() => await _sut.RoleBaseSendMail(receiverRoles, mailParams, userNameParam, template, _companyId);

// Assert
var ex = await Assert.ThrowsAsync<ConfigurationException>(Action);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1111,15 +1111,20 @@ public async Task DeclineOfferAsync_WithValidData_CallsExpected(OfferTypeId offe
// Arrange
var offer = _fixture.Create<Offer>();
var offerId = _fixture.Create<Guid>();
var recipients = new[] { new UserRoleConfig("Test", new[] { "Abc" }) };
var recipients = new[]
{
new UserRoleConfig("Test", new[] { "Abc" })
};
var roleIds = _fixture.CreateMany<Guid>();
var documentStatusDatas = new DocumentStatusData[]
{
new(Guid.NewGuid(), DocumentStatusId.LOCKED),
new(Guid.NewGuid(), DocumentStatusId.PENDING),
};
var companyId = Guid.NewGuid();
var offerName = _fixture.Create<string>();
A.CallTo(() => _offerRepository.GetOfferDeclineDataAsync(offerId, offerTypeId))
.Returns(("test", OfferStatusId.IN_REVIEW, Guid.NewGuid(), documentStatusDatas));
.Returns((offerName, OfferStatusId.IN_REVIEW, companyId, documentStatusDatas));
A.CallTo(() => _offerRepository.AttachAndModifyOffer(offerId, A<Action<Offer>>._, A<Action<Offer>?>._))
.Invokes((Guid _, Action<Offer> setOptionalParameters, Action<Offer>? initializeParemeters) =>
{
Expand All @@ -1129,7 +1134,7 @@ public async Task DeclineOfferAsync_WithValidData_CallsExpected(OfferTypeId offe
A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A<IEnumerable<UserRoleConfig>>._))
.Returns(roleIds.ToAsyncEnumerable());
A.CallTo(() => _userRepository.GetCompanyUserEmailForCompanyAndRoleId(A<IEnumerable<Guid>>._, A<Guid>._))
.Returns(new (string Email, string? Firstname, string? Lastname)[] { new("test@email.com", "Test User 1", "cx-user-2") }.ToAsyncEnumerable());
.Returns(new[] { ("test@email.com", (string?)"Test User 1", (string?)"cx-user-2") }.ToAsyncEnumerable());

IEnumerable<Document>? initial = null;
IEnumerable<Document>? modified = null;
Expand All @@ -1152,15 +1157,35 @@ public async Task DeclineOfferAsync_WithValidData_CallsExpected(OfferTypeId offe
).ToImmutableArray();
});

var declineMessage = _fixture.Create<string>();
var basePortalAddress = _fixture.Create<string>();

var mailParameters = new[]
{
("offerName", offerName),
("url", basePortalAddress),
("declineMessage", declineMessage)
};
var userNameParameter = ("offerProviderName", "Service Manager");
var template = new[]
{
"offer-request-decline"
};

// Act
await _sut.DeclineOfferAsync(offerId, _identity.UserId, new OfferDeclineRequest("Test"), offerTypeId, NotificationTypeId.SERVICE_RELEASE_REJECTION, recipients, string.Empty, new[] { NotificationTypeId.APP_SUBSCRIPTION_REQUEST }, _fixture.CreateMany<UserRoleConfig>()).ConfigureAwait(false);
await _sut.DeclineOfferAsync(offerId, _identity.UserId, new OfferDeclineRequest(declineMessage), offerTypeId, NotificationTypeId.SERVICE_RELEASE_REJECTION, recipients, basePortalAddress, new[] { NotificationTypeId.APP_SUBSCRIPTION_REQUEST }, _fixture.CreateMany<UserRoleConfig>()).ConfigureAwait(false);

// Assert
A.CallTo(() => _offerRepository.AttachAndModifyOffer(offerId, A<Action<Offer>>._, A<Action<Offer>?>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly();
A.CallTo(() => _notificationService.CreateNotifications(A<IEnumerable<UserRoleConfig>>._, A<Guid>._, A<IEnumerable<(string? content, NotificationTypeId notificationTypeId)>>._, A<Guid>._, A<bool?>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => _createNotificationsEnumerator.MoveNextAsync()).MustHaveHappened(2, Times.Exactly);
A.CallTo(() => _roleBaseMailService.RoleBaseSendMail(A<IEnumerable<UserRoleConfig>>._, A<IDictionary<string, string>>._, A<IEnumerable<string>>._, A<Guid>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => _roleBaseMailService.RoleBaseSendMail(
A<IEnumerable<UserRoleConfig>>.That.IsSameSequenceAs(recipients),
A<IEnumerable<(string, string)>>.That.IsSameSequenceAs(mailParameters),
userNameParameter,
A<IEnumerable<string>>.That.IsSameSequenceAs(template),
companyId)).MustHaveHappenedOnceExactly();
offer.OfferStatusId.Should().Be(OfferStatusId.CREATED);
A.CallTo(() => _documentRepository.AttachAndModifyDocuments(A<IEnumerable<(Guid, Action<Document>?, Action<Document>)>>._)).MustHaveHappenedOnceExactly();
initial.Should().HaveCount(2).And.Satisfy(
Expand Down
Loading

0 comments on commit ccecc86

Please sign in to comment.