|
| 1 | +using System.Globalization; |
| 2 | +using System.Text.Json; |
| 3 | +using Bit.Billing.Services; |
| 4 | +using Bit.Core; |
| 5 | +using Bit.Core.Billing.Constants; |
| 6 | +using Bit.Core.Jobs; |
| 7 | +using Bit.Core.Services; |
| 8 | +using Quartz; |
| 9 | +using Stripe; |
| 10 | + |
| 11 | +namespace Bit.Billing.Jobs; |
| 12 | + |
| 13 | +public class ReconcileAdditionalStorageJob( |
| 14 | + IStripeFacade stripeFacade, |
| 15 | + ILogger<ReconcileAdditionalStorageJob> logger, |
| 16 | + IFeatureService featureService) : BaseJob(logger) |
| 17 | +{ |
| 18 | + private const string _storageGbMonthlyPriceId = "storage-gb-monthly"; |
| 19 | + private const string _storageGbAnnuallyPriceId = "storage-gb-annually"; |
| 20 | + private const string _personalStorageGbAnnuallyPriceId = "personal-storage-gb-annually"; |
| 21 | + private const int _storageGbToRemove = 4; |
| 22 | + |
| 23 | + protected override async Task ExecuteJobAsync(IJobExecutionContext context) |
| 24 | + { |
| 25 | + if (!featureService.IsEnabled(FeatureFlagKeys.PM28265_EnableReconcileAdditionalStorageJob)) |
| 26 | + { |
| 27 | + logger.LogInformation("Skipping ReconcileAdditionalStorageJob, feature flag off."); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + var liveMode = featureService.IsEnabled(FeatureFlagKeys.PM28265_ReconcileAdditionalStorageJobEnableLiveMode); |
| 32 | + |
| 33 | + // Execution tracking |
| 34 | + var subscriptionsFound = 0; |
| 35 | + var subscriptionsUpdated = 0; |
| 36 | + var subscriptionsWithErrors = 0; |
| 37 | + var failures = new List<string>(); |
| 38 | + |
| 39 | + logger.LogInformation("Starting ReconcileAdditionalStorageJob (live mode: {LiveMode})", liveMode); |
| 40 | + |
| 41 | + var priceIds = new[] { _storageGbMonthlyPriceId, _storageGbAnnuallyPriceId, _personalStorageGbAnnuallyPriceId }; |
| 42 | + |
| 43 | + foreach (var priceId in priceIds) |
| 44 | + { |
| 45 | + var options = new SubscriptionListOptions |
| 46 | + { |
| 47 | + Limit = 100, |
| 48 | + Status = StripeConstants.SubscriptionStatus.Active, |
| 49 | + Price = priceId |
| 50 | + }; |
| 51 | + |
| 52 | + await foreach (var subscription in stripeFacade.ListSubscriptionsAutoPagingAsync(options)) |
| 53 | + { |
| 54 | + if (context.CancellationToken.IsCancellationRequested) |
| 55 | + { |
| 56 | + logger.LogWarning( |
| 57 | + "Job cancelled!! Exiting. Progress at time of cancellation: Subscriptions found: {SubscriptionsFound}, " + |
| 58 | + "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", |
| 59 | + subscriptionsFound, |
| 60 | + liveMode |
| 61 | + ? subscriptionsUpdated |
| 62 | + : $"(In live mode, would have updated) {subscriptionsUpdated}", |
| 63 | + subscriptionsWithErrors, |
| 64 | + failures.Count > 0 |
| 65 | + ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" |
| 66 | + : string.Empty |
| 67 | + ); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + if (subscription == null) |
| 72 | + { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + logger.LogInformation("Processing subscription: {SubscriptionId}", subscription.Id); |
| 77 | + subscriptionsFound++; |
| 78 | + |
| 79 | + if (subscription.Metadata?.TryGetValue(StripeConstants.MetadataKeys.StorageReconciled2025, out var dateString) == true) |
| 80 | + { |
| 81 | + if (DateTime.TryParse(dateString, null, DateTimeStyles.RoundtripKind, out var dateProcessed)) |
| 82 | + { |
| 83 | + logger.LogInformation("Skipping subscription {SubscriptionId} - already processed on {Date}", |
| 84 | + subscription.Id, |
| 85 | + dateProcessed.ToString("f")); |
| 86 | + continue; |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + var updateOptions = BuildSubscriptionUpdateOptions(subscription, priceId); |
| 91 | + |
| 92 | + if (updateOptions == null) |
| 93 | + { |
| 94 | + logger.LogInformation("Skipping subscription {SubscriptionId} - no updates needed", subscription.Id); |
| 95 | + continue; |
| 96 | + } |
| 97 | + |
| 98 | + subscriptionsUpdated++; |
| 99 | + |
| 100 | + if (!liveMode) |
| 101 | + { |
| 102 | + logger.LogInformation( |
| 103 | + "Not live mode (dry-run): Would have updated subscription {SubscriptionId} with item changes: {NewLine}{UpdateOptions}", |
| 104 | + subscription.Id, |
| 105 | + Environment.NewLine, |
| 106 | + JsonSerializer.Serialize(updateOptions)); |
| 107 | + continue; |
| 108 | + } |
| 109 | + |
| 110 | + try |
| 111 | + { |
| 112 | + await stripeFacade.UpdateSubscription(subscription.Id, updateOptions); |
| 113 | + logger.LogInformation("Successfully updated subscription: {SubscriptionId}", subscription.Id); |
| 114 | + } |
| 115 | + catch (Exception ex) |
| 116 | + { |
| 117 | + subscriptionsWithErrors++; |
| 118 | + failures.Add($"Subscription {subscription.Id}: {ex.Message}"); |
| 119 | + logger.LogError(ex, "Failed to update subscription {SubscriptionId}: {ErrorMessage}", |
| 120 | + subscription.Id, ex.Message); |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + logger.LogInformation( |
| 126 | + "ReconcileAdditionalStorageJob completed. Subscriptions found: {SubscriptionsFound}, " + |
| 127 | + "Updated: {SubscriptionsUpdated}, Errors: {SubscriptionsWithErrors}{Failures}", |
| 128 | + subscriptionsFound, |
| 129 | + liveMode |
| 130 | + ? subscriptionsUpdated |
| 131 | + : $"(In live mode, would have updated) {subscriptionsUpdated}", |
| 132 | + subscriptionsWithErrors, |
| 133 | + failures.Count > 0 |
| 134 | + ? $", Failures: {Environment.NewLine}{string.Join(Environment.NewLine, failures)}" |
| 135 | + : string.Empty |
| 136 | + ); |
| 137 | + } |
| 138 | + |
| 139 | + private SubscriptionUpdateOptions? BuildSubscriptionUpdateOptions( |
| 140 | + Subscription subscription, |
| 141 | + string targetPriceId) |
| 142 | + { |
| 143 | + if (subscription.Items?.Data == null) |
| 144 | + { |
| 145 | + return null; |
| 146 | + } |
| 147 | + |
| 148 | + var updateOptions = new SubscriptionUpdateOptions |
| 149 | + { |
| 150 | + ProrationBehavior = StripeConstants.ProrationBehavior.CreateProrations, |
| 151 | + Metadata = new Dictionary<string, string> |
| 152 | + { |
| 153 | + [StripeConstants.MetadataKeys.StorageReconciled2025] = DateTime.UtcNow.ToString("o") |
| 154 | + }, |
| 155 | + Items = [] |
| 156 | + }; |
| 157 | + |
| 158 | + var hasUpdates = false; |
| 159 | + |
| 160 | + foreach (var item in subscription.Items.Data.Where(item => item?.Price?.Id == targetPriceId)) |
| 161 | + { |
| 162 | + hasUpdates = true; |
| 163 | + var currentQuantity = item.Quantity; |
| 164 | + |
| 165 | + if (currentQuantity > _storageGbToRemove) |
| 166 | + { |
| 167 | + var newQuantity = currentQuantity - _storageGbToRemove; |
| 168 | + logger.LogInformation( |
| 169 | + "Subscription {SubscriptionId}: reducing quantity from {CurrentQuantity} to {NewQuantity} for price {PriceId}", |
| 170 | + subscription.Id, |
| 171 | + currentQuantity, |
| 172 | + newQuantity, |
| 173 | + item.Price.Id); |
| 174 | + |
| 175 | + updateOptions.Items.Add(new SubscriptionItemOptions |
| 176 | + { |
| 177 | + Id = item.Id, |
| 178 | + Quantity = newQuantity |
| 179 | + }); |
| 180 | + } |
| 181 | + else |
| 182 | + { |
| 183 | + logger.LogInformation("Subscription {SubscriptionId}: deleting storage item with quantity {CurrentQuantity} for price {PriceId}", |
| 184 | + subscription.Id, |
| 185 | + currentQuantity, |
| 186 | + item.Price.Id); |
| 187 | + |
| 188 | + updateOptions.Items.Add(new SubscriptionItemOptions |
| 189 | + { |
| 190 | + Id = item.Id, |
| 191 | + Deleted = true |
| 192 | + }); |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + return hasUpdates ? updateOptions : null; |
| 197 | + } |
| 198 | + |
| 199 | + public static ITrigger GetTrigger() |
| 200 | + { |
| 201 | + return TriggerBuilder.Create() |
| 202 | + .WithIdentity("EveryMorningTrigger") |
| 203 | + .StartNow() |
| 204 | + .WithCronSchedule("0 0 16 * * ?") // 10am CST daily; the pods execute in UTC time |
| 205 | + .Build(); |
| 206 | + } |
| 207 | +} |
0 commit comments