From 537b9d854ff530c6931ac56fc211002368364f85 Mon Sep 17 00:00:00 2001 From: Brian Moyles <157126600+BrianMoyles@users.noreply.github.com> Date: Thu, 18 Jul 2024 22:44:36 +0100 Subject: [PATCH] Feat/devtooling 655: conversations_messaging_settings resource (#1150) * Created Resource * Created Resource & added tests * Added examples * Update tf_exporter_resource_test.go --- .../conversations_messaging_settings.md | 30 +++ .../conversations_messaging_settings.md | 116 +++++++++ .../data-source.tf | 3 + .../apis.md | 5 + .../resource.tf | 21 ++ ...source_conversations_messaging_settings.go | 32 +++ ...e_conversations_messaging_settings_test.go | 55 +++++ ...versations_messaging_settings_init_test.go | 54 +++++ ..._conversations_messaging_settings_proxy.go | 170 +++++++++++++ ...source_conversations_messaging_settings.go | 128 ++++++++++ ...conversations_messaging_settings_schema.go | 163 +++++++++++++ ...e_conversations_messaging_settings_test.go | 144 +++++++++++ ..._conversations_messaging_settings_utils.go | 225 ++++++++++++++++++ .../resource_genesyscloud_init_test.go | 6 +- .../tfexporter/tf_exporter_resource_test.go | 5 +- main.go | 8 +- 16 files changed, 1160 insertions(+), 5 deletions(-) create mode 100644 docs/data-sources/conversations_messaging_settings.md create mode 100644 docs/resources/conversations_messaging_settings.md create mode 100644 examples/data-sources/genesyscloud_conversations_messaging_settings/data-source.tf create mode 100644 examples/resources/genesyscloud_conversations_messaging_settings/apis.md create mode 100644 examples/resources/genesyscloud_conversations_messaging_settings/resource.tf create mode 100644 genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings.go create mode 100644 genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings_test.go create mode 100644 genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_init_test.go create mode 100644 genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_proxy.go create mode 100644 genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings.go create mode 100644 genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_schema.go create mode 100644 genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_test.go create mode 100644 genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_utils.go diff --git a/docs/data-sources/conversations_messaging_settings.md b/docs/data-sources/conversations_messaging_settings.md new file mode 100644 index 000000000..d093dd0ed --- /dev/null +++ b/docs/data-sources/conversations_messaging_settings.md @@ -0,0 +1,30 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "genesyscloud_conversations_messaging_settings Data Source - terraform-provider-genesyscloud" +subcategory: "" +description: |- + Genesys Cloud conversations messaging settings data source. Select an conversations messaging settings by name +--- + +# genesyscloud_conversations_messaging_settings (Data Source) + +Genesys Cloud conversations messaging settings data source. Select an conversations messaging settings by name + +## Example Usage + +```terraform +data "genesyscloud_conversations_messaging_settings" "example-messaging-settings" { + name = "settings name" +} +``` + + +## Schema + +### Required + +- `name` (String) conversations messaging settings name + +### Read-Only + +- `id` (String) The ID of this resource. diff --git a/docs/resources/conversations_messaging_settings.md b/docs/resources/conversations_messaging_settings.md new file mode 100644 index 000000000..b2a86a76b --- /dev/null +++ b/docs/resources/conversations_messaging_settings.md @@ -0,0 +1,116 @@ +--- +page_title: "genesyscloud_conversations_messaging_settings Resource - terraform-provider-genesyscloud" +subcategory: "" +description: |- + Genesys Cloud conversations messaging settings +--- +# genesyscloud_conversations_messaging_settings (Resource) + +Genesys Cloud conversations messaging settings + +## API Usage +The following Genesys Cloud APIs are used by this resource. Ensure your OAuth Client has been granted the necessary scopes and permissions to perform these operations: + +* [GET /api/v2/conversations/messaging/settings](https://developer.genesys.cloud/devapps/api-explorer#get-api-v2-conversations-messaging-settings) +* [POST /api/v2/conversations/messaging/settings](https://developer.genesys.cloud/devapps/api-explorer#post-api-v2-conversations-messaging-settings) +* [GET /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#get-api-v2-conversations-messaging-settings--messageSettingId-) +* [PATCH /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#patch-api-v2-conversations-messaging-settings--messageSettingId-) +* [DELETE /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#delete-api-v2-conversations-messaging-settings--messageSettingId-) + +## Example Usage + +```terraform +resource "genesyscloud_conversations_messaging_settings" "example-messaging-settings" { + name = "Sample Messaging Settings" + content { + story { + mention { + inbound = "Enabled" + } + reply { + inbound = "Enabled" + } + } + } + event { + typing { + on { + inbound = "Enabled" + outbound = "Enabled" + } + } + } +} +``` + + +## Schema + +### Required + +- `name` (String) The messaging Setting profile name + +### Optional + +- `content` (Block List, Max: 1) Settings relating to message contents (see [below for nested schema](#nestedblock--content)) +- `event` (Block List, Max: 1) Settings relating to events which may occur (see [below for nested schema](#nestedblock--event)) + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `content` + +Optional: + +- `story` (Block List, Max: 1) Settings relating to facebook and instagram stories feature (see [below for nested schema](#nestedblock--content--story)) + + +### Nested Schema for `content.story` + +Optional: + +- `mention` (Block List, Max: 1) Setting relating to Story Mentions (see [below for nested schema](#nestedblock--content--story--mention)) +- `reply` (Block List, Max: 1) Setting relating to Story Replies (see [below for nested schema](#nestedblock--content--story--reply)) + + +### Nested Schema for `content.story.mention` + +Optional: + +- `inbound` (String) Valid values: Enabled, Disabled. + + + +### Nested Schema for `content.story.reply` + +Optional: + +- `inbound` (String) Valid values: Enabled, Disabled. + + + + + +### Nested Schema for `event` + +Optional: + +- `typing` (Block List, Max: 1) Settings regarding typing events (see [below for nested schema](#nestedblock--event--typing)) + + +### Nested Schema for `event.typing` + +Optional: + +- `on` (Block List, Max: 1) Should typing indication Events be sent (see [below for nested schema](#nestedblock--event--typing--on)) + + +### Nested Schema for `event.typing.on` + +Optional: + +- `inbound` (String) Status for the Inbound Direction. Valid values: Enabled, Disabled. +- `outbound` (String) Status for the outbound Direction. Valid values: Enabled, Disabled. + diff --git a/examples/data-sources/genesyscloud_conversations_messaging_settings/data-source.tf b/examples/data-sources/genesyscloud_conversations_messaging_settings/data-source.tf new file mode 100644 index 000000000..b1f4d48b1 --- /dev/null +++ b/examples/data-sources/genesyscloud_conversations_messaging_settings/data-source.tf @@ -0,0 +1,3 @@ +data "genesyscloud_conversations_messaging_settings" "example-messaging-settings" { + name = "settings name" +} \ No newline at end of file diff --git a/examples/resources/genesyscloud_conversations_messaging_settings/apis.md b/examples/resources/genesyscloud_conversations_messaging_settings/apis.md new file mode 100644 index 000000000..9f6c3fe3e --- /dev/null +++ b/examples/resources/genesyscloud_conversations_messaging_settings/apis.md @@ -0,0 +1,5 @@ +* [GET /api/v2/conversations/messaging/settings](https://developer.genesys.cloud/devapps/api-explorer#get-api-v2-conversations-messaging-settings) +* [POST /api/v2/conversations/messaging/settings](https://developer.genesys.cloud/devapps/api-explorer#post-api-v2-conversations-messaging-settings) +* [GET /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#get-api-v2-conversations-messaging-settings--messageSettingId-) +* [PATCH /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#patch-api-v2-conversations-messaging-settings--messageSettingId-) +* [DELETE /api/v2/conversations/messaging/settings/{messageSettingId}](https://developer.genesys.cloud/devapps/api-explorer#delete-api-v2-conversations-messaging-settings--messageSettingId-) \ No newline at end of file diff --git a/examples/resources/genesyscloud_conversations_messaging_settings/resource.tf b/examples/resources/genesyscloud_conversations_messaging_settings/resource.tf new file mode 100644 index 000000000..d80fe743a --- /dev/null +++ b/examples/resources/genesyscloud_conversations_messaging_settings/resource.tf @@ -0,0 +1,21 @@ +resource "genesyscloud_conversations_messaging_settings" "example-messaging-settings" { + name = "Sample Messaging Settings" + content { + story { + mention { + inbound = "Enabled" + } + reply { + inbound = "Enabled" + } + } + } + event { + typing { + on { + inbound = "Enabled" + outbound = "Enabled" + } + } + } +} \ No newline at end of file diff --git a/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings.go b/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings.go new file mode 100644 index 000000000..853421688 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings.go @@ -0,0 +1,32 @@ +package conversations_messaging_settings + +import ( + "context" + "fmt" + "terraform-provider-genesyscloud/genesyscloud/provider" + "terraform-provider-genesyscloud/genesyscloud/util" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +func dataSourceConversationsMessagingSettingsRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics { + sdkConfig := m.(*provider.ProviderMeta).ClientConfig + proxy := getConversationsMessagingSettingsProxy(sdkConfig) + name := d.Get("name").(string) + + return util.WithRetries(ctx, 15*time.Second, func() *retry.RetryError { + messageSettingsId, resp, retryable, err := proxy.getConversationsMessagingSettingsIdByName(ctx, name) + if err != nil && !retryable { + return retry.NonRetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("error requesting conversations messaging setting by name %s | error: %s", name, err), resp)) + } + + if retryable { + return retry.RetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("no conversations messaging setting found with name %s", name), resp)) + } + d.SetId(messageSettingsId) + return nil + }) +} diff --git a/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings_test.go b/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings_test.go new file mode 100644 index 000000000..19f88cd25 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/data_source_conversations_messaging_settings_test.go @@ -0,0 +1,55 @@ +package conversations_messaging_settings + +import ( + "fmt" + "terraform-provider-genesyscloud/genesyscloud/provider" + "terraform-provider-genesyscloud/genesyscloud/util" + "testing" + + "github.com/google/uuid" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccDataSourceConversationsMessagingSettings(t *testing.T) { + var ( + id = "conversations_messaging_settings" + dataId = "conversations_messaging_settings_data" + name = "Messaging Settings " + uuid.NewString() + ) + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + ProviderFactories: provider.GetProviderFactories(providerResources, providerDataSources), + Steps: []resource.TestStep{ + { + Config: generateConversationsMessagingSettingsResource( + id, + name, + generateContentStoryBlock( + generateMentionInboundOnlySetting("Enabled"), + generateReplyInboundOnlySetting("Enabled"), + ), + generateTypingOnSetting( + "Enabled", + "Disabled", + ), + ) + generateConversationsMessagingSettingsDataSource( + dataId, + name, + "genesyscloud_conversations_messaging_settings."+id, + ), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("data.genesyscloud_conversations_messaging_settings."+dataId, "id", + "genesyscloud_conversations_messaging_settings."+id, "id"), + ), + }, + }, + }) +} + +func generateConversationsMessagingSettingsDataSource(id, name, dependsOn string) string { + return fmt.Sprintf(`data "genesyscloud_conversations_messaging_settings" "%s" { + name = "%s" + depends_on = [%s] + } +`, id, name, dependsOn) +} diff --git a/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_init_test.go b/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_init_test.go new file mode 100644 index 000000000..7d372594f --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_init_test.go @@ -0,0 +1,54 @@ +package conversations_messaging_settings + +import ( + "sync" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +var providerDataSources map[string]*schema.Resource + +// providerResources holds a map of all registered resources +var providerResources map[string]*schema.Resource + +type registerTestInstance struct { + resourceMapMutex sync.RWMutex + datasourceMapMutex sync.RWMutex +} + +// registerTestResources registers all resources used in the tests +func (r *registerTestInstance) registerTestResources() { + r.resourceMapMutex.Lock() + defer r.resourceMapMutex.Unlock() + + providerResources[resourceName] = ResourceConversationsMessagingSettings() +} + +// registerTestDataSources registers all data sources used in the tests. +func (r *registerTestInstance) registerTestDataSources() { + r.datasourceMapMutex.Lock() + defer r.datasourceMapMutex.Unlock() + + providerDataSources[resourceName] = DataSourceConversationsMessagingSettings() +} + +// initTestResources initializes all test resources and data sources. +func initTestResources() { + providerDataSources = make(map[string]*schema.Resource) + providerResources = make(map[string]*schema.Resource) + + regInstance := ®isterTestInstance{} + + regInstance.registerTestResources() + regInstance.registerTestDataSources() +} + +// TestMain is a "setup" function called by the testing framework when run the test +func TestMain(m *testing.M) { + // Run setup function before starting the test suite for the conversations_messaging_settings package + initTestResources() + + // Run the test suite for the conversations_messaging_settings package + m.Run() +} diff --git a/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_proxy.go b/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_proxy.go new file mode 100644 index 000000000..0a277e2bc --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/genesyscloud_conversations_messaging_settings_proxy.go @@ -0,0 +1,170 @@ +package conversations_messaging_settings + +import ( + "context" + "fmt" + "log" + rc "terraform-provider-genesyscloud/genesyscloud/resource_cache" + + "github.com/mypurecloud/platform-client-sdk-go/v133/platformclientv2" +) + +var internalProxy *conversationsMessagingSettingsProxy + +type getAllConversationsMessagingSettingsFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy) (*[]platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) +type createConversationsMessagingSettingsFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy, messagingSettingRequest *platformclientv2.Messagingsettingrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) +type getConversationsMessagingSettingsByIdFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy, id string) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) +type getConversationsMessagingSettingsIdByNameFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy, name string) (string, *platformclientv2.APIResponse, bool, error) +type updateConversationsMessagingSettingsFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy, id string, messagingSettingRequest *platformclientv2.Messagingsettingpatchrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) +type deleteConversationsMessagingSettingsFunc func(ctx context.Context, p *conversationsMessagingSettingsProxy, id string) (*platformclientv2.APIResponse, error) + +// conversationsMessagingSettingsProxy contains all of the methods that call genesys cloud APIs. +type conversationsMessagingSettingsProxy struct { + clientConfig *platformclientv2.Configuration + conversationsApi *platformclientv2.ConversationsApi + createConversationsMessagingSettingsAttr createConversationsMessagingSettingsFunc + getAllConversationsMessagingSettingsAttr getAllConversationsMessagingSettingsFunc + getConversationsMessagingSettingsIdByNameAttr getConversationsMessagingSettingsIdByNameFunc + getConversationsMessagingSettingsByIdAttr getConversationsMessagingSettingsByIdFunc + updateConversationsMessagingSettingsAttr updateConversationsMessagingSettingsFunc + deleteConversationsMessagingSettingsAttr deleteConversationsMessagingSettingsFunc + messagingSettingsCache rc.CacheInterface[platformclientv2.Messagingsetting] +} + +// newConversationsMessagingSettingsProxy initializes the conversations messaging settings proxy with all of the data needed to communicate with Genesys Cloud +func newConversationsMessagingSettingsProxy(clientConfig *platformclientv2.Configuration) *conversationsMessagingSettingsProxy { + api := platformclientv2.NewConversationsApiWithConfig(clientConfig) + messagingSettingsCache := rc.NewResourceCache[platformclientv2.Messagingsetting]() + return &conversationsMessagingSettingsProxy{ + clientConfig: clientConfig, + conversationsApi: api, + createConversationsMessagingSettingsAttr: createConversationsMessagingSettingsFn, + getAllConversationsMessagingSettingsAttr: getAllConversationsMessagingSettingsFn, + getConversationsMessagingSettingsIdByNameAttr: getConversationsMessagingSettingsIdByNameFn, + getConversationsMessagingSettingsByIdAttr: getConversationsMessagingSettingsByIdFn, + updateConversationsMessagingSettingsAttr: updateConversationsMessagingSettingsFn, + deleteConversationsMessagingSettingsAttr: deleteConversationsMessagingSettingsFn, + messagingSettingsCache: messagingSettingsCache, + } +} + +// getConversationsMessagingSettingsProxy acts as a singleton to for the internalProxy. It also ensures +// that we can still proxy our tests by directly setting internalProxy package variable +func getConversationsMessagingSettingsProxy(clientConfig *platformclientv2.Configuration) *conversationsMessagingSettingsProxy { + if internalProxy == nil { + internalProxy = newConversationsMessagingSettingsProxy(clientConfig) + } + return internalProxy +} + +// getConversationsMessagingSettings retrieves all Genesys Cloud conversations messaging settings +func (p *conversationsMessagingSettingsProxy) getAllConversationsMessagingSettings(ctx context.Context) (*[]platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.getAllConversationsMessagingSettingsAttr(ctx, p) +} + +// createConversationsMessagingSettings creates a Genesys Cloud conversations messaging settings +func (p *conversationsMessagingSettingsProxy) createConversationsMessagingSettings(ctx context.Context, conversationsMessagingSettings *platformclientv2.Messagingsettingrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.createConversationsMessagingSettingsAttr(ctx, p, conversationsMessagingSettings) +} + +// getConversationsMessagingSettingsById returns a single Genesys Cloud conversations messaging settings by Id +func (p *conversationsMessagingSettingsProxy) getConversationsMessagingSettingsById(ctx context.Context, id string) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.getConversationsMessagingSettingsByIdAttr(ctx, p, id) +} + +// getConversationsMessagingSettingsIdByName returns a single Genesys Cloud conversations messaging settings by a name +func (p *conversationsMessagingSettingsProxy) getConversationsMessagingSettingsIdByName(ctx context.Context, name string) (string, *platformclientv2.APIResponse, bool, error) { + return p.getConversationsMessagingSettingsIdByNameAttr(ctx, p, name) +} + +// updateConversationsMessagingSettings updates a Genesys Cloud conversations messaging settings +func (p *conversationsMessagingSettingsProxy) updateConversationsMessagingSettings(ctx context.Context, id string, conversationsMessagingSettings *platformclientv2.Messagingsettingpatchrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.updateConversationsMessagingSettingsAttr(ctx, p, id, conversationsMessagingSettings) +} + +// deleteConversationsMessagingSettings deletes a Genesys Cloud conversations messaging settings by Id +func (p *conversationsMessagingSettingsProxy) deleteConversationsMessagingSettings(ctx context.Context, id string) (*platformclientv2.APIResponse, error) { + return p.deleteConversationsMessagingSettingsAttr(ctx, p, id) +} + +// getAllConversationsMessagingSettingsFn is the implementation for retrieving all conversations messaging settings in Genesys Cloud +func getAllConversationsMessagingSettingsFn(ctx context.Context, p *conversationsMessagingSettingsProxy) (*[]platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + var ( + allMessagingSettings []platformclientv2.Messagingsetting + pageSize = 100 + response *platformclientv2.APIResponse + ) + + messagingSettings, resp, err := p.conversationsApi.GetConversationsMessagingSettings(pageSize, 1) + if err != nil { + return nil, resp, fmt.Errorf("failed to get messaging setting request: %v", err) + } + + if messagingSettings.Entities == nil || len(*messagingSettings.Entities) == 0 { + return &allMessagingSettings, resp, nil + } + allMessagingSettings = append(allMessagingSettings, *messagingSettings.Entities...) + + for pageNum := 2; pageNum <= *messagingSettings.PageCount; pageNum++ { + messagingSettings, resp, err := p.conversationsApi.GetConversationsMessagingSettings(pageSize, pageNum) + if err != nil { + return nil, resp, fmt.Errorf("failed to get messaging setting request: %v", err) + } + response = resp + + if messagingSettings.Entities == nil || len(*messagingSettings.Entities) == 0 { + break + } + allMessagingSettings = append(allMessagingSettings, *messagingSettings.Entities...) + } + + for _, setting := range allMessagingSettings { + rc.SetCache(p.messagingSettingsCache, *setting.Id, setting) + } + + return &allMessagingSettings, response, nil +} + +// createConversationsMessagingSettingsFn is an implementation function for creating a Genesys Cloud conversations messaging settings +func createConversationsMessagingSettingsFn(ctx context.Context, p *conversationsMessagingSettingsProxy, conversationsMessagingSettings *platformclientv2.Messagingsettingrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.conversationsApi.PostConversationsMessagingSettings(*conversationsMessagingSettings) +} + +// getConversationsMessagingSettingsByIdFn is an implementation of the function to get a Genesys Cloud conversations messaging settings by Id +func getConversationsMessagingSettingsByIdFn(ctx context.Context, p *conversationsMessagingSettingsProxy, id string) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + if setting := rc.GetCacheItem(p.messagingSettingsCache, id); setting != nil { + return setting, nil, nil + } + return p.conversationsApi.GetConversationsMessagingSetting(id) +} + +// getConversationsMessagingSettingsIdByNameFn is an implementation of the function to get a Genesys Cloud conversations messaging settings by name +func getConversationsMessagingSettingsIdByNameFn(ctx context.Context, p *conversationsMessagingSettingsProxy, name string) (string, *platformclientv2.APIResponse, bool, error) { + messagingSettings, resp, err := getAllConversationsMessagingSettingsFn(ctx, p) + if err != nil { + return "", resp, false, err + } + + if messagingSettings == nil || len(*messagingSettings) == 0 { + return "", resp, true, fmt.Errorf("no conversations messaging settings found with name %s", name) + } + + for _, messagingSetting := range *messagingSettings { + if *messagingSetting.Name == name { + log.Printf("Retrieved the conversations messaging settings id %s by name %s", *messagingSetting.Id, name) + return *messagingSetting.Id, resp, false, nil + } + } + + return "", resp, true, fmt.Errorf("unable to find conversations messaging settings with name %s", name) +} + +// updateConversationsMessagingSettingsFn is an implementation of the function to update a Genesys Cloud conversations messaging settings +func updateConversationsMessagingSettingsFn(ctx context.Context, p *conversationsMessagingSettingsProxy, id string, messagingSettingRequest *platformclientv2.Messagingsettingpatchrequest) (*platformclientv2.Messagingsetting, *platformclientv2.APIResponse, error) { + return p.conversationsApi.PatchConversationsMessagingSetting(id, *messagingSettingRequest) +} + +// deleteConversationsMessagingSettingsFn is an implementation function for deleting a Genesys Cloud conversations messaging settings +func deleteConversationsMessagingSettingsFn(ctx context.Context, p *conversationsMessagingSettingsProxy, id string) (*platformclientv2.APIResponse, error) { + return p.conversationsApi.DeleteConversationsMessagingSetting(id) +} diff --git a/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings.go b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings.go new file mode 100644 index 000000000..f1304dc77 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings.go @@ -0,0 +1,128 @@ +package conversations_messaging_settings + +import ( + "context" + "fmt" + "log" + "terraform-provider-genesyscloud/genesyscloud/consistency_checker" + "terraform-provider-genesyscloud/genesyscloud/provider" + resourceExporter "terraform-provider-genesyscloud/genesyscloud/resource_exporter" + "terraform-provider-genesyscloud/genesyscloud/util" + "terraform-provider-genesyscloud/genesyscloud/util/constants" + "terraform-provider-genesyscloud/genesyscloud/util/resourcedata" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mypurecloud/platform-client-sdk-go/v133/platformclientv2" +) + +func getAllAuthConversationsMessagingSettings(ctx context.Context, clientConfig *platformclientv2.Configuration) (resourceExporter.ResourceIDMetaMap, diag.Diagnostics) { + proxy := getConversationsMessagingSettingsProxy(clientConfig) + resources := make(resourceExporter.ResourceIDMetaMap) + + messagingSettings, resp, err := proxy.getAllConversationsMessagingSettings(ctx) + if err != nil { + return nil, util.BuildAPIDiagnosticError(resourceName, fmt.Sprintf("Failed to get Conversations messaging Settings: %s", err), resp) + } + + for _, messagingSetting := range *messagingSettings { + resources[*messagingSetting.Id] = &resourceExporter.ResourceMeta{Name: *messagingSetting.Name} + } + + return resources, nil +} + +func createConversationsMessagingSettings(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + sdkConfig := meta.(*provider.ProviderMeta).ClientConfig + proxy := getConversationsMessagingSettingsProxy(sdkConfig) + + conversationsMessagingSettingsReq := getConversationsMessagingSettingsFromResourceData(d) + + log.Printf("Creating conversations messaging settings %s", *conversationsMessagingSettingsReq.Name) + messagingSetting, resp, err := proxy.createConversationsMessagingSettings(ctx, &conversationsMessagingSettingsReq) + if err != nil { + return util.BuildAPIDiagnosticError(resourceName, fmt.Sprintf("Failed to create conversations messaging setting %s error: %s", *conversationsMessagingSettingsReq.Name, err), resp) + } + + d.SetId(*messagingSetting.Id) + log.Printf("Created conversations messaging settings %s", *messagingSetting.Id) + return readConversationsMessagingSettings(ctx, d, meta) +} + +func readConversationsMessagingSettings(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + sdkConfig := meta.(*provider.ProviderMeta).ClientConfig + proxy := getConversationsMessagingSettingsProxy(sdkConfig) + cc := consistency_checker.NewConsistencyCheck(ctx, d, meta, ResourceConversationsMessagingSettings(), constants.DefaultConsistencyChecks, resourceName) + + log.Printf("Reading conversations messaging settings %s", d.Id()) + + return util.WithRetriesForRead(ctx, d, func() *retry.RetryError { + messagingSetting, resp, err := proxy.getConversationsMessagingSettingsById(ctx, d.Id()) + if err != nil { + if util.IsStatus404(resp) { + return retry.RetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("Failed to read conversations messaging settings %s | error: %s", d.Id(), err), resp)) + } + return retry.NonRetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("Failed to read conversations messaging settings %s | error: %s", d.Id(), err), resp)) + } + + resourcedata.SetNillableValue(d, "name", messagingSetting.Name) + resourcedata.SetNillableValueWithInterfaceArrayWithFunc(d, "content", messagingSetting.Content, flattenContentSettings) + resourcedata.SetNillableValueWithInterfaceArrayWithFunc(d, "event", messagingSetting.Event, flattenEventSettings) + + log.Printf("Read conversations messaging settings %s", d.Id()) + return cc.CheckState(d) + }) +} + +func updateConversationsMessagingSettings(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + sdkConfig := meta.(*provider.ProviderMeta).ClientConfig + proxy := getConversationsMessagingSettingsProxy(sdkConfig) + + name := d.Get("name").(string) + content := d.Get("content").([]interface{}) + event := d.Get("event").([]interface{}) + + var conversationsMessagingSettings platformclientv2.Messagingsettingpatchrequest + + if name != "" { + conversationsMessagingSettings.Name = &name + } + if content != nil { + conversationsMessagingSettings.Content = buildContentSettings(content) + } + if event != nil { + conversationsMessagingSettings.Event = buildEventSetting(event) + } + + _, resp, err := proxy.updateConversationsMessagingSettings(ctx, d.Id(), &conversationsMessagingSettings) + if err != nil { + return util.BuildAPIDiagnosticError(resourceName, fmt.Sprintf("Failed to update conversations messaging settings %s error: %s", d.Id(), err), resp) + } + + log.Printf("Updated conversations messaging settings %s", d.Id()) + return readConversationsMessagingSettings(ctx, d, meta) +} + +func deleteConversationsMessagingSettings(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + sdkConfig := meta.(*provider.ProviderMeta).ClientConfig + proxy := getConversationsMessagingSettingsProxy(sdkConfig) + + resp, err := proxy.deleteConversationsMessagingSettings(ctx, d.Id()) + if err != nil { + return util.BuildAPIDiagnosticError(resourceName, fmt.Sprintf("Failed to delete conversations messaging setting %s error: %s", d.Id(), err), resp) + } + + return util.WithRetries(ctx, 180*time.Second, func() *retry.RetryError { + _, resp, err := proxy.getConversationsMessagingSettingsById(ctx, d.Id()) + if err != nil { + if util.IsStatus404(resp) { + log.Printf("Deleted Conversations messaging Setting") + return nil + } + return retry.NonRetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("Error deleting Conversations messaging Setting: %s | error: %s", d.Id(), err), resp)) + } + return retry.RetryableError(util.BuildWithRetriesApiDiagnosticError(resourceName, fmt.Sprintf("Conversations messaging Setting %s still exists", d.Id()), resp)) + }) +} diff --git a/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_schema.go b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_schema.go new file mode 100644 index 000000000..9564bbd70 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_schema.go @@ -0,0 +1,163 @@ +package conversations_messaging_settings + +import ( + "terraform-provider-genesyscloud/genesyscloud/provider" + resourceExporter "terraform-provider-genesyscloud/genesyscloud/resource_exporter" + registrar "terraform-provider-genesyscloud/genesyscloud/resource_register" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +const resourceName = "genesyscloud_conversations_messaging_settings" + +var ( + eventSettingResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "typing": { + Description: "Settings regarding typing events", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: typingSettingResource, + }, + }, + } + typingSettingResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "on": { + Description: "Should typing indication Events be sent", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: settingDirectionResource, + }, + }, + } + settingDirectionResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "inbound": { + Description: "Status for the Inbound Direction. Valid values: Enabled, Disabled.", + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false), + }, + "outbound": { + Description: "Status for the outbound Direction. Valid values: Enabled, Disabled.", + Type: schema.TypeString, + Optional: true, + ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false), + }, + }, + } + + contentSettingResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "story": { + Description: "Settings relating to facebook and instagram stories feature", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: storySettingResource, + }, + }, + } + storySettingResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "mention": { + Description: "Setting relating to Story Mentions", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: inboundOnlySettingResource, + }, + "reply": { + Description: "Setting relating to Story Replies", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: inboundOnlySettingResource, + }, + }, + } + inboundOnlySettingResource = &schema.Resource{ + Schema: map[string]*schema.Schema{ + "inbound": { + Description: "Valid values: Enabled, Disabled.", + Optional: true, + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{"Enabled", "Disabled"}, false), + }, + }, + } +) + +// SetRegistrar registers all of the resources, datasources and exporters in the package +func SetRegistrar(regInstance registrar.Registrar) { + regInstance.RegisterResource(resourceName, ResourceConversationsMessagingSettings()) + regInstance.RegisterDataSource(resourceName, DataSourceConversationsMessagingSettings()) + regInstance.RegisterExporter(resourceName, ConversationsMessagingSettingsExporter()) +} + +func ResourceConversationsMessagingSettings() *schema.Resource { + return &schema.Resource{ + Description: "Genesys Cloud conversations messaging settings", + + CreateContext: provider.CreateWithPooledClient(createConversationsMessagingSettings), + ReadContext: provider.ReadWithPooledClient(readConversationsMessagingSettings), + UpdateContext: provider.UpdateWithPooledClient(updateConversationsMessagingSettings), + DeleteContext: provider.DeleteWithPooledClient(deleteConversationsMessagingSettings), + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + SchemaVersion: 1, + Schema: map[string]*schema.Schema{ + "name": { + Description: "The messaging Setting profile name", + Required: true, + Type: schema.TypeString, + }, + "content": { + Description: "Settings relating to message contents", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: contentSettingResource, + AtLeastOneOf: []string{"content", "event"}, + }, + "event": { + Description: "Settings relating to events which may occur", + Optional: true, + Type: schema.TypeList, + MaxItems: 1, + Elem: eventSettingResource, + AtLeastOneOf: []string{"content", "event"}, + }, + }, + } +} + +// DataSourceConversationsMessagingSettings registers the genesyscloud_conversations_messaging_settings data source +func DataSourceConversationsMessagingSettings() *schema.Resource { + return &schema.Resource{ + Description: "Genesys Cloud conversations messaging settings data source. Select an conversations messaging settings by name", + ReadContext: provider.ReadWithPooledClient(dataSourceConversationsMessagingSettingsRead), + Importer: &schema.ResourceImporter{ + StateContext: schema.ImportStatePassthroughContext, + }, + Schema: map[string]*schema.Schema{ + "name": { + Description: "conversations messaging settings name", + Type: schema.TypeString, + Required: true, + }, + }, + } +} + +// ConversationsMessagingSettingsExporter returns the resourceExporter object used to hold the genesyscloud_conversations_messaging_settings exporter's config +func ConversationsMessagingSettingsExporter() *resourceExporter.ResourceExporter { + return &resourceExporter.ResourceExporter{ + GetResourcesFunc: provider.GetAllWithPooledClient(getAllAuthConversationsMessagingSettings), + } +} diff --git a/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_test.go b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_test.go new file mode 100644 index 000000000..9f569e324 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_test.go @@ -0,0 +1,144 @@ +package conversations_messaging_settings + +import ( + "fmt" + "terraform-provider-genesyscloud/genesyscloud/provider" + "terraform-provider-genesyscloud/genesyscloud/util" + "testing" + + "github.com/mypurecloud/platform-client-sdk-go/v133/platformclientv2" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccResourceConversationsMessagingSettings(t *testing.T) { + var ( + resource1 = "testConversationsMessagingSettings" + name1 = "testSettings" + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + ProviderFactories: provider.GetProviderFactories(providerResources, providerDataSources), + Steps: []resource.TestStep{ + { + // Create with Content Block + Config: generateConversationsMessagingSettingsResource( + resource1, + name1, + generateContentStoryBlock( + generateMentionInboundOnlySetting("Disabled"), + generateReplyInboundOnlySetting("Enabled"), + ), + ), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "name", name1), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "content.0.story.0.mention.0.inbound", "Disabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "content.0.story.0.reply.0.inbound", "Enabled"), + ), + }, + { + // Update and Add Event Block + Config: generateConversationsMessagingSettingsResource( + resource1, + name1, + generateContentStoryBlock( + generateMentionInboundOnlySetting("Enabled"), + generateReplyInboundOnlySetting("Enabled"), + ), + generateTypingOnSetting( + "Enabled", + "Disabled", + ), + ), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "name", name1), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "content.0.story.0.mention.0.inbound", "Enabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "content.0.story.0.reply.0.inbound", "Enabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "event.0.typing.0.on.0.inbound", "Enabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource1, "event.0.typing.0.on.0.outbound", "Disabled"), + ), + }, + { + // Import/Read + ResourceName: "genesyscloud_conversations_messaging_settings." + resource1, + ImportState: true, + ImportStateVerify: true, + }, + }, + CheckDestroy: testVerifySettingDestroyed, + }) +} + +func TestAccResourceConversationsMessagingSettingsContentOnly(t *testing.T) { + var ( + resource2 = "testConversationsMessagingSettingsContentOnly" + name2 = "testSettingsContentOnly" + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { util.TestAccPreCheck(t) }, + ProviderFactories: provider.GetProviderFactories(providerResources, providerDataSources), + Steps: []resource.TestStep{ + { + // Create + Config: generateConversationsMessagingSettingsResource( + resource2, + name2, + generateContentStoryBlock( + generateMentionInboundOnlySetting("Disabled"), + generateReplyInboundOnlySetting("Disabled"), + ), + ), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "name", name2), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "content.0.story.0.mention.0.inbound", "Disabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "content.0.story.0.reply.0.inbound", "Disabled"), + ), + }, + { + // Update + Config: generateConversationsMessagingSettingsResource( + resource2, + name2, + generateContentStoryBlock( + generateMentionInboundOnlySetting("Enabled"), + generateReplyInboundOnlySetting("Enabled"), + ), + ), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "name", name2), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "content.0.story.0.mention.0.inbound", "Enabled"), + resource.TestCheckResourceAttr("genesyscloud_conversations_messaging_settings."+resource2, "content.0.story.0.reply.0.inbound", "Enabled"), + ), + }, + { + // Import/Read + ResourceName: "genesyscloud_conversations_messaging_settings." + resource2, + ImportState: true, + ImportStateVerify: true, + }, + }, + CheckDestroy: testVerifySettingDestroyed, + }) +} + +func testVerifySettingDestroyed(state *terraform.State) error { + messagingAPI := platformclientv2.NewConversationsApi() + for _, rs := range state.RootModule().Resources { + if rs.Type != "genesyscloud_conversations_messaging_settings" { + continue + } + + setting, resp, err := messagingAPI.GetConversationsMessagingSetting(rs.Primary.ID) + if setting != nil { + return fmt.Errorf("Messaging setting (%s) still exists", rs.Primary.ID) + } else if util.IsStatus404(resp) { + continue + } else { + return fmt.Errorf("Unexpected error: %s", err) + } + } + return nil +} diff --git a/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_utils.go b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_utils.go new file mode 100644 index 000000000..582676fb3 --- /dev/null +++ b/genesyscloud/conversations_messaging_settings/resource_conversations_messaging_settings_utils.go @@ -0,0 +1,225 @@ +package conversations_messaging_settings + +import ( + "fmt" + "strings" + "terraform-provider-genesyscloud/genesyscloud/util/resourcedata" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/mypurecloud/platform-client-sdk-go/v133/platformclientv2" +) + +func getConversationsMessagingSettingsFromResourceData(d *schema.ResourceData) platformclientv2.Messagingsettingrequest { + return platformclientv2.Messagingsettingrequest{ + Name: platformclientv2.String(d.Get("name").(string)), + Content: buildContentSettings(d.Get("content").([]interface{})), + Event: buildEventSetting(d.Get("event").([]interface{})), + } +} + +func buildContentSettings(contentSettings []interface{}) *platformclientv2.Contentsetting { + var sdkContentSetting platformclientv2.Contentsetting + + for _, contentSetting := range contentSettings { + contentSettingsMap, ok := contentSetting.(map[string]interface{}) + if !ok { + continue + } + + resourcedata.BuildSDKInterfaceArrayValueIfNotNil(&sdkContentSetting.Story, contentSettingsMap, "story", buildStorySettings) + } + return &sdkContentSetting +} + +func buildStorySettings(storySettings []interface{}) *platformclientv2.Storysetting { + var sdkStorySetting platformclientv2.Storysetting + + for _, storySetting := range storySettings { + storySettingsMap, ok := storySetting.(map[string]interface{}) + if !ok { + continue + } + + resourcedata.BuildSDKInterfaceArrayValueIfNotNil(&sdkStorySetting.Mention, storySettingsMap, "mention", buildInboundOnlySettings) + resourcedata.BuildSDKInterfaceArrayValueIfNotNil(&sdkStorySetting.Reply, storySettingsMap, "reply", buildInboundOnlySettings) + } + + return &sdkStorySetting +} + +func buildInboundOnlySettings(inboundOnlySettings []interface{}) *platformclientv2.Inboundonlysetting { + var sdkInboundOnlySetting platformclientv2.Inboundonlysetting + + for _, inboundOnlySetting := range inboundOnlySettings { + inboundOnlySettingsMap, ok := inboundOnlySetting.(map[string]interface{}) + if !ok { + continue + } + resourcedata.BuildSDKStringValueIfNotNil(&sdkInboundOnlySetting.Inbound, inboundOnlySettingsMap, "inbound") + } + + return &sdkInboundOnlySetting +} + +func buildEventSetting(eventSettings []interface{}) *platformclientv2.Eventsetting { + var sdkEventSetting platformclientv2.Eventsetting + + for _, eventSetting := range eventSettings { + eventSettingsMap, ok := eventSetting.(map[string]interface{}) + if !ok { + continue + } + resourcedata.BuildSDKInterfaceArrayValueIfNotNil(&sdkEventSetting.Typing, eventSettingsMap, "typing", buildTypingSettings) + } + + return &sdkEventSetting +} + +func buildTypingSettings(typingSettings []interface{}) *platformclientv2.Typingsetting { + var sdkTypingSetting platformclientv2.Typingsetting + + for _, typingSetting := range typingSettings { + typingSettingsMap, ok := typingSetting.(map[string]interface{}) + if !ok { + continue + } + + resourcedata.BuildSDKInterfaceArrayValueIfNotNil(&sdkTypingSetting.On, typingSettingsMap, "on", buildSettingDirections) + } + + return &sdkTypingSetting +} + +func buildSettingDirections(settingDirections []interface{}) *platformclientv2.Settingdirection { + var sdkSettingDirection platformclientv2.Settingdirection + + for _, settingDirection := range settingDirections { + settingDirectionsMap, ok := settingDirection.(map[string]interface{}) + if !ok { + continue + } + + resourcedata.BuildSDKStringValueIfNotNil(&sdkSettingDirection.Inbound, settingDirectionsMap, "inbound") + resourcedata.BuildSDKStringValueIfNotNil(&sdkSettingDirection.Outbound, settingDirectionsMap, "outbound") + } + + return &sdkSettingDirection +} + +// flattenInboundOnlySettings maps a Genesys Cloud *[]platformclientv2.Inboundonlysetting into a []interface{} +func flattenInboundOnlySettings(inboundOnlySettings *platformclientv2.Inboundonlysetting) []interface{} { + var inboundOnlySettingList []interface{} + inboundOnlySettingMap := make(map[string]interface{}) + + resourcedata.SetMapValueIfNotNil(inboundOnlySettingMap, "inbound", inboundOnlySettings.Inbound) + + inboundOnlySettingList = append(inboundOnlySettingList, inboundOnlySettingMap) + + return inboundOnlySettingList +} + +// flattenStorySettings maps a Genesys Cloud *[]platformclientv2.Storysetting into a []interface{} +func flattenStorySettings(storySettings *platformclientv2.Storysetting) []interface{} { + var storySettingList []interface{} + storySettingMap := make(map[string]interface{}) + + resourcedata.SetMapInterfaceArrayWithFuncIfNotNil(storySettingMap, "mention", storySettings.Mention, flattenInboundOnlySettings) + resourcedata.SetMapInterfaceArrayWithFuncIfNotNil(storySettingMap, "reply", storySettings.Reply, flattenInboundOnlySettings) + + storySettingList = append(storySettingList, storySettingMap) + + return storySettingList +} + +// flattenContentSettings maps a Genesys Cloud *[]platformclientv2.Contentsetting into a []interface{} +func flattenContentSettings(contentSettings *platformclientv2.Contentsetting) []interface{} { + var contentSettingList []interface{} + contentSettingMap := make(map[string]interface{}) + + resourcedata.SetMapInterfaceArrayWithFuncIfNotNil(contentSettingMap, "story", contentSettings.Story, flattenStorySettings) + + contentSettingList = append(contentSettingList, contentSettingMap) + + return contentSettingList +} + +// flattenSettingDirections maps a Genesys Cloud *[]platformclientv2.Settingdirection into a []interface{} +func flattenSettingDirections(settingDirections *platformclientv2.Settingdirection) []interface{} { + var settingDirectionList []interface{} + settingDirectionMap := make(map[string]interface{}) + + resourcedata.SetMapValueIfNotNil(settingDirectionMap, "inbound", settingDirections.Inbound) + resourcedata.SetMapValueIfNotNil(settingDirectionMap, "outbound", settingDirections.Outbound) + + settingDirectionList = append(settingDirectionList, settingDirectionMap) + + return settingDirectionList +} + +// flattenTypingSettings maps a Genesys Cloud *[]platformclientv2.Typingsetting into a []interface{} +func flattenTypingSettings(typingSettings *platformclientv2.Typingsetting) []interface{} { + var typingSettingList []interface{} + typingSettingMap := make(map[string]interface{}) + + resourcedata.SetMapInterfaceArrayWithFuncIfNotNil(typingSettingMap, "on", typingSettings.On, flattenSettingDirections) + + typingSettingList = append(typingSettingList, typingSettingMap) + + return typingSettingList +} + +// flattenEventSettings maps a Genesys Cloud *[]platformclientv2.Eventsetting into a []interface{} +func flattenEventSettings(eventSettings *platformclientv2.Eventsetting) []interface{} { + var eventSettingList []interface{} + eventSettingMap := make(map[string]interface{}) + + resourcedata.SetMapInterfaceArrayWithFuncIfNotNil(eventSettingMap, "typing", eventSettings.Typing, flattenTypingSettings) + + eventSettingList = append(eventSettingList, eventSettingMap) + + return eventSettingList +} + +func generateConversationsMessagingSettingsResource(resourceID string, name string, nestedBlocks ...string) string { + return fmt.Sprintf(`resource "genesyscloud_conversations_messaging_settings" "%s" { + name = "%s" + %s + } + `, resourceID, name, strings.Join(nestedBlocks, "\n")) +} + +func generateTypingOnSetting(inbound, outbound string) string { + return fmt.Sprintf(` + event { + typing { + on { + inbound = "%s" + outbound = "%s" + } + } + }`, inbound, outbound) +} + +func generateContentStoryBlock(nestedBlocks ...string) string { + return fmt.Sprintf(` + content { + story { + %s + } + }`, strings.Join(nestedBlocks, "\n")) +} + +func generateMentionInboundOnlySetting(value string) string { + return fmt.Sprintf(` + mention { + inbound = "%s" + } + `, value) +} + +func generateReplyInboundOnlySetting(value string) string { + return fmt.Sprintf(` + reply { + inbound = "%s" + }`, value) +} diff --git a/genesyscloud/resource_genesyscloud_init_test.go b/genesyscloud/resource_genesyscloud_init_test.go index 4d46ea6ee..c42f6da23 100644 --- a/genesyscloud/resource_genesyscloud_init_test.go +++ b/genesyscloud/resource_genesyscloud_init_test.go @@ -6,6 +6,7 @@ import ( "terraform-provider-genesyscloud/genesyscloud/architect_flow" archScheduleGroup "terraform-provider-genesyscloud/genesyscloud/architect_schedulegroups" architectSchedules "terraform-provider-genesyscloud/genesyscloud/architect_schedules" + cMessagingSettings "terraform-provider-genesyscloud/genesyscloud/conversations_messaging_settings" "terraform-provider-genesyscloud/genesyscloud/group" "terraform-provider-genesyscloud/genesyscloud/provider" routinglanguage "terraform-provider-genesyscloud/genesyscloud/routing_language" @@ -67,6 +68,7 @@ func (r *registerTestInstance) registerTestResources() { providerResources["genesyscloud_architect_schedulegroups"] = archScheduleGroup.ResourceArchitectSchedulegroups() providerResources["genesyscloud_architect_schedules"] = architectSchedules.ResourceArchitectSchedules() providerResources["genesyscloud_routing_utilization_label"] = routingUtilizationLabel.ResourceRoutingUtilizationLabel() + providerResources["genesyscloud_conversations_messaging_settings"] = cMessagingSettings.ResourceConversationsMessagingSettings() } @@ -101,7 +103,9 @@ func (r *registerTestInstance) registerTestDataSources() { providerDataSources["genesyscloud_routing_wrapupcode"] = DataSourceRoutingWrapupcode() providerDataSources["genesyscloud_user"] = DataSourceUser() providerDataSources["genesyscloud_widget_deployment"] = dataSourceWidgetDeployments() - providerResources["genesyscloud_routing_utilization_label"] = routingUtilizationLabel.DataSourceRoutingUtilizationLabel() + providerDataSources["genesyscloud_routing_utilization_label"] = routingUtilizationLabel.DataSourceRoutingUtilizationLabel() + providerDataSources["genesyscloud_conversations_messaging_settings"] = cMessagingSettings.DataSourceConversationsMessagingSettings() + } func initTestResources() { diff --git a/genesyscloud/tfexporter/tf_exporter_resource_test.go b/genesyscloud/tfexporter/tf_exporter_resource_test.go index 23d3e221c..19364f3ef 100644 --- a/genesyscloud/tfexporter/tf_exporter_resource_test.go +++ b/genesyscloud/tfexporter/tf_exporter_resource_test.go @@ -12,6 +12,7 @@ import ( architectSchedulegroups "terraform-provider-genesyscloud/genesyscloud/architect_schedulegroups" architectSchedules "terraform-provider-genesyscloud/genesyscloud/architect_schedules" authRole "terraform-provider-genesyscloud/genesyscloud/auth_role" + cMessagingSettings "terraform-provider-genesyscloud/genesyscloud/conversations_messaging_settings" employeeperformanceExternalmetricsDefinition "terraform-provider-genesyscloud/genesyscloud/employeeperformance_externalmetrics_definitions" flowLogLevel "terraform-provider-genesyscloud/genesyscloud/flow_loglevel" flowMilestone "terraform-provider-genesyscloud/genesyscloud/flow_milestone" @@ -203,7 +204,7 @@ func (r *registerTestInstance) registerTestResources() { providerResources["genesyscloud_task_management_workbin"] = workbin.ResourceTaskManagementWorkbin() providerResources["genesyscloud_task_management_workitem_schema"] = workitemSchema.ResourceTaskManagementWorkitemSchema() providerResources["genesyscloud_task_management_worktype"] = worktype.ResourceTaskManagementWorktype() - + providerResources["genesyscloud_conversations_messaging_settings"] = cMessagingSettings.ResourceConversationsMessagingSettings() providerResources["genesyscloud_tf_export"] = ResourceTfExport() } @@ -304,6 +305,7 @@ func (r *registerTestInstance) registerTestExporters() { RegisterExporter("genesyscloud_task_management_workbin", workbin.TaskManagementWorkbinExporter()) RegisterExporter("genesyscloud_task_management_workitem_schema", workbin.TaskManagementWorkbinExporter()) RegisterExporter("genesyscloud_task_management_worktype", worktype.TaskManagementWorktypeExporter()) + RegisterExporter("genesyscloud_conversations_messaging_settings", cMessagingSettings.ConversationsMessagingSettingsExporter()) RegisterExporter("genesyscloud_script", scripts.ExporterScript()) @@ -314,6 +316,7 @@ func (r *registerTestInstance) registerTestDataSources() { providerDataSources["genesyscloud_auth_division_home"] = gcloud.DataSourceAuthDivisionHome() providerDataSources["genesyscloud_script"] = scripts.DataSourceScript() providerDataSources["genesyscloud_telephony_providers_edges_site"] = edgeSite.DataSourceSite() + providerDataSources["genesyscloud_conversations_messaging_settings"] = cMessagingSettings.DataSourceConversationsMessagingSettings() } func RegisterExporter(exporterName string, resourceExporter *resourceExporter.ResourceExporter) { diff --git a/main.go b/main.go index c5962bd8b..5174c193f 100644 --- a/main.go +++ b/main.go @@ -70,9 +70,7 @@ import ( routingUtilization "terraform-provider-genesyscloud/genesyscloud/routing_utilization" routingUtilizationLabel "terraform-provider-genesyscloud/genesyscloud/routing_utilization_label" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" - + cMessageSettings "terraform-provider-genesyscloud/genesyscloud/conversations_messaging_settings" routingQueueConditionalGroupRouting "terraform-provider-genesyscloud/genesyscloud/routing_queue_conditional_group_routing" routingQueueOutboundEmailAddress "terraform-provider-genesyscloud/genesyscloud/routing_queue_outbound_email_address" routingSettings "terraform-provider-genesyscloud/genesyscloud/routing_settings" @@ -99,6 +97,9 @@ import ( userRoles "terraform-provider-genesyscloud/genesyscloud/user_roles" webDeployConfig "terraform-provider-genesyscloud/genesyscloud/webdeployments_configuration" webDeployDeploy "terraform-provider-genesyscloud/genesyscloud/webdeployments_deployment" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/plugin" ) // Run "go generate" to format example terraform files and generate the docs for the registry/website @@ -245,6 +246,7 @@ func registerResources() { journeyViews.SetRegistrar(regInstance) //Registering journey views routingLanguage.SetRegistrar(regInstance) //Registering Routing Language routingEmailDomain.SetRegistrar(regInstance) //Registering Routing Email Domain + cMessageSettings.SetRegistrar(regInstance) // Registering conversations messaging settings // setting resources for Use cases like TF export where provider is used in resource classes. tfexp.SetRegistrar(regInstance) //Registering tf exporter registrar.SetResources(providerResources, providerDataSources)