huntban-cli 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,27 @@
1
+ const { apiRequest, resolveTask, checkActor } = require('../api');
2
+
3
+ module.exports = async function commentCommand(parsed, config) {
4
+ const target = parsed.positional[0] || parsed.flags.task;
5
+ const boardId = parsed.flags.board || config.boardId;
6
+ const text = parsed.flags.m || parsed.flags.text || parsed.flags.comment || parsed.positional[1];
7
+
8
+ if (!target || !text) {
9
+ console.error('❌ Falta información. Uso: huntban comment <TASK_ID_O_CODIGO> -m "Texto del comentario..."');
10
+ process.exit(1);
11
+ }
12
+
13
+ const resolved = await resolveTask(boardId, target, config);
14
+
15
+ const payload = {
16
+ taskId: resolved.id,
17
+ comment: text
18
+ };
19
+
20
+ const endpoint = `/boards/${boardId}/connector`;
21
+ const response = await apiRequest(endpoint, 'PUT', payload, config);
22
+
23
+ console.log(`\n✅ Comentario registrado en tarea [${resolved.code}]:`);
24
+ console.log(`💬 "${text}"`);
25
+ checkActor(response?.actor, config.userEmail);
26
+ console.log('');
27
+ };
@@ -0,0 +1,66 @@
1
+ const { setGlobalConfig, setLocalConfig, getGlobalConfig, loadConfig, GLOBAL_CONFIG_FILE, LOCAL_CONFIG_FILE } = require('../config');
2
+
3
+ module.exports = async function configCommand(parsed) {
4
+ const subAction = parsed.positional[0] || 'show';
5
+
6
+ if (subAction === 'set') {
7
+ const updates = {};
8
+ if (parsed.flags.url) updates.apiUrl = parsed.flags.url;
9
+ if (parsed.flags.key) updates.apiKey = parsed.flags.key;
10
+ if (parsed.flags.secret) updates.apiSecret = parsed.flags.secret;
11
+ if (parsed.flags.board) updates.boardId = parsed.flags.board;
12
+ if (parsed.flags.email) updates.userEmail = parsed.flags.email;
13
+
14
+ if (Object.keys(updates).length === 0) {
15
+ console.log('⚠️ No se pasaron parámetros para actualizar.');
16
+ console.log(' Uso: huntban config set [--url <url>] [--board <id>] [--key <key>] [--secret <secret>] [--email <email>] [--local|--global]');
17
+ return;
18
+ }
19
+
20
+ const isLocal = parsed.flags.local || (!parsed.flags.global && require('fs').existsSync(LOCAL_CONFIG_FILE));
21
+ if (isLocal) {
22
+ const next = setLocalConfig(updates);
23
+ console.log(`\n✅ Configuración local actualizada en ${LOCAL_CONFIG_FILE}:\n`);
24
+ console.log(JSON.stringify(maskConfig(next), null, 2));
25
+ } else {
26
+ try {
27
+ const next = setGlobalConfig(updates);
28
+ console.log(`\n✅ Configuración global actualizada en ${GLOBAL_CONFIG_FILE}:\n`);
29
+ console.log(JSON.stringify(maskConfig(next), null, 2));
30
+ } catch (err) {
31
+ // En entornos sandbox o restringidos, guardar localmente como fallback amigable
32
+ const next = setLocalConfig(updates);
33
+ console.log(`\n✅ Configuración guardada en archivo local ${LOCAL_CONFIG_FILE}:\n`);
34
+ console.log(JSON.stringify(maskConfig(next), null, 2));
35
+ }
36
+ }
37
+ console.log('');
38
+ return;
39
+ }
40
+
41
+ // Subaction 'show' (default)
42
+ const currentMerged = loadConfig();
43
+ console.log('\n⚙️ Configuración activa de Huntban:\n');
44
+ console.log(JSON.stringify(maskConfig({
45
+ apiUrl: currentMerged.apiUrl,
46
+ boardId: currentMerged.boardId,
47
+ apiKey: currentMerged.apiKey,
48
+ apiSecret: currentMerged.apiSecret,
49
+ userEmail: currentMerged.userEmail
50
+ }), null, 2));
51
+
52
+ if (currentMerged._localFile) {
53
+ console.log(`\n📁 Archivo de proyecto activo: ${currentMerged._localFile}`);
54
+ }
55
+ console.log(`🌐 Archivo global de usuario: ${currentMerged._globalFile}`);
56
+ console.log('\nPara modificar valores:');
57
+ console.log(' huntban config set --board <id> --key <key> --secret <secret> [--local]\n');
58
+ };
59
+
60
+ function maskConfig(cfg) {
61
+ const copy = { ...cfg };
62
+ if (copy.apiSecret) {
63
+ copy.apiSecret = copy.apiSecret.substring(0, 4) + '***' + copy.apiSecret.slice(-4);
64
+ }
65
+ return copy;
66
+ }
@@ -0,0 +1,71 @@
1
+ const { apiRequest, getPipelines, checkActor } = require('../api');
2
+
3
+ module.exports = async function createCommand(parsed, config) {
4
+ const boardId = parsed.flags.board || config.boardId;
5
+ const name = parsed.flags.name || parsed.positional[0];
6
+
7
+ if (!boardId || !name) {
8
+ console.error('❌ Falta información obligatoria.');
9
+ console.error(' Uso: huntban create --name "Título" [--pipeline <nombre_o_id>] [--desc "..."] [--content "..."] [--checklist "A, B, C"]');
10
+ process.exit(1);
11
+ }
12
+
13
+ // 1. Resolver pipeline
14
+ let pipelineId = parsed.flags.pipeline;
15
+ const pipelines = await getPipelines(boardId, config);
16
+
17
+ if (!pipelineId && pipelines.length > 0) {
18
+ pipelineId = pipelines[0].id || pipelines[0]._id;
19
+ } else if (pipelineId && pipelines.length > 0) {
20
+ const cleanKey = String(pipelineId).trim().toLowerCase();
21
+ const matched = pipelines.find(p =>
22
+ String(p.id || p._id).toLowerCase() === cleanKey ||
23
+ p.name.toLowerCase().includes(cleanKey) ||
24
+ p.phase.toLowerCase().includes(cleanKey)
25
+ );
26
+ if (matched) {
27
+ pipelineId = matched.id || matched._id;
28
+ }
29
+ }
30
+
31
+ const payload = {
32
+ name,
33
+ pipelineId,
34
+ description: parsed.flags.desc || parsed.flags.description || '',
35
+ priority: parsed.flags.priority ? parseInt(parsed.flags.priority) : 3
36
+ };
37
+
38
+ if (parsed.flags.content) {
39
+ payload.content = parsed.flags.content;
40
+ }
41
+
42
+ if (parsed.flags.checklist) {
43
+ const items = parsed.flags.checklist.split(',').map(t => ({ text: t.trim(), done: false }));
44
+ payload.checkboxes = [{ name: 'Tareas', tasks: items }];
45
+ }
46
+
47
+ if (parsed.flags.responsible) {
48
+ payload.responsibleId = parsed.flags.responsible;
49
+ }
50
+
51
+ const endpoint = `/boards/${boardId}/connector`;
52
+ const response = await apiRequest(endpoint, 'POST', payload, config);
53
+
54
+ const created = response?.data || response;
55
+ const code = created?.code || created?.serial ? `#${created?.serial}` : 'N/A';
56
+ const id = created?.id || created?._id;
57
+
58
+ const appBaseUrl = (config.apiUrl || 'https://next.huntban.com')
59
+ .replace(/\/api\/(v1|v2)\/?$/, '')
60
+ .replace(/\/$/, '');
61
+ const webUrl = `${appBaseUrl}/${boardId}/board?taskId=${code !== 'N/A' ? code : id}`;
62
+
63
+ console.log(`\n✅ Tarea creada con éxito!`);
64
+ console.log(`Código: ${code}`);
65
+ console.log(`ID: ${id}`);
66
+ console.log(`Nombre: ${created?.name}`);
67
+ console.log(`🔗 Web: ${webUrl}`);
68
+
69
+ checkActor(response?.actor, config.userEmail);
70
+ console.log('');
71
+ };
@@ -0,0 +1,77 @@
1
+ const { getTask } = require('../api');
2
+
3
+ module.exports = async function getCommand(parsed, config) {
4
+ const target = parsed.positional[0] || parsed.flags.task || parsed.flags.code;
5
+ const boardId = parsed.flags.board || config.boardId;
6
+
7
+ if (!target) {
8
+ console.error('❌ Falta el identificador o código de la tarea. Uso: huntban get <TASK_ID_O_CODIGO>');
9
+ process.exit(1);
10
+ }
11
+
12
+ const task = await getTask(boardId, target, config);
13
+ if (!task) {
14
+ console.error(`❌ Tarea no encontrada: "${target}"`);
15
+ process.exit(1);
16
+ }
17
+
18
+ if (parsed.flags.json) {
19
+ console.log(JSON.stringify(task, null, 2));
20
+ return;
21
+ }
22
+
23
+ const appBaseUrl = (config.apiUrl || 'https://next.huntban.com')
24
+ .replace(/\/api\/(v1|v2)\/?$/, '')
25
+ .replace(/\/$/, '');
26
+ const webUrl = `${appBaseUrl}/${boardId}/board?taskId=${task.code || task.id || task._id}`;
27
+
28
+ console.log(`\n📄 Detalle de Tarea [${task.code || target}]:`);
29
+ console.log(`ID: ${task.id || task._id}`);
30
+ console.log(`Código: ${task.code || 'N/A'}`);
31
+ console.log(`Nombre: ${task.name}`);
32
+ console.log(`Fase: ${task.phase || task.pipeline?.phase || 'N/A'}`);
33
+ console.log(`Columna: ${task.pipeline?.name || task.pipeline || 'N/A'}`);
34
+ console.log(`Responsable: ${task.responsible?.firstName ? `${task.responsible.firstName} ${task.responsible.lastName || ''}`.trim() : 'Sin asignar'}`);
35
+ console.log(`Autor: ${task.autor?.firstName ? `${task.autor.firstName} ${task.autor.lastName || ''}`.trim() : 'Desconocido'}`);
36
+ console.log(`Inicio Est.: ${task.expectedStartAt ? task.expectedStartAt.split('T')[0] : 'No fijado'}`);
37
+ console.log(`Entrega Est.: ${task.expectedAt ? task.expectedAt.split('T')[0] : 'No fijado'}`);
38
+ console.log(`Inicio Real: ${task.startedAt ? task.startedAt.split('T')[0] : 'No iniciado'}`);
39
+ console.log(`Cierre Real: ${task.closedAt ? task.closedAt.split('T')[0] : 'No cerrado'}`);
40
+ if (task.globalGroupId?.name) {
41
+ console.log(`Épica: ${task.globalGroupId.name}`);
42
+ }
43
+ if (task.colortags && task.colortags.length > 0) {
44
+ const tagsStr = task.colortags.map(t => t.name || t.id).join(', ');
45
+ console.log(`Etiquetas: ${tagsStr}`);
46
+ }
47
+ console.log(`🔗 Web URL: ${webUrl}`);
48
+
49
+ if (task.description) {
50
+ console.log(`\n🎯 Objetivo Situacional:\n${task.description}`);
51
+ }
52
+
53
+ if (task.content) {
54
+ console.log(`\n📝 Especificaciones Completas:\n${task.content}`);
55
+ }
56
+
57
+ if (task.checkboxes && task.checkboxes.length > 0) {
58
+ console.log(`\n☑️ Checklists / Criterios de Aceptación:`);
59
+ task.checkboxes.forEach(group => {
60
+ console.log(` [${group.name || 'Tareas'}]`);
61
+ (group.tasks || []).forEach((item, idx) => {
62
+ const idInfo = item.id ? ` (ID: ${item.id})` : ` (#${idx + 1})`;
63
+ console.log(` ${item.done ? '✅ [x]' : '⬜ [ ]'} ${item.text}${idInfo}`);
64
+ });
65
+ });
66
+ }
67
+
68
+ if (task.comments && task.comments.length > 0) {
69
+ console.log(`\n💬 Hilo de Discusión / Comentarios (${task.comments.length}):`);
70
+ task.comments.forEach(c => {
71
+ const dateStr = c.createdAt ? c.createdAt.split('T')[0] : '';
72
+ console.log(` • [${dateStr}] ${c.author}:`);
73
+ console.log(` "${c.text}"`);
74
+ });
75
+ }
76
+ console.log('');
77
+ };
@@ -0,0 +1,123 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { setLocalConfig, loadConfig, LOCAL_CONFIG_FILE } = require('../config');
5
+ const { isInteractive, askQuestion } = require('../interactive');
6
+ const { getPipelines } = require('../api');
7
+
8
+ const TEMPLATE_PATH = path.join(__dirname, '..', '..', 'templates', 'SKILL.md');
9
+
10
+ module.exports = async function initCommand(parsed, config) {
11
+ const isGlobal = parsed.flags.global || parsed.flags.g;
12
+
13
+ console.log('\n🚀 Inicializando Antigravity Skill para Huntban...');
14
+
15
+ // 1. Instalar SKILL.md
16
+ if (!fs.existsSync(TEMPLATE_PATH)) {
17
+ console.error('❌ Error: Archivo de plantilla SKILL.md no encontrado en el paquete CLI.');
18
+ process.exit(1);
19
+ }
20
+
21
+ const templateContent = fs.readFileSync(TEMPLATE_PATH, 'utf8');
22
+
23
+ let targetSkillDir;
24
+ let targetSkillPath;
25
+
26
+ if (isGlobal) {
27
+ targetSkillDir = path.join(os.homedir(), '.gemini', 'config', 'skills', 'huntban-connector');
28
+ targetSkillPath = path.join(targetSkillDir, 'SKILL.md');
29
+ } else {
30
+ targetSkillDir = path.join(process.cwd(), '.agents', 'skills', 'huntban-connector');
31
+ targetSkillPath = path.join(targetSkillDir, 'SKILL.md');
32
+ }
33
+
34
+ try {
35
+ fs.mkdirSync(targetSkillDir, { recursive: true });
36
+ fs.writeFileSync(targetSkillPath, templateContent, 'utf8');
37
+ console.log(`✅ Habilidad instalada en: ${targetSkillPath}`);
38
+ } catch (err) {
39
+ console.error(`❌ Error instalando la habilidad: ${err.message}`);
40
+ process.exit(1);
41
+ }
42
+
43
+ // Si fue instalación global y no se pidieron credenciales de proyecto, terminar aquí
44
+ if (isGlobal && !parsed.flags.board && !parsed.flags.key) {
45
+ console.log('\n🎉 Habilidad instalada globalmente para Antigravity.');
46
+ console.log(' Ahora Antigravity reconocerá huntban-connector en cualquier repositorio.\n');
47
+ return;
48
+ }
49
+
50
+ // 2. Configurar .huntban.json en el repositorio
51
+ const updates = {};
52
+ if (parsed.flags.url) updates.apiUrl = parsed.flags.url;
53
+ if (parsed.flags.board) updates.boardId = parsed.flags.board;
54
+ if (parsed.flags.key) updates.apiKey = parsed.flags.key;
55
+ if (parsed.flags.secret) updates.apiSecret = parsed.flags.secret;
56
+ if (parsed.flags.email) updates.userEmail = parsed.flags.email;
57
+
58
+ const hasFlags = Object.keys(updates).length > 0;
59
+ const configExists = fs.existsSync(LOCAL_CONFIG_FILE);
60
+
61
+ if (!hasFlags && isInteractive() && (!configExists || parsed.flags.force)) {
62
+ console.log('\n📋 Configuración del Tablero de Huntban:');
63
+ console.log(' (Puedes obtener estos datos en: Tablero > Configuración ⚙️ > Conector / Webhooks)\n');
64
+
65
+ const defaultUrl = config.apiUrl || 'https://next.huntban.com/api/v2';
66
+ const inputUrl = await askQuestion(`URL de la API [${defaultUrl}]: `);
67
+ updates.apiUrl = inputUrl.trim() || defaultUrl;
68
+
69
+ const inputBoard = await askQuestion(`ID del Tablero (24 caracteres): `);
70
+ if (inputBoard.trim()) updates.boardId = inputBoard.trim();
71
+
72
+ const inputKey = await askQuestion(`API Key (hb_pk_...): `);
73
+ if (inputKey.trim()) updates.apiKey = inputKey.trim();
74
+
75
+ const inputSecret = await askQuestion(`API Secret (hb_sk_...): `);
76
+ if (inputSecret.trim()) updates.apiSecret = inputSecret.trim();
77
+
78
+ const defaultEmail = config.userEmail || '';
79
+ const emailPrompt = defaultEmail ? `Email del usuario [${defaultEmail}]: ` : `Email del usuario: `;
80
+ const inputEmail = await askQuestion(emailPrompt);
81
+ updates.userEmail = inputEmail.trim() || defaultEmail;
82
+ }
83
+
84
+ if (Object.keys(updates).length > 0) {
85
+ setLocalConfig(updates);
86
+ console.log(`✅ Archivo de configuración creado en: ${LOCAL_CONFIG_FILE}`);
87
+ } else if (!configExists) {
88
+ console.log(`\n💡 Nota: Aún no has configurado las credenciales del tablero.`);
89
+ console.log(` Configúralas con: huntban config set --board <ID> --key <KEY> --secret <SECRET> --local\n`);
90
+ }
91
+
92
+ // 3. Añadir .huntban.json a .gitignore si existe
93
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
94
+ if (fs.existsSync(gitignorePath)) {
95
+ try {
96
+ const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');
97
+ if (!gitignoreContent.includes('.huntban.json')) {
98
+ const toAppend = gitignoreContent.endsWith('\n') ? '.huntban.json\n' : '\n.huntban.json\n';
99
+ fs.appendFileSync(gitignorePath, toAppend, 'utf8');
100
+ console.log('🔒 .huntban.json agregado automáticamente a .gitignore para proteger credenciales.');
101
+ }
102
+ } catch (e) {
103
+ // Ignorar error al escribir gitignore
104
+ }
105
+ }
106
+
107
+ // 4. Verificación de conexión
108
+ const currentMerged = loadConfig();
109
+ if (currentMerged.apiKey && currentMerged.boardId) {
110
+ try {
111
+ const pipelines = await getPipelines(currentMerged.boardId, currentMerged);
112
+ if (pipelines.length > 0) {
113
+ console.log(`\n🎉 ¡Conexión con Huntban exitosa!`);
114
+ console.log(`📊 ${pipelines.length} columnas detectadas en el tablero.`);
115
+ }
116
+ } catch (err) {
117
+ // No bloquear si no hay conexión en el momento
118
+ }
119
+ }
120
+
121
+ console.log('\n✨ ¡Listo! Antigravity y Huntban CLI están vinculados a este repositorio.');
122
+ console.log(' Prueba comandos como: huntban cols, huntban ls, huntban get <CODIGO>\n');
123
+ };
@@ -0,0 +1,50 @@
1
+ const { apiRequest } = require('../api');
2
+
3
+ module.exports = async function listCommand(parsed, config) {
4
+ const boardId = parsed.flags.board || config.boardId;
5
+ if (!boardId) {
6
+ console.error('❌ Falta especificar el tablero. Configúralo con "huntban config set --board <ID>" o usa el flag "--board <ID>".');
7
+ process.exit(1);
8
+ }
9
+
10
+ const params = new URLSearchParams();
11
+ if (parsed.flags.pipeline) params.set('pipelineId', parsed.flags.pipeline);
12
+ if (parsed.flags.search) params.set('search', parsed.flags.search);
13
+ if (parsed.flags.responsible) params.set('responsible', parsed.flags.responsible);
14
+ if (parsed.flags.priority) params.set('priority', parsed.flags.priority);
15
+ if (parsed.flags.epic) params.set('epic', parsed.flags.epic);
16
+ if (parsed.flags.limit) params.set('limit', parsed.flags.limit);
17
+ if (parsed.flags.code) params.set('code', parsed.flags.code);
18
+
19
+ const endpoint = `/boards/${boardId}/connector?${params.toString()}`;
20
+ const response = await apiRequest(endpoint, 'GET', null, config);
21
+ const tasks = response?.data || (Array.isArray(response) ? response : []);
22
+
23
+ if (parsed.flags.json) {
24
+ console.log(JSON.stringify(tasks, null, 2));
25
+ return;
26
+ }
27
+
28
+ console.log(`\n📋 Tareas en Tablero (${tasks.length} encontradas):\n`);
29
+ if (tasks.length === 0) {
30
+ console.log(' No se encontraron tareas con los filtros especificados.\n');
31
+ return;
32
+ }
33
+
34
+ tasks.forEach((t) => {
35
+ const code = t.code || t.card?.code || `#${t.serial || '?'}`;
36
+ const phase = t.phase || t.pipeline?.phase || 'open';
37
+ const responsible = t.responsible?.firstName
38
+ ? `${t.responsible.firstName} ${t.responsible.lastName || ''}`.trim()
39
+ : 'Sin asignar';
40
+ const closed = t.closedAt ? ` [Cerrada: ${t.closedAt.split('T')[0]}]` : '';
41
+
42
+ console.log(`• [${code}] ${t.name}`);
43
+ console.log(` ID: ${t.id} | Fase: ${phase} | Resp: ${responsible}${closed}`);
44
+ if (t.description) {
45
+ const desc = t.description.length > 95 ? t.description.substring(0, 95) + '...' : t.description;
46
+ console.log(` Objetivo: ${desc}`);
47
+ }
48
+ console.log('');
49
+ });
50
+ };
@@ -0,0 +1,36 @@
1
+ const { apiRequest, resolveTask, checkActor } = require('../api');
2
+
3
+ module.exports = async function moveCommand(parsed, config) {
4
+ const target = parsed.positional[0] || parsed.flags.task;
5
+ const targetColumn = parsed.positional[1] || parsed.flags.pipeline || parsed.flags.to;
6
+ const boardId = parsed.flags.board || config.boardId;
7
+ const comment = parsed.flags.m || parsed.flags.comment || null;
8
+
9
+ if (!target || !targetColumn) {
10
+ console.error('❌ Falta información.');
11
+ console.error(' Uso: huntban move <TASK_ID_O_CODIGO> <COLUMNA> [-m "comentario"]');
12
+ console.error(' Ejemplo: huntban move BLBX-55 "Review" -m "Listo para revisión"');
13
+ process.exit(1);
14
+ }
15
+
16
+ const resolved = await resolveTask(boardId, target, config);
17
+
18
+ const payload = {
19
+ taskId: resolved.id,
20
+ pipeline: targetColumn
21
+ };
22
+
23
+ if (comment) {
24
+ payload.comment = comment;
25
+ }
26
+
27
+ const endpoint = `/boards/${boardId}/connector`;
28
+ const response = await apiRequest(endpoint, 'PUT', payload, config);
29
+
30
+ console.log(`\n📦 Tarea [${resolved.code}] movida a la columna "${targetColumn}"`);
31
+ if (comment) {
32
+ console.log(`💬 Comentario registrado: "${comment}"`);
33
+ }
34
+ checkActor(response?.actor, config.userEmail);
35
+ console.log('');
36
+ };
@@ -0,0 +1,116 @@
1
+ const { apiRequest, getPipelines, getTask, checkActor } = require('../api');
2
+ const { isInteractive, askConfirm, askQuestion } = require('../interactive');
3
+
4
+ const phaseIcons = {
5
+ 'open': '📂',
6
+ 'ready': '📋',
7
+ 'in-progress': '⚙️',
8
+ 'in-confirmation': '🔍',
9
+ 'closed-success': '✅',
10
+ 'closed-failed': '❌',
11
+ 'on-hold': '⏸️'
12
+ };
13
+
14
+ module.exports = async function nextCommand(parsed, config) {
15
+ const target = parsed.positional[0] || parsed.flags.task;
16
+ const boardId = parsed.flags.board || config.boardId;
17
+
18
+ if (!target) {
19
+ console.error('❌ Falta especificar la tarea. Uso: huntban next <TASK_ID_O_CODIGO> [-m "comentario"] [-y]');
20
+ process.exit(1);
21
+ }
22
+
23
+ // 1. Obtener la tarea
24
+ const task = await getTask(boardId, target, config);
25
+ if (!task) {
26
+ console.error(`❌ Tarea no encontrada: "${target}"`);
27
+ process.exit(1);
28
+ }
29
+
30
+ // 2. Obtener las columnas del tablero
31
+ const pipelines = await getPipelines(boardId, config);
32
+ if (pipelines.length === 0) {
33
+ console.error('❌ No se encontraron columnas en el tablero.');
34
+ process.exit(1);
35
+ }
36
+
37
+ // 3. Localizar la columna actual
38
+ const currentPipelineId = String(task.pipeline?.id || task.pipeline?._id || task.pipeline || '');
39
+ let currentIndex = pipelines.findIndex(p => String(p.id || p._id) === currentPipelineId);
40
+
41
+ if (currentIndex === -1) {
42
+ // Si no coincide por ID, intentar por nombre
43
+ const currentName = task.pipeline?.name;
44
+ if (currentName) {
45
+ currentIndex = pipelines.findIndex(p => p.name.toLowerCase() === currentName.toLowerCase());
46
+ }
47
+ }
48
+
49
+ if (currentIndex === -1) {
50
+ console.warn(`⚠️ No se pudo determinar la columna actual con certeza. Se asume columna inicial.`);
51
+ currentIndex = 0;
52
+ }
53
+
54
+ // 4. Determinar la siguiente columna
55
+ if (currentIndex >= pipelines.length - 1) {
56
+ const lastPipe = pipelines[pipelines.length - 1];
57
+ console.log(`\n🏁 La tarea [${task.code || target}] ya se encuentra en la última etapa: "${lastPipe.name}".`);
58
+ console.log(` No hay etapas posteriores a las que avanzar.`);
59
+ return;
60
+ }
61
+
62
+ const currentPipe = pipelines[currentIndex];
63
+ const nextPipe = pipelines[currentIndex + 1];
64
+
65
+ const currIcon = phaseIcons[currentPipe.phase] || '•';
66
+ const nextIcon = phaseIcons[nextPipe.phase] || '•';
67
+
68
+ console.log(`\n⏩ Avance de etapa para [${task.code || target}] "${task.name}":`);
69
+ console.log(` De: ${currIcon} ${currentPipe.name} (${currentPipe.phase})`);
70
+ console.log(` A: ${nextIcon} ${nextPipe.name} (${nextPipe.phase})\n`);
71
+
72
+ // 5. Confirmación interactiva si aplica
73
+ const skipConfirm = parsed.flags.y || parsed.flags.yes;
74
+ if (!skipConfirm && isInteractive()) {
75
+ const ok = await askConfirm('¿Deseas confirmar el avance a la siguiente columna?');
76
+ if (!ok) {
77
+ console.log('Operación cancelada por el usuario.');
78
+ return;
79
+ }
80
+ }
81
+
82
+ // 6. Comentario
83
+ let comment = parsed.flags.m || parsed.flags.comment || null;
84
+ if (!comment && isInteractive() && !skipConfirm) {
85
+ const userNote = await askQuestion('¿Deseas agregar un comentario de entrega o avance? (Enter para omitir): ');
86
+ if (userNote) comment = userNote;
87
+ }
88
+
89
+ const payload = {
90
+ taskId: task.id,
91
+ pipelineId: nextPipe.id,
92
+ phase: nextPipe.phase
93
+ };
94
+
95
+ if (comment) {
96
+ payload.comment = comment;
97
+ }
98
+
99
+ // Si la siguiente etapa es de cierre definitivo (closed-success), registrar closedAt
100
+ if (nextPipe.phase === 'closed-success') {
101
+ payload.closedAt = parsed.flags.date || new Date().toISOString().split('T')[0];
102
+ }
103
+
104
+ const endpoint = `/boards/${boardId}/connector`;
105
+ const updateRes = await apiRequest(endpoint, 'PUT', payload, config);
106
+
107
+ console.log(`\n🎉 Tarea [${task.code || target}] avanzada con éxito a "${nextPipe.name}"!`);
108
+ if (nextPipe.phase === 'closed-success') {
109
+ console.log(`✅ Fase final completada. Fecha de cierre fijada: ${payload.closedAt}`);
110
+ }
111
+ if (comment) {
112
+ console.log(`💬 Comentario: "${comment}"`);
113
+ }
114
+ checkActor(updateRes?.actor, config.userEmail);
115
+ console.log('');
116
+ };
@@ -0,0 +1,43 @@
1
+ const { getTask } = require('../api');
2
+ const { exec } = require('child_process');
3
+
4
+ module.exports = async function openCommand(parsed, config) {
5
+ const target = parsed.positional[0] || parsed.flags.task || parsed.flags.code;
6
+ const boardId = parsed.flags.board || config.boardId;
7
+
8
+ if (!boardId) {
9
+ console.error('❌ Falta especificar el tablero (--board <id> o HUNTBAN_BOARD_ID)');
10
+ process.exit(1);
11
+ }
12
+
13
+ const appBaseUrl = (config.apiUrl || 'https://next.huntban.com')
14
+ .replace(/\/api\/(v1|v2)\/?$/, '')
15
+ .replace(/\/$/, '');
16
+
17
+ let url;
18
+ if (!target) {
19
+ // Abrir el tablero directamente
20
+ url = `${appBaseUrl}/${boardId}/board`;
21
+ } else {
22
+ // Si viene target, intentar obtener el código o usar el target como taskId
23
+ try {
24
+ const task = await getTask(boardId, target, config);
25
+ const codeOrId = task?.code || task?.id || target;
26
+ url = `${appBaseUrl}/${boardId}/board?taskId=${encodeURIComponent(codeOrId)}`;
27
+ } catch (e) {
28
+ url = `${appBaseUrl}/${boardId}/board?taskId=${encodeURIComponent(target)}`;
29
+ }
30
+ }
31
+
32
+ console.log(`\n🌐 Abriendo en navegador: ${url}\n`);
33
+
34
+ const startCmd = process.platform === 'darwin' ? 'open'
35
+ : process.platform === 'win32' ? 'start'
36
+ : 'xdg-open';
37
+
38
+ exec(`${startCmd} "${url}"`, (err) => {
39
+ if (err) {
40
+ console.log(`💡 Si no se abre automáticamente, copia este enlace en tu navegador:\n ${url}\n`);
41
+ }
42
+ });
43
+ };
@@ -0,0 +1,34 @@
1
+ const { getPipelines } = require('../api');
2
+
3
+ module.exports = async function pipelinesCommand(parsed, config) {
4
+ const boardId = parsed.flags.board || config.boardId;
5
+ if (!boardId) {
6
+ console.error('❌ Falta especificar el tablero (--board <id> o HUNTBAN_BOARD_ID)');
7
+ process.exit(1);
8
+ }
9
+
10
+ const pipelines = await getPipelines(boardId, config);
11
+
12
+ if (parsed.flags.json) {
13
+ console.log(JSON.stringify(pipelines, null, 2));
14
+ return;
15
+ }
16
+
17
+ console.log(`\n📊 Columnas / Pipelines del Tablero (${pipelines.length} encontradas):\n`);
18
+ pipelines.forEach((p, idx) => {
19
+ const phaseIcons = {
20
+ 'open': '📂',
21
+ 'ready': '📋',
22
+ 'in-progress': '⚙️',
23
+ 'in-confirmation': '🔍',
24
+ 'closed-success': '✅',
25
+ 'closed-failed': '❌',
26
+ 'on-hold': '⏸️'
27
+ };
28
+ const icon = phaseIcons[p.phase] || '•';
29
+ console.log(` ${idx + 1}. ${icon} ${p.name}`);
30
+ console.log(` ID: ${p.id || p._id} | Fase: ${p.phase} | Orden: ${p.order !== undefined ? p.order : idx}`);
31
+ if (p.description) console.log(` Nota: ${p.description}`);
32
+ console.log('');
33
+ });
34
+ };