diff --git a/src/Payments.Core/Domain/Team.cs b/src/Payments.Core/Domain/Team.cs index b7d03e39..e58df338 100644 --- a/src/Payments.Core/Domain/Team.cs +++ b/src/Payments.Core/Domain/Team.cs @@ -78,6 +78,23 @@ public Team() public bool SlothAutoApprove { get; set; } = false; + /// + /// This will be a system admin setting. + /// It will relax the rules for Aggie Enterprise chart string validation. + /// The idea is that an application using the API will determine what is valid or not. + /// + /// Possibly we could have an invoice value that could be specified instead if we wanted to get that fancy. + /// + public bool UseCustomAccountValidation { get; set; } = false; + + /// + /// This will be a system admin setting. + /// This may be used if UseCustomAccountValidation is true. + /// If it is, the recharge debit natural account/expenditure type will be replaced + /// + [StringLength(6)] + public string RechargeDebitNaturalAccount { get; set; } + [NotMapped] public FinancialAccount DefaultAccount { get { diff --git a/src/Payments.Core/Jobs/MoneyMovementJob.cs b/src/Payments.Core/Jobs/MoneyMovementJob.cs index 4a2c2361..bf8c42de 100644 --- a/src/Payments.Core/Jobs/MoneyMovementJob.cs +++ b/src/Payments.Core/Jobs/MoneyMovementJob.cs @@ -132,7 +132,7 @@ public async Task FindBankReconcileTransactions(ILogger log) if (accountOverride != null) { //Do we want to validate? Sloth will validate (based on the current config setting in prod), but we can do it here to avoid a failed transaction. This is a bit of a judgement call. If we don't validate, the transaction will fail and the invoice will stay in paid status. If we do validate, the invoice will be rejected and the user will have to fix it. - var validationResult = await _aggieEnterpriseService.IsAccountValid(accountOverride.FinancialSegmentString); + var validationResult = await _aggieEnterpriseService.IsAccountValid(accountOverride.FinancialSegmentString, team); if (validationResult.IsValid) { incomeAeAccount = validationResult.ChartString ?? accountOverride.FinancialSegmentString; diff --git a/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.Designer.cs b/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.Designer.cs new file mode 100644 index 00000000..7f420222 --- /dev/null +++ b/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.Designer.cs @@ -0,0 +1,1209 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Payments.Core.Data; + +#nullable disable + +namespace Payments.Core.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261014152156_CustomCoaValidation")] + partial class CustomCoaValidation + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "6.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Payments.Core.Domain.Coupon", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Code") + .HasColumnType("nvarchar(max)"); + + b.Property("DiscountAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("DiscountPercent") + .HasColumnType("decimal(18,5)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("TeamId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TeamId"); + + b.ToTable("Coupons"); + }); + + modelBuilder.Entity("Payments.Core.Domain.FinancialAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Account") + .HasMaxLength(7) + .HasColumnType("nvarchar(7)"); + + b.Property("Chart") + .HasMaxLength(1) + .HasColumnType("nvarchar(1)"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("FinancialSegmentString") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("IsActive") + .HasColumnType("bit"); + + b.Property("IsDefault") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Project") + .HasMaxLength(9) + .HasColumnType("nvarchar(9)"); + + b.Property("SubAccount") + .HasMaxLength(5) + .HasColumnType("nvarchar(5)"); + + b.Property("TeamId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("TeamId"); + + b.ToTable("FinancialAccounts"); + }); + + modelBuilder.Entity("Payments.Core.Domain.History", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("ActionDateTime") + .HasColumnType("datetime2"); + + b.Property("Actor") + .HasColumnType("nvarchar(max)"); + + b.Property("Data") + .HasColumnType("nvarchar(max)"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("Type") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("InvoiceId"); + + b.ToTable("History"); + }); + + modelBuilder.Entity("Payments.Core.Domain.Invoice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AccountId") + .HasColumnType("int"); + + b.Property("CalculatedDiscount") + .HasColumnType("decimal(18,2)"); + + b.Property("CalculatedSubtotal") + .HasColumnType("decimal(18,2)"); + + b.Property("CalculatedTaxAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("CalculatedTaxableAmount") + .HasColumnType("decimal(18,2)"); + + b.Property("CalculatedTotal") + .HasColumnType("decimal(18,2)"); + + b.Property("CouponId") + .HasColumnType("int"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerAddress") + .HasColumnType("nvarchar(max)"); + + b.Property("CustomerCompany") + .HasColumnType("nvarchar(max)"); + + b.Property("CustomerEmail") + .HasColumnType("nvarchar(max)"); + + b.Property("CustomerName") + .HasColumnType("nvarchar(max)"); + + b.Property("Deleted") + .HasColumnType("bit"); + + b.Property("DeletedAt") + .HasColumnType("datetime2"); + + b.Property("DraftCount") + .HasColumnType("int"); + + b.Property("DueDate") + .HasColumnType("datetime2"); + + b.Property("ExternalId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ExternalIdentifier") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("ExternalLink") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("KfsTrackingNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("LinkId") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ManualDiscount") + .HasColumnType("decimal(18,2)"); + + b.Property("Memo") + .HasColumnType("nvarchar(max)"); + + b.Property("Paid") + .HasColumnType("bit"); + + b.Property("PaidAt") + .HasColumnType("datetime2"); + + b.Property("PaymentProcessorId") + .HasColumnType("nvarchar(max)"); + + b.Property("PaymentType") + .HasColumnType("nvarchar(max)"); + + b.Property("Refunded") + .HasColumnType("bit"); + + b.Property("RefundedAt") + .HasColumnType("datetime2"); + + b.Property("Sent") + .HasColumnType("bit"); + + b.Property("SentAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("TaxPercent") + .HasColumnType("decimal(18,5)"); + + b.Property("TeamId") + .HasColumnType("int"); + + b.Property("Type") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)") + .HasDefaultValue("CC"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("CouponId"); + + b.HasIndex("LinkId"); + + b.HasIndex("TeamId"); + + b.HasIndex("Type"); + + b.HasIndex("TeamId", "ExternalIdentifier", "ExternalId"); + + b.ToTable("Invoices"); + }); + + modelBuilder.Entity("Payments.Core.Domain.InvoiceAttachment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("ContentType") + .HasColumnType("nvarchar(max)"); + + b.Property("FileName") + .HasColumnType("nvarchar(max)"); + + b.Property("Identifier") + .HasColumnType("nvarchar(max)"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("Size") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("InvoiceId"); + + b.ToTable("InvoiceAttachments"); + }); + + modelBuilder.Entity("Payments.Core.Domain.InvoiceLink", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Expired") + .HasColumnType("bit"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("LinkId") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("InvoiceId"); + + b.ToTable("InvoiceLinks"); + }); + + modelBuilder.Entity("Payments.Core.Domain.LineItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Amount") + .HasColumnType("decimal(18,2)"); + + b.Property("Description") + .HasColumnType("nvarchar(max)"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("Quantity") + .HasColumnType("decimal(18,2)"); + + b.Property("TaxExempt") + .HasColumnType("bit"); + + b.Property("Total") + .HasColumnType("decimal(18,2)"); + + b.HasKey("Id"); + + b.HasIndex("InvoiceId"); + + b.ToTable("LineItems"); + }); + + modelBuilder.Entity("Payments.Core.Domain.LogMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("CorrelationId") + .HasColumnType("nvarchar(max)"); + + b.Property("Exception") + .HasColumnType("nvarchar(max)"); + + b.Property("JobId") + .HasColumnType("nvarchar(450)"); + + b.Property("JobName") + .HasColumnType("nvarchar(max)"); + + b.Property("Level") + .HasColumnType("nvarchar(max)"); + + b.Property("LogEvent") + .HasColumnType("nvarchar(max)"); + + b.Property("Message") + .HasColumnType("nvarchar(max)"); + + b.Property("MessageTemplate") + .HasColumnType("nvarchar(max)"); + + b.Property("Properties") + .HasColumnType("xml"); + + b.Property("Source") + .HasColumnType("nvarchar(max)"); + + b.Property("TimeStamp") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("JobId"); + + b.ToTable("Logs", (string)null); + }); + + modelBuilder.Entity("Payments.Core.Domain.MoneyMovementJobRecord", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("RanOn") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("MoneyMovementJobRecords"); + }); + + modelBuilder.Entity("Payments.Core.Domain.PaymentEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Amount") + .HasColumnType("decimal(18,2)"); + + b.Property("BillingCity") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("BillingCompany") + .HasMaxLength(60) + .HasColumnType("nvarchar(60)"); + + b.Property("BillingCountry") + .HasMaxLength(2) + .HasColumnType("nvarchar(2)"); + + b.Property("BillingEmail") + .HasMaxLength(1500) + .HasColumnType("nvarchar(1500)"); + + b.Property("BillingFirstName") + .HasMaxLength(60) + .HasColumnType("nvarchar(60)"); + + b.Property("BillingLastName") + .HasMaxLength(60) + .HasColumnType("nvarchar(60)"); + + b.Property("BillingPhone") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("BillingPostalCode") + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("BillingState") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("BillingStreet1") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("BillingStreet2") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("CardExpiry") + .HasColumnType("datetime2"); + + b.Property("CardNumber") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CardType") + .HasMaxLength(3) + .HasColumnType("nvarchar(3)"); + + b.Property("Decision") + .HasColumnType("nvarchar(max)"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("OccuredAt") + .HasColumnType("datetime2"); + + b.Property("Processor") + .HasColumnType("nvarchar(max)"); + + b.Property("ProcessorId") + .HasColumnType("nvarchar(max)"); + + b.Property("ReturnedResults") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("InvoiceId"); + + b.ToTable("PaymentEvents"); + }); + + modelBuilder.Entity("Payments.Core.Domain.RechargeAccount", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Amount") + .HasColumnType("decimal(18,2)"); + + b.Property("ApprovedByKerb") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("ApprovedByName") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Direction") + .HasColumnType("int"); + + b.Property("EnteredByKerb") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("EnteredByName") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("FinancialSegmentString") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("InvoiceId") + .HasColumnType("int"); + + b.Property("Notes") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("Percentage") + .HasColumnType("decimal(5,2)"); + + b.HasKey("Id"); + + b.HasIndex("ApprovedByKerb"); + + b.HasIndex("EnteredByKerb"); + + b.HasIndex("InvoiceId"); + + b.ToTable("RechargeAccounts"); + }); + + modelBuilder.Entity("Payments.Core.Domain.TaxReportJobRecord", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(max)"); + + b.Property("RanOn") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("TaxReportJobRecords"); + }); + + modelBuilder.Entity("Payments.Core.Domain.Team", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("AllowedInvoiceType") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)") + .HasDefaultValue("CC"); + + b.Property("ApiKey") + .HasColumnType("nvarchar(max)"); + + b.Property("ContactEmail") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ContactName") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ContactPhoneNumber") + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("IsActive") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RechargeDebitNaturalAccount") + .HasMaxLength(6) + .HasColumnType("nvarchar(6)"); + + b.Property("SlothAutoApprove") + .HasColumnType("bit"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("UseCustomAccountValidation") + .HasColumnType("bit"); + + b.Property("WebHookApiKey") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Id"); + + b.ToTable("Teams"); + }); + + modelBuilder.Entity("Payments.Core.Domain.TeamPermission", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("RoleId") + .HasColumnType("int"); + + b.Property("TeamId") + .HasColumnType("int"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.HasIndex("TeamId"); + + b.HasIndex("UserId"); + + b.ToTable("TeamPermissions"); + }); + + modelBuilder.Entity("Payments.Core.Domain.TeamRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("TeamRoles"); + }); + + modelBuilder.Entity("Payments.Core.Domain.User", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("CampusKerberos") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("FirstName") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("LastName") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Payments.Core.Domain.WebHook", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id"), 1L, 1); + + b.Property("ContentType") + .HasColumnType("nvarchar(max)"); + + b.Property("IsActive") + .HasColumnType("bit"); + + b.Property("TeamId") + .HasColumnType("int"); + + b.Property("TriggerOnPaid") + .HasColumnType("bit"); + + b.Property("TriggerOnReconcile") + .HasColumnType("bit"); + + b.Property("Url") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("TeamId"); + + b.ToTable("WebHooks"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Payments.Core.Domain.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Payments.Core.Domain.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Payments.Core.Domain.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Payments.Core.Domain.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Payments.Core.Domain.Coupon", b => + { + b.HasOne("Payments.Core.Domain.Team", "Team") + .WithMany("Coupons") + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Team"); + }); + + modelBuilder.Entity("Payments.Core.Domain.FinancialAccount", b => + { + b.HasOne("Payments.Core.Domain.Team", "Team") + .WithMany("Accounts") + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Team"); + }); + + modelBuilder.Entity("Payments.Core.Domain.History", b => + { + b.HasOne("Payments.Core.Domain.Invoice", null) + .WithMany("History") + .HasForeignKey("InvoiceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Payments.Core.Domain.Invoice", b => + { + b.HasOne("Payments.Core.Domain.FinancialAccount", "Account") + .WithMany() + .HasForeignKey("AccountId"); + + b.HasOne("Payments.Core.Domain.Coupon", "Coupon") + .WithMany("Invoices") + .HasForeignKey("CouponId"); + + b.HasOne("Payments.Core.Domain.Team", "Team") + .WithMany() + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Coupon"); + + b.Navigation("Team"); + }); + + modelBuilder.Entity("Payments.Core.Domain.InvoiceAttachment", b => + { + b.HasOne("Payments.Core.Domain.Invoice", "Invoice") + .WithMany("Attachments") + .HasForeignKey("InvoiceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invoice"); + }); + + modelBuilder.Entity("Payments.Core.Domain.InvoiceLink", b => + { + b.HasOne("Payments.Core.Domain.Invoice", "Invoice") + .WithMany() + .HasForeignKey("InvoiceId"); + + b.Navigation("Invoice"); + }); + + modelBuilder.Entity("Payments.Core.Domain.LineItem", b => + { + b.HasOne("Payments.Core.Domain.Invoice", null) + .WithMany("Items") + .HasForeignKey("InvoiceId"); + }); + + modelBuilder.Entity("Payments.Core.Domain.LogMessage", b => + { + b.HasOne("Payments.Core.Domain.MoneyMovementJobRecord", null) + .WithMany("Logs") + .HasForeignKey("JobId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Payments.Core.Domain.TaxReportJobRecord", null) + .WithMany("Logs") + .HasForeignKey("JobId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("Payments.Core.Domain.PaymentEvent", b => + { + b.HasOne("Payments.Core.Domain.Invoice", "Invoice") + .WithMany("PaymentEvents") + .HasForeignKey("InvoiceId"); + + b.Navigation("Invoice"); + }); + + modelBuilder.Entity("Payments.Core.Domain.RechargeAccount", b => + { + b.HasOne("Payments.Core.Domain.Invoice", "Invoice") + .WithMany("RechargeAccounts") + .HasForeignKey("InvoiceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invoice"); + }); + + modelBuilder.Entity("Payments.Core.Domain.TeamPermission", b => + { + b.HasOne("Payments.Core.Domain.TeamRole", "Role") + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Payments.Core.Domain.Team", "Team") + .WithMany("Permissions") + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Payments.Core.Domain.User", "User") + .WithMany("TeamPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("Team"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Payments.Core.Domain.WebHook", b => + { + b.HasOne("Payments.Core.Domain.Team", "Team") + .WithMany("WebHooks") + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Team"); + }); + + modelBuilder.Entity("Payments.Core.Domain.Coupon", b => + { + b.Navigation("Invoices"); + }); + + modelBuilder.Entity("Payments.Core.Domain.Invoice", b => + { + b.Navigation("Attachments"); + + b.Navigation("History"); + + b.Navigation("Items"); + + b.Navigation("PaymentEvents"); + + b.Navigation("RechargeAccounts"); + }); + + modelBuilder.Entity("Payments.Core.Domain.MoneyMovementJobRecord", b => + { + b.Navigation("Logs"); + }); + + modelBuilder.Entity("Payments.Core.Domain.TaxReportJobRecord", b => + { + b.Navigation("Logs"); + }); + + modelBuilder.Entity("Payments.Core.Domain.Team", b => + { + b.Navigation("Accounts"); + + b.Navigation("Coupons"); + + b.Navigation("Permissions"); + + b.Navigation("WebHooks"); + }); + + modelBuilder.Entity("Payments.Core.Domain.User", b => + { + b.Navigation("TeamPermissions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.cs b/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.cs new file mode 100644 index 00000000..93f496d3 --- /dev/null +++ b/src/Payments.Core/Migrations/20261014152156_CustomCoaValidation.cs @@ -0,0 +1,37 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Payments.Core.Migrations +{ + public partial class CustomCoaValidation : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "RechargeDebitNaturalAccount", + table: "Teams", + type: "nvarchar(6)", + maxLength: 6, + nullable: true); + + migrationBuilder.AddColumn( + name: "UseCustomAccountValidation", + table: "Teams", + type: "bit", + nullable: false, + defaultValue: false); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "RechargeDebitNaturalAccount", + table: "Teams"); + + migrationBuilder.DropColumn( + name: "UseCustomAccountValidation", + table: "Teams"); + } + } +} diff --git a/src/Payments.Core/Migrations/ApplicationDbContextModelSnapshot.cs b/src/Payments.Core/Migrations/ApplicationDbContextModelSnapshot.cs index d4e3df14..fb39721f 100644 --- a/src/Payments.Core/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/src/Payments.Core/Migrations/ApplicationDbContextModelSnapshot.cs @@ -768,6 +768,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(128) .HasColumnType("nvarchar(128)"); + b.Property("RechargeDebitNaturalAccount") + .HasMaxLength(6) + .HasColumnType("nvarchar(6)"); + b.Property("SlothAutoApprove") .HasColumnType("bit"); @@ -776,6 +780,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(40) .HasColumnType("nvarchar(40)"); + b.Property("UseCustomAccountValidation") + .HasColumnType("bit"); + b.Property("WebHookApiKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); diff --git a/src/Payments.Core/Models/Configuration/FinanceSettings.cs b/src/Payments.Core/Models/Configuration/FinanceSettings.cs index c0a3e062..4e5a3e7f 100644 --- a/src/Payments.Core/Models/Configuration/FinanceSettings.cs +++ b/src/Payments.Core/Models/Configuration/FinanceSettings.cs @@ -30,6 +30,11 @@ public class FinanceSettings public bool ValidateRechargeFinancialSegmentString { get; set; } = true; + /// + /// Feature flag to turn on team level natural account replacement of debit natural account (vs. hard coded value) + /// + public bool EnableRechargeDebitNaturalAccount { get; set; } = false; + public int RechargeAutoApproveDays { get; set; } = 7; } } diff --git a/src/Payments.Core/Services/AggieEnterpriseService.cs b/src/Payments.Core/Services/AggieEnterpriseService.cs index cbe08ab9..475a1ac4 100644 --- a/src/Payments.Core/Services/AggieEnterpriseService.cs +++ b/src/Payments.Core/Services/AggieEnterpriseService.cs @@ -3,6 +3,7 @@ using AggieEnterpriseApi.Types; using AggieEnterpriseApi.Validation; using Microsoft.Extensions.Options; +using Payments.Core.Domain; using Payments.Core.Models.Configuration; using Payments.Core.Models.Validation; using Serilog; @@ -16,24 +17,66 @@ namespace Payments.Core.Services { public interface IAggieEnterpriseService { - Task IsAccountValid(string financialSegmentString, bool validateCVRs = true); + Task IsAccountValid(string financialSegmentString, Team team, bool validateCVRs = true); - Task IsRechargeAccountValid(string financialSegmentString, CreditDebit direction, bool validateCVRs = true); + Task IsRechargeAccountValid(string financialSegmentString, CreditDebit direction, Team team, bool validateCVRs = true); + + Task> SearchNaturalAccounts(string query); + + Task IsNaturalAccountValid(string naturalAccount); } public class AggieEnterpriseService : IAggieEnterpriseService { private readonly AggieEnterpriseOptions _aeSettings; + private readonly FinanceSettings _financeSettings; private IAggieEnterpriseClient _aggieClient; private const string FiscalOfficer = "Fiscal Officer Approver"; - public AggieEnterpriseService(IOptions aeSettings) + public AggieEnterpriseService(IOptions aeSettings, IOptions financeSettings) { _aeSettings = aeSettings.Value; + _financeSettings = financeSettings.Value; //_aggieClient = GraphQlClient.Get(options.Value.GraphQlUrl, options.Value.Token); _aggieClient = GraphQlClient.Get(_aeSettings.GraphQlUrl, _aeSettings.TokenEndpoint, _aeSettings.ConsumerKey, _aeSettings.ConsumerSecret, $"{_aeSettings.ScopeApp}-{_aeSettings.ScopeEnv}"); } + public async Task> SearchNaturalAccounts(string query) + { + var filter = new ErpAccountFilterInput + { + Name = new StringFilterInput { Contains = query.Trim().Replace(" ", "%") } + }; + var result = await _aggieClient.ErpAccountSearch.ExecuteAsync(filter, query.Trim().ToUpperInvariant()); + var data = result.ReadData(); + var accounts = data.ErpAccountSearch.Data + .Where(account => account.EligibleForUse) + .GroupBy(account => account.Code) + .ToDictionary(group => group.Key, group => group.First().Name); + + if (data.ErpAccount?.EligibleForUse == true) + { + accounts[data.ErpAccount.Code] = data.ErpAccount.Name; + } + + return accounts; + } + + public async Task IsNaturalAccountValid(string naturalAccount) + { + if (string.IsNullOrWhiteSpace(naturalAccount) || naturalAccount.Length != 6 + || naturalAccount.Any(character => !(character >= '0' && character <= '9') + && !(character >= 'A' && character <= 'Z'))) + { + return false; + } + + var result = await _aggieClient.ErpAccountSearch.ExecuteAsync( + new ErpAccountFilterInput { Code = new StringFilterInput { Eq = naturalAccount } }, naturalAccount); + var account = result.ReadData().ErpAccount; + return account?.EligibleForUse == true && account.Code == naturalAccount; + } + //TODO: Change this to return invalid reasons private async Task CommonAccountValidation(AccountValidationModel accountValidationModel, string financialSegmentString, bool validateCVRs = true) @@ -215,12 +258,22 @@ private async Task CommonPpmFundChecks(AccountValidation return accountValidationModel; } - public async Task IsAccountValid(string financialSegmentString, bool validateCVRs = true) + public async Task IsAccountValid(string financialSegmentString, Team team, bool validateCVRs = true) { var rtValue = new AccountValidationModel(); rtValue = await CommonAccountValidation(rtValue, financialSegmentString, validateCVRs); + if (team == null) + { + Log.Error("Team is null in IsAccountValid"); + } + + if (team != null && team.UseCustomAccountValidation) + { + return rtValue; //If the team is using custom account validation, we don't want to do any further checks + } + if (rtValue.CoaChartType == FinancialChartStringType.Gl) { @@ -303,11 +356,21 @@ public async Task IsAccountValid(string financialSegment return rtValue; } - public async Task IsRechargeAccountValid(string financialSegmentString, CreditDebit direction, bool validateCVRs = true) + public async Task IsRechargeAccountValid(string financialSegmentString, CreditDebit direction, Team team, bool validateCVRs = true) { + if(team == null) + { + Log.Error("Team is null in IsRechargeAccountValid"); + } + var debitNaturalAccount = "770006"; + if(_financeSettings.EnableRechargeDebitNaturalAccount && team != null && team.UseCustomAccountValidation && !string.IsNullOrWhiteSpace(team.RechargeDebitNaturalAccount)) + { + debitNaturalAccount = team.RechargeDebitNaturalAccount; + } + var rtValue = new AccountValidationModel(); - var newChartString = ReplaceNaturalAccount(financialSegmentString, direction == CreditDebit.Credit ? "775000" : "770006"); + var newChartString = ReplaceNaturalAccount(financialSegmentString, direction == CreditDebit.Credit ? "775000" : debitNaturalAccount); var chartStringUpdated = newChartString != financialSegmentString; financialSegmentString = newChartString; @@ -320,11 +383,17 @@ public async Task IsRechargeAccountValid(string financia if(chartStringUpdated) { //Add a warning that we changed the natural account for them. Otherwise, they may not notice if it would have been valid except for the change - rtValue.Warnings.Add(new KeyValuePair("Natural Account", direction == CreditDebit.Credit ? "The Natural Account/Expenditure Type segment has been changed to 775000." : "The Natural Account/Expenditure Type segment has been changed to 770006.")); + rtValue.Warnings.Add(new KeyValuePair("Natural Account", direction == CreditDebit.Credit ? "The Natural Account/Expenditure Type segment has been changed to 775000." : $"The Natural Account/Expenditure Type segment has been changed to {debitNaturalAccount}.")); } return rtValue; } + if(team?.UseCustomAccountValidation == true) + { + rtValue = await MinimumCustomValidationChecks(direction, chartStringUpdated, direction == CreditDebit.Credit ? "775000" : debitNaturalAccount, rtValue); + return rtValue; + } + if (direction == CreditDebit.Credit) { //The big unknown for now if the rollup stuff/parent stuff. @@ -422,6 +491,59 @@ public async Task IsRechargeAccountValid(string financia return rtValue; } + /// + /// For Recharge Accounts + /// + /// + /// + /// + private async Task MinimumCustomValidationChecks(CreditDebit direction, bool chartStringUpdated, string naturalAccountToUse, AccountValidationModel rtValue) + { + if (chartStringUpdated) + { + var segmentName = rtValue.CoaChartType == FinancialChartStringType.Ppm + ? "Expenditure Type" + : "Natural Account"; + + rtValue.Warnings.Add(new KeyValuePair( + segmentName, + $"The {segmentName} segment has been changed to {naturalAccountToUse}.")); + } + + if (direction == CreditDebit.Credit) + { + //For credit, we don't need to do anything else. The custom validation is enough. + } + else //Debit + { + if (rtValue.CoaChartType == FinancialChartStringType.Gl) + { + if (rtValue.IsValid) + { + var result = await _aggieClient.ErpDepartmentApprovers.ExecuteAsync(rtValue.GlSegments.Department); + var data = result.ReadData(); + if (data != null) + { + if (data.ErpFinancialDepartment != null && data.ErpFinancialDepartment.Approvers != null) + { + foreach (var approver in data.ErpFinancialDepartment.Approvers.Where(a => a.ApproverType == FiscalOfficer)) + { + rtValue.Approvers.Add(new Approver + { + FirstName = approver.FirstName, + LastName = approver.LastName, + Email = approver.EmailAddress, + }); + } + } + } + } + } + } + + return rtValue; + } + private PpmSegmentInput ConvertToPpmSegmentInput(PpmSegments segments) { return new PpmSegmentInput diff --git a/src/Payments.Mvc/ClientApp/src/components/rechargeAccountsControl.tsx b/src/Payments.Mvc/ClientApp/src/components/rechargeAccountsControl.tsx index 486e7b1d..66252917 100644 --- a/src/Payments.Mvc/ClientApp/src/components/rechargeAccountsControl.tsx +++ b/src/Payments.Mvc/ClientApp/src/components/rechargeAccountsControl.tsx @@ -14,6 +14,7 @@ import { } from '../helpers/calculations'; interface IProps { + teamSlug: string; rechargeAccounts: InvoiceRechargeItem[]; invoiceTotal: number; onChange: (rechargeAccounts: InvoiceRechargeItem[]) => void; @@ -363,7 +364,9 @@ export default class RechargeAccountsControl extends React.Component< const response = await fetch( `/api/recharge/validate?chartString=${encodeURIComponent( chartString - )}&direction=${directionValue}&checkApprover=${checkApprover}`, + )}&direction=${directionValue}&checkApprover=${checkApprover}&teamSlug=${encodeURIComponent( + this.props.teamSlug + )}`, { method: 'GET', headers: { diff --git a/src/Payments.Mvc/ClientApp/src/components/sendModal.tsx b/src/Payments.Mvc/ClientApp/src/components/sendModal.tsx index e4bf841f..488ed73b 100644 --- a/src/Payments.Mvc/ClientApp/src/components/sendModal.tsx +++ b/src/Payments.Mvc/ClientApp/src/components/sendModal.tsx @@ -160,6 +160,7 @@ export default class SendModal extends React.PureComponent { paid: false, paidDate: null, team: { + slug: team.slug, name: team.name, contactName: '', contactEmail: team.contactEmail, diff --git a/src/Payments.Mvc/ClientApp/src/containers/CreateInvoiceContainer.tsx b/src/Payments.Mvc/ClientApp/src/containers/CreateInvoiceContainer.tsx index dc82f73d..fb05e7ff 100644 --- a/src/Payments.Mvc/ClientApp/src/containers/CreateInvoiceContainer.tsx +++ b/src/Payments.Mvc/ClientApp/src/containers/CreateInvoiceContainer.tsx @@ -180,6 +180,7 @@ export default class CreateInvoiceContainer extends React.Component< {invoiceType === 'Recharge' && (
{ this._rechargeAccountsRef = r; }} rechargeAccounts={rechargeAccounts} invoiceTotal={invoiceTotal} diff --git a/src/Payments.Mvc/ClientApp/src/containers/EditInvoiceContainer.tsx b/src/Payments.Mvc/ClientApp/src/containers/EditInvoiceContainer.tsx index ddf7d572..c36f4c91 100644 --- a/src/Payments.Mvc/ClientApp/src/containers/EditInvoiceContainer.tsx +++ b/src/Payments.Mvc/ClientApp/src/containers/EditInvoiceContainer.tsx @@ -181,6 +181,7 @@ export default class EditInvoiceContainer extends React.Component< {type === 'Recharge' && (
{ this._rechargeAccountsRef = r; }} diff --git a/src/Payments.Mvc/ClientApp/src/containers/FinancialApproveInvoiceContainer.tsx b/src/Payments.Mvc/ClientApp/src/containers/FinancialApproveInvoiceContainer.tsx index e224c64b..6c42b154 100644 --- a/src/Payments.Mvc/ClientApp/src/containers/FinancialApproveInvoiceContainer.tsx +++ b/src/Payments.Mvc/ClientApp/src/containers/FinancialApproveInvoiceContainer.tsx @@ -45,6 +45,7 @@ export interface InvoiceAttachmentModel { } export interface InvoiceTeam { + slug: string; name: string; contactName: string; contactEmail: string; @@ -347,6 +348,7 @@ export default class FinancialApproveInvoiceContainer extends React.Component< can be modified.

{ this._rechargeAccountsRef = r; }} diff --git a/src/Payments.Mvc/ClientApp/src/containers/PayInvoiceContainer.tsx b/src/Payments.Mvc/ClientApp/src/containers/PayInvoiceContainer.tsx index 42ac97f4..27784f69 100644 --- a/src/Payments.Mvc/ClientApp/src/containers/PayInvoiceContainer.tsx +++ b/src/Payments.Mvc/ClientApp/src/containers/PayInvoiceContainer.tsx @@ -43,6 +43,7 @@ export interface InvoiceAttachmentModel { } export interface InvoiceTeam { + slug: string; name: string; contactName: string; contactEmail: string; @@ -318,6 +319,7 @@ export default class PayInvoiceContainer extends React.Component< amount must match the invoice total.

{ this._rechargeAccountsRef = r; }} diff --git a/src/Payments.Mvc/ClientApp/src/containers/PreviewRechargeInvoiceContainer.tsx b/src/Payments.Mvc/ClientApp/src/containers/PreviewRechargeInvoiceContainer.tsx index 1d0a4617..7786dd0a 100644 --- a/src/Payments.Mvc/ClientApp/src/containers/PreviewRechargeInvoiceContainer.tsx +++ b/src/Payments.Mvc/ClientApp/src/containers/PreviewRechargeInvoiceContainer.tsx @@ -172,6 +172,7 @@ export default class PreviewRechargeInvoiceContainer extends React.Component< form works. Changes cannot be saved in preview mode.

{ this._rechargeAccountsRef = r; }} diff --git a/src/Payments.Mvc/Controllers/FinancialAccountsController.cs b/src/Payments.Mvc/Controllers/FinancialAccountsController.cs index e452a5d1..48e81080 100644 --- a/src/Payments.Mvc/Controllers/FinancialAccountsController.cs +++ b/src/Payments.Mvc/Controllers/FinancialAccountsController.cs @@ -195,7 +195,7 @@ public async Task ConfirmAccount(FinancialAccountModel financialA } if (!String.IsNullOrWhiteSpace(financialAccount.FinancialSegmentString) ) { - financialAccount.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString); + financialAccount.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString, team); if (!financialAccount.AeValidationModel.IsValid) { ModelState.AddModelError("FinancialSegmentString", $"Financial Segment String is not valid. {financialAccount.AeValidationModel.Message}"); @@ -290,7 +290,7 @@ public async Task CreateAccount(FinancialAccountModel financialAc if (!String.IsNullOrWhiteSpace(financialAccount.FinancialSegmentString)) { //TODO: Extra payments account validation (income, etc.) - var validationResult = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString); + var validationResult = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString, team); if (!validationResult.IsValid) { ModelState.AddModelError("FinancialSegmentString", $"Financial Segment String is not valid. {validationResult.Message}"); @@ -359,7 +359,7 @@ public async Task EditAccount(int? id) } var model = new FinancialAccountEditModel { FinancialAccount = financialAccount, ShowCoa = _financeSettings.ShowCoa, UseCoa = _financeSettings.UseCoa }; - model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString); + model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString, team); model.AllowCoaEdit = string.IsNullOrWhiteSpace( financialAccount.FinancialSegmentString); return View(model); @@ -410,7 +410,7 @@ public async Task EditAccount(int id, int teamId, FinancialAccoun else { financialAccountToUpdate.FinancialSegmentString = financialAccount.FinancialSegmentString; //Only allow it to be updated once if it is empty. - model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString); + model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString, team); if (!model.AeValidationModel.IsValid) { ModelState.AddModelError("FinancialAccount.FinancialSegmentString", $"Financial Segment String is not valid. {model.AeValidationModel.Message}"); @@ -484,7 +484,7 @@ public async Task AccountDetails(int? id) { model.KfsAccount = new KfsAccount(); model.ShowKfsAccount = false; - model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString); + model.AeValidationModel = await _aggieEnterpriseService.IsAccountValid(financialAccount.FinancialSegmentString, team); model.IsAeAccountValid = model.AeValidationModel.IsValid; model.AeValidationMessage = model.AeValidationModel.Message; } @@ -596,7 +596,13 @@ public async Task GetAccountInfo(string chart, string account, string su [HttpGet("{team}/api/financial-accounts/validate")] public async Task ValidateFinancialSegmentString(string chartString) { - var result = await _aggieEnterpriseService.IsAccountValid(chartString); + var team = await _context.Teams.SingleOrDefaultAsync(m => m.Slug == TeamSlug && m.IsActive); + if (team == null) + { + return NotFound(); + } + + var result = await _aggieEnterpriseService.IsAccountValid(chartString, team); return new JsonResult(new { diff --git a/src/Payments.Mvc/Controllers/RechargeController.cs b/src/Payments.Mvc/Controllers/RechargeController.cs index 79186c65..9ec7d99a 100644 --- a/src/Payments.Mvc/Controllers/RechargeController.cs +++ b/src/Payments.Mvc/Controllers/RechargeController.cs @@ -36,9 +36,15 @@ public RechargeController(ApplicationDbContext dbContext, IAggieEnterpriseServic [HttpGet] [Route("api/recharge/validate")] - public async Task ValidateChartString(string chartString, CreditDebit direction, bool checkApprover = false) + public async Task ValidateChartString(string chartString, CreditDebit direction, string teamSlug, bool checkApprover = false) { - var result = await _aggieEnterpriseService.IsRechargeAccountValid(chartString, direction); + var team = await _dbContext.Teams.SingleOrDefaultAsync(t => t.Slug == teamSlug); + if (team == null) + { + return NotFound(); + } + + var result = await _aggieEnterpriseService.IsRechargeAccountValid(chartString, direction, team); //This may not need to return the entire result object @@ -229,7 +235,7 @@ public async Task Pay(string id, [FromBody] RechargeAccount[] mod var savedApprovers = new List(); foreach (var item in model) { - var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(item.FinancialSegmentString, RechargeAccount.CreditDebit.Debit); + var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(item.FinancialSegmentString, RechargeAccount.CreditDebit.Debit, invoice.Team); if (!validationResult.IsValid) { return BadRequest($"The chart string {item.FinancialSegmentString} is not valid: {validationResult.Message}"); @@ -531,7 +537,7 @@ public async Task FinancialApprove(string id, string actionType, } //We don't really care about checking if they changed the chart string, we will just pass whatever is in the model and validate/save that. - var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(item.FinancialSegmentString, RechargeAccount.CreditDebit.Debit); + var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(item.FinancialSegmentString, RechargeAccount.CreditDebit.Debit, invoice.Team); if (!validationResult.IsValid) { return BadRequest($"The chart string {item.FinancialSegmentString} is not valid: {validationResult.Message}"); @@ -618,7 +624,7 @@ public IActionResult Expired(string id) foreach (var ra in invoice.RechargeAccounts.Where(ra => ra.Direction == CreditDebit.Debit)) { - var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, CreditDebit.Debit); + var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, CreditDebit.Debit, invoice.Team); if (validationResult.Approvers != null && validationResult.Approvers.Count > 0) { if (IsUserAnApprover(validationResult.Approvers, user, additionalEmails)) diff --git a/src/Payments.Mvc/Controllers/SettingsController.cs b/src/Payments.Mvc/Controllers/SettingsController.cs index cfddbc0b..cae3bfc0 100644 --- a/src/Payments.Mvc/Controllers/SettingsController.cs +++ b/src/Payments.Mvc/Controllers/SettingsController.cs @@ -8,9 +8,11 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using Payments.Core.Data; using Payments.Core.Domain; using Payments.Core.Extensions; +using Payments.Core.Models.Configuration; using Payments.Core.Services; using Payments.Emails; using Payments.Mvc.Identity; @@ -30,19 +32,25 @@ public class SettingsController : SuperController private readonly INotificationService _notificationService; private readonly IEmailService _emailService; private readonly ApplicationUserManager _userManager; + private readonly IAggieEnterpriseService _aggieEnterpriseService; + private readonly FinanceSettings _financeSettings; public SettingsController( ApplicationDbContext context, IDirectorySearchService directorySearchService, INotificationService notificationService, IEmailService emailService, - ApplicationUserManager userManager) + ApplicationUserManager userManager, + IAggieEnterpriseService aggieEnterpriseService, + IOptions financeSettings) { _context = context; _directorySearchService = directorySearchService; _notificationService = notificationService; _emailService = emailService; _userManager = userManager; + _aggieEnterpriseService = aggieEnterpriseService; + _financeSettings = financeSettings.Value; } /// @@ -74,6 +82,9 @@ public async Task Index() WebHookApiKey = team.WebHookApiKey, AllowedInvoiceType = team.AllowedInvoiceType, SlothAutoApprove = team.SlothAutoApprove, + UseCustomAccountValidation = team.UseCustomAccountValidation, + RechargeDebitNaturalAccount = team.RechargeDebitNaturalAccount, + ShowRechargeDebitNaturalAccount = _financeSettings.EnableRechargeDebitNaturalAccount, }; return View(model); @@ -102,6 +113,9 @@ public async Task Edit() WebHookApiKey = team.WebHookApiKey, AllowedInvoiceType = team.AllowedInvoiceType, SlothAutoApprove = team.SlothAutoApprove, + UseCustomAccountValidation = team.UseCustomAccountValidation, + RechargeDebitNaturalAccount = team.RechargeDebitNaturalAccount, + ShowRechargeDebitNaturalAccount = _financeSettings.EnableRechargeDebitNaturalAccount, }; return View(model); @@ -125,6 +139,44 @@ public async Task Edit(EditTeamViewModel model) ModelState.AddModelError("Slug", "Team Slug already used."); } + var isSystemUser = User.IsInRole(ApplicationRoleCodes.Admin); + model.ShowRechargeDebitNaturalAccount = _financeSettings.EnableRechargeDebitNaturalAccount; + ModelState.Remove(nameof(model.ShowRechargeDebitNaturalAccount)); + if (!isSystemUser) + { + model.UseCustomAccountValidation = team.UseCustomAccountValidation; + model.RechargeDebitNaturalAccount = team.RechargeDebitNaturalAccount; + ModelState.Remove(nameof(model.UseCustomAccountValidation)); + ModelState.Remove(nameof(model.RechargeDebitNaturalAccount)); + } + else if (!_financeSettings.EnableRechargeDebitNaturalAccount) + { + model.RechargeDebitNaturalAccount = team.RechargeDebitNaturalAccount; + ModelState.Remove(nameof(model.RechargeDebitNaturalAccount)); + } + else if (!model.UseCustomAccountValidation) + { + model.RechargeDebitNaturalAccount = null; + ModelState.Remove(nameof(model.RechargeDebitNaturalAccount)); + } + else if (ModelState.IsValid && !string.IsNullOrWhiteSpace(model.RechargeDebitNaturalAccount)) + { + try + { + if (!await _aggieEnterpriseService.IsNaturalAccountValid(model.RechargeDebitNaturalAccount)) + { + ModelState.AddModelError(nameof(model.RechargeDebitNaturalAccount), + "Select an eligible natural account from Aggie Enterprise."); + } + } + catch (Exception) + { + Log.Warning("Aggie Enterprise natural account validation failed."); + ModelState.AddModelError(nameof(model.RechargeDebitNaturalAccount), + "Unable to validate the natural account with Aggie Enterprise. Please try again."); + } + } + if (!ModelState.IsValid) { return View(model); @@ -139,11 +191,17 @@ public async Task Edit(EditTeamViewModel model) // only admins can change active - if (User.IsInRole(ApplicationRoleCodes.Admin)) + if (isSystemUser) { team.IsActive = model.IsActive; team.AllowedInvoiceType = model.AllowedInvoiceType; team.SlothAutoApprove = model.SlothAutoApprove; + team.UseCustomAccountValidation = model.UseCustomAccountValidation; + if (_financeSettings.EnableRechargeDebitNaturalAccount) + { + team.RechargeDebitNaturalAccount = string.IsNullOrWhiteSpace(model.RechargeDebitNaturalAccount) + ? null : model.RechargeDebitNaturalAccount; + } } await _context.SaveChangesAsync(); @@ -151,6 +209,33 @@ public async Task Edit(EditTeamViewModel model) return RedirectToAction(nameof(Index), new { team = team.Slug }); } + [HttpGet] + [Authorize(Roles = ApplicationRoleCodes.Admin)] + public async Task SearchNaturalAccounts(string query) + { + if (!_financeSettings.EnableRechargeDebitNaturalAccount) + { + return NotFound(); + } + + query = query?.Trim(); + if (string.IsNullOrEmpty(query) || query.Length < 3 || query.Length > 100) + { + return BadRequest("Enter between 3 and 100 characters to search for a natural account."); + } + + try + { + var accounts = await _aggieEnterpriseService.SearchNaturalAccounts(query); + return Json(accounts.Select(account => new { code = account.Key, name = account.Value })); + } + catch (Exception) + { + Log.Warning("Aggie Enterprise natural account search failed."); + return StatusCode(503, "Unable to search Aggie Enterprise. Please try again."); + } + } + [Authorize(Policy = PolicyCodes.TeamEditor)] public async Task Roles() { diff --git a/src/Payments.Mvc/Models/PaymentViewModels/PaymentInvoiceTeamViewModel.cs b/src/Payments.Mvc/Models/PaymentViewModels/PaymentInvoiceTeamViewModel.cs index 8ab2513a..484400a2 100644 --- a/src/Payments.Mvc/Models/PaymentViewModels/PaymentInvoiceTeamViewModel.cs +++ b/src/Payments.Mvc/Models/PaymentViewModels/PaymentInvoiceTeamViewModel.cs @@ -10,6 +10,7 @@ public PaymentInvoiceTeamViewModel() { } public PaymentInvoiceTeamViewModel(Team team) { Name = team.Name; + Slug = team.Slug; ContactName = team.ContactName; ContactEmail = team.ContactEmail; ContactPhoneNumber = team.ContactPhoneNumber; @@ -20,6 +21,8 @@ public PaymentInvoiceTeamViewModel(Team team) [Required] public string Name { get; set; } + public string Slug { get; set; } + [StringLength(128)] [Display(Name = "Contact Name")] public string ContactName { get; set; } diff --git a/src/Payments.Mvc/Models/TeamViewModels/EditTeamViewModel.cs b/src/Payments.Mvc/Models/TeamViewModels/EditTeamViewModel.cs index 8ce88475..a69e26ea 100644 --- a/src/Payments.Mvc/Models/TeamViewModels/EditTeamViewModel.cs +++ b/src/Payments.Mvc/Models/TeamViewModels/EditTeamViewModel.cs @@ -1,5 +1,6 @@ using System; using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Payments.Mvc.Models.TeamViewModels { @@ -7,5 +8,16 @@ public class EditTeamViewModel : BaseTeamViewModel { [Display(Name = "Active?")] public bool IsActive { get; set; } + + [Display(Name = "Use Custom Account Validation")] + public bool UseCustomAccountValidation { get; set; } + + [StringLength(6)] + [RegularExpression("^[0-9A-Z]{6}$", ErrorMessage = "Select a six-character natural account from Aggie Enterprise.")] + [Display(Name = "Recharge Debit Natural Account")] + public string RechargeDebitNaturalAccount { get; set; } + + [BindNever] + public bool ShowRechargeDebitNaturalAccount { get; set; } } } diff --git a/src/Payments.Mvc/Models/TeamViewModels/TeamDetailsModel.cs b/src/Payments.Mvc/Models/TeamViewModels/TeamDetailsModel.cs index 89266a59..71b33653 100644 --- a/src/Payments.Mvc/Models/TeamViewModels/TeamDetailsModel.cs +++ b/src/Payments.Mvc/Models/TeamViewModels/TeamDetailsModel.cs @@ -36,6 +36,14 @@ public class TeamDetailsModel [Display(Name = "Sloth Recharge Auto Approve")] public bool SlothAutoApprove { get; set; } + [Display(Name = "Use Custom Account Validation")] + public bool UseCustomAccountValidation { get; set; } + + [Display(Name = "Recharge Debit Natural Account")] + public string RechargeDebitNaturalAccount { get; set; } + + public bool ShowRechargeDebitNaturalAccount { get; set; } + public IList Accounts { get; set; } public IList Permissions { get; set; } diff --git a/src/Payments.Mvc/Payments.Mvc.csproj b/src/Payments.Mvc/Payments.Mvc.csproj index 96ee990b..9ef76bf9 100644 --- a/src/Payments.Mvc/Payments.Mvc.csproj +++ b/src/Payments.Mvc/Payments.Mvc.csproj @@ -1,7 +1,7 @@ net6.0 - 1.0.3 + 1.0.4 true Latest false diff --git a/src/Payments.Mvc/Services/InvoiceService.cs b/src/Payments.Mvc/Services/InvoiceService.cs index 286daa42..f633d24a 100644 --- a/src/Payments.Mvc/Services/InvoiceService.cs +++ b/src/Payments.Mvc/Services/InvoiceService.cs @@ -71,7 +71,7 @@ public async Task> CreateInvoices(CreateInvoiceModel mode foreach(var ra in model.RechargeAccounts) { - var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction); + var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction, team); if(!validationModel.IsValid) { throw new ArgumentException($"Recharge account '{ra.FinancialSegmentString}' is not valid", nameof(model.RechargeAccounts)); @@ -195,7 +195,7 @@ public async Task> CreateInvoices(CreateInvoiceModel mode var AccountOverride = model.RechargeAccounts?.SingleOrDefault(a => a.Direction == RechargeAccount.CreditDebit.Credit && !string.IsNullOrWhiteSpace(a.FinancialSegmentString)); if (AccountOverride != null) { - var validationModel = await _aggieEnterpriseService.IsAccountValid(AccountOverride.FinancialSegmentString); + var validationModel = await _aggieEnterpriseService.IsAccountValid(AccountOverride.FinancialSegmentString, team); if (!validationModel.IsValid) { throw new ArgumentException($"Account override '{AccountOverride.FinancialSegmentString}' is not valid", nameof(model.RechargeAccounts)); @@ -335,7 +335,7 @@ public async Task UpdateInvoice(Invoice invoice, EditInvoiceModel model foreach (var ra in invoice.RechargeAccounts) { - var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction); + var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction, team); if (!validationModel.IsValid) { throw new ArgumentException($"Recharge account '{ra.FinancialSegmentString}' is not valid"); @@ -424,7 +424,7 @@ private async Task UpdateAccountOverride(Invoice invoice, EditInvoiceModel model return; } - var validationModel = await _aggieEnterpriseService.IsAccountValid(accountOverride.FinancialSegmentString); + var validationModel = await _aggieEnterpriseService.IsAccountValid(accountOverride.FinancialSegmentString, invoice.Team); if (!validationModel.IsValid) { throw new ArgumentException($"Account override '{accountOverride.FinancialSegmentString}' is not valid", nameof(model.RechargeAccounts)); @@ -522,7 +522,7 @@ public async Task SendInvoice(Invoice invoice, SendInvoiceModel model) { foreach (var ra in invoice.RechargeAccounts) { - var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction); + var validationModel = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction, invoice.Team); if (!validationModel.IsValid) { //This will throw an uncontrolled exception, but that is probably better than sending an invoice with invalid accounts. @@ -702,7 +702,7 @@ private async Task GetInvoiceApprovers(Invoice invoice) var approvers = new List(); foreach(var ra in invoice.RechargeAccounts.Where(a => a.Direction == RechargeAccount.CreditDebit.Debit)) { - var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction); + var validationResult = await _aggieEnterpriseService.IsRechargeAccountValid(ra.FinancialSegmentString, ra.Direction, invoice.Team); if(validationResult.Approvers != null) { approvers.AddRange(validationResult.Approvers); diff --git a/src/Payments.Mvc/Views/Invoices/Details.cshtml b/src/Payments.Mvc/Views/Invoices/Details.cshtml index b4f6fbcc..c6dcaaed 100644 --- a/src/Payments.Mvc/Views/Invoices/Details.cshtml +++ b/src/Payments.Mvc/Views/Invoices/Details.cshtml @@ -1255,7 +1255,7 @@ else // Recharge account validation functions function validateChartString(chartString, direction) { const directionValue = direction === 'Credit' ? 0 : 1; - return fetch(`/api/recharge/validate?chartString=${encodeURIComponent(chartString)}&direction=${directionValue}`, { + return fetch(`/api/recharge/validate?chartString=${encodeURIComponent(chartString)}&direction=${directionValue}&teamSlug=@teamSlug`, { method: 'GET', headers: { 'Content-Type': 'application/json', diff --git a/src/Payments.Mvc/Views/Settings/Edit.cshtml b/src/Payments.Mvc/Views/Settings/Edit.cshtml index 80c2e7f3..c9914bc2 100644 --- a/src/Payments.Mvc/Views/Settings/Edit.cshtml +++ b/src/Payments.Mvc/Views/Settings/Edit.cshtml @@ -6,7 +6,16 @@ ViewData["Title"] = "Edit Team"; } -
+@section AdditionalStyles { + +} + +

@ViewBag.Title

Back @@ -85,6 +94,34 @@ @if (isAdmin) { +
+
+ + +
+ +
+ @if (Model.ShowRechargeDebitNaturalAccount) + { +
+ +
+ + +
+ +
+
+ Optional. Search and select an account, or leave blank to remove the override. + Turning off custom account validation clears this override. +
+
+ } +
@@ -144,6 +181,169 @@ var slug = $('#Slug').val(); $('#slugUrl').text("https://payments.ucdavis.edu/" + slug); } + + var customValidation = $('#UseCustomAccountValidation'); + var naturalAccount = $('#RechargeDebitNaturalAccount'); + if (!customValidation.length || !naturalAccount.length) { + return; + } + + var lookup = $('#naturalAccountLookup'); + var results = $('#naturalAccountResults'); + var status = $('#naturalAccountStatus'); + var searchUrl = '@Url.Action("SearchNaturalAccounts", "Settings", new { team = Model.Slug })'; + var searchTimer; + var searchRequest; + var searchVersion = 0; + var activeResult = -1; + var dropdownDismissed = false; + + function hideResults() { + results.removeClass('show'); + results.children().removeClass('active').attr('aria-selected', 'false'); + naturalAccount.attr('aria-expanded', 'false').removeAttr('aria-activedescendant'); + activeResult = -1; + dropdownDismissed = true; + } + + function showResults() { + if (results.children().length) { + results.addClass('show'); + naturalAccount.attr('aria-expanded', 'true'); + } + } + + function resetSearch() { + clearTimeout(searchTimer); + searchVersion++; + if (searchRequest) { + searchRequest.abort(); + searchRequest = null; + } + hideResults(); + results.empty(); + dropdownDismissed = false; + } + + function updateNaturalAccountControls() { + resetSearch(); + var enabled = customValidation.prop('checked'); + naturalAccount.prop('disabled', !enabled); + if (!enabled) { + naturalAccount.val(''); + } + status.text(enabled ? 'Enter at least 3 characters to search Aggie Enterprise.' : 'Enable custom account validation to select an account.'); + + var code = naturalAccount.val().trim(); + if (enabled && /^[0-9A-Z]{6}$/.test(code)) { + var version = searchVersion; + status.text('Loading natural account name...'); + searchRequest = $.getJSON(searchUrl, { query: code }) + .done(function (accounts) { + if (version !== searchVersion) { + return; + } + var account = accounts.find(function (item) { return item.code === code; }); + status.text(account ? 'Selected: ' + account.code + ' — ' + account.name + : 'This natural account could not be found or is no longer eligible.'); + }) + .fail(function (_, textStatus) { + if (textStatus !== 'abort' && version === searchVersion) { + status.text('Unable to load the natural account name. Search again to retry.'); + } + }); + } + } + + customValidation.on('change', updateNaturalAccountControls); + naturalAccount.on('focus', function () { + dropdownDismissed = false; + showResults(); + }); + lookup.on('focusout', function (event) { + if (!lookup[0].contains(event.relatedTarget)) { + hideResults(); + } + }); + $(document).on('pointerdown', function (event) { + if (!lookup[0].contains(event.target)) { + hideResults(); + } + }); + results.on('mousedown', 'button', function (event) { + event.preventDefault(); + }); + naturalAccount.on('keydown', function (event) { + if (event.key === 'Escape') { + event.preventDefault(); + hideResults(); + } + else if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && results.children().length) { + event.preventDefault(); + dropdownDismissed = false; + showResults(); + var options = results.children(); + activeResult = event.key === 'ArrowDown' + ? (activeResult + 1) % options.length + : (activeResult <= 0 ? options.length - 1 : activeResult - 1); + options.removeClass('active').attr('aria-selected', 'false'); + var option = options.eq(activeResult).addClass('active').attr('aria-selected', 'true'); + naturalAccount.attr('aria-activedescendant', option.attr('id')); + option[0].scrollIntoView({ block: 'nearest' }); + } + else if (event.key === 'Enter' && results.hasClass('show') && activeResult >= 0) { + event.preventDefault(); + results.children().eq(activeResult).trigger('click'); + } + }); + naturalAccount.on('input', function () { + resetSearch(); + var query = naturalAccount.val().trim(); + if (!query) { + naturalAccount.val('').valid(); + status.text('No override selected. Enter at least 3 characters to search.'); + return; + } + if (query.length < 3) { + status.text('Enter at least 3 characters to search Aggie Enterprise.'); + return; + } + + var version = searchVersion; + status.text('Searching Aggie Enterprise...'); + searchTimer = setTimeout(function () { + searchRequest = $.getJSON(searchUrl, { query: query }) + .done(function (accounts) { + if (version !== searchVersion) { + return; + } + status.text(accounts.length ? 'Select a natural account from the dropdown.' : 'No eligible natural accounts found.'); + accounts.forEach(function (account, index) { + $('
@@ -162,4 +191,24 @@ \ No newline at end of file +
+ +@section Scripts { + +} diff --git a/src/Payments.Mvc/appsettings.json b/src/Payments.Mvc/appsettings.json index 3d527fed..54ee6cea 100644 --- a/src/Payments.Mvc/appsettings.json +++ b/src/Payments.Mvc/appsettings.json @@ -46,7 +46,8 @@ "RechargeAutoApprove": false, "RechargeDisableJob": false, "RechargeSlothSourceName": "PaymentsRecharge", - "RechargeAutoApproveDays": 7 + "RechargeAutoApproveDays": 7, + "EnableRechargeDebitNaturalAccount": false }, "Stackify": { "AppName": "payments.mvc", diff --git a/tests/Payments.Tests/ControllerTests/SettingsControllerTests.cs b/tests/Payments.Tests/ControllerTests/SettingsControllerTests.cs new file mode 100644 index 00000000..3f40d5e4 --- /dev/null +++ b/tests/Payments.Tests/ControllerTests/SettingsControllerTests.cs @@ -0,0 +1,472 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Reflection; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Infrastructure; +using Microsoft.AspNetCore.Routing; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Moq; +using Newtonsoft.Json.Linq; +using Payments.Core.Data; +using Payments.Core.Domain; +using Payments.Core.Models.Configuration; +using Payments.Core.Services; +using Payments.Mvc.Controllers; +using Payments.Mvc.Identity; +using Payments.Mvc.Models.Roles; +using Payments.Mvc.Models.TeamViewModels; +using Xunit; + +namespace payments.Tests.ControllerTests +{ + [Trait("Category", "ControllerTests")] + public class SettingsControllerTests : IDisposable + { + private readonly SqliteConnection _connection; + private readonly ApplicationDbContext _dbContext; + private readonly Mock _aggieEnterpriseService; + + public SettingsControllerTests() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + var options = new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options; + _dbContext = new ApplicationDbContext(options); + _dbContext.Database.EnsureCreated(); + _dbContext.Teams.Add(new Team + { + Id = 1, + Name = "Alpha Team", + Slug = "alpha", + ContactName = "Original Contact", + ContactEmail = "original@example.com", + ContactPhoneNumber = "530-555-0100", + UseCustomAccountValidation = true, + RechargeDebitNaturalAccount = "123456", + }); + _dbContext.SaveChanges(); + _dbContext.ChangeTracker.Clear(); + _aggieEnterpriseService = new Mock(MockBehavior.Strict); + } + + [Fact] + public void RechargeDebitNaturalAccountIsDisabledByDefault() + { + Assert.False(new FinanceSettings().EnableRechargeDebitNaturalAccount); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task EditLoadsTheStoredCustomAccountSettingsAndConfiguredVisibility(bool featureEnabled) + { + var controller = CreateController(enableRechargeDebitNaturalAccount: featureEnabled); + + var result = await controller.Edit(); + + var model = Assert.IsType(Assert.IsType(result).Model); + Assert.True(model.UseCustomAccountValidation); + Assert.Equal("123456", model.RechargeDebitNaturalAccount); + Assert.Equal(featureEnabled, model.ShowRechargeDebitNaturalAccount); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DetailsLoadsTheConfiguredAccountVisibility(bool featureEnabled) + { + var userManager = new Mock( + Mock.Of>(), Options.Create(new IdentityOptions()), + null, null, null, null, null, null, null); + userManager.Setup(manager => manager.GetUserAsync(It.IsAny())) + .ReturnsAsync(new User()); + var controller = CreateController( + enableRechargeDebitNaturalAccount: featureEnabled, userManager: userManager.Object); + + var result = await controller.Index(); + + var model = Assert.IsType(Assert.IsType(result).Model); + Assert.Equal(featureEnabled, model.ShowRechargeDebitNaturalAccount); + Assert.Equal("123456", model.RechargeDebitNaturalAccount); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(true, null)] + [InlineData(true, "654321")] + [InlineData(true, "invalid-account")] + [InlineData(false, null)] + [InlineData(false, "invalid-account")] + public async Task DisabledFeaturePreservesTheAccountAndIgnoresSubmittedValuesAndErrors( + bool useCustomAccountValidation, string submittedAccount) + { + var controller = CreateController(enableRechargeDebitNaturalAccount: false); + var model = CreateModel(); + model.UseCustomAccountValidation = useCustomAccountValidation; + model.RechargeDebitNaturalAccount = submittedAccount; + model.ShowRechargeDebitNaturalAccount = true; + ValidateModel(controller, model); + controller.ModelState.AddModelError(nameof(model.RechargeDebitNaturalAccount), "Submitted account error."); + + var result = await controller.Edit(model); + + Assert.IsType(result); + var stored = await ReadTeam(); + Assert.Equal(model.Name, stored.Name); + Assert.Equal(useCustomAccountValidation, stored.UseCustomAccountValidation); + Assert.Equal("123456", stored.RechargeDebitNaturalAccount); + Assert.False(model.ShowRechargeDebitNaturalAccount); + Assert.False(controller.ModelState.ContainsKey(nameof(model.RechargeDebitNaturalAccount))); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task InvalidEditUsesConfiguredVisibilityInsteadOfThePostedValue(bool featureEnabled) + { + var controller = CreateController(enableRechargeDebitNaturalAccount: featureEnabled); + var model = CreateModel(); + model.ShowRechargeDebitNaturalAccount = !featureEnabled; + controller.ModelState.AddModelError(nameof(model.Name), "Team name is required."); + + var result = await controller.Edit(model); + + Assert.Same(model, Assert.IsType(result).Model); + Assert.Equal(featureEnabled, model.ShowRechargeDebitNaturalAccount); + Assert.NotEmpty(controller.ModelState[nameof(model.Name)].Errors); + await AssertOriginalTeamIsUnchanged(); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("654321")] + [InlineData("12X456")] + public async Task SystemUserCanSaveAnAccountValidatedByAggieEnterprise(string account) + { + var controller = CreateController(); + var model = CreateModel(); + model.RechargeDebitNaturalAccount = account; + ValidateModel(controller, model); + _aggieEnterpriseService.Setup(service => service.IsNaturalAccountValid(account)) + .ReturnsAsync(true); + + var result = await controller.Edit(model); + + var redirect = Assert.IsType(result); + Assert.Equal(nameof(SettingsController.Index), redirect.ActionName); + var stored = await ReadTeam(); + Assert.Equal(model.Name, stored.Name); + Assert.True(stored.UseCustomAccountValidation); + Assert.Equal(account, stored.RechargeDebitNaturalAccount); + _aggieEnterpriseService.Verify(service => service.IsNaturalAccountValid(account), Times.Once); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task SystemUserCanEnableCustomValidationWithoutAnOverride(string account) + { + var team = await _dbContext.Teams.SingleAsync(); + team.UseCustomAccountValidation = false; + team.RechargeDebitNaturalAccount = null; + await _dbContext.SaveChangesAsync(); + _dbContext.ChangeTracker.Clear(); + var controller = CreateController(); + var model = CreateModel(); + model.RechargeDebitNaturalAccount = account; + ValidateModel(controller, model); + + var result = await controller.Edit(model); + + Assert.IsType(result); + var stored = await ReadTeam(); + Assert.True(stored.UseCustomAccountValidation); + Assert.True(string.IsNullOrEmpty(stored.RechargeDebitNaturalAccount)); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("654321")] + [InlineData("invalid-account")] + public async Task DisablingCustomValidationClearsTheOverrideAndIgnoresItsValidationErrors(string account) + { + var controller = CreateController(); + var model = CreateModel(); + model.UseCustomAccountValidation = false; + model.RechargeDebitNaturalAccount = account; + ValidateModel(controller, model); + + var result = await controller.Edit(model); + + Assert.IsType(result); + var stored = await ReadTeam(); + Assert.Equal(model.Name, stored.Name); + Assert.False(stored.UseCustomAccountValidation); + Assert.Null(stored.RechargeDebitNaturalAccount); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(true, "123456", false)] + [InlineData(false, null, true)] + public async Task TeamUserCannotOverpostCustomAccountSettingsButCanSaveOtherEdits( + bool storedFlag, string storedAccount, bool submittedFlag) + { + var team = await _dbContext.Teams.SingleAsync(); + team.UseCustomAccountValidation = storedFlag; + team.RechargeDebitNaturalAccount = storedAccount; + await _dbContext.SaveChangesAsync(); + _dbContext.ChangeTracker.Clear(); + var controller = CreateController(isSystemUser: false); + var model = CreateModel(); + model.UseCustomAccountValidation = submittedFlag; + model.RechargeDebitNaturalAccount = "invalid-account"; + ValidateModel(controller, model); + controller.ModelState.AddModelError(nameof(model.UseCustomAccountValidation), "Invalid boolean value."); + + var result = await controller.Edit(model); + + Assert.IsType(result); + var stored = await ReadTeam(); + Assert.Equal(model.Name, stored.Name); + Assert.Equal(model.ContactEmail, stored.ContactEmail); + Assert.Equal(storedFlag, stored.UseCustomAccountValidation); + Assert.Equal(storedAccount, stored.RechargeDebitNaturalAccount); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FailedAccountValidationDoesNotSaveAnyTeamChanges(bool serviceFails) + { + var controller = CreateController(); + var model = CreateModel(); + var validation = _aggieEnterpriseService.Setup(service => service.IsNaturalAccountValid("654321")); + if (serviceFails) + { + validation.ThrowsAsync(new InvalidOperationException("Service unavailable")); + } + else + { + validation.ReturnsAsync(false); + } + + var result = await controller.Edit(model); + + Assert.Same(model, Assert.IsType(result).Model); + Assert.NotEmpty(controller.ModelState[nameof(model.RechargeDebitNaturalAccount)].Errors); + await AssertOriginalTeamIsUnchanged(); + _aggieEnterpriseService.Verify(service => service.IsNaturalAccountValid("654321"), Times.Once); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData("12345")] + [InlineData("1234567")] + [InlineData("12-456")] + [InlineData("123456")] + public async Task MalformedAccountIsRejectedBeforeCallingAggieEnterprise(string account) + { + var controller = CreateController(); + var model = CreateModel(); + model.RechargeDebitNaturalAccount = account; + ValidateModel(controller, model); + + var result = await controller.Edit(model); + + Assert.Same(model, Assert.IsType(result).Model); + Assert.NotEmpty(controller.ModelState[nameof(model.RechargeDebitNaturalAccount)].Errors); + await AssertOriginalTeamIsUnchanged(); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task IgnoringRestrictedAccountFieldsDoesNotIgnoreOtherValidationErrors(bool isSystemUser) + { + var controller = CreateController(isSystemUser); + var model = CreateModel(); + model.UseCustomAccountValidation = false; + model.RechargeDebitNaturalAccount = "invalid-account"; + ValidateModel(controller, model); + controller.ModelState.AddModelError(nameof(model.Name), "Team name is required."); + + var result = await controller.Edit(model); + + Assert.IsType(result); + Assert.NotEmpty(controller.ModelState[nameof(model.Name)].Errors); + await AssertOriginalTeamIsUnchanged(); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Fact] + public void NaturalAccountSearchRequiresTheSystemRoleAndGetMethod() + { + var method = typeof(SettingsController).GetMethod(nameof(SettingsController.SearchNaturalAccounts)); + + Assert.NotNull(method.GetCustomAttribute()); + var authorization = Assert.Single(method.GetCustomAttributes()); + Assert.Equal(ApplicationRoleCodes.Admin, authorization.Roles); + } + + [Theory] + [InlineData(null)] + [InlineData("12")] + [InlineData("travel")] + public async Task DisabledFeatureRejectsSearchWithoutCallingAggieEnterprise(string query) + { + var result = await CreateController(enableRechargeDebitNaturalAccount: false) + .SearchNaturalAccounts(query); + + Assert.IsType(result); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("12")] + [InlineData(" 12 ")] + public async Task SearchRejectsQueriesShorterThanThreeCharacters(string query) + { + var result = await CreateController().SearchNaturalAccounts(query); + + Assert.Equal(StatusCodes.Status400BadRequest, Assert.IsAssignableFrom(result).StatusCode); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Fact] + public async Task SearchRejectsQueriesLongerThanOneHundredCharacters() + { + var result = await CreateController().SearchNaturalAccounts(new string('a', 101)); + + Assert.Equal(StatusCodes.Status400BadRequest, Assert.IsAssignableFrom(result).StatusCode); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Theory] + [InlineData(3)] + [InlineData(100)] + public async Task SearchTrimsQueriesAndReturnsAccountCodesAndNames(int queryLength) + { + var query = new string('a', queryLength); + _aggieEnterpriseService.Setup(service => service.SearchNaturalAccounts(query)) + .ReturnsAsync(new Dictionary { ["654321"] = "Example natural account" }); + + var result = await CreateController().SearchNaturalAccounts(" " + query + " "); + + var json = Assert.IsType(result); + var account = Assert.Single(JArray.FromObject(json.Value)); + Assert.Equal("654321", account.Value("code")); + Assert.Equal("Example natural account", account.Value("name")); + _aggieEnterpriseService.Verify(service => service.SearchNaturalAccounts(query), Times.Once); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + [Fact] + public async Task SearchReturnsServiceUnavailableWhenAggieEnterpriseFails() + { + _aggieEnterpriseService.Setup(service => service.SearchNaturalAccounts("travel")) + .ThrowsAsync(new InvalidOperationException("Service unavailable")); + + var result = await CreateController().SearchNaturalAccounts("travel"); + + Assert.Equal(StatusCodes.Status503ServiceUnavailable, Assert.IsAssignableFrom(result).StatusCode); + _aggieEnterpriseService.Verify(service => service.SearchNaturalAccounts("travel"), Times.Once); + _aggieEnterpriseService.VerifyNoOtherCalls(); + } + + private SettingsController CreateController( + bool isSystemUser = true, bool enableRechargeDebitNaturalAccount = true, + ApplicationUserManager userManager = null) + { + var claims = isSystemUser + ? new[] { new Claim(ClaimTypes.Role, ApplicationRoleCodes.Admin) } + : Array.Empty(); + var routeData = new RouteData(); + routeData.Values.Add("team", "alpha"); + var financeSettings = Options.Create(new FinanceSettings + { + EnableRechargeDebitNaturalAccount = enableRechargeDebitNaturalAccount, + }); + return new SettingsController(_dbContext, null, null, null, userManager, + _aggieEnterpriseService.Object, financeSettings) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity(claims, "Test")), + }, + RouteData = routeData, + }, + }; + } + + private static EditTeamViewModel CreateModel() + { + return new EditTeamViewModel + { + Name = "Updated Team", + Slug = "alpha", + ContactName = "Updated Contact", + ContactEmail = "updated@example.com", + ContactPhoneNumber = "530-555-0101", + IsActive = true, + UseCustomAccountValidation = true, + RechargeDebitNaturalAccount = "654321", + }; + } + + private static void ValidateModel(SettingsController controller, EditTeamViewModel model) + { + var errors = new List(); + Validator.TryValidateObject(model, new ValidationContext(model), errors, validateAllProperties: true); + foreach (var error in errors) + { + foreach (var member in error.MemberNames) + { + controller.ModelState.AddModelError(member, error.ErrorMessage); + } + } + } + + private Task ReadTeam() + { + return _dbContext.Teams.AsNoTracking().SingleAsync(); + } + + private async Task AssertOriginalTeamIsUnchanged() + { + var stored = await ReadTeam(); + Assert.Equal("Alpha Team", stored.Name); + Assert.Equal("Original Contact", stored.ContactName); + Assert.Equal("original@example.com", stored.ContactEmail); + Assert.True(stored.UseCustomAccountValidation); + Assert.Equal("123456", stored.RechargeDebitNaturalAccount); + } + + public void Dispose() + { + _dbContext.Dispose(); + _connection.Dispose(); + } + } +} diff --git a/tests/Payments.Tests/DatabaseTests/TeamTests.cs b/tests/Payments.Tests/DatabaseTests/TeamTests.cs index 27f52fa6..be256ddd 100644 --- a/tests/Payments.Tests/DatabaseTests/TeamTests.cs +++ b/tests/Payments.Tests/DatabaseTests/TeamTests.cs @@ -70,6 +70,10 @@ public void TestAllFieldsInTheDatabaseHaveBeenTested() { "[Newtonsoft.Json.JsonIgnoreAttribute()]", })); + expectedFields.Add(new NameAndType("RechargeDebitNaturalAccount", "System.String", new List + { + "[System.ComponentModel.DataAnnotations.StringLengthAttribute((Int32)6)]", + })); expectedFields.Add(new NameAndType("SlothAutoApprove", "System.Boolean", new List())); expectedFields.Add(new NameAndType("Slug", "System.String", new List { @@ -78,6 +82,7 @@ public void TestAllFieldsInTheDatabaseHaveBeenTested() "[System.ComponentModel.DataAnnotations.RequiredAttribute()]", "[System.ComponentModel.DataAnnotations.StringLengthAttribute((Int32)40, MinimumLength = 3, ErrorMessage = \"Slug must be between 3 and 40 characters\")]", })); + expectedFields.Add(new NameAndType("UseCustomAccountValidation", "System.Boolean", new List())); expectedFields.Add(new NameAndType("WebHookApiKey", "System.String", new List { "[Newtonsoft.Json.JsonIgnoreAttribute()]", diff --git a/tests/Payments.Tests/JobTests/MoneyMovementJobTests.cs b/tests/Payments.Tests/JobTests/MoneyMovementJobTests.cs index 8d65774b..ac848c5e 100644 --- a/tests/Payments.Tests/JobTests/MoneyMovementJobTests.cs +++ b/tests/Payments.Tests/JobTests/MoneyMovementJobTests.cs @@ -98,7 +98,7 @@ public async Task FindBankReconcileTransactions_UsesValidOverrideAndFallsBackWhe var aggieEnterpriseService = new Mock(); aggieEnterpriseService - .Setup(service => service.IsAccountValid("override-chart-string", true)) + .Setup(service => service.IsAccountValid("override-chart-string", team, true)) .ReturnsAsync(new AccountValidationModel { IsValid = overrideIsValid, @@ -125,8 +125,8 @@ public async Task FindBankReconcileTransactions_UsesValidOverrideAndFallsBackWhe && transfer.Description == "Funds Distribution"); Assert.Equal(expectedChartString, incomeTransfer.FinancialSegmentString); aggieEnterpriseService.Verify( - service => service.IsAccountValid("override-chart-string", true), + service => service.IsAccountValid("override-chart-string", team, true), Times.Once); } } -} \ No newline at end of file +} diff --git a/tests/Payments.Tests/ServiceTests/InvoiceServiceTests.cs b/tests/Payments.Tests/ServiceTests/InvoiceServiceTests.cs index 5cc4331e..ccc6c3c2 100644 --- a/tests/Payments.Tests/ServiceTests/InvoiceServiceTests.cs +++ b/tests/Payments.Tests/ServiceTests/InvoiceServiceTests.cs @@ -69,6 +69,7 @@ public async Task CreateInvoices_CopiesExternalDetailsToCreatedInvoices() [Fact] public async Task CreateInvoices_InvalidRechargeAccount_IdentifiesRechargeAccountsParameter() { + var team = new Team { Id = 1 }; var dbContext = new Mock(new DbContextOptions()); dbContext .Setup(context => context.FinancialAccounts) @@ -77,7 +78,7 @@ public async Task CreateInvoices_InvalidRechargeAccount_IdentifiesRechargeAccoun var aggieEnterpriseService = new Mock(); aggieEnterpriseService .Setup(service => service.IsRechargeAccountValid( - "invalid-chart-string", RechargeAccount.CreditDebit.Credit, true)) + "invalid-chart-string", RechargeAccount.CreditDebit.Credit, team, true)) .ReturnsAsync(new AccountValidationModel { IsValid = false }); var service = new InvoiceService( @@ -99,7 +100,7 @@ public async Task CreateInvoices_InvalidRechargeAccount_IdentifiesRechargeAccoun }; var exception = await Assert.ThrowsAsync( - () => service.CreateInvoices(model, new Team { Id = 1 })); + () => service.CreateInvoices(model, team)); Assert.Equal(nameof(model.RechargeAccounts), exception.ParamName); } @@ -337,6 +338,7 @@ private static (InvoiceService service, CreateInvoiceModel model, Team team) Cre decimal rechargeAmount) { const string chartString = "valid-chart-string"; + var team = new Team { Id = 1 }; var dbContext = new Mock(new DbContextOptions()); dbContext .Setup(context => context.FinancialAccounts) @@ -348,7 +350,7 @@ private static (InvoiceService service, CreateInvoiceModel model, Team team) Cre var aggieEnterpriseService = new Mock(); aggieEnterpriseService .Setup(service => service.IsRechargeAccountValid( - chartString, RechargeAccount.CreditDebit.Credit, true)) + chartString, RechargeAccount.CreditDebit.Credit, team, true)) .ReturnsAsync(new AccountValidationModel { IsValid = true, @@ -388,7 +390,7 @@ private static (InvoiceService service, CreateInvoiceModel model, Team team) Cre }, }; - return (service, model, new Team { Id = 1 }); + return (service, model, team); } } }