/
data_source_agreement.go
273 lines (225 loc) · 9.3 KB
/
data_source_agreement.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package base
import (
"context"
"fmt"
"net/http"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/patrickcping/pingone-go-sdk-v2/management"
"github.com/pingidentity/terraform-provider-pingone/internal/framework"
"github.com/pingidentity/terraform-provider-pingone/internal/sdk"
"github.com/pingidentity/terraform-provider-pingone/internal/verify"
)
// Types
type AgreementDataSource serviceClientType
type AgreementDataSourceModel struct {
Id types.String `tfsdk:"id"`
EnvironmentId types.String `tfsdk:"environment_id"`
AgreementId types.String `tfsdk:"agreement_id"`
Name types.String `tfsdk:"name"`
Enabled types.Bool `tfsdk:"enabled"`
Description types.String `tfsdk:"description"`
ReconsentPeriodDays types.Float64 `tfsdk:"reconsent_period_days"`
TotalUserConsents types.Int64 `tfsdk:"total_user_consent_count"`
ExpiredUserConsents types.Int64 `tfsdk:"expired_user_consent_count"`
ConsentCountsUpdateAt types.String `tfsdk:"consent_counts_updated_at"`
}
// Framework interfaces
var (
_ datasource.DataSource = &AgreementDataSource{}
)
// New Object
func NewAgreementDataSource() datasource.DataSource {
return &AgreementDataSource{}
}
// Metadata
func (r *AgreementDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_agreement"
}
// Schema
func (r *AgreementDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) {
nameLength := 1
totalUserCountDescription := framework.SchemaAttributeDescriptionFromMarkdown(
"The total number of users who have consented to the agreement. This value is last calculated at the `consent_counts_updated_at` time.",
)
expiredUserCountDescription := framework.SchemaAttributeDescriptionFromMarkdown(
"The number of users who have consented to the agreement, but their consent has expired. This value is last calculated at the `consent_counts_updated_at` time.",
)
resp.Schema = schema.Schema{
// This description is used by the documentation generator and the language server.
Description: "Datasource to retrieve details of an agreement configured in a PingOne environment.",
Attributes: map[string]schema.Attribute{
"id": framework.Attr_ID(),
"environment_id": framework.Attr_LinkID(
framework.SchemaAttributeDescriptionFromMarkdown("The ID of the environment that is configured with the agreement."),
),
"agreement_id": schema.StringAttribute{
Description: "The ID of the agreement to retrieve. Either `agreement_id`, or `name` can be used to retrieve the agreement localization, but cannot be set together.",
Optional: true,
Validators: []validator.String{
stringvalidator.ExactlyOneOf(path.MatchRelative().AtParent().AtName("name")),
verify.P1ResourceIDValidator(),
},
},
"name": schema.StringAttribute{
Description: "A string that specifies the name of the agreement to retrieve. Either `agreement_id`, or `name` can be used to retrieve the agreement localization, but cannot be set together.",
Optional: true,
Validators: []validator.String{
stringvalidator.ExactlyOneOf(path.MatchRelative().AtParent().AtName("agreement_id")),
stringvalidator.LengthAtLeast(nameLength),
},
},
"description": schema.StringAttribute{
Description: "A string that specifies the description of the agreement.",
Computed: true,
},
"enabled": schema.BoolAttribute{
Description: "The current enabled state of the agreement.",
Computed: true,
},
"reconsent_period_days": schema.Float64Attribute{
Description: "A number that specifies the number of days until a consent to this agreement expires.",
Computed: true,
},
"total_user_consent_count": schema.Int64Attribute{
Description: totalUserCountDescription.Description,
MarkdownDescription: totalUserCountDescription.MarkdownDescription,
Computed: true,
},
"expired_user_consent_count": schema.Int64Attribute{
Description: expiredUserCountDescription.Description,
MarkdownDescription: expiredUserCountDescription.MarkdownDescription,
Computed: true,
},
"consent_counts_updated_at": schema.StringAttribute{
Description: "The date and time the consent user count metrics were last updated. This value is typically updated once every 24 hours.",
Computed: true,
},
},
}
}
func (r *AgreementDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
resourceConfig, ok := req.ProviderData.(framework.ResourceType)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected the provider client, got: %T. Please report this issue to the provider maintainers.", req.ProviderData),
)
return
}
r.Client = resourceConfig.Client.API
if r.Client == nil {
resp.Diagnostics.AddError(
"Client not initialised",
"Expected the PingOne client, got nil. Please report this issue to the provider maintainers.",
)
return
}
}
func (r *AgreementDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var data *AgreementDataSourceModel
if r.Client.ManagementAPIClient == nil {
resp.Diagnostics.AddError(
"Client not initialized",
"Expected the PingOne client, got nil. Please report this issue to the provider maintainers.")
return
}
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
var agreement management.Agreement
if !data.Name.IsNull() {
// Run the API call
var entityArray *management.EntityArray
resp.Diagnostics.Append(framework.ParseResponse(
ctx,
func() (any, *http.Response, error) {
fO, fR, fErr := r.Client.ManagementAPIClient.AgreementsResourcesApi.ReadAllAgreements(ctx, data.EnvironmentId.ValueString()).Execute()
return framework.CheckEnvironmentExistsOnPermissionsError(ctx, r.Client.ManagementAPIClient, data.EnvironmentId.ValueString(), fO, fR, fErr)
},
"ReadAllAgreements",
framework.DefaultCustomError,
sdk.DefaultCreateReadRetryable,
&entityArray,
)...)
if resp.Diagnostics.HasError() {
return
}
if agreements, ok := entityArray.Embedded.GetAgreementsOk(); ok {
found := false
for _, agreementItem := range agreements {
if agreementItem.GetName() == data.Name.ValueString() {
agreement = agreementItem
found = true
break
}
}
if !found {
resp.Diagnostics.AddError(
"Cannot find agreement from name",
fmt.Sprintf("The agreement %s for environment %s cannot be found", data.Name.String(), data.EnvironmentId.String()),
)
return
}
}
} else if !data.AgreementId.IsNull() {
// Run the API call
var response *management.Agreement
resp.Diagnostics.Append(framework.ParseResponse(
ctx,
func() (any, *http.Response, error) {
fO, fR, fErr := r.Client.ManagementAPIClient.AgreementsResourcesApi.ReadOneAgreement(ctx, data.EnvironmentId.ValueString(), data.AgreementId.ValueString()).Execute()
return framework.CheckEnvironmentExistsOnPermissionsError(ctx, r.Client.ManagementAPIClient, data.EnvironmentId.ValueString(), fO, fR, fErr)
},
"ReadOneAgreement",
framework.DefaultCustomError,
sdk.DefaultCreateReadRetryable,
&response,
)...)
if resp.Diagnostics.HasError() {
return
}
agreement = *response
} else {
resp.Diagnostics.AddError(
"Missing parameter",
"Cannot find the requested agreement. agreement_id or name must be set.",
)
return
}
// Save updated data into Terraform state
resp.Diagnostics.Append(data.toState(&agreement)...)
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (p *AgreementDataSourceModel) toState(apiObject *management.Agreement) diag.Diagnostics {
var diags diag.Diagnostics
if apiObject == nil {
diags.AddError(
"Data object missing",
"Cannot convert the data object to state as the data object is nil. Please report this to the provider maintainers.",
)
return diags
}
p.Id = framework.StringToTF(apiObject.GetId())
p.EnvironmentId = framework.StringToTF(*apiObject.GetEnvironment().Id)
p.AgreementId = framework.StringToTF(apiObject.GetId())
p.Name = framework.StringOkToTF(apiObject.GetNameOk())
p.Enabled = framework.BoolOkToTF(apiObject.GetEnabledOk())
p.Description = framework.StringOkToTF(apiObject.GetDescriptionOk())
p.ReconsentPeriodDays = framework.Float32OkToTF(apiObject.GetReconsentPeriodDaysOk())
p.TotalUserConsents = framework.Int32OkToTF(apiObject.GetTotalConsentsOk())
p.ExpiredUserConsents = framework.Int32OkToTF(apiObject.GetTotalExpiredConsentsOk())
p.ConsentCountsUpdateAt = framework.TimeOkToTF(apiObject.GetConsentsAggregatedAtOk())
return diags
}