compute_tax_function.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) HashiCorp, Inc.
  2. // SPDX-License-Identifier: MPL-2.0
  3. package provider
  4. import (
  5. "context"
  6. "math"
  7. "github.com/hashicorp/terraform-plugin-framework/function"
  8. )
  9. var (
  10. _ function.Function = &ComputeTaxFunction{}
  11. )
  12. type ComputeTaxFunction struct{}
  13. func NewComputeTaxFunction() function.Function {
  14. return &ComputeTaxFunction{}
  15. }
  16. func (f *ComputeTaxFunction) Metadata(ctx context.Context, req function.MetadataRequest, resp *function.MetadataResponse) {
  17. resp.Name = "compute_tax"
  18. }
  19. func (f *ComputeTaxFunction) Definition(ctx context.Context, req function.DefinitionRequest, resp *function.DefinitionResponse) {
  20. resp.Definition = function.Definition{
  21. Parameters: []function.Parameter{
  22. function.Float64Parameter{
  23. Description: "Price of coffee item.",
  24. Name: "price",
  25. },
  26. function.Float64Parameter{
  27. Description: "Tax rate. 0.085 == 8.5%",
  28. Name: "rate",
  29. },
  30. },
  31. Return: function.Float64Return{},
  32. Summary: "Compute tax for coffee",
  33. Description: "Given a price and tax rate, return the total cost including tax.",
  34. }
  35. }
  36. func (f *ComputeTaxFunction) Run(ctx context.Context, req function.RunRequest, resp *function.RunResponse) {
  37. var (
  38. price, rate, total float64
  39. )
  40. // 1. Read Terraform argument data into the variables.
  41. resp.Error = function.ConcatFuncErrors(
  42. resp.Error,
  43. req.Arguments.Get(ctx, &price, &rate),
  44. )
  45. // 2. Perform the calculation
  46. total = math.Round((price+price*rate)*100) / 100
  47. // 3. Set the result on the state
  48. resp.Error = function.ConcatFuncErrors(
  49. resp.Error,
  50. resp.Result.Set(ctx, total),
  51. )
  52. }