Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 724 725 726 727 728 729 730 731 732 733 734 | 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 24x 24x 24x 24x 24x 1x 1x 1x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 24x 59x 59x 59x 59x 59x 59x 59x 8x 8x 8x 2x 1x 8x 8x 1x 1x 8x 8x 1x 1x 8x 8x 1x 1x 8x 8x 1x 1x 8x 8x 1x 1x 8x 8x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 59x 59x 8x 8x 8x 8x 8x 8x 7x 8x 1x 1x 7x 8x 2x 2x 5x 5x 5x 8x 8x 5x 8x 1x 1x 4x 8x 1x 1x 3x 3x 8x 59x 59x 6x 6x 1x 6x 1x 6x 1x 6x 1x 6x 2x 6x 6x 59x 59x 17x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 16x 16x 17x 59x 59x 5x 5x 1x 5x 5x 5x 5x 3x 3x 5x 5x 2x 2x 5x 5x 5x 59x 59x 10x 10x 10x 10x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 10x 10x 10x 10x 10x 2x 2x 2x 2x 2x 7x 7x 10x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 5x 5x 10x 59x 59x 9x 2x 2x 7x 7x 7x 7x 9x 1x 1x 6x 6x 6x 5x 5x 6x 6x 6x 6x 9x 9x 9x 59x 59x 2x 1x 1x 1x 1x 1x 1x 1x 2x 59x 59x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 4x 4x 4x 4x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 59x 59x 6x 6x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 2x 2x 4x 4x 4x 4x 5x 2x 2x 2x 2x 2x 2x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 6x 2x 2x 2x 2x 2x 2x 6x 59x 59x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 3x 59x 59x 21x 1x 1x 1x 20x 20x 20x 20x 21x 21x 21x 2x 2x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 17x 17x 2x 2x 2x 2x 15x 15x 117x 117x 117x 117x 117x 15x 18x 18x 18x 1x 1x 14x 14x 14x 1x 1x 1x 1x 13x 13x 13x 16x 16x 13x 13x 13x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 15x 15x 15x 2x 15x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 15x 15x 15x 15x 15x 15x 12x 12x 12x 12x 12x 12x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 9x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 9x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 12x 12x 12x 12x 16x 11x 11x 5x 5x 5x 16x 16x 16x 16x 16x 16x 16x 16x 16x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 21x 5x 5x 5x 12x 3x 3x 3x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 21x 7x 7x 7x 7x 7x 7x 7x 7x 7x 20x 20x 20x 21x 59x 59x 4x 4x 4x 4x 4x 4x 1x 1x 4x 1x 1x 4x 4x 2x 2x 4x 4x 59x 59x 1x 1x 59x 59x 59x | /**
* Componente backend para manejar el modal de adjuntos de work items
*/
const vscode = require("vscode");
const path = require("path");
const WorkItemService = require("../../api/workItemService");
const WorkItemAttachmentDownloader = require("../../api/workItemAttachmentDownloader");
const DocxToPdfConverter = require("../../generators/docxToPdfConverter");
const { SharePointService } = require("../../api/sharePoint");
class WorkItemAttachmentsModal {
/**
* @param {vscode.Webview} webview
* @param {Object} config
* @param {Object} logger
*/
constructor(webview, config, logger) {
this.webview = webview;
this.config = config;
this.logger = logger;
this.workItemService = null;
this.attachmentDownloader = null;
this.docxConverter = null;
this.isProcessing = false;
this.platform = process.platform;
this._maxAttachmentsPerWorkItem = 50;
this._attachmentsTimeoutMs = 10000;
this._maxTotalAttachmentBytes = 500 * 1024 * 1024;
this._largeAttachmentThresholdBytes = 10 * 1024 * 1024;
this._lastDownloadConcurrency = null;
this.logger.info("WorkItemAttachmentsModal inicializado");
}
_initServices() {
if (!this.workItemService) {
const organization = this.config.azure?.organization;
const pat = this.config.azure?.pat;
if (!organization || !pat) {
throw new Error(
"Configuración de Azure Boards (config.azure) incompleta",
);
}
this.workItemService = new WorkItemService(organization, pat, (msg) =>
this.logger.info(msg),
);
}
if (!this.attachmentDownloader) {
const pat = this.config.azure?.pat;
this.attachmentDownloader = new WorkItemAttachmentDownloader({
pat,
logCallback: (msg) => this.logger.info(msg),
});
}
if (!this.docxConverter) {
const vsConfig = vscode.workspace.getConfiguration("gbot");
const docxConversionMode = vsConfig.get("docxConversionMode");
const docxEnv = docxConversionMode
? { ...process.env, GBOT_DOCX_CONVERSION_MODE: docxConversionMode }
: process.env;
this.docxConverter = new DocxToPdfConverter({
logCallback: (msg) => this.logger.info(msg),
env: docxEnv,
});
}
}
/**
* Manejar mensajes desde el webview
* @param {Object} message
* @returns {Promise<boolean>}
*/
async handleMessage(message) {
try {
switch (message.command) {
case "loadWorkItemsForAttachments":
await this.loadWorkItems(message.passNumber);
return true;
case "loadAttachmentsForWorkItems":
await this.loadAttachmentsForWorkItems(message.workItemIds);
return true;
case "browseFolderForAttachmentWorkItem":
await this.handleBrowseFolder(message.workItemId);
return true;
case "downloadWorkItemAttachments":
await this.downloadAttachments(message.data);
return true;
case "logAttachmentsMessage":
this._handleWebviewLog(message.level, message.message, message.data);
return true;
case "openManualAttachmentUrl":
await this._openManualAttachmentUrl(message.url);
return true;
default:
return false;
}
} catch (error) {
const errorType = this._classifyError(error);
const userMessage = this._getFriendlyMessage(error, errorType);
this.logger.error(
`Error en WorkItemAttachmentsModal.handleMessage [${errorType}]: ${error.message}`,
);
const sanitizedMessage = this._sanitizeErrorMessage(userMessage);
this.webview.postMessage({
command: "attachmentsDownloadError",
error: sanitizedMessage,
errorType,
});
return true;
}
}
_classifyError(error) {
const message = error.message || "";
const code = error.code || "";
if (
code === "ECONNREFUSED" ||
code === "ETIMEDOUT" ||
code === "ENOTFOUND"
) {
return "network";
}
if (error.response?.status === 401 || error.response?.status === 403) {
return "auth";
}
if (
message.includes("inválido") ||
message.includes("invalido") ||
message.includes("no encontrado") ||
message.includes("Configuración")
) {
return "validation";
}
if (code === "EACCES" || code === "EPERM") {
return "permission";
}
return "unknown";
}
_getFriendlyMessage(error, errorType) {
switch (errorType) {
case "network":
return "Error de conexión. Verifica tu conexión a internet o que Azure DevOps esté accesible.";
case "auth":
return "Error de autenticación. Verifica que tu Personal Access Token (PAT) sea válido y tenga los permisos necesarios.";
case "validation":
return error.message;
case "permission":
return "Error de permisos. Verifica que tengas permisos de escritura en la carpeta de destino.";
default:
return `Error inesperado: ${error.message}`;
}
}
_sanitizeErrorMessage(errorMessage) {
if (!errorMessage || typeof errorMessage !== "string") {
return "Error desconocido";
}
let sanitized = errorMessage;
const MAX_ERROR_LENGTH = 500;
sanitized = sanitized.replace(/[a-z0-9]{20,}/gi, "[TOKEN]");
sanitized = sanitized.replace(/[A-Z]{2,}\\[\w\-\.]+/g, "[DOMAIN\\USER]");
sanitized = sanitized.replace(
/[\w\-\.]+@[\w\-\.]+\.[a-z]{2,}/gi,
"[EMAIL]",
);
sanitized = sanitized.replace(
/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
"[IP]",
);
sanitized = sanitized.replace(
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
"[GUID]",
);
sanitized = sanitized.replace(/\{[^}]{20,}\}/g, "[JSON]");
sanitized = sanitized.replace(/[?&][\w-]+=[^&\s]+/g, "?[PARAM]");
sanitized = sanitized.replace(/[A-Z]:\\[\\\w\s\-\.()]+/gi, "[PATH]");
sanitized = sanitized.replace(
/\\\\[\w\-\.]+\\[\\\w\s\-\.()]+/gi,
"[UNC_PATH]",
);
sanitized = sanitized.replace(/\/[\w\-\.\/~]+/g, "[PATH]");
if (sanitized.length > MAX_ERROR_LENGTH) {
sanitized = `${sanitized.substring(0, MAX_ERROR_LENGTH)}...[TRUNCADO]`;
}
return sanitized;
}
_withTimeout(promise, timeoutMs, message) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(message));
}, timeoutMs);
promise
.then((value) => {
clearTimeout(timer);
resolve(value);
})
.catch((error) => {
clearTimeout(timer);
reject(error);
});
});
}
_buildSharePointUrlForLocalFile(filePath) {
const baseUrl = this.config.sharepoint?.baseUrl;
const localRoot = this.config.sharepoint?.localPath;
if (!baseUrl || !localRoot || !filePath) {
return {
url: null,
reason: "missing_sharepoint_config",
};
}
const normalizedRoot = path.resolve(localRoot);
const normalizedFile = path.resolve(filePath);
const rootCompare =
this.platform === "win32" ? normalizedRoot.toLowerCase() : normalizedRoot;
const fileCompare =
this.platform === "win32" ? normalizedFile.toLowerCase() : normalizedFile;
if (!fileCompare.startsWith(rootCompare)) {
return {
url: null,
reason: "outside_sharepoint_root",
};
}
let relativePath = path.relative(normalizedRoot, normalizedFile);
if (!relativePath || relativePath.startsWith("..")) {
return {
url: null,
reason: "invalid_relative_path",
};
}
relativePath = relativePath.split(path.sep).join("/");
const url = SharePointService.buildSharePointUrlFromRelativePath(
baseUrl,
relativePath,
);
if (!url) {
return {
url: null,
reason: "url_build_failed",
};
}
return { url, reason: null };
}
_ensureWordOnlineUrl(url) {
if (!url || typeof url !== "string") {
return null;
}
const hasWeb = /[?&]web=1(?:&|$)/i.test(url);
const hasActionEdit = /[?&]action=edit(?:&|$)/i.test(url);
if (hasWeb && hasActionEdit) {
return url;
}
const params = [];
if (!hasWeb) {
params.push("web=1");
}
if (!hasActionEdit) {
params.push("action=edit");
}
const separator = url.includes("?") ? "&" : "?";
return `${url}${separator}${params.join("&")}`;
}
async _openManualAttachmentUrl(url) {
if (!url || typeof url !== "string") {
vscode.window.showErrorMessage(
"No se pudo abrir el enlace de Word Online.",
);
return;
}
await vscode.env.openExternal(vscode.Uri.parse(url));
}
async loadWorkItems(passNumber) {
try {
this.logger.info(`Cargando work items para adjuntos: ${passNumber}`);
if (!WorkItemService.isValidPassNumber(passNumber)) {
throw new Error(
"Número de pase inválido. Solo se permiten letras, números, espacios, guiones, puntos y guión bajo (máximo 50 caracteres)",
);
}
this._initServices();
const boardsOrg = this.config.azure?.organization;
const boardsPat = this.config.azure?.pat;
if (!boardsOrg || !boardsPat) {
throw new Error("Configuración de Azure Boards no encontrada");
}
const workItems = await this.workItemService.getWorkItemsForPass(
passNumber,
boardsOrg,
boardsPat,
);
this.webview.postMessage({
command: "workItemsLoadedForAttachments",
workItems,
});
} catch (error) {
this.logger.error(`Error cargando work items: ${error.message}`);
vscode.window.showErrorMessage(
`Error cargando work items: ${error.message}`,
);
this.webview.postMessage({
command: "workItemsLoadedForAttachments",
workItems: [],
});
}
}
async loadAttachmentsForWorkItems(workItemIds) {
try {
if (!Array.isArray(workItemIds) || workItemIds.length === 0) {
throw new Error("Lista de work items inválida");
}
this._initServices();
const ids = [...new Set(workItemIds)]
.map((id) => Number(id))
.filter((id) => Number.isInteger(id) && id > 0);
if (ids.length === 0) {
throw new Error("Lista de work items inválida");
}
const CONCURRENT_LIMIT = 3;
const processWithThrottle = async (items, limit, processFn) => {
const results = [];
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
const batchPromises = batch.map((item) => processFn(item));
const batchResults = await Promise.allSettled(batchPromises);
results.push(...batchResults);
}
return results;
};
const results = await processWithThrottle(
ids,
CONCURRENT_LIMIT,
async (workItemId) => {
const attachments = await this._withTimeout(
this.workItemService.getWorkItemAttachments(workItemId),
this._attachmentsTimeoutMs,
"Timeout cargando adjuntos",
);
let truncated = false;
let trimmed = attachments;
if (attachments.length > this._maxAttachmentsPerWorkItem) {
truncated = true;
trimmed = attachments.slice(0, this._maxAttachmentsPerWorkItem);
this.logger.warn(
`Work item ${workItemId} tiene ${attachments.length} adjuntos (truncado a ${this._maxAttachmentsPerWorkItem})`,
);
}
return { workItemId, attachments: trimmed, truncated };
},
);
results.forEach((result, index) => {
if (result.status === "fulfilled") {
this.webview.postMessage({
command: "attachmentsLoadedForWorkItem",
workItemId: result.value.workItemId,
attachments: result.value.attachments,
truncated: result.value.truncated === true,
});
} else {
const fallbackId = ids[index];
this.logger.error(
`Error cargando adjuntos para work item ${fallbackId}: ${result.reason?.message || result.reason}`,
);
this.webview.postMessage({
command: "attachmentsLoadedForWorkItem",
workItemId: fallbackId,
attachments: [],
error: result.reason?.message || "Error cargando adjuntos",
});
}
});
} catch (error) {
this.logger.error(`Error cargando adjuntos: ${error.message}`);
this.webview.postMessage({
command: "attachmentsLoadError",
error: this._sanitizeErrorMessage(error.message),
});
}
}
async handleBrowseFolder(workItemId) {
try {
const baseOutputPath = this.config.sharepoint?.localPath;
const defaultUri = baseOutputPath
? vscode.Uri.file(baseOutputPath)
: undefined;
const options = {
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: "Seleccionar carpeta destino",
defaultUri: defaultUri,
title: `Seleccionar carpeta destino para Work Item ${workItemId}`,
};
const folderUri = await vscode.window.showOpenDialog(options);
if (folderUri && folderUri[0]) {
const folderPath = folderUri[0].fsPath;
this.webview.postMessage({
command: "folderSelectedForAttachments",
workItemId,
folderPath,
});
}
} catch (error) {
this.logger.error(`Error en selección de carpeta: ${error.message}`);
vscode.window.showErrorMessage(
`Error seleccionando carpeta: ${error.message}`,
);
}
}
async downloadAttachments(data) {
if (this.isProcessing) {
vscode.window.showWarningMessage("Ya hay una descarga en proceso");
return;
}
this.isProcessing = true;
try {
const { workItems } = data || {};
if (!workItems || !Array.isArray(workItems) || workItems.length === 0) {
throw new Error("No hay adjuntos seleccionados");
}
this._initServices();
const tasks = [];
workItems.forEach((item) => {
const workItemId = Number(item.workItemId);
const folder =
typeof item.folder === "string" ? item.folder.trim() : "";
const attachments = Array.isArray(item.attachments)
? item.attachments
: [];
if (!workItemId || workItemId <= 0) {
throw new Error(`Work Item ID inválido: ${item.workItemId}`);
}
if (!folder) {
throw new Error(
`Carpeta inválida para work item ${workItemId}: Ruta vacía`,
);
}
attachments.forEach((attachment) => {
tasks.push({
workItemId,
folder,
attachment,
});
});
});
if (tasks.length === 0) {
throw new Error("No hay adjuntos seleccionados");
}
const MAX_ATTACHMENTS = 100;
if (tasks.length > MAX_ATTACHMENTS) {
throw new Error(
`Máximo ${MAX_ATTACHMENTS} adjuntos permitidos por operación. Seleccionaste ${tasks.length}.`,
);
}
const total = tasks.length;
const totalSizeBytes = tasks.reduce((sum, task) => {
const size = task?.attachment?.size;
return Number.isFinite(size) ? sum + size : sum;
}, 0);
if (totalSizeBytes > this._maxTotalAttachmentBytes) {
const totalSizeMb = totalSizeBytes / (1024 * 1024);
const choice = await vscode.window.showWarningMessage(
`El tamaño total de descarga es ${totalSizeMb.toFixed(1)}MB. ¿Continuar?`,
"Continuar",
"Cancelar",
);
if (choice !== "Continuar") {
return;
}
}
const progressOptions = {
location: vscode.ProgressLocation.Notification,
title: `Descargando adjuntos (0/${total})`,
cancellable: false,
};
const results = await vscode.window.withProgress(
progressOptions,
async (progress) => {
const hasLargeFiles = tasks.some((task) => {
const size = task?.attachment?.size;
return (
Number.isFinite(size) &&
size >= this._largeAttachmentThresholdBytes
);
});
const CONCURRENT_LIMIT = hasLargeFiles ? 1 : 3;
this._lastDownloadConcurrency = CONCURRENT_LIMIT;
const processWithThrottle = async (items, limit, processFn) => {
const batchResults = [];
for (let i = 0; i < items.length; i += limit) {
const batch = items.slice(i, i + limit);
const batchPromises = batch.map((item, batchIndex) =>
processFn(item, i + batchIndex),
);
const settled = await Promise.allSettled(batchPromises);
batchResults.push(...settled);
}
return batchResults;
};
const settled = await processWithThrottle(
tasks,
CONCURRENT_LIMIT,
async (task, index) => {
const { workItemId, folder, attachment } = task;
const downloadResult =
await this.attachmentDownloader.downloadAttachment(
attachment,
folder,
);
let pdfPath = null;
let manualRequired = false;
let manualUrl = null;
let manualReason = null;
if (downloadResult.isDocx) {
const pdfFileName = `${path.parse(downloadResult.fileName).name}.pdf`;
const pdfOutput = path.join(folder, pdfFileName);
const conversion = await this.docxConverter.convertDocxToPdf(
downloadResult.path,
pdfOutput,
{
mode: "auto",
manualFallback: true,
returnMeta: true,
},
);
if (conversion?.method === "manual") {
manualRequired = true;
const manualInfo = this._buildSharePointUrlForLocalFile(
downloadResult.path,
);
manualUrl = this._ensureWordOnlineUrl(manualInfo.url);
manualReason =
manualInfo.reason ||
conversion.reason ||
"office_not_available";
} else {
pdfPath = conversion?.pdfPath || pdfOutput;
}
}
progress.report({
message: `Procesando adjuntos (${index + 1}/${total})`,
increment: 100 / total,
});
return {
workItemId,
attachmentName: downloadResult.fileName,
downloadPath: downloadResult.path,
pdfPath,
manualRequired,
manualUrl,
manualReason,
success: true,
};
},
);
return settled.map((result, index) => {
if (result.status === "fulfilled") {
return result.value;
}
const failedTask = tasks[index];
return {
workItemId: failedTask?.workItemId || 0,
attachmentName: failedTask?.attachment?.name || "",
downloadPath: null,
pdfPath: null,
success: false,
error: this._sanitizeErrorMessage(
result.reason?.message || "Error desconocido",
),
};
});
},
);
const successCount = results.filter((r) => r.success).length;
const failCount = results.filter((r) => !r.success).length;
const manualCount = results.filter((r) => r.manualRequired).length;
this.webview.postMessage({
command: "attachmentsDownloadComplete",
results,
});
if (successCount === total && manualCount === 0) {
vscode.window.showInformationMessage(
`✅ ${successCount} adjunto(s) descargado(s) exitosamente`,
);
} else if (successCount === total && manualCount > 0) {
vscode.window.showInformationMessage(
`ℹ️ ${successCount} adjunto(s) descargado(s). ${manualCount} requieren conversión manual en Word Online.`,
);
} else if (successCount > 0) {
const manualSuffix =
manualCount > 0
? ` ${manualCount} requieren conversión manual en Word Online.`
: "";
vscode.window.showWarningMessage(
`⚠ ${successCount}/${total} adjunto(s) descargado(s). ${failCount} fallaron.${manualSuffix}`,
);
} else {
vscode.window.showErrorMessage(
"❌ No se pudo descargar ningún adjunto. Revise los logs para más detalles.",
);
}
} catch (error) {
this.logger.error(`Error descargando adjuntos: ${error.message}`);
vscode.window.showErrorMessage(
`Error descargando adjuntos: ${error.message}`,
);
this.webview.postMessage({
command: "attachmentsDownloadError",
error: this._sanitizeErrorMessage(error.message),
});
} finally {
this.isProcessing = false;
}
}
_handleWebviewLog(level, message, data) {
const logMessage = data
? `[Webview] ${message}: ${JSON.stringify(data)}`
: `[Webview] ${message}`;
switch (level) {
case "error":
this.logger.error(logMessage);
break;
case "warn":
this.logger.warn(logMessage);
break;
case "info":
default:
this.logger.info(logMessage);
break;
}
}
async dispose() {
this.logger.info("WorkItemAttachmentsModal recursos liberados");
}
}
module.exports = WorkItemAttachmentsModal;
|