DRAB/Drab.Logic/Services/OrdersStore.cs
2025-07-11 00:18:14 +02:00

78 lines
2.5 KiB
C#

using Drab.Core.Models;
using Drab.Logic.Dtos;
using Drab.Logic.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using Pcm.Db;
using Pcm.Db.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Drab.Core.Configuration;
namespace Drab.Logic.Services;
public class OrdersStore : IOrdersStore, IDisposable
{
private readonly ILogger _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IDrabSettings _drabSettings;
public OrdersStore(IServiceScopeFactory serviceScopeFactory, IDrabSettings drabSettings)
{
_serviceScopeFactory = serviceScopeFactory;
_drabSettings = drabSettings;
_logger = LogManager.GetCurrentClassLogger();
}
public async Task<Result<List<DokDto>, string>> FetchOrders()
{
_logger.Info("Fetch new orders");
DateTime date;
try
{
date = DateTime.ParseExact(_drabSettings.IgnoreOrdersBefore, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
catch
{
date = DateTime.Now - TimeSpan.FromDays(30);
}
using var scope = _serviceScopeFactory.CreateScope();
await using var dbContext = scope.ServiceProvider.GetService<PcmDbContext>();
try
{
var orders = await dbContext.Dokumenty
.Where(x => x.Aktywny == 1
&& x.TypDok == (short)TypDok.RejestracjaZamowieniaOdOdbiorcy
&& x.Opcja1 == 0
&& x.Data >= date)
.Include(x => x.DokKontr)
.ThenInclude(x => x.Kontr)
.Include(x => x.TekstDoks.Where(y =>
y.Znaczenie == (short)TekstDokZnaczenie.InfoDoZamowienia ||
y.Znaczenie == (short)TekstDokZnaczenie.TekstDod2))
.Include(x => x.PozDoks)
.ThenInclude(x => x.TekstPozs.Where(y => y.Znaczenie == 0 || y.Znaczenie == 13))
.Include(x => x.PozDoks)
.ThenInclude(x => x.Tow)
.ThenInclude(x => x.Jm)
.ToListAsync();
return Result.Ok<List<DokDto>, string>(orders.Select(x => x.ToDokDto()).ToList());
}
catch (Exception e)
{
_logger.Error(e, "Error on fetching orders");
return Result.Failed<List<DokDto>, string>(e.Message);
}
}
public void Dispose()
{
}
}