using Microsoft.EntityFrameworkCore; using StockMaster.Models; using StockMaster.ViewModels; using Microsoft.AspNetCore.Http; namespace StockMaster.Data { public class StockDbContext : DbContext { private readonly IHttpContextAccessor _httpContextAccessor; public StockDbContext(DbContextOptions options, IHttpContextAccessor httpContextAccessor) : base(options) { _httpContextAccessor = httpContextAccessor; } public DbSet Users { get; set; } public DbSet Customers { get; set; } public DbSet Categories { get; set; } public DbSet Suppliers { get; set; } public DbSet Products { get; set; } public DbSet Warehouses { get; set; } public DbSet Sales { get; set; } public DbSet PurchaseOrders { get; set; } public DbSet SaleItems { get; set; } public DbSet PurchaseOrderItems { get; set; } public DbSet WarehouseStocks { get; set; } public DbSet ProductPriceLogs { get; set; } public DbSet VwSalesByDays { get; set; } public DbSet VwEmployeeRankings { get; set; } public DbSet VwTodaysSummaries { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity().HasKey(si => new { si.SaleId, si.ProductId }); modelBuilder.Entity().HasKey(poi => new { poi.PoId, poi.ProductId }); modelBuilder.Entity().HasKey(ws => new { ws.WarehouseId, ws.ProductId }); modelBuilder.Entity().Property(p => p.UnitPrice).HasPrecision(12, 2); modelBuilder.Entity().Property(s => s.TotalAmount).HasPrecision(15, 2); modelBuilder.Entity().Property(si => si.UnitPriceAtSale).HasPrecision(12, 2); modelBuilder.Entity().Property(poi => poi.UnitCost).HasPrecision(12, 2); modelBuilder.Entity().ToTable("product_price_log", "stock_management"); modelBuilder.Entity().HasNoKey().ToView("vw_sales_by_day_of_week", "stock_management"); modelBuilder.Entity().HasNoKey().ToView("vw_employee_sales_ranking", "stock_management"); modelBuilder.Entity().HasNoKey().ToView("vw_todays_sales_summary", "stock_management"); } public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { var username = _httpContextAccessor.HttpContext?.User?.Identity?.Name ?? "system"; await Database.ExecuteSqlRawAsync("SELECT set_config('app.current_user', {0}, false)", new[] { username }, cancellationToken); return await base.SaveChangesAsync(cancellationToken); } } }