public async Task UpdatePartnerAsync([FromBody] PartnerUpdateRequest request)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.ProgramPartners);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                var existingPartner = await _partnerManagementClient.Partners.GetByIdAsync(request.Id);

                // filter data for current _requestContext.UserId
                if (existingPartner != null &&
                    existingPartner.CreatedBy != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var requestModel = _mapper.Map <PartnerUpdateModel>(request);

            PartnerUpdateResponse response;

            try
            {
                response = await _partnerManagementClient.Partners.UpdateAsync(requestModel);
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }

            ThrowIfError(response.ErrorCode, response.ErrorMessage);
        }
        public async Task <AdminModel> ResetPasswordAsync([FromBody] AdminResetPasswordModel model)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.AdminUsers);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (model.AdminId != _requestContext.UserId)
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var(error, admin) = await _adminsService.ResetPasswordAsync(model.AdminId);

            if (error == AdminResetPasswordErrorCodes.None)
            {
                await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, model.ToJson(), ActionType.ResetAdminPassword);

                return(_mapper.Map <AdminModel>(admin));
            }
            switch (error)
            {
            case AdminResetPasswordErrorCodes.AdminUserDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task <AdminModel> GetAdminByIdAsync([FromQuery][Required] Guid adminUserId)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.AdminUsers);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (adminUserId != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var(error, admin) = await _adminsService.GetAsync(adminUserId.ToString());

            switch (error)
            {
            case AdminServiceResponseError.None:
                return(_mapper.Map <AdminModel>(admin));

            case AdminServiceResponseError.AdminUserDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public async Task SetImage([FromQuery] SmartVoucherCampaignSetImageRequest model, [Required] IFormFile formFile)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.VoucherManager);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                var existingCampaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(model.CampaignId);

                // filter data for current _requestContext.UserId
                if (existingCampaign != null &&
                    existingCampaign.CreatedBy != _requestContext.UserId)
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var imageContent = _imageService.HandleFile(formFile, model.ContentId);

            var imageModel = _mapper.Map <SmartVoucherCampaignSetImageRequest, CampaignImageFileRequest>(model,
                                                                                                         opt => opt.AfterMap((src, dest) =>
            {
                dest.Type    = formFile.ContentType;
                dest.Name    = formFile.FileName;
                dest.Content = imageContent;
            }));

            SaveImageErrorCodes error;

            try
            {
                error = await _smartVouchersClient.CampaignsApi.SetImage(imageModel);
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }

            if (error != SaveImageErrorCodes.None)
            {
                throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(error.ToString()));
            }
            await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, model.ToJson(), ActionType.SetSmartVoucherCampaignImage);
        }
        public async Task <AdminModel> UpdateAdminAsync([FromBody] AdminUpdateModel model)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.AdminUsers);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (model.Id != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var(error, admin) = await _adminsService.UpdateAdminAsync(
                model.Id.ToString(),
                model.PhoneNumber,
                model.FirstName,
                model.LastName,
                model.Company,
                model.Department,
                model.JobTitle,
                model.IsActive);

            if (error == AdminServiceResponseError.None)
            {
                model.FirstName   = model.FirstName.SanitizeName();
                model.LastName    = model.LastName.SanitizeName();
                model.PhoneNumber = model.PhoneNumber.SanitizePhone();
                await _auditLogPublisher.PublishAuditLogAsync(_requestContext.UserId, model.ToJson(), ActionType.AdminUpdate);

                return(_mapper.Map <AdminModel>(admin));
            }

            switch (error)
            {
            case AdminServiceResponseError.AdminUserDoesNotExist:
                throw LykkeApiErrorException.BadRequest(ApiErrorCodes.Service.AdminNotFound);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        /* TODO: implement when will be 2 or more payment providers
         * /// <summary>
         * /// Update payment provider details
         * /// </summary>
         * [HttpDelete]
         * [ProducesResponseType((int)HttpStatusCode.NoContent)]
         * [ProducesResponseType((int)HttpStatusCode.BadRequest)]
         * public async Task DeletePaymentProviderDetailsAsync([FromQuery] Guid id)
         * {
         *  var error = await _customerProfileClient.PaymentProviderDetails.DeleteAsync(id);
         *
         *  if (error != PaymentProviderDetailsErrorCodes.None)
         *      throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(error.ToString()));
         * }
         */

        private async Task VerifyPermissionForPartnerAdmin(Guid partnerId)
        {
            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.ProgramPartners);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                var partners = await _partnerManagementClient.Partners.GetAsync(new PartnerListRequestModel
                {
                    CreatedBy   = Guid.Parse(_requestContext.UserId),
                    CurrentPage = 1,
                    PageSize    = Constants.MaxPageSize
                });;

                if (!partners.PartnersDetails.Any(_ => _.Id.Equals(partnerId)))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }
        }
        public async Task <PartnerDetailsResponse> GetPartnerByIdAsync([FromQuery] Guid id)
        {
            var response = await _partnerManagementClient.Partners.GetByIdAsync(id);

            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.ProgramPartners);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (response.CreatedBy != Guid.Parse(_requestContext.UserId))
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            return(_mapper.Map <PartnerDetailsResponse>(response));
        }
        public async Task <IActionResult> Cashout([FromBody] CreateCashoutRequest cmd, [FromQuery] Guid?id)
        {
            if (string.IsNullOrWhiteSpace(cmd.DestinationAddress) || string.IsNullOrWhiteSpace(cmd.AssetId) || cmd.Volume == 0m)
            {
                throw LykkeApiErrorException.BadRequest(LykkeApiErrorCodes.Service.InvalidInput);
            }

            var asset = await _assetsServiceWithCache.TryGetAssetAsync(cmd.AssetId);

            if (asset == null)
            {
                return(NotFound($"Asset '{cmd.AssetId}' not found."));
            }

            var balance = await _balancesClient.GetClientBalanceByAssetId(new ClientBalanceByAssetIdModel(cmd.AssetId, _requestContext.ClientId));

            var cashoutSettings = await _clientAccountClient.ClientSettings.GetCashOutBlockSettingsAsync(_requestContext.ClientId);

            var kycStatus = await _kycStatusService.GetKycStatusAsync(_requestContext.ClientId);

            if (_baseSettings.EnableTwoFactor)
            {
                try
                {
                    if ((await _confirmationCodesClient.Google2FaIsClientBlacklistedAsync(_requestContext.ClientId)).IsClientBlacklisted)
                    {
                        throw LykkeApiErrorException.Forbidden(LykkeApiErrorCodes.Service.SecondFactorCheckForbiden);
                    }
                }
                catch (ApiException e)
                {
                    if (e.StatusCode == HttpStatusCode.BadRequest)
                    {
                        throw LykkeApiErrorException.Forbidden(LykkeApiErrorCodes.Service.TwoFactorRequired);
                    }
                }
            }

            var operationId = id ?? Guid.NewGuid();

            var cashoutCommand = new CreateCashoutCommand
            {
                OperationId                 = operationId,
                DestinationAddress          = cmd.DestinationAddress,
                DestinationAddressExtension = cmd.DestinationAddressExtension,
                Volume = cmd.Volume,
                Asset  = new AssetCashoutModel
                {
                    Id              = asset.Id,
                    DisplayId       = asset.DisplayId,
                    MultiplierPower = asset.MultiplierPower,
                    AssetAddress    = asset.AssetAddress,
                    Accuracy        = asset.Accuracy,
                    BlockchainIntegrationLayerId = asset.BlockchainIntegrationLayerId,
                    Blockchain           = asset.Blockchain.ToString(),
                    Type                 = asset.Type?.ToString(),
                    IsTradable           = asset.IsTradable,
                    IsTrusted            = asset.IsTrusted,
                    KycNeeded            = asset.KycNeeded,
                    BlockchainWithdrawal = asset.BlockchainWithdrawal,
                    CashoutMinimalAmount = (decimal)asset.CashoutMinimalAmount,
                    LowVolumeAmount      = (decimal?)asset.LowVolumeAmount ?? 0,
                    LykkeEntityId        = asset.LykkeEntityId
                },
                Client = new ClientCashoutModel
                {
                    Id               = new Guid(_requestContext.ClientId),
                    Balance          = balance?.Balance ?? 0,
                    CashOutBlocked   = cashoutSettings.CashOutBlocked,
                    KycStatus        = kycStatus.ToString(),
                    ConfirmationType = "google"
                },
                GlobalSettings = new GlobalSettingsCashoutModel
                {
                    MaxConfirmationAttempts = _baseSettings.MaxTwoFactorConfirmationAttempts,
                    TwoFactorEnabled        = _baseSettings.EnableTwoFactor,
                    CashOutBlocked          = false, // TODO
                    FeeSettings             = new FeeSettingsCashoutModel
                    {
                        TargetClients = new Dictionary <string, string>
                        {
                            { "Cashout", _feeSettings.TargetClientId.Cashout }
                        }
                    }
                }
            };

            _cqrsEngine.SendCommand(cashoutCommand, "apiv2", OperationsBoundedContext.Name);

            return(Created(Url.Action("Get", new { operationId }), operationId));
        }
Esempio n. 9
0
        public async Task UpdateAsync([FromBody] SmartVoucherCampaignEditRequest model)
        {
            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.VoucherManager);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                var existingCampaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(model.Id);

                // filter data for current _requestContext.UserId
                if (existingCampaign != null &&
                    existingCampaign.CreatedBy != _requestContext.UserId)
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var campaign = _mapper.Map <VoucherCampaignEditModel>(model);

            var mobileContents = new List <VoucherCampaignContentEditModel>();

            foreach (var mobileContent in model.MobileContents)
            {
                Enum.TryParse <SmartVouchers.Client.Models.Enums.Localization>(mobileContent.MobileLanguage.ToString(), out var mobileLanguage);

                if (!string.IsNullOrEmpty(mobileContent.Title))
                {
                    mobileContents.Add(new VoucherCampaignContentEditModel
                    {
                        Id           = mobileContent.TitleId,
                        ContentType  = VoucherCampaignContentType.Name,
                        Localization = mobileLanguage,
                        Value        = mobileContent.Title
                    });
                }

                mobileContents.Add(new VoucherCampaignContentEditModel
                {
                    Id           = mobileContent.DescriptionId,
                    ContentType  = VoucherCampaignContentType.Description,
                    Localization = mobileLanguage,
                    Value        = string.IsNullOrEmpty(mobileContent.Description) ? null : mobileContent.Description
                });

                mobileContents.Add(new VoucherCampaignContentEditModel
                {
                    Id           = mobileContent.ImageId,
                    ContentType  = VoucherCampaignContentType.ImageUrl,
                    Localization = mobileLanguage,
                    Value        = mobileContent.ImageBlobUrl
                });
            }

            campaign.LocalizedContents = mobileContents;

            UpdateVoucherCampaignErrorCodes response;

            try
            {
                response = await _smartVouchersClient.CampaignsApi.UpdateAsync(campaign);
            }
            catch (ClientApiException exception)
            {
                throw new ValidationApiException(exception.ErrorResponse);
            }

            if (response != UpdateVoucherCampaignErrorCodes.None)
            {
                throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode(response.ToString()));
            }
        }
Esempio n. 10
0
        public async Task <SmartVoucherCampaignDetailsResponse> GetByIdAsync(Guid campaignId)
        {
            var campaign = await _smartVouchersClient.CampaignsApi.GetByIdAsync(campaignId);

            if (campaign == null)
            {
                throw LykkeApiErrorException.BadRequest(new LykkeApiErrorCode("SmartVoucherCampaignDoesNotExist",
                                                                              "Smart voucher campaign with this id does not exist"));
            }

            #region Filter

            var permissionLevel = await _requestContext.GetPermissionLevelAsync(PermissionType.VoucherManager);

            if (permissionLevel.HasValue && permissionLevel.Value == PermissionLevel.PartnerEdit)
            {
                // filter data for current _requestContext.UserId
                if (campaign.CreatedBy != _requestContext.UserId)
                {
                    throw LykkeApiErrorException.Forbidden(new LykkeApiErrorCode(nameof(HttpStatusCode.Forbidden)));
                }
            }

            #endregion

            var result = _mapper.Map <SmartVoucherCampaignDetailsResponse>(campaign);

            // dictionary by Localization
            var mobileContentsDictionary = new Dictionary <string, MobileContentResponse>();

            foreach (var content in campaign.LocalizedContents)
            {
                if (mobileContentsDictionary.TryGetValue(content.Localization.ToString(), out var existingMobileContent))
                {
                    FillMobileContent(existingMobileContent);
                }
                else
                {
                    Enum.TryParse <MobileLocalization>(content.Localization.ToString(), out var mobileLanguage);

                    var newMobileContent = new MobileContentResponse {
                        MobileLanguage = mobileLanguage
                    };

                    FillMobileContent(newMobileContent);

                    mobileContentsDictionary.TryAdd(content.Localization.ToString(), newMobileContent);
                }

                void FillMobileContent(MobileContentResponse mobileContent)
                {
                    switch (content.ContentType)
                    {
                    case VoucherCampaignContentType.Name:
                        mobileContent.Title   = content.Value;
                        mobileContent.TitleId = content.Id;
                        break;

                    case VoucherCampaignContentType.Description:
                        mobileContent.Description   = content.Value;
                        mobileContent.DescriptionId = content.Id;
                        break;

                    case VoucherCampaignContentType.ImageUrl:
                        mobileContent.ImageId      = content.Id;
                        mobileContent.ImageBlobUrl = content.Value;
                        mobileContent.Image        = new ImageResponse
                        {
                            Id            = content.Image?.Id,
                            RuleContentId = content.Id.ToString(),
                            ImageBlobUrl  = content.Image?.BlobUrl
                        };
                        break;
                    }
                }
            }

            result.MobileContents = mobileContentsDictionary.ToList().OrderBy(x => x.Key).Select(x => x.Value).ToList();

            return(result);
        }