import { UniqueID } from "@repo/rdx-ddd"; import { DataTypes, QueryTypes, type Sequelize } from "sequelize"; export async function migrateSupport(database: Sequelize) { const query = database.getQueryInterface(); const tables = await database.query<{ name: string }>( "SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()", { type: QueryTypes.SELECT } ); const fk = (model: string) => ({ type: DataTypes.UUID, allowNull: false, references: { model, key: "id" }, onDelete: "RESTRICT", }); const definitions = [ ["support_catalog_lock", { id: { type: DataTypes.INTEGER, primaryKey: true } }], [ "support_tools", { id: { type: DataTypes.UUID, primaryKey: true }, name: { type: DataTypes.STRING(100), allowNull: false, unique: true }, active: { type: DataTypes.BOOLEAN, allowNull: false }, builtin: { type: DataTypes.BOOLEAN, allowNull: false }, }, ], [ "asset_support", { id: { type: DataTypes.UUID, primaryKey: true }, companyId: fk("companies"), assetId: fk("assets"), toolId: fk("support_tools"), values: { type: DataTypes.JSON, allowNull: false }, preferredKey: { type: DataTypes.UUID, allowNull: true, unique: true }, }, ], [ "asset_support_revisions", { id: { type: DataTypes.UUID, primaryKey: true }, connectionId: fk("asset_support"), actorId: fk("users"), toolId: fk("support_tools"), values: { type: DataTypes.JSON, allowNull: false }, recordedAt: { type: DataTypes.STRING(30), allowNull: false }, position: { type: DataTypes.INTEGER, allowNull: false }, }, ], ] as const; for (const [table, columns] of definitions) { if (!tables.some((item) => item.name === table)) { await query.createTable(table, columns); } } const constraints = await database.query<{ name: string }>( "SELECT CONSTRAINT_NAME AS name FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='asset_support'", { type: QueryTypes.SELECT } ); if (!constraints.some((item) => item.name === "support_asset_company")) { await database.query( "ALTER TABLE asset_support ADD CONSTRAINT support_asset_company FOREIGN KEY (companyId,assetId) REFERENCES assets(companyId,id)" ); } await database.query("INSERT IGNORE INTO support_catalog_lock (id) VALUES (1)"); for (const name of ["AnyDesk", "Supremo Control", "Escritorio remoto", "TeamViewer"]) { await database.query( "INSERT IGNORE INTO support_tools (id,name,active,builtin) VALUES (:id,:name,1,1)", { replacements: { id: UniqueID.generateNewID().toPrimitive(), name }, } ); } }