Files
Backend-Api/CompanyManagment.EFCore/Repository/LawRepository.cs

104 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using _0_Framework.InfraStructure;
using Company.Domain.LawAgg;
using CompanyManagment.App.Contracts.Law;
using Microsoft.EntityFrameworkCore;
namespace CompanyManagment.EFCore.Repository;
public class LawRepository:RepositoryBase<long,Law>,ILawRepository
{
private readonly CompanyContext _context;
public LawRepository(CompanyContext context) : base(context)
{
_context = context;
}
public async Task<Law> GetWithItems(long id)
{
return await _context.Laws.Include(x => x.Items).FirstOrDefaultAsync(x => x.id == id);
}
public async Task<List<Law>> GetActive()
{
return await _context.Laws.Where(x => x.IsActive).ToListAsync();
}
public async Task<LawViewModel> GetByType(LawType type)
{
return await _context.Laws.Where(x => x.Type == type && x.IsActive)
.Select(x => new LawViewModel
{
Id = x.id,
Title = x.Title,
IsActive = x.IsActive,
CreatedAt = x.CreationDate,
HeadTitle = x.HeadTitle,
Notifications = x.Notifications,
Type = x.Type,
Items = x.Items.OrderBy(i => i.OrderNumber).Select(i => new LawItemViewModel
{
Header = i.Header,
Details = i.Details,
}).ToList()
}).FirstOrDefaultAsync();
}
public async Task<List<LawViewModel>> GetList(LawSearchModel searchModel)
{
var query = _context.Laws.Include(x => x.Items)
.Where(x=>x.IsActive).AsQueryable();
if (!string.IsNullOrWhiteSpace(searchModel.Title))
query = query.Where(x => x.Title.Contains(searchModel.Title));
if (!string.IsNullOrWhiteSpace(searchModel.Text))
query = query.Where(x => x.Items.Any(i => i.Header.Contains(searchModel.Text) || i.Details.Contains(searchModel.Text)));
var list = await query.Select(x => new LawViewModel
{
Id = x.id,
Title = x.Title,
IsActive = x.IsActive,
CreatedAt = x.CreationDate,
Type = x.Type
}).ToListAsync();
// Create a set of existing law types
var existingTypes = list.Select(x => x.Type).ToHashSet();
if (string.IsNullOrWhiteSpace(searchModel.Text) && string.IsNullOrWhiteSpace(searchModel.Title))
{
// Add placeholder laws for any missing enum values
foreach (LawType lawType in Enum.GetValues(typeof(LawType)))
{
if (!existingTypes.Contains(lawType))
{
list.Add(new LawViewModel
{
Id = 0, // Indicates it doesn't exist in the database yet
Title = GetDefaultTitleForLawType(lawType),
IsActive = false,
CreatedAt = DateTime.Now,
Type = lawType,
Items = new List<LawItemViewModel>()
});
}
}
}
return list;
}
private string GetDefaultTitleForLawType(LawType lawType)
{
return lawType switch
{
LawType.Register => "قوانین ثبت نام",
_ => $"قوانین {lawType}"
};
}
}