Phase F: Customer/Vendor Statements, Payment Terms Parser, Tax Rates

F1: GetCustomerStatementAsync/GetVendorStatementAsync on IFinancialReportService;
    StatementLineDto; CustomerStatementDto/VendorStatementDto; Statement action on
    CustomersController + VendorsController; Statement views + PDF download via
    StatementPdfHelper (QuestPDF); Statement button on Customer/Vendor Details pages.

F2: PaymentTermsParser static helper (CalculateDueDate, ParseEarlyPaymentDiscount);
    EarlyPaymentDiscountPercent/Days on Invoice entity; GetCustomerPaymentTerms AJAX
    endpoint on InvoicesController auto-populates Terms + due date on customer select;
    early payment discount notice on Invoice Create.

F3: TaxRate entity (Name/Rate/State/IsDefault/IsActive, tenant-filtered);
    IUnitOfWork.TaxRates + UnitOfWork + ApplicationDbContext; TaxRatesController
    (Index/Create/Edit/Delete/ToggleActive, CompanyAdminOnly); GetTaxRateForCustomer
    AJAX endpoint; Tax Rates in Settings gear menu.

Also fixes AddVendorCredits migration: VendorCreditApplications FKs changed from
CASCADE to NoAction to resolve SQL Server error 1785 (multiple cascade paths).
Migration: AddPaymentTermsAndTaxRates applied locally; 200/200 unit tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-10 10:55:22 -04:00
parent 1229081436
commit d3a5d827f9
27 changed files with 11492 additions and 12 deletions
@@ -26,6 +26,7 @@ public class CustomersController : Controller
private readonly ISubscriptionService _subscriptionService;
private readonly ITenantContext _tenantContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IFinancialReportService _financialReports;
public CustomersController(
IUnitOfWork unitOfWork,
@@ -34,7 +35,8 @@ public class CustomersController : Controller
INotificationService notificationService,
ISubscriptionService subscriptionService,
ITenantContext tenantContext,
UserManager<ApplicationUser> userManager)
UserManager<ApplicationUser> userManager,
IFinancialReportService financialReports)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
@@ -43,6 +45,7 @@ public class CustomersController : Controller
_subscriptionService = subscriptionService;
_tenantContext = tenantContext;
_userManager = userManager;
_financialReports = financialReports;
}
/// <summary>
@@ -935,6 +938,30 @@ public class CustomersController : Controller
return RedirectToAction(nameof(Details), new { id });
}
/// <summary>
/// Displays or downloads a dated activity statement for a customer.
/// Pass <c>pdf=true</c> to download the QuestPDF version; otherwise renders the HTML view.
/// </summary>
[HttpGet]
public async Task<IActionResult> Statement(int id, DateTime? from, DateTime? to, bool pdf = false)
{
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
var fromDate = from ?? new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
var toDate = to ?? DateTime.Today;
var dto = await _financialReports.GetCustomerStatementAsync(companyId, id, fromDate, toDate);
if (pdf)
{
var bytes = StatementPdfHelper.Generate(
dto.CustomerName, dto.CompanyName, dto.CustomerAddress,
dto.From, dto.To, dto.OpeningBalance, dto.Lines, dto.ClosingBalance, isVendor: false);
return File(bytes, "application/pdf", $"Statement-{dto.CustomerName}-{toDate:yyyyMMdd}.pdf");
}
return View(dto);
}
/// <summary>
/// Generates the next sequential credit memo number in CM-YYMM-#### format.
/// Uses <c>ignoreQueryFilters: true</c> when scanning all existing memos so that
@@ -1851,6 +1851,54 @@ public class InvoicesController : Controller
return $"{prefix}{(maxNum + 1):D4}";
}
/// <summary>
/// Returns the customer's payment terms, derived due date, and early-payment discount info
/// for the Invoice Create form so JavaScript can auto-populate those fields on customer selection.
/// </summary>
[HttpGet]
public async Task<IActionResult> GetCustomerPaymentTerms(int customerId)
{
var customer = await _unitOfWork.Customers.GetByIdAsync(customerId);
if (customer == null) return NotFound();
var invoiceDate = DateTime.Today;
var dueDate = PaymentTermsParser.CalculateDueDate(customer.PaymentTerms, invoiceDate);
var (discountPercent, discountDays) = PaymentTermsParser.ParseEarlyPaymentDiscount(customer.PaymentTerms);
return Json(new
{
paymentTerms = customer.PaymentTerms,
dueDate = dueDate?.ToString("yyyy-MM-dd"),
earlyPaymentDiscountPercent = discountPercent,
earlyPaymentDiscountDays = discountDays,
isTaxExempt = customer.IsTaxExempt
});
}
/// <summary>
/// Returns the default active tax rate for the current company, or zero for tax-exempt customers.
/// Called by the Invoice Create form when the customer selection changes.
/// </summary>
[HttpGet]
public async Task<IActionResult> GetTaxRateForCustomer(int customerId)
{
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
var customer = await _unitOfWork.Customers.GetByIdAsync(customerId);
if (customer == null) return NotFound();
if (customer.IsTaxExempt)
return Json(new { taxPercent = 0m, taxRateName = (string?)null });
var defaultRate = await _unitOfWork.TaxRates
.FirstOrDefaultAsync(r => r.IsDefault && r.IsActive && !r.IsDeleted);
return Json(new
{
taxPercent = defaultRate?.Rate ?? 0m,
taxRateName = defaultRate?.Name
});
}
/// <summary>
/// Populates ViewBag data used by both Create GET and Create POST (on validation failure re-display):
/// — Active customer list for the customer dropdown.
@@ -0,0 +1,139 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Interfaces;
using PowderCoating.Shared.Constants;
namespace PowderCoating.Web.Controllers;
/// <summary>
/// Manages named tax rates used to pre-fill the tax percent field on invoices when a taxable
/// customer is selected. Only one rate may be marked as default at a time; that default is
/// auto-applied via the GetTaxRateForCustomer AJAX endpoint on the Invoice Create form.
/// </summary>
[Authorize(Policy = AppConstants.Policies.CompanyAdminOnly)]
public class TaxRatesController : Controller
{
private readonly IUnitOfWork _unitOfWork;
private readonly ITenantContext _tenantContext;
private readonly ILogger<TaxRatesController> _logger;
public TaxRatesController(
IUnitOfWork unitOfWork,
ITenantContext tenantContext,
ILogger<TaxRatesController> logger)
{
_unitOfWork = unitOfWork;
_tenantContext = tenantContext;
_logger = logger;
}
/// <summary>Lists all tax rates for the current company.</summary>
public async Task<IActionResult> Index()
{
var rates = await _unitOfWork.TaxRates.GetAllAsync();
return View(rates.OrderBy(r => r.Name).ToList());
}
[HttpGet]
public IActionResult Create() => View(new TaxRate());
/// <summary>Creates a new tax rate. Enforces that only one rate is the default.</summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(TaxRate model)
{
if (!ModelState.IsValid) return View(model);
if (model.IsDefault)
await ClearOtherDefaultsAsync(0);
await _unitOfWork.TaxRates.AddAsync(model);
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Tax rate \"{model.Name}\" created.";
return RedirectToAction(nameof(Index));
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
var rate = await _unitOfWork.TaxRates.GetByIdAsync(id);
if (rate == null) return NotFound();
return View(rate);
}
/// <summary>Updates an existing tax rate. Clears default flag on other rates when IsDefault is set.</summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, TaxRate model)
{
if (id != model.Id) return BadRequest();
if (!ModelState.IsValid) return View(model);
var rate = await _unitOfWork.TaxRates.GetByIdAsync(id);
if (rate == null) return NotFound();
if (model.IsDefault && !rate.IsDefault)
await ClearOtherDefaultsAsync(id);
rate.Name = model.Name;
rate.Rate = model.Rate;
rate.State = model.State;
rate.Description = model.Description;
rate.IsDefault = model.IsDefault;
rate.IsActive = model.IsActive;
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Tax rate \"{rate.Name}\" updated.";
return RedirectToAction(nameof(Index));
}
/// <summary>Toggles IsActive without a full page reload.</summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ToggleActive(int id)
{
var rate = await _unitOfWork.TaxRates.GetByIdAsync(id);
if (rate == null) return NotFound();
rate.IsActive = !rate.IsActive;
if (!rate.IsActive) rate.IsDefault = false;
await _unitOfWork.CompleteAsync();
return RedirectToAction(nameof(Index));
}
/// <summary>Soft-deletes a tax rate. Blocked when the rate is currently the default.</summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id)
{
var rate = await _unitOfWork.TaxRates.GetByIdAsync(id);
if (rate == null) return NotFound();
if (rate.IsDefault)
{
TempData["Error"] = "Cannot delete the default tax rate. Set another rate as default first.";
return RedirectToAction(nameof(Index));
}
await _unitOfWork.TaxRates.SoftDeleteAsync(id);
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Tax rate \"{rate.Name}\" deleted.";
return RedirectToAction(nameof(Index));
}
/// <summary>
/// Clears IsDefault on all rates except the one with <paramref name="exceptId"/>.
/// Called before saving a newly-designated default to enforce the single-default invariant.
/// </summary>
private async Task ClearOtherDefaultsAsync(int exceptId)
{
var others = await _unitOfWork.TaxRates.FindAsync(r => r.IsDefault && r.Id != exceptId);
foreach (var r in others)
r.IsDefault = false;
}
}
@@ -7,9 +7,11 @@ using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using PowderCoating.Application.DTOs.Common;
using PowderCoating.Application.DTOs.Vendor;
using PowderCoating.Application.Interfaces;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Enums;
using PowderCoating.Core.Interfaces;
using PowderCoating.Web.Helpers;
namespace PowderCoating.Web.Controllers;
@@ -27,17 +29,23 @@ public class VendorsController : Controller
private readonly IMapper _mapper;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<VendorsController> _logger;
private readonly IFinancialReportService _financialReports;
private readonly ITenantContext _tenantContext;
public VendorsController(
IUnitOfWork unitOfWork,
IMapper mapper,
UserManager<ApplicationUser> userManager,
ILogger<VendorsController> logger)
ILogger<VendorsController> logger,
IFinancialReportService financialReports,
ITenantContext tenantContext)
{
_unitOfWork = unitOfWork;
_mapper = mapper;
_userManager = userManager;
_logger = logger;
_financialReports = financialReports;
_tenantContext = tenantContext;
}
/// <summary>
@@ -377,6 +385,29 @@ public class VendorsController : Controller
/// <summary>
/// Populates <c>ViewBag.ExpenseAccounts</c> with active Expense, Cost of Goods, and Asset accounts
/// <summary>
/// Displays or downloads a dated activity statement for a vendor.
/// </summary>
[HttpGet]
public async Task<IActionResult> Statement(int id, DateTime? from, DateTime? to, bool pdf = false)
{
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
var fromDate = from ?? new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
var toDate = to ?? DateTime.Today;
var dto = await _financialReports.GetVendorStatementAsync(companyId, id, fromDate, toDate);
if (pdf)
{
var bytes = StatementPdfHelper.Generate(
dto.VendorName, dto.CompanyName, null,
dto.From, dto.To, dto.OpeningBalance, dto.Lines, dto.ClosingBalance, isVendor: true);
return File(bytes, "application/pdf", $"Statement-{dto.VendorName}-{toDate:yyyyMMdd}.pdf");
}
return View(dto);
}
/// for the vendor's default expense account dropdown. All three account types are included because
/// vendor bills can legitimately be coded to COGS (powder, materials) or asset accounts (equipment
/// purchases) in addition to regular operating expenses. A "— None —" placeholder is prepended so