Мой мозг слоался на написании контроллера покупки. В голове возник вопрос: "я что даун?"

This commit is contained in:
frog24 2024-05-28 01:50:20 +04:00
parent 9c7a3dda3c
commit 758ea3b38f
11 changed files with 319 additions and 59 deletions

View File

@ -0,0 +1,44 @@
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
using VetclinicContracts.ViewModels;
namespace ClientApp
{
public static class APIClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -6,6 +6,10 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VetclinicBusinessLogic\VetclinicBusinessLogic.csproj" />
<ProjectReference Include="..\VetclinicContracts\VetclinicContracts.csproj" />

View File

@ -1,10 +1,12 @@
using ClientApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

View File

@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"IPAddress": "http://localhost:5244"
}

View File

@ -21,14 +21,12 @@ namespace VetclinicDatabaseImplement.Implements
}
public List<AnimalViewModel> GetFilteredList(AnimalSearchModel model)
{
if (string.IsNullOrEmpty(model.AnimalName))
{
return new();
}
using var context = new VetclinicDatabase();
return context.Animals.Where(x => x.AnimalName.Contains(model.AnimalName)).
Select(x => x.GetViewModel).ToList();
}
using var context = new VetclinicDatabase();
return context.Animals.Where(x => x.ClientId == model.ClientId)
.Where(x => String.IsNullOrEmpty(model.AnimalName) || x.AnimalName.Contains(model.AnimalName))
.Select(x => x.GetViewModel)
.ToList();
}
public AnimalViewModel? GetElement(AnimalSearchModel model)
{
if (string.IsNullOrEmpty(model.AnimalName) && !model.Id.HasValue)

View File

@ -0,0 +1,93 @@
using Microsoft.AspNetCore.Mvc;
using VetclinicContracts.BindingModels;
using VetclinicContracts.BusinessLogicsContracts;
using VetclinicContracts.SearchModels;
using VetclinicContracts.ViewModels;
namespace VetclinicRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AnimalController : Controller
{
private readonly ILogger _logger;
private readonly IAnimalLogic _animal;
public AnimalController(ILogger<AnimalController> logger, IAnimalLogic animal)
{
_logger = logger;
_animal = animal;
}
[HttpGet]
public List<AnimalViewModel> GetAnimals(int clentId)
{
try
{
return _animal.ReadList(new AnimalSearchModel { ClientId = clentId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка животных");
throw;
}
}
[HttpGet]
public Tuple<AnimalViewModel>? GetAnimal(int animalId)
{
try
{
var elem = _animal.ReadElement(new AnimalSearchModel { Id = animalId });
if (elem == null)
{
return null;
}
return Tuple.Create(elem);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения животного по id={Id}", animalId);
throw;
}
}
[HttpPost]
public bool CreateAnimal(AnimalBindingModel model)
{
try
{
return _animal.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Не удалось создать животного");
throw;
}
}
[HttpPost]
public bool UpdateAnimal(AnimalBindingModel model)
{
try
{
return _animal.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Не удалось обновить животное");
throw;
}
}
[HttpPost]
public bool DeleteAnimal(AnimalBindingModel model)
{
try
{
return _animal.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления животного");
throw;
}
}
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.AspNetCore.Mvc;
using VetclinicContracts.BindingModels;
using VetclinicContracts.BusinessLogicsContracts;
using VetclinicContracts.SearchModels;
using VetclinicContracts.ViewModels;
namespace VetclinicRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ClientController : Controller
{
private readonly ILogger _logger;
private readonly IClientLogic _logic;
public ClientController(ILogger<ClientController> logger, IClientLogic logic)
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public ClientViewModel? Login(string email, string password)
{
try
{
return _logic.ReadElement(new ClientSearchModel
{
Email = email,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка входа в систему");
throw;
}
}
[HttpPost]
public void Register(ClientBindingModel model)
{
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка регистрации");
throw;
}
}
[HttpPost]
public void UpdateData(ClientBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных");
throw;
}
}
}
}

View File

@ -0,0 +1,66 @@
using Microsoft.AspNetCore.Mvc;
using VetclinicContracts.BindingModels;
using VetclinicContracts.BusinessLogicsContracts;
using VetclinicContracts.SearchModels;
using VetclinicContracts.ViewModels;
using VetclinicDatabaseImplement.Models;
namespace VetclinicRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class DrugPurchaseController : Controller
{
private readonly ILogger _logger;
private readonly IDrugPurchaseLogic _drugPurchase;
public DrugPurchaseController(ILogger<DrugPurchaseController> logger, IDrugPurchaseLogic drugPurchase)
{
_logger = logger;
_drugPurchase = drugPurchase;
}
[HttpGet]
public Tuple<DrugPurchaseViewModel>? GetDrugPurchase(int drugPurchaseId)
{
try
{
var elem = _drugPurchase.ReadElement(new DrugPurchaseSearchModel { Id = drugPurchaseId });
if (elem == null)
{
return null;
}
return Tuple.Create(elem);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения животного по id={Id}", drugPurchaseId);
throw;
}
}
[HttpGet]
public List<DrugPurchaseViewModel>? GetPurchases(int? clientId)
{
try
{
return _drugPurchase.ReadList(new DrugPurchaseSearchModel { ClientId = clientId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка покупок");
throw;
}
}
[HttpPost]
public bool CreatePurchase(DrugPurchaseBindingModel model)
{
try
{
return _drugPurchase.CreateDrugPurchase(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Не удалось создать покупку");
throw;
}
}
}
}

View File

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace VetclinicRestApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@ -1,12 +1,46 @@
using Microsoft.OpenApi.Models;
using VetclinicBusinessLogic.BusinessLogics;
using VetclinicContracts.BusinessLogicsContracts;
using VetclinicContracts.StoragesContracts;
using VetclinicDatabaseImplement.Implements;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IDoctorStorage, DoctorStorage>();
builder.Services.AddTransient<IAnimalStorage, AnimalStorage>();
builder.Services.AddTransient<IDrugStorage, DrugStorage>();
builder.Services.AddTransient<IDoctorVisitStorage, DoctorVisitStorage>();
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IServiceStorage, ServiceStorage>();
builder.Services.AddTransient<IMedicineStorage, MedicineStorage>();
builder.Services.AddTransient<IDrugPurchaseStorage, DrugPurchaseStorage>();
builder.Services.AddTransient<IDoctorLogic, DoctorLogic>();
builder.Services.AddTransient<IAnimalLogic, AnimalLogic>();
builder.Services.AddTransient<IDrugLogic, DrugLogic>();
builder.Services.AddTransient<IDoctorVisitLogic, DoctorVisitLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IServiceLogic, ServiceLogic>();
builder.Services.AddTransient<IMedicineLogic, MedicineLogic>();
builder.Services.AddTransient<IDrugPurchaseLogic, DrugPurchaseLogic>();
//builder.Services.AddTransient<IReportLogicDoctor, ReportLogicDoctor>();
//builder.Services.AddTransient<IReportLogicOwner, ReportLogicOwner>();
//builder.Services.AddTransient<AbstractSaveToExcelDoctor, SaveToExcelDoctor>();
//builder.Services.AddTransient<AbstractSaveToWordDoctor, SaveToWordDoctor>();
//builder.Services.AddTransient<AbstractSaveToPdfDoctor, SaveToPdfDoctor>();
//builder.Services.AddTransient<AbstractSaveToExcelOwner, SaveToExcelOwner>();
//builder.Services.AddTransient<AbstractSaveToWordOwner, SaveToWordOwner>();
//builder.Services.AddTransient<AbstractSaveToPdfOwner, SaveToPdfOwner>();
//builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen( c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "VetclinicRestApi", Version = "v1" });
});
var app = builder.Build();

View File

@ -1,13 +0,0 @@
namespace VetclinicRestApi
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}