-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsubscription_store.go
More file actions
770 lines (688 loc) · 22.4 KB
/
subscription_store.go
File metadata and controls
770 lines (688 loc) · 22.4 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
package payment
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/lib/pq"
)
var ErrSubscriptionNotFound = errors.New("subscription not found")
var ErrUserNotFound = errors.New("user not found")
var ErrUserRoleNotFound = errors.New("user role not found")
const teamRoleID = 3
// SubscriptionStore handles persistence for subscription lifecycle operations.
type SubscriptionStore struct {
db *sql.DB
}
func NewSubscriptionStore(db *sql.DB) *SubscriptionStore {
return &SubscriptionStore{db: db}
}
type CreateTeamSubscriptionRecordInput struct {
SubscriptionID string
OwnerUserID int
OrgID int
DBPlanType string
Quantity int
Status string
RazorpayPlanID string
CurrentPeriodStart time.Time
CurrentPeriodEnd time.Time
LicenseExpiresAt time.Time
ShortURL string
Notes map[string]string
}
func (s *SubscriptionStore) CreateTeamSubscriptionRecord(input CreateTeamSubscriptionRecordInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
notesJSON, err := json.Marshal(input.Notes)
if err != nil {
return fmt.Errorf("failed to marshal notes: %w", err)
}
_, err = tx.Exec(`
INSERT INTO subscriptions (
razorpay_subscription_id, owner_user_id, org_id, plan_type,
quantity, assigned_seats, status, razorpay_plan_id,
current_period_start, current_period_end, license_expires_at,
short_url, notes, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, NOW(), NOW())`,
input.SubscriptionID, input.OwnerUserID, input.OrgID, input.DBPlanType,
input.Quantity, 0, input.Status, input.RazorpayPlanID,
input.CurrentPeriodStart, input.CurrentPeriodEnd, input.LicenseExpiresAt,
input.ShortURL, notesJSON,
)
if err != nil {
return fmt.Errorf("failed to insert subscription: %w", err)
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"plan_id": input.RazorpayPlanID,
"quantity": input.Quantity,
"status": input.Status,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
input.OwnerUserID, input.OrgID, "subscription_created",
fmt.Sprintf("Created %s subscription with %d seats", input.DBPlanType, input.Quantity),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log subscription creation: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type UpdateSubscriptionQuantityRecordInput struct {
SubscriptionID string
Quantity int
ScheduleChangeAt int64
Status string
HasScheduledChanges bool
}
func (s *SubscriptionStore) UpdateSubscriptionQuantityRecord(input UpdateSubscriptionQuantityRecordInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
var ownerUserID, orgID int
err = tx.QueryRow(`
SELECT owner_user_id, org_id
FROM subscriptions
WHERE razorpay_subscription_id = $1`,
input.SubscriptionID,
).Scan(&ownerUserID, &orgID)
if err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%w: %s", ErrSubscriptionNotFound, input.SubscriptionID)
}
return fmt.Errorf("failed to get subscription details: %w", err)
}
_, err = tx.Exec(`
UPDATE subscriptions
SET quantity = $1,
status = $2,
updated_at = NOW()
WHERE razorpay_subscription_id = $3`,
input.Quantity, input.Status, input.SubscriptionID,
)
if err != nil {
return fmt.Errorf("failed to update subscription: %w", err)
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"new_quantity": input.Quantity,
"schedule_change_at": input.ScheduleChangeAt,
"has_scheduled_change": input.HasScheduledChanges,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
ownerUserID, orgID, "subscription_quantity_updated",
fmt.Sprintf("Updated subscription quantity to %d", input.Quantity),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log quantity update: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type CancelSubscriptionRecordInput struct {
SubscriptionID string
Immediate bool
Status string
}
func (s *SubscriptionStore) CancelSubscriptionRecord(input CancelSubscriptionRecordInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
var ownerUserID, orgID int
err = tx.QueryRow(`
SELECT owner_user_id, org_id
FROM subscriptions
WHERE razorpay_subscription_id = $1`,
input.SubscriptionID,
).Scan(&ownerUserID, &orgID)
if err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%w: %s", ErrSubscriptionNotFound, input.SubscriptionID)
}
return fmt.Errorf("failed to get subscription details: %w", err)
}
_, err = tx.Exec(`
UPDATE subscriptions
SET status = $1,
cancel_at_period_end = $2,
updated_at = NOW()
WHERE razorpay_subscription_id = $3`,
input.Status, !input.Immediate, input.SubscriptionID,
)
if err != nil {
return fmt.Errorf("failed to update subscription: %w", err)
}
if input.Immediate {
_, err = tx.Exec(`
UPDATE user_roles
SET plan_type = 'free',
license_expires_at = NULL,
active_subscription_id = NULL,
updated_at = NOW()
WHERE user_id = $1 AND org_id = $2`,
ownerUserID, orgID,
)
if err != nil {
return fmt.Errorf("failed to update user_roles: %w", err)
}
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"immediate": input.Immediate,
"status": input.Status,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
ownerUserID, orgID, "subscription_cancelled",
fmt.Sprintf("Cancelled subscription (immediate: %t)", input.Immediate),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log cancellation: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type SubscriptionDetailsRow struct {
ID int64
RazorpaySubscriptionID string
OwnerUserID int
OrgID int
PlanType string
Quantity int
AssignedSeats int
Status string
LicenseExpiresAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
PaymentVerified bool
LastPaymentID sql.NullString
LastPaymentStatus sql.NullString
LastPaymentReceivedAt sql.NullTime
}
func (s *SubscriptionStore) GetSubscriptionDetailsRow(subscriptionID string) (*SubscriptionDetailsRow, error) {
var row SubscriptionDetailsRow
err := s.db.QueryRow(`
SELECT s.id, s.razorpay_subscription_id, s.owner_user_id, s.org_id, s.plan_type, s.quantity,
COALESCE((SELECT COUNT(*) FROM user_roles ur WHERE ur.active_subscription_id = s.id AND ur.plan_type = 'team'), 0) as assigned_seats,
s.status, s.license_expires_at, s.created_at, s.updated_at,
s.payment_verified, s.last_payment_id, s.last_payment_status, s.last_payment_received_at
FROM subscriptions s
WHERE s.razorpay_subscription_id = $1`,
subscriptionID,
).Scan(
&row.ID, &row.RazorpaySubscriptionID, &row.OwnerUserID, &row.OrgID, &row.PlanType,
&row.Quantity, &row.AssignedSeats, &row.Status,
&row.LicenseExpiresAt, &row.CreatedAt, &row.UpdatedAt,
&row.PaymentVerified, &row.LastPaymentID, &row.LastPaymentStatus, &row.LastPaymentReceivedAt,
)
if err == sql.ErrNoRows {
return nil, fmt.Errorf("%w: %s", ErrSubscriptionNotFound, subscriptionID)
}
if err != nil {
return nil, fmt.Errorf("failed to get subscription from DB: %w", err)
}
return &row, nil
}
type AssignLicenseInput struct {
SubscriptionID string
UserID int
OrgID int
}
func (s *SubscriptionStore) AssignLicense(input AssignLicenseInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
var quantity int
var dbSubscriptionID int64
var licenseExpiresAt time.Time
var assignedSeats int
var paymentVerified bool
var lastPaymentStatus sql.NullString
err = tx.QueryRow(`
SELECT s.id, s.quantity, s.license_expires_at, s.payment_verified, s.last_payment_status,
COALESCE((SELECT COUNT(*) FROM user_roles ur WHERE ur.active_subscription_id = s.id AND ur.plan_type = 'team'), 0) as assigned_seats
FROM subscriptions s
WHERE s.razorpay_subscription_id = $1
FOR UPDATE`,
input.SubscriptionID,
).Scan(&dbSubscriptionID, &quantity, &licenseExpiresAt, &paymentVerified, &lastPaymentStatus, &assignedSeats)
if err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%w: %s", ErrSubscriptionNotFound, input.SubscriptionID)
}
return fmt.Errorf("failed to get subscription: %w", err)
}
if !paymentVerified {
return fmt.Errorf("payment pending - licenses cannot be assigned until payment is received. Check back in 5-10 minutes")
}
if assignedSeats >= quantity {
return fmt.Errorf("subscription at capacity: %d/%d seats used", assignedSeats, quantity)
}
var existingSubID sql.NullInt64
var existingRazorpaySubID sql.NullString
err = tx.QueryRow(`
SELECT ur.active_subscription_id, s.razorpay_subscription_id
FROM user_roles ur
LEFT JOIN subscriptions s ON ur.active_subscription_id = s.id
WHERE ur.user_id = $1 AND ur.org_id = $2 AND ur.plan_type = 'team'`,
input.UserID, input.OrgID,
).Scan(&existingSubID, &existingRazorpaySubID)
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("failed to check existing subscription: %w", err)
}
if existingSubID.Valid && existingSubID.Int64 != dbSubscriptionID {
return fmt.Errorf("user already has an active license from subscription %s - please revoke that first", existingRazorpaySubID.String)
}
_, err = tx.Exec(`
UPDATE user_roles
SET plan_type = 'team',
license_expires_at = $1,
active_subscription_id = $2,
updated_at = NOW()
WHERE user_id = $3 AND org_id = $4`,
licenseExpiresAt, dbSubscriptionID, input.UserID, input.OrgID,
)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok && pqErr.Code == "23503" {
_, err = tx.Exec(`
INSERT INTO user_roles (
user_id, org_id, role_id, plan_type, license_expires_at, active_subscription_id, created_at, updated_at
) VALUES ($1, $2, $3, 'team', $4, $5, NOW(), NOW())`,
input.UserID, input.OrgID, teamRoleID, licenseExpiresAt, dbSubscriptionID,
)
if err != nil {
return fmt.Errorf("failed to create user_roles: %w", err)
}
} else {
return fmt.Errorf("failed to update user_roles: %w", err)
}
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"assigned_to": input.UserID,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
input.UserID, input.OrgID, "license_assigned",
fmt.Sprintf("License assigned from subscription %s", input.SubscriptionID),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log license assignment: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type RevokeLicenseInput struct {
SubscriptionID string
UserID int
OrgID int
}
func (s *SubscriptionStore) RevokeLicense(input RevokeLicenseInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
var dbSubscriptionID int64
err = tx.QueryRow(`
SELECT id
FROM subscriptions
WHERE razorpay_subscription_id = $1`,
input.SubscriptionID,
).Scan(&dbSubscriptionID)
if err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%w: %s", ErrSubscriptionNotFound, input.SubscriptionID)
}
return fmt.Errorf("failed to get subscription: %w", err)
}
var currentSubID sql.NullInt64
err = tx.QueryRow(`
SELECT active_subscription_id
FROM user_roles
WHERE user_id = $1 AND org_id = $2`,
input.UserID, input.OrgID,
).Scan(¤tSubID)
if err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%w: user_id=%d org_id=%d", ErrUserRoleNotFound, input.UserID, input.OrgID)
}
return fmt.Errorf("failed to get user_roles: %w", err)
}
if !currentSubID.Valid || currentSubID.Int64 != dbSubscriptionID {
return fmt.Errorf("user %d does not have subscription %s", input.UserID, input.SubscriptionID)
}
_, err = tx.Exec(`
UPDATE user_roles
SET plan_type = 'free',
license_expires_at = NULL,
active_subscription_id = NULL,
updated_at = NOW()
WHERE user_id = $1 AND org_id = $2`,
input.UserID, input.OrgID,
)
if err != nil {
return fmt.Errorf("failed to update user_roles: %w", err)
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"revoked_from": input.UserID,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
input.UserID, input.OrgID, "license_revoked",
fmt.Sprintf("License revoked from subscription %s", input.SubscriptionID),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log license revocation: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
func (s *SubscriptionStore) GetUserIDByEmail(email string) (int64, error) {
var userID int64
err := s.db.QueryRow(`SELECT id FROM users WHERE email = $1`, email).Scan(&userID)
if err != nil {
if err == sql.ErrNoRows {
return 0, ErrUserNotFound
}
return 0, err
}
return userID, nil
}
func (s *SubscriptionStore) CreateShadowUser(email, passwordHash string) (int64, error) {
var userID int64
err := s.db.QueryRow(`
INSERT INTO users (email, password_hash, created_at, updated_at)
VALUES ($1, $2, NOW(), NOW())
RETURNING id`,
email, passwordHash,
).Scan(&userID)
if err != nil {
return 0, fmt.Errorf("failed to create shadow user: %w", err)
}
return userID, nil
}
type CreateSelfHostedSubscriptionRecordInput struct {
SubscriptionID string
UserID int64
Quantity int
Status string
RazorpayPlanID string
CurrentPeriodStart time.Time
CurrentPeriodEnd time.Time
LicenseExpiresAt time.Time
ShortURL string
Notes map[string]string
Email string
}
func (s *SubscriptionStore) CreateSelfHostedSubscriptionRecord(input CreateSelfHostedSubscriptionRecordInput) error {
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
notesJSON, err := json.Marshal(input.Notes)
if err != nil {
return fmt.Errorf("failed to marshal notes: %w", err)
}
_, err = tx.Exec(`
INSERT INTO subscriptions (
razorpay_subscription_id, owner_user_id, org_id, plan_type,
quantity, assigned_seats, status, razorpay_plan_id,
current_period_start, current_period_end, license_expires_at,
short_url, notes, created_at, updated_at
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, NOW(), NOW())`,
input.SubscriptionID, input.UserID, nil, "selfhosted_annual",
input.Quantity, 0, input.Status, input.RazorpayPlanID,
input.CurrentPeriodStart, input.CurrentPeriodEnd, input.LicenseExpiresAt,
input.ShortURL, notesJSON,
)
if err != nil {
return fmt.Errorf("failed to insert subscription: %w", err)
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"plan_id": input.RazorpayPlanID,
"email": input.Email,
"quantity": input.Quantity,
"status": input.Status,
"purpose": "self_hosted_purchase",
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
nil, nil, "selfhosted_subscription_created",
fmt.Sprintf("Created self-hosted subscription for email: %s", input.Email),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log subscription creation: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type SelfHostedConfirmationSeed struct {
SubscriptionDBID int64
Email string
Quantity int
}
func (s *SubscriptionStore) GetSelfHostedConfirmationSeed(subscriptionID string) (SelfHostedConfirmationSeed, error) {
var seed SelfHostedConfirmationSeed
var notesJSON []byte
err := s.db.QueryRow(`
SELECT id, notes, quantity
FROM subscriptions
WHERE razorpay_subscription_id = $1 AND plan_type = 'selfhosted_annual'`,
subscriptionID,
).Scan(&seed.SubscriptionDBID, ¬esJSON, &seed.Quantity)
if err != nil {
if err == sql.ErrNoRows {
return SelfHostedConfirmationSeed{}, fmt.Errorf("%w: %s", ErrSubscriptionNotFound, subscriptionID)
}
return SelfHostedConfirmationSeed{}, fmt.Errorf("failed to fetch self-hosted confirmation seed: %w", err)
}
var notes map[string]string
if err := json.Unmarshal(notesJSON, ¬es); err != nil {
return SelfHostedConfirmationSeed{}, fmt.Errorf("failed to decode subscription notes: %w", err)
}
seed.Email = notes["email"]
return seed, nil
}
type PersistSelfHostedFallbackInput struct {
SubscriptionDBID int64
PaymentID string
PaymentStatus string
PaymentAmount int64
PaymentCurrency string
PaymentCaptured bool
PaymentMethod string
PaymentJSON []byte
LicenseKey string
}
func (s *SubscriptionStore) PersistSelfHostedFallback(input PersistSelfHostedFallbackInput) error {
if input.LicenseKey == "" {
return fmt.Errorf("license key cannot be empty")
}
if len(input.LicenseKey) > 8192 {
return fmt.Errorf("license key too large")
}
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
_, err = tx.Exec(`
UPDATE subscriptions
SET last_payment_id = $1,
last_payment_status = $2,
last_payment_received_at = NOW(),
payment_verified = TRUE,
notes = jsonb_set(COALESCE(notes, '{}'::jsonb), '{license_key}', to_jsonb($3::text)),
updated_at = NOW()
WHERE id = $4`,
input.PaymentID, input.PaymentStatus, input.LicenseKey, input.SubscriptionDBID,
)
if err != nil {
return fmt.Errorf("failed to update subscription: %w", err)
}
_, err = tx.Exec(`
INSERT INTO subscription_payments (
subscription_id, razorpay_payment_id, amount, currency,
status, captured, method, created_at, razorpay_data
) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), $8)
ON CONFLICT (razorpay_payment_id) DO NOTHING`,
input.SubscriptionDBID, input.PaymentID, input.PaymentAmount, input.PaymentCurrency,
input.PaymentStatus, input.PaymentCaptured, input.PaymentMethod, input.PaymentJSON,
)
if err != nil {
return fmt.Errorf("failed to insert payment record: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
type PersistSelfHostedJWTInput struct {
SubscriptionID string
SubscriptionDBID int64
PaymentID string
PaymentStatus string
PaymentAmount int64
PaymentCurrency string
PaymentCaptured bool
PaymentMethod string
PaymentJSON []byte
JWTToken string
Email string
}
func (s *SubscriptionStore) PersistSelfHostedJWT(input PersistSelfHostedJWTInput) error {
if input.JWTToken == "" {
return fmt.Errorf("jwt token cannot be empty")
}
if len(input.JWTToken) > 8192 {
return fmt.Errorf("jwt token too large")
}
tx, err := s.db.Begin()
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
_, err = tx.Exec(`
UPDATE subscriptions
SET last_payment_id = $1,
last_payment_status = $2,
last_payment_received_at = NOW(),
payment_verified = TRUE,
notes = jsonb_set(COALESCE(notes, '{}'::jsonb), '{jwt_token}', to_jsonb($3::text)),
updated_at = NOW()
WHERE id = $4`,
input.PaymentID, input.PaymentStatus, input.JWTToken, input.SubscriptionDBID,
)
if err != nil {
return fmt.Errorf("failed to update subscription: %w", err)
}
_, err = tx.Exec(`
INSERT INTO subscription_payments (
subscription_id, razorpay_payment_id, amount, currency,
status, captured, method, created_at, razorpay_data
) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), $8)
ON CONFLICT (razorpay_payment_id) DO NOTHING`,
input.SubscriptionDBID, input.PaymentID, input.PaymentAmount, input.PaymentCurrency,
input.PaymentStatus, input.PaymentCaptured, input.PaymentMethod, input.PaymentJSON,
)
if err != nil {
return fmt.Errorf("failed to insert payment record: %w", err)
}
metadata := map[string]interface{}{
"subscription_id": input.SubscriptionID,
"payment_id": input.PaymentID,
"email": input.Email,
"jwt_issued": true,
"amount": input.PaymentAmount,
}
metadataJSON, err := json.Marshal(metadata)
if err != nil {
return fmt.Errorf("failed to marshal log metadata: %w", err)
}
_, err = tx.Exec(`
INSERT INTO license_log (
user_id, org_id, event_type, description, metadata, created_at
) VALUES ($1, $2, $3, $4, $5, NOW())`,
nil, nil, "selfhosted_license_generated",
fmt.Sprintf("Generated self-hosted JWT license for %s", input.Email),
metadataJSON,
)
if err != nil {
return fmt.Errorf("failed to log license generation: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}