/// <summary> /// Initializes a new instance of the SharedAuthorizationLogic class. /// </summary> /// <param name="context"> /// The context of the current API call. /// </param> /// <param name="authorizationOperations"> /// The object to use to perform operations on authorizations. /// </param> public SharedAuthorizationLogic(CommerceContext context, IAuthorizationOperations authorizationOperations) { Context = context; AuthorizationOperations = authorizationOperations; }
public void Execute_TimesQualified_Two_MaximumApplications_One( CartItemQuantityXSellPriceAction action, IRuleValue <string> targetItemId, IRuleValue <int> quantityX, IRuleValue <decimal> sellPrice, IRuleValue <int> maximumApplications, Cart cart, CommerceContext commerceContext, IRuleExecutionContext context) { /********************************************** * Arrange **********************************************/ cart.Adjustments.Clear(); cart.Lines.ForEach(l => l.Adjustments.Clear()); var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>(); globalPricingPolicy.ShouldRoundPriceCalc = false; cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100); while (cart.Lines.Count > 1) { cart.Lines.RemoveAt(0); } var cartline = cart.Lines[0]; cartline.Quantity = 4; cartline.Totals.SubTotal.Amount = 300; cartline.ItemId = "Habitat_Master|12345|"; cartline.SetPolicy(new PurchaseOptionMoneyPolicy { SellPrice = new Money(75) }); var cartTotals = new CartTotals(cart); targetItemId.Yield(context).ReturnsForAnyArgs("Habitat_Master|12345|"); quantityX.Yield(context).ReturnsForAnyArgs(2); sellPrice.Yield(context).ReturnsForAnyArgs(40); maximumApplications.Yield(context).ReturnsForAnyArgs(1); context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext); commerceContext.AddObject(cartTotals); commerceContext.AddObject(cart); action.TargetItemId = targetItemId; action.QuantityX = quantityX; action.SellPrice = sellPrice; action.MaximumApplications = maximumApplications; /********************************************** * Act **********************************************/ Action executeAction = () => action.Execute(context); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1); cart.Adjustments.Should().BeEmpty(); cartTotals.Lines[cartline.Id].SubTotal.Amount.Should().Be(190); }
/// <summary> /// Initializes a new instance of the RewardsPtsProcessor class. /// </summary> public RewardsPtsProcessor() { Context = new CommerceContext(string.Empty, CommerceWorkerConfig.Instance); RewardOperations = CommerceOperationsFactory.RewardOperations(Context); }
/// <summary> /// Processes the specified commerce context. /// </summary> /// <param name="commerceContext">The commerce context.</param> /// <param name="sourceEnvironmentName">Name of the source environment.</param> /// <param name="newEnvironmentName">New name of the environment.</param> /// <param name="newArtifactStoreId">The new artifact store identifier.</param> /// <returns> /// User site terms /// </returns> public virtual async Task <bool> Process(CommerceContext commerceContext, string sourceEnvironmentName, string newEnvironmentName, Guid newArtifactStoreId) { using (CommandActivity.Start(commerceContext, this)) { var migrationSqlPolicy = commerceContext.GetPolicy <MigrationSqlPolicy>(); if (migrationSqlPolicy == null) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "InvalidOrMissingPropertyValue", new object[] { "MigrationSqlPolicy" }, $"{this.GetType()}. Missing MigrationSqlPolicy").ConfigureAwait(false); return(false); } if (string.IsNullOrEmpty(migrationSqlPolicy.SourceStoreSqlPolicy.Server)) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "InvalidOrMissingPropertyValue", new object[] { "MigrationSqlPolicy" }, $"{this.GetType()}. Empty server name in the MigrationSqlPolicy").ConfigureAwait(false); return(false); } var migrationPolicy = commerceContext.GetPolicy <MigrationPolicy>(); if (migrationPolicy == null) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "InvalidOrMissingPropertyValue", new object[] { "MigrationPolicy" }, $"{this.GetType()}. Missing MigrationPolicy").ConfigureAwait(false); return(false); } if (!Guid.TryParse(migrationSqlPolicy.ArtifactStoreId, out var id)) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "InvalidOrMissingPropertyValue", new object[] { "MigrationSqlPolicy.ArtifactStoreId" }, "MigrationSqlPolicy. Invalid ArtifactStoreId").ConfigureAwait(false); return(false); } var context = commerceContext.PipelineContextOptions; var findArg = new FindEntityArgument(typeof(CommerceEnvironment), $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{newEnvironmentName}"); var findResult = await this._findEntityPipeline.Run(findArg, context).ConfigureAwait(false); if (findResult is CommerceEnvironment newEnvironment) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "InvalidOrMissingPropertyValue", new object[] { newEnvironmentName }, $"Environment {newEnvironmentName} already exists.").ConfigureAwait(false); return(false); } findArg = new FindEntityArgument(typeof(CommerceEnvironment), $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{migrationPolicy.DefaultEnvironmentName}"); findResult = await this._findEntityPipeline.Run(findArg, context).ConfigureAwait(false); var sourceEnvironment = findResult as CommerceEnvironment; if (sourceEnvironment == null) { await commerceContext.AddMessage( commerceContext.GetPolicy <KnownResultCodes>().Error, "EntityNotFound", new object[] { migrationPolicy.DefaultEnvironmentName }, $"Entity {migrationPolicy.DefaultEnvironmentName} was not found.").ConfigureAwait(false); return(false); } if (sourceEnvironment.HasPolicy <EntityShardingPolicy>()) { commerceContext.AddUniqueObjectByType(sourceEnvironment.GetPolicy <EntityShardingPolicy>()); sourceEnvironment.RemovePolicy(typeof(EntityShardingPolicy)); } // set sql policies var sqlPoliciesCollection = new List <KeyValuePair <string, EntityStoreSqlPolicy> > { new KeyValuePair <string, EntityStoreSqlPolicy>("SourceGlobal", migrationSqlPolicy.SourceStoreSqlPolicy) }; // Get sql Policy set var ps = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(PolicySet), $"{CommerceEntity.IdPrefix<PolicySet>()}{migrationPolicy.SqlPolicySetName}"), context).ConfigureAwait(false); if (ps == null) { context.CommerceContext.Logger.LogError($"PolicySet {migrationPolicy.SqlPolicySetName} was not found."); } else { sqlPoliciesCollection.Add(new KeyValuePair <string, EntityStoreSqlPolicy>("DestinationShared", ps.GetPolicy <EntityStoreSqlPolicy>())); } commerceContext.AddUniqueObjectByType(sqlPoliciesCollection); sourceEnvironment.Name = sourceEnvironmentName; sourceEnvironment.ArtifactStoreId = id; sourceEnvironment.Id = $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{sourceEnvironmentName}"; sourceEnvironment.SetPolicy(migrationSqlPolicy.SourceStoreSqlPolicy); var migrateEnvironmentArgument = new MigrateEnvironmentArgument(sourceEnvironment, newArtifactStoreId, newEnvironmentName); var result = await this._migrateEnvironmentPipeline.Run(migrateEnvironmentArgument, context).ConfigureAwait(false); return(result); } }
private async Task <Decimal> GetListCount(string listName, CommerceContext context) { var listMetaData = await this.Commander.Pipeline <IPopulateListMetadataPipeline>().Run(new ListMetadata(listName), (IPipelineExecutionContextOptions)context.GetPipelineContextOptions()); return(Convert.ToDecimal(listMetaData.Count)); }
public ProductRepository(CommerceContext context) : base(context) { }
/// <summary> /// Adds the specified card for the specified user. /// </summary> /// <param name="context"> /// The context object containing information on the card to add. /// </param> public AddCardInvoker(CommerceContext context) { // Save the context. Context = context; }
public async Task <bool> EndItemListing(CommerceContext commerceContext, SellableItem sellableItem, string reason) { using (var activity = CommandActivity.Start(commerceContext, this)) { //Instantiate the call wrapper class try { var apiCall = new EndItemCall(await GetEbayContext(commerceContext)); if (sellableItem.HasComponent <EbayItemComponent>()) { var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>(); var reasonCodeType = EndReasonCodeType.NotAvailable; switch (reason) { case "NotAvailable": reasonCodeType = EndReasonCodeType.NotAvailable; break; case "CustomCode": reasonCodeType = EndReasonCodeType.CustomCode; break; case "Incorrect": reasonCodeType = EndReasonCodeType.Incorrect; break; case "LostOrBroken": reasonCodeType = EndReasonCodeType.LostOrBroken; break; case "OtherListingError": reasonCodeType = EndReasonCodeType.OtherListingError; break; case "SellToHighBidder": reasonCodeType = EndReasonCodeType.SellToHighBidder; break; case "Sold": reasonCodeType = EndReasonCodeType.Sold; break; default: reasonCodeType = EndReasonCodeType.CustomCode; break; } if (string.IsNullOrEmpty(ebayItemComponent.EbayId)) { ebayItemComponent.Status = "LostSync"; } else { if (ebayItemComponent.Status != "Ended") { //Call Ebay and End the Item Listing try { apiCall.EndItem(ebayItemComponent.EbayId, reasonCodeType); ebayItemComponent.Status = "Ended"; } catch (Exception ex) { if (ex.Message == "The auction has already been closed.") { //Capture a case where the listing has expired naturally and it can now no longer be ended. reason = "Expired"; ebayItemComponent.Status = "Ended"; } else { commerceContext.Logger.LogError(ex, $"EbayCommand.EndItemListing.Exception: Message={ex.Message}"); await commerceContext.AddMessage("Error", "EbayCommand.EndItemListing", new [] { ex }, ex.Message).ConfigureAwait(false); } } } } ebayItemComponent.ReasonEnded = reason; ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = "Listing Ended", EventUser = commerceContext.CurrentCsrId() }); sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Ended"); var persistResult = await this._commerceCommander.PersistEntity(commerceContext, sellableItem).ConfigureAwait(false); var listRemoveResult = await this._commerceCommander.Command <ListCommander>() .RemoveItemsFromList(commerceContext, "Ebay_Listed", new List <String>() { sellableItem.Id }).ConfigureAwait(false); } } catch (Exception ex) { commerceContext.Logger.LogError($"Ebay.EndItemListing.Exception: Message={ex.Message}"); await commerceContext.AddMessage("Error", "Ebay.EndItemListing.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false); } return(true); } }
public ProductService() { this.dbContext = new CommerceContext(); }
public virtual string Process(CommerceContext commerceContext, InputAddress inputAddress) { var upsClientPolicy = commerceContext.GetPolicy <UpsAddressValidationPolicy>(); var url = upsClientPolicy.IsLive ? upsClientPolicy.ProdUrl : upsClientPolicy.TestUrl; var requestString = $@"{{ ""UPSSecurity"": {{ ""UsernameToken"": {{ ""Username"": ""{upsClientPolicy.UserName}"", ""Password"": ""{upsClientPolicy.Password}"" }}, ""ServiceAccessToken"": {{ ""AccessLicenseNumber"": ""{upsClientPolicy.LicenseKey}"" }} }}, ""XAVRequest"": {{ ""Request"": {{ ""RequestOption"": ""1"", ""TransactionReference"": {{ ""CustomerContext"": ""Your Customer Context"" }} }}, ""MaximumListSize"": ""10"", ""AddressKeyFormat"": {{ ""ConsigneeName"": ""{inputAddress.ConsigneeName}"", ""BuildingName"": ""{inputAddress.BuildingName}"", ""AddressLine"": ""{inputAddress.AddressLine1}"", ""PoliticalDivision2"": ""{inputAddress.City}"", ""PoliticalDivision1"": ""{inputAddress.State}"", ""PostcodePrimaryLow"": ""{inputAddress.ZipCode}"", ""CountryCode"": ""{inputAddress.CountryCode}"" }} }} }}"; var client = new HttpClient(); var content = new StringContent(requestString, Encoding.UTF8, Constants.Headers.ContentType); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.Headers.ContentType)); content.Headers.ContentType = new MediaTypeHeaderValue(Constants.Headers.ContentType); client.DefaultRequestHeaders.Add(Constants.Headers.AcessControlHeaders, Constants.Headers.AllowHeaders); client.DefaultRequestHeaders.Add(Constants.Headers.AcessControlMethods, Constants.Headers.Methods); client.DefaultRequestHeaders.Add(Constants.Headers.AcessControlOrigin, Constants.Headers.Origin); try { var output = client.PostAsync(url, content).Result; output.EnsureSuccessStatusCode(); var outputData = output.Content.ReadAsStringAsync().Result; return(outputData); } catch (Exception ex) { Log.Error(ex.Message); } return(string.Empty); }
/// <summary> /// Initializes a new instance of the VisaAuthorizationExecutor class. /// </summary> /// <param name="context"> /// The context for the API being invoked. /// </param> public VisaAuthorizationExecutor(CommerceContext context) { Context = context; Context[Key.Partner] = Partner.Visa; }
public DiscountApplicator(CommerceContext commerceContext) { this.commerceContext = commerceContext; }
/// <summary> /// Processes the call from First Data. /// </summary> /// <param name="context"> /// The context of the call. /// </param> /// <param name="callTimer"> /// The Stopwatch used to time the call. /// </param> /// <param name="executorInvoker"> /// The callback that invokes the executor to execute call logic. /// </param> /// <returns> /// The HTTP status code to place within the response. /// </returns> private static HttpStatusCode ProcessFirstDataCall(CommerceContext context, Stopwatch callTimer, Func <ResultCode> executorInvoker) { HttpStatusCode result = HttpStatusCode.OK; context.Log.Information("Processing {0} call.", context.ApiCallDescription); CallCompletionStatus callCompletionStatus; try { HttpClientCertificate httpClientCertificate = HttpContext.Current.Request.ClientCertificate; context.Log.Verbose("Presented client certificate has serial number \"{0}\".", httpClientCertificate.SerialNumber); if (General.IsPresentedCertValid(httpClientCertificate, CommerceServiceConfig.Instance.FirstDataClientCertificateSerialNumbers) == true) { ResultCode resultCode = executorInvoker(); if (resultCode == ResultCode.Success || resultCode == ResultCode.Created) { callCompletionStatus = CallCompletionStatus.Success; context.Log.Information("{0} call processed successfully.", context.ApiCallDescription); } else { callCompletionStatus = CallCompletionStatus.SuccessWithWarnings; #if !IntDebug && !IntRelease context.Log.Warning("{0} call unsuccessfully processed.\r\n\r\nResultCode: {1}\r\n\r\nExplanation: {2}", (int)resultCode, context.ApiCallDescription, resultCode, ResultCodeExplanation.Get(resultCode)); #endif if (resultCode == ResultCode.None || resultCode == ResultCode.UnknownError) { result = HttpStatusCode.InternalServerError; } } } else { callCompletionStatus = CallCompletionStatus.SuccessWithWarnings; #if !IntDebug && !IntRelease context.Log.Warning("{0} call unsuccessfully processed.\r\n\r\nResultCode: {1}\r\n\r\nExplanation: {2}", (int)ResultCode.InvalidClientCertificate, context.ApiCallDescription, ResultCode.InvalidClientCertificate, ResultCodeExplanation.Get(ResultCode.InvalidClientCertificate)); #endif result = HttpStatusCode.Unauthorized; } } catch (Exception ex) { callCompletionStatus = CallCompletionStatus.Error; context.Log.Critical("{0} call ended with an error.", ex, context.ApiCallDescription); result = HttpStatusCode.InternalServerError; } callTimer.Stop(); context.PerformanceInformation.Add("Total", String.Format("{0} ms", callTimer.ElapsedMilliseconds)); context.Log.CallCompletion(context.ApiCallDescription, callCompletionStatus, context.PerformanceInformation); return(result); }
public async Task <bool> ImportComposerViewsFields(CommerceEntity commerceEntity, Dictionary <string, string> composerFields, CommerceContext context) { var masterView = await _commerceCommander.Command <GetEntityViewCommand>().Process( context, commerceEntity.Id, commerceEntity.EntityVersion, context.GetPolicy <KnownCatalogViewsPolicy>().Master, string.Empty, string.Empty); if (masterView == null) { Log.Error($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}"); throw new ApplicationException($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}"); } if (masterView.ChildViews == null || masterView.ChildViews.Count == 0) { Log.Error($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}"); throw new ApplicationException($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}"); } var isUpdated = false; foreach (EntityView view in masterView.ChildViews) { EntityView composerViewForEdit = null; foreach (var viewField in view.Properties) { if (composerFields.Keys.Contains(viewField.Name)) { if (composerViewForEdit == null) { composerViewForEdit = Task.Run <EntityView>(async() => await commerceEntity.GetComposerView(view.ItemId, _commerceCommander, context)).Result; } if (composerViewForEdit != null) { var composerProperty = composerViewForEdit.GetProperty(viewField.Name); if (composerViewForEdit != null) { composerProperty.ParseValueAndSetEntityView(composerFields[viewField.Name]); isUpdated = true; } } } } } if (isUpdated) { return(await _composerCommander.PersistEntity(context, commerceEntity)); } return(false); }
public override void Initialize(IServiceProvider serviceProvider, ILogger logger, MinionPolicy policy, CommerceEnvironment environment, CommerceContext globalContext) { base.Initialize(serviceProvider, logger, policy, environment, globalContext); this.MinionPipeline = serviceProvider.GetService <ICreateCouponsPipeline>(); }
public async Task <ItemType> PrepareItem(CommerceContext commerceContext, SellableItem sellableItem) { using (var activity = CommandActivity.Start(commerceContext, this)) { //Instantiate the call wrapper class var apiCall = new AddFixedPriceItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false)); var item = await this._commerceCommander.Pipeline <IPrepareEbayItemPipeline>().Run(sellableItem, commerceContext.PipelineContextOptions).ConfigureAwait(false); item.Description = sellableItem.Description; item.Title = sellableItem.DisplayName; item.SubTitle = "Test Item"; var listPricingPolicy = sellableItem.GetPolicy <ListPricingPolicy>(); var listPrice = listPricingPolicy.Prices.FirstOrDefault(); item.StartPrice = new AmountType { currencyID = CurrencyCodeType.USD, Value = System.Convert.ToDouble(listPrice.Amount, System.Globalization.CultureInfo.InvariantCulture) }; item.ConditionID = 1000; //new item.PaymentMethods = new BuyerPaymentMethodCodeTypeCollection(); item.PaymentMethods.Add(BuyerPaymentMethodCodeType.PayPal); item.PaymentMethods.Add(BuyerPaymentMethodCodeType.VisaMC); item.PayPalEmailAddress = "*****@*****.**"; item.PostalCode = "98014"; item.DispatchTimeMax = 3; item.ShippingDetails = new ShippingDetailsType(); item.ShippingDetails.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection(); item.ShippingDetails.ShippingType = ShippingTypeCodeType.Flat; ShippingServiceOptionsType shipservice1 = new ShippingServiceOptionsType(); shipservice1.ShippingService = "USPSPriority"; shipservice1.ShippingServicePriority = 1; shipservice1.ShippingServiceCost = new AmountType(); shipservice1.ShippingServiceCost.currencyID = CurrencyCodeType.USD; shipservice1.ShippingServiceCost.Value = 5.0; shipservice1.ShippingServiceAdditionalCost = new AmountType(); shipservice1.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.USD; shipservice1.ShippingServiceAdditionalCost.Value = 1.0; item.ShippingDetails.ShippingServiceOptions.Add(shipservice1); //ShippingServiceOptionsType shipservice2 = new ShippingServiceOptionsType(); //shipservice2.ShippingService = "US_Regular"; //shipservice2.ShippingServicePriority = 2; //shipservice2.ShippingServiceCost = new AmountType(); //shipservice2.ShippingServiceCost.currencyID = CurrencyCodeType.USD; //shipservice2.ShippingServiceCost.Value = 1.0; //shipservice2.ShippingServiceAdditionalCost = new AmountType(); //shipservice2.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.USD; //shipservice2.ShippingServiceAdditionalCost.Value = 1.0; //item.ShippingDetails.ShippingServiceOptions.Add(shipservice2); //item.Variations. item.ReturnPolicy = new ReturnPolicyType { ReturnsAcceptedOption = "ReturnsAccepted" }; //Add pictures item.PictureDetails = new PictureDetailsType(); //Specify GalleryType item.PictureDetails.GalleryType = GalleryTypeCodeType.None; item.PictureDetails.GalleryTypeSpecified = true; return(item); } }
void ValidateEnrollment( CommerceContext context, RewardsProgramCardEnrollment enrollment, out Guid globalUserId, out CardBrand[] cardBrands, out RewardPrograms rewardPrograms) { cardBrands = null; rewardPrograms = RewardPrograms.None; globalUserId = Guid.Empty; string errorMessage = null; if (enrollment == null) { errorMessage = "The enrollment request body is invalid."; } else { if (string.IsNullOrWhiteSpace(enrollment.UserId)) { errorMessage = "The user id should be specified."; } else if (!Guid.TryParse(enrollment.UserId, out globalUserId)) { errorMessage = "The user id is not valid."; } else if (enrollment.CardBrands == null || enrollment.CardBrands.Length == 0) { errorMessage = "No card brands were specified."; } else if (enrollment.RewardPrograms == null || enrollment.RewardPrograms.Length == 0) { errorMessage = "No reward programs were specified."; } else { cardBrands = new CardBrand[enrollment.CardBrands.Length]; for (int i = 0; i < enrollment.CardBrands.Length; i++) { var cardBrand = enrollment.CardBrands[i]; CardBrand brand; if (Enum.TryParse(cardBrand, true, out brand)) { cardBrands[i] = brand; } else { errorMessage = string.Format("The card brand '{0}' is not valid.", cardBrand); break; } } if (errorMessage == null) { rewardPrograms = RewardPrograms.None; foreach (var rewardProgram in enrollment.RewardPrograms) { RewardPrograms program; if (Enum.TryParse(rewardProgram, true, out program)) { rewardPrograms |= program; } else { errorMessage = string.Format("The reward program '{0}' is not valid.", rewardProgram); break; } } } } } if (errorMessage != null) { context.Log.Information("The enrollment request body had errors: {0}", errorMessage); throw new HttpResponseException( this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage)); } }
public async Task <ItemType> AddItem(CommerceContext commerceContext, SellableItem sellableItem) { using (var activity = CommandActivity.Start(commerceContext, this)) { var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>(); try { //Instantiate the call wrapper class var apiCall = new AddFixedPriceItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false)); var item = await PrepareItem(commerceContext, sellableItem).ConfigureAwait(false); //Send the call to eBay and get the results FeeTypeCollection feeTypeCollection = apiCall.AddFixedPriceItem(item); foreach (var feeItem in feeTypeCollection) { var fee = feeItem as FeeType; ebayItemComponent.Fees.Add(new AwardedAdjustment { Adjustment = new Money(fee.Fee.currencyID.ToString(), System.Convert.ToDecimal(fee.Fee.Value)), AdjustmentType = "Fee", Name = fee.Name }); } ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = "Listing Added", EventUser = commerceContext.CurrentCsrId() }); ebayItemComponent.EbayId = item.ItemID; ebayItemComponent.Status = "Listed"; sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed"); await commerceContext.AddMessage("Info", "EbayCommand.AddItem", new [] { item.ItemID }, $"Item Listed:{item.ItemID}").ConfigureAwait(false); return(item); } catch (Exception ex) { if (ex.Message.Contains("It looks like this listing is for an item you already have on eBay")) { var existingId = ex.Message.Substring(ex.Message.IndexOf("(") + 1); existingId = existingId.Substring(0, existingId.IndexOf(")")); await commerceContext.AddMessage("Warn", "EbayCommand.AddItem", new [] { existingId }, $"ExistingId:{existingId}-ComponentId:{ebayItemComponent.EbayId}").ConfigureAwait(false); ebayItemComponent.EbayId = existingId; ebayItemComponent.Status = "Listed"; ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = "Existing Listing Linked", EventUser = commerceContext.CurrentCsrId() }); sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed"); } else { commerceContext.Logger.LogError($"Ebay.AddItem.Exception: Message={ex.Message}"); await commerceContext.AddMessage("Error", "Ebay.AddItem.Exception", new [] { ex }, ex.Message).ConfigureAwait(false); ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = $"Error-{ex.Message}", EventUser = commerceContext.CurrentCsrId() }); } } return(new ItemType()); } }
/// <summary> /// The execute. /// </summary> /// <param name="arg"> /// The AddJobArgument argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="Job"/>. /// </returns> public override async Task <Job> Run(AddJobArgument arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull("AddJobArgument The argument cannot be null."); Condition.Requires(arg.Name).IsNotNullOrEmpty("The Job name cannot be null or empty."); Condition.Requires(arg.JobConnection).IsNotNull("The Job Connection cannot be null."); var awaiter = _findEntityPipeline.Run(new FindEntityArgument(typeof(Job), $"{(object) CommerceEntity.IdPrefix<Job>()}{ arg.Name}"), context).GetAwaiter(); if (awaiter.GetResult()) { CommerceContext commerceContext = context.CommerceContext; string validationError = context.GetPolicy <KnownResultCodes>().ValidationError; string commerceTermKey = "JobNameAlreadyInUse"; object[] args = new object[1] { arg.Name }; string defaultMessage = $"Job name { arg.Name} is already in use."; context.Abort("Ok|" + await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context); context = null; return(null); } var job = new Job(arg.Name) { Id = $"{ CommerceEntity.IdPrefix<Job>()}{ arg.JobConnection.Name}-{ arg.Name}", FriendlyId = $"{arg.JobConnection.Name}-{arg.Name}" }; job.JobConnection = new EntityReference() { EntityTarget = arg.JobConnection.Id, Name = arg.JobConnection.Name }; job.Description = arg.Description;; job.DisplayName = arg.DisplayName; job.Type = arg.Type; job.NotificationEmail = arg.NotificationEmail; job.SqlQuery = arg.SqlQuery; //Assign Policy data var jobPolicy = context.GetPolicy <JobPolicy>(); jobPolicy.IsRecurringJob = arg.IsRecurringJob; jobPolicy.StartDateTime = arg.StartDateTime; jobPolicy.EndDateTime = arg.EndDateTime; jobPolicy.RecurrenceRepeatType = arg.RecurrenceRepeatType; jobPolicy.RepeatValue = arg.RepeatValue; job.SetPolicy(jobPolicy); job.SetComponent(new ListMembershipsComponent() { Memberships = new List <string>() { CommerceEntity.ListName <Job>() } }); var jobAdded = new JobAdded(job.FriendlyId) { Name = job.Name }; context.CommerceContext.AddModel(jobAdded); return(job); }
public HomeController([FromServices] CommerceContext context) { _context = context; }
public void Execute_WithProperties( BaseCartItemSubtotalPercentOffAction action, IRuleValue <decimal> subtotal, IRuleValue <decimal> percentOff, Cart cart, CommerceContext commerceContext, IRuleExecutionContext context) { /********************************************** * Arrange **********************************************/ cart.Adjustments.Clear(); cart.Lines.ForEach(l => l.Adjustments.Clear()); var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>(); globalPricingPolicy.ShouldRoundPriceCalc = false; cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100); var cartline = cart.Lines[1]; cartline.Totals.SubTotal.Amount = 150; var cartTotals = new CartTotals(cart); subtotal.Yield(context).ReturnsForAnyArgs(150); percentOff.Yield(context).ReturnsForAnyArgs(25.55M); var propertiesModel = new PropertiesModel(); propertiesModel.Properties.Add("PromotionId", "id"); propertiesModel.Properties.Add("PromotionCartText", "carttext"); propertiesModel.Properties.Add("PromotionText", "text"); commerceContext.AddObject(propertiesModel); context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext); commerceContext.AddObject(cartTotals); commerceContext.AddObject(cart); action.MatchingLines(context).ReturnsForAnyArgs(cart.Lines); action.SubtotalOperator = new DecimalGreaterThanEqualToOperator(); action.Subtotal = subtotal; action.PercentOff = percentOff; /********************************************** * Act **********************************************/ Action executeAction = () => action.Execute(context); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1); cart.Adjustments.Should().BeEmpty(); cartTotals.Lines[cartline.Id].SubTotal.Amount.Should().Be(111.6750M); cartline.Adjustments.Should().NotBeEmpty(); cartline.Adjustments.FirstOrDefault().Should().NotBeNull(); cartline.Adjustments.FirstOrDefault().Should().BeOfType <CartLineLevelAwardedAdjustment>(); cartline.Adjustments.FirstOrDefault()?.Name.Should().Be("text"); cartline.Adjustments.FirstOrDefault()?.DisplayName.Should().Be("carttext"); cartline.Adjustments.FirstOrDefault()?.AdjustmentType.Should().Be(commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount); cartline.Adjustments.FirstOrDefault()?.AwardingBlock.Should().Contain(nameof(BaseCartItemSubtotalPercentOffAction)); cartline.Adjustments.FirstOrDefault()?.IsTaxable.Should().BeFalse(); cartline.Adjustments.FirstOrDefault()?.Adjustment.CurrencyCode.Should().Be(commerceContext.CurrentCurrency()); cartline.Adjustments.FirstOrDefault()?.Adjustment.Amount.Should().Be(-38.325M); cartline.HasComponent <MessagesComponent>().Should().BeTrue(); }
private IProductRepository CreateProductRepository(CommerceContext context) => (IProductRepository)Activator.CreateInstance(this._configuration.ProductRepositoryType, context);
void OnSendNotification(CommerceContext context) { context.Mailer.SendInvoiceEmail(context.OrderData); }