-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbilling.plan.model.mongoose.js
More file actions
113 lines (106 loc) · 2.62 KB
/
Copy pathbilling.plan.model.mongoose.js
File metadata and controls
113 lines (106 loc) · 2.62 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
/**
* Module dependencies
*/
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
/**
* BillingPlan Data Model Mongoose
*
* Versioned plan definitions for meter-based pricing.
* Each (planId, version) pair is immutable after creation.
* Use bumpVersion to create a new version and deactivate the previous one.
*/
const BillingPlanMongoose = new Schema(
{
planId: {
type: String,
required: true,
trim: true,
},
version: {
type: String,
required: true,
trim: true,
},
meterQuota: {
type: Number,
required: true,
min: 0,
},
stripePriceMonthly: {
type: String,
trim: true,
sparse: true,
},
stripePriceAnnual: {
type: String,
trim: true,
sparse: true,
},
/**
* Flexible ratio map for meter unit attribution.
* Each key is a feature name; each value is a non-negative finite number.
* Example: { scrap: 1, autofix: 2, wizard: 5 }
*/
ratios: {
type: Schema.Types.Mixed,
default: () => ({}),
validate: {
validator(value) {
return (
value != null &&
typeof value === 'object' &&
!Array.isArray(value) &&
Object.values(value).every((n) => Number.isFinite(n) && n >= 0)
);
},
message: 'ratios must be an object whose values are finite numbers >= 0',
},
},
effectiveFrom: {
type: Date,
required: true,
},
effectiveUntil: {
type: Date,
default: null,
},
active: {
type: Boolean,
default: true,
index: true,
},
},
{
timestamps: true,
},
);
/**
* Unique index per (planId, version) — immutable identity
*/
BillingPlanMongoose.index({ planId: 1, version: 1 }, { unique: true });
/**
* Compound index to look up the active plan for a given planId efficiently.
* Partial unique constraint: only one active plan per planId at a time
* (effectiveUntil: null means currently active). Guards against concurrent
* bumpVersion() races producing two simultaneously-active versions.
*/
BillingPlanMongoose.index(
{ planId: 1, active: 1, effectiveUntil: 1 },
{ unique: true, partialFilterExpression: { active: true, effectiveUntil: null } },
);
/**
* Returns the hex string representation of the document ObjectId.
* @returns {string} Hex string of the ObjectId.
*/
function addID() {
return this._id.toHexString();
}
/**
* Model configuration
*/
BillingPlanMongoose.virtual('id').get(addID);
BillingPlanMongoose.set('toJSON', {
virtuals: true,
});
mongoose.model('BillingPlan', BillingPlanMongoose);