| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 9 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 10 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 11 | | using WinSolutions.Sveta.Common; |
| | | 12 | | using WinSolutions.Sveta.Server.Domain; |
| | | 13 | | using SVETA.Api.Helpers; |
| | | 14 | | using Microsoft.EntityFrameworkCore.Internal; |
| | | 15 | | using Clave.Expressionify; |
| | | 16 | | |
| | | 17 | | namespace WinSolutions.Sveta.Server.Services.Implements |
| | | 18 | | { |
| | | 19 | | public class PriceTrendService : SvetaServiceBase, IPriceTrendService |
| | | 20 | | { |
| | | 21 | | private readonly SvetaDbContext _db; |
| | | 22 | | private readonly ILogger<PriceTrendService> _logger; |
| | | 23 | | private readonly IAuthenticationService _authenticationService; |
| | | 24 | | private readonly IDepartmentService _departService; |
| | | 25 | | |
| | | 26 | | public PriceTrendService(SvetaDbContext db, ILogger<PriceTrendService> logger, IAuthenticationService authentica |
| | 184 | 27 | | : base(authenticationService) |
| | 184 | 28 | | { |
| | 184 | 29 | | _db = db; |
| | 184 | 30 | | _departService = departService; |
| | 184 | 31 | | _logger = logger; |
| | 184 | 32 | | _authenticationService = authenticationService; |
| | 184 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// создает запись в PriceTrend |
| | | 37 | | /// </summary> |
| | | 38 | | /// <param name="data">объект PriceTrend</param> |
| | | 39 | | /// <returns></returns> |
| | | 40 | | public async Task CreatePriceTrend(PriceTrend data) |
| | 184 | 41 | | { |
| | 184 | 42 | | _db.Entry(data.SupplierDepartment).State = EntityState.Unchanged; |
| | 184 | 43 | | await _db.PricesTrend.AddAsync(data); |
| | 184 | 44 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 184 | 45 | | data.DocNumber = "PT" + data.Id.ToString("D8"); |
| | 184 | 46 | | await UpdatePriceTrend(data); |
| | 184 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary> |
| | | 50 | | /// предварительная выборка объектов PriceTrend |
| | | 51 | | /// </summary> |
| | | 52 | | /// <returns></returns> |
| | 184 | 53 | | private IQueryable<PriceTrend> PreparePriceTrends() => _db.PricesTrend |
| | 184 | 54 | | .Include(e => e.SupplierDepartment).ThenInclude(SupplierDepartment => SupplierDepartment.Contragent) |
| | 184 | 55 | | .Where(e => !e.IsDeleted) |
| | 184 | 56 | | .AsQueryable(); |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// предварительная выборка объектов PriceTrendDetail |
| | | 60 | | /// </summary> |
| | | 61 | | /// <returns></returns> |
| | 0 | 62 | | private IQueryable<PriceTrendDetail> PreparePriceTrendsDetail() => _db.PriceTrendDetails |
| | 0 | 63 | | .Include(e => e.Good).ThenInclude(x => x.Category) |
| | 0 | 64 | | .Include(e => e.Good).ThenInclude(x => x.GoodBarcodes).ThenInclude(d => d.BarCode) |
| | 0 | 65 | | .Include(e => e.Good).ThenInclude(x => x.DefaultBarCode) |
| | 0 | 66 | | .Include(e => e.Good).ThenInclude(x => x.Photos) |
| | 0 | 67 | | .Include(d => d.Good) |
| | 0 | 68 | | .ThenInclude(Good => Good.DepartmentGoodSettings) |
| | 0 | 69 | | .Include(e => e.PriceTrend).ThenInclude(PriceTrend => PriceTrend.SupplierDepartment).ThenInclude(SupplierDep |
| | 0 | 70 | | .Where(e => !e.IsDeleted && !e.Good.IsDeleted) |
| | 0 | 71 | | .AsQueryable(); |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// удаляет запись из PriceTrend |
| | | 75 | | /// </summary> |
| | | 76 | | /// <param name="id">id записи</param> |
| | | 77 | | /// <returns></returns> |
| | | 78 | | public async Task DeletePriceTrend(long id) |
| | 0 | 79 | | { |
| | 0 | 80 | | var data = await PreparePriceTrends() |
| | 0 | 81 | | .FirstAsync(p => p.Id == id); |
| | 0 | 82 | | if (data == null) |
| | 0 | 83 | | { |
| | 0 | 84 | | throw new KeyNotFoundException($"Переоценка с id={id} не найдена"); |
| | | 85 | | } |
| | 0 | 86 | | var details = _db.PriceTrendDetails.Where(x => x.PriceTrendId == id); |
| | 0 | 87 | | foreach (var item in details) |
| | 0 | 88 | | item.IsDeleted = true; |
| | 0 | 89 | | data.IsDeleted = true; |
| | 0 | 90 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 0 | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// удаляет запись из PriceTrendDetail |
| | | 95 | | /// </summary> |
| | | 96 | | /// <param name="id">id записи</param> |
| | | 97 | | /// <returns></returns> |
| | | 98 | | public async Task DeletePriceTrendDetail(long id) |
| | 0 | 99 | | { |
| | 0 | 100 | | var data = await _db.PriceTrendDetails |
| | 0 | 101 | | .FirstAsync(p => p.Id == id); |
| | 0 | 102 | | if (data == null) |
| | 0 | 103 | | { |
| | 0 | 104 | | throw new KeyNotFoundException($"Переоценка товара с id={id} не найдена"); |
| | | 105 | | } |
| | 0 | 106 | | data.IsDeleted = true; |
| | 0 | 107 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 0 | 108 | | } |
| | | 109 | | |
| | | 110 | | /// <summary> |
| | | 111 | | /// Возвращает последнюю цену переоценки, которая уже действует (она есть текущая цена) |
| | | 112 | | /// </summary> |
| | | 113 | | /// <param name="goodId">id товара</param> |
| | | 114 | | /// <param name="departmentId">id склада</param> |
| | | 115 | | /// <returns></returns> |
| | 0 | 116 | | public async Task<PriceTrendDetail> GetCurrentPriceFromDetail(long goodId, long departmentId) => await PreparePr |
| | 0 | 117 | | .Where(x => x.PriceTrend.BeginDate <= DateTime.Now && x.GoodId == goodId && x.PriceTrend.SupplierDepartm |
| | 0 | 118 | | .OrderBy(x => x.PriceTrend.BeginDate) |
| | 0 | 119 | | .LastOrDefaultAsync(); |
| | | 120 | | |
| | | 121 | | /// <summary> |
| | | 122 | | /// получить запись из PriceTrend |
| | | 123 | | /// </summary> |
| | | 124 | | /// <param name="id">id записи</param> |
| | | 125 | | /// <param name="contragentId">id контрагента (необязательно)</param> |
| | | 126 | | /// <returns></returns> |
| | 0 | 127 | | public async Task<PriceTrend> GetPriceTrend(long id, long? contragentId) => await PreparePriceTrends() |
| | 0 | 128 | | .Where(x=> !contragentId.HasValue || x.SupplierDepartment.Contragent.Id == contragentId) |
| | 0 | 129 | | .FirstOrDefaultAsync(d => d.Id == id); |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// получить запись из PriceTrend с привязкой записей из PriceTrendDetail |
| | | 133 | | /// </summary> |
| | | 134 | | /// <param name="id">id записи</param> |
| | | 135 | | /// <param name="contragentId">id контрагента (необязательно)</param> |
| | | 136 | | /// <returns></returns> |
| | 0 | 137 | | public async Task<PriceTrend> GetPriceTrendWithDetails(long id, long? contragentId) => await PreparePriceTrends( |
| | 0 | 138 | | .Include(e => e.PriceTrendDetails) |
| | 0 | 139 | | .ThenInclude(PriceTrendDetails => PriceTrendDetails.Good) |
| | 0 | 140 | | .ThenInclude(x => x.DefaultBarCode) |
| | 0 | 141 | | .Include(e => e.PriceTrendDetails) |
| | 0 | 142 | | .ThenInclude(PriceTrendDetails => PriceTrendDetails.Good) |
| | 0 | 143 | | .ThenInclude(x => x.GoodBarcodes) |
| | 0 | 144 | | .ThenInclude(x => x.BarCode) |
| | 0 | 145 | | .Expressionify() |
| | 0 | 146 | | .AsNoTracking() |
| | 0 | 147 | | .Where(x => !contragentId.HasValue || x.SupplierDepartment.Contragent.Id == contragentId) |
| | 0 | 148 | | .FirstOrDefaultAsync(d => d.Id == id); |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// получает записи из PriceTrendDetail с пагинацией и фильтрацией |
| | | 152 | | /// </summary> |
| | | 153 | | /// <param name="priceTrendId">id родительской записи</param> |
| | | 154 | | /// <param name="page">номер страницы</param> |
| | | 155 | | /// <param name="limit">размер страницы</param> |
| | | 156 | | /// <param name="filter">фильтр по названию товара</param> |
| | | 157 | | /// <returns></returns> |
| | | 158 | | public async Task<PaginatedData<List<PriceTrendDetail>>> GetPriceTrendDetails(long priceTrendId, int page, int l |
| | 0 | 159 | | { |
| | 0 | 160 | | var details = PreparePriceTrendsDetail().AsNoTracking().Where(x=>x.PriceTrendId == priceTrendId); |
| | 0 | 161 | | int total = await details?.CountAsync(); |
| | 0 | 162 | | details = details.Where(x => string.IsNullOrWhiteSpace(filter) || x.Good.Name.ToUpper().Contains(filter.ToUp |
| | 0 | 163 | | int totalFiltered = await details?.CountAsync(); |
| | 0 | 164 | | return new PaginatedData<List<PriceTrendDetail>> |
| | 0 | 165 | | { |
| | 0 | 166 | | Result = await details.Skip(page * limit).Take(limit).ToListAsync(), |
| | 0 | 167 | | TotalCount = total, |
| | 0 | 168 | | TotalFilteredCount = totalFiltered |
| | 0 | 169 | | }; |
| | 0 | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary> |
| | | 173 | | /// получить запись из PriceTrendDetail |
| | | 174 | | /// </summary> |
| | | 175 | | /// <param name="id">id записи </param> |
| | | 176 | | /// <param name="contragentId">id контрагента (необязательно)</param> |
| | | 177 | | /// <returns></returns> |
| | 0 | 178 | | public async Task<PriceTrendDetail> GetPriceTrendDetail(long id, long? contragentId) => await PreparePriceTrends |
| | 0 | 179 | | .Where(d => !contragentId.HasValue || d.PriceTrend.SupplierDepartment.Contragent.Id == contragentId) |
| | 0 | 180 | | .FirstOrDefaultAsync(d => d.Id == id); |
| | | 181 | | |
| | | 182 | | /// <summary> |
| | | 183 | | /// получить список записей из PriceTrend с пагинацией, сортировкой и фильтрацией |
| | | 184 | | /// </summary> |
| | | 185 | | /// <param name="page">номер страницы</param> |
| | | 186 | | /// <param name="limit">размер страницы</param> |
| | | 187 | | /// <param name="departmentId">id склада</param> |
| | | 188 | | /// <param name="beginDate">дата с</param> |
| | | 189 | | /// <param name="endDate">дата по</param> |
| | | 190 | | /// <param name="filter">фильтр по названию товара</param> |
| | | 191 | | /// <param name="sort">сортировка</param> |
| | | 192 | | /// <returns></returns> |
| | | 193 | | public async Task<PaginatedData<List<PriceTrend>>> GetPriceTrends(int page, int limit, long departmentId, DateTi |
| | 0 | 194 | | { |
| | 0 | 195 | | var prices = PreparePriceTrends().Include(e => e.PriceTrendDetails).ThenInclude(PriceTrendDetails => PriceTr |
| | | 196 | | // Тотал записей для смертных считаем после прмиенения ограничения роли |
| | 0 | 197 | | int total = await prices?.CountAsync(x => _authenticationService.IsUserPlatform() || x.SupplierDepartment.Co |
| | 0 | 198 | | prices = prices.Where(x => _authenticationService.IsUserPlatform() || x.SupplierDepartment.Contragent.Id == |
| | 0 | 199 | | .Where(x=> departmentId ==0 || x.SupplierDepartment.Id == departmentId) |
| | 0 | 200 | | .Where(x=> beginDate.IsNullOrMinValue() || x.BeginDate.Date >= beginDate.Value.Date) |
| | 0 | 201 | | .Where(x => endDate.IsNullOrMinValue() || x.BeginDate.Date <= endDate.Value.Date) //сравниваем с beginda |
| | 0 | 202 | | .Where(x => string.IsNullOrWhiteSpace(filter) || x.PriceTrendDetails.Any(x=> x.Good.Name.ToUpper().Conta |
| | 0 | 203 | | prices = Sort(prices, sort?.ToLower()); |
| | 0 | 204 | | int filtered = await prices?.CountAsync(); |
| | 0 | 205 | | return new PaginatedData<List<PriceTrend>> |
| | 0 | 206 | | { |
| | 0 | 207 | | Result = await prices.Skip(page * limit).Take(limit).ToListAsync(), |
| | 0 | 208 | | TotalCount = total, |
| | 0 | 209 | | TotalFilteredCount = filtered |
| | 0 | 210 | | }; |
| | 0 | 211 | | } |
| | | 212 | | |
| | | 213 | | /// <summary> |
| | | 214 | | /// проверяет существование записи в PriceTrend |
| | | 215 | | /// </summary> |
| | | 216 | | /// <param name="id">id записи</param> |
| | | 217 | | /// <returns></returns> |
| | 184 | 218 | | public async Task<bool> PriceTrendExists(long id) => await PreparePriceTrends() |
| | 184 | 219 | | .Where(e => e.Id == id) |
| | 184 | 220 | | .AnyAsync(); |
| | | 221 | | |
| | | 222 | | /// <summary> |
| | | 223 | | /// обновляет запись в PriceTrend |
| | | 224 | | /// </summary> |
| | | 225 | | /// <param name="data">объект PriceTrend</param> |
| | | 226 | | /// <returns></returns> |
| | | 227 | | public async Task UpdatePriceTrend(PriceTrend data) |
| | 184 | 228 | | { |
| | 184 | 229 | | if (!(await PriceTrendExists(data.Id))) |
| | 0 | 230 | | { |
| | 0 | 231 | | throw new ArgumentException($"Переоценка с id={data.Id} не найдена"); |
| | | 232 | | } |
| | 184 | 233 | | _db.PricesTrend.Update(data); |
| | 184 | 234 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 184 | 235 | | } |
| | | 236 | | |
| | | 237 | | /// <summary> |
| | | 238 | | /// создает запись в PriceTrendDetail |
| | | 239 | | /// </summary> |
| | | 240 | | /// <param name="data">объект PriceTrendDetail</param> |
| | | 241 | | /// <returns></returns> |
| | | 242 | | public async Task CreatePriceTrendDetail(PriceTrendDetail data) |
| | 368 | 243 | | { |
| | 368 | 244 | | var existing = await _db.PriceTrendDetails.FirstOrDefaultAsync(x => x.Good.Id == data.Good.Id && x.PriceTren |
| | 368 | 245 | | if (existing != null) |
| | 0 | 246 | | { |
| | 0 | 247 | | existing.PriceNew = data.PriceNew; |
| | 0 | 248 | | existing.PriceOld = data.PriceOld; |
| | 0 | 249 | | existing.IsDeleted = false; |
| | 0 | 250 | | } |
| | | 251 | | else |
| | 368 | 252 | | { |
| | 368 | 253 | | _db.Entry(data.Good).State = EntityState.Unchanged; |
| | 368 | 254 | | _db.Entry(data.PriceTrend).State = EntityState.Unchanged; |
| | 368 | 255 | | await _db.PriceTrendDetails.AddAsync(data); |
| | 368 | 256 | | } |
| | 368 | 257 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 368 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <summary> |
| | | 261 | | /// проверяет существование записи в PriceTrendDetails |
| | | 262 | | /// </summary> |
| | | 263 | | /// <param name="id">id записи</param> |
| | | 264 | | /// <returns></returns> |
| | 0 | 265 | | public async Task<bool> PriceTrendDetailExists(long id) => await _db.PriceTrendDetails |
| | 0 | 266 | | .Where(e => e.Id == id) |
| | 0 | 267 | | .AnyAsync(); |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// обновляет запись в PriceTrendDetail |
| | | 271 | | /// </summary> |
| | | 272 | | /// <param name="data">объект PriceTrendDetail</param> |
| | | 273 | | /// <returns></returns> |
| | | 274 | | public async Task UpdatePriceTrendDetail(PriceTrendDetail data) |
| | 0 | 275 | | { |
| | 0 | 276 | | if (!(await PriceTrendDetailExists(data.Id))) |
| | 0 | 277 | | { |
| | 0 | 278 | | throw new ArgumentException($"Переоценка товара с id={data.Id} не найдена"); |
| | | 279 | | } |
| | 0 | 280 | | _db.PriceTrendDetails.Update(data); |
| | 0 | 281 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 0 | 282 | | } |
| | | 283 | | |
| | | 284 | | /// <summary> |
| | | 285 | | /// сортировка |
| | | 286 | | /// </summary> |
| | | 287 | | /// <param name="items">выборка записей PriceTrend</param> |
| | | 288 | | /// <param name="sort">тип сортировки</param> |
| | | 289 | | /// <returns></returns> |
| | 0 | 290 | | private IQueryable<PriceTrend> Sort(IQueryable<PriceTrend> items, string sort = default) => (sort ?? "").ToLower |
| | 0 | 291 | | { |
| | 0 | 292 | | "goodscount" => items.OrderBy(d => d.PriceTrendDetails.Count()), |
| | 0 | 293 | | "goodscount|desc" => items.OrderByDescending(d => d.PriceTrendDetails.Count()), |
| | 0 | 294 | | "begindate" => items.OrderBy(d => d.BeginDate), |
| | 0 | 295 | | "begindate|desc" => items.OrderByDescending(d => d.BeginDate), |
| | 0 | 296 | | "creationdate" => items.OrderBy(d => d.CreationDateTime), |
| | 0 | 297 | | "creationdate|desc" => items.OrderByDescending(d => d.CreationDateTime), |
| | 0 | 298 | | "docnumber" => items.OrderBy(d => d.DocNumber), |
| | 0 | 299 | | _ => items.OrderByDescending(d => d.DocNumber) |
| | 0 | 300 | | }; |
| | | 301 | | |
| | | 302 | | |
| | | 303 | | } |
| | | 304 | | } |