/// <summary> /// Executes the get cards invocation. /// </summary> public void Execute() { // get userid if its there Guid userId = Context[Key.GlobalUserId] == null ? Guid.Empty : (Guid)Context[Key.GlobalUserId]; if (userId == Guid.Empty) { // no user specified so get all active cards ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; resultSummary.SetResultCode(GetAllActiveCards()); } else { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); User user = sharedUserLogic.RetrieveUser(); Context[Key.User] = user; ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; if (user != null) { resultSummary.SetResultCode(GetCards()); } else { resultSummary.SetResultCode(ResultCode.UnregisteredUser); } } }
/// <summary> /// create request file /// </summary> /// <returns> /// Async task wrapper /// </returns> private async Task <string> CreateNewRequestFileIfNeededAsync() { ICollection <string> recordNames = DetailRecordsBloblClient.RetrieveFilesToProcess(); Collection <string> records = new Collection <string>(); string fileToUpload = null; if (recordNames != null) { foreach (string recordName in recordNames) { MemoryStream memStream = new MemoryStream(); memStream.Position = 0; await DetailRecordsBloblClient.DownloadAsync(memStream, recordName).ConfigureAwait(false);; memStream.Position = 0; using (StreamReader streamReader = new StreamReader(memStream)) { string record = streamReader.ReadToEnd(); records.Add(record); } await DetailRecordsBloblClient.MarkAsProcessedAsync(recordName).ConfigureAwait(false);; } } if (records.Count > 0) { Context[Key.SequenceName] = "AmexOfferRegistrationSequence"; SharedSequenceLogic sequenceLogic = new SharedSequenceLogic(Context, CommerceOperationsFactory.SequenceOperations(Context)); int sequenceNumber = sequenceLogic.RetrieveNextValueInSequence(); fileToUpload = OfferRegistrationFileBuilder.Build(records, sequenceNumber, DateTime.UtcNow); } return(fileToUpload); }
/// <summary> /// Executes the get redemption history invocation. /// </summary> public void Execute() { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); User user = sharedUserLogic.RetrieveUser(); Context[Key.User] = user; ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; if (user != null) { RewardPrograms rewardProgram = (RewardPrograms)Context[Key.RewardProgramType]; if ((rewardProgram & RewardPrograms.CardLinkOffers) == RewardPrograms.CardLinkOffers) { resultSummary.SetResultCode(GetRedemptionHistory()); } else if ((rewardProgram & RewardPrograms.EarnBurn) == RewardPrograms.EarnBurn) { resultSummary.SetResultCode(GetEarnBurnHistory()); } } else { resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser); } }
/// <summary> /// Initializes a new instance of the FirstDataExtractProcessor class. /// </summary> /// <param name="enableRedemptionRewards"> /// Specifies whether redemption rewards should be enabled. /// </param> public FirstDataExtractProcessor(bool enableRedemptionRewards) { Context = new CommerceContext(string.Empty, CommerceWorkerConfig.Instance); RedeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); RewardOperations = CommerceOperationsFactory.RewardOperations(Context); EnableRedemptionRewards = enableRedemptionRewards; }
/// <summary> /// Decrease sequence number, in case file submission failed /// </summary> internal void DecrementSequence() { Context[Key.SequenceName] = "AmexOfferRegistrationSequence"; SharedSequenceLogic sequenceLogic = new SharedSequenceLogic(Context, CommerceOperationsFactory.SequenceOperations(Context)); sequenceLogic.DecrementSequence(); }
/// <summary> /// Executes job tear down tasks. /// For the current job. once all autolinking taks are successfully done, we do the following: /// 1. Retrieve the deal by id /// 2. Update the deal stauts to : AutoLinkingComplete /// 3. Updat the deal /// 4. Schedule the job to which will tell Deal Server that deal is active /// </summary> /// <param name="executionResult"> /// The result of job startup tasks. /// </param> /// <param name="jobResult"> /// The result of job. /// </param> /// <returns> /// The result of the execution of the tear down tasks. /// </returns> public OrchestratedExecutionResult TearDown(OrchestratedExecutionResult executionResult) { Log.Information("AutoLinking Job Complete for Deal :{0}", DealId); Log.Information("Job Result :{0}", executionResult); if (executionResult == OrchestratedExecutionResult.Success) { CommerceContext context = new CommerceContext("Claim Discount For Existing Cards Job Context", CommerceWorkerConfig.Instance); // get the deal context[Key.GlobalDealId] = DealId; SharedDealLogic sharedDealLogic = new SharedDealLogic(context, CommerceOperationsFactory.DealOperations(context)); Deal deal = sharedDealLogic.RetrieveDeal(); //now upate deal status to mark autolinking complete context[Key.InitialDeal] = new Deal(deal); context[Key.Deal] = deal; deal.DealStatusId = DealStatus.AutoLinkingComplete; context[Key.PreviouslyRegistered] = true; sharedDealLogic.RegisterDeal(); //TODO:schedule the job to tell DS that deal should be activated, but now do it right here context[Key.GlobalDealId] = DealId; deal = sharedDealLogic.RetrieveDeal(); context[Key.InitialDeal] = new Deal(deal); context[Key.Deal] = deal; deal.DealStatusId = DealStatus.Activated; context[Key.PreviouslyRegistered] = true; sharedDealLogic.RegisterDeal(); } return(OrchestratedExecutionResult.Success); }
public RewardNetworkReportProcessor(CommerceContext commerceContext) { Context = commerceContext; RedeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); FtpUserName = CloudConfigurationManager.GetSetting(RewardsNetworkConstants.FtpUserName); FtpPassword = CloudConfigurationManager.GetSetting(RewardsNetworkConstants.FtpPassword); FtpUri = CloudConfigurationManager.GetSetting(RewardsNetworkConstants.FtpAddress); FtpFolder = CloudConfigurationManager.GetSetting(RewardsNetworkConstants.FtpTransactionReportDirectory); }
/// <summary> /// Initializes a new instance of the TransactionLogFileProcessor class. /// </summary> /// <param name="enableRedemptionRewards"> /// Specifies whether redemption rewards should be enabled. /// </param> public TransactionLogFileProcessor(bool enableRedemptionRewards) { Context = new CommerceContext(string.Empty, CommerceWorkerConfig.Instance); RedeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); RewardOperations = CommerceOperationsFactory.RewardOperations(Context); EnableRedemptionRewards = enableRedemptionRewards; Context[Key.Partner] = Partner.Amex; TransactionIdSet = new HashSet <string>(); }
/// <summary> /// Initializes a new instance of the GetUsersReferralsExecutor class. /// </summary> /// <param name="context"> /// The context describing the referral type to register. /// </param> /// <exception cref="ArgumentNullException"> /// Parameter context cannot be null. /// </exception> public GetUsersReferralsExecutor(CommerceContext context) { if (context == null) { throw new ArgumentNullException("context", "Parameter context cannot be null."); } Context = context; ReferralOperations = CommerceOperationsFactory.ReferralOperations(Context); }
/// <summary> /// Applies the Earn reward according to RewardPayoutRecord parameters. /// </summary> /// <returns></returns> public OrchestratedExecutionResult Apply() { OrchestratedExecutionResult result = OrchestratedExecutionResult.NonTerminalError; CommerceContext context = new CommerceContext("Updating reward status", CommerceWorkerConfig.Instance); context[Key.RewardPayoutId] = RewardPayoutRecord.RewardPayoutId; context[Key.RewardPayoutStatus] = RewardPayoutStatus.NoEligibleUser; string actionDescription = String.Empty; if (RewardPayoutRecord.PayeeType == PayeeType.User) { if (RewardPayoutRecord.PayeeId != Guid.Empty) { if (RewardPayoutRecord.Rescinded == false) { result = OrchestratedExecutionResult.Success; context[Key.RewardPayoutStatus] = RewardPayoutStatus.Paid; actionDescription = "was paid"; } else { context[Key.RewardPayoutStatus] = RewardPayoutStatus.Rescinded; Log.Information("A rescinded reward cannot be paid out."); actionDescription = "could not be paid because the reward has been rescinded"; } } else { Log.Warning("Payee ID cannot be Guid.Empty."); actionDescription = "could not be paid because no eligible user could be found"; } } else { Log.Warning("Earn Rewards cannot be applied to payees of type {0}.", RewardPayoutRecord.PayeeType); actionDescription = String.Format("could not be paid because payees of type {0} cannot receive Earn Rewards", RewardPayoutRecord.PayeeType); } Log.Verbose("Updating reward payout record status to indicate the reward {0}.", actionDescription); IRewardOperations rewardOperations = CommerceOperationsFactory.RewardOperations(context); ResultCode resultCode = rewardOperations.UpdateRewardPayoutStatus(); if (resultCode != ResultCode.Success && resultCode != ResultCode.PayoutStatusTooAdvanced) { result = OrchestratedExecutionResult.NonTerminalError; Log.Warning("{0} call unsuccessfully processed.\r\n\r\nResultCode: {1}\r\n\r\nExplanation: {2}", (int)resultCode, context.ApiCallDescription, resultCode, ResultCodeExplanation.Get(resultCode)); } return(result); }
/// <summary> /// Adds a redemption reward for the transaction in the context. /// </summary> internal void AddRedemptionRewards() { RedeemedDealInfo redeemedDealInfo = (RedeemedDealInfo)Context[Key.RedeemedDealInfo]; if (Context.Config.EnableRedemptionRewards == true && (ReimbursementTender)redeemedDealInfo.ReimbursementTenderId == ReimbursementTender.MicrosoftEarn) { IRewardOperations rewardOperations = CommerceOperationsFactory.RewardOperations(Context); Context[Key.RewardId] = Context.Config.FirstEarnRewardId; Context[Key.FirstEarnRewardAmount] = Context.Config.FirstEarnRewardAmount; Context[Key.FirstEarnRewardExplanation] = Context.Config.FirstEarnRewardExplanation; ConcurrentDictionary <string, string> payload = new ConcurrentDictionary <string, string>(); IScheduler scheduler = PartnerFactory.Scheduler(Context.Config.SchedulerQueueName, Context.Config.SchedulerTableName, Context.Config); if (rewardOperations.AddRedemptionReward() == ResultCode.Success) { // Add a job to potentially reward user for their first Earn. payload[Key.RewardPayoutId.ToString()] = ((Guid)Context[Key.RewardPayoutId]).ToString(); payload[Key.PartnerCardId.ToString()] = (string)Context[Key.PartnerCardId]; payload[Key.PartnerRedeemedDealId.ToString()] = redeemedDealInfo.PartnerRedeemedDealId; payload[Key.RewardId.ToString()] = Context.Config.FirstEarnRewardId.ToString(); ScheduledJobDetails scheduledJobDetails = new ScheduledJobDetails { JobId = Guid.NewGuid(), JobType = ScheduledJobType.ApplyRedemptionReward, JobDescription = redeemedDealInfo.GlobalUserId.ToString(), Orchestrated = true, Payload = payload }; scheduler.ScheduleJobAsync(scheduledJobDetails).Wait(); } // Add a job to potentially reward the person who referred this user for this user's first Earn. Context[Key.RedeemedDealId] = ((RedeemedDeal)Context[Key.RedeemedDeal]).Id; Guid globalUserId = ((RedeemedDealInfo)Context[Key.RedeemedDealInfo]).GlobalUserId; Context[Key.GlobalUserId] = globalUserId; string userId = globalUserId.ToString(); if (rewardOperations.AddReferredRedemptionReward() == ResultCode.Success) { payload[Key.GlobalUserId.ToString()] = userId; payload[Key.ReferralEvent.ToString()] = ReferralEvent.Signup.ToString(); ScheduledJobDetails scheduledJobDetails = new ScheduledJobDetails { JobId = Guid.NewGuid(), JobType = ScheduledJobType.ApplyReferralReward, JobDescription = userId, Orchestrated = true, StartTime = DateTime.UtcNow, Payload = payload }; scheduler.ScheduleJobAsync(scheduledJobDetails).Wait(); } } }
/// <summary> /// Updates the data store to reflect the reversal of the redeemed deal. /// </summary> /// <returns> /// The ResultCode corresponding to the result of the operation. /// </returns> public ResultCode ReverseRedeemedDeal() { ResultCode result; Context.Log.Verbose("Attempting to update the data store to reflect the reversal of the redeemed deal."); IRedeemedDealOperations redeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); result = redeemedDealOperations.ReverseRedeemedDeal(); Context.Log.Verbose("ResultCode after reversing the redeemed deal in the data store: {0}", result); return(result); }
/// <summary> /// Enroll new user to Visa /// </summary> /// <returns></returns> private async Task <ResultCode> CreateEnrollment(string userKey) { ResultCode result = ResultCode.None; var newCardNumber = ((NewCardInfo)Context[Key.NewCardInfo]).Number; var lastFourOfNewCard = newCardNumber.Substring(12); // Build a card register request object. var request = VisaRtmDataManager.GetCreateEnrollmentRequest( community: VisaConstants.CommunityName, userkey: userKey, cardnumbers: new List <string> { newCardNumber } ); LogRequest("CreateEnrollment", request, newCardNumber, lastFourOfNewCard); // Invoke the partner to add the card. result = await PartnerUtilities.InvokePartner(Context, async() => { var response = await VisaInvoker.CreateEnrollment(request).ConfigureAwait(false); LogRequestResponse("CreateEnrollment", request, response, response.Success, newCardNumber, lastFourOfNewCard); result = ResultCode.UnknownError; if (response.Success) { result = ResultCode.Created; } else if (response.HasError()) { result = visaErrorUtility.GetResultCode(response, null); } if (result == ResultCode.Created) { PartnerCardInfo partnerCardInfo = GetVisaCardInfo((Card)Context[Key.Card]); partnerCardInfo.PartnerCardId = response.EnrollmentRecord.CardDetails[0].CardId.ToString(); partnerCardInfo.PartnerCardSuffix = "00"; var partnerUserId = response.EnrollmentRecord.UserProfileId; User user = (User)Context[Key.User]; user.AddOrUpdatePartnerUserId(Partner.Visa, partnerUserId.ToString(), true); //add partner user information to the database var userOperations = CommerceOperationsFactory.UserOperations(Context); userOperations.AddOrUpdateUser(); } return(result); }, null, Partner.None, true).ConfigureAwait(false); return(result); }
/// <summary> /// Updates the data store to reflect the reversal of the redeemed deal. /// </summary> /// <returns> /// The ResultCode corresponding to the result of the operation. /// </returns> public ResultCode ProcessRedemptionTimeout() { ResultCode result; Context.Log.Verbose("Attempting to update the data store to reflect the reversal of the timed out redemption."); IRedeemedDealOperations redeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); result = redeemedDealOperations.ProcessRedemptionTimeout(); Context.Log.Verbose("ResultCode after reversing the timed out redemption in the data store: {0}", result); return(result); }
/// <summary> /// Adds the redeemed deal to the data store and logs accordingly. /// </summary> /// <returns> /// The ResultCode corresponding to the result of the operation. /// </returns> private ResultCode AddRedeemedDeal() { ResultCode result = ResultCode.Success; // Add the redemption event info to the data store. Context.Log.Verbose("Attempting to add the redeemed deal to the data store."); IRedeemedDealOperations redeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); result = redeemedDealOperations.AddRedeemedDeal(); Context.Log.Verbose("ResultCode after adding the redeemed deal to the data store: {0}", result); return(result); }
/// <summary> /// Executes the distribute MSSV API invocation. /// </summary> public void Execute() { ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; // Make sure the user exists. SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); if (sharedUserLogic.RetrieveUser() != null) { // Validate the distribution amount. decimal distributionAmount = (decimal)Context[Key.DistributionAmount]; if (distributionAmount >= 0 && distributionAmount % 10 == 0) { // Validate the voucher expiration date. DateTime voucherExpiration = (DateTime)Context[Key.VoucherExpirationUtc]; DateTime utcNow = DateTime.UtcNow; if (voucherExpiration > utcNow && voucherExpiration <= utcNow + TimeSpan.FromDays(366)) { // HTML encode user-submitted text to prevent script injection and then truncate to maximum length. (SQL injection is prevented through use of a // paramterized stored procedure.) string notes = Context[Key.Notes] as string; if (String.IsNullOrWhiteSpace(notes) == false) { notes = HttpUtility.HtmlEncode(notes); if (notes.Length > MaxNotesLength) { notes = notes.Substring(0, MaxNotesLength); } } // Submit the distribution request to the database. ResultCode result = CommerceOperationsFactory.RedeemedDealOperations(Context).DistributeMssv(); DistributeMssvResponse response = (DistributeMssvResponse)Context[Key.Response]; response.RemainingFunds = (decimal)Context[Key.RemainingFunds]; resultSummary.SetResultCode(result); } else { resultSummary.SetResultCode(ResultCode.InvalidExpirationDate); } } else { resultSummary.SetResultCode(ResultCode.InvalidDistributionAmount); } } else { resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser); } }
/// <summary> /// Executes processing of the request. /// </summary> public ResultCode Execute() { const string statusFail = "0"; var request = (EndPointMessageRequest)Context[Key.Request]; var messageElementCollectionDictionary = request.MessageElementsCollection.ToDictionary(c => c.Key, c => c.Value, StringComparer.OrdinalIgnoreCase); var transactionId = messageElementCollectionDictionary[VisaEPMConstants.TransactionTransactionID]; var status = messageElementCollectionDictionary[VisaEPMConstants.FulfillmentStatus]; var creditStatus = CreditStatus.CreditGranted; if (status == statusFail) { creditStatus = CreditStatus.RejectedByPartner; if (messageElementCollectionDictionary.ContainsKey(VisaEPMConstants.FulfillmentStatusMessage)) { var errorMessage = messageElementCollectionDictionary[VisaEPMConstants.FulfillmentStatusMessage]; if (errorMessage.IndexOf(ErrorStatementCreditAlreadyIssuedForTransaction, StringComparison.OrdinalIgnoreCase) >= 0) { creditStatus = CreditStatus.CreditGranted; Context.Log.Verbose("Received statementCredit EPM message from Visa for partnerRedeemedDealScopeId={0} informing that credit for this transaction is already issued. Setting credit status to {1}.", transactionId, creditStatus); } else { Context.Log.Verbose("StatementCredit for Visa for partnerRedeemedDealScopeId={0} failed with error {1}", transactionId, errorMessage); } } } DateTime processedDateTime = DateTime.UtcNow; if (messageElementCollectionDictionary.ContainsKey(VisaEPMConstants.FulfillmentProcessedDateTime)) { var processedDateTimeString = messageElementCollectionDictionary[VisaEPMConstants.FulfillmentProcessedDateTime]; // UTC Time: 2014-08-19T23:17:03.000Z processedDateTime = DateTime.Parse(processedDateTimeString); processedDateTime = DateTime.SpecifyKind(processedDateTime, DateTimeKind.Utc); } Context[Key.CreditStatus] = creditStatus; Context[Key.Transaction] = transactionId; Context[Key.TransactionCreditApprovedDate] = processedDateTime; Context.Log.Verbose("Updating redeemed deal having partnerRedeemedDealScopeId={0} to credit status {1}.", transactionId, creditStatus); var redeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); redeemedDealOperations.UpdateRedeemedDealsByVisa(); Context.Log.Verbose("Updated redeemed deal having partnerRedeemedDealScopeId={0} to credit status {1}.", transactionId, creditStatus); return(ResultCode.Success); }
/// <summary> /// Executes the add referral type API invocation. /// </summary> public virtual void Execute() { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; if (sharedUserLogic.RetrieveUser() != null) { resultSummary.SetResultCode(CoreExecute()); } else { resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser); } }
/// <summary> /// Executes the distribute MSSV API invocation. /// </summary> public void Execute() { ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; // Make sure the user exists. SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); if (sharedUserLogic.RetrieveUser() != null) { ResultCode result = CommerceOperationsFactory.RedeemedDealOperations(Context).MssVoucherDistributionHistory(); MssVoucherDistributionHistory history = (MssVoucherDistributionHistory)Context[Key.MssVoucherDistributionHistory]; GetMssVoucherDistributionHistoryResponse response = (GetMssVoucherDistributionHistoryResponse)Context[Key.Response]; response.AmountRemaining = (decimal)history.AmountRemaining / 100; List <DistributionHistoryDataContract> distributionHistoryList = new List <DistributionHistoryDataContract>(); response.DistributionHistory = distributionHistoryList; foreach (DistributionHistory distributionHistoryItem in history.DistributionHistory) { DistributionHistoryDataContract distributionHistoryItemDataContract = new DistributionHistoryDataContract { DistributionDate = distributionHistoryItem.DistributionDate, Amount = (decimal)distributionHistoryItem.Amount / 100, Currency = distributionHistoryItem.Currency, ExpirationDate = distributionHistoryItem.ExpirationDate }; distributionHistoryList.Add(distributionHistoryItemDataContract); } List <TransactionHistoryDataContract> transactionHistoryList = new List <TransactionHistoryDataContract>(); response.TransactionHistory = transactionHistoryList; foreach (TransactionHistory transactionHistoryItem in history.TransactionHistory) { TransactionHistoryDataContract transactionHistoryItemDataContract = new TransactionHistoryDataContract { Business = transactionHistoryItem.Business, CreditStatus = transactionHistoryItem.CreditStatus.ToString(), PurchaseDate = transactionHistoryItem.PurchaseDate, DiscountAmount = (decimal)transactionHistoryItem.DiscountAmount / 100 }; transactionHistoryList.Add(transactionHistoryItemDataContract); } resultSummary.SetResultCode(result); } else { resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser); } }
/// <summary> /// Updates analytics with information about the transaction in the context. /// </summary> private void UpdateAnalytics() { RedeemedDealInfo redeemedDealInfo = (RedeemedDealInfo)Context[Key.RedeemedDealInfo]; SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); Context[Key.GlobalUserId] = redeemedDealInfo.GlobalUserId; User user = sharedUserLogic.RetrieveUser(); RedeemedDeal redeemedDeal = (RedeemedDeal)Context[Key.RedeemedDeal]; Analytics.AddRedemptionEvent(redeemedDealInfo.GlobalUserId, redeemedDeal.AnalyticsEventId, user.AnalyticsEventId, redeemedDealInfo.ParentDealId, redeemedDealInfo.Currency, redeemedDeal.AuthorizationAmount, redeemedDealInfo.DiscountAmount, redeemedDealInfo.GlobalId, (string)Context[Key.PartnerMerchantId], CommerceWorkerConfig.Instance); }
/// <summary> /// Executes the get user's referrals API invocation. /// </summary> public void Execute() { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; if (sharedUserLogic.RetrieveUser() != null) { Context[Key.ReferrerId] = Context[Key.GlobalUserId]; Context[Key.ReferrerType] = ReferrerType.User; resultSummary.SetResultCode(GetUsersReferrals()); } else { resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser); } }
/// <summary> /// Executes the Remove card invocation. /// </summary> public async Task Execute() { try { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); SharedCardLogic sharedCardLogic = new SharedCardLogic(Context, CommerceOperationsFactory.CardOperations(Context)); RemoveCardConcluder removeCardConcluder = new RemoveCardConcluder(Context); User user = sharedUserLogic.RetrieveUser(); Context[Key.User] = user; if (user != null) { Card card = sharedCardLogic.RetrieveCard(); Context[Key.Card] = card; if (card != null) { if (card.GlobalUserId == user.GlobalId) { Context.Log.Verbose("Attempting to remove the card from all current partners."); RemoveCardInvoker removeCardInvoker = new RemoveCardInvoker(Context); await removeCardInvoker.Invoke(); } else { removeCardConcluder.Conclude(ResultCode.CardDoesNotBelongToUser); } } else { removeCardConcluder.Conclude(ResultCode.UnregisteredCard); } } else { removeCardConcluder.Conclude(ResultCode.UnexpectedUnregisteredUser); } } catch (Exception ex) { ((ResultSummary)Context[Key.ResultSummary]).SetResultCode(ResultCode.UnknownError); RestResponder.BuildAsynchronousResponse(Context, ex); } }
/// <summary> /// Executes the get claimed deals invocation. /// </summary> public void Execute() { SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); User user = sharedUserLogic.RetrieveUser(); Context[Key.User] = user; ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary]; if (user != null) { resultSummary.SetResultCode(GetClaimedDeals()); } else { resultSummary.SetResultCode(ResultCode.UnregisteredUser); } }
/// <summary> /// Build the statement credit file /// </summary> /// <param name="result"> /// Collection of records to build credit for /// </param> /// <returns> /// Instance of StatmentCreditFile <see cref="StatementCreditFile"/> /// </returns> internal StatementCreditFile BuildCreditFile(Collection <OutstandingRedeemedDealInfo> result) { StatementCreditFile file = null; if (result.Count > 0) { Context[Key.SequenceName] = "AmexStatementCreditSequence"; SharedSequenceLogic sequenceLogic = new SharedSequenceLogic(Context, CommerceOperationsFactory.SequenceOperations(Context)); int sequenceNumber = sequenceLogic.RetrieveNextValueInSequence(); file = new StatementCreditFile() { Header = new StatementCreditHeader() { Date = DateTime.UtcNow, SequenceNumber = sequenceNumber } }; int totalAmount = 0; foreach (OutstandingRedeemedDealInfo outstandingRedeemedDealInfo in result) { totalAmount += outstandingRedeemedDealInfo.DiscountAmount; StatementCreditDetail detail = new StatementCreditDetail() { CampaignName = outstandingRedeemedDealInfo.MerchantName, CardToken = outstandingRedeemedDealInfo.Token, DiscountAmount = (decimal)outstandingRedeemedDealInfo.DiscountAmount / 100, OfferId = outstandingRedeemedDealInfo.OfferId, StatementDescriptor = StatmentDescriptor(outstandingRedeemedDealInfo.MerchantName), TransactionId = outstandingRedeemedDealInfo.ReferenceNumber.ToString(CultureInfo.InvariantCulture) }; file.StatementCreditRecords.Add(detail); } file.Trailer = new StatementCreditTrailer() { TrailerAmount = (decimal)totalAmount / 100, TrailerCount = file.StatementCreditRecords.Count }; } return(file); }
/// <summary> /// Validates the user ID in the context. /// </summary> /// <param name="crud"> /// The CRUD operation for which a token is being created. /// </param> /// <returns> /// The ResultCode corresponding to the result of the operation. /// </returns> /// <remarks> /// Authenticated user is automatically created within the system if necessary when validating the user ID in the /// context while obtaining a token for Create operations. /// </remarks> private ResultCode ValidateUserId(Crud crud) { ResultCode result = ResultCode.Success; // Attempt to retrieve the user. SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context)); User user = sharedUserLogic.RetrieveUser(); // If the user is null and the CRUD operation is Create, implicitly create the user. if (user == null) { if (crud == Crud.Create) { if (Context.ContainsKey(Key.CorrelationId) == true) { Guid userId = (Guid)Context[Key.GlobalUserId]; user = new User(userId, Guid.NewGuid()); Context[Key.User] = user; sharedUserLogic.AddUser(); // Update analytics. Analytics.AddRegisterUserEvent(userId, user.AnalyticsEventId, (Guid)Context[Key.CorrelationId], Context[Key.ReferrerId] as string); // Add referral, if any. SharedReferralLogic sharedReferralLogic = new SharedReferralLogic(Context, CommerceOperationsFactory.ReferralOperations(Context)); sharedReferralLogic.AddReferral((string)Context[Key.ReferredUserId]); } else { Context.Log.Warning("No correlation ID could be found in the context."); result = ResultCode.ParameterCannotBeNull; } } else { result = ResultCode.UnexpectedUnregisteredUser; } } return(result); }
/// <summary> /// Executes the task. /// </summary> /// <returns> /// The result of the execution of the task. /// </returns> public OrchestratedExecutionResult Execute() { OrchestratedExecutionResult result = OrchestratedExecutionResult.NonTerminalError; switch (RewardPayoutRecord.RewardType) { case RewardType.Undefined: case RewardType.StatementCredit: Log.Verbose("Updating reward payout record status to indicate the reward is pending."); CommerceContext context = new CommerceContext("Updating reward status", CommerceWorkerConfig.Instance); context[Key.RewardPayoutId] = RewardPayoutRecord.RewardPayoutId; context[Key.RewardPayoutStatus] = RewardPayoutStatus.Pending; IRewardOperations rewardOperations = CommerceOperationsFactory.RewardOperations(context); ResultCode resultCode = rewardOperations.UpdateRewardPayoutStatus(); if (resultCode != ResultCode.Success) { result = OrchestratedExecutionResult.NonTerminalError; Log.Warning("{0} call unsuccessfully processed.\r\n\r\nResultCode: {1}\r\n\r\nExplanation: {2}", (int)resultCode, context.ApiCallDescription, resultCode, ResultCodeExplanation.Get(resultCode)); } else { result = OrchestratedExecutionResult.Success; } break; case RewardType.EarnCredit: ApplyEarnCredit applyEarnCredit = new ApplyEarnCredit(RewardPayoutRecord, Log); result = applyEarnCredit.Apply(); break; default: Log.Error("Invalid reward type {0} in reward payout record.", null, RewardPayoutRecord.RewardType); break; } return(result); }
/// <summary> /// Adds the card in the context for the user in the context to this partner. /// </summary> /// <returns> /// A task that will yield the result code for the operation. /// </returns> public async Task <ResultCode> AddCardAsync() { ResultCode result; // If the card has a PAN token, see if a Visa ID has already been allocated for that PAN token. We do this because Visa rejects // registering a card that had previously been registered to a different account. This approach allows us to differentiate false // positives (i.e. Visa rejects a card for which we already have the Visa partner card ID somewhere in our DB) from true positives // (i.e. Visa rejects a card erroneously as far as we can tell.) ICardOperations cardOperations = CommerceOperationsFactory.CardOperations(Context); //Since we will comment FDC code, FDC PAN token will not be assigned to a card. So the code below is commented since RetrieveVisaPartnerCardId will never return any card //without FDC PAN token /* * Card card = (Card)Context[Key.Card]; * string visaPartnerCardId = cardOperations.RetrieveVisaPartnerCardId(); * if (String.IsNullOrWhiteSpace(visaPartnerCardId) == false) * { * PartnerCardInfo partnerCardInfo = GetVisaCardInfo(card); * partnerCardInfo.PartnerCardId = visaPartnerCardId; * partnerCardInfo.PartnerCardSuffix = "00"; * result = ResultCode.Created; * result = Task.FromResult(result).Result; * } * else */ { var userEnrolledWithVisa = false; var cards = cardOperations.RetrieveCards(); if (cards != null) { userEnrolledWithVisa = cards.Any(c => c.CardBrand == CardBrand.Visa); } result = await InvokeVisaAddCard(userEnrolledWithVisa); } return(result); }
/// <summary> /// Initializes a new instance of the MasterCardFilteringProcessor class. /// </summary> public MasterCardFilteringProcessor() { Context = new CommerceContext(string.Empty, CommerceWorkerConfig.Instance); CardOperations = CommerceOperationsFactory.CardOperations(Context); }
/// <summary> /// Initializes a new instance of the MasterCardRebateProcessor class. /// </summary> public MasterCardRebateProcessor() { Context = new CommerceContext(string.Empty, CommerceWorkerConfig.Instance); RedeemedDealOperations = CommerceOperationsFactory.RedeemedDealOperations(Context); }
/// <summary> /// Executes processing of the request. /// </summary> public ResultCode Execute() { ResultCode result = ResultCode.None; EndPointMessageRequest request = (EndPointMessageRequest)Context[Key.Request]; Dictionary <String, String> messageElementCollectionDictionary = new Dictionary <string, string>(); foreach (MessageElementsCollection c in request.MessageElementsCollection) { messageElementCollectionDictionary.Add(c.Key, c.Value); } String requestType = messageElementCollectionDictionary[VisaEPMConstants.EventEventType]; if (string.Equals(requestType, VisaEPMConstants.OnClearEventTypeValue, StringComparison.OrdinalIgnoreCase)) { Dictionary <String, String> userDefinedFieldsCollectionDictionary = new Dictionary <string, string>(); foreach (UserDefinedFieldsCollection c in request.UserDefinedFieldsCollection) { userDefinedFieldsCollectionDictionary.Add(c.Key, c.Value); } String cardId = request.CardId; String merchantId = messageElementCollectionDictionary[VisaEPMConstants.TransactionVisaMerchantId]; String storeId = messageElementCollectionDictionary[VisaEPMConstants.TransactionVisaStoreId]; // Marshal the redeem deal request into a RedeemedDeal object. RedeemedDeal redeemedDeal = new RedeemedDeal() { AnalyticsEventId = Guid.NewGuid() }; Context[Key.RedeemedDeal] = redeemedDeal; redeemedDeal.CallbackEvent = RedemptionEvent.Settlement; redeemedDeal.PartnerRedeemedDealScopeId = messageElementCollectionDictionary[VisaEPMConstants.TransactionVipTransactionId]; redeemedDeal.PartnerRedeemedDealId = messageElementCollectionDictionary[VisaEPMConstants.TransactionTransactionID]; String time = messageElementCollectionDictionary[VisaEPMConstants.TransactionTimeStampYYMMDD]; // UTC Time: 2013-12-05T07:25:06 redeemedDeal.PurchaseDateTime = DateTime.Parse(time); redeemedDeal.PurchaseDateTime = DateTime.SpecifyKind(redeemedDeal.PurchaseDateTime, DateTimeKind.Utc); String amount = messageElementCollectionDictionary[VisaEPMConstants.TransactionClearingAmount]; redeemedDeal.AuthorizationAmount = AmexUtilities.ParseAuthAmount(amount); redeemedDeal.Currency = VisaConstants.CurrencyUSD; Context[Key.PartnerCardId] = cardId; Context[Key.PartnerClaimedDealId] = null; // could be the BingOfferDealId Context[Key.PartnerMerchantId] = string.Format("{0};{1}", merchantId, storeId); Context[Key.OutletPartnerMerchantId] = null; // storedId; Context[Key.CreditStatus] = CreditStatus.ClearingReceived; string merchantCity = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantCityString); string merchantState = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantStateString); var merchantPostalCode = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantPostalCodeString); KeyTransactionData keyTransactionData = new KeyTransactionData { MerchantCity = merchantCity, MerchantState = merchantState, MerchantPostalCode = merchantPostalCode }; Context[Key.PartnerData] = keyTransactionData.XmlSerialize(); LogRedeedmedDealRequestParameters(redeemedDeal); result = AddRedeemedDeal(); Context[Key.ResultCode] = result; // If the deal was successfully redeemed, apply any applicable rewards. if (result == ResultCode.Created) { RedeemedDealInfo redeemedDealInfo = (RedeemedDealInfo)Context[Key.RedeemedDealInfo]; if (redeemedDealInfo != null) { // Update analytics. SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations( Context)); Context[Key.GlobalUserId] = redeemedDealInfo.GlobalUserId; User user = sharedUserLogic.RetrieveUser(); if (user != null) { Analytics.AddRedemptionEvent(redeemedDealInfo.GlobalUserId, redeemedDeal.AnalyticsEventId, user.AnalyticsEventId, redeemedDealInfo.ParentDealId, redeemedDealInfo.Currency, redeemedDeal.AuthorizationAmount, redeemedDealInfo.DiscountAmount, redeemedDealInfo.GlobalId, (string)Context[Key.PartnerMerchantId]); } // Add rewards for any active rewards program. AddRedemptionRewards(); } } } return(result); }