private async Task CreateBuyers(EnvironmentSeed seed, string token) { seed.Buyers.Add(new HSBuyer { Name = "Default HeadStart Buyer", Active = true, xp = new BuyerXp { MarkupPercent = 0 } }); foreach (var buyer in seed.Buyers) { var superBuyer = new SuperHSBuyer() { Buyer = buyer, Markup = new BuyerMarkup() { Percent = 0 } }; var exists = await BuyerExistsAsync(buyer.Name, token); if (!exists) { await _buyerCommand.Create(superBuyer, token, isSeedingEnvironment : true); } } }
private async Task CreateBuyers(EnvironmentSeed seed, VerifiedUserContext user) { seed.Buyers.Add(new HSBuyer { ID = "Default_HeadStart_Buyer", Name = "Default HeadStart Buyer", Active = true, xp = new BuyerXp { MarkupPercent = 0 } }); foreach (var buyer in seed.Buyers) { var superBuyer = new SuperHSBuyer() { Buyer = buyer, Markup = new BuyerMarkup() { Percent = 0 } }; await _buyerCommand.Create(superBuyer, user, isSeedingEnvironment : true); } }
private async Task CreateBuyers(EnvironmentSeed seed, string token) { var defaultBuyer = SeedConstants.DefaultBuyer(); seed.Buyers.Add(defaultBuyer); foreach (var buyer in seed.Buyers) { var superBuyer = new SuperHSBuyer() { Buyer = buyer, Markup = new BuyerMarkup() { Percent = 0 } }; var exists = await BuyerExistsAsync(buyer.Name, token); if (exists == null || exists.Count == 0) { var createdBuyer = await _buyerCommand.Create(superBuyer, token, _oc); if (createdBuyer.Buyer.Name == defaultBuyer.Name && seed.AnonymousShoppingBuyerID == null) { seed.AnonymousShoppingBuyerID = createdBuyer.Buyer.ID; } } else { seed.AnonymousShoppingBuyerID = exists.FirstOrDefault().ID; } } }
private async Task CreateOnlyOnceAnonBuyerConfig(EnvironmentSeed seed, string token) { // validate AnonymousShoppingBuyerID or provide fallback if none is defined var allBuyers = await _oc.Buyers.ListAllAsync(accessToken : token); if (seed.AnonymousShoppingBuyerID != null) { if (!allBuyers.Select(b => b.ID).Contains(seed.AnonymousShoppingBuyerID)) { throw new Exception("The buyer defined by AnonymousShoppingBuyerID does not exist"); } } else { seed.AnonymousShoppingBuyerID = SeedConstants.DefaultBuyerID; } //create and assign initial buyer location await _buyerLocationCommand.Save(seed.AnonymousShoppingBuyerID, $"{seed.AnonymousShoppingBuyerID}-{SeedConstants.DefaultLocationID}", SeedConstants.DefaultBuyerLocation(), token, _oc); // create user var anonBuyerUser = await _oc.Users.SaveAsync(seed.AnonymousShoppingBuyerID, SeedConstants.AnonymousBuyerUser().ID, SeedConstants.AnonymousBuyerUser(), token); // save assignment between user and buyergroup (location) var assignment = new UserGroupAssignment() { UserGroupID = $"{seed.AnonymousShoppingBuyerID}-{SeedConstants.DefaultLocationID}", UserID = anonBuyerUser.ID }; await _oc.UserGroups.SaveUserAssignmentAsync(seed.AnonymousShoppingBuyerID, assignment, accessToken : token); }
private async Task AssignSecurityProfiles(EnvironmentSeed seed, string orgToken) { // assign buyer security profiles var buyerSecurityProfileAssignmentRequests = seed.Buyers.Select(b => { return(_oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment { BuyerID = b.ID, SecurityProfileID = CustomRole.HSBaseBuyer.ToString() }, orgToken)); }); await Task.WhenAll(buyerSecurityProfileAssignmentRequests); // assign seller security profiles to seller org var sellerSecurityProfileAssignmentRequests = SeedConstants.SellerHsRoles.Select(role => { return(_oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment() { SecurityProfileID = role.ToString() }, orgToken)); }); await Task.WhenAll(sellerSecurityProfileAssignmentRequests); // assign full access security profile to default admin user var defaultAdminUser = (await _oc.AdminUsers.ListAsync(accessToken: orgToken)).Items.First(u => u.Username == SeedConstants.SellerUserName); await _oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment() { SecurityProfileID = SeedConstants.FullAccessSecurityProfile, UserID = defaultAdminUser.ID }, orgToken); }
private async Task CreateDefaultSellerUsers(EnvironmentSeed seed, string token) { // the middleware api client will use this user as the default context user var middlewareIntegrationsUser = new User { ID = "MiddlewareIntegrationsUser", Username = _sellerUserName, Email = "*****@*****.**", Active = true, FirstName = "Default", LastName = "User" }; await _oc.AdminUsers.SaveAsync(middlewareIntegrationsUser.ID, middlewareIntegrationsUser, token); // used to log in immediately after seeding the organization var initialAdminUser = new User { ID = "InitialAdminUser", Username = seed.InitialAdminUsername, Password = seed.InitialAdminPassword, Email = "*****@*****.**", Active = true, FirstName = "Initial", LastName = "User" }; await _oc.AdminUsers.SaveAsync(initialAdminUser.ID, initialAdminUser, token); }
public async Task CreateSecurityProfiles(EnvironmentSeed seed, string accessToken) { var profiles = DefaultSecurityProfiles.Select(p => new SecurityProfile() { Name = p.CustomRole.ToString(), ID = p.CustomRole.ToString(), CustomRoles = p.CustomRoles == null ? new List <string>() { p.CustomRole.ToString() } : p.CustomRoles.Append(p.CustomRole).Select(r => r.ToString()).ToList(), Roles = p.Roles }).ToList(); profiles.Add(new SecurityProfile() { Roles = new List <ApiRole> { ApiRole.FullAccess }, Name = _fullAccessSecurityProfile, ID = _fullAccessSecurityProfile }); var profileCreateRequests = profiles.Select(p => _oc.SecurityProfiles.CreateAsync(p, accessToken)); await Task.WhenAll(profileCreateRequests); }
private async Task CreateSuppliers(VerifiedUserContext user, EnvironmentSeed seed, string token) { // Create Suppliers and necessary user groups and security profile assignments foreach (HSSupplier supplier in seed.Suppliers) { await _supplierCommand.Create(supplier, user, isSeedingEnvironment : true); } }
private async Task CreateOnlyOnceApiClients(EnvironmentSeed seed, string token) { var existingClients = await _oc.ApiClients.ListAllAsync(accessToken : token); await CreateOrGetBuyerClient(existingClients, SeedConstants.BuyerClient(seed), seed, token); await CreateOrGetApiClient(existingClients, SeedConstants.IntegrationsClient(), token); await CreateOrGetApiClient(existingClients, SeedConstants.SellerClient(), token); await CreateOrGetApiClient(existingClients, SeedConstants.BuyerLocalClient(seed), token); }
public static MessageSender SuplierEmails(EnvironmentSeed seed) { return(new MessageSender() { ID = "SupplierEmails", Name = "Supplier Emails", MessageTypes = new[] { MessageType.ForgottenPassword, }, URL = seed.MiddlewareBaseUrl + "/messagesenders/{messagetype}", SharedKey = seed.OrderCloudSettings.WebhookHashKey }); }
private async Task CreateSuppliers(EnvironmentSeed seed, string token) { // Create Suppliers and necessary user groups and security profile assignments foreach (HSSupplier supplier in seed.Suppliers) { var exists = await SupplierExistsAsync(supplier.Name, token); if (!exists) { await _supplierCommand.Create(supplier, token, isSeedingEnvironment : true); } } }
public static ApiClient BuyerLocalClient(EnvironmentSeed seed) { return(new ApiClient() { AppName = BuyerLocalApiClientName, Active = true, AllowAnyBuyer = true, AllowAnySupplier = false, AllowSeller = false, AccessTokenDuration = 600, RefreshTokenDuration = 43200, DefaultContextUserName = seed.EnableAnonymousShopping ? AnonymousBuyerUser().ID : null, IsAnonBuyer = seed.EnableAnonymousShopping }); }
private async Task CreateMessageSenders(EnvironmentSeed seed, string accessToken) { var defaultMessageSenders = new List <MessageSender>() { SeedConstants.BuyerEmails(_settings), SeedConstants.SellerEmails(_settings), SeedConstants.SuplierEmails(_settings) }; foreach (var sender in defaultMessageSenders) { var messageSender = await _oc.MessageSenders.SaveAsync(sender.ID, sender, accessToken); if (messageSender.ID == "BuyerEmails") { foreach (var buyer in seed.Buyers) { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, BuyerID = buyer.ID }, accessToken); } } else if (messageSender.ID == "SellerEmails") { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID }, accessToken); } catch (Exception ex) { } } else if (messageSender.ID == "SupplierEmails") { foreach (var supplier in seed.Suppliers) { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, SupplierID = supplier.ID }, accessToken); } } } }
public async Task <string> Seed(EnvironmentSeed seed) { if (string.IsNullOrEmpty(_settings.OrderCloudSettings.ApiUrl)) { throw new Exception("Missing required app setting OrderCloudSettings:ApiUrl"); } if (string.IsNullOrEmpty(_settings.OrderCloudSettings.WebhookHashKey)) { throw new Exception("Missing required app setting OrderCloudSettings:WebhookHashKey"); } if (string.IsNullOrEmpty(_settings.EnvironmentSettings.BaseUrl)) { throw new Exception("Missing required app setting EnvironmentSettings:BaseUrl"); } var portalUserToken = await _portal.Login(seed.PortalUsername, seed.PortalPassword); await VerifyOrgExists(seed.SellerOrgID, portalUserToken); var orgToken = await _portal.GetOrgToken(seed.SellerOrgID, portalUserToken); await CreateDefaultSellerUser(orgToken); await CreateApiClients(orgToken); await CreateSecurityProfiles(seed, orgToken); await AssignSecurityProfiles(seed, orgToken); var apiClients = await GetApiClients(orgToken); await CreateWebhooks(new string[] { apiClients.BuyerUiApiClient.ID }, apiClients.AdminUiApiClient.ID, orgToken); await CreateMessageSenders(orgToken); await CreateIncrementors(orgToken); // must be before CreateBuyers var userContext = await GetVerifiedUserContext(apiClients.MiddlewareApiClient); await CreateBuyers(seed, userContext); await CreateXPIndices(orgToken); await CreateAndAssignIntegrationEvents(new string[] { apiClients.BuyerUiApiClient.ID }, apiClients.BuyerLocalUiApiClient.ID, orgToken); await CreateSuppliers(userContext, seed, orgToken); await CreateContentDocSchemas(userContext); await CreateDefaultContentDocs(userContext); return(orgToken); }
private async Task CreateConfigureAnonBuyer(EnvironmentSeed seed, string token) { var anonBuyer = SeedConstants.AnonymousBuyerUser(); var defaultBuyer = SeedConstants.DefaultBuyer(); //create anonymous buyer user var createUser = _oc.Users.SaveAsync(seed.AnonymousShoppingBuyerID, anonBuyer.ID, anonBuyer, token); //create and assign initial buyer location var createBuyerLocation = _buyerLocationCommand.Save(seed.AnonymousShoppingBuyerID, $"{seed.AnonymousShoppingBuyerID}-{SeedConstants.DefaultLocationID}", SeedConstants.DefaultBuyerLocation(), token, true); var assignment = new UserGroupAssignment() { UserGroupID = $"{seed.AnonymousShoppingBuyerID}-{SeedConstants.DefaultLocationID}", UserID = anonBuyer.ID }; var saveAssignment = _oc.UserGroups.SaveUserAssignmentAsync(seed.AnonymousShoppingBuyerID, assignment, token); await Task.WhenAll(createUser, createBuyerLocation, saveAssignment); }
public static MessageSender BuyerEmails(EnvironmentSeed seed) { return(new MessageSender() { ID = "BuyerEmails", Name = "Buyer Emails", MessageTypes = new[] { MessageType.ForgottenPassword, MessageType.NewUserInvitation, MessageType.OrderApproved, MessageType.OrderDeclined, // MessageType.OrderSubmitted, this is currently being handled in PostOrderSubmitCommand, possibly move to message senders MessageType.OrderSubmittedForApproval, // MessageType.OrderSubmittedForYourApprovalHasBeenApproved, // too noisy // MessageType.OrderSubmittedForYourApprovalHasBeenDeclined, // too noisy // MessageType.ShipmentCreated this is currently being triggered in-app possibly move to message senders }, URL = seed.MiddlewareBaseUrl + "/messagesenders/{messagetype}", SharedKey = seed.OrderCloudSettings.WebhookHashKey }); }
private async Task CreateOnlyOnceBuyers(EnvironmentSeed seed, string token) { // create default buyer if it does not exist // default buyer will have a well-known ID we can use to query with var defaultBuyer = await GetBuyerByID(SeedConstants.DefaultBuyerID, token); if (defaultBuyer == null) { var superBuyer = new SuperHSBuyer() { Buyer = SeedConstants.DefaultBuyer(), Markup = new BuyerMarkup() { Percent = 0 } }; await _buyerCommand.Create(superBuyer, token, _oc); } // create seed buyers if they don't exist // seed buyers may not have ID defined, we are relying on Name instead foreach (var buyer in seed.Buyers) { var seedBuyer = await GetBuyerByName(buyer.Name, token); if (seedBuyer == null) { var superBuyer = new SuperHSBuyer() { Buyer = buyer, Markup = new BuyerMarkup() { Percent = 0 } }; await _buyerCommand.Create(superBuyer, token, _oc); } } }
private async Task CreateOrUpdateSecurityProfileAssignments(EnvironmentSeed seed, string orgToken) { // assign buyer security profiles var buyerSecurityProfileAssignmentRequests = seed.Buyers.Select(b => { return(_oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment { BuyerID = b.ID, SecurityProfileID = CustomRole.HSBaseBuyer.ToString() }, orgToken)); }); await Task.WhenAll(buyerSecurityProfileAssignmentRequests); // assign seller security profiles to seller org var sellerSecurityProfileAssignmentRequests = SeedConstants.SellerHsRoles.Select(role => { return(_oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment() { SecurityProfileID = role.ToString() }, orgToken)); }); await Task.WhenAll(sellerSecurityProfileAssignmentRequests); // assign full access security profile to default admin user var adminUsersList = await _oc.AdminUsers.ListAsync(filters : new { Username = SeedConstants.SellerUserName }, accessToken : orgToken); var defaultAdminUser = adminUsersList.Items.FirstOrDefault(); if (defaultAdminUser == null) { throw new Exception($"Unable to find default admin user (username: {SeedConstants.SellerUserName}"); } await _oc.SecurityProfiles.SaveAssignmentAsync(new SecurityProfileAssignment() { SecurityProfileID = SeedConstants.FullAccessSecurityProfile, UserID = defaultAdminUser.ID }, orgToken); }
private async Task CreateMessageSenders(EnvironmentSeed seed, string accessToken) { foreach (var sender in DefaultMessageSenders()) { var messageSender = await _oc.MessageSenders.SaveAsync(sender.ID, sender, accessToken); if (messageSender.ID == "BuyerEmails") { foreach (var buyer in seed.Buyers) { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, BuyerID = buyer.ID }, accessToken); } } else if (messageSender.ID == "SellerEmails") { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID }, accessToken); } else if (messageSender.ID == "SupplierEmails") { foreach (var supplier in seed.Suppliers) { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, SupplierID = supplier.ID }, accessToken); } } } }
private async Task CreateOrUpdateAndAssignIntegrationEvents(string token, EnvironmentSeed seed = null) { var storefrontApiClientIDs = await GetStoreFrontClientIDs(token); var apiClients = await GetApiClients(token); var localBuyerClientID = apiClients.BuyerLocalUiApiClient.ID; // this gets called by both the /seed command and the post-staging restore so we need to handle getting settings from two sources var middlewareBaseUrl = seed != null ? seed.MiddlewareBaseUrl : _settings.EnvironmentSettings.MiddlewareBaseUrl; var webhookHashKey = seed != null ? seed.OrderCloudSettings.WebhookHashKey : _settings.OrderCloudSettings.WebhookHashKey; var checkoutEvent = SeedConstants.CheckoutEvent(middlewareBaseUrl, webhookHashKey); await _oc.IntegrationEvents.SaveAsync(checkoutEvent.ID, checkoutEvent, token); var localCheckoutEvent = SeedConstants.LocalCheckoutEvent(webhookHashKey); await _oc.IntegrationEvents.SaveAsync(localCheckoutEvent.ID, localCheckoutEvent, token); await _oc.ApiClients.PatchAsync(localBuyerClientID, new PartialApiClient { OrderCheckoutIntegrationEventID = "HeadStartCheckoutLOCAL" }, token); await Throttler.RunAsync(storefrontApiClientIDs, 500, 20, clientID => _oc.ApiClients.PatchAsync(clientID, new PartialApiClient { OrderCheckoutIntegrationEventID = "HeadStartCheckout" }, token)); }
private async Task CreateMessageSenders(EnvironmentSeed seed, string accessToken) { var defaultMessageSenders = new List <MessageSender>() { SeedConstants.BuyerEmails(seed), SeedConstants.SellerEmails(seed), SeedConstants.SuplierEmails(seed) }; foreach (var sender in defaultMessageSenders) { var messageSender = await _oc.MessageSenders.SaveAsync(sender.ID, sender, accessToken); if (messageSender.ID == "BuyerEmails") { foreach (var buyer in seed.Buyers) { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, BuyerID = buyer.ID }, accessToken); } catch (OrderCloudException ex) { if (ex.HttpStatus != HttpStatusCode.Conflict) // this is a bug in the api https://four51.atlassian.net/browse/EX-2210 { throw ex; } } } } else if (messageSender.ID == "SellerEmails") { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID }, accessToken); } catch (OrderCloudException ex) { if (ex.HttpStatus != HttpStatusCode.Conflict) // this is a bug in the api https://four51.atlassian.net/browse/EX-2210 { throw ex; } } } else if (messageSender.ID == "SupplierEmails") { foreach (var supplier in seed.Suppliers) { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, SupplierID = supplier.ID }, accessToken); } catch (OrderCloudException ex) { if (ex.HttpStatus != HttpStatusCode.Conflict) // this is a bug in the api https://four51.atlassian.net/browse/EX-2210 { throw ex; } } } } } }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserSeed userSeed, RoleSeed roleSeed, LevelSeed levelSeed, EnvironmentSeed environmentSeed, LogSeed logSeed, EventSeed eventSeed) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); userSeed.Populate(); roleSeed.Populate(); levelSeed.Populate(); environmentSeed.Populate(); logSeed.Populate(); eventSeed.Populate(); } app.UseSwaggerSetup(); app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(c => { c.AllowAnyHeader(); c.AllowAnyMethod(); c.AllowAnyOrigin(); }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
/// <summary> /// This seeding function can be used to initially seed an marketplace /// it is also meant to be safe to call after an marketplace has been seeded (by including seed.MarketplaceID) /// If a method starts with CreateOrUpdate it will update the resource every time its called based on what has been defined in SeedConstants.cs /// If a method starts with CreateOnlyOnce it will only create the resource once and then ignore thereafter /// The CreateOnlyOnce resources are likely to change after initial creation so we ignore to avoid overwriting desired changes that happen outside of seeding /// </summary> public async Task <EnvironmentSeedResponse> Seed(EnvironmentSeed seed) { OcEnv requestedEnv = validateEnvironment(seed.OrderCloudSettings.Environment); if (requestedEnv.environmentName == OrderCloudEnvironments.Production.environmentName && seed.MarketplaceID == null) { throw new Exception("Cannot create a production environment via the environment seed endpoint. Please contact an OrderCloud Developer to create a production marketplace."); } // lets us handle requests to multiple api environments _oc = new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = requestedEnv.apiUrl, AuthUrl = requestedEnv.apiUrl }); var portalUserToken = await _portal.Login(seed.PortalUsername, seed.PortalPassword); var marketplace = await GetOrCreateMarketplace(portalUserToken, requestedEnv.environmentName, seed.MarketplaceName, seed.MarketplaceID); var marketplaceToken = await _portal.GetMarketplaceToken(marketplace.Id, portalUserToken); await CreateOrUpdateDefaultSellerUser(seed, marketplaceToken); await CreateOnlyOnceIncrementors(marketplaceToken); // must be before CreateBuyers await CreateOrUpdateMessageSendersAndAssignments(seed, marketplaceToken); // must be before CreateBuyers and CreateSuppliers await CreateOrUpdateSecurityProfiles(marketplaceToken); await CreateOnlyOnceBuyers(seed, marketplaceToken); await CreateOnlyOnceApiClients(seed, marketplaceToken); await CreateOrUpdateSecurityProfileAssignments(seed, marketplaceToken); await CreateOrUpdateXPIndices(marketplaceToken); await CreateOrUpdateAndAssignIntegrationEvents(marketplaceToken, seed); await CreateOrUpdateSuppliers(seed, marketplaceToken); await CreateOrUpdateProductFacets(marketplaceToken); if (seed?.StorageAccountSettings?.ConnectionString != null && seed?.StorageAccountSettings?.ContainerNameTranslations != null) { await UpdateTranslations(seed.StorageAccountSettings.ConnectionString, seed.StorageAccountSettings.ContainerNameTranslations); } var apiClients = await GetApiClients(marketplaceToken); return(new EnvironmentSeedResponse { Comments = "Success! Your environment is now seeded. The following clientIDs & secrets should be used to finalize the configuration of your application. The initial admin username and password can be used to sign into your admin application", MarketplaceName = marketplace.Name, MarketplaceID = marketplace.Id, OrderCloudEnvironment = requestedEnv.environmentName, ApiClients = new Dictionary <string, dynamic> { ["Middleware"] = new { ClientID = apiClients.MiddlewareApiClient.ID, ClientSecret = apiClients.MiddlewareApiClient.ClientSecret }, ["Seller"] = new { ClientID = apiClients.AdminUiApiClient.ID }, ["Buyer"] = new { ClientID = apiClients.BuyerUiApiClient.ID } } }); }
public async Task <EnvironmentSeedResponse> Seed(EnvironmentSeed seed) { if (string.IsNullOrEmpty(_settings.OrderCloudSettings.ApiUrl)) { throw new Exception("Missing required app setting OrderCloudSettings:ApiUrl"); } if (string.IsNullOrEmpty(_settings.OrderCloudSettings.WebhookHashKey)) { throw new Exception("Missing required app setting OrderCloudSettings:WebhookHashKey"); } if (string.IsNullOrEmpty(_settings.EnvironmentSettings.MiddlewareBaseUrl)) { throw new Exception("Missing required app setting EnvironmentSettings:MiddlewareBaseUrl"); } var portalUserToken = await _portal.Login(seed.PortalUsername, seed.PortalPassword); await VerifyOrgExists(seed.SellerOrgID, portalUserToken); var orgToken = await _portal.GetOrgToken(seed.SellerOrgID, portalUserToken); await CreateDefaultSellerUsers(seed, orgToken); await CreateIncrementors(orgToken); // must be before CreateBuyers await CreateMessageSenders(seed, orgToken); // must be before CreateBuyers and CreateSuppliers await CreateSecurityProfiles(orgToken); await CreateBuyers(seed, orgToken); await CreateConfigureAnonBuyer(seed, orgToken); await CreateApiClients(orgToken); await AssignSecurityProfiles(seed, orgToken); var apiClients = await GetApiClients(orgToken); await CreateXPIndices(orgToken); await CreateAndAssignIntegrationEvents(new string[] { apiClients.BuyerUiApiClient.ID }, apiClients.BuyerLocalUiApiClient.ID, orgToken); await CreateSuppliers(seed, orgToken); // populates exchange rates into blob container name: settings.BlobSettings.ContainerNameExchangeRates or "currency" if setting is not defined await _exhangeRates.Update(); // populate default english translations into blob container name: settings.BlobSettings.ContainerNameTranslations or "ngx-translate" if setting is not defined // provide other language files to support multiple languages var currentDirectory = Directory.GetCurrentDirectory(); var englishTranslationsPath = Path.GetFullPath(Path.Combine(currentDirectory, @"..\Headstart.Common\Assets\english-translations.json")); await _translationsBlob.Save("i18n/en.json", File.ReadAllText(englishTranslationsPath)); return(new EnvironmentSeedResponse { Comments = "Success! Your environment is now seeded. The following clientIDs & secrets should be used to finalize the configuration of your application. The initial admin username and password can be used to sign into your admin application", ApiClients = new Dictionary <string, dynamic> { ["Middleware"] = new { ClientID = apiClients.MiddlewareApiClient.ID, ClientSecret = apiClients.MiddlewareApiClient.ClientSecret }, ["Seller"] = new { ClientID = apiClients.AdminUiApiClient.ID }, ["Buyer"] = new { ClientID = apiClients.BuyerUiApiClient.ID } } }); }
private async Task CreateOrUpdateMessageSendersAndAssignments(EnvironmentSeed seed, string accessToken) { var defaultMessageSenders = new List <MessageSender>() { SeedConstants.BuyerEmails(seed), SeedConstants.SellerEmails(seed), SeedConstants.SuplierEmails(seed) }; var existingMessageSenders = await _oc.MessageSenders.ListAllAsync(accessToken : accessToken); foreach (var sender in defaultMessageSenders) { var messageSender = await GetOrCreateMessageSender(existingMessageSenders, sender, accessToken); if (messageSender.ID == "BuyerEmails") { var allBuyers = await _oc.Buyers.ListAllAsync(accessToken : accessToken); foreach (var buyer in allBuyers) { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, BuyerID = buyer.ID }, accessToken); } catch (OrderCloudException ex) { // this is a bug in the api PUTs should never return 409s so ignore those errors // https://four51.atlassian.net/browse/EX-2210 if (ex.HttpStatus != HttpStatusCode.Conflict) { throw ex; } } } } else if (messageSender.ID == "SellerEmails") { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID }, accessToken); } catch (OrderCloudException ex) { // this is a bug in the api PUTs should never return 409s so ignore those errors // https://four51.atlassian.net/browse/EX-2210 if (ex.HttpStatus != HttpStatusCode.Conflict) { throw ex; } } } else if (messageSender.ID == "SupplierEmails") { var allSuppliers = await _oc.Suppliers.ListAllAsync(accessToken : accessToken); foreach (var supplier in allSuppliers) { try { await _oc.MessageSenders.SaveAssignmentAsync(new MessageSenderAssignment { MessageSenderID = messageSender.ID, SupplierID = supplier.ID }, accessToken); } catch (OrderCloudException ex) { // this is a bug in the api PUTs should never return 409s so ignore those errors // https://four51.atlassian.net/browse/EX-2210 if (ex.HttpStatus != HttpStatusCode.Conflict) { throw ex; } } } } } }
private async Task <ApiClient> CreateOrGetBuyerClient(List <ApiClient> existingClients, ApiClient client, EnvironmentSeed seed, string token) { var match = existingClients.FirstOrDefault(c => c.AppName == client.AppName); if (match == null) { await CreateOnlyOnceAnonBuyerConfig(seed, token); var apiClient = await _oc.ApiClients.CreateAsync(client, token); return(apiClient); } return(match); }
public async Task Seed([FromBody] EnvironmentSeed seed) { await _command.Seed(seed); }
public async Task <EnvironmentSeedResponse> Seed(EnvironmentSeed seed) { OcEnv requestedEnv = validateEnvironment(seed.OrderCloudSettings.Environment); if (requestedEnv.environmentName == OrderCloudEnvironments.Production.environmentName && seed.SellerOrgID == null) { throw new Exception("Cannot create a production environment via the environment seed endpoint. Please contact an OrderCloud Developer to create a production org."); } // lets us handle requests to multiple api environments _oc = new OrderCloudClient(new OrderCloudClientConfig { ApiUrl = requestedEnv.apiUrl, AuthUrl = requestedEnv.apiUrl }); var portalUserToken = await _portal.Login(seed.PortalUsername, seed.PortalPassword); var sellerOrg = await GetOrCreateOrg(portalUserToken, requestedEnv.environmentName, seed.SellerOrgName, seed.SellerOrgID); var orgToken = await _portal.GetOrgToken(sellerOrg.Id, portalUserToken); await CreateDefaultSellerUsers(seed, orgToken); await CreateIncrementors(orgToken); // must be before CreateBuyers await CreateMessageSenders(seed, orgToken); // must be before CreateBuyers and CreateSuppliers await CreateSecurityProfiles(orgToken); await CreateBuyers(seed, orgToken); await CreateConfigureAnonBuyer(seed, orgToken); await CreateApiClients(orgToken); await AssignSecurityProfiles(seed, orgToken); var apiClients = await GetApiClients(orgToken); await CreateXPIndices(orgToken); await CreateAndAssignIntegrationEvents(new string[] { apiClients.BuyerUiApiClient.ID }, apiClients.BuyerLocalUiApiClient.ID, orgToken, seed); await CreateSuppliers(seed, orgToken); // populate default english translations into blob container name: settings.BlobSettings.ContainerNameTranslations or "ngx-translate" if setting is not defined // provide other language files to support multiple languages var englishTranslationsPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "Assets", "english-translations.json")); if (seed?.BlobSettings?.ConnectionString != null && seed?.BlobSettings?.ContainerNameTranslations != null) { var translationsConfig = new BlobServiceConfig() { ConnectionString = seed.BlobSettings.ConnectionString, Container = seed.BlobSettings.ContainerNameTranslations, AccessType = BlobContainerPublicAccessType.Container }; var translationsBlob = new OrderCloudIntegrationsBlobService(translationsConfig); await translationsBlob.Save("i18n/en.json", File.ReadAllText(englishTranslationsPath)); } return(new EnvironmentSeedResponse { Comments = "Success! Your environment is now seeded. The following clientIDs & secrets should be used to finalize the configuration of your application. The initial admin username and password can be used to sign into your admin application", OrganizationName = sellerOrg.Name, OrganizationID = sellerOrg.Id, OrderCloudEnvironment = requestedEnv.environmentName, ApiClients = new Dictionary <string, dynamic> { ["Middleware"] = new { ClientID = apiClients.MiddlewareApiClient.ID, ClientSecret = apiClients.MiddlewareApiClient.ClientSecret }, ["Seller"] = new { ClientID = apiClients.AdminUiApiClient.ID }, ["Buyer"] = new { ClientID = apiClients.BuyerUiApiClient.ID } } }); }
public async Task <EnvironmentSeedResponse> Seed([FromBody] EnvironmentSeed seed) { return(await _command.Seed(seed)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserSeed userSeed, LogLevelSeed levelSeed, EnvironmentSeed environmentSeed) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); userSeed.Populate(); levelSeed.Populate(); environmentSeed.Populate(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/v1/swagger.json", "CadeOErro API")); }