All files / generator/rirekisho data.ts

95.66% Statements 243/254
83% Branches 166/200
100% Functions 50/50
95.92% Lines 212/221

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                                                        283x                         14x 14x 14x 11x   14x       14x               64x             10x 10x                               24x           24x                                                               72x 71x   9x 9x   68x                   41x 4x   3x 3x   2x                   16x 2x   2x 2x                       15x 4x   4x 4x   2x                     1x 1x 1x 1x           19x 19x 22x 22x 22x           22x 22x 22x   22x 22x 22x             19x           10x 10x 10x     9x 1x 1x           9x 9x             10x     9x   3x   4x 4x 3x   1x         3x 3x 3x               10x           6x 6x 9x 8x 8x           1x     6x             37x 35x 35x 35x 35x 35x 35x 35x                       26x   26x 26x 20x 20x   20x 20x   20x 20x 20x 46x         32x 26x 10x 10x   10x 10x   10x 10x 10x 12x         88x 26x 114x   26x             19x 16x   7x 7x     7x 16x   16x             14x 14x 14x 14x   14x 22x 14x 14x 14x   14x       14x 22x 22x     22x   22x   4x     4x 2x 2x       4x 18x   2x 2x             16x 16x   16x   2x 2x     14x         14x           14x 14x 2x     14x             30x 41x 31x 17x 12x     5x 1x 2x   1x         4x   3x 4x       3x 2x 3x   2x 2x 3x   2x       1x       14x                     14x 20x 15x 5x 4x   2x 1x 2x       1x 1x 1x 1x 1x           9x                 28x   28x 28x 21x 21x   21x   20x 1x 1x       37x 28x 6x 6x   6x   6x 7x     7x 7x   7x 2x                 28x 39x 28x 8x 8x   8x 7x 1x 1x       28x    
/**
 * Data extraction and transformation for Rirekisho (履歴書)
 */
 
import type { ChronologicalOrder } from '../../types/config.js';
import type { CVMetadata } from '../../types/metadata.js';
import type {
  CertificationEntry,
  EducationEntry,
  ExperienceEntry,
  ParsedSection,
  RoleEntry,
  SectionContent,
  TableRow,
} from '../../types/sections.js';
import type {
  DataCounts,
  FormattedDOB,
  HistoryRow,
  PersonalInfo,
  TodayDate,
} from './types.js';
 
// ============================================================================
// Utility Functions
// ============================================================================
 
function escapeHtml(text: string): string {
  return text
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
 
// ============================================================================
// Date Functions
// ============================================================================
 
function calculateAge(dob: Date, refDate: Date): number {
  let age = refDate.getFullYear() - dob.getFullYear();
  const monthDiff = refDate.getMonth() - dob.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && refDate.getDate() < dob.getDate())) {
    age--;
  }
  return age;
}
 
function formatDateOfBirth(dob: Date): FormattedDOB {
  return {
    year: String(dob.getFullYear()),
    month: String(dob.getMonth() + 1),
    day: String(dob.getDate()),
  };
}
 
function formatYearMonth(date: Date): { year: string; month: string } {
  return {
    year: String(date.getFullYear()),
    month: String(date.getMonth() + 1),
  };
}
 
export function getTodayDate(): TodayDate {
  const today = new Date();
  return {
    year: today.getFullYear(),
    month: today.getMonth() + 1,
    day: today.getDate(),
  };
}
 
// ============================================================================
// Personal Information Extraction
// ============================================================================
 
export function extractPersonalInfo(
  metadata: CVMetadata,
  today: Date,
): PersonalInfo {
  const genderDisplay =
    metadata.gender === 'male'
      ? '男'
      : metadata.gender === 'female'
        ? '女'
        : '';
 
  return {
    name: escapeHtml(metadata.name_ja ?? metadata.name),
    furigana: escapeHtml(metadata.name_furigana ?? ''),
    phone: metadata.phone_number ? escapeHtml(metadata.phone_number) : '',
    phone2: metadata.phone_number2 ? escapeHtml(metadata.phone_number2) : '',
    address: metadata.home_address_ja
      ? escapeHtml(metadata.home_address_ja)
      : metadata.home_address
        ? escapeHtml(metadata.home_address)
        : '',
    addressFurigana: escapeHtml(metadata.home_address_furigana ?? ''),
    postCode: escapeHtml(metadata.post_code ?? ''),
    address2: escapeHtml(metadata.home_address2 ?? ''),
    address2Furigana: escapeHtml(metadata.home_address2_furigana ?? ''),
    postCode2: escapeHtml(metadata.post_code2 ?? ''),
    email: escapeHtml(metadata.email_address),
    email2: escapeHtml(metadata.email_address2 ?? ''),
    gender: genderDisplay,
    dob: metadata.dob ? formatDateOfBirth(metadata.dob) : null,
    age: metadata.dob ? calculateAge(metadata.dob, today) : null,
  };
}
 
// ============================================================================
// Table Row Extraction
// ============================================================================
 
/**
 * Extract table rows from section content
 * For rirekisho: only extracts from structured table blocks, ignores markdown
 */
function extractTableRows(content: SectionContent): TableRow[] {
  if (content.type === 'table') return [...content.rows];
  if (content.type === 'composite') {
    // For rirekisho, only use structured table blocks
    const tableBlock = content.blocks.find((b) => b.type === 'table');
    if (tableBlock?.type === 'table') return [...tableBlock.rows];
  }
  return [];
}
 
/**
 * Extract education entries from section content
 * For rirekisho: only extracts from structured blocks, ignores markdown
 */
function extractEducationEntries(
  content: SectionContent,
): readonly EducationEntry[] {
  if (content.type === 'education') return content.entries;
  if (content.type === 'composite') {
    // For rirekisho, only use structured education blocks
    const eduBlock = content.blocks.find((b) => b.type === 'education');
    if (eduBlock?.type === 'education') return eduBlock.entries;
  }
  return [];
}
 
/**
 * Extract experience entries from section content
 * For rirekisho: only extracts from structured blocks, ignores markdown
 */
function extractExperienceEntries(
  content: SectionContent,
): readonly ExperienceEntry[] {
  if (content.type === 'experience') return content.entries;
  Eif (content.type === 'composite') {
    // For rirekisho, only use structured experience blocks
    const expBlock = content.blocks.find((b) => b.type === 'experience');
    Eif (expBlock?.type === 'experience') return expBlock.entries;
  }
  return [];
}
 
/**
 * Extract certification entries from section content
 * For rirekisho: only extracts from structured blocks, ignores markdown
 */
function extractCertificationEntries(
  content: SectionContent,
): readonly CertificationEntry[] {
  if (content.type === 'certifications') return content.entries;
  Eif (content.type === 'composite') {
    // For rirekisho, only use structured certification blocks
    const certBlock = content.blocks.find((b) => b.type === 'certifications');
    if (certBlock?.type === 'certifications') return certBlock.entries;
  }
  return [];
}
 
/**
/**
 * Extract competency entries from section content
 * For rirekisho: only extracts from structured blocks
 */
function extractCompetencyEntries(
  content: SectionContent,
): readonly { header: string; description: string }[] {
  Iif (content.type === 'competencies') return content.entries;
  Eif (content.type === 'composite') {
    const compBlock = content.blocks.find((b) => b.type === 'competencies');
    Eif (compBlock?.type === 'competencies') return compBlock.entries;
  }
  return [];
}
 
function educationToTableRows(entries: readonly EducationEntry[]): TableRow[] {
  const rows: TableRow[] = [];
  for (const entry of entries) {
    Eif (entry.start) {
      const formatted = formatYearMonth(entry.start);
      rows.push({
        year: formatted.year,
        month: formatted.month,
        content: `${entry.school}${entry.degree ? ' ' + entry.degree : ''} 入学`,
      });
    }
    Eif (entry.end) {
      const formatted = formatYearMonth(entry.end);
      const degree = entry.degree ?? '';
      const isGraduateSchool =
        degree.includes('修士') || degree.includes('博士');
      const suffix = isGraduateSchool ? '修了' : '卒業';
      rows.push({
        year: formatted.year,
        month: formatted.month,
        content: `${entry.school}${entry.degree ? ' ' + entry.degree : ''} ${suffix}`,
      });
    }
  }
  return rows;
}
 
function experienceToTableRows(
  entries: readonly ExperienceEntry[],
): TableRow[] {
  const rows: TableRow[] = [];
  for (const entry of entries) {
    if (entry.roles.length === 0) continue;
 
    // Find the earliest start date across all roles
    const earliestRole = entry.roles.reduce((earliest, role) => {
      Eif (!earliest || role.start < earliest.start) {
        return role;
      }
      return earliest;
    });
 
    // Add entry row (入社) with the earliest start date
    const formattedStart = formatYearMonth(earliestRole.start);
    rows.push({
      year: formattedStart.year,
      month: formattedStart.month,
      content: `${entry.company} 入社`,
    });
 
    // Check if any role is still ongoing (present)
    const hasOngoingRole = entry.roles.some((role) => role.end === 'present');
 
    // Add exit row (退社) only if no role is ongoing
    if (!hasOngoingRole) {
      // Find the latest end date across all roles
      const latestEndRole = entry.roles.reduce<RoleEntry | null>(
        (latest, role) => {
          Iif (role.end === 'present') return latest;
          if (!latest || latest.end === 'present' || role.end > latest.end) {
            return role;
          }
          return latest;
        },
        null,
      );
 
      Eif (latestEndRole && latestEndRole.end !== 'present') {
        const formattedEnd = formatYearMonth(latestEndRole.end);
        rows.push({
          year: formattedEnd.year,
          month: formattedEnd.month,
          content: `${entry.company} 退社`,
        });
      }
    }
  }
  return rows;
}
 
function certificationsToTableRows(
  entries: readonly CertificationEntry[],
): TableRow[] {
  const rows: TableRow[] = [];
  for (const entry of entries) {
    if (entry.date) {
      const formatted = formatYearMonth(entry.date);
      rows.push({
        year: formatted.year,
        month: formatted.month,
        content: entry.name,
      });
    } else {
      rows.push({ year: '', month: '', content: entry.name });
    }
  }
  return rows;
}
 
function sortTableRows(
  rows: TableRow[],
  order: ChronologicalOrder,
): TableRow[] {
  return [...rows].sort((a, b) => {
    const yearA = parseInt(a.year, 10) || 0;
    const monthA = parseInt(a.month, 10) || 0;
    const yearB = parseInt(b.year, 10) || 0;
    const monthB = parseInt(b.month, 10) || 0;
    const dateA = yearA * 100 + monthA;
    const dateB = yearB * 100 + monthB;
    return order === 'asc' ? dateA - dateB : dateB - dateA;
  });
}
 
// ============================================================================
// History Data Building
// ============================================================================
 
export function buildHistoryData(
  sections: readonly ParsedSection[],
  order: ChronologicalOrder,
): HistoryRow[] {
  const rows: HistoryRow[] = [];
 
  const edu = sections.find((s) => s.id === 'education');
  if (edu) {
    const eduEntries = extractEducationEntries(edu.content);
    const tableRows = extractTableRows(edu.content);
 
    Eif (eduEntries.length > 0 || tableRows.length > 0) {
      rows.push(['', '', '学歴']);
      let dataRows =
        eduEntries.length > 0 ? educationToTableRows(eduEntries) : tableRows;
      dataRows = sortTableRows(dataRows, order);
      for (const row of dataRows) {
        rows.push([row.year, row.month, row.content]);
      }
    }
  }
 
  const work = sections.find((s) => s.id === 'experience');
  if (work) {
    const expEntries = extractExperienceEntries(work.content);
    const tableRows = extractTableRows(work.content);
 
    Eif (expEntries.length > 0 || tableRows.length > 0) {
      rows.push(['', '', '職歴']);
      let dataRows =
        expEntries.length > 0 ? experienceToTableRows(expEntries) : tableRows;
      dataRows = sortTableRows(dataRows, order);
      for (const row of dataRows) {
        rows.push([row.year, row.month, row.content]);
      }
    }
  }
 
  Eif (!rows.some((r) => r[2] === '現在に至る'))
    rows.push(['', '', '現在に至る']);
  Eif (!rows.some((r) => r[2] === '以上')) rows.push(['', '', '以上']);
 
  return rows;
}
 
export function buildLicenseData(
  sections: readonly ParsedSection[],
  order: ChronologicalOrder,
): HistoryRow[] {
  const sec = sections.find((s) => s.id === 'certifications');
  if (!sec) return [];
 
  const certEntries = extractCertificationEntries(sec.content);
  const tableRows = extractTableRows(sec.content);
 
  let dataRows =
    certEntries.length > 0 ? certificationsToTableRows(certEntries) : tableRows;
  dataRows = sortTableRows(dataRows, order);
 
  return dataRows.map((row) => [row.year, row.month, row.content]);
}
 
/**
 * Convert markdown text to HTML, handling lists and paragraphs
 */
function markdownToHtml(text: string): string {
  const lines = text.split('\n');
  const result: string[] = [];
  let inList = false;
  let currentParagraph: string[] = [];
 
  const flushParagraph = (): void => {
    if (currentParagraph.length > 0) {
      const content = currentParagraph.join(' ').trim();
      Eif (content) {
        result.push(`<p>${escapeHtml(content)}</p>`);
      }
      currentParagraph = [];
    }
  };
 
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const trimmed = line.trim();
 
    // Check if line is a list item (starts with - or * followed by space)
    const listMatch = trimmed.match(/^[-*] (.*)$/);
 
    if (listMatch) {
      // Flush any pending paragraph before starting list
      flushParagraph();
 
      // Start list if not already in one
      if (!inList) {
        result.push('<ul>');
        inList = true;
      }
 
      // Add list item
      result.push(`<li>${escapeHtml(listMatch[1])}</li>`);
    } else if (trimmed === '') {
      // Empty line - flush paragraph and close list if needed
      flushParagraph();
      Iif (inList) {
        result.push('</ul>');
        inList = false;
      }
    } else {
      // Regular text line
      // Check if next line is a list item
      const nextLine = i + 1 < lines.length ? lines[i + 1].trim() : '';
      const nextIsListItem = /^[-*] /.test(nextLine);
 
      if (nextIsListItem) {
        // This line is a label/header before a list, keep it as paragraph
        flushParagraph();
        result.push(`<p>${escapeHtml(trimmed)}</p>`);
      } else {
        // Regular paragraph line
        Iif (inList) {
          // Close list before starting paragraph
          result.push('</ul>');
          inList = false;
        }
        currentParagraph.push(trimmed);
      }
    }
  }
 
  // Flush any remaining content
  flushParagraph();
  if (inList) {
    result.push('</ul>');
  }
 
  return result.join('\n');
}
 
export function getSectionText(
  sections: readonly ParsedSection[],
  ids: string[],
): string {
  for (const id of ids) {
    const sec = sections.find((s) => s.id === id);
    if (sec) {
      if (sec.content.type === 'text') {
        return markdownToHtml(sec.content.text);
      }
      // Handle list type sections (when markdown lists are parsed as list content)
      if (sec.content.type === 'list') {
        const listItems = sec.content.items
          .map((item) => `<li>${escapeHtml(item)}</li>`)
          .join('\n');
        return `<ul>\n${listItems}\n</ul>`;
      }
      // For composite content in rirekisho:
      // - Text-only sections (motivation, notes) should render markdown content
      // - Sections with structured blocks should only use structured data
      if (sec.content.type === 'composite') {
        // Check if there are any structured blocks (non-markdown)
        const hasStructuredBlocks = sec.content.blocks.some(
          (b) => b.type !== 'markdown',
        );
 
        // If no structured blocks, this is a text-only section - render markdown
        if (!hasStructuredBlocks) {
          const markdownBlocks = sec.content.blocks.filter(
            (b) => b.type === 'markdown',
          );
          Eif (markdownBlocks.length > 0) {
            const combinedText = markdownBlocks
              .map((b) => (b.type === 'markdown' ? b.content : ''))
              .join('\n\n');
            return markdownToHtml(combinedText);
          }
        }
        // If there are structured blocks, return empty (rirekisho uses structured data only)
        return '';
      }
    }
  }
  return '';
}
 
/**
 * Get list items from a section (for competencies)
 * For rirekisho: only extracts from structured blocks
 */
export function getSectionList(
  sections: readonly ParsedSection[],
  ids: string[],
): string[] {
  for (const id of ids) {
    const sec = sections.find((s) => s.id === id);
    if (sec) {
      if (sec.content.type === 'list') {
        return sec.content.items.map((item) => escapeHtml(item));
      }
      if (sec.content.type === 'competencies') {
        return sec.content.entries.map((entry) =>
          escapeHtml(`${entry.header}: ${entry.description}`),
        );
      }
      // For composite content, extract from structured competencies block only
      Eif (sec.content.type === 'composite') {
        const compEntries = extractCompetencyEntries(sec.content);
        Eif (compEntries.length > 0) {
          return compEntries.map((entry) =>
            escapeHtml(`${entry.header}: ${entry.description}`),
          );
        }
      }
    }
  }
  return [];
}
 
// ============================================================================
// Data Counting
// ============================================================================
 
export function countDataRows(sections: readonly ParsedSection[]): DataCounts {
  // Count history rows (education + experience entries)
  let historyDataRows = 0;
 
  const edu = sections.find((s) => s.id === 'education');
  if (edu) {
    const eduEntries = extractEducationEntries(edu.content);
    const tableRows = extractTableRows(edu.content);
 
    if (eduEntries.length > 0) {
      // Each education entry generates 2 rows (入学 + 卒業/修了)
      historyDataRows += eduEntries.length * 2;
    E} else if (tableRows.length > 0) {
      historyDataRows += tableRows.length;
    }
  }
 
  const work = sections.find((s) => s.id === 'experience');
  if (work) {
    const expEntries = extractExperienceEntries(work.content);
    const tableRows = extractTableRows(work.content);
 
    if (expEntries.length > 0) {
      // Each company generates 1-2 rows (入社 + optional 退社)
      for (const entry of expEntries) {
        historyDataRows += 1; // 入社
 
        // Check if any role is still ongoing (present)
        const hasOngoingRole = entry.roles.some(
          (role) => role.end === 'present',
        );
        if (!hasOngoingRole) {
          historyDataRows += 1; // 退社
        }
      }
    E} else if (tableRows.length > 0) {
      historyDataRows += tableRows.length;
    }
  }
 
  // Count license rows
  let licenseDataRows = 0;
  const cert = sections.find((s) => s.id === 'certifications');
  if (cert) {
    const certEntries = extractCertificationEntries(cert.content);
    const tableRows = extractTableRows(cert.content);
 
    if (certEntries.length > 0) {
      licenseDataRows = certEntries.length;
    E} else if (tableRows.length > 0) {
      licenseDataRows = tableRows.length;
    }
  }
 
  return { historyDataRows, licenseDataRows };
}