import { Model, ModelOptions, QueryContext } from 'objection'; import { randomUUID } from 'crypto'; /** * Central database models using Objection.js * These models work with the central database (not tenant databases) */ export class CentralTenant extends Model { static tableName = 'tenants'; id: string; name: string; slug: string; dbHost: string; dbPort: number; dbName: string; dbUsername: string; dbPassword: string; status: string; createdAt: Date; updatedAt: Date; // Relations domains?: CentralDomain[]; $beforeInsert(queryContext: QueryContext) { this.id = this.id || randomUUID(); // Auto-generate slug from name if not provided if (!this.slug && this.name) { this.slug = this.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); } this.createdAt = new Date(); this.updatedAt = new Date(); } $beforeUpdate(opt: ModelOptions, queryContext: QueryContext) { this.updatedAt = new Date(); } static get relationMappings() { return { domains: { relation: Model.HasManyRelation, modelClass: CentralDomain, join: { from: 'tenants.id', to: 'domains.tenantId', }, }, }; } } export class CentralDomain extends Model { static tableName = 'domains'; id: string; domain: string; tenantId: string; isPrimary: boolean; createdAt: Date; updatedAt: Date; // Relations tenant?: CentralTenant; $beforeInsert(queryContext: QueryContext) { this.id = this.id || randomUUID(); this.createdAt = new Date(); this.updatedAt = new Date(); } $beforeUpdate(opt: ModelOptions, queryContext: QueryContext) { this.updatedAt = new Date(); } static get relationMappings() { return { tenant: { relation: Model.BelongsToOneRelation, modelClass: CentralTenant, join: { from: 'domains.tenantId', to: 'tenants.id', }, }, }; } } export class CentralUser extends Model { static tableName = 'users'; id: string; email: string; password: string; firstName: string | null; lastName: string | null; role: string; isActive: boolean; createdAt: Date; updatedAt: Date; $beforeInsert(queryContext: QueryContext) { this.id = this.id || randomUUID(); this.createdAt = new Date(); this.updatedAt = new Date(); } $beforeUpdate(opt: ModelOptions, queryContext: QueryContext) { this.updatedAt = new Date(); } }