< Summary

Class:SVETA.Api.Controllers.BankAccountsController
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Controllers/BankAccountsController.cs
Covered lines:0
Uncovered lines:87
Coverable lines:87
Total lines:296
Line coverage:0% (0 of 87)
Covered branches:0
Total branches:40
Branch coverage:0% (0 of 40)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
GetBankAccount()0%0%
CreateBankAccount()0%0%
UpdateBankAccount()0%0%
DeleteBankAccount()0%0%
ToBankAccountDtoMapper()0%0%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Controllers/BankAccountsController.cs

#LineLine coverage
 1using System;
 2using WinSolutions.Sveta.Common.Extensions;
 3using System.Collections.Generic;
 4using System.Linq;
 5using System.Threading.Tasks;
 6using AutoMapper;
 7using Microsoft.AspNetCore.Authorization;
 8using Microsoft.AspNetCore.Http;
 9using Microsoft.AspNetCore.Mvc;
 10using Microsoft.Extensions.Logging;
 11using SVETA.Api.Data.DTO;
 12using SVETA.Api.Data.DTO.BankAccount;
 13using SVETA.Api.Helpers.Authorize;
 14using Swashbuckle.AspNetCore.Annotations;
 15using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 16using WinSolutions.Sveta.Server.Services.Interfaces;
 17using WinSolutions.Sveta.Common;
 18
 19namespace SVETA.Api.Controllers
 20{
 21    [Route("api/v1/BankAccounts")]
 22    [ApiController]
 23    public class BankAccountsController : SvetaController
 24    {
 25        const string _routeUrl = "api/v1/BankAccounts";
 26        readonly IBankAccountService _bankAccountService;
 27        readonly IContragentService _contragentService;
 28        readonly IUserService _userService;
 29        readonly ILogger<BankAccountsController> _logger;
 30        readonly IAuthenticationService _authenticationService;
 31        private User _user;
 32
 33        public BankAccountsController(
 34            IBankAccountService bankAccountService,
 35            IContragentService contragentService,
 36            IAuthenticationService authenticationService,
 37            IUserService userService,
 038            ILogger<BankAccountsController> logger) : base(logger)
 039        {
 040            _bankAccountService = bankAccountService;
 041            _contragentService = contragentService;
 042            _userService = userService;
 043            _authenticationService = authenticationService;
 044            _logger = logger;
 045        }
 46
 47        /// <summary>
 48        /// Получить список банковских счетов
 49        /// </summary>
 50        /// <remarks>author IPod</remarks>
 51        /// <param name="page">Любое значение ниже нуля изменится на 1, Номер страницы для паганации</param>
 52        /// <param name="limit">Любое значение ниже нуля изменится на 10, Количество коммуникаций на страницу</param>
 53        /// <param name="filter">Фильтр по которому будет производиться поиск BankName||Contragent.FullName||Contragent.
 54        /// <param name="sort">Поле по которому сортировать: id - id|desc, bankName,bankName|desc bik,bik|desc settlemen
 55        /// <returns>List of BankAccountResponseDTO</returns>
 56        [HttpGet("")]
 57        [SwaggerResponse(200, "Успешно", typeof(List<BankAccountResponseDTO>))]
 58        [SwaggerResponse(401, "Пользователь не авторизован", typeof(ErrorDTO))]
 59        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 60        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 61        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 62            + "," + Role.SupplierOperator + "," + Role.SupplierSpec)]
 63        public async Task<IActionResult> GetBankAccounts(int page = 1, int limit = 10, string filter = "", string sort =
 64        {
 65            filter = filter.NormalizeName();
 66            page = page < 1 ? 1 : page;
 67            limit = limit < 1 ? 10 : limit;
 68
 69            _logger.LogDebug($"Get list BankAccount: page {page}, limit {limit}, filter {filter}, sort {sort}");
 70
 71            _user = await _userService.GetUser(_authenticationService.UserId); //Получаем пользователя из токена
 72            Contragent contr = !User.IsInRole(Role.SystemAdmin) ? _user.Contragent : null;
 73
 74            var data = await _bankAccountService.GetBankAccounts(page - 1, limit, filter, contr?.Id, sort);
 75            var result = data.Select(x => new BankAccountResponseDTO
 76            {
 77                Id = x.Id,
 78                ContragentId = x.Contragent.Id,
 79                BankName = x.BankName,
 80                Bik = x.Bik,
 81                SettlementAccount = x.SettlementAccount,
 82                CorrespondentAccount = x.CorrespondentAccount
 83            }).ToList();
 84
 85            var totalCount = (await _bankAccountService.GetBankAccounts(1, null, null))?.Count();
 86            var totalFiltredCount = (await _bankAccountService.GetBankAccounts(0, null, filter, contr?.Id, sort))?.Count
 87
 88            var response = new BaseResponseDTO<BankAccountResponseDTO>(_routeUrl, page, limit, totalFiltredCount ?? 0, t
 89            {
 90                Data = result
 91            };
 92            return Ok(response);
 93        }
 94
 95        /// <summary>
 96        /// Получить одну запись банковского счета
 97        /// </summary>
 98        /// <remarks>author IPod</remarks>
 99        /// <param name="bankAccountId">id записи банковского счета</param>
 100        /// <returns>Single BankAccountResponseDTO</returns>
 101        [HttpGet("{bankAccountId}")]
 102        [SwaggerResponse(200, "Успешно", typeof(BankAccountResponseDTO))]
 103        [SwaggerResponse(401, "Пользователь не авторизован", typeof(ErrorDTO))]
 104        [SwaggerResponse(403, "Отказ в доступе", typeof(ErrorDTO))]
 105        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 106        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 107        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 108        public async Task<IActionResult> GetBankAccount(long bankAccountId)
 0109        {
 0110            _user = await _userService.GetUser(_authenticationService.UserId);
 0111            Contragent contr = !User.IsInRole(Role.SystemAdmin) ? _user.Contragent : null;
 112
 0113            var data = await _bankAccountService.GetBankAccount(bankAccountId, contr?.Id);
 0114            if (data == null)
 0115                return NotFound($"Лицевой счет с id {bankAccountId} не найден");
 0116            if (!User.IsInRole(Role.SystemAdmin) && data.Contragent.Id != contr?.Id)
 0117                throw new ForbidException("Нет прав");
 0118            var result = new BankAccountResponseDTO
 0119            {
 0120                Id = data.Id,
 0121                ContragentId = data.Contragent.Id,
 0122                BankName = data.BankName,
 0123                Bik = data.Bik,
 0124                SettlementAccount = data.SettlementAccount,
 0125                CorrespondentAccount = data.CorrespondentAccount
 0126            };
 127
 0128            _logger.LogDebug($"Get BankAccount by id {bankAccountId}");
 0129            return Ok(result);
 0130        }
 131
 132        /// <summary>
 133        /// Получить все записи банковских счетов одного контрагента
 134        /// </summary>
 135        /// <remarks>author IPod</remarks>
 136        /// <param name="contragentId">после добавления проверки Токеном, надо убрать этот параметр</param>
 137        /// <param name="page">Любое значение ниже нуля изменится на 1, Номер страницы для паганации</param>
 138        /// <param name="limit">Любое значение ниже нуля изменится на 10, Количество коммуникаций на страницу</param>
 139        /// <param name="filter">Фильтр по которому будет производиться поиск BankName||Contragent.FullName||Contragent.
 140        /// <param name="sort">Поле по которому сортировать: id - id|desc, bankName,bankName|desc bik,bik|desc settlemen
 141        /// <returns>List of BankAccountResponseDTO</returns>
 142        [HttpGet("Contragents/{contragentId}")]
 143        [SwaggerResponse(200, "Успешно", typeof(BankAccountResponseDTO))]
 144        [SwaggerResponse(401, "Пользователь не авторизован", typeof(ErrorDTO))]
 145        [SwaggerResponse(403, "Отказ в доступе", typeof(ErrorDTO))]
 146        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 147        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 148        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 149        public async Task<IActionResult> GetBankAccountsForContragent(long contragentId, int page = 1, int limit = 10, s
 150        {
 151            filter = filter.NormalizeName();
 152            page = page < 1 ? 1 : page;
 153            limit = limit < 1 ? 10 : limit;
 154
 155            _user = await _userService.GetUser(_authenticationService.UserId);
 156            if (!User.IsInRole(Role.SystemAdmin))
 157            {
 158                if (contragentId != _user.Contragent.Id)
 159                    throw new ForbidException("Нет прав");
 160            }
 161
 162            _logger.LogDebug($"Get list BankAccount:contragent {contragentId} page {page}, limit {limit}, filter {filter
 163            var data = await _bankAccountService.GetBankAccountsForContragent(contragentId, page - 1, limit, filter, sor
 164            var result = data.Select(x => new BankAccountResponseDTO
 165            {
 166                Id = x.Id,
 167                ContragentId = x.Contragent.Id,
 168                BankName = x.BankName,
 169                Bik = x.Bik,
 170                SettlementAccount = x.SettlementAccount,
 171                CorrespondentAccount = x.CorrespondentAccount
 172            }).ToList();
 173            return Ok(result);
 174        }
 175
 176        /// <summary>
 177        /// Создает банковский счет для контрагента
 178        /// </summary>
 179        /// <remarks>author Obo\IPod</remarks>
 180        /// <param name="id">id контрагента, для которого создается банковский счет</param>
 181        /// <param name="data">BankAccountRequestDTO {BankName, Bik, CorrespondentAccount, SettlementAccoun }</param>
 182        /// <returns> return BankAccountResponseDTO {BankName, Bik, ContragentId, CorrespondentAccount, SettlementAccoun
 183        [HttpPost("Contragents/{id}")]
 184        [SwaggerResponse(200, "Успешно", typeof(BankAccountResponseDTO))]
 185        [SwaggerResponse(400, "Не заполнены обязательные поля!", typeof(ErrorDTO))]
 186        [SwaggerResponse(403, "Пользователю запрещено редактировать счета других контрагентов", typeof(ErrorDTO))]
 187        [SwaggerResponse(404, "Контрагент с таким id не найден", typeof(ErrorDTO))]
 188        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 189        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 190        private async Task<IActionResult> CreateBankAccount(long id, [FromBody] BankAccountRequestDTO data)
 0191        {
 0192            if (!ModelState.IsValid)
 0193            {
 0194                return BadRequest("Не заполнены обязательные поля!");
 195            }
 0196            _user = await _userService.GetUser(_authenticationService.UserId);
 0197            if(!User.IsInRole(Role.SystemAdmin) && _user.Contragent.Id != id)
 0198            {
 0199                return ForbidResult("Нет прав");
 200            }
 201
 0202            var contr = User.IsInRole(Role.SystemAdmin) ? await _contragentService.GetContragent(id) : _user.Contragent;
 0203            if(contr == null)
 0204            {
 0205                return NotFoundResult("Контрагент не найден");
 206            }
 207
 0208            var bankAccount = new BankAccount
 0209            {
 0210                BankName = data.BankName,
 0211                Bik = data.Bik,
 0212                Contragent = contr,
 0213                CorrespondentAccount = data.CorrespondentAccount,
 0214                SettlementAccount = data.SettlementAccount
 0215            };
 0216            await _bankAccountService.CreateBankAccount(bankAccount);
 217
 0218            return Ok(ToBankAccountDtoMapper().Map<BankAccountResponseDTO>(bankAccount));
 0219        }
 220
 221        /// <summary>
 222        /// Обновляет банковский счет для контрагента
 223        /// </summary>
 224        /// <remarks>author Obo\IPod</remarks>
 225        /// <param name="bankAccountId"></param>
 226        /// <param name="data">BankAccountRequestDTO {BankName, Bik, CorrespondentAccount, SettlementAccoun }</param>
 227        /// <returns> return BankAccountResponseDTO {BankName, Bik, ContragentId, CorrespondentAccount, SettlementAccoun
 228        [HttpPut("{bankAccountId}")]
 229        [SwaggerResponse(200, "Успешно", typeof(BankAccountResponseDTO))]
 230        [SwaggerResponse(400, "Не заполнены обязательные поля!", typeof(ErrorDTO))]
 231        [SwaggerResponse(403, "Пользователю запрещено редактировать счета других контрагентов", typeof(ErrorDTO))]
 232        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 233        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 234        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 235        public async Task<IActionResult> UpdateBankAccount(long bankAccountId, [FromBody] BankAccountRequestDTO data)
 0236        {
 0237            if (!ModelState.IsValid)
 0238            {
 0239                return BadRequestResult("Не заполнены обязательные поля!");
 240            }
 0241            _user = await _userService.GetUser(_authenticationService.UserId);
 242
 0243            var account = await _bankAccountService.GetBankAccount(bankAccountId);
 0244            if (account == null)
 0245                return NotFoundResult("Счет не найден");
 246
 0247            if (!User.IsInRole(Role.SystemAdmin) && account.Contragent.Id != _user.Contragent.Id)
 0248                return ForbidResult("Not allowed to change bank account of different contragent");
 249
 0250            account.BankName = data.BankName;
 0251            account.Bik = data.Bik;
 0252            account.CorrespondentAccount = data.CorrespondentAccount;
 0253            account.SettlementAccount = data.SettlementAccount;
 0254            await _bankAccountService.UpdateBankAccount(account);
 255
 0256            return Ok(ToBankAccountDtoMapper().Map<BankAccountResponseDTO>(account));
 0257        }
 258
 259        /// <summary>
 260        /// Удаляет банковский счет контрагента
 261        /// </summary>
 262        /// <remarks>author Obo\IPod</remarks>
 263        /// <param name="bankAccountId">id записи банковского аккаунта</param>
 264        /// <returns> Status code 200</returns>
 265        [HttpDelete("{bankAccountId}")]
 266        [SwaggerResponse(200, "Успешно", typeof(EmptyResult))]
 267        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 268        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 269        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.SupplierOwne
 270        public async Task<IActionResult> DeleteBankAccount(long bankAccountId)
 0271        {
 0272            _user = await _userService.GetUser(_authenticationService.UserId);
 273
 0274            var account = await _bankAccountService.GetBankAccount(bankAccountId);
 275
 0276            if (account == null)
 0277                return NotFoundResult("Счет не найден");
 0278            else if (account.Contragent.Id != _user.Contragent.Id)
 0279                return ForbidResult("Not allowed to change bank account of different contragent");
 280
 0281            await _bankAccountService.DeleteBankAccount(bankAccountId);
 0282            return Ok();
 0283        }
 284
 285        private static IMapper ToBankAccountDtoMapper()
 0286        {
 0287            var config = new MapperConfiguration(cfg =>
 0288            {
 0289                cfg.CreateMap<BankAccount, BankAccountResponseDTO>()
 0290                    .ForMember(d => d.Bik, e => e.MapFrom(s => s.Bik));
 0291            });
 0292            IMapper mapper = config.CreateMapper();
 0293            return mapper;
 0294        }
 295    }
 296}