shoc-backend/SeaHaven.DataServices/Implementation/EmployeeDataService.cs

109 lines
3.4 KiB
C#
Raw Normal View History

2026-04-28 18:55:14 -05:00
using Data.SeaHavenIndustries;
using Microsoft.EntityFrameworkCore;
using SeaHaven.DataServices.Interfaces;
namespace SeaHaven.DataServices.Implementation
{
public class EmployeeDataService : IEmployeeDataService
{
private readonly ApplicationDbContext _context;
public EmployeeDataService(ApplicationDbContext context)
{
_context = context;
}
public async Task<Employee?> GetByIdAsync(int id)
{
return await _context.Employees.FindAsync(id);
}
public async Task<Employee?> GetByIdWithDetailsAsync(int id)
{
return await _context.Employees
.Include(e => e.Department)
.Include(e => e.JobTitle)
2026-05-06 10:49:33 -05:00
.Include(e => e.Region)
2026-04-28 18:55:14 -05:00
.Include(e => e.Emails)
2026-05-06 10:49:33 -05:00
.Include(e => e.Phones)
2026-04-28 18:55:14 -05:00
.FirstOrDefaultAsync(e => e.Id == id);
}
public async Task<IEnumerable<Employee>> GetAllAsync()
{
return await _context.Employees.ToListAsync();
}
public async Task<(IEnumerable<Employee> Items, int TotalCount)> GetPagedAsync(
2026-05-06 10:49:33 -05:00
int page,
int pageSize,
2026-04-28 18:55:14 -05:00
string? search = null)
{
2026-05-06 10:49:33 -05:00
search ??= "";
var query = _context.Employees
.Include(e => e.JobTitle)
.Include(e => e.Department)
.Include(e => e.Region)
.Include(e => e.Emails)
.Include(e => e.Phones)
.Where(e => !e.IsDeleted.HasValue || e.IsDeleted == false);
2026-04-28 18:55:14 -05:00
if (!string.IsNullOrWhiteSpace(search))
{
2026-05-06 10:49:33 -05:00
var s = search.ToLower();
query = query.Where(e =>
(e.FirstName != null && e.FirstName.ToLower().Contains(s)) ||
(e.LastName != null && e.LastName.ToLower().Contains(s)) ||
e.Emails.Any(x => x.Address != null && x.Address.ToLower().Contains(s)) ||
e.Phones.Any(x => x.Number != null && x.Number.Contains(search))
);
2026-04-28 18:55:14 -05:00
}
var totalCount = await query.CountAsync();
var items = await query
2026-05-06 10:49:33 -05:00
.OrderByDescending(e => e.Id)
2026-04-28 18:55:14 -05:00
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return (items, totalCount);
}
public async Task<Employee> AddAsync(Employee employee)
{
employee.CreatedDate = DateTime.UtcNow;
2026-04-28 18:55:14 -05:00
await _context.Employees.AddAsync(employee);
await _context.SaveChangesAsync();
return employee;
}
public async Task UpdateAsync(Employee employee)
{
employee.LastModificationTime = DateTime.UtcNow;
2026-04-28 18:55:14 -05:00
_context.Employees.Update(employee);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var entity = await GetByIdAsync(id);
if (entity != null)
{
_context.Employees.Remove(entity);
await _context.SaveChangesAsync();
}
}
public async Task<bool> ExistsAsync(int id)
{
return await _context.Employees.AnyAsync(e => e.Id == id);
}
public async Task<int> CountAsync()
{
return await _context.Employees.CountAsync();
}
}
}