public Task <object> ClaimInvitationLink(ClaimReferralLinkRequest request) { throw new NotImplementedException("Reserved for version 2"); //try //{ // return await _service.ClaimInvitationLinkAsync(request); //} //catch (Exception ex) //{ // await _log.WriteErrorAsync(nameof(ReferralLinksClient), nameof(ClaimInvitationLink), ex); // throw; //} }
public Task <object> ClaimGiftCoins(ClaimReferralLinkRequest request) { throw new NotImplementedException("Reserved for version 2"); //try //{ // return await _service.ClaimGiftCoinsAsync(request); //} //catch (Exception ex) //{ // await _log.WriteErrorAsync(nameof(ReferralLinksClient), nameof(GetReferralLinksStatisticsBySenderId), ex); // throw; //} }
private string ValidateClaimRefLinkAndRequest(IReferralLink refLink, ClaimReferralLinkRequest request, string refLinkId) { if (request.RecipientClientId == null) { return("RecipientClientId not found or not supplied"); } if (refLinkId == null && request.ReferalLinkUrl == null) { return("ReferalLinkId and ReferalLinkUrl not supplied. Please specify either of them."); } if (refLink == null) { return("RefLink not found by id or url."); } if (refLink.SenderClientId == request.RecipientClientId) { return("RecipientClientId can't be the same as SenderClientId. Client cant claim their own ref link."); } if (Math.Abs(refLink.Amount) < MinimalAmount && refLink.Type == ReferralLinkType.GiftCoins.ToString()) { return($"Requested amount for RefLink with id {refLink.Id} is 0 (not set). 0 amount gift links are not allowed."); } if (refLink.Type == ReferralLinkType.GiftCoins.ToString() && refLink.State != ReferralLinkState.SentToLykkeSharedWallet.ToString()) { return($"RefLink type {refLink.Type} with state {refLink.State} can not be claimed."); } if (refLink.Type == ReferralLinkType.Invitation.ToString() && refLink.State != ReferralLinkState.Created.ToString()) { return($"RefLink type {refLink.Type} with state {refLink.State} can not be claimed."); } if (refLink.ExpirationDate.HasValue && refLink.ExpirationDate.Value.CompareTo(DateTime.UtcNow) < 0) { return($"RefLink is expired at {refLink.ExpirationDate.Value} and can not be claimed."); } return(null); }
/// <summary> /// Claim invitation referral link. /// </summary> /// <param name='refLinkId'> /// </param> /// <param name='request'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <object> > ClaimInvitationLinkWithHttpMessagesAsync(string refLinkId, ClaimReferralLinkRequest request = default(ClaimReferralLinkRequest), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (refLinkId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "refLinkId"); } if (request != null) { request.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("refLinkId", refLinkId); tracingParameters.Add("request", request); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ClaimInvitationLink", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/referralLinks/invitation/{refLinkId}/claim").ToString(); _url = _url.Replace("{refLinkId}", System.Uri.EscapeDataString(refLinkId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (request != null) { _requestContent = SafeJsonConvert.SerializeObject(request, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400 && (int)_statusCode != 500) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <ClaimRefLinkResponse>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 400) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <ErrorResponseModel>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 500) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <ErrorResponseModel>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Claim invitation referral link. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='refLinkId'> /// </param> /// <param name='request'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <object> ClaimInvitationLinkAsync(this ILykkeReferralLinksService operations, string refLinkId, ClaimReferralLinkRequest request = default(ClaimReferralLinkRequest), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ClaimInvitationLinkWithHttpMessagesAsync(refLinkId, request, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Claim invitation referral link. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='refLinkId'> /// </param> /// <param name='request'> /// </param> public static object ClaimInvitationLink(this ILykkeReferralLinksService operations, string refLinkId, ClaimReferralLinkRequest request = default(ClaimReferralLinkRequest)) { return(operations.ClaimInvitationLinkAsync(refLinkId, request).GetAwaiter().GetResult()); }
public async Task <IActionResult> ClaimInvitationLink(string refLinkId, [FromBody] ClaimReferralLinkRequest request) { if (!request.IsNewClient) { return(await LogAndReturnBadRequest(request, ControllerContext, "Not a new client.")); } var refLink = await _referralLinksService.GetReferralLinkById(refLinkId ?? "") ?? await _referralLinksService.GetReferralLinkByUrl(request.ReferalLinkUrl ?? ""); var validationError = ValidateClaimRefLinkAndRequest(refLink, request, refLinkId); if (!String.IsNullOrEmpty(validationError)) { return(await LogAndReturnBadRequest(request, ControllerContext, validationError)); } var claims = (await _referralLinkClaimsService.GetRefLinkClaims(refLink.Id)).ToList(); var alreadyClaimedByThisRecipient = claims.Any(c => c.RecipientClientId == request.RecipientClientId); if (alreadyClaimedByThisRecipient) { return(await LogAndReturnBadRequest(request, ControllerContext, $"Link already claimed by client id {request.RecipientClientId}")); } bool shouldReceiveReward = await ShoulReceiveReward(claims, refLink); try { var newRefLinkClaimRecipient = await CreateNewRefLinkClaim(refLink, request.RecipientClientId, shouldReceiveReward, true); if (shouldReceiveReward) { var newRefLinkClaimSender = await CreateNewRefLinkClaim(refLink, refLink.SenderClientId, true, false); if (Math.Abs(refLink.Amount) < MinimalAmount) { await LogWarn(request, ControllerContext, $"Invitation link with id {refLink.Id} is claimed, but the link is set to reward amount 0. If this is intentional, please act accordingly - possibly rewarding the recipients manually. Records for the claim will be created in DB, but with empty transaction ID. Invitation links get created with 0 amount if the relevant setting in config is set to 0. "); return(Ok(new ClaimRefLinkResponse())); } var transactionRewardSender = await _exchangeService.TransferRewardCoins(refLink, false, refLink.SenderClientId, ControllerContext.GetControllerAndAction()); await SetRefLinkClaimTransactionId(transactionRewardSender, newRefLinkClaimSender); var transactionRewardRecipient = await _exchangeService.TransferRewardCoins(refLink, request.IsNewClient, request.RecipientClientId, ControllerContext.GetControllerAndAction()); await SetRefLinkClaimTransactionId(transactionRewardRecipient, newRefLinkClaimRecipient); if (transactionRewardSender.IsOk() && transactionRewardRecipient.IsOk()) { return(Ok ( new ClaimRefLinkResponse { TransactionRewardSender = transactionRewardSender.TransactionId, TransactionRewardRecipient = transactionRewardRecipient.TransactionId } )); } return(await LogAndReturnInternalServerError(request, ControllerContext, $"TransactionRewardRecipientError: Code: {transactionRewardRecipient.Code}, {transactionRewardRecipient.Message}; TransactionRewardSenderError: Code: {transactionRewardSender.Code}, {transactionRewardSender.Message}")); } return(Ok(new ClaimRefLinkResponse())); } catch (Exception ex) { return(await LogAndReturnInternalServerError(request, ControllerContext, $"{ex.ToJson()}.")); } }
//[HttpPut("giftCoinLinks/{refLinkId}/claim")] - reserved for version 2 //[SwaggerOperation("ClaimGiftCoins")] //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.BadRequest)] //[ProducesResponseType(typeof(ErrorResponseModel), (int)HttpStatusCode.NotFound)] //[ProducesResponseType(typeof(ClaimRefLinkResponse), (int)HttpStatusCode.OK)] private async Task <IActionResult> ClaimGiftCoins([FromBody] ClaimReferralLinkRequest request, string refLinkId) { var refLink = await _referralLinksService.GetReferralLinkById(refLinkId ?? ""); var validationError = ValidateClaimRefLinkAndRequest(refLink, request, refLinkId); if (!String.IsNullOrEmpty(validationError)) { return(await LogAndReturnBadRequest(request, ControllerContext, validationError)); } var asset = (await _assets.GetDictionaryAsync()).Values.FirstOrDefault(v => v.Id == refLink.Asset); if (asset == null) { return(await LogAndReturnBadRequest(request, ControllerContext, $"Asset with id {refLink.Asset} for Referral link {refLink.Id} not found. Check transfer's history.")); } if (await _srvKycForAsset.IsKycNeeded(request.RecipientClientId, asset.Id)) { return(await LogAndReturnBadRequest(request, ControllerContext, $"KYC needed for recipient client id {request.RecipientClientId} before claiming asset {refLink.Asset}")); } var newRefLinkClaimRecipient = await CreateNewRefLinkClaim(refLink, request.RecipientClientId, true, request.IsNewClient); var transactionRewardRecipient = await _exchangeService.TransferRewardCoins(refLink, request.IsNewClient, request.RecipientClientId, ControllerContext.GetControllerAndAction()); try { if (transactionRewardRecipient.IsOk()) { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await SetRefLinkClaimTransactionId(transactionRewardRecipient, newRefLinkClaimRecipient); await UpdateRefLinkState(refLink, ReferralLinkState.Claimed); scope.Complete(); } return(Ok(new ClaimRefLinkResponse { TransactionRewardRecipient = transactionRewardRecipient.TransactionId, SenderOffchainTransferId = refLink.SenderOffchainTransferId })); } return(await LogAndReturnNotFound(request, ControllerContext, $"TransactionRewardRecipientError: Code: {transactionRewardRecipient.Code}, Message: {transactionRewardRecipient.Message}")); } catch (TransactionAbortedException ex) { await LogError(new { Request = request, RefLink = refLink ?? new ReferralLink() }, ControllerContext, ex); return(NotFound(ex.Message)); } catch (ApplicationException ex) { await LogError(new { Request = request, RefLink = refLink ?? new ReferralLink() }, ControllerContext, ex); return(NotFound(ex.Message)); } catch (Exception ex) { await LogError(new { Request = request, RefLink = refLink ?? new ReferralLink() }, ControllerContext, ex); return(NotFound(ex.Message)); } }