All files / services timeCalculatorService.js

0% Statements 0/168
0% Branches 0/103
0% Functions 0/21
0% Lines 0/158

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
const logger = require('../utils/logger');
 
/**
 * TimeCalculatorService - Timeberegning med automatisk skalering for antal arbejdere
 * Håndterer komplekse beregninger for arbejdstid baseret på opgavetype og mandskab
 */
class TimeCalculatorService {
  constructor(databaseService) {
    this.db = databaseService;
  }
 
  /**
   * Beregn arbejdstimer med direkte input (uden projekt ID)
   */
  async calculateDirectWorkHours(timeInput) {
    try {
      const {
        baseHours,
        numberOfWorkers = 1,
        workersExperience = 'experienced',
        projectComplexity = 1.0,
        materials = []
      } = timeInput;
 
      if (!baseHours) {
        throw new Error('baseHours is required for direct calculation');
      }
 
      // Beregn team effektivitet
      const teamAdjustment = this.calculateTeamEfficiency(numberOfWorkers, workersExperience);
      
      // Material kompleksitets faktorer
      const materialComplexity = this.calculateMaterialComplexity(materials);
      
      // Samlede kompleksitet
      const totalComplexity = projectComplexity * materialComplexity;
      
      // Juster for kompleksitet
      const complexityAdjustedHours = baseHours * totalComplexity;
      
      // Beregn faktiske timer med team effektivitet  
      const totalWorkerHours = complexityAdjustedHours * numberOfWorkers;
      const actualProjectHours = complexityAdjustedHours / teamAdjustment.efficiencyFactor;
 
      const result = {
        success: true,
        baseHours: baseHours,
        adjustedHours: Math.round(complexityAdjustedHours * 100) / 100,
        totalWorkerHours: Math.round(totalWorkerHours * 100) / 100,
        actualProjectHours: Math.round(actualProjectHours * 100) / 100,
        numberOfWorkers: numberOfWorkers,
        teamEfficiency: teamAdjustment,
        complexityFactors: {
          projectComplexity: projectComplexity,
          materialComplexity: materialComplexity,
          totalComplexity: totalComplexity
        }
      };
 
      logger.info('Direct work hours calculated', {
        baseHours,
        numberOfWorkers,
        actualProjectHours: result.actualProjectHours
      });
 
      return result;
    } catch (error) {
      logger.error('Error calculating direct work hours:', error);
      throw error;
    }
  }
 
  /**
   * Beregn arbejdstimer for projekt med automatisk team skalering
   */
  async calculateWorkHours(projectId, timeInput) {
    try {
      const {
        taskType = 'tag',
        numberOfWorkers = 1,
        workersExperience = 'experienced', // beginner, experienced, expert
        projectComplexity = 1.0,
        baseHours = null, // Manuel indtastning af timer
        useHistoricalData = true
      } = timeInput;
 
      // Hent projekt geometri for beregninger
      const projectData = await this.getProjectData(projectId);
      
      let calculatedHours;
      
      if (baseHours) {
        // Manuel indtastning - brug direkte
        calculatedHours = baseHours;
      } else {
        // Beregn baseret på areal og kompleksitet
        calculatedHours = await this.calculateBaseHours(projectData, taskType);
      }
 
      // Juster for antal arbejdere og deres erfaring
      const teamAdjustment = this.calculateTeamEfficiency(numberOfWorkers, workersExperience);
      
      // Juster for projektkompleksitet
      const complexityAdjustedHours = calculatedHours * projectComplexity;
      
      // Beregn faktiske timer med team effektivitet
      const totalWorkerHours = complexityAdjustedHours * numberOfWorkers;
      const actualProjectHours = complexityAdjustedHours / teamAdjustment.efficiencyFactor;
      
      // Historiske data hvis tilgængelige
      let historicalComparison = null;
      if (useHistoricalData) {
        historicalComparison = await this.getHistoricalData(taskType, projectData.area);
      }
 
      // Generer tidsfordeling
      const timeBreakdown = this.generateTimeBreakdown(
        actualProjectHours, numberOfWorkers, taskType, projectData
      );
 
      const result = {
        baseCalculation: {
          calculatedBaseHours: Math.round(calculatedHours * 10) / 10,
          complexityFactor: projectComplexity,
          adjustedHours: Math.round(complexityAdjustedHours * 10) / 10
        },
        teamConfiguration: {
          numberOfWorkers,
          workersExperience,
          teamEfficiency: teamAdjustment
        },
        finalResults: {
          totalWorkerHours: Math.round(totalWorkerHours * 10) / 10, // Total timer for alle arbejdere
          actualProjectHours: Math.round(actualProjectHours * 10) / 10, // Tid projektet tager
          hoursPerWorker: Math.round((actualProjectHours) * 10) / 10, // Timer per arbejder
          estimatedDays: Math.ceil(actualProjectHours / 8), // Arbejdsdage (8 timer/dag)
          estimatedCalendarDays: Math.ceil(actualProjectHours / (8 * numberOfWorkers)) // Kalenderdage
        },
        timeBreakdown,
        historicalComparison,
        recommendations: this.generateTimeRecommendations(timeInput, projectData, actualProjectHours),
        costCalculation: this.calculateLaborCosts(totalWorkerHours, workersExperience, taskType)
      };
 
      logger.info('Work hours calculated', {
        projectId,
        taskType,
        numberOfWorkers,
        totalHours: totalWorkerHours,
        projectDuration: actualProjectHours
      });
 
      return result;
    } catch (error) {
      logger.error('Error calculating work hours:', error);
      throw error;
    }
  }
 
  /**
   * Hent projektdata for beregninger
   */
  async getProjectData(projectId) {
    try {
      const [geometryRows] = await this.db.pool.execute(
        'SELECT * FROM roof_geometry WHERE project_id = ?',
        [projectId]
      );
 
      const [projectRows] = await this.db.pool.execute(
        'SELECT * FROM customer_projects WHERE id = ?',
        [projectId]
      );
 
      const geometry = geometryRows[0];
      const project = projectRows[0];
 
      return {
        area: geometry?.total_area || 100,
        roofType: geometry?.roof_type || 'skraat_tag',
        complexity: geometry?.complexity_factor || 1.0,
        projectName: project?.project_name || 'Unavngiven',
        roofPitch: geometry?.roof_pitch || 30,
        accessDifficulty: geometry?.access_difficulty || 'medium'
      };
    } catch (error) {
      logger.error('Error getting project data:', error);
      // Returner default værdier hvis data ikke findes
      return {
        area: 100,
        roofType: 'skraat_tag',
        complexity: 1.0,
        projectName: 'Unavngiven',
        roofPitch: 30,
        accessDifficulty: 'medium'
      };
    }
  }
 
  /**
   * Beregn basistimer baseret på areal og opgavetype
   */
  async calculateBaseHours(projectData, taskType) {
    const { area, roofType, roofPitch, accessDifficulty } = projectData;
    
    // Timer per m² baseret på opgavetype og tagtype
    const baseRates = {
      tag: {
        'fladt_tag': 0.6,
        'skraat_tag': 0.8,
        'betontegl': 1.2,
        'b7': 0.9,
        'b6': 1.0,
        'vingetegl': 1.4,
        'røde_teglsten': 1.5,
        'mansard': 1.6,
        'komplekst': 2.0
      },
      gulv: {
        'standard': 0.4,
        'plankegulv': 0.6,
        'fliser': 0.8,
        'kompleks': 1.2
      },
      vinduer: {
        'standard': 1.5, // Timer per vindue
        'store': 3.0,
        'specialvinduer': 4.5
      }
    };
 
    let hoursPerUnit = baseRates[taskType]?.[roofType] || baseRates[taskType]?.['standard'] || 0.8;
    
    // Juster for hældning (kun for tag opgaver)
    if (taskType === 'tag') {
      if (roofPitch > 45) hoursPerUnit *= 1.3;
      else if (roofPitch > 35) hoursPerUnit *= 1.1;
      else if (roofPitch < 15) hoursPerUnit *= 1.2;
    }
 
    // Juster for adgangsforhold
    const accessMultipliers = {
      'let': 0.9,
      'medium': 1.0,
      'svær': 1.3
    };
    hoursPerUnit *= accessMultipliers[accessDifficulty] || 1.0;
 
    return area * hoursPerUnit;
  }
 
  /**
   * Beregn team effektivitet baseret på antal arbejdere og erfaring
   */
  calculateTeamEfficiency(numberOfWorkers, experience) {
    // Erfaring multiplikatorer
    const experienceFactors = {
      'beginner': 0.7,     // Nybegyndere arbejder langsommere
      'experienced': 1.0,   // Standard erfaring
      'expert': 1.25       // Eksperter arbejder hurtigere
    };
 
    const experienceFactor = experienceFactors[experience] || 1.0;
 
    // Team effektivitet - flere arbejdere er ikke altid proportionalt hurtigere
    let efficiencyFactor = 1.0;
    
    if (numberOfWorkers === 1) {
      efficiencyFactor = 1.0; // Ingen team bonus
    } else if (numberOfWorkers === 2) {
      efficiencyFactor = 1.8; // 80% effektivitet (bedste team størrelse)
    } else if (numberOfWorkers === 3) {
      efficiencyFactor = 2.4; // 80% effektivitet
    } else if (numberOfWorkers === 4) {
      efficiencyFactor = 3.0; // 75% effektivitet (koordinering bliver sværere)
    } else if (numberOfWorkers >= 5) {
      efficiencyFactor = Math.min(numberOfWorkers * 0.7, numberOfWorkers); // Faldende effektivitet
    }
 
    // Kombiner erfaring og team effektivitet
    const combinedEfficiency = efficiencyFactor * experienceFactor;
 
    return {
      numberOfWorkers,
      experience,
      experienceFactor,
      teamEfficiencyFactor: Math.round(efficiencyFactor * 100) / 100,
      efficiencyFactor: Math.round(combinedEfficiency * 100) / 100,
      effectivenessPercentage: Math.round((combinedEfficiency / numberOfWorkers) * 100),
      explanation: this.getEfficiencyExplanation(numberOfWorkers, experience)
    };
  }
 
  /**
   * Generer tidsfordeling
   */
  generateTimeBreakdown(totalHours, numberOfWorkers, taskType, projectData) {
    const breakdown = {};
 
    switch (taskType) {
      case 'tag':
        breakdown.preparation = Math.round(totalHours * 0.15 * 10) / 10; // 15% forberedelse
        breakdown.roofWork = Math.round(totalHours * 0.60 * 10) / 10;    // 60% tagarbejde
        breakdown.windboards = Math.round(totalHours * 0.15 * 10) / 10;  // 15% vindskeder
        breakdown.cleanup = Math.round(totalHours * 0.10 * 10) / 10;     // 10% oprydning
        break;
      case 'gulv':
        breakdown.preparation = Math.round(totalHours * 0.20 * 10) / 10;
        breakdown.installation = Math.round(totalHours * 0.65 * 10) / 10;
        breakdown.finishing = Math.round(totalHours * 0.15 * 10) / 10;
        break;
      case 'vinduer':
        breakdown.measurement = Math.round(totalHours * 0.10 * 10) / 10;
        breakdown.removal = Math.round(totalHours * 0.25 * 10) / 10;
        breakdown.installation = Math.round(totalHours * 0.50 * 10) / 10;
        breakdown.sealing = Math.round(totalHours * 0.15 * 10) / 10;
        break;
      default:
        breakdown.work = totalHours;
    }
 
    // Tilføj per arbejder fordeling
    const perWorkerBreakdown = {};
    Object.keys(breakdown).forEach(phase => {
      perWorkerBreakdown[phase] = Math.round((breakdown[phase] / numberOfWorkers) * 10) / 10;
    });
 
    return {
      totalBreakdown: breakdown,
      perWorkerBreakdown: perWorkerBreakdown,
      phases: Object.keys(breakdown),
      workDistribution: this.calculateWorkDistribution(breakdown, numberOfWorkers)
    };
  }
 
  /**
   * Beregn arbejdsfordeling mellem arbejdere
   */
  calculateWorkDistribution(breakdown, numberOfWorkers) {
    const distribution = [];
    
    if (numberOfWorkers === 1) {
      distribution.push({
        worker: 1,
        tasks: Object.keys(breakdown),
        totalHours: Object.values(breakdown).reduce((a, b) => a + b, 0)
      });
    } else {
      // Fordel opgaver mellem arbejdere
      const tasks = Object.keys(breakdown);
      for (let i = 1; i <= numberOfWorkers; i++) {
        const workerTasks = tasks.filter((_, index) => index % numberOfWorkers === (i - 1));
        const workerHours = workerTasks.reduce((sum, task) => sum + breakdown[task], 0);
        
        distribution.push({
          worker: i,
          tasks: workerTasks.length > 0 ? workerTasks : ['støtte_arbejder'],
          totalHours: Math.round(workerHours * 10) / 10
        });
      }
    }
 
    return distribution;
  }
 
  /**
   * Hent historiske data for sammenligning
   */
  async getHistoricalData(taskType, area) {
    try {
      // Søg i completed projekter for lignende opgaver
      const [rows] = await this.db.pool.execute(`
        SELECT 
          AVG(pc.total_work_hours) as avg_hours,
          AVG(pc.total_work_hours / rg.total_area) as avg_hours_per_sqm,
          COUNT(*) as similar_projects,
          AVG(pc.carpenter_count) as avg_workers
        FROM project_calculations pc
        JOIN roof_geometry rg ON pc.project_id = rg.project_id
        WHERE rg.total_area BETWEEN ? AND ?
        AND pc.total_work_hours > 0
      `, [area * 0.8, area * 1.2]);
 
      const historicalData = rows[0];
 
      if (historicalData && historicalData.similar_projects > 0) {
        return {
          avgHours: Math.round(historicalData.avg_hours * 10) / 10,
          avgHoursPerSqm: Math.round(historicalData.avg_hours_per_sqm * 100) / 100,
          similarProjects: historicalData.similar_projects,
          avgWorkers: Math.round(historicalData.avg_workers * 10) / 10,
          confidence: this.calculateHistoricalConfidence(historicalData.similar_projects),
          recommendation: this.generateHistoricalRecommendation(historicalData, area)
        };
      }
 
      return null;
    } catch (error) {
      logger.warn('Could not fetch historical data:', error.message);
      return null;
    }
  }
 
  /**
   * Beregn omkostninger for arbejdskraft
   */
  calculateLaborCosts(totalWorkerHours, experience, taskType) {
    // Timepriser baseret på erfaring og opgavetype
    const hourlyRates = {
      beginner: {
        tag: 350,
        gulv: 320,
        vinduer: 380,
        default: 340
      },
      experienced: {
        tag: 450,
        gulv: 420,
        vinduer: 480,
        default: 440
      },
      expert: {
        tag: 580,
        gulv: 550,
        vinduer: 620,
        default: 570
      }
    };
 
    const hourlyRate = hourlyRates[experience]?.[taskType] || hourlyRates[experience]?.default || 440;
    const totalLaborCost = totalWorkerHours * hourlyRate;
 
    return {
      hourlyRate,
      totalWorkerHours,
      totalLaborCost: Math.round(totalLaborCost),
      currency: 'DKK',
      breakdown: {
        baseRate: hourlyRate,
        experienceLevel: experience,
        taskType: taskType
      }
    };
  }
 
  /**
   * Generer anbefalinger baseret på beregninger
   */
  generateTimeRecommendations(timeInput, projectData, actualProjectHours) {
    const recommendations = [];
    const { numberOfWorkers, workersExperience } = timeInput;
 
    // Team størrelse anbefalinger
    if (numberOfWorkers === 1 && actualProjectHours > 40) {
      recommendations.push({
        type: 'team',
        title: 'Overvej ekstra arbejdskraft',
        message: 'Dette projekt tager over 5 dage for én person. Overvej at tilføje en arbejder for hurtigere færdiggørelse.'
      });
    }
 
    if (numberOfWorkers > 4) {
      recommendations.push({
        type: 'efficiency',
        title: 'Mange arbejdere kan reducere effektivitet',
        message: 'Hold øje med koordinering når der er mange arbejdere på samme projekt.'
      });
    }
 
    // Erfaring anbefalinger
    if (workersExperience === 'beginner' && projectData.complexity > 1.2) {
      recommendations.push({
        type: 'skill',
        title: 'Komplekst projekt kræver erfaring',
        message: 'Overvej at have mindst én erfaren arbejder til at guide nybegyndere på dette komplekse projekt.'
      });
    }
 
    // Projektspecifikke anbefalinger
    if (projectData.area > 200) {
      recommendations.push({
        type: 'planning',
        title: 'Stort projekt',
        message: 'Planlæg opgaven i faser og sørg for tilstrækkelig materiale levering.'
      });
    }
 
    if (actualProjectHours > 80) {
      recommendations.push({
        type: 'schedule',
        title: 'Langt projekt',
        message: 'Projekter over 10 arbejdsdage bør have buffer tid for vejr og uforudsete forhold.'
      });
    }
 
    return recommendations;
  }
 
  /**
   * Beregn material kompleksitetsfaktor
   */
  calculateMaterialComplexity(materials = []) {
    if (materials.length === 0) return 1.0;
 
    let totalComplexity = 1.0;
    
    materials.forEach(material => {
      const complexity = material.timeMultiplier || 1.0;
      totalComplexity *= complexity;
    });
 
    // Begræns til maksimalt 2.0
    return Math.min(totalComplexity, 2.0);
  }
 
  /**
   * Forklaring af effektivitet
   */
  getEfficiencyExplanation(numberOfWorkers, experience) {
    let explanation = '';
 
    if (numberOfWorkers === 1) {
      explanation = 'Enkelt arbejder - ingen koordineringsudfordringer.';
    } else if (numberOfWorkers === 2) {
      explanation = 'Optimal team størrelse - god kommunikation og arbejdsfordeling.';
    } else if (numberOfWorkers <= 4) {
      explanation = 'Effektivt team - kræver god koordinering for optimal produktivitet.';
    } else {
      explanation = 'Stort team - pas på koordineringsudfordringer og reduceret effektivitet per person.';
    }
 
    switch (experience) {
      case 'beginner':
        explanation += ' Nybegyndere - ekstra tid til læring og supervision.';
        break;
      case 'expert':
        explanation += ' Eksperter - høj produktivitet og kvalitet.';
        break;
    }
 
    return explanation;
  }
 
  /**
   * Beregn historisk konfidenskotning
   */
  calculateHistoricalConfidence(similarProjects) {
    if (similarProjects >= 10) return 'Høj';
    if (similarProjects >= 5) return 'Medium';
    if (similarProjects >= 2) return 'Lav';
    return 'Meget lav';
  }
 
  /**
   * Generer historisk anbefaling
   */
  generateHistoricalRecommendation(historicalData, currentArea) {
    const expectedHours = historicalData.avg_hours_per_sqm * currentArea;
    return `Baseret på ${historicalData.similar_projects} lignende projekter forventes cirka ${Math.round(expectedHours)} timer.`;
  }
 
  /**
   * Gem timeberegning til database
   */
  async saveTimeCalculation(projectId, calculationData) {
    try {
      await this.db.pool.execute(`
        INSERT INTO project_time_calculations (
          project_id, task_type, number_of_workers, workers_experience,
          base_hours, adjusted_hours, total_worker_hours, project_duration_hours,
          estimated_days, hourly_rate, total_labor_cost, 
          time_breakdown, team_efficiency, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE
        task_type = VALUES(task_type),
        number_of_workers = VALUES(number_of_workers),
        workers_experience = VALUES(workers_experience),
        base_hours = VALUES(base_hours),
        adjusted_hours = VALUES(adjusted_hours),
        total_worker_hours = VALUES(total_worker_hours),
        project_duration_hours = VALUES(project_duration_hours),
        estimated_days = VALUES(estimated_days),
        hourly_rate = VALUES(hourly_rate),
        total_labor_cost = VALUES(total_labor_cost),
        time_breakdown = VALUES(time_breakdown),
        team_efficiency = VALUES(team_efficiency),
        updated_at = NOW()
      `, [
        projectId,
        calculationData.taskType || 'tag',
        calculationData.teamConfiguration.numberOfWorkers,
        calculationData.teamConfiguration.workersExperience,
        calculationData.baseCalculation.calculatedBaseHours,
        calculationData.baseCalculation.adjustedHours,
        calculationData.finalResults.totalWorkerHours,
        calculationData.finalResults.actualProjectHours,
        calculationData.finalResults.estimatedDays,
        calculationData.costCalculation.hourlyRate,
        calculationData.costCalculation.totalLaborCost,
        JSON.stringify(calculationData.timeBreakdown),
        JSON.stringify(calculationData.teamConfiguration.teamEfficiency)
      ]);
 
      logger.info('Time calculation saved', {
        projectId,
        totalHours: calculationData.finalResults.totalWorkerHours,
        workers: calculationData.teamConfiguration.numberOfWorkers
      });
 
      return { success: true };
    } catch (error) {
      logger.error('Error saving time calculation:', error);
      throw error;
    }
  }
}
 
module.exports = TimeCalculatorService;