Repository navigation
Expand file tree
/
Copy pathdatabase.service.ts
More file actions
723 lines (655 loc) · 29.1 KB
/
Copy pathdatabase.service.ts
File metadata and controls
723 lines (655 loc) · 29.1 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import type { ResultSetHeader, RowDataPacket } from 'mysql2';
import * as mysql from 'mysql2/promise';
type SqlParam = string | number | boolean | null;
type MySqlConnection = mysql.Pool;
@Injectable()
export class DatabaseService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(DatabaseService.name);
private mySqlPool?: MySqlConnection;
async onModuleInit() {
await this.initialize();
}
async onModuleDestroy() {
if (this.mySqlPool) {
await this.mySqlPool.end();
}
}
async connection() {
if (!this.mySqlPool) {
await this.initialize();
}
return {
dialect: 'mysql' as const,
};
}
getDialect() {
return 'mysql' as const;
}
async queryOne<T>(sql: string, params: SqlParam[] = []): Promise<T | null> {
if (!this.mySqlPool) {
await this.initialize();
}
if (!this.mySqlPool) {
return null;
}
const [rows] = await this.mySqlPool.query<RowDataPacket[]>(sql, params);
return rows.length > 0 ? (rows[0] as T) : null;
}
async queryMany<T>(sql: string, params: SqlParam[] = []): Promise<T[]> {
if (!this.mySqlPool) {
await this.initialize();
}
if (!this.mySqlPool) {
return [];
}
const [rows] = await this.mySqlPool.query<RowDataPacket[]>(sql, params);
return rows as T[];
}
async execute(sql: string, params: SqlParam[] = []) {
if (!this.mySqlPool) {
await this.initialize();
}
if (!this.mySqlPool) {
return {
insertId: 0,
affectedRows: 0,
};
}
const [result] = await this.mySqlPool.execute<ResultSetHeader>(sql, params);
return {
insertId: Number(result.insertId ?? 0),
affectedRows: Number(result.affectedRows ?? 0),
};
}
async executeScript(script: string) {
if (!this.mySqlPool) {
await this.initialize();
}
if (this.mySqlPool) {
await this.mySqlPool.query(script);
}
}
private async initialize() {
await this.initializeMySql();
await this.createSchemaMySql();
await this.migrateProjectContextColumns();
await this.migrateExperimentNotesTitleColumn();
await this.createFrontendSchemaMySql();
await this.seedInitialDataMySql();
await this.seedFrontendContentMySql();
this.logger.log('MySQL ready');
}
private async initializeMySql() {
const host = process.env.MYSQL_HOST || '127.0.0.1';
const port = Number(process.env.MYSQL_PORT || 3306);
const user = process.env.MYSQL_USER || 'root';
const password = process.env.MYSQL_PASSWORD || '';
const database = process.env.MYSQL_DATABASE || 'innovation_challenge';
const bootstrapPool = mysql.createPool({
host,
port,
user,
password,
waitForConnections: true,
connectionLimit: 5,
queueLimit: 0,
multipleStatements: true,
ssl: process.env.MYSQL_SSL === 'true' ? { rejectUnauthorized: false } : undefined,
});
await bootstrapPool.query(
`CREATE DATABASE IF NOT EXISTS \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,
);
await bootstrapPool.end();
this.mySqlPool = mysql.createPool({
host,
port,
user,
password,
database,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
multipleStatements: true,
ssl: process.env.MYSQL_SSL === 'true' ? { rejectUnauthorized: false } : undefined,
});
}
private async createSchemaMySql() {
await this.executeScript(`
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS projects (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(180) NOT NULL,
owner VARCHAR(120) NOT NULL,
description TEXT NOT NULL,
working_on TEXT NULL COMMENT 'Descripción de en qué está trabajando el usuario',
goal TEXT NULL COMMENT 'Objetivo del proyecto',
created_at DATETIME(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS project_documents (
id INT AUTO_INCREMENT PRIMARY KEY,
project_id INT NOT NULL,
document_name VARCHAR(255) NOT NULL,
document_path VARCHAR(500) NOT NULL,
document_type VARCHAR(50) NOT NULL,
file_size_bytes BIGINT NULL,
uploaded_by_user_id INT NULL,
created_at DATETIME(3) NOT NULL,
CONSTRAINT fk_project_documents_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
CONSTRAINT fk_project_documents_user FOREIGN KEY (uploaded_by_user_id) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_project_documents_project (project_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS project_members (
id INT AUTO_INCREMENT PRIMARY KEY,
project_id INT NOT NULL,
user_id INT NOT NULL,
role VARCHAR(40) NOT NULL DEFAULT 'member',
status VARCHAR(40) NOT NULL DEFAULT 'requested',
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uq_project_user (project_id, user_id),
CONSTRAINT fk_project_members_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
CONSTRAINT fk_project_members_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS project_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
project_id INT NOT NULL,
message TEXT NOT NULL,
author VARCHAR(120) NOT NULL,
created_at DATETIME(3) NOT NULL,
CONSTRAINT fk_project_logs_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS tasks (
id VARCHAR(40) PRIMARY KEY,
title VARCHAR(200) NOT NULL,
\`module\` VARCHAR(120) NOT NULL,
due_date VARCHAR(80) NOT NULL,
status VARCHAR(40) NOT NULL,
feedback TEXT NULL,
submission TEXT NULL,
user_id INT NULL,
created_at DATETIME(3) NOT NULL,
CONSTRAINT fk_tasks_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS resources (
id VARCHAR(40) PRIMARY KEY,
title VARCHAR(200) NOT NULL,
type VARCHAR(50) NOT NULL,
\`module\` INT NOT NULL,
url VARCHAR(500) NOT NULL,
tags JSON NOT NULL,
created_at DATETIME(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS project_invitations (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
project_id INT NOT NULL,
email VARCHAR(255) NOT NULL,
invited_by_user_id INT NULL,
status ENUM('pending', 'accepted', 'declined', 'expired') NOT NULL DEFAULT 'pending',
token VARCHAR(120) NOT NULL,
expires_at DATETIME(3) NULL,
responded_at DATETIME(3) NULL,
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_project_invitations_token (token),
KEY idx_project_invitations_project_status (project_id, status),
KEY idx_project_invitations_email_status (email, status),
CONSTRAINT fk_project_invitations_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
CONSTRAINT fk_project_invitations_inviter FOREIGN KEY (invited_by_user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS experiments (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
project_id INT NOT NULL,
title VARCHAR(180) NOT NULL,
objective TEXT NULL,
status ENUM('draft', 'running', 'closed', 'archived') NOT NULL DEFAULT 'draft',
risk_level ENUM('low', 'medium', 'high', 'critical') NOT NULL DEFAULT 'medium',
created_by_user_id INT NULL,
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
closed_at DATETIME(3) NULL,
PRIMARY KEY (id),
KEY idx_experiments_project_status (project_id, status),
KEY idx_experiments_created_at (created_at),
CONSTRAINT fk_experiments_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
CONSTRAINT fk_experiments_creator FOREIGN KEY (created_by_user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS experiment_steps (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
experiment_id BIGINT UNSIGNED NOT NULL,
step_order SMALLINT UNSIGNED NOT NULL,
instruction TEXT NOT NULL,
cautions TEXT NULL,
risk_level ENUM('low', 'medium', 'high', 'critical') NOT NULL DEFAULT 'medium',
is_completed TINYINT(1) NOT NULL DEFAULT 0,
completed_by_user_id INT NULL,
completed_at DATETIME(3) NULL,
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_experiment_steps_order (experiment_id, step_order),
KEY idx_experiment_steps_completion (experiment_id, is_completed),
CONSTRAINT fk_experiment_steps_experiment FOREIGN KEY (experiment_id) REFERENCES experiments(id) ON DELETE CASCADE,
CONSTRAINT fk_experiment_steps_user FOREIGN KEY (completed_by_user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS experiment_artifacts (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
experiment_id BIGINT UNSIGNED NOT NULL,
artifact_type ENUM('csv', 'image', 'document', 'note', 'report') NOT NULL,
storage_url VARCHAR(700) NOT NULL,
mime_type VARCHAR(120) NULL,
size_bytes BIGINT UNSIGNED NULL,
checksum_sha256 VARCHAR(128) NULL,
metadata JSON NULL,
uploaded_by_user_id INT NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
KEY idx_experiment_artifacts_type (experiment_id, artifact_type),
CONSTRAINT fk_experiment_artifacts_experiment FOREIGN KEY (experiment_id) REFERENCES experiments(id) ON DELETE CASCADE,
CONSTRAINT fk_experiment_artifacts_user FOREIGN KEY (uploaded_by_user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS ai_interactions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
experiment_id BIGINT UNSIGNED NULL,
user_id INT NULL,
provider VARCHAR(50) NOT NULL DEFAULT 'azure',
model VARCHAR(100) NOT NULL,
task_type ENUM('chat', 'protocol_interpret', 'results_analyze', 'image_analyze', 'next_steps') NOT NULL,
prompt_excerpt TEXT NULL,
response_excerpt TEXT NULL,
safety_flags JSON NULL,
latency_ms INT UNSIGNED NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
KEY idx_ai_interactions_experiment_created (experiment_id, created_at),
KEY idx_ai_interactions_task_created (task_type, created_at),
CONSTRAINT fk_ai_interactions_experiment FOREIGN KEY (experiment_id) REFERENCES experiments(id) ON DELETE SET NULL,
CONSTRAINT fk_ai_interactions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS safety_reviews (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
experiment_id BIGINT UNSIGNED NULL,
source_interaction_id BIGINT UNSIGNED NULL,
severity ENUM('info', 'warning', 'critical') NOT NULL,
category VARCHAR(80) NOT NULL,
decision ENUM('allow', 'warn', 'block') NOT NULL,
rationale TEXT NOT NULL,
reviewed_by_user_id INT NULL,
created_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
KEY idx_safety_reviews_experiment_created (experiment_id, created_at),
KEY idx_safety_reviews_decision_created (decision, created_at),
CONSTRAINT fk_safety_reviews_experiment FOREIGN KEY (experiment_id) REFERENCES experiments(id) ON DELETE SET NULL,
CONSTRAINT fk_safety_reviews_interaction FOREIGN KEY (source_interaction_id) REFERENCES ai_interactions(id) ON DELETE SET NULL,
CONSTRAINT fk_safety_reviews_user FOREIGN KEY (reviewed_by_user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS experiment_notes (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
experiment_id BIGINT UNSIGNED NOT NULL,
title VARCHAR(255) NOT NULL DEFAULT '',
user_id INT NULL,
content LONGTEXT NOT NULL,
ai_suggestions_generated TINYINT(1) NOT NULL DEFAULT 0,
last_suggestion_at DATETIME(3) NULL,
created_at DATETIME(3) NOT NULL,
updated_at DATETIME(3) NOT NULL,
PRIMARY KEY (id),
KEY idx_experiment_notes_experiment_created (experiment_id, created_at),
KEY idx_experiment_notes_user_created (user_id, created_at),
CONSTRAINT fk_experiment_notes_experiment FOREIGN KEY (experiment_id) REFERENCES experiments(id) ON DELETE CASCADE,
CONSTRAINT fk_experiment_notes_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
}
private async createFrontendSchemaMySql() {
await this.executeScript(`
CREATE TABLE IF NOT EXISTS pages (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
slug VARCHAR(120) NOT NULL,
name VARCHAR(160) NOT NULL,
route_path VARCHAR(255) NOT NULL DEFAULT '/',
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_pages_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS sections (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
page_id BIGINT UNSIGNED NOT NULL,
parent_section_id BIGINT UNSIGNED NULL,
section_key VARCHAR(100) NOT NULL,
title VARCHAR(160) NULL,
subtitle VARCHAR(255) NULL,
section_type ENUM('hero', 'content', 'links', 'spacer', 'decorator') NOT NULL,
display_order SMALLINT UNSIGNED NOT NULL DEFAULT 0,
is_visible TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_sections_page_key (page_id, section_key),
CONSTRAINT fk_sections_page FOREIGN KEY (page_id) REFERENCES pages (id)
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_sections_parent FOREIGN KEY (parent_section_id) REFERENCES sections (id)
ON UPDATE CASCADE ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS assets (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
asset_key VARCHAR(120) NOT NULL,
file_path VARCHAR(255) NOT NULL,
asset_kind ENUM('image', 'svg', 'icon-sprite', 'favicon') NOT NULL,
mime_type VARCHAR(100) NULL,
width_px SMALLINT UNSIGNED NULL,
height_px SMALLINT UNSIGNED NULL,
metadata JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_assets_key (asset_key),
UNIQUE KEY uq_assets_path (file_path)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS section_assets (
section_id BIGINT UNSIGNED NOT NULL,
asset_id BIGINT UNSIGNED NOT NULL,
role_key ENUM('base', 'framework', 'brand', 'background', 'icon') NOT NULL,
display_order SMALLINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (section_id, asset_id, role_key),
CONSTRAINT fk_section_assets_section FOREIGN KEY (section_id) REFERENCES sections (id)
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_section_assets_asset FOREIGN KEY (asset_id) REFERENCES assets (id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS links (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
section_id BIGINT UNSIGNED NOT NULL,
label VARCHAR(120) NOT NULL,
url VARCHAR(512) NOT NULL,
link_group ENUM('documentation', 'social') NOT NULL,
icon_symbol VARCHAR(120) NULL,
asset_id BIGINT UNSIGNED NULL,
open_in_new_tab TINYINT(1) NOT NULL DEFAULT 1,
display_order SMALLINT UNSIGNED NOT NULL DEFAULT 0,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_links_section_label (section_id, label),
CONSTRAINT fk_links_section FOREIGN KEY (section_id) REFERENCES sections (id)
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_links_asset FOREIGN KEY (asset_id) REFERENCES assets (id)
ON UPDATE CASCADE ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS themes (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
theme_key VARCHAR(60) NOT NULL,
name VARCHAR(120) NOT NULL,
is_dark_mode TINYINT(1) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_themes_key (theme_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS theme_tokens (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
theme_id BIGINT UNSIGNED NOT NULL,
token_name VARCHAR(80) NOT NULL,
token_value VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_theme_tokens_name (theme_id, token_name),
CONSTRAINT fk_theme_tokens_theme FOREIGN KEY (theme_id) REFERENCES themes (id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS ui_metrics (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
page_id BIGINT UNSIGNED NOT NULL,
metric_key VARCHAR(80) NOT NULL,
current_value BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_ui_metrics_page_key (page_id, metric_key),
CONSTRAINT fk_ui_metrics_page FOREIGN KEY (page_id) REFERENCES pages (id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS ui_metric_events (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
metric_id BIGINT UNSIGNED NOT NULL,
delta_value INT NOT NULL DEFAULT 1,
event_source VARCHAR(80) NOT NULL DEFAULT 'button_click',
event_context JSON NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
CONSTRAINT fk_ui_metric_events_metric FOREIGN KEY (metric_id) REFERENCES ui_metrics (id)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
}
private formatNow(date?: Date) {
const d = date ?? new Date();
const pad = (n: number, z = 2) => String(n).padStart(z, '0');
const ms = String(d.getMilliseconds()).padStart(3, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(
d.getMinutes(),
)}:${pad(d.getSeconds())}.${ms}`;
}
private async migrateProjectContextColumns() {
try {
if (!this.mySqlPool) {
return;
}
// Verificar si la columna working_on existe
const checkWorkingOn = await this.queryOne<{ column_name: string }>(
`SELECT COLUMN_NAME as column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'projects' AND COLUMN_NAME = 'working_on'`
);
if (!checkWorkingOn) {
this.logger.log('Agregando columna working_on a projects...');
await this.executeScript(`
ALTER TABLE projects ADD COLUMN working_on TEXT NULL COMMENT 'Descripción de en qué está trabajando el usuario';
`);
}
// Verificar si la columna goal existe
const checkGoal = await this.queryOne<{ column_name: string }>(
`SELECT COLUMN_NAME as column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'projects' AND COLUMN_NAME = 'goal'`
);
if (!checkGoal) {
this.logger.log('Agregando columna goal a projects...');
await this.executeScript(`
ALTER TABLE projects ADD COLUMN goal TEXT NULL COMMENT 'Objetivo del proyecto';
`);
}
// Verificar si la tabla project_documents existe
const checkDocumentsTable = await this.queryOne<{ table_name: string }>(
`SELECT TABLE_NAME as table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'project_documents'`
);
if (!checkDocumentsTable) {
this.logger.log('Creando tabla project_documents...');
await this.executeScript(`
CREATE TABLE IF NOT EXISTS project_documents (
id INT AUTO_INCREMENT PRIMARY KEY,
project_id INT NOT NULL,
document_name VARCHAR(255) NOT NULL,
document_path VARCHAR(500) NOT NULL,
document_type VARCHAR(50) NOT NULL,
file_size_bytes BIGINT NULL,
uploaded_by_user_id INT NULL,
created_at DATETIME(3) NOT NULL,
CONSTRAINT fk_project_documents_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
CONSTRAINT fk_project_documents_user FOREIGN KEY (uploaded_by_user_id) REFERENCES users(id) ON DELETE SET NULL,
INDEX idx_project_documents_project (project_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
`);
}
} catch (error) {
this.logger.warn(`Migration warning: ${error.message}`);
// No es fatal si falla
}
}
private async migrateExperimentNotesTitleColumn() {
const rows = await this.queryMany<{ COLUMN_NAME: string }>(
`SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'experiment_notes' AND COLUMN_NAME = 'title'`,
);
if (rows.length === 0) {
await this.executeScript(
`ALTER TABLE experiment_notes ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT '' AFTER experiment_id`,
);
this.logger.log('Migrated: experiment_notes.title column added');
}
}
private async seedInitialDataMySql() {
const now = this.formatNow();
const userCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM users');
if (!userCount || userCount.total === 0) {
await this.execute('INSERT INTO users (name, email, password, created_at) VALUES (?, ?, ?, ?)', [
'Usuario Demo',
'demo@lab.local',
'Password123!',
now,
]);
}
const projectCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM projects');
if (!projectCount || projectCount.total === 0) {
await this.execute('INSERT INTO projects (name, owner, description, created_at) VALUES (?, ?, ?, ?)', [
'BioReactivos Fase 1',
'Equipo Atlas',
'Validacion de seguridad y control de calidad en muestras de laboratorio.',
now,
]);
await this.execute('INSERT INTO projects (name, owner, description, created_at) VALUES (?, ?, ?, ?)', [
'Citometria Baseline',
'Equipo Prisma',
'Analisis exploratorio de series de datos de citometria de flujo.',
now,
]);
}
const logCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM project_logs');
if (!logCount || logCount.total === 0) {
await this.execute('INSERT INTO project_logs (project_id, message, author, created_at) VALUES (?, ?, ?, ?)', [
1,
'Se cargo lote inicial de observaciones del experimento A-14.',
'Usuario Demo',
now,
]);
}
const taskCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM tasks');
if (!taskCount || taskCount.total === 0) {
await this.execute(
'INSERT INTO tasks (id, title, \`module\`, due_date, status, feedback, submission, user_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
['t1', 'Entregar Protocolo Inicial', '1. Preparacion', 'Hoy 23:59', 'pending', null, null, 1, now],
);
await this.execute(
'INSERT INTO tasks (id, title, \`module\`, due_date, status, feedback, submission, user_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
['t2', 'Analisis CSV de Corrida 3', '2. Datos', 'Manana 20:00', 'pending', null, null, 1, now],
);
await this.execute(
'INSERT INTO tasks (id, title, \`module\`, due_date, status, feedback, submission, user_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
't3',
'Checklist de Bioseguridad',
'3. Seguridad',
'Hace 2 dias',
'approved',
'Checklist consistente y bien fundamentado.',
null,
1,
now,
],
);
}
const resourceCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM resources');
if (!resourceCount || resourceCount.total === 0) {
await this.execute(
'INSERT INTO resources (id, title, type, \`module\`, url, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
[
'r1',
'Guia de Seguridad en Laboratorio',
'pdf',
1,
'/docs/safety-guide.pdf',
JSON.stringify(['seguridad', 'bio', 'ppe']),
now,
],
);
await this.execute(
'INSERT INTO resources (id, title, type, \`module\`, url, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
[
'r2',
'Plantilla de Registro Experimental',
'doc',
2,
'/docs/lab-template.docx',
JSON.stringify(['bitacora', 'registro']),
now,
],
);
await this.execute(
'INSERT INTO resources (id, title, type, \`module\`, url, tags, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
[
'r3',
'Ejemplos CSV para Practica',
'csv',
2,
'/docs/sample-results.csv',
JSON.stringify(['csv', 'datos']),
now,
],
);
}
const experimentCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM experiments');
if (!experimentCount || experimentCount.total === 0) {
await this.execute(
'INSERT INTO experiments (project_id, title, objective, status, risk_level, created_by_user_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[1, 'Experimento PCR Fase 1', 'Validacion de protocolos de amplificacion para muestras biologicas de control.', 'running', 'medium', 1, now, now],
);
await this.execute(
'INSERT INTO experiments (project_id, title, objective, status, risk_level, created_by_user_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
[1, 'Analisis de Citometria Baseline', 'Medicion de parametros basales en series de citometria de flujo.', 'draft', 'low', 1, now, now],
);
}
}
private async seedFrontendContentMySql() {
const pageCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM pages');
if (!pageCount || pageCount.total === 0) {
await this.execute('INSERT INTO pages (slug, name, route_path, is_active) VALUES (?, ?, ?, ?)', [
'home',
'Frontend Landing',
'/',
1,
]);
}
const homePage = await this.queryOne<{ id: number }>('SELECT id FROM pages WHERE slug = ? LIMIT 1', ['home']);
if (!homePage) {
return;
}
const metric = await this.queryOne<{ id: number }>(
'SELECT id FROM ui_metrics WHERE page_id = ? AND metric_key = ? LIMIT 1',
[homePage.id, 'counter_clicks'],
);
if (!metric) {
await this.execute('INSERT INTO ui_metrics (page_id, metric_key, current_value) VALUES (?, ?, ?)', [
homePage.id,
'counter_clicks',
0,
]);
}
const themeCount = await this.queryOne<{ total: number }>('SELECT COUNT(*) as total FROM themes');
if (!themeCount || themeCount.total === 0) {
await this.execute('INSERT INTO themes (theme_key, name, is_dark_mode) VALUES (?, ?, ?)', [
'light',
'Light Theme',
0,
]);
await this.execute('INSERT INTO themes (theme_key, name, is_dark_mode) VALUES (?, ?, ?)', [
'dark',
'Dark Theme',
1,
]);
}
}
}