85 lines
1.9 KiB
JavaScript
85 lines
1.9 KiB
JavaScript
/**
|
|
* Subscription History Cache
|
|
*
|
|
* Caches customer subscription history to avoid expensive Stripe API calls
|
|
* during promo eligibility checks. Updated via webhook sync and CLI script.
|
|
*
|
|
* Use Cases:
|
|
* - Check if customer has ever subscribed to a specific type/price
|
|
* - Determine eligibility for "new customer only" or "returning customer" promos
|
|
* - Query local DB instead of Stripe API for better performance
|
|
*/
|
|
|
|
const mongoose = require('mongoose');
|
|
const Schema = mongoose.Schema;
|
|
const { SubStatus, SubType } = require('./subscription');
|
|
|
|
const subscriptionHistorySchema = new Schema({
|
|
// Stripe customer ID (indexed for fast lookup)
|
|
custId: {
|
|
type: String,
|
|
required: true,
|
|
index: true
|
|
},
|
|
|
|
// Subscription type ('package' or 'addon')
|
|
type: {
|
|
type: String,
|
|
enum: Object.values(SubType),
|
|
required: true,
|
|
index: true
|
|
},
|
|
|
|
// price's lookup_key (e.g., 'ess_1', 'addon_1') - optional for type-level history
|
|
priceKey: {
|
|
type: String,
|
|
sparse: true,
|
|
index: true
|
|
},
|
|
|
|
// History summary
|
|
firstSubscribedAt: {
|
|
type: Date,
|
|
required: true
|
|
},
|
|
|
|
lastSubscribedAt: {
|
|
type: Date,
|
|
required: true
|
|
},
|
|
|
|
totalSubscriptions: {
|
|
type: Number,
|
|
default: 1,
|
|
min: 1
|
|
},
|
|
|
|
// Track active subscription ID if exists
|
|
currentSubscriptionId: {
|
|
type: String
|
|
},
|
|
|
|
// Last subscription status (to know what happened with most recent subscription)
|
|
lastSubscriptionStatus: {
|
|
type: String,
|
|
enum: Object.values(SubStatus)
|
|
},
|
|
|
|
// Last sync timestamp (to know when cache was updated)
|
|
lastSyncedAt: {
|
|
type: Date,
|
|
default: Date.now
|
|
}
|
|
}, {
|
|
timestamps: true,
|
|
collection: 'subscription_histories'
|
|
});
|
|
|
|
// Compound index for fast eligibility checks
|
|
subscriptionHistorySchema.index({ custId: 1, type: 1, priceKey: 1 });
|
|
|
|
// Index for cleanup queries
|
|
subscriptionHistorySchema.index({ lastSyncedAt: 1 });
|
|
|
|
module.exports = mongoose.model('SubscriptionHistory', subscriptionHistorySchema);
|