codebase-models 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,324 @@
1
+ # codebase-models
2
+
3
+ Common Mongoose models and utilities for the Conversion.IO codebase.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install codebase-models
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { connect, Client, User, Provider, ProviderType } from "codebase-models";
15
+
16
+ // Connect to MongoDB
17
+ await connect(process.env.MONGODB_URI);
18
+
19
+ // Use models
20
+ const client = await Client.findOne({ name: "Example Client" });
21
+ const user = await User.findOne({ email: "user@example.com" });
22
+ ```
23
+
24
+ ## Features
25
+
26
+ - **50+ Mongoose Models**: Pre-defined schemas for clients, users, tests, reports, and more
27
+ - **Database Connection Helper**: Automatic connection management with role seeding
28
+ - **TypeScript Support**: Full TypeScript definitions for all models
29
+ - **Provider Integration**: Built-in support for third-party integrations (Shopify, BigQuery, Google services, etc.)
30
+ - **Utility Functions**: Helper functions for ID generation and constants
31
+
32
+ ## Available Models
33
+
34
+ ### Core Models
35
+
36
+ - `Client` - Client/organization management
37
+ - `User` - User accounts and authentication
38
+ - `Organization` - Organization structure
39
+ - `Role` - User roles and permissions
40
+ - `UserPermission` - User-specific permissions
41
+ - `UserOrganization` - User-organization relationships
42
+ - `Package` - Feature packages and subscriptions
43
+ - `Tier` - Client tiers
44
+
45
+ ### Testing & Experiments
46
+
47
+ - `Test` - A/B tests and experiments
48
+ - `TestSequentialValue` - Sequential testing configuration
49
+ - `TestTimeline` - Test event timeline
50
+ - `Hypothesis` - Test hypotheses
51
+ - `HypothesisSheet` - Hypothesis evaluation sheets
52
+ - `Page` - Landing pages
53
+ - `PageElement` - Page elements/components
54
+ - `PageTestType` - Page test type configurations
55
+ - `Trigger` - Test triggers
56
+ - `Audience` - Test audiences
57
+
58
+ ### Reporting & Analytics
59
+
60
+ - `Report` - General reports
61
+ - `CVRReport` - Conversion rate reports
62
+ - `ClientReportsTemp` - Temporary client reports
63
+ - `BqPreCompiledData` - BigQuery pre-compiled data
64
+ - `PrecalculationFilters` - Data precalculation filters
65
+
66
+ ### Client Management
67
+
68
+ - `ClientRetention` - Client retention data
69
+ - `ClientStrategy` - Client strategies
70
+ - `ClientLearning` - Client learnings
71
+ - `ClientLinks` - Client links and documents
72
+ - `ClientNote` - Client notes
73
+ - `ClientNextStep` - Client next steps
74
+ - `ClientAdditionalRevenue` - Additional revenue tracking
75
+ - `ClientScript` - Client scripts
76
+ - `ClientSurvey` - Client surveys
77
+
78
+ ### Content & Communication
79
+
80
+ - `Thread` - Communication threads
81
+ - `ThreadMessage` - Thread messages
82
+ - `Notification` - System notifications
83
+ - `ReadNotification` - Notification read status
84
+ - `Announcement` - System announcements
85
+ - `Invitation` - User invitations
86
+ - `Feedback` - User feedback
87
+ - `Faq` - Frequently asked questions
88
+
89
+ ### Integrations & Providers
90
+
91
+ - `Provider` - Third-party provider configurations (Shopify, BigQuery, Google services, etc.)
92
+ - `ApiLog` - API call logging
93
+
94
+ ### Other Models
95
+
96
+ - `Goal` - Goals and objectives
97
+ - `NewIdeas` - New ideas tracking
98
+ - `SavedSegment` - Saved user segments
99
+ - `Snippet` - Code snippets
100
+ - `Tag` - Tagging system
101
+ - `Portfolio` - Portfolio management
102
+ - `LandingPages` - Landing page management
103
+ - `StageInCustomerJourney` - Customer journey stages
104
+ - `Environment` - Environment configurations
105
+ - `CustomQuery` - Custom database queries
106
+ - `CronData` - Cron job data
107
+ - `CronConfig` - Cron job configurations
108
+ - `AppEvent` - Application events
109
+ - `Temp` - Temporary data storage
110
+
111
+ ## Database Connection
112
+
113
+ The package provides a `connect` function that handles MongoDB connection and automatically seeds roles:
114
+
115
+ ```typescript
116
+ import { connect } from "codebase-models";
117
+
118
+ // Basic connection
119
+ await connect(process.env.MONGODB_URI);
120
+
121
+ // With options
122
+ await connect(process.env.MONGODB_URI, {
123
+ maxPoolSize: 10,
124
+ serverSelectionTimeoutMS: 5000,
125
+ });
126
+ ```
127
+
128
+ The connection function:
129
+
130
+ - Automatically checks if already connected
131
+ - Seeds default roles on first connection
132
+ - Returns the mongoose instance
133
+
134
+ ## Provider Model
135
+
136
+ The `Provider` model is designed to store API keys, secrets, and configurations for third-party integrations.
137
+
138
+ ### Supported Provider Types
139
+
140
+ ```typescript
141
+ import { Provider, ProviderType } from "codebase-models";
142
+
143
+ // Available provider types
144
+ ProviderType.SHOPIFY;
145
+ ProviderType.BIGQUERY;
146
+ ProviderType.GOOGLE_ANALYTICS;
147
+ ProviderType.GOOGLE_TAG_MANAGER;
148
+ ProviderType.GOOGLE_ADS;
149
+ ProviderType.GOOGLE_SEARCH_CONSOLE;
150
+ ProviderType.GOOGLE_SHEETS;
151
+ ProviderType.GOOGLE_DOCS;
152
+ ProviderType.GOOGLE_DRIVE;
153
+ ProviderType.GOOGLE_MAIL;
154
+ ProviderType.GOOGLE_CALENDAR;
155
+ ```
156
+
157
+ ### Example: Shopify Provider
158
+
159
+ ```typescript
160
+ import { Provider, ProviderType, IShopifyMetadata } from "codebase-models";
161
+
162
+ const shopifyProvider = new Provider({
163
+ name: "My Shopify Store",
164
+ providerType: ProviderType.SHOPIFY,
165
+ client: clientId,
166
+ user: userId,
167
+ organizationId: orgId,
168
+ metadata: {
169
+ apiKey: "your-api-key",
170
+ apiSecretKey: "your-secret-key",
171
+ hostName: "your-store.myshopify.com",
172
+ apiVersion: "2026-01",
173
+ } as IShopifyMetadata,
174
+ active: true,
175
+ });
176
+
177
+ await shopifyProvider.save();
178
+ ```
179
+
180
+ ### Example: BigQuery Provider
181
+
182
+ ```typescript
183
+ import { Provider, ProviderType, IBigQueryMetadata } from "codebase-models";
184
+
185
+ const bigQueryProvider = new Provider({
186
+ name: "Analytics BigQuery",
187
+ providerType: ProviderType.BIGQUERY,
188
+ client: clientId,
189
+ user: userId,
190
+ organizationId: orgId,
191
+ metadata: {
192
+ projectId: "your-project-id",
193
+ credentials: {
194
+ type: "service_account",
195
+ project_id: "your-project-id",
196
+ private_key_id: "key-id",
197
+ private_key:
198
+ "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
199
+ client_email: "service-account@project.iam.gserviceaccount.com",
200
+ client_id: "client-id",
201
+ auth_uri: "https://accounts.google.com/o/oauth2/auth",
202
+ token_uri: "https://oauth2.googleapis.com/token",
203
+ auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
204
+ client_x509_cert_url:
205
+ "https://www.googleapis.com/robot/v1/metadata/x509/...",
206
+ },
207
+ datasetId: "your-dataset",
208
+ location: "US",
209
+ } as IBigQueryMetadata,
210
+ active: true,
211
+ });
212
+
213
+ await bigQueryProvider.save();
214
+ ```
215
+
216
+ ### Querying Providers
217
+
218
+ ```typescript
219
+ // Find all active Shopify providers for a client
220
+ const shopifyProviders = await Provider.find({
221
+ providerType: ProviderType.SHOPIFY,
222
+ client: clientId,
223
+ active: true,
224
+ });
225
+
226
+ // Find provider by IID
227
+ const provider = await Provider.findOne({ iid: "ABC123XYZ456" });
228
+ ```
229
+
230
+ ## Utility Functions
231
+
232
+ ### Generate Random IID
233
+
234
+ ```typescript
235
+ import { generateRandomIID } from "codebase-models";
236
+
237
+ const uniqueId = generateRandomIID(); // Returns 12-character uppercase string
238
+ ```
239
+
240
+ ### Constants
241
+
242
+ ```typescript
243
+ import {
244
+ RolesConstants,
245
+ PermissionsConstants,
246
+ PackageFeaturesConstants,
247
+ HypothesisSheetConstants,
248
+ } from "codebase-models";
249
+
250
+ // Available roles
251
+ RolesConstants; // ['USER', 'ADMIN', 'CLIENT', 'EXTERNAL', 'QA', 'OPTIMIZER']
252
+
253
+ // Permissions
254
+ PermissionsConstants.dashboard;
255
+ PermissionsConstants.reporting;
256
+ PermissionsConstants.insights;
257
+ // ... etc
258
+ ```
259
+
260
+ ## Model Patterns
261
+
262
+ All models follow consistent patterns:
263
+
264
+ 1. **Model Name Check**: Models check `mongoose.models.modelname` before creation to prevent overwrite errors
265
+ 2. **Lowercase Model Names**: All model names are lowercase (e.g., `"client"`, `"user"`, `"provider"`)
266
+ 3. **Timestamps**: Most models include `createdAt` and `updatedAt` timestamps
267
+ 4. **IID Support**: Many models use `iid` (internal ID) generated via `generateRandomIID()`
268
+ 5. **Indexes**: Models include appropriate indexes for common query patterns
269
+
270
+ ## TypeScript Support
271
+
272
+ All models export TypeScript interfaces:
273
+
274
+ ```typescript
275
+ import { Client, IClient } from "codebase-models";
276
+ import { Provider, IProvider, ProviderType } from "codebase-models";
277
+ import { User, IUser } from "codebase-models";
278
+ ```
279
+
280
+ ## Development
281
+
282
+ ### Building
283
+
284
+ ```bash
285
+ npm run build
286
+ ```
287
+
288
+ This will:
289
+
290
+ 1. Clean the `dist` directory
291
+ 2. Compile TypeScript with declaration files
292
+
293
+ ### Publishing
294
+
295
+ ```bash
296
+ npm publish
297
+ ```
298
+
299
+ The `prepublish` script automatically builds before publishing.
300
+
301
+ ## Requirements
302
+
303
+ - Node.js 20+
304
+ - MongoDB
305
+ - TypeScript 5.4+
306
+
307
+ ## Dependencies
308
+
309
+ - `mongoose` ^8.2.3 - MongoDB ODM
310
+ - `mongoose-slug-updater` ^3.3.0 - Slug generation
311
+ - `uuid` ^11.1.0 - Unique ID generation
312
+
313
+ ## License
314
+
315
+ ISC
316
+
317
+ ## Repository
318
+
319
+ - **GitHub**: [Conversion-IO/codebase-models](https://github.com/Conversion-IO/codebase-models)
320
+ - **Issues**: [GitHub Issues](https://github.com/Conversion-IO/codebase-models/issues)
321
+
322
+ ## Author
323
+
324
+ Vaibhav Anchal <vaibhav@conversion.io>
package/dist/index.d.ts CHANGED
@@ -80,5 +80,7 @@ import Thread from "./src/models/Thread";
80
80
  import ThreadMessage from "./src/models/ThreadMessage";
81
81
  import Provider from "./src/models/Provider";
82
82
  import ApiLog from "./src/models/ApiLog";
83
+ import { ProviderType } from "./src/models/Provider";
84
+ import Log from "./src/models/Log";
83
85
  export declare function connect(uri: string, options?: mongoose.ConnectOptions | undefined): Promise<typeof mongoose>;
84
- export { generateRandomIID, RolesConstants, Client, ClientReportsTemp, Report, Provider, Test, TestSequentialValue, User, AppEvent, Announcement, ClientAdditionalRevenue, ClientLearning, ClientLinks, ClientNextStep, ClientNote, ClientRetention, ClientStrategy, ClientSurvey, CVRReport, Faq, Feedback, Goal, Hypothesis, HypothesisSheet, LandingPages, NewIdeas, Notification, Page, PageElement, PageTestType, Portfolio, ReadNotification, Role, CustomQuery, SavedSegment, TestTimeline, Snippet, StageInCustomerJourney, Tag, Temp, Tier, Trigger, ClientScript, Audience, Environment, Organization, PrecalculationFilters, BqPreCompiledData, CronData, CronConfig, UserPermission, UserOrganization, Package, Invitation, Thread, ThreadMessage, ApiLog, };
86
+ export { generateRandomIID, RolesConstants, Client, ClientReportsTemp, Report, Provider, Test, TestSequentialValue, User, AppEvent, Announcement, ClientAdditionalRevenue, ClientLearning, ClientLinks, ClientNextStep, ClientNote, ClientRetention, ClientStrategy, ClientSurvey, CVRReport, Faq, Feedback, Goal, Hypothesis, HypothesisSheet, LandingPages, NewIdeas, Notification, Page, PageElement, PageTestType, Portfolio, ReadNotification, Role, CustomQuery, SavedSegment, TestTimeline, Snippet, StageInCustomerJourney, Tag, Temp, Tier, Trigger, ClientScript, Audience, Environment, Organization, PrecalculationFilters, BqPreCompiledData, CronData, CronConfig, UserPermission, UserOrganization, Package, Invitation, Thread, ThreadMessage, ApiLog, ProviderType, Log, };
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.BqPreCompiledData = exports.PrecalculationFilters = exports.Organization = exports.Environment = exports.Audience = exports.ClientScript = exports.Trigger = exports.Tier = exports.Temp = exports.Tag = exports.StageInCustomerJourney = exports.Snippet = exports.TestTimeline = exports.SavedSegment = exports.CustomQuery = exports.Role = exports.ReadNotification = exports.Portfolio = exports.PageTestType = exports.PageElement = exports.Page = exports.Notification = exports.NewIdeas = exports.LandingPages = exports.HypothesisSheet = exports.Hypothesis = exports.Goal = exports.Feedback = exports.Faq = exports.CVRReport = exports.ClientSurvey = exports.ClientStrategy = exports.ClientRetention = exports.ClientNote = exports.ClientNextStep = exports.ClientLinks = exports.ClientLearning = exports.ClientAdditionalRevenue = exports.Announcement = exports.AppEvent = exports.User = exports.TestSequentialValue = exports.Test = exports.Provider = exports.Report = exports.ClientReportsTemp = exports.Client = exports.RolesConstants = exports.generateRandomIID = exports.connect = void 0;
16
- exports.ApiLog = exports.ThreadMessage = exports.Thread = exports.Invitation = exports.Package = exports.UserOrganization = exports.UserPermission = exports.CronConfig = exports.CronData = void 0;
16
+ exports.Log = exports.ProviderType = exports.ApiLog = exports.ThreadMessage = exports.Thread = exports.Invitation = exports.Package = exports.UserOrganization = exports.UserPermission = exports.CronConfig = exports.CronData = void 0;
17
17
  const mongoose_1 = __importDefault(require("mongoose"));
18
18
  const Client_1 = __importDefault(require("./src/models/Client"));
19
19
  exports.Client = Client_1.default;
@@ -130,6 +130,10 @@ const Provider_1 = __importDefault(require("./src/models/Provider"));
130
130
  exports.Provider = Provider_1.default;
131
131
  const ApiLog_1 = __importDefault(require("./src/models/ApiLog"));
132
132
  exports.ApiLog = ApiLog_1.default;
133
+ const Provider_2 = require("./src/models/Provider");
134
+ Object.defineProperty(exports, "ProviderType", { enumerable: true, get: function () { return Provider_2.ProviderType; } });
135
+ const Log_1 = __importDefault(require("./src/models/Log"));
136
+ exports.Log = Log_1.default;
133
137
  function seedRoles() {
134
138
  return __awaiter(this, void 0, void 0, function* () {
135
139
  const checkRoles = yield Role_1.default.countDocuments();
@@ -0,0 +1,47 @@
1
+ /// <reference types="mongoose/types/aggregate" />
2
+ /// <reference types="mongoose/types/callback" />
3
+ /// <reference types="mongoose/types/collection" />
4
+ /// <reference types="mongoose/types/connection" />
5
+ /// <reference types="mongoose/types/cursor" />
6
+ /// <reference types="mongoose/types/document" />
7
+ /// <reference types="mongoose/types/error" />
8
+ /// <reference types="mongoose/types/expressions" />
9
+ /// <reference types="mongoose/types/helpers" />
10
+ /// <reference types="mongoose/types/middlewares" />
11
+ /// <reference types="mongoose/types/indexes" />
12
+ /// <reference types="mongoose/types/models" />
13
+ /// <reference types="mongoose/types/mongooseoptions" />
14
+ /// <reference types="mongoose/types/pipelinestage" />
15
+ /// <reference types="mongoose/types/populate" />
16
+ /// <reference types="mongoose/types/query" />
17
+ /// <reference types="mongoose/types/schemaoptions" />
18
+ /// <reference types="mongoose/types/schematypes" />
19
+ /// <reference types="mongoose/types/session" />
20
+ /// <reference types="mongoose/types/types" />
21
+ /// <reference types="mongoose/types/utility" />
22
+ /// <reference types="mongoose/types/validation" />
23
+ /// <reference types="mongoose/types/virtuals" />
24
+ /// <reference types="mongoose/types/inferschematype" />
25
+ import { Document } from "mongoose";
26
+ export interface ILogMeta {
27
+ operationType?: string;
28
+ operationName?: string;
29
+ rootFields?: string[];
30
+ userId?: string;
31
+ ip?: string;
32
+ clientFullUrl?: string;
33
+ clientId?: string;
34
+ organizationId?: string;
35
+ timestamp?: string;
36
+ [key: string]: any;
37
+ }
38
+ export interface ILog extends Document {
39
+ level: string;
40
+ message: string;
41
+ meta: ILogMeta;
42
+ timestamp: Date;
43
+ }
44
+ declare const Log: import("mongoose").Model<ILog, {}, {}, {}, Document<unknown, {}, ILog> & ILog & {
45
+ _id: import("mongoose").Types.ObjectId;
46
+ }, any>;
47
+ export default Log;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const mongoose_1 = require("mongoose");
4
+ const LogSchema = new mongoose_1.Schema({
5
+ level: {
6
+ type: String,
7
+ required: true,
8
+ trim: true,
9
+ },
10
+ message: {
11
+ type: String,
12
+ required: true,
13
+ },
14
+ meta: {
15
+ type: mongoose_1.Schema.Types.Mixed,
16
+ default: {},
17
+ },
18
+ timestamp: {
19
+ type: Date,
20
+ default: Date.now,
21
+ },
22
+ }, {
23
+ collection: "logs",
24
+ timestamps: false,
25
+ });
26
+ LogSchema.index({
27
+ "meta.rootFields": 1,
28
+ "meta.userId": 1,
29
+ "meta.clientId": 1,
30
+ "meta.timestamp": -1,
31
+ });
32
+ LogSchema.index({ "meta.operationType": 1 });
33
+ const Log = (0, mongoose_1.model)("Log", LogSchema);
34
+ exports.default = Log;
package/index.ts CHANGED
@@ -57,6 +57,9 @@ import Thread from "./src/models/Thread";
57
57
  import ThreadMessage from "./src/models/ThreadMessage";
58
58
  import Provider from "./src/models/Provider";
59
59
  import ApiLog from "./src/models/ApiLog";
60
+ import { ProviderType } from "./src/models/Provider";
61
+ import Log from "./src/models/Log";
62
+
60
63
  async function seedRoles() {
61
64
  const checkRoles = await Role.countDocuments();
62
65
  if (checkRoles < RolesConstants.length) {
@@ -163,4 +166,6 @@ export {
163
166
  Thread,
164
167
  ThreadMessage,
165
168
  ApiLog,
169
+ ProviderType,
170
+ Log,
166
171
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codebase-models",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "Common models for codebase",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -24,10 +24,10 @@
24
24
  "types": "./dist/index.d.ts",
25
25
  "repository": {
26
26
  "type": "git",
27
- "url": "git+https://github.com/AcceleratedAgency/codebase-models.git"
27
+ "url": "git+https://github.com/Conversion-IO/codebase-models.git"
28
28
  },
29
29
  "bugs": {
30
- "url": "https://github.com/AcceleratedAgency/codebase-models/issues"
30
+ "url": "https://github.com/Conversion-IO/codebase-models/issues"
31
31
  },
32
- "homepage": "https://github.com/AcceleratedAgency/codebase-models#readme"
32
+ "homepage": "https://github.com/Conversion-IO/codebase-models#readme"
33
33
  }
@@ -0,0 +1,59 @@
1
+ import { Document, Schema, model } from "mongoose";
2
+
3
+ export interface ILogMeta {
4
+ operationType?: string;
5
+ operationName?: string;
6
+ rootFields?: string[];
7
+ userId?: string;
8
+ ip?: string;
9
+ clientFullUrl?: string;
10
+ clientId?: string;
11
+ organizationId?: string;
12
+ timestamp?: string;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export interface ILog extends Document {
17
+ level: string;
18
+ message: string;
19
+ meta: ILogMeta;
20
+ timestamp: Date;
21
+ }
22
+
23
+ const LogSchema = new Schema<ILog>(
24
+ {
25
+ level: {
26
+ type: String,
27
+ required: true,
28
+ trim: true,
29
+ },
30
+ message: {
31
+ type: String,
32
+ required: true,
33
+ },
34
+ meta: {
35
+ type: Schema.Types.Mixed,
36
+ default: {},
37
+ },
38
+ timestamp: {
39
+ type: Date,
40
+ default: Date.now,
41
+ },
42
+ },
43
+ {
44
+ collection: "logs",
45
+ timestamps: false,
46
+ }
47
+ );
48
+
49
+ LogSchema.index({
50
+ "meta.rootFields": 1,
51
+ "meta.userId": 1,
52
+ "meta.clientId": 1,
53
+ "meta.timestamp": -1,
54
+ });
55
+ LogSchema.index({ "meta.operationType": 1 });
56
+
57
+ const Log = model<ILog>("Log", LogSchema);
58
+
59
+ export default Log;