OnProfNext/OnProfNext.Client/Services/OrderApiService.cs
2025-10-15 15:01:00 +02:00

131 lines
4.3 KiB
C#

using OnProfNext.Shared.Models.DTOs;
using System.Net.Http.Json;
namespace OnProfNext.Client.Services
{
public class OrderApiService
{
private readonly HttpClient _httpClient;
public OrderApiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
// Alle Aufträge zu einem Projekt abrufen
public async Task<(bool Success, List<OrderDto>? Data, string? Error)> GetOrdersByProjectAsync(int projectId)
{
try
{
var orders = await _httpClient.GetFromJsonAsync<List<OrderDto>>($"api/orders/byproject/{projectId}");
return (true, orders ?? new List<OrderDto>(), null);
}
catch (Exception ex)
{
return (false, null, ex.Message);
}
}
// Einzelnen Auftrag abrufen
public async Task<(bool Success, OrderDto? Data, string? Error)> GetOrderAsync(int id)
{
try
{
var order = await _httpClient.GetFromJsonAsync<OrderDto>($"api/orders/{id}");
if (order == null)
return (false, null, "Auftrag nicht gefunden.");
return (true, order, null);
}
catch (Exception ex)
{
return (false, null, ex.Message);
}
}
//Auftrag erstellen
public async Task<(bool Success, string? Error)> CreateOrderAsync(OrderDto order)
{
try
{
var createDto = new OrderCreateDto
{
ProjectId = order.ProjectId,
Auftragsnummer = order.Auftragsnummer,
Titel = order.Titel,
Status = order.Status,
Planstunden = order.Planstunden,
MandantId = order.MandantId,
UserIds = order.Mitarbeiter.Select(u => u.Id).ToList()
};
var response = await _httpClient.PostAsJsonAsync("api/orders", createDto);
return response.IsSuccessStatusCode
? (true, null)
: (false, $"Fehler beim Anlegen: {response.ReasonPhrase}");
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
//Auftrag aktualisieren
public async Task<(bool Success, string? Error)> UpdateOrderAsync(OrderDto order)
{
try
{
var response = await _httpClient.PutAsJsonAsync($"api/orders/{order.Id}", order);
if (!response.IsSuccessStatusCode)
return (false, $"Fehler beim Aktualisieren: {response.ReasonPhrase}");
return (true, null);
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
//Auftrag löschen
public async Task<(bool Success, string? Error)> DeleteOrderAsync(int id)
{
try
{
var response = await _httpClient.DeleteAsync($"api/orders/{id}");
if (!response.IsSuccessStatusCode)
return (false, $"Fehler beim Löschen: {response.ReasonPhrase}");
return (true, null);
}
catch (HttpRequestException)
{
return (false, "Server nicht erreichbar.");
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
//Set Order Users Async
public async Task<(bool Success, string? Error)> SetOrderUsersAsync(int orderId, List<int> userIds)
{
try
{
var payload = new { OrderId = orderId, UserIds = userIds };
var response = await _httpClient.PostAsJsonAsync("api/orderusers", payload);
if (!response.IsSuccessStatusCode)
return (false, $"Fehler beim Speichern: {response.ReasonPhrase}");
return (true, null);
}
catch (Exception ex)
{
return (false, ex.Message);
}
}
}
}