Exemplo n.º 1
0
        public void Setup()
        {
            _oc       = Substitute.For <IOrderCloudClient>();
            _settings = Substitute.For <AppSettings>();
            _settings.CardConnectSettings = new OrderCloudIntegrationsCardConnectConfig
            {
                UsdMerchantID = "mockUsdMerchantID",
                CadMerchantID = "mockCadMerchantID",
                EurMerchantID = "mockEurMerchantID"
            };
            _settings.OrderCloudSettings = new OrderCloudSettings
            {
                IncrementorPrefix = "SEB"
            };
            _card = Substitute.For <ICreditCardCommand>();
            _card.AuthorizePayment(Arg.Any <OrderCloudIntegrationsCreditCardPayment>(), "mockUserToken", Arg.Any <string>())
            .Returns(Task.FromResult(new Payment {
            }));

            _oc.Orders.PatchAsync(OrderDirection.Incoming, "mockOrderID", Arg.Any <PartialOrder>()).Returns(Task.FromResult(new Order {
                ID = "SEB12345"
            }));
            _oc.AuthenticateAsync().Returns(Task.FromResult(new TokenResponse {
                AccessToken = "mockToken"
            }));
            _oc.Orders.SubmitAsync <HSOrder>(Arg.Any <OrderDirection>(), Arg.Any <string>(), Arg.Any <string>()).Returns(Task.FromResult(new HSOrder {
                ID = "submittedorderid"
            }));
            _sut = new OrderSubmitCommand(_oc, _settings, _card); // sut is subject under test
        }
        public async Task <HSBuyerLocation> Create(string buyerID, [FromBody] HSBuyerLocation buyerLocation)
        {
            // ocAuth is the token for the organization that is specified in the AppSettings
            var ocAuth = await _oc.AuthenticateAsync();

            return(await _buyerLocationCommand.Create(buyerID, buyerLocation, ocAuth.AccessToken));
        }
Exemplo n.º 3
0
        private async Task <PriceSchedule> UpdateRelatedPriceSchedules(PriceSchedule updated, string token)
        {
            var ocAuth = await _oc.AuthenticateAsync();

            var initial = await _oc.PriceSchedules.GetAsync(updated.ID);

            if (initial.MaxQuantity != updated.MaxQuantity ||
                initial.MinQuantity != updated.MinQuantity ||
                initial.UseCumulativeQuantity != updated.UseCumulativeQuantity ||
                initial.RestrictedQuantity != updated.RestrictedQuantity ||
                initial.ApplyShipping != updated.ApplyShipping ||
                initial.ApplyTax != updated.ApplyTax)
            {
                var patch = new PartialPriceSchedule()
                {
                    MinQuantity           = updated.MinQuantity,
                    MaxQuantity           = updated.MaxQuantity,
                    UseCumulativeQuantity = updated.UseCumulativeQuantity,
                    RestrictedQuantity    = updated.RestrictedQuantity,
                    ApplyShipping         = updated.ApplyShipping,
                    ApplyTax = updated.ApplyTax
                };
                var relatedPriceSchedules = await _oc.PriceSchedules.ListAllAsync(filters : $"ID={initial.ID}*");

                var priceSchedulesToUpdate = relatedPriceSchedules.Where(p => p.ID != updated.ID);
                await Throttler.RunAsync(priceSchedulesToUpdate, 100, 5, p =>
                {
                    return(_oc.PriceSchedules.PatchAsync(p.ID, patch, ocAuth.AccessToken));
                });
            }
            return(await _oc.PriceSchedules.SaveAsync <PriceSchedule>(updated.ID, updated, token));
        }
Exemplo n.º 4
0
        /// <summary>
        /// This method is not for regular use. If you are attempting to use it for any reason consult the project lead
        /// If you need the context of an authenticated user ensure you're using a valid OrderCloudIntegrationsAuth attribute
        /// and reference the VerifiedUserContext from the BaseController
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public async Task <VerifiedUserContext> Define(OrderCloudClientConfig config)
        {
            var auth = await _oc.AuthenticateAsync();

            var user = await _oc.Me.GetAsync();

            var jwt = new JwtSecurityToken(auth.AccessToken);

            var cid = new ClaimsIdentity("OrderCloudIntegrations");

            cid.AddClaim(new Claim("accesstoken", auth.AccessToken));
            cid.AddClaim(new Claim("clientid", jwt.GetClientID()));
            cid.AddClaim(new Claim("usrtype", jwt.GetUserType()));
            cid.AddClaim(new Claim("username", user.Username));
            cid.AddClaim(new Claim("userid", user.ID));
            cid.AddClaim(new Claim("email", user.Email ?? ""));
            cid.AddClaim(new Claim("buyer", user.Buyer?.ID ?? ""));
            cid.AddClaim(new Claim("supplier", user.Supplier?.ID ?? ""));
            cid.AddClaim(new Claim("seller", user.Seller?.ID ?? ""));
            cid.AddClaims(user.AvailableRoles.Select(r => new Claim(ClaimTypes.Role, r)));
            var roles = user.AvailableRoles.Select(r => new Claim(ClaimTypes.Role, r)).ToList();

            roles.Add(new Claim(ClaimTypes.Role, "BaseUserRole"));
            cid.AddClaims(roles);

            Principal = new ClaimsPrincipal(cid);
            _token    = new JwtSecurityTokenHandler().ReadJwtToken(auth.AccessToken);
            return(this);
        }
        private async Task <string> GetTokenAsync()
        {
            var token = _oc.TokenResponse?.AccessToken;

            if (token == null || DateTime.UtcNow > _oc.TokenResponse.ExpiresUtc)
            {
                await _oc.AuthenticateAsync();

                token = _oc.TokenResponse?.AccessToken;
            }
            return(token);
        }
Exemplo n.º 6
0
        private async Task <string> GetAdminToken()
        {
            var adminOcToken = _oc.TokenResponse?.AccessToken;

            if (adminOcToken == null || DateTime.UtcNow > _oc.TokenResponse.ExpiresUtc)
            {
                await _oc.AuthenticateAsync();

                adminOcToken = _oc.TokenResponse.AccessToken;
            }
            return(adminOcToken);
        }
        /// <summary>
        /// The staging environment gets restored weekly from production
        /// during that restore things like webhooks, message senders, and integration events are shut off (so you don't for example email production customers)
        /// this process restores integration events which are required for checkout (with environment specific settings)
        public async Task PostStagingRestore()
        {
            var token = (await _oc.AuthenticateAsync()).AccessToken;

            var deleteIE = DeleteAllIntegrationEvents(token);
            await Task.WhenAll(deleteIE);

            // recreate with environment specific data
            var createIE = CreateOrUpdateAndAssignIntegrationEvents(token);
            var shutOffSupplierEmails = ShutOffSupplierEmailsAsync(token); // shut off email notifications for all suppliers

            await Task.WhenAll(createIE, shutOffSupplierEmails);
        }
Exemplo n.º 8
0
        /// <summary>
        /// The staging environment gets restored weekly from production
        /// during that restore things like webhooks, message senders, and integration events are shut off (so you don't for example email production customers)
        /// this process restores integration events which are required for checkout (with environment specific settings)
        public async Task PostStagingRestore()
        {
            var token      = (await _oc.AuthenticateAsync()).AccessToken;
            var apiClients = await GetApiClients(token);

            var storefrontClientIDs = await GetStoreFrontClientIDs(token);

            var deleteIE = DeleteAllIntegrationEvents(token);
            await Task.WhenAll(deleteIE);

            // recreate with environment specific data
            var createIE = CreateAndAssignIntegrationEvents(storefrontClientIDs, apiClients.BuyerLocalUiApiClient.ID, token);
            var shutOffSupplierEmails = ShutOffSupplierEmailsAsync(token); // shut off email notifications for all suppliers

            await Task.WhenAll(createIE, shutOffSupplierEmails);
        }
Exemplo n.º 9
0
        public async Task <List <HSBuyer> > GetBuyerFilterValues(DecodedToken decodedToken)
        {
            if (decodedToken.CommerceRole == CommerceRole.Seller)
            {
                return(await _oc.Buyers.ListAllAsync <HSBuyer>());
            }

            var adminOcToken = _oc.TokenResponse?.AccessToken;

            if (adminOcToken == null || DateTime.UtcNow > _oc.TokenResponse.ExpiresUtc)
            {
                await _oc.AuthenticateAsync();

                adminOcToken = _oc.TokenResponse.AccessToken;
            }

            return(await _oc.Buyers.ListAllAsync <HSBuyer>(adminOcToken));
        }
Exemplo n.º 10
0
        public async Task <JObject> GetOrderAsync(string ID, VerifiedUserContext user)
        {
            //TODO: BaseUrl cannot be found here
            var ocAuth = await _ocSeller.AuthenticateAsync();

            HSShipEstimate estimate;
            HSShipMethod   ship_method       = null;
            var            supplierWorksheet = await _ocSeller.IntegrationEvents.GetWorksheetAsync <HSOrderWorksheet>(OrderDirection.Outgoing, ID, ocAuth.AccessToken);

            var buyerWorksheet = await _ocSeller.IntegrationEvents.GetWorksheetAsync <HSOrderWorksheet>(OrderDirection.Incoming, ID.Split('-')[0], ocAuth.AccessToken);

            var buyerLineItems = buyerWorksheet.GetBuyerLineItemsBySupplierID(supplierWorksheet.Order.ToCompanyID);

            if (buyerWorksheet?.ShipEstimateResponse != null && buyerWorksheet?.ShipEstimateResponse?.ShipEstimates.Count > 0)
            {
                estimate    = buyerWorksheet.GetMatchingShipEstimate(supplierWorksheet?.LineItems?.FirstOrDefault()?.ShipFromAddressID);
                ship_method = estimate?.ShipMethods?.FirstOrDefault(m => m.ID == estimate.SelectedShipMethodID);
            }

            var returnObject = new JObject {
            };

            if (supplierWorksheet.Order != null)
            {
                returnObject.Add(new JProperty("SupplierOrder", new JObject {
                    { "Order", JToken.FromObject(supplierWorksheet?.Order) },
                    new JProperty("LineItems", JToken.FromObject(supplierWorksheet?.LineItems))
                }));
            }

            if (buyerWorksheet.Order != null)
            {
                returnObject.Add(new JProperty("BuyerOrder", new JObject {
                    { "Order", JToken.FromObject(buyerWorksheet?.Order) },
                    new JProperty("LineItems", JToken.FromObject(buyerLineItems))
                }));
            }

            if (ship_method != null)
            {
                returnObject.Add(new JProperty("ShipMethod", JToken.FromObject(ship_method)));
            }
            return(JObject.FromObject(returnObject));
        }
Exemplo n.º 11
0
        public async Task AutoApplyPromotions(string orderID)
        {
            try
            {
                await _oc.Orders.ValidateAsync(OrderDirection.Incoming, orderID);
            }
            catch (Exception ex)
            {
                await RemoveOrderPromotions(orderID);
            }

            var ocAuth = await _oc.AuthenticateAsync();

            var autoEligablePromos = await _oc.Promotions.ListAsync(filters : "xp.Automatic=true");

            await Throttler.RunAsync(autoEligablePromos.Items, 100, 5, promo =>
            {
                //  Not useing the sdk here because we need to ignore errors on promos that are not able to be
                //  applied to the order. We need to try this request on every automatic promo.
                return($"{_settings.OrderCloudSettings.ApiUrl}/v1/orders/Incoming/{orderID}/promotions/{promo.Code}"
                       .WithOAuthBearerToken(ocAuth.AccessToken)
                       .AllowAnyHttpStatus().PostAsync(null));
            });
        }