File size: 7,456 Bytes
16cdcb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package adapter

import (
	"cmp"
	"context"
	"encoding/json"
	"fmt"
	"slices"

	"entgo.io/ent/dialect/sql"

	"github.com/openmeterio/openmeter/openmeter/ent/db"
	taxcodedb "github.com/openmeterio/openmeter/openmeter/ent/db/taxcode"
	"github.com/openmeterio/openmeter/openmeter/taxcode"
	"github.com/openmeterio/openmeter/pkg/clock"
	"github.com/openmeterio/openmeter/pkg/framework/entutils"
	"github.com/openmeterio/openmeter/pkg/models"
	"github.com/openmeterio/openmeter/pkg/pagination"
)

func (a *adapter) CreateTaxCode(ctx context.Context, input taxcode.CreateTaxCodeInput) (taxcode.TaxCode, error) {
	if err := input.Validate(); err != nil {
		return taxcode.TaxCode{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (taxcode.TaxCode, error) {
		query := a.db.TaxCode.Create().
			SetNamespace(input.Namespace).
			SetKey(input.Key).
			SetName(input.Name).
			SetNillableDescription(input.Description).
			SetMetadata(input.Metadata).
			SetAnnotations(input.Annotations)

		if len(input.AppMappings) > 0 {
			query = query.SetAppMappings(&input.AppMappings)
		}

		entity, err := query.Save(ctx)
		if err != nil {
			if db.IsConstraintError(err) {
				return taxcode.TaxCode{}, models.NewGenericConflictError(fmt.Errorf("tax code with the same key already exists"))
			}

			return taxcode.TaxCode{}, fmt.Errorf("failed to create tax code: %w", err)
		}

		return MapTaxCodeFromEntity(entity)
	})
}

func (a *adapter) UpdateTaxCode(ctx context.Context, input taxcode.UpdateTaxCodeInput) (taxcode.TaxCode, error) {
	if err := input.Validate(); err != nil {
		return taxcode.TaxCode{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (taxcode.TaxCode, error) {
		query := a.db.TaxCode.UpdateOneID(input.ID).
			Where(taxcodedb.NamespaceEQ(input.Namespace)).
			Where(taxcodedb.DeletedAtIsNil()).
			SetName(input.Name).
			SetNillableDescription(input.Description).
			SetMetadata(input.Metadata).
			SetAnnotations(input.Annotations)

		if len(input.AppMappings) > 0 {
			query = query.SetAppMappings(&input.AppMappings)
		} else {
			query = query.ClearAppMappings()
		}

		entity, err := query.Save(ctx)
		if err != nil {
			if db.IsNotFound(err) {
				return taxcode.TaxCode{}, taxcode.NewTaxCodeNotFoundError(input.ID)
			}

			return taxcode.TaxCode{}, fmt.Errorf("failed to update tax code: %w", err)
		}

		return MapTaxCodeFromEntity(entity)
	})
}

func (a *adapter) ListTaxCodes(ctx context.Context, input taxcode.ListTaxCodesInput) (pagination.Result[taxcode.TaxCode], error) {
	if err := input.Validate(); err != nil {
		return pagination.Result[taxcode.TaxCode]{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (pagination.Result[taxcode.TaxCode], error) {
		query := a.db.TaxCode.Query().
			Where(taxcodedb.Namespace(input.Namespace))
		if !input.IncludeDeleted {
			query = query.Where(taxcodedb.DeletedAtIsNil())
		}

		entities, err := query.Paginate(ctx, input.Page)
		if err != nil {
			return pagination.Result[taxcode.TaxCode]{}, fmt.Errorf("failed to list tax codes: %w", err)
		}

		return pagination.MapResultErr(entities, MapTaxCodeFromEntity)
	})
}

func (a *adapter) GetTaxCode(ctx context.Context, input taxcode.GetTaxCodeInput) (taxcode.TaxCode, error) {
	if err := input.Validate(); err != nil {
		return taxcode.TaxCode{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (taxcode.TaxCode, error) {
		query := a.db.TaxCode.Query().
			Where(taxcodedb.Namespace(input.Namespace)).
			Where(taxcodedb.ID(input.ID))
		if !input.IncludeDeleted {
			query = query.Where(taxcodedb.DeletedAtIsNil())
		}

		entity, err := query.Only(ctx)
		if err != nil {
			if db.IsNotFound(err) {
				return taxcode.TaxCode{}, taxcode.NewTaxCodeNotFoundError(input.ID)
			}

			return taxcode.TaxCode{}, fmt.Errorf("failed to get tax code: %w", err)
		}

		return MapTaxCodeFromEntity(entity)
	})
}

func (a *adapter) GetTaxCodeByKey(ctx context.Context, input taxcode.GetTaxCodeByKeyInput) (taxcode.TaxCode, error) {
	if err := input.Validate(); err != nil {
		return taxcode.TaxCode{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (taxcode.TaxCode, error) {
		query := a.db.TaxCode.Query().
			Where(taxcodedb.Namespace(input.Namespace)).
			Where(taxcodedb.Key(input.Key)).
			Where(taxcodedb.DeletedAtIsNil())

		entity, err := query.Only(ctx)
		if err != nil {
			if db.IsNotFound(err) {
				return taxcode.TaxCode{}, taxcode.NewTaxCodeByKeyNotFoundError(input.Key)
			}

			return taxcode.TaxCode{}, fmt.Errorf("failed to get tax code by key: %w", err)
		}

		return MapTaxCodeFromEntity(entity)
	})
}

func (a *adapter) GetTaxCodeByAppMapping(ctx context.Context, input taxcode.GetTaxCodeByAppMappingInput) (taxcode.TaxCode, error) {
	if err := input.Validate(); err != nil {
		return taxcode.TaxCode{}, err
	}

	return entutils.TransactingRepo(ctx, a, func(ctx context.Context, a *adapter) (taxcode.TaxCode, error) {
		// Build a JSONB containment query: app_mappings @> '[{"app_type": "...", "tax_code": "..."}]'
		pattern, err := json.Marshal([]taxcode.TaxCodeAppMapping{
			{AppType: input.AppType, TaxCode: input.TaxCode},
		})
		if err != nil {
			return taxcode.TaxCode{}, fmt.Errorf("failed to marshal app mapping pattern: %w", err)
		}

		entities, err := a.db.TaxCode.Query().
			Where(taxcodedb.Namespace(input.Namespace)).
			Where(taxcodedb.DeletedAtIsNil()).
			Where(func(s *sql.Selector) {
				s.Where(sql.P(func(b *sql.Builder) {
					b.Ident(taxcodedb.FieldAppMappings).WriteString(" @> ").Arg(string(pattern))
				}))
			}).
			All(ctx)
		if err != nil {
			return taxcode.TaxCode{}, fmt.Errorf("failed to get tax code by app mapping: %w", err)
		}

		if len(entities) == 0 {
			return taxcode.TaxCode{}, taxcode.NewTaxCodeByAppMappingNotFoundError(
				string(input.AppType), input.TaxCode,
			)
		}

		slices.SortStableFunc(entities, func(a, b *db.TaxCode) int {
			aManagedBy, _ := a.Annotations.GetString(taxcode.AnnotationKeyManagedBy)
			bManagedBy, _ := b.Annotations.GetString(taxcode.AnnotationKeyManagedBy)

			aSystemManaged := aManagedBy == taxcode.AnnotationValueManagedBySystem
			bSystemManaged := bManagedBy == taxcode.AnnotationValueManagedBySystem

			if aSystemManaged && !bSystemManaged {
				return -1
			}

			if !aSystemManaged && bSystemManaged {
				return 1
			}

			if byCreatedAt := a.CreatedAt.Compare(b.CreatedAt); byCreatedAt != 0 {
				return byCreatedAt
			}

			return cmp.Compare(a.ID, b.ID)
		})

		return MapTaxCodeFromEntity(entities[0])
	})
}

func (a *adapter) DeleteTaxCode(ctx context.Context, input taxcode.DeleteTaxCodeInput) error {
	if err := input.Validate(); err != nil {
		return err
	}

	return entutils.TransactingRepoWithNoValue(ctx, a, func(ctx context.Context, a *adapter) error {
		entity, err := a.db.TaxCode.Query().
			Where(taxcodedb.Namespace(input.Namespace)).
			Where(taxcodedb.ID(input.ID)).
			Only(ctx)
		if err != nil {
			if db.IsNotFound(err) {
				return taxcode.NewTaxCodeNotFoundError(input.ID)
			}

			return fmt.Errorf("failed to get tax code: %w", err)
		}

		if entity.DeletedAt == nil {
			err := a.db.TaxCode.UpdateOneID(input.ID).
				Where(taxcodedb.Namespace(input.Namespace)).
				SetDeletedAt(clock.Now()).
				Exec(ctx)
			if err != nil {
				return fmt.Errorf("failed to delete tax code: %w", err)
			}
		}

		return nil
	})
}