-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPaymentRequestAppService.cs
More file actions
563 lines (481 loc) · 24.7 KB
/
PaymentRequestAppService.cs
File metadata and controls
563 lines (481 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Unity.Payments.Domain.Exceptions;
using Unity.Payments.Domain.PaymentConfigurations;
using Unity.Payments.Domain.PaymentRequests;
using Unity.Payments.Domain.Services;
using Unity.Payments.Domain.Shared;
using Unity.Payments.Enums;
using Unity.Payments.Permissions;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Data;
using Volo.Abp.Features;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Users;
using Unity.Payments.Domain.PaymentThresholds;
using Volo.Abp.Domain.Repositories;
using Unity.GrantManager.Applications;
namespace Unity.Payments.PaymentRequests
{
[RequiresFeature("Unity.Payments")]
[Authorize]
#pragma warning disable S107 // Suppress "Constructor has too many parameters"
public class PaymentRequestAppService(
ICurrentUser currentUser,
IDataFilter dataFilter,
IExternalUserLookupServiceProvider externalUserLookupServiceProvider,
IApplicationRepository applicationRepository,
IApplicationFormRepository applicationFormRepository,
IPaymentConfigurationRepository paymentConfigurationRepository,
IPaymentsManager paymentsManager,
IPaymentRequestRepository paymentRequestsRepository,
IPaymentThresholdRepository paymentThresholdRepository,
IPermissionChecker permissionChecker) : PaymentsAppService, IPaymentRequestAppService
#pragma warning restore S107
{
public async Task<Guid?> GetDefaultAccountCodingId()
{
Guid? accountCodingId = null;
// If no account coding is found look up the payment configuration
PaymentConfiguration? paymentConfiguration = await GetPaymentConfigurationAsync();
if (paymentConfiguration != null && paymentConfiguration.DefaultAccountCodingId.HasValue)
{
accountCodingId = paymentConfiguration.DefaultAccountCodingId;
}
return accountCodingId;
}
[Authorize(PaymentsPermissions.Payments.RequestPayment)]
public virtual async Task<List<PaymentRequestDto>> CreateAsync(List<CreatePaymentRequestDto> paymentRequests)
{
List<PaymentRequestDto> createdPayments = [];
var paymentConfig = await GetPaymentConfigurationAsync();
var paymentIdPrefix = string.Empty;
if (paymentConfig != null && !paymentConfig.PaymentIdPrefix.IsNullOrEmpty())
{
paymentIdPrefix = paymentConfig.PaymentIdPrefix;
}
var batchNumber = await GetMaxBatchNumberAsync();
var batchName = $"{paymentIdPrefix}_UNITY_BATCH_{batchNumber}";
var currentYear = DateTime.UtcNow.Year;
var nextSequenceNumber = await GetNextSequenceNumberAsync(currentYear);
foreach (var paymentRequestItem in paymentRequests.Select((value, i) => new { i, value }))
{
try
{
// referenceNumber + Chefs Confirmation ID + 6 digit sequence based on sequence number and index
CreatePaymentRequestDto paymentRequestDto = paymentRequestItem.value;
string referenceNumberPrefix = GenerateReferenceNumberPrefixAsync(paymentIdPrefix);
string sequenceNumber = GenerateSequenceNumberAsync(nextSequenceNumber, paymentRequestItem.i);
string referenceNumber = GenerateReferenceNumberAsync(referenceNumberPrefix, sequenceNumber);
string invoiceNumber = GenerateInvoiceNumberAsync(referenceNumberPrefix, paymentRequestDto.InvoiceNumber, sequenceNumber);
paymentRequestDto.InvoiceNumber = invoiceNumber;
paymentRequestDto.ReferenceNumber = referenceNumber;
paymentRequestDto.BatchName = batchName;
paymentRequestDto.BatchNumber = batchNumber;
var payment = new PaymentRequest(Guid.NewGuid(), paymentRequestDto);
var result = await paymentRequestsRepository.InsertAsync(payment);
createdPayments.Add(new PaymentRequestDto()
{
Id = result.Id,
InvoiceNumber = result.InvoiceNumber,
InvoiceStatus = result.InvoiceStatus,
Amount = result.Amount,
PayeeName = result.PayeeName,
SupplierNumber = result.SupplierNumber,
ContractNumber = result.ContractNumber,
CorrelationId = result.CorrelationId,
CorrelationProvider = result.CorrelationProvider,
Description = result.Description,
CreationTime = result.CreationTime,
Status = result.Status,
ReferenceNumber = result.ReferenceNumber,
SubmissionConfirmationCode = result.SubmissionConfirmationCode
});
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
return createdPayments;
}
public async Task<string> GetNextBatchInfoAsync()
{
var paymentConfig = await GetPaymentConfigurationAsync();
var paymentIdPrefix = string.Empty;
if (paymentConfig != null && !paymentConfig.PaymentIdPrefix.IsNullOrEmpty())
{
paymentIdPrefix = paymentConfig.PaymentIdPrefix;
}
var batchNumber = await GetMaxBatchNumberAsync();
var batchName = $"{paymentIdPrefix}_UNITY_BATCH_{batchNumber}";
return batchName;
}
private static string GenerateInvoiceNumberAsync(string referenceNumber, string invoiceNumber, string sequencePart)
{
return $"{referenceNumber}-{invoiceNumber}-{sequencePart}";
}
private static string GenerateReferenceNumberAsync(string referenceNumber, string sequencePart)
{
return $"{referenceNumber}-{sequencePart}";
}
private static string GenerateSequenceNumberAsync(int sequenceNumber, int index)
{
sequenceNumber = sequenceNumber + index;
return sequenceNumber.ToString("D4");
}
private static string GenerateReferenceNumberPrefixAsync(string paymentIdPrefix)
{
var currentYear = DateTime.UtcNow.Year;
var yearPart = currentYear.ToString();
return $"{paymentIdPrefix}-{yearPart}";
}
private async Task<decimal> GetMaxBatchNumberAsync()
{
var paymentRequestList = await paymentRequestsRepository.GetListAsync();
decimal batchNumber = 1; // Lookup max plus 1
if (paymentRequestList != null && paymentRequestList.Count > 0)
{
var maxBatchNumber = paymentRequestList.Max(s => s.BatchNumber);
if (maxBatchNumber > 0)
{
batchNumber = maxBatchNumber + 1;
}
}
return batchNumber;
}
public Task<int> GetPaymentRequestCountBySiteIdAsync(Guid siteId)
{
return paymentRequestsRepository.GetPaymentRequestCountBySiteId(siteId);
}
public virtual async Task<List<PaymentRequestDto>> UpdateStatusAsync(List<UpdatePaymentStatusRequestDto> paymentRequests)
{
List<PaymentRequestDto> updatedPayments = [];
// Check approval batches
var approvalRequests = paymentRequests.Where(r => r.IsApprove).Select(x => x.PaymentRequestId).ToList();
var approvalList = await paymentRequestsRepository.GetListAsync(x => approvalRequests.Contains(x.Id), includeDetails: true);
// Rule AB#26693: Reject Payment Request update batch if violates L1 and L2 separation of duties
if (approvalList.Any(
x => x.Status == PaymentRequestStatus.L2Pending
&& CurrentUser.Id == x.ExpenseApprovals.FirstOrDefault(y => y.Type == ExpenseApprovalType.Level1)?.DecisionUserId))
{
throw new BusinessException(
code: ErrorConsts.L2ApproverRestriction,
message: L[ErrorConsts.L2ApproverRestriction]);
}
foreach (var dto in paymentRequests)
{
try
{
var payment = await paymentRequestsRepository.GetAsync(dto.PaymentRequestId);
if (payment == null)
continue;
if (!string.IsNullOrWhiteSpace(payment.Note) && !string.IsNullOrWhiteSpace(dto.Note))
{
payment.SetNote($"{payment.Note}; {dto.Note}");
}
else
{
payment.SetNote(dto.Note);
}
var triggerAction = await DetermineTriggerActionAsync(dto, payment);
if (triggerAction != PaymentApprovalAction.None)
{
await paymentsManager.UpdatePaymentStatusAsync(dto.PaymentRequestId, triggerAction);
updatedPayments.Add(await CreatePaymentRequestDtoAsync(dto.PaymentRequestId));
}
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
return updatedPayments;
}
private async Task<PaymentApprovalAction> DetermineTriggerActionAsync(
UpdatePaymentStatusRequestDto dto,
PaymentRequest payment)
{
if (payment == null)
{
Logger.LogWarning("Payment is null in DetermineTriggerActionAsync.");
return PaymentApprovalAction.None;
}
try
{
if (await CanPerformLevel1ActionAsync(payment.Status))
return dto.IsApprove ? PaymentApprovalAction.L1Approve : PaymentApprovalAction.L1Decline;
if (await CanPerformLevel2ActionAsync(payment, dto.IsApprove))
return await GetLevel2ApprovalActionAsync(dto, payment);
if (await CanPerformLevel3ActionAsync(payment.Status))
return dto.IsApprove ? PaymentApprovalAction.Submit : PaymentApprovalAction.L3Decline;
}
catch (Exception ex)
{
Logger.LogException(ex);
}
return PaymentApprovalAction.None;
}
private async Task<PaymentApprovalAction> GetLevel2ApprovalActionAsync(UpdatePaymentStatusRequestDto dto, PaymentRequest payment)
{
if (!dto.IsApprove)
return PaymentApprovalAction.L2Decline;
decimal? threshold = null;
try
{
decimal? userPaymentThreshold = await GetUserPaymentThresholdAsync();
threshold = await GetPaymentRequestThresholdByApplicationIdAsync(payment.CorrelationId, userPaymentThreshold);
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to get payment threshold for applicationId: {CorrelationId}", payment.CorrelationId);
}
if (threshold.HasValue && payment.Amount > threshold.Value)
return PaymentApprovalAction.L2Approve;
return PaymentApprovalAction.Submit;
}
public async Task<decimal?> GetPaymentRequestThresholdByApplicationIdAsync(Guid applicationId, decimal? userPaymentThreshold = null)
{
var application = await (await applicationRepository.GetQueryableAsync())
.Include(a => a.ApplicationForm)
.FirstOrDefaultAsync(a => a.Id == applicationId);
if (application == null)
{
throw new BusinessException($"Application with Id {applicationId} not found.");
}
var appForm = application.ApplicationForm ??
(application.ApplicationFormId != Guid.Empty
? await applicationFormRepository.GetAsync(application.ApplicationFormId)
: null);
var formThreshold = appForm?.PaymentApprovalThreshold;
if (formThreshold.HasValue && userPaymentThreshold.HasValue)
{
return Math.Min(formThreshold.Value, userPaymentThreshold.Value);
}
return formThreshold ?? userPaymentThreshold ?? 0m;
}
private async Task<bool> CanPerformLevel1ActionAsync(PaymentRequestStatus status)
{
List<PaymentRequestStatus> level1Approvals = new() { PaymentRequestStatus.L1Pending, PaymentRequestStatus.L1Declined };
return await permissionChecker.IsGrantedAsync(PaymentsPermissions.Payments.L1ApproveOrDecline) && level1Approvals.Contains(status);
}
private async Task<bool> CanPerformLevel2ActionAsync(PaymentRequest payment, bool IsApprove)
{
List<PaymentRequestStatus> level2Approvals = new() { PaymentRequestStatus.L2Pending, PaymentRequestStatus.L2Declined };
// Rule AB#26693: Reject Payment Request update if violates L1 and L2 separation of duties
var IsSameApprover = CurrentUser.Id == payment.ExpenseApprovals.FirstOrDefault(x => x.Type == ExpenseApprovalType.Level1)?.DecisionUserId;
if (IsSameApprover && IsApprove)
{
throw new BusinessException(
code: ErrorConsts.L2ApproverRestriction,
message: L[ErrorConsts.L2ApproverRestriction]);
}
return await permissionChecker.IsGrantedAsync(PaymentsPermissions.Payments.L2ApproveOrDecline) && level2Approvals.Contains(payment.Status);
}
private async Task<bool> CanPerformLevel3ActionAsync(PaymentRequestStatus status)
{
List<PaymentRequestStatus> level3Approvals = new() { PaymentRequestStatus.L3Pending, PaymentRequestStatus.L3Declined };
return await permissionChecker.IsGrantedAsync(PaymentsPermissions.Payments.L3ApproveOrDecline) && level3Approvals.Contains(status);
}
private async Task<PaymentRequestDto> CreatePaymentRequestDtoAsync(Guid paymentRequestId)
{
var payment = await paymentRequestsRepository.GetAsync(paymentRequestId);
return new PaymentRequestDto
{
Id = payment.Id,
InvoiceNumber = payment.InvoiceNumber,
InvoiceStatus = payment.InvoiceStatus,
Amount = payment.Amount,
PayeeName = payment.PayeeName,
SupplierNumber = payment.SupplierNumber,
ContractNumber = payment.ContractNumber,
CorrelationId = payment.CorrelationId,
CorrelationProvider = payment.CorrelationProvider,
Description = payment.Description,
CreationTime = payment.CreationTime,
Status = payment.Status,
ReferenceNumber = payment.ReferenceNumber,
SubmissionConfirmationCode = payment.SubmissionConfirmationCode,
Note = payment.Note
};
}
public async Task<List<PaymentDetailsDto>> GetListByApplicationIdsAsync(List<Guid> applicationIds)
{
var paymentsQueryable = await paymentRequestsRepository.GetQueryableAsync();
var payments = await paymentsQueryable.Include(pr => pr.Site).ToListAsync();
var filteredPayments = payments.Where(pr => applicationIds.Contains(pr.CorrelationId)).ToList();
return ObjectMapper.Map<List<PaymentRequest>, List<PaymentDetailsDto>>(filteredPayments);
}
public async Task<PagedResultDto<PaymentRequestDto>> GetListAsync(PagedAndSortedResultRequestDto input)
{
var totalCount = await paymentRequestsRepository.GetCountAsync();
using (dataFilter.Disable<ISoftDelete>())
{
await paymentRequestsRepository
.GetPagedListAsync(input.SkipCount, input.MaxResultCount, input.Sorting ?? string.Empty, includeDetails: true);
// Include PaymentTags in the query
var paymentsQueryable = await paymentRequestsRepository.GetQueryableAsync();
// Changing this breaks the code so suppressing the warning
#pragma warning disable CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var paymentWithIncludes = await paymentsQueryable
.Include(pr => pr.AccountCoding)
.Include(pr => pr.PaymentTags)
.ThenInclude(pt => pt.Tag)
.ToListAsync();
#pragma warning restore CS8620 // Argument cannot be used for parameter due to differences in the nullability of reference types.
var mappedPayments = await MapToDtoAndLoadDetailsAsync(paymentWithIncludes);
ApplyErrorSummary(mappedPayments);
return new PagedResultDto<PaymentRequestDto>(totalCount, mappedPayments);
}
}
protected internal async Task<List<PaymentRequestDto>> MapToDtoAndLoadDetailsAsync(List<PaymentRequest> paymentsList)
{
var paymentDtos = ObjectMapper.Map<List<PaymentRequest>, List<PaymentRequestDto>>(paymentsList);
// Flatten all DecisionUserIds from ExpenseApprovals across all PaymentRequestDtos
List<Guid> paymentRequesterIds = paymentDtos
.Select(payment => payment.CreatorId)
.OfType<Guid>()
.Distinct()
.ToList();
List<Guid> expenseApprovalCreatorIds = paymentDtos
.SelectMany(payment => payment.ExpenseApprovals)
.Where(expenseApproval => expenseApproval.Status != ExpenseApprovalStatus.Requested)
.Select(expenseApproval => expenseApproval.DecisionUserId)
.OfType<Guid>()
.Distinct()
.ToList();
// Call external lookup for each distinct User Id and store in a dictionary.
var userDictionary = new Dictionary<Guid, PaymentUserDto>();
var allUserIds = paymentRequesterIds.Concat(expenseApprovalCreatorIds).Distinct();
foreach (var userId in allUserIds)
{
var userInfo = await externalUserLookupServiceProvider.FindByIdAsync(userId);
if (userInfo != null)
{
userDictionary[userId] = ObjectMapper.Map<IUserData, PaymentUserDto>(userInfo);
}
}
// Map UserInfo details to each ExpenseApprovalDto
foreach (var paymentRequestDto in paymentDtos)
{
if (paymentRequestDto.CreatorId.HasValue
&& userDictionary.TryGetValue(paymentRequestDto.CreatorId.Value, out var paymentRequestUserDto))
{
paymentRequestDto.CreatorUser = paymentRequestUserDto;
}
if(paymentRequestDto != null && paymentRequestDto.AccountCoding != null)
{
paymentRequestDto.AccountCodingDisplay = await GetAccountDistributionCode(paymentRequestDto.AccountCoding);
}
foreach (var expenseApproval in paymentRequestDto.ExpenseApprovals)
{
if (expenseApproval.DecisionUserId.HasValue
&& userDictionary.TryGetValue(expenseApproval.DecisionUserId.Value, out var expenseApprovalUserDto))
{
expenseApproval.DecisionUser = expenseApprovalUserDto;
}
}
}
return paymentDtos;
}
public virtual Task<string> GetAccountDistributionCode(AccountCodingDto? accountCoding)
{
string accountDistributionCode = "";
if (accountCoding == null) return Task.FromResult(accountDistributionCode);
if (accountCoding.Responsibility != null
&& accountCoding.ServiceLine != null
&& accountCoding.Stob != null
&& accountCoding.MinistryClient != null
&& accountCoding.ProjectNumber != null)
{
const string DefaultAccountDistributionPostfix = "000000.0000";
accountDistributionCode =
$"{accountCoding.MinistryClient}.{accountCoding.Responsibility}.{accountCoding.ServiceLine}.{accountCoding.Stob}.{accountCoding.ProjectNumber}.{DefaultAccountDistributionPostfix}";
}
return Task.FromResult(accountDistributionCode);
}
private static void ApplyErrorSummary(List<PaymentRequestDto> mappedPayments)
{
mappedPayments.ForEach(mappedPayment =>
{
if (!string.IsNullOrWhiteSpace(mappedPayment.CasResponse) &&
!mappedPayment.CasResponse.Equals("SUCCEEDED", StringComparison.OrdinalIgnoreCase))
{
mappedPayment.ErrorSummary = mappedPayment.CasResponse;
}
});
}
public async Task<List<PaymentDetailsDto>> GetListByApplicationIdAsync(Guid applicationId)
{
using (dataFilter.Disable<ISoftDelete>())
{
var paymentsQueryable = await paymentRequestsRepository.GetQueryableAsync();
var payments = await paymentsQueryable.Include(pr => pr.Site).ToListAsync();
var filteredPayments = payments.Where(e => e.CorrelationId == applicationId).ToList();
return ObjectMapper.Map<List<PaymentRequest>, List<PaymentDetailsDto>>(filteredPayments);
}
}
public async Task<List<PaymentDetailsDto>> GetListByPaymentIdsAsync(List<Guid> paymentIds)
{
var paymentsQueryable = await paymentRequestsRepository.GetQueryableAsync();
var payments = await paymentsQueryable
.Where(e => paymentIds.Contains(e.Id))
.Include(pr => pr.Site)
.Include(x => x.ExpenseApprovals)
.ToListAsync();
return ObjectMapper.Map<List<PaymentRequest>, List<PaymentDetailsDto>>(payments);
}
public virtual async Task<decimal> GetTotalPaymentRequestAmountByCorrelationIdAsync(Guid correlationId)
{
return await paymentRequestsRepository.GetTotalPaymentRequestAmountByCorrelationIdAsync(correlationId);
}
public async Task<decimal?> GetUserPaymentThresholdAsync()
{
var userThreshold = await paymentThresholdRepository.FirstOrDefaultAsync(x => x.UserId == currentUser.Id);
return userThreshold?.Threshold;
}
protected virtual string GetCurrentRequesterName()
{
return $"{currentUser.Name} {currentUser.SurName}";
}
protected virtual async Task<PaymentConfiguration?> GetPaymentConfigurationAsync()
{
var paymentConfigs = await paymentConfigurationRepository.GetListAsync();
if (paymentConfigs.Count > 0)
{
var paymentConfig = paymentConfigs[0];
return paymentConfig;
}
return null;
}
private async Task<int> GetNextSequenceNumberAsync(int currentYear)
{
// Retrieve all payment requests
var payments = await paymentRequestsRepository.GetListAsync();
// Filter payments for the current year
var filteredPayments = payments
.Where(p => p.CreationTime.Year == currentYear)
.OrderByDescending(p => p.CreationTime)
.ToList();
// Use the first payment in the sorted list (most recent) if available
if (filteredPayments.Count > 0)
{
var latestPayment = filteredPayments[0]; // Access the most recent payment directly
var referenceParts = latestPayment.ReferenceNumber.Split('-');
// Extract the sequence number from the reference number safely
if (referenceParts.Length > 0 && int.TryParse(referenceParts[^1], out int latestSequenceNumber))
{
return latestSequenceNumber + 1;
}
}
// If no payments exist or parsing fails, return the initial sequence number
return 1;
}
}
}