File size: 10,993 Bytes
1c4c66b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package service

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/samber/lo"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"

	"github.com/openmeterio/openmeter/openmeter/billing"
	"github.com/openmeterio/openmeter/openmeter/billing/worker/subscriptionsync"
	"github.com/openmeterio/openmeter/openmeter/billing/worker/subscriptionsync/service/reconciler"
	"github.com/openmeterio/openmeter/openmeter/customer"
	"github.com/openmeterio/openmeter/openmeter/subscription"
	"github.com/openmeterio/openmeter/pkg/clock"
	"github.com/openmeterio/openmeter/pkg/convert"
	"github.com/openmeterio/openmeter/pkg/currencyx"
	"github.com/openmeterio/openmeter/pkg/filter"
	"github.com/openmeterio/openmeter/pkg/framework/tracex"
	"github.com/openmeterio/openmeter/pkg/models"
	"github.com/openmeterio/openmeter/pkg/pagination"
)

const (
	SubscriptionSyncComponentName billing.ComponentName = "subscription-sync"
)

func (s *Service) invoicePendingLines(ctx context.Context, customer customer.CustomerID) error {
	span := tracex.StartWithNoValue(ctx, s.tracer, "billing.worker.subscription.sync.invoicePendingLines", trace.WithAttributes(
		attribute.String("customer_id", customer.ID),
	))

	return span.Wrap(func(ctx context.Context) error {
		_, err := s.billingService.InvoicePendingLines(
			ctx,
			billing.InvoicePendingLinesInput{
				Customer:          customer,
				ForceAsyncAdvance: s.forceAsyncInvoicePendingLines,
			},
			billing.WithPartialInvoiceLinesDisabled(),
			billing.WithMaxLinesPerInvoice(s.featureFlags.MaxLinesPerCollectedInvoice),
		)
		if err != nil {
			if errors.Is(err, billing.ErrInvoiceCreateNoLines) {
				return nil
			}

			return err
		}

		return nil
	})
}

func (s *Service) HandleSubscriptionSyncEvent(ctx context.Context, event *subscription.SubscriptionSyncEvent) error {
	if event == nil {
		return nil
	}

	return s.synchronizeSubscriptionAndInvoiceCustomer(ctx, newSubscriptionReferenceOrView(event.Subscription), time.Now())
}

func (s *Service) synchronizeSubscriptionAndInvoiceCustomer(ctx context.Context, refOrView subscriptionReferenceOrView, asOf time.Time) error {
	res, err := s.synchronizeSubscription(ctx, refOrView, asOf)
	if err != nil {
		return fmt.Errorf("synchronize subscription: %w", err)
	}

	if res != nil && res.View != nil {
		customerID := customer.CustomerID{
			Namespace: res.View.Subscription.Namespace,
			ID:        res.View.Subscription.CustomerId,
		}
		// Invoice any pending lines invoicable now, so that any in advance fees are invoiced immediately.
		if err := s.invoicePendingLines(ctx, customerID); err != nil {
			return fmt.Errorf("invoice pending lines (post): %w [customer_id=%s]", err, customerID.ID)
		}
	}

	return nil
}

type synchronizeSubscriptionResult struct {
	View    *subscription.SubscriptionView
	Deleted bool
}

func (s *Service) synchronizeSubscription(ctx context.Context, refOrView subscriptionReferenceOrView, asOf time.Time, opts ...subscriptionsync.SynchronizeSubscriptionOption) (*synchronizeSubscriptionResult, error) {
	subscriptionID := refOrView.GetID()

	span := tracex.Start[*synchronizeSubscriptionResult](ctx, s.tracer, "billing.worker.subscription.sync.SynchronizeSubscription", trace.WithAttributes(
		attribute.String("subscription_id", subscriptionID.ID),
		attribute.String("as_of", asOf.Format(time.RFC3339)),
	))

	options := subscriptionsync.SynchronizeSubscriptionOptions{}
	for _, opt := range opts {
		opt(&options)
	}

	return span.Wrap(func(ctx context.Context) (*synchronizeSubscriptionResult, error) {
		subs, err := s.getSubscription(ctx, subscriptionID)
		if err != nil {
			return nil, err
		}

		var subsView *subscription.SubscriptionView
		if subs.IsDeleted() {
			subsView = nil
		} else if refOrView.Type() == SubscriptionReferenceTypeView {
			view, err := refOrView.AsSubscriptionView()
			if err != nil {
				return nil, err
			}

			subsView = &view
		} else {
			view, err := s.subscriptionService.GetView(ctx, subscriptionID)
			if err != nil {
				return nil, err
			}

			subsView = &view
		}

		res := &synchronizeSubscriptionResult{
			View:    subsView,
			Deleted: subs.IsDeleted(),
		}

		customerID := customer.CustomerID{
			Namespace: subs.Namespace,
			ID:        subs.CustomerId,
		}

		var customerDeletedAt *time.Time
		var subscriptionEndProrationMode billing.SubscriptionEndProrationMode
		if subsView != nil && subsView.Spec.HasBillables() {
			// TODO[later]: Right now we are getting the billing profile as a validation step, but later if we allow more collection
			// alignment settings, we should use the collection settings from here to determine the generation end (overriding asof).
			customerOverride, err := s.billingService.GetCustomerOverride(ctx, billing.GetCustomerOverrideInput{
				Customer: customerID,
				Expand: billing.CustomerOverrideExpand{
					Customer: true,
				},
			})
			if err != nil {
				return nil, fmt.Errorf("getting billing profile: %w", err)
			}

			if customerOverride.Customer != nil {
				customerDeletedAt = convert.SafeToUTC(customerOverride.Customer.GetDeletedAt())
			}
			subscriptionEndProrationMode = customerOverride.MergedProfile.WorkflowConfig.Invoicing.SubscriptionEndProrationMode

			if customerOverride.Customer != nil && customerOverride.Customer.DeletedAt != nil && !customerOverride.Customer.DeletedAt.After(subsView.Spec.ActiveFrom) {
				if options.DryRun {
					return res, nil
				}

				if err := s.updateSyncState(ctx, updateSyncStateInput{
					SubscriptionID: subscriptionID,
					// Prevent deleted customers from continuing to be scheduled for sync.
					PreventFurtherSyncs: true,
				}); err != nil {
					return nil, fmt.Errorf("updating sync state: %w", err)
				}

				s.logger.WarnContext(ctx, "customer deleted before subscription start, skipping sync", "subscription_id", subscriptionID.ID, "customer_id", customerID.ID)
				return res, nil
			}
		}

		cur, err := currencyx.NewCurrencyBuilder(currencyx.CurrencyTypeFiat).
			WithCode(subs.Currency).
			Build()
		if err != nil {
			return nil, fmt.Errorf("getting currency calculator: %w", err)
		}

		return withBillingLock(ctx, s, customer.CustomerID{
			Namespace: subs.Namespace,
			ID:        subs.CustomerId,
		}, func(ctx context.Context) (*synchronizeSubscriptionResult, error) {
			// Calculate per line patches
			linesDiff, err := s.buildSyncPlan(ctx, buildSyncPlanInput{
				Subscription:                 subs,
				SubscriptionView:             subsView,
				AsOf:                         asOf,
				CustomerDeletedAt:            customerDeletedAt,
				SubscriptionEndProrationMode: subscriptionEndProrationMode,
				Currency:                     cur,
				DryRun:                       options.DryRun,
			})
			if err != nil {
				return nil, err
			}

			// If we have a view, we can use it to determine if the subscription has billables, if the
			// subscription is deleted (no view), let's set hasBillables to false, so that we prevent further syncs.
			hasBillables := false
			if subsView != nil {
				hasBillables = subsView.Spec.HasBillables()
			}

			if linesDiff == nil || linesDiff.IsEmpty() {
				if options.DryRun {
					return res, nil
				}

				generationLimit := time.Time{}
				if linesDiff != nil {
					generationLimit = linesDiff.SubscriptionMaxGenerationTimeLimit
				}

				if err := s.updateSyncState(ctx, updateSyncStateInput{
					SubscriptionID:         subscriptionID,
					MaxGenerationTimeLimit: generationLimit,
					HasBillables:           hasBillables,
				}); err != nil {
					return nil, fmt.Errorf("updating sync state: %w", err)
				}

				return res, nil
			}

			if err := s.reconciler.Apply(ctx, reconciler.ApplyInput{
				DryRun:   options.DryRun,
				Customer: customerID,
				Currency: cur,
				Plan:     linesDiff,
			}); err != nil {
				return nil, err
			}

			if options.DryRun {
				return res, nil
			}

			if err := s.updateSyncState(ctx, updateSyncStateInput{
				SubscriptionID:         subscriptionID,
				MaxGenerationTimeLimit: linesDiff.SubscriptionMaxGenerationTimeLimit,
				HasBillables:           hasBillables,
			}); err != nil {
				return nil, fmt.Errorf("updating sync state: %w", err)
			}

			return res, nil
		})
	})
}

func withBillingLock[T any](ctx context.Context, s *Service, customerID customer.CustomerID, fn func(ctx context.Context) (T, error)) (T, error) {
	var out T
	err := s.billingService.WithLock(ctx, customerID, func(ctx context.Context) error {
		var err error
		out, err = fn(ctx)
		return err
	})
	if err != nil {
		return lo.Empty[T](), err
	}

	return out, nil
}

func (s *Service) getSubscription(ctx context.Context, subscriptionID models.NamespacedID) (subscription.Subscription, error) {
	subs, err := s.subscriptionService.List(ctx, subscription.ListSubscriptionsInput{
		Namespaces:     []string{subscriptionID.Namespace},
		ID:             &filter.FilterULID{FilterString: filter.FilterString{In: &[]string{subscriptionID.ID}}},
		IncludeDeleted: true,
		Page: pagination.Page{
			PageNumber: 1,
			PageSize:   1,
		},
	})
	if err != nil {
		return subscription.Subscription{}, fmt.Errorf("getting subscription: %w", err)
	}

	if len(subs.Items) == 0 {
		return subscription.Subscription{}, subscription.NewSubscriptionNotFoundError(subscriptionID.ID)
	}

	return subs.Items[0], nil
}

type updateSyncStateInput struct {
	SubscriptionID         models.NamespacedID
	MaxGenerationTimeLimit time.Time
	PreventFurtherSyncs    bool
	HasBillables           bool
}

func (s *Service) updateSyncState(ctx context.Context, in updateSyncStateInput) error {
	span := tracex.StartWithNoValue(ctx, s.tracer, "billing.worker.subscription.sync.updateSyncState", trace.WithAttributes(
		attribute.String("subscription_id", in.SubscriptionID.ID),
		attribute.String("max_generation_time_limit", in.MaxGenerationTimeLimit.Format(time.RFC3339)),
	))

	return span.Wrap(func(ctx context.Context) error {
		hasBillables := in.HasBillables
		if in.PreventFurtherSyncs {
			// We are using the hasBillables flag to prevent further syncs, this is used when the customer is
			// deleted etc.
			hasBillables = false
		}

		if !hasBillables {
			return s.subscriptionSyncAdapter.UpsertSyncState(ctx, subscriptionsync.UpsertSyncStateInput{
				SubscriptionID: in.SubscriptionID,
				HasBillables:   false,
				SyncedAt:       clock.Now().UTC(),
			})
		}

		nextSyncAfter := in.MaxGenerationTimeLimit

		if in.MaxGenerationTimeLimit.IsZero() {
			// Fallback: we cannot determine the next sync after, so we'll just mandate the sync
			if nextSyncAfter.IsZero() {
				s.logger.WarnContext(ctx, "cannot determine the next sync after, syncing immediately", "subscription_id", in.SubscriptionID.ID)
				nextSyncAfter = clock.Now().UTC()
			}
		}

		return s.subscriptionSyncAdapter.UpsertSyncState(ctx, subscriptionsync.UpsertSyncStateInput{
			SubscriptionID: in.SubscriptionID,
			HasBillables:   true,
			NextSyncAfter:  lo.ToPtr(nextSyncAfter),
			SyncedAt:       clock.Now().UTC(),
		})
	})
}