using iRIS.Framework.CrossCutting.Caching.MemoryCache; using…
- User
using iRIS.Framework.CrossCutting.Caching.MemoryCache; using iRIS.InsuranceCore.Code.CustomProcesses.BasketPreparationProcess.Enums; using iRIS.InsuranceCore.Entities; using iRIS.Framework.Data; using iRIS.Framework.Data.Services.Client.Interfaces; using iRIS.Framework.SystemLayout.Entities; using System; using System.Collections.Generic; using System.Linq; using iRIS.InsuranceCore.Code.Interfaces;
namespace iRIS.InsuranceCore.Code.Queries { public class QueryOffer : IQueryOffer { private static readonly string CacheKey = "GetAllOffers";
private readonly ITimeFramedProactiveMemoryCache _memoryCache; private readonly IQueryProductConfiguration _queryProductConfiguration; public static void WarmUpAllOffersCache(ICachedQueryServiceInvoker queryService, ITimeFramedProactiveMemoryCache memoryCache, IQueryProductConfiguration queryProductConfiguration) { // опции для кеша var defaultCacheOptions = TimeFrameCacheItemOptions.GetDefaultCacheOptions(); defaultCacheOptions.ActualBeginDateOffset = TimeSpan.FromDays(90); //90 день назад, радиус загрузки memoryCache.RegisterCacheItem( CacheKey, (dateBegin, dateEnd) => { var cashedOffers = GetOffersFromDB(queryService, dateBegin, dateEnd); return cashedOffers; }, (actualDate, offers) => offers, CacheTags.Offers, defaultCacheOptions, false); } private static List<Offer> GetOffersFromDB(ICachedQueryServiceInvoker queryService, DateTime dateBegin, DateTime dateEnd) { return queryService.GetByExpressionActualVersion<Offer>( queryable => queryable.Select(x => x), dateBegin, dateEnd, new List<string> { nameof(Offer.Product), nameof(Offer.Segments), nameof(Offer.Currencies), nameof(Offer.Product) + "." + nameof(Product.DeliveryWays), nameof(Offer.OfferStructs), nameof(Offer.OfferMappings), nameof(Offer.OfferSets), nameof(Offer.OfferCalculationMethods), $"{nameof(Offer.OfferSets)}.{nameof(OfferSet.OfferSetType)}", }); } public QueryOffer(ITimeFramedProactiveMemoryCache memoryCache, IQueryProductConfiguration queryProductConfiguration) { _memoryCache = memoryCache; _queryProductConfiguration = queryProductConfiguration; } public void ReloadCacheOffers() { _memoryCache.ReloadCacheItem(CacheKey); } /// <summary> /// Догрузка настроек расчета для офферов /// </summary> public List<Offer> GetOffersForRater(int?[] offerIds, DateTime currentDate, bool? useDrafts) { var result = GetAllOffersFiltered(currentDate, useDrafts, offerIds) .FilterByState(useDrafts) .ToList(); return result; } /// <inheritdoc/> public Offer GetOffer(int? offerId, DateTime currentDate, bool? useDrafts) { var result = GetAllOffersFiltered(currentDate, useDrafts, new[] { offerId }) .FirstOrDefault(); return result; } /// <inheritdoc/> public Product GetOfferProduct(int? offerId, DateTime currentDate) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, false); return offerItem?.Product; } else { return null; } } /// <inheritdoc/> public string GetOfferName(int? offerId, DateTime currentDate, bool? useDrafts) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, useDrafts); return offerItem?.Name; } else { return null; } } /// <inheritdoc/> public IReadOnlyCollection<OfferStruct> GetOfferStructs(int? offerId, DateTime currentDate, bool? useDrafts) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, useDrafts); return offerItem?.OfferStructs; } else { return null; } } /// <inheritdoc/> public IEnumerable<OfferCalculationMethod> GetOfferCalculationMethods(int? offerId, DateTime currentDate, bool? useDrafts, ICalculationMethodsFinder calculationMethodsFinder, bool? isProlongation = null) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, useDrafts); return calculationMethodsFinder.GetCalculationMethods(offerItem, currentDate, useDrafts, isProlongation); } else { return null; } } /// <inheritdoc/> public bool? GetOfferIsBox(int? offerId, DateTime currentDate) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, false); return offerItem?.IsBox; } else { return (bool?)null; } } /// <inheritdoc/> public bool? GetOfferIsSpecial(int? offerId, DateTime currentDate) { if (offerId.HasValue) { var offerItem = GetOffer(offerId, currentDate, false); return offerItem?.IsSpecialOffer; } else { return (bool?)null; } } /// <inheritdoc/> public List<Offer> GetOffers(int?[] offerIds, DateTime currentDate, bool? useDrafts) { return GetAllOffersFiltered(currentDate, useDrafts, offerIds) .FilterByState(useDrafts) .ToList(); } public List<Offer> GetOffers(Func<Offer, bool> condition, DateTime currentDate, bool? useDrafts) { return GetAllOffersFiltered(currentDate, useDrafts) .Where(condition) .FilterByState(useDrafts) .ToList(); } public IDictionary<int, ObservableList<WidgetDynamicAttribute>> GetHiddenAttributeForOffers(int?[] offerIds, DateTime currentDate, bool? useDrafts) { return GetAllOffersFiltered(currentDate, useDrafts, offerIds) .ToDictionary(offer => offer.Id, offer => offer.WidgetDynamicAttributes); } /// <summary> /// Получить комбинацию всех возможных офферов для всех активных сделок /// </summary> /// <param name="deals">Сделки</param> /// <returns>Офферы</returns> public Dictionary<Deal, IEnumerable<Offer>> GetOffersForDeals(IEnumerable<Deal> deals, DateTime currentDate, bool? useDrafts) { var offers = new Dictionary<Deal, IEnumerable<Offer>>(); foreach (var deal in deals.Where(d => d.DealStatusCode != EntityStatusType.OfferTerminated.ToString()).ToList()) { var offerIds = deal.Proposals .Where(p => p.Offer_Id.HasValue) .Select(p => p.Offer_Id).Distinct().ToArray(); var offers_ = GetOffers(offerIds, deal.DateActual ?? currentDate, useDrafts).ToList(); offers.Add(deal, offers_); } return offers; } private List<Offer> GetAllOffersFiltered(DateTime currentDate, bool? useDrafts, int?[] offerIds = null) { var offers = _memoryCache.Get<List<Offer>>(CacheKey, currentDate); if (offerIds != null) { offers = offers.Where(x => offerIds.Contains(x.Id)).ToList(); } return offers.FilterOffersByDate(currentDate) .FilterOfferStructByProductConfigurationVersion(_queryProductConfiguration, currentDate, useDrafts); } public int? GetOfferIdByProgramName(string aisProductGuid, string name) { throw new NotImplementedException(); } } - Assistant
Давайте добавим метод
GetOfferIdByProgramNameв классQueryOffer. Этот метод будет искать offer по заданномуaisProductGuidиnameи возвращать его id. Предполагая, что сущностиOfferсодержат поля сAisProductGuidиName, вот как вы можете реализовать этот метод:public int? GetOfferIdByProgramName(string aisProductGuid, string name) { // Получаем все предложения из кэша на текущий момент var currentDate = DateTime.Now; bool? useDrafts = false; // Предположим, что мы не используем черновики; значение можно изменить по необходимости var offers = GetAllOffersFiltered(currentDate, useDrafts); // Находим оффер, соответствующий переданным параметрам var offer = offers.FirstOrDefault(o => o.AisProductGuid == aisProductGuid && o.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); // Возвращаем Id оффера, если он был найден, иначе null return offer?.Id; } - User
по state они фильтруются?
- Assistant
Да, в вашем коде офферы фильтруются по состоянию. В методе
GetAllOffersFiltered, после получения офферов из кэша, применяется фильтрация с помощью методаFilterOffersByDateи затем с помощью методаFilterOfferStructByProductConfigurationVersion. После этого, результаты фильтруются по состоянию через вызовFilterByStateперед возвратом окончательного списка офферов в методах вродеGetOffersForRater,GetOffer, и других.Однако, в вашем коде не показано в деталях, как именно работает
FilterByState. Нужно убедиться, что этот метод корректно реализует логику фильтрации офферов по их состоянию (например, активный, черновик и т.д.). Поскольку документация и реализация этих методов не предоставлена в вашем коде, вам нужно проверить это отдельно.Если все фильтры настроены правильно, офферы должны фильтроваться по состоянию в зависимости от значений, переданных в метод
GetAllOffersFiltered, таких как текущая дата и флаг использования черновиков (useDrafts).