< Summary

Class:WinSolutions.Sveta.Server.Services.Implements.CategoryService
Assembly:WinSolutions.Sveta.Server
File(s):/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/CategoryService .cs
Covered lines:10
Uncovered lines:129
Coverable lines:139
Total lines:212
Line coverage:7.1% (10 of 139)
Covered branches:0
Total branches:50
Branch coverage:0% (0 of 50)

Metrics

MethodLine coverage Branch coverage
.ctor(...)100%100%
GetCategory()100%100%
GetCategory()0%100%
FindCategory()0%100%
CheckCollision()0%100%
FindCategory()0%0%
CheckParentIds()0%100%
GetNoTrackCategory()0%100%
GetCategoryByGuid()0%100%
GetCategories()0%0%
GetCategoriesCount()0%100%
GetPathToCategoryForFeed()0%0%
PrepareCategoriesQuery(...)0%0%
GetChildCategories()0%100%
GetChildCategoriesCount()0%100%
CreateCategory()0%0%
UpdateCategory()0%0%
ItemsExists()0%100%
DeleteCategory()0%0%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading.Tasks;
 5using Microsoft.EntityFrameworkCore;
 6using Microsoft.Extensions.Logging;
 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 TidVtbc;
 12using WinSolutions.Sveta.Common.Extensions;
 13
 14namespace WinSolutions.Sveta.Server.Services.Implements
 15{
 16    public class CategoryService: SvetaServiceBase, ICategoryService
 17    {
 18        private readonly SvetaDbContext _db;
 19        private readonly ILogger<CategoryService> _logger;
 20
 21        public CategoryService(SvetaDbContext db, ILogger<CategoryService> logger, IAuthenticationService authentication
 18922            : base(authenticationService)
 18923        {
 18924            _db = db;
 18925            _logger = logger;
 18926        }
 27
 28        public async Task<Category> GetCategory(long categoryId) =>
 229            await _db.Categories
 230            .Include(x => x.Parent)
 231            .Include(d => d.RecState)
 232            .Where(d => !d.IsDeleted)
 233            .FirstOrDefaultAsync(e => e.Id == categoryId);
 34
 35        public async Task<Category> GetCategory(string name) =>
 036            await _db.Categories.Where(d => !d.IsDeleted)
 037                .FirstOrDefaultAsync(d => d.Name.ToLower().Equals(name.NormalizeName().ToLower()));
 38
 39        public async Task<Category> FindCategory(long categoryId) =>
 040            await PrepareCategoriesQuery().FirstOrDefaultAsync(e => e.Id == categoryId);
 41
 42        /// <summary>
 43        /// Проверяем на колизии
 44        /// </summary>
 45        /// <param name="id"></param>
 46        /// <param name="parentId"></param>
 47        /// <returns></returns>
 48        public async Task<bool> CheckCollision(long id, long parentId)
 049        {
 50            //Проверка прямой колизии
 051            var items = await _db.Categories
 052                .Include(p => p.Parent)
 053                .Where(x => x.Id == parentId && x.Parent.Id == id)
 054                .AnyAsync();
 55
 056            return items;
 057        }
 58
 59        public async Task<List<Category>> FindCategory(string code)
 060        {
 061            var result = PrepareCategoriesQuery();
 062            if(!string.IsNullOrWhiteSpace(code))
 063            {
 064                result = result.Where(e => e.Code == code.NormalizeName());
 065            }
 066            return await result.ToListAsync();
 067        }
 68
 069        public async Task<List<long>> CheckParentIds(long[] parentIds) => await _db.Categories
 070            .Include(p=>p.Parent)
 071            .Where(x => parentIds.Contains(x.Parent.Id)) //проверив кто является родителем, отправим обратно список id э
 072            .Select(x=>x.Parent.Id)
 073            .ToListAsync();
 74
 075        public async Task<Category> GetNoTrackCategory(long categoryId) => await _db.Categories
 076            .Include(d => d.RecState)
 077            .AsNoTracking()
 078            .Include(x => x.Parent)
 079            .Where(d => !d.IsDeleted)
 080            .FirstOrDefaultAsync(e => e.Id == categoryId);
 81
 082        public async Task<Category> GetCategoryByGuid(Guid guid) => await _db.Categories
 083            .Where(d => !d.IsDeleted)
 084            .FirstOrDefaultAsync(d => d.GUID == guid);
 85
 086        public async Task<List<Category>> GetCategories(int page, int limit, string filter, long? parentId = null) => aw
 087            .AsNoTracking()
 088            .Skip((page < 2 ? 0: page -1) * limit)
 089            .Take(limit)
 090            .ToListAsync();
 91
 092        public async Task<int> GetCategoriesCount(string filter, long? parentId) => await PrepareCategoriesQuery(filter,
 93
 94        /// <summary>
 95        /// Метод возвращает полный путь к категории в виде Главная категория > Дочерняя категория > Входная категория
 96        /// </summary>
 97        /// <param name="categoryId"></param>
 98        /// <returns></returns>
 99        public async Task<string> GetPathToCategoryForFeed(long categoryId)
 0100        {
 0101            List<string> categories = new List<string>() { };
 0102            var category = await GetCategory(categoryId);
 0103            categories.Add(category.Name);
 0104            while (category.Parent != null)
 0105            {
 0106                category = await GetCategory(category.Parent.Id);
 0107                categories.Add(category.Name);
 0108            }
 0109            categories.Reverse();
 0110            return string.Join(" > ", categories);
 0111        }
 112
 113        IQueryable<Category> PrepareCategoriesQuery(string filter = "", long? parentId = null)
 0114        {
 0115            var result = _db.Categories
 0116                .Include(d => d.Parent)
 0117                .Include(d => d.RecState)
 0118                .OrderBy(x => x.Name)
 0119                .Where(e => !e.IsDeleted);
 0120            if (!string.IsNullOrWhiteSpace(filter))
 0121            {
 0122                result = result.Where(n => n.Name.ToUpper().Contains(filter.ToUpper()) || n.Code.ToUpper().Contains(filt
 0123            }
 124
 0125            if (parentId.HasValue)
 0126            {
 0127                result = parentId.Value switch
 0128                {
 0129                    -1 => result,
 0130                    0 => result.Where(x => x.Parent == null),
 0131                    _ => result.Where(x => x.Parent != null && x.Parent.Id == parentId.Value)
 0132                };
 0133            }
 0134            return result;
 0135        }
 136
 137        public async Task<List<Category>> GetChildCategories(int page, int limit, long? parentId)
 0138        {
 0139            return await PrepareCategoriesQuery(parentId: parentId)
 0140                .AsNoTracking()
 0141                .Skip(page * limit)
 0142                .Take(limit)
 0143                .ToListAsync();
 0144        }
 145
 0146        public async Task<int> GetChildCategoriesCount(long? parentId) => await PrepareCategoriesQuery(parentId: parentI
 147
 148        public async Task CreateCategory(Category categoryIn)
 0149        {
 0150            var exists = PrepareCategoriesQuery()
 0151                .Where(x => x.Name.ToLower() == categoryIn.Name.ToLower()
 0152                    || x.Code.ToLower() == categoryIn.Code.ToLower())
 0153                .Any();
 0154            if(exists)
 0155            {
 0156                throw new ArgumentException("Такая категория уже существует");
 157            }
 158
 0159            if (categoryIn.RecState != null)
 0160            {
 0161                _db.Entry(categoryIn.RecState).State = categoryIn.RecState.Id == 0 ? EntityState.Detached : EntityState.
 0162            }
 0163            if (categoryIn.Parent != null)
 0164            {
 0165                _db.Entry(categoryIn.Parent).State = categoryIn.Parent?.Id == 0 ? EntityState.Added : EntityState.Unchan
 0166            }
 0167            await _db.Categories.AddAsync(categoryIn);
 0168            await _db.SaveChangesAsync(CurrentUserId);
 0169        }
 170
 171        public async Task UpdateCategory(Category data)
 0172        {
 0173            if (!(await ItemsExists(data.Id)))
 0174            {
 0175                throw new ArgumentException($"Record #{data.Id} not found");
 176            }
 177
 0178            var exists = PrepareCategoriesQuery()
 0179                .Where(x => x.Id != data.Id
 0180                    && (x.Name.ToLower() == data.Name.NormalizeName().ToLower()
 0181                    || x.Code.ToLower() == data.Code.NormalizeName().ToLower()))
 0182                .Any();
 0183            if (exists)
 0184            {
 0185                throw new ArgumentException("Такая категория уже существует");
 186            }
 187
 0188            if (data.Parent != null)
 0189            {
 0190                _db.Entry(data.Parent).State = data.Parent?.Id == 0 ? EntityState.Added : EntityState.Unchanged;
 0191            }
 0192            _db.Categories.Update(data);
 0193            await _db.SaveChangesAsync(CurrentUserId);
 0194        }
 195
 0196        public async Task<bool> ItemsExists(long id) => await _db.Categories
 0197           .Where(e => e.Id == id)
 0198           .Where(d => !d.IsDeleted)
 0199           .AnyAsync();
 200
 201        public async Task DeleteCategory(long categoryId)
 0202        {
 0203            Category rec = await _db.Categories.FindAsync(categoryId);
 0204            if (rec == null)
 0205            {
 0206                throw new KeyNotFoundException($"Record #{categoryId} not found");
 207            }
 0208            rec.IsDeleted = true;
 0209            await _db.SaveChangesAsync(CurrentUserId);
 0210        }
 211    }
 212}