Files
2026-04-20 14:47:24 -05:00

123 lines
3.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;
using LCU.API.Collections.RepoApi.Exceptions;
using LCU.Shared.Collections.RepoApiLib.Models;
using LCU.Shared.Collections.RepoApiLib.Repositories;
using Serilog;
namespace LCU.API.Collections.RepoApi.Services
{
public class CollateralService : ICollateralService
{
private readonly ICollateralRepository _collateralRepository;
private readonly IUnitOfWork _unitOfWork;
public CollateralService(
ICollateralRepository collateralRepository,
IUnitOfWork unitOfWork)
{
_collateralRepository = collateralRepository;
_unitOfWork = unitOfWork;
}
public async Task<IEnumerable<Collateral>> ListAll()
{
try
{
return await _collateralRepository.ListAllAsync();
}
catch (Exception ex)
{
Log.Error(ex, "Failure retrieving Collaterals");
throw new ServerErrorException();
}
}
public async Task<Collateral> SaveAsync(Collateral collateral)
{
try
{
await _collateralRepository.AddAsync(collateral);
await _unitOfWork.CompleteAsync();
return collateral;
}
catch (Exception ex)
{
Log.Error(ex, $"Failure saving Collateral: {collateral}", collateral);
throw new ServerErrorException();
}
}
public async Task<Collateral> Get(int id)
{
Collateral collateral;
try
{
collateral = await _collateralRepository.FindByIdAsync(id);
}
catch (Exception ex)
{
Log.Error(ex, $"Failure retrieving Collateral with id: {id}");
throw new ServerErrorException();
}
if (collateral == null)
{
throw new NotFoundException($"Collateral with id {id} not found.");
}
return collateral;
}
public async Task<Collateral> UpdateAsync(Collateral collateral)
{
Collateral existing = null;
try
{
existing = await _collateralRepository.FindByIdAsync(collateral.CollateralId);
}catch(Exception ex)
{
Log.Error(ex, $"Failure retrieving existing collateral with collateralId: {collateral.CollateralId}",collateral);
throw new ServerErrorException();
}
if (existing == null)
{
throw new NotFoundException($"Collateral with id {collateral.CollateralId} not found.");
}
existing.Vin = collateral.Vin;
existing.Make = collateral.Make;
existing.Model = collateral.Model;
existing.Year = collateral.Year;
existing.Description = collateral.Description;
existing.VehicleType = collateral.VehicleType;
existing.BodyStyle = collateral.BodyStyle;
existing.Inoperable = collateral.Inoperable;
existing.CollateralTypeId = collateral.CollateralTypeId;
existing.RetitledInLandmarkName = collateral.RetitledInLandmarkName;
try
{
_collateralRepository.Update(existing);
await _unitOfWork.CompleteAsync();
return (existing);
}
catch (SqlException ex)
{
Log.Error(ex, $"SQL Failure updating Collateral: {collateral}", collateral);
throw new ServerErrorException();
}
catch (Exception ex)
{
Log.Error(ex, $"Failure updating Collateral: {collateral}", collateral);
throw new ServerErrorException();
}
}
}
}