Phase D: Add Vendor Credits (AP cycle completion)

- VendorCredit, VendorCreditLineItem, VendorCreditApplication entities
- VendorCreditStatus enum (Open, PartiallyApplied, Applied, Voided)
- Migration AddVendorCredits: three new tables
- IUnitOfWork/UnitOfWork wired with all three repositories
- VendorCreditsController: Index (status tabs), Create, Details, Post, Apply, Void
- Post action: DR AP, CR each expense line (reverses original expense)
- Apply action: links credit to bill, updates Bill.AmountPaid and bill status
- Views: Index (summary cards + table), Create (dynamic line grid), Details (apply panel)
- Nav: Vendor Credits added to Finance section in _Layout

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-10 00:03:14 -04:00
parent a33687f7bd
commit cf9dcfb4c1
13 changed files with 11387 additions and 3 deletions
@@ -200,3 +200,59 @@ public class JournalEntryLine : BaseEntity
public virtual JournalEntry JournalEntry { get; set; } = null!;
public virtual Account Account { get; set; } = null!;
}
/// <summary>
/// A credit note received from a vendor (returned goods, pricing dispute, short-ship).
/// Reduces Accounts Payable and reverses the original expense/COGS when posted.
/// Numbering: VC-YYMM-####
/// </summary>
public class VendorCredit : BaseEntity
{
public string CreditNumber { get; set; } = string.Empty;
public int VendorId { get; set; }
/// <summary>AP account this credit reduces (default: Accounts Payable 2000).</summary>
public int APAccountId { get; set; }
public DateTime CreditDate { get; set; } = DateTime.UtcNow;
public VendorCreditStatus Status { get; set; } = VendorCreditStatus.Open;
public decimal Total { get; set; }
public decimal RemainingAmount { get; set; }
public string? Memo { get; set; }
// Navigation
public virtual Vendor Vendor { get; set; } = null!;
public virtual Account APAccount { get; set; } = null!;
public virtual ICollection<VendorCreditLineItem> LineItems { get; set; } = new List<VendorCreditLineItem>();
public virtual ICollection<VendorCreditApplication> Applications { get; set; } = new List<VendorCreditApplication>();
}
/// <summary>
/// A single line on a vendor credit, each reversing a specific expense/COGS account.
/// </summary>
public class VendorCreditLineItem : BaseEntity
{
public int VendorCreditId { get; set; }
/// <summary>Expense/COGS account being reversed by this line.</summary>
public int? AccountId { get; set; }
public string Description { get; set; } = string.Empty;
public decimal Amount { get; set; }
// Navigation
public virtual VendorCredit VendorCredit { get; set; } = null!;
public virtual Account? Account { get; set; }
}
/// <summary>
/// Records the application of a vendor credit against a specific vendor bill.
/// No additional GL posting is needed — AP was already adjusted when the credit was posted.
/// </summary>
public class VendorCreditApplication : BaseEntity
{
public int VendorCreditId { get; set; }
public int BillId { get; set; }
public decimal Amount { get; set; }
public DateTime AppliedDate { get; set; } = DateTime.UtcNow;
// Navigation
public virtual VendorCredit VendorCredit { get; set; } = null!;
public virtual Bill Bill { get; set; } = null!;
}
@@ -80,6 +80,14 @@ public enum AccountingMethod
Accrual = 1
}
public enum VendorCreditStatus
{
Open = 0,
PartiallyApplied = 1,
Applied = 2,
Voided = 3
}
/// <summary>Lifecycle state of a Manual Journal Entry.</summary>
public enum JournalEntryStatus
{
@@ -95,6 +95,11 @@ public interface IUnitOfWork : IDisposable
IRepository<JournalEntry> JournalEntries { get; }
IRepository<JournalEntryLine> JournalEntryLines { get; }
// Vendor Credits
IRepository<VendorCredit> VendorCredits { get; }
IRepository<VendorCreditLineItem> VendorCreditLineItems { get; }
IRepository<VendorCreditApplication> VendorCreditApplications { get; }
// Notifications — typed repository for IgnoreQueryFilters-based history lookups
INotificationLogRepository NotificationLogs { get; }
IRepository<NotificationTemplate> NotificationTemplates { get; }
@@ -329,6 +329,13 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
/// <summary>Individual debit/credit lines within a journal entry; soft-delete only (access controlled through parent JournalEntry).</summary>
public DbSet<JournalEntryLine> JournalEntryLines { get; set; }
/// <summary>Credit notes received from vendors (returned goods, pricing disputes); tenant-filtered with soft delete.</summary>
public DbSet<VendorCredit> VendorCredits { get; set; }
/// <summary>Expense-reversal line items on a vendor credit; soft-delete only.</summary>
public DbSet<VendorCreditLineItem> VendorCreditLineItems { get; set; }
/// <summary>Application records linking a vendor credit to a specific bill; soft-delete only.</summary>
public DbSet<VendorCreditApplication> VendorCreditApplications { get; set; }
// Job Templates
/// <summary>Reusable job templates that pre-populate job items, coats, and prep services on job creation.</summary>
public DbSet<JobTemplate> JobTemplates { get; set; }
@@ -624,6 +631,12 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
modelBuilder.Entity<JournalEntryLine>().HasQueryFilter(e => !e.IsDeleted);
// Vendor Credits: tenant-filtered; child rows soft-delete only
modelBuilder.Entity<VendorCredit>().HasQueryFilter(e =>
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
modelBuilder.Entity<VendorCreditLineItem>().HasQueryFilter(e => !e.IsDeleted);
modelBuilder.Entity<VendorCreditApplication>().HasQueryFilter(e => !e.IsDeleted);
// Purchase Orders
modelBuilder.Entity<PurchaseOrder>().HasQueryFilter(e =>
!e.IsDeleted && (IsPlatformAdmin || e.CompanyId == CurrentCompanyId));
@@ -650,6 +663,20 @@ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDataPro
.HasForeignKey(je => je.ReversalOfId)
.OnDelete(DeleteBehavior.Restrict);
// VendorCredit → APAccount (no cascade)
modelBuilder.Entity<VendorCredit>()
.HasOne(vc => vc.APAccount)
.WithMany()
.HasForeignKey(vc => vc.APAccountId)
.OnDelete(DeleteBehavior.Restrict);
// VendorCreditLineItem → Account (nullable, no cascade)
modelBuilder.Entity<VendorCreditLineItem>()
.HasOne(li => li.Account)
.WithMany()
.HasForeignKey(li => li.AccountId)
.OnDelete(DeleteBehavior.Restrict);
// Vendor → DefaultExpenseAccount (no cascade)
modelBuilder.Entity<Vendor>()
.HasOne(s => s.DefaultExpenseAccount)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,212 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PowderCoating.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddVendorCredits : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "VendorCredits",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CreditNumber = table.Column<string>(type: "nvarchar(max)", nullable: false),
VendorId = table.Column<int>(type: "int", nullable: false),
APAccountId = table.Column<int>(type: "int", nullable: false),
CreditDate = table.Column<DateTime>(type: "datetime2", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
Total = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
RemainingAmount = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
Memo = table.Column<string>(type: "nvarchar(max)", nullable: true),
CompanyId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_VendorCredits", x => x.Id);
table.ForeignKey(
name: "FK_VendorCredits_Accounts_APAccountId",
column: x => x.APAccountId,
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_VendorCredits_Vendors_VendorId",
column: x => x.VendorId,
principalTable: "Vendors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "VendorCreditApplications",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
VendorCreditId = table.Column<int>(type: "int", nullable: false),
BillId = table.Column<int>(type: "int", nullable: false),
Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
AppliedDate = table.Column<DateTime>(type: "datetime2", nullable: false),
CompanyId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_VendorCreditApplications", x => x.Id);
table.ForeignKey(
name: "FK_VendorCreditApplications_Bills_BillId",
column: x => x.BillId,
principalTable: "Bills",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_VendorCreditApplications_VendorCredits_VendorCreditId",
column: x => x.VendorCreditId,
principalTable: "VendorCredits",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "VendorCreditLineItems",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
VendorCreditId = table.Column<int>(type: "int", nullable: false),
AccountId = table.Column<int>(type: "int", nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: false),
Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false),
CompanyId = table.Column<int>(type: "int", nullable: false),
CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
CreatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
UpdatedBy = table.Column<string>(type: "nvarchar(max)", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedAt = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedBy = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_VendorCreditLineItems", x => x.Id);
table.ForeignKey(
name: "FK_VendorCreditLineItems_Accounts_AccountId",
column: x => x.AccountId,
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_VendorCreditLineItems_VendorCredits_VendorCreditId",
column: x => x.VendorCreditId,
principalTable: "VendorCredits",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(6994));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 2,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(7001));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 3,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(7003));
migrationBuilder.CreateIndex(
name: "IX_VendorCreditApplications_BillId",
table: "VendorCreditApplications",
column: "BillId");
migrationBuilder.CreateIndex(
name: "IX_VendorCreditApplications_VendorCreditId",
table: "VendorCreditApplications",
column: "VendorCreditId");
migrationBuilder.CreateIndex(
name: "IX_VendorCreditLineItems_AccountId",
table: "VendorCreditLineItems",
column: "AccountId");
migrationBuilder.CreateIndex(
name: "IX_VendorCreditLineItems_VendorCreditId",
table: "VendorCreditLineItems",
column: "VendorCreditId");
migrationBuilder.CreateIndex(
name: "IX_VendorCredits_APAccountId",
table: "VendorCredits",
column: "APAccountId");
migrationBuilder.CreateIndex(
name: "IX_VendorCredits_VendorId",
table: "VendorCredits",
column: "VendorId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "VendorCreditApplications");
migrationBuilder.DropTable(
name: "VendorCreditLineItems");
migrationBuilder.DropTable(
name: "VendorCredits");
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 1,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9350));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 2,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9357));
migrationBuilder.UpdateData(
table: "PricingTiers",
keyColumn: "Id",
keyValue: 3,
column: "CreatedAt",
value: new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9359));
}
}
}
@@ -6206,7 +6206,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 1,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9350),
CreatedAt = new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(6994),
Description = "Standard pricing for regular customers",
DiscountPercent = 0m,
IsActive = true,
@@ -6217,7 +6217,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 2,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9357),
CreatedAt = new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(7001),
Description = "5% discount for preferred customers",
DiscountPercent = 5m,
IsActive = true,
@@ -6228,7 +6228,7 @@ namespace PowderCoating.Infrastructure.Migrations
{
Id = 3,
CompanyId = 0,
CreatedAt = new DateTime(2026, 5, 10, 3, 45, 31, 524, DateTimeKind.Utc).AddTicks(9359),
CreatedAt = new DateTime(2026, 5, 10, 3, 58, 27, 360, DateTimeKind.Utc).AddTicks(7003),
Description = "10% discount for premium customers",
DiscountPercent = 10m,
IsActive = true,
@@ -7846,6 +7846,179 @@ namespace PowderCoating.Infrastructure.Migrations
b.ToTable("Vendors");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCredit", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("APAccountId")
.HasColumnType("int");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreditDate")
.HasColumnType("datetime2");
b.Property<string>("CreditNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("DeletedBy")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<string>("Memo")
.HasColumnType("nvarchar(max)");
b.Property<decimal>("RemainingAmount")
.HasColumnType("decimal(18,2)");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<decimal>("Total")
.HasColumnType("decimal(18,2)");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("datetime2");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<int>("VendorId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("APAccountId");
b.HasIndex("VendorId");
b.ToTable("VendorCredits");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCreditApplication", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<decimal>("Amount")
.HasColumnType("decimal(18,2)");
b.Property<DateTime>("AppliedDate")
.HasColumnType("datetime2");
b.Property<int>("BillId")
.HasColumnType("int");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("DeletedBy")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("datetime2");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<int>("VendorCreditId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BillId");
b.HasIndex("VendorCreditId");
b.ToTable("VendorCreditApplications");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCreditLineItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int?>("AccountId")
.HasColumnType("int");
b.Property<decimal>("Amount")
.HasColumnType("decimal(18,2)");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("CreatedBy")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("datetime2");
b.Property<string>("DeletedBy")
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("datetime2");
b.Property<string>("UpdatedBy")
.HasColumnType("nvarchar(max)");
b.Property<int>("VendorCreditId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("VendorCreditId");
b.ToTable("VendorCreditLineItems");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
@@ -9451,6 +9624,62 @@ namespace PowderCoating.Infrastructure.Migrations
b.Navigation("DefaultExpenseAccount");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCredit", b =>
{
b.HasOne("PowderCoating.Core.Entities.Account", "APAccount")
.WithMany()
.HasForeignKey("APAccountId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("PowderCoating.Core.Entities.Vendor", "Vendor")
.WithMany()
.HasForeignKey("VendorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("APAccount");
b.Navigation("Vendor");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCreditApplication", b =>
{
b.HasOne("PowderCoating.Core.Entities.Bill", "Bill")
.WithMany()
.HasForeignKey("BillId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PowderCoating.Core.Entities.VendorCredit", "VendorCredit")
.WithMany("Applications")
.HasForeignKey("VendorCreditId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Bill");
b.Navigation("VendorCredit");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCreditLineItem", b =>
{
b.HasOne("PowderCoating.Core.Entities.Account", "Account")
.WithMany()
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("PowderCoating.Core.Entities.VendorCredit", "VendorCredit")
.WithMany("LineItems")
.HasForeignKey("VendorCreditId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
b.Navigation("VendorCredit");
});
modelBuilder.Entity("PowderCoating.Core.Entities.Account", b =>
{
b.Navigation("BillLineItems");
@@ -9706,6 +9935,13 @@ namespace PowderCoating.Infrastructure.Migrations
b.Navigation("InventoryItems");
});
modelBuilder.Entity("PowderCoating.Core.Entities.VendorCredit", b =>
{
b.Navigation("Applications");
b.Navigation("LineItems");
});
#pragma warning restore 612, 618
}
}
@@ -146,6 +146,11 @@ public class UnitOfWork : IUnitOfWork
private IRepository<JournalEntry>? _journalEntries;
private IRepository<JournalEntryLine>? _journalEntryLines;
// Vendor Credits
private IRepository<VendorCredit>? _vendorCredits;
private IRepository<VendorCreditLineItem>? _vendorCreditLineItems;
private IRepository<VendorCreditApplication>? _vendorCreditApplications;
/// <summary>
/// Initialises the unit of work with the scoped <paramref name="context"/>.
/// The context is shared across all repositories created by this instance so that
@@ -526,6 +531,19 @@ public class UnitOfWork : IUnitOfWork
public IRepository<JournalEntryLine> JournalEntryLines =>
_journalEntryLines ??= new Repository<JournalEntryLine>(_context);
// Vendor Credits
/// <summary>Repository for <see cref="VendorCredit"/> credit notes received from vendors; tenant-filtered with soft delete.</summary>
public IRepository<VendorCredit> VendorCredits =>
_vendorCredits ??= new Repository<VendorCredit>(_context);
/// <summary>Repository for <see cref="VendorCreditLineItem"/> expense-reversal lines on a vendor credit.</summary>
public IRepository<VendorCreditLineItem> VendorCreditLineItems =>
_vendorCreditLineItems ??= new Repository<VendorCreditLineItem>(_context);
/// <summary>Repository for <see cref="VendorCreditApplication"/> records linking a vendor credit to a specific bill.</summary>
public IRepository<VendorCreditApplication> VendorCreditApplications =>
_vendorCreditApplications ??= new Repository<VendorCreditApplication>(_context);
/// <summary>
/// Flushes all pending changes in the EF Core change tracker to the database.
/// Returns the number of state entries written.
@@ -0,0 +1,359 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using PowderCoating.Application.Interfaces;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Enums;
using PowderCoating.Core.Interfaces;
using PowderCoating.Shared.Constants;
namespace PowderCoating.Web.Controllers;
[Authorize(Policy = AppConstants.Policies.CanViewData)]
public class VendorCreditsController : Controller
{
private readonly IUnitOfWork _unitOfWork;
private readonly ITenantContext _tenantContext;
private readonly IAccountBalanceService _accountBalanceService;
public VendorCreditsController(
IUnitOfWork unitOfWork,
ITenantContext tenantContext,
IAccountBalanceService accountBalanceService)
{
_unitOfWork = unitOfWork;
_tenantContext = tenantContext;
_accountBalanceService = accountBalanceService;
}
private bool AllowAccounting() =>
User.IsInRole("SuperAdmin") || User.IsInRole("Administrator") || User.IsInRole("Manager");
// ── Index ────────────────────────────────────────────────────────────────
/// <summary>Lists vendor credits grouped by status with unapplied balance summary.</summary>
public async Task<IActionResult> Index(string? status)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
var all = (await _unitOfWork.VendorCredits.FindAsync(
vc => vc.CompanyId == companyId,
false,
vc => vc.Vendor))
.OrderByDescending(vc => vc.CreditDate)
.ThenByDescending(vc => vc.Id)
.ToList();
var displayed = status switch
{
"Open" => all.Where(vc => vc.Status == VendorCreditStatus.Open).ToList(),
"Partial" => all.Where(vc => vc.Status == VendorCreditStatus.PartiallyApplied).ToList(),
"Applied" => all.Where(vc => vc.Status == VendorCreditStatus.Applied).ToList(),
"Voided" => all.Where(vc => vc.Status == VendorCreditStatus.Voided).ToList(),
_ => all
};
ViewBag.StatusFilter = status ?? "All";
ViewBag.TotalCount = all.Count;
ViewBag.OpenCount = all.Count(vc => vc.Status == VendorCreditStatus.Open);
ViewBag.PartialCount = all.Count(vc => vc.Status == VendorCreditStatus.PartiallyApplied);
ViewBag.TotalUnapplied = all
.Where(vc => vc.Status is VendorCreditStatus.Open or VendorCreditStatus.PartiallyApplied)
.Sum(vc => vc.RemainingAmount);
return View(displayed);
}
// ── Create ───────────────────────────────────────────────────────────────
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
public async Task<IActionResult> Create()
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
await PopulateDropdownsAsync();
return View(new VendorCredit { CreditDate = DateTime.Today });
}
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
VendorCredit model,
int[] lineAccountIds,
string[] lineDescriptions,
decimal[] lineAmounts)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var lines = BuildLines(lineAccountIds, lineDescriptions, lineAmounts);
if (lines.Count == 0)
{
TempData["Error"] = "At least one line item is required.";
await PopulateDropdownsAsync();
return View(model);
}
var companyId = _tenantContext.GetCurrentCompanyId() ?? 0;
model.CreditNumber = await GenerateCreditNumberAsync(companyId);
model.Status = VendorCreditStatus.Open;
model.Total = lines.Sum(l => l.Amount);
model.RemainingAmount = model.Total;
model.LineItems = lines;
await _unitOfWork.VendorCredits.AddAsync(model);
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Vendor credit {model.CreditNumber} created.";
return RedirectToAction(nameof(Details), new { id = model.Id });
}
// ── Details ──────────────────────────────────────────────────────────────
public async Task<IActionResult> Details(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var vc = (await _unitOfWork.VendorCredits.FindAsync(
v => v.Id == id,
false,
v => v.Vendor,
v => v.APAccount,
v => v.LineItems,
v => v.Applications))
.FirstOrDefault();
if (vc == null) return NotFound();
// Load account names for lines
var accountIds = vc.LineItems
.Where(l => l.AccountId.HasValue)
.Select(l => l.AccountId!.Value)
.Distinct()
.ToList();
var accounts = await _unitOfWork.Accounts.FindAsync(a => accountIds.Contains(a.Id));
ViewBag.AccountMap = accounts.ToDictionary(a => a.Id, a => $"{a.AccountNumber} {a.Name}");
// Load bills referenced by applications
if (vc.Applications.Any())
{
var billIds = vc.Applications.Select(a => a.BillId).ToList();
var bills = await _unitOfWork.Bills.FindAsync(b => billIds.Contains(b.Id));
ViewBag.BillMap = bills.ToDictionary(b => b.Id, b => b.BillNumber);
}
else
{
ViewBag.BillMap = new Dictionary<int, string>();
}
// Unapplied bills from the same vendor for the "Apply" panel
if (vc.Status is VendorCreditStatus.Open or VendorCreditStatus.PartiallyApplied)
{
var openBills = await _unitOfWork.Bills.FindAsync(
b => b.VendorId == vc.VendorId
&& (b.Status == BillStatus.Open || b.Status == BillStatus.PartiallyPaid));
ViewBag.OpenBills = openBills.OrderBy(b => b.DueDate).ToList();
}
return View(vc);
}
// ── Post ─────────────────────────────────────────────────────────────────
/// <summary>
/// Posts a vendor credit to the GL:
/// DR Accounts Payable (APAccountId) — vendor owes us, reduces AP
/// CR Expense/COGS accounts (each line) — reverses the original expense
/// </summary>
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Post(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var vc = (await _unitOfWork.VendorCredits.FindAsync(
v => v.Id == id,
false,
v => v.LineItems))
.FirstOrDefault();
if (vc == null) return NotFound();
if (vc.Status != VendorCreditStatus.Open)
{
TempData["Error"] = "Only open (unposted) credits can be posted.";
return RedirectToAction(nameof(Details), new { id });
}
await _unitOfWork.ExecuteInTransactionAsync(async () =>
{
// DR AP (reduces what we owe the vendor)
await _accountBalanceService.DebitAsync(vc.APAccountId, vc.Total);
// CR each expense account (reverses original expense)
foreach (var line in vc.LineItems)
await _accountBalanceService.CreditAsync(line.AccountId, line.Amount);
// Status stays Open — the credit is now in the GL but not yet applied to a bill
await _unitOfWork.CompleteAsync();
});
TempData["Success"] = $"Vendor credit {vc.CreditNumber} posted to GL.";
return RedirectToAction(nameof(Details), new { id });
}
// ── Apply ─────────────────────────────────────────────────────────────────
/// <summary>
/// Applies a vendor credit against a vendor bill. Reduces Bill.AmountPaid (increasing balance)
/// and VendorCredit.RemainingAmount. No additional GL posting — AP was already adjusted when
/// the credit was posted.
/// </summary>
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CanManageJobs)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Apply(int id, int billId, decimal amount)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var vc = await _unitOfWork.VendorCredits.GetByIdAsync(id);
var bill = await _unitOfWork.Bills.GetByIdAsync(billId);
if (vc == null || bill == null) return NotFound();
if (amount <= 0 || amount > vc.RemainingAmount || amount > bill.BalanceDue)
{
TempData["Error"] = "Invalid application amount.";
return RedirectToAction(nameof(Details), new { id });
}
await _unitOfWork.ExecuteInTransactionAsync(async () =>
{
var application = new VendorCreditApplication
{
VendorCreditId = vc.Id,
BillId = bill.Id,
Amount = amount,
AppliedDate = DateTime.UtcNow
};
await _unitOfWork.VendorCreditApplications.AddAsync(application);
// Update bill — treated as a payment against the balance
bill.AmountPaid += amount;
if (bill.AmountPaid >= bill.Total)
bill.Status = BillStatus.Paid;
else if (bill.AmountPaid > 0)
bill.Status = BillStatus.PartiallyPaid;
// Update credit
vc.RemainingAmount -= amount;
vc.Status = vc.RemainingAmount <= 0
? VendorCreditStatus.Applied
: VendorCreditStatus.PartiallyApplied;
await _unitOfWork.CompleteAsync();
});
TempData["Success"] = $"Applied {amount:C} of credit {vc.CreditNumber} to bill {bill.BillNumber}.";
return RedirectToAction(nameof(Details), new { id });
}
// ── Void ─────────────────────────────────────────────────────────────────
[HttpPost]
[Authorize(Policy = AppConstants.Policies.CompanyAdminOnly)]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Void(int id)
{
if (!AllowAccounting()) return RedirectToAction("Landing", "Reports");
var vc = await _unitOfWork.VendorCredits.GetByIdAsync(id);
if (vc == null) return NotFound();
if (vc.Status == VendorCreditStatus.Applied)
{
TempData["Error"] = "Fully applied credits cannot be voided.";
return RedirectToAction(nameof(Details), new { id });
}
vc.Status = VendorCreditStatus.Voided;
vc.RemainingAmount = 0;
await _unitOfWork.CompleteAsync();
TempData["Success"] = $"Vendor credit {vc.CreditNumber} voided.";
return RedirectToAction(nameof(Index));
}
// ── Helpers ──────────────────────────────────────────────────────────────
private static List<VendorCreditLineItem> BuildLines(
int[] accountIds, string[] descriptions, decimal[] amounts)
{
var lines = new List<VendorCreditLineItem>();
for (int i = 0; i < accountIds.Length; i++)
{
if (i < amounts.Length && amounts[i] > 0)
lines.Add(new VendorCreditLineItem
{
AccountId = accountIds[i] > 0 ? accountIds[i] : null,
Description = i < descriptions.Length ? descriptions[i] : string.Empty,
Amount = amounts[i]
});
}
return lines;
}
/// <summary>
/// Generates the next sequential credit number in the format VC-YYMM-####.
/// Uses ignoreQueryFilters so voided/deleted records are included and numbers are never reused.
/// </summary>
private async Task<string> GenerateCreditNumberAsync(int companyId)
{
var prefix = $"VC-{DateTime.Now:yyMM}-";
var all = await _unitOfWork.VendorCredits.FindAsync(
vc => vc.CompanyId == companyId && vc.CreditNumber.StartsWith(prefix),
ignoreQueryFilters: true);
int next = 1;
if (all.Any())
{
var nums = all
.Select(vc => vc.CreditNumber[prefix.Length..])
.Select(s => int.TryParse(s, out int n) ? n : 0);
next = nums.Max() + 1;
}
return $"{prefix}{next:D4}";
}
private async Task PopulateDropdownsAsync()
{
var vendors = await _unitOfWork.Vendors.FindAsync(v => v.IsActive);
var accounts = await _unitOfWork.Accounts.FindAsync(a => a.IsActive);
ViewBag.VendorList = vendors
.OrderBy(v => v.CompanyName)
.Select(v => new SelectListItem { Value = v.Id.ToString(), Text = v.CompanyName })
.ToList();
ViewBag.APAccountList = accounts
.Where(a => a.AccountSubType == AccountSubType.AccountsPayable)
.OrderBy(a => a.AccountNumber)
.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = $"{a.AccountNumber} {a.Name}"
})
.ToList();
ViewBag.ExpenseAccountList = accounts
.Where(a => a.AccountType is AccountType.Expense or AccountType.CostOfGoods)
.OrderBy(a => a.AccountNumber)
.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = $"{a.AccountNumber} {a.Name}"
})
.ToList();
}
}
@@ -1134,6 +1134,10 @@
<i class="bi bi-journal-text"></i>
<span>Journal Entries</span>
</a>
<a asp-controller="VendorCredits" asp-action="Index" class="nav-link">
<i class="bi bi-arrow-return-left"></i>
<span>Vendor Credits</span>
</a>
if (hasReports)
{
<a asp-controller="AccountingExport" asp-action="Index" class="nav-link">
@@ -0,0 +1,132 @@
@model PowderCoating.Core.Entities.VendorCredit
@{
ViewData["Title"] = "New Vendor Credit";
var apAccounts = ViewBag.APAccountList as List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> ?? new();
var expAccounts = ViewBag.ExpenseAccountList as List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> ?? new();
var vendors = ViewBag.VendorList as List<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem> ?? new();
}
<div class="d-flex align-items-center mb-3 gap-2">
<a asp-action="Index" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
<h4 class="mb-0 fw-semibold ms-2">New Vendor Credit</h4>
</div>
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<form asp-action="Create" method="post">
@Html.AntiForgeryToken()
<div class="card shadow-sm mb-3">
<div class="card-header fw-semibold">Credit Details</div>
<div class="card-body">
<div class="row g-3">
<div class="col-md-4">
<label class="form-label fw-semibold">Vendor <span class="text-danger">*</span></label>
<select asp-for="VendorId" asp-items="vendors" class="form-select" required>
<option value="">— select vendor —</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label fw-semibold">Credit Date <span class="text-danger">*</span></label>
<input asp-for="CreditDate" type="date" class="form-control"
value="@Model.CreditDate.ToString("yyyy-MM-dd")" required />
</div>
<div class="col-md-5">
<label class="form-label fw-semibold">AP Account <span class="text-danger">*</span></label>
<select asp-for="APAccountId" asp-items="apAccounts" class="form-select" required>
<option value="">— select account —</option>
</select>
</div>
<div class="col-12">
<label class="form-label fw-semibold">Memo</label>
<input asp-for="Memo" class="form-control" placeholder="Reason for the credit" />
</div>
</div>
</div>
</div>
<div class="card shadow-sm mb-3">
<div class="card-header fw-semibold">Line Items</div>
<div class="card-body p-0">
<table class="table table-sm mb-0" id="linesTable">
<thead class="table-light">
<tr>
<th style="width:40%">Expense / COGS Account</th>
<th>Description</th>
<th class="text-end" style="width:130px">Amount</th>
<th style="width:40px"></th>
</tr>
</thead>
<tbody id="linesBody"></tbody>
</table>
</div>
<div class="card-footer d-flex justify-content-between align-items-center">
<button type="button" class="btn btn-sm btn-outline-secondary" id="addLineBtn">
<i class="bi bi-plus-lg me-1"></i>Add Line
</button>
<span class="fw-semibold">
Total: <span id="lineTotal">$0.00</span>
</span>
</div>
</div>
<div class="d-flex gap-2">
<button type="submit" class="btn btn-primary">Create Vendor Credit</button>
<a asp-action="Index" class="btn btn-outline-secondary">Cancel</a>
</div>
</form>
@section Scripts {
<script>
(function() {
const expenseAccounts = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(
expAccounts.Select(a => new { value = a.Value, text = a.Text })));
let idx = 0;
function addLine() {
const tbody = document.getElementById('linesBody');
const i = idx++;
const tr = document.createElement('tr');
tr.innerHTML = `
<td>
<select name="lineAccountIds" class="form-select form-select-sm">
<option value="">— optional —</option>
${expenseAccounts.map(a => `<option value="${a.value}">${escHtml(a.text)}</option>`).join('')}
</select>
</td>
<td><input name="lineDescriptions" type="text" class="form-control form-control-sm" placeholder="what was credited" /></td>
<td>
<input name="lineAmounts" type="number" step="0.01" min="0.01" class="form-control form-control-sm text-end line-amount" placeholder="0.00" required />
</td>
<td>
<button type="button" class="btn btn-sm btn-link text-danger p-0" onclick="this.closest('tr').remove(); updateTotal();">
<i class="bi bi-x-lg"></i>
</button>
</td>`;
tr.querySelector('.line-amount').addEventListener('input', updateTotal);
tbody.appendChild(tr);
}
function updateTotal() {
let total = 0;
document.querySelectorAll('.line-amount').forEach(el => total += parseFloat(el.value) || 0);
document.getElementById('lineTotal').textContent = total.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
function escHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
document.getElementById('addLineBtn').addEventListener('click', addLine);
addLine();
})();
</script>
}
@@ -0,0 +1,238 @@
@model PowderCoating.Core.Entities.VendorCredit
@using PowderCoating.Core.Enums
@{
ViewData["Title"] = $"Vendor Credit {Model.CreditNumber}";
var accountMap = ViewBag.AccountMap as Dictionary<int, string> ?? new();
var billMap = ViewBag.BillMap as Dictionary<int, string> ?? new();
var openBills = ViewBag.OpenBills as List<PowderCoating.Core.Entities.Bill> ?? new();
bool canApply = Model.Status is VendorCreditStatus.Open or VendorCreditStatus.PartiallyApplied;
}
<div class="d-flex align-items-center mb-3 gap-2 flex-wrap">
<a asp-action="Index" class="btn btn-sm btn-outline-secondary">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
<h4 class="mb-0 fw-semibold ms-2">@Model.CreditNumber</h4>
@{
var (badgeClass, label) = Model.Status switch
{
VendorCreditStatus.Open => ("bg-success", "Open"),
VendorCreditStatus.PartiallyApplied => ("bg-warning text-dark", "Partially Applied"),
VendorCreditStatus.Applied => ("bg-secondary", "Applied"),
VendorCreditStatus.Voided => ("bg-danger", "Voided"),
_ => ("bg-secondary", Model.Status.ToString())
};
}
<span class="badge @badgeClass ms-1 fs-6">@label</span>
<div class="ms-auto d-flex gap-2">
@if (Model.Status == VendorCreditStatus.Open)
{
<form asp-action="Post" asp-route-id="@Model.Id" method="post" class="d-inline">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-success"
onclick="return confirm('Post this credit to the GL? Accounts Payable will be debited and expense accounts credited.')">
<i class="bi bi-check-circle me-1"></i>Post to GL
</button>
</form>
}
@if (Model.Status != VendorCreditStatus.Voided && Model.Status != VendorCreditStatus.Applied)
{
<form asp-action="Void" asp-route-id="@Model.Id" method="post" class="d-inline">
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-sm btn-outline-danger"
onclick="return confirm('Void this vendor credit?')">
<i class="bi bi-x-circle me-1"></i>Void
</button>
</form>
}
</div>
</div>
@if (TempData["Success"] != null)
{
<div class="alert alert-success alert-permanent alert-dismissible fade show">
@TempData["Success"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<div class="row g-3 mb-3">
<div class="col-md-8">
<div class="card shadow-sm h-100">
<div class="card-body">
<dl class="row mb-0">
<dt class="col-4 text-muted">Credit Number</dt>
<dd class="col-8 fw-semibold">@Model.CreditNumber</dd>
<dt class="col-4 text-muted">Vendor</dt>
<dd class="col-8">@Model.Vendor?.CompanyName</dd>
<dt class="col-4 text-muted">Date</dt>
<dd class="col-8">@Model.CreditDate.ToString("MMMM d, yyyy")</dd>
<dt class="col-4 text-muted">AP Account</dt>
<dd class="col-8">@Model.APAccount?.AccountNumber @Model.APAccount?.Name</dd>
@if (!string.IsNullOrWhiteSpace(Model.Memo))
{
<dt class="col-4 text-muted">Memo</dt>
<dd class="col-8">@Model.Memo</dd>
}
</dl>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow-sm h-100">
<div class="card-body text-center py-4">
<div class="fs-5 fw-bold">@Model.Total.ToString("C")</div>
<div class="text-muted small mb-3">Total Credit</div>
@if (Model.RemainingAmount > 0)
{
<div class="fs-4 fw-bold text-success">@Model.RemainingAmount.ToString("C")</div>
<div class="text-muted small">Remaining</div>
}
else
{
<div class="text-muted">Fully Applied</div>
}
</div>
</div>
</div>
</div>
<div class="card shadow-sm mb-3">
<div class="card-header fw-semibold">Line Items</div>
<div class="card-body p-0">
<table class="table table-sm mb-0">
<thead class="table-light">
<tr>
<th>Account</th>
<th>Description</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
@foreach (var line in Model.LineItems)
{
<tr>
<td class="small">
@if (line.AccountId.HasValue && accountMap.TryGetValue(line.AccountId.Value, out var acct))
{ @acct }
else
{ <span class="text-muted">—</span> }
</td>
<td class="text-muted small">@line.Description</td>
<td class="text-end">@line.Amount.ToString("C")</td>
</tr>
}
</tbody>
<tfoot class="table-light fw-semibold">
<tr>
<td colspan="2" class="text-end">Total</td>
<td class="text-end">@Model.Total.ToString("C")</td>
</tr>
</tfoot>
</table>
</div>
</div>
@if (Model.Applications.Any())
{
<div class="card shadow-sm mb-3">
<div class="card-header fw-semibold">Applied To</div>
<div class="card-body p-0">
<table class="table table-sm mb-0">
<thead class="table-light">
<tr>
<th>Bill</th>
<th>Applied Date</th>
<th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
@foreach (var app in Model.Applications.OrderByDescending(a => a.AppliedDate))
{
<tr>
<td>
@if (billMap.TryGetValue(app.BillId, out var billNum))
{
<a asp-controller="Bills" asp-action="Details" asp-route-id="@app.BillId">@billNum</a>
}
else
{
<span class="text-muted">#@app.BillId</span>
}
</td>
<td>@app.AppliedDate.ToLocalTime().ToString("MMM d, yyyy")</td>
<td class="text-end">@app.Amount.ToString("C")</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
@if (canApply && openBills.Any())
{
<div class="card shadow-sm">
<div class="card-header fw-semibold">Apply to a Bill</div>
<div class="card-body p-0">
<table class="table table-sm mb-0">
<thead class="table-light">
<tr>
<th>Bill</th>
<th>Due Date</th>
<th class="text-end">Balance Due</th>
<th class="text-end">Apply Amount</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var bill in openBills)
{
var maxApply = Math.Min(Model.RemainingAmount, bill.BalanceDue);
<tr>
<td>
<a asp-controller="Bills" asp-action="Details" asp-route-id="@bill.Id">@bill.BillNumber</a>
</td>
<td class="text-muted small">@(bill.DueDate?.ToString("MMM d, yyyy") ?? "—")</td>
<td class="text-end">@bill.BalanceDue.ToString("C")</td>
<td class="text-end" style="width:150px">
<form asp-action="Apply" method="post" class="d-inline">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Id" />
<input type="hidden" name="billId" value="@bill.Id" />
<div class="input-group input-group-sm">
<span class="input-group-text">$</span>
<input name="amount" type="number" step="0.01" min="0.01"
max="@maxApply"
value="@maxApply.ToString("F2")"
class="form-control text-end" />
<button type="submit" class="btn btn-sm btn-success">Apply</button>
</div>
</form>
</td>
<td></td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
else if (canApply)
{
<div class="alert alert-info alert-permanent">
No open bills found for this vendor to apply the credit against.
</div>
}
@@ -0,0 +1,138 @@
@model IEnumerable<PowderCoating.Core.Entities.VendorCredit>
@using PowderCoating.Core.Enums
@{
ViewData["Title"] = "Vendor Credits";
var statusFilter = ViewBag.StatusFilter as string ?? "All";
}
<div class="d-flex align-items-center mb-3 gap-2">
<h4 class="mb-0 fw-semibold">Vendor Credits</h4>
<a asp-action="Create" class="btn btn-sm btn-primary ms-auto">
<i class="bi bi-plus-lg me-1"></i>New Credit
</a>
</div>
@if (TempData["Success"] != null)
{
<div class="alert alert-success alert-permanent alert-dismissible fade show">
@TempData["Success"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
@if (TempData["Error"] != null)
{
<div class="alert alert-danger alert-permanent alert-dismissible fade show">
@TempData["Error"]
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
}
<div class="row g-3 mb-3">
<div class="col-md-4">
<div class="card shadow-sm text-center py-3">
<div class="fs-4 fw-bold text-success">@((ViewBag.TotalUnapplied as decimal? ?? 0).ToString("C"))</div>
<div class="small text-muted">Total Unapplied Credit</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow-sm text-center py-3">
<div class="fs-4 fw-bold">@ViewBag.OpenCount</div>
<div class="small text-muted">Open Credits</div>
</div>
</div>
<div class="col-md-4">
<div class="card shadow-sm text-center py-3">
<div class="fs-4 fw-bold">@ViewBag.PartialCount</div>
<div class="small text-muted">Partially Applied</div>
</div>
</div>
</div>
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<a class="nav-link @(statusFilter == "All" ? "active" : "")" asp-action="Index">
All <span class="badge bg-secondary ms-1">@ViewBag.TotalCount</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link @(statusFilter == "Open" ? "active" : "")" asp-action="Index" asp-route-status="Open">
Open <span class="badge bg-success ms-1">@ViewBag.OpenCount</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link @(statusFilter == "Partial" ? "active" : "")" asp-action="Index" asp-route-status="Partial">
Partially Applied <span class="badge bg-warning text-dark ms-1">@ViewBag.PartialCount</span>
</a>
</li>
</ul>
<div class="card shadow-sm">
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead class="table-light">
<tr>
<th>Credit #</th>
<th>Date</th>
<th>Vendor</th>
<th>Memo</th>
<th class="text-end">Total</th>
<th class="text-end">Remaining</th>
<th>Status</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
@if (!Model.Any())
{
<tr>
<td colspan="8" class="text-center text-muted py-4">No vendor credits found.</td>
</tr>
}
@foreach (var vc in Model)
{
<tr>
<td>
<a asp-action="Details" asp-route-id="@vc.Id" class="fw-semibold text-decoration-none">
@vc.CreditNumber
</a>
</td>
<td>@vc.CreditDate.ToString("MMM d, yyyy")</td>
<td>@vc.Vendor?.CompanyName</td>
<td class="text-muted small text-truncate" style="max-width:180px">@vc.Memo</td>
<td class="text-end">@vc.Total.ToString("C")</td>
<td class="text-end">
@if (vc.RemainingAmount > 0)
{
<span class="text-success fw-semibold">@vc.RemainingAmount.ToString("C")</span>
}
else
{
<span class="text-muted">—</span>
}
</td>
<td>
@{
var (badgeClass, label) = vc.Status switch
{
VendorCreditStatus.Open => ("bg-success", "Open"),
VendorCreditStatus.PartiallyApplied => ("bg-warning text-dark", "Partial"),
VendorCreditStatus.Applied => ("bg-secondary", "Applied"),
VendorCreditStatus.Voided => ("bg-danger", "Voided"),
_ => ("bg-secondary", vc.Status.ToString())
};
}
<span class="badge @badgeClass">@label</span>
</td>
<td class="text-end">
<a asp-action="Details" asp-route-id="@vc.Id" class="btn btn-sm btn-outline-secondary">
View
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>