< Summary

Class:WinSolutions.Sveta.Server.Services.Implements.CategoryRatioService
Assembly:WinSolutions.Sveta.Server
File(s):/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/CategoryRatioService.cs
Covered lines:56
Uncovered lines:12
Coverable lines:68
Total lines:149
Line coverage:82.3% (56 of 68)
Covered branches:17
Total branches:36
Branch coverage:47.2% (17 of 36)

Metrics

MethodLine coverage Branch coverage
.ctor(...)100%100%
Create()93.75%50%
Delete()75%50%
PrepareDepartmentCategoryRatios()100%100%
GetDepartmentCategoryRatio()100%100%
GetDepartmentCategoryRatio()100%90%
DepartmentCategoryRatioExists()100%100%
Update()71.42%50%
Sort(...)0%0%

File(s)

/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/CategoryRatioService.cs

#LineLine coverage
 1
 2using Microsoft.EntityFrameworkCore;
 3using Microsoft.Extensions.Logging;
 4using System.Collections.Generic;
 5using System.Linq;
 6using System.Threading.Tasks;
 7using WinSolutions.Sveta.Server.Data.DataModel.Contexts;
 8using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 9using WinSolutions.Sveta.Server.Services.Interfaces;
 10using WinSolutions.Sveta.Common;
 11using System;
 12
 13namespace WinSolutions.Sveta.Server.Services.Implements
 14{
 15    public class CategoryRatioService : SvetaServiceBase, ICategoryRatioService
 16    {
 17        private readonly SvetaDbContext _db;
 18        private readonly ICategoryService _catService;
 19        private readonly ILogger<CategoryRatioService> _logger;
 20
 21        public CategoryRatioService(SvetaDbContext db, ILogger<CategoryRatioService> logger, IAuthenticationService auth
 18922            : base(authenticationService)
 18923        {
 18924            _catService = catService;
 18925            _db = db;
 18926            _logger = logger;
 18927        }
 28
 29        /// <summary>
 30        /// Создать торговый коэффициент  для категории
 31        /// </summary>
 32        /// <param name="data">DepartmentCategoryRatio</param>
 33        public async Task<DepartmentCategoryRatio> Create(DepartmentCategoryRatio data)
 234        {
 235            var ratio = _db.DepartmentCategoryRatio.FirstOrDefault(x => x.DepartmentId == data.DepartmentId && x.Categor
 236            if (ratio != null)
 137            {
 138                ratio.IsDeleted = false;
 139                ratio.TradeRatio = data.TradeRatio;
 140            }
 41            else
 142            {
 143                if (data.RecState != null)
 044                    _db.Entry(data.RecState).State = data.RecState.Id == 0 ? EntityState.Detached : EntityState.Unchange
 145                _db.DepartmentCategoryRatio.Add(data);
 146                ratio = data;
 147            }
 248            await _db.SaveChangesAsync(CurrentUserId);
 49
 250            return ratio;
 251        }
 52
 53        /// <summary>
 54        /// Удалить торговы коэфф-т категории по id
 55        /// </summary>
 56        /// <param name="id">id записи</param>
 57        /// <returns></returns>
 58        public async Task Delete(long id)
 159        {
 160            var data = await _db.DepartmentCategoryRatio.FindAsync(id);
 161            if (data == null)
 062            {
 063                throw new KeyNotFoundException($"Запись с id={id} не найдена");
 64            }
 165            data.IsDeleted = true;
 166            await _db.SaveChangesAsync(CurrentUserId);
 167        }
 68
 69        /// <summary>
 70        /// предварительная выборка торговых коэфф-тов
 71        /// </summary>
 72        /// <returns></returns>
 1173        private IQueryable<DepartmentCategoryRatio> PrepareDepartmentCategoryRatios() => _db.DepartmentCategoryRatio
 1174            .Include(d => d.Category)
 1175            .ThenInclude(p => p.Parent)
 1176            .Include(d => d.Department)
 1177            .Include(d => d.RecState)
 1178            .Where(e => !e.IsDeleted)
 1179            .AsQueryable();
 80
 81        /// <summary>
 82        /// получает торговый коэфф-т категории по id
 83        /// </summary>
 84        /// <param name="id">id записи</param>
 85        /// <returns></returns>
 786        public async Task<DepartmentCategoryRatio> GetDepartmentCategoryRatio(long id) => await PrepareDepartmentCategor
 787            .Where(x => x.Id == id)
 788            .FirstOrDefaultAsync();
 89
 90        /// <summary>
 91        /// Возвращаем коэф для категории в рамках подразделения. Если коэффициента нет, то смотрим есть ли у родительск
 92        /// При отсутствии родителя возвращаем 100
 93        /// </summary>
 94        /// <param name="departmentId">id департмента</param>
 95        /// <param name="categoryId">id категории</param>
 96        /// <returns></returns>
 97        public async Task<DepartmentCategoryRatio> GetDepartmentCategoryRatio(long departmentId, long categoryId)
 498        {
 499            var ratio = await PrepareDepartmentCategoryRatios()
 4100            .Where(x => x.Department.Id == departmentId)
 4101            .Where(c => c.Category.Id == categoryId)
 4102            .FirstOrDefaultAsync() ?? new DepartmentCategoryRatio(); //находим запись или создаем пустой экземпляр
 4103            if (ratio.Category == null)
 2104                ratio.Category = await _catService.GetCategory(categoryId); // если нет категории (пустой экземпляр), на
 4105            if (ratio.TradeRatio == 0)
 2106            {//если нет родительской категории, то присваиваем коэф 100, иначе рекурсивно ищем по родительским категория
 2107                ratio.TradeRatio = ratio.Category?.Parent == null ? 100 : (await GetDepartmentCategoryRatio(departmentId
 2108            }
 4109            return ratio;
 4110        }
 111
 112        /// <summary>
 113        /// проверяет существование записи по id
 114        /// </summary>
 115        /// <param name="id">id записи</param>
 116        /// <returns>true/false</returns>
 3117        public async Task<bool> DepartmentCategoryRatioExists(long id) => await _db.DepartmentCategoryRatio.Where(e => !
 118
 119        /// <summary>
 120        /// Обновляет торговый коэфф-т для категории
 121        /// </summary>
 122        /// <param name="data">объект DepartmentCategoryRatio</param>
 123        /// <returns></returns>
 124        public async Task Update(DepartmentCategoryRatio data)
 1125        {
 1126            if (!(await DepartmentCategoryRatioExists(data.Id)))
 0127            {
 0128                throw new ArgumentException($"Запись с id={data.Id} не найдена");
 129            }
 1130            _db.DepartmentCategoryRatio.Update(data);
 1131            await _db.SaveChangesAsync(CurrentUserId);
 1132        }
 133
 134        /// <summary>
 135        /// Сортирует BankAccount по полям
 136        /// </summary>
 137        /// <param name="items"></param>
 138        /// <param name="sort">сортировка по умолчанию
 139        /// по id - id|desc, TradeRatio,TradeRatio|desc</param>
 140        /// <returns></returns>
 0141        private IQueryable<DepartmentCategoryRatio> Sort(IQueryable<DepartmentCategoryRatio> items, string sort = defaul
 0142        {
 0143            "traderatio" => items.OrderBy(d => d.TradeRatio),
 0144            "traderatio|desc" => items.OrderByDescending(d => d.TradeRatio),
 0145            "id|desc" => items.OrderByDescending(d => d.Id),
 0146            _ => items.OrderBy(d => d.Id),
 0147        };
 148    }
 149}