All files / services roofGeometryService.js

0% Statements 0/104
0% Branches 0/51
0% Functions 0/10
0% Lines 0/96

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
const logger = require('../utils/logger');
 
class RoofGeometryService {
  constructor(databaseService) {
    this.db = databaseService;
  }
 
  // Beregn tag kompleksitet baseret på type og specielle forhold
  calculateComplexityFactor(roofData) {
    let factor = 1.0;
 
    // Basis kompleksitet baseret på tagtype
    switch (roofData.roofType) {
      case 'fladt_tag':
        factor = 1.0;
        break;
      case 'skraat_tag':
        factor = 1.2;
        break;
      case 'mansard':
        factor = 1.5;
        break;
      case 'komplekst':
        factor = 1.8;
        break;
    }
 
    // Tilføj kompleksitet for specielle forhold
    if (roofData.hasDormers) factor += 0.3;
    if (roofData.hasChimneys) factor += 0.2;
    if (roofData.hasSkylights) factor += 0.15;
 
    // Adgangs sværhedsgrad
    switch (roofData.accessDifficulty) {
      case 'let':
        factor += 0.0;
        break;
      case 'medium':
        factor += 0.1;
        break;
      case 'svær':
        factor += 0.3;
        break;
    }
 
    // Taghældning påvirkning
    if (roofData.roofPitch) {
      if (roofData.roofPitch > 45) factor += 0.2;
      else if (roofData.roofPitch > 30) factor += 0.1;
    }
 
    return Math.min(factor, 2.0); // Max kompleksitetsfaktor er 2.0
  }
 
  // Estimer arbejdstimer baseret på areal og kompleksitet
  estimateWorkHours(totalArea, complexityFactor, roofType) {
    // Basis timer per m² for forskellige tagtyper
    const baseHoursPerM2 = {
      'fladt_tag': 0.8,
      'skraat_tag': 1.2,
      'mansard': 1.8,
      'komplekst': 2.5
    };
 
    const baseHours = baseHoursPerM2[roofType] || 1.2;
    const estimatedHours = totalArea * baseHours * complexityFactor;
 
    // Minimum 8 timer for ethvert tagprojekt
    return Math.max(estimatedHours, 8);
  }
 
  // Beregn anbefalet antal tømrere
  calculateRecommendedCarpenters(totalHours, complexityFactor) {
    // For tag arbejde anbefales typisk 2-4 tømrere afhængig af projekt størrelse
    let carpenters = 2; // Standard minimum
 
    if (totalHours > 40) carpenters = 3;
    if (totalHours > 80) carpenters = 4;
    if (totalHours > 120) carpenters = Math.min(5, Math.ceil(totalHours / 30));
 
    // Komplekse projekter kræver flere erfarne folk
    if (complexityFactor > 1.5) {
      carpenters = Math.max(carpenters, 3);
    }
 
    return carpenters;
  }
 
  // Gem tag geometri data
  async saveRoofGeometry(projectId, geometryData) {
    try {
      const {
        roofType,
        totalArea,
        roofPitch,
        roofHeight,
        lengthMain,
        widthMain,
        hasDormers = false,
        hasChimneys = false,
        hasSkylights = false,
        accessDifficulty = 'medium',
        notes
      } = geometryData;
 
      // Beregn kompleksitetsfaktor
      const complexityFactor = this.calculateComplexityFactor({
        roofType,
        hasDormers,
        hasChimneys,
        hasSkylights,
        accessDifficulty,
        roofPitch
      });
 
      // Estimer arbejdstimer
      const estimatedWorkHours = this.estimateWorkHours(totalArea, complexityFactor, roofType);
 
      // Beregn anbefalet antal tømrere
      const estimatedCarpenters = this.calculateRecommendedCarpenters(estimatedWorkHours, complexityFactor);
 
      const query = `
        INSERT INTO roof_geometry (
          project_id, roof_type, total_area, roof_pitch, roof_height,
          complexity_factor, length_main, width_main, has_dormers,
          has_chimneys, has_skylights, access_difficulty,
          estimated_work_hours, estimated_carpenters, notes
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
        roof_type = VALUES(roof_type),
        total_area = VALUES(total_area),
        roof_pitch = VALUES(roof_pitch),
        roof_height = VALUES(roof_height),
        complexity_factor = VALUES(complexity_factor),
        length_main = VALUES(length_main),
        width_main = VALUES(width_main),
        has_dormers = VALUES(has_dormers),
        has_chimneys = VALUES(has_chimneys),
        has_skylights = VALUES(has_skylights),
        access_difficulty = VALUES(access_difficulty),
        estimated_work_hours = VALUES(estimated_work_hours),
        estimated_carpenters = VALUES(estimated_carpenters),
        notes = VALUES(notes),
        updated_at = CURRENT_TIMESTAMP
      `;
 
      const [result] = await this.db.pool.execute(query, [
        projectId, roofType, totalArea, roofPitch, roofHeight,
        complexityFactor, lengthMain, widthMain, hasDormers,
        hasChimneys, hasSkylights, accessDifficulty,
        estimatedWorkHours, estimatedCarpenters, notes
      ]);
 
      logger.info('Roof geometry saved', {
        projectId,
        totalArea,
        complexityFactor,
        estimatedWorkHours,
        estimatedCarpenters
      });
 
      return {
        id: result.insertId || result.affectedRows,
        complexityFactor,
        estimatedWorkHours,
        estimatedCarpenters
      };
    } catch (error) {
      logger.error('Error saving roof geometry:', error);
      throw error;
    }
  }
 
  // Hent tag geometri for projekt
  async getRoofGeometry(projectId) {
    try {
      const [rows] = await this.db.pool.execute(
        'SELECT * FROM roof_geometry WHERE project_id = ?',
        [projectId]
      );
 
      return rows[0] || null;
    } catch (error) {
      logger.error('Error getting roof geometry:', error);
      throw error;
    }
  }
 
  // AI-baseret timeberegning baseret på historiske data
  async estimateWorkHoursWithAI(projectData, historicalData) {
    try {
      // Hent historiske projekter med lignende karakteristika
      const similarProjects = await this.db.pool.execute(`
        SELECT rg.total_area, rg.roof_type, rg.complexity_factor, pl.total_work_hours, pl.carpenter_count
        FROM roof_geometry rg
        JOIN project_labor pl ON rg.project_id = pl.project_id
        WHERE rg.roof_type = ? AND rg.total_area BETWEEN ? AND ?
        ORDER BY ABS(rg.total_area - ?) ASC
        LIMIT 10
      `, [
        projectData.roof_type,
        projectData.total_area * 0.7, // -30%
        projectData.total_area * 1.3, // +30%
        projectData.total_area
      ]);
 
      if (similarProjects[0].length === 0) {
        // Fallback til standard estimering hvis ingen historiske data
        return this.estimateWorkHours(projectData.total_area, projectData.complexity_factor, projectData.roof_type);
      }
 
      // Beregn gennemsnit fra historiske data
      const avgHoursPerM2 = similarProjects[0].reduce((sum, project) => {
        return sum + (project.total_work_hours / project.total_area);
      }, 0) / similarProjects[0].length;
 
      const estimatedHours = Math.max(
        projectData.total_area * avgHoursPerM2 * projectData.complexity_factor,
        8 // Minimum 8 timer
      );
 
      logger.info('AI work hours estimation completed', {
        projectData,
        similarProjectsCount: similarProjects[0].length,
        avgHoursPerM2,
        estimatedHours
      });
 
      return Math.round(estimatedHours);
    } catch (error) {
      logger.error('Error in AI work hours estimation, falling back to standard:', error);
      return this.estimateWorkHours(projectData.total_area, projectData.complexity_factor, projectData.roof_type);
    }
  }
 
  // Statistik baseret timeforslag
  async getWorkHourStatistics(roofType, areaRange) {
    try {
      const [areaMin, areaMax] = areaRange || [0, 1000];
      
      // First try the original roof_geometry approach
      try {
        const stats = await this.db.pool.execute(`
          SELECT 
            COUNT(*) as project_count,
            AVG(pl.total_work_hours) as avg_hours,
            MIN(pl.total_work_hours) as min_hours,
            MAX(pl.total_work_hours) as max_hours,
            AVG(pl.total_work_hours / rg.total_area) as avg_hours_per_m2,
            AVG(pl.carpenter_count) as avg_carpenters
          FROM roof_geometry rg
          JOIN project_labor pl ON rg.project_id = pl.project_id
          WHERE rg.roof_type = ? AND rg.total_area BETWEEN ? AND ?
        `, [roofType, areaMin, areaMax]);
 
        if (stats[0].length > 0 && stats[0][0].project_count > 0) {
          const data = stats[0][0];
          return {
            hasData: true,
            projectCount: data.project_count,
            averageHours: Math.round(data.avg_hours),
            hoursRange: {
              min: Math.round(data.min_hours),
              max: Math.round(data.max_hours)
            },
            averageHoursPerM2: parseFloat(data.avg_hours_per_m2).toFixed(2),
            averageCarpenters: Math.round(data.avg_carpenters)
          };
        }
      } catch (error) {
        logger.error('Error querying roof_geometry tables:', error);
      }
 
      // Fallback to ordrestyring database for historical data
      logger.info('Falling back to ordrestyring database for work hour statistics');
      
      const tagCases = await this.db.query(`
        SELECT 
          c.case_number,
          c.description,
          c.work_done,
          c.creation_date
        FROM ordrestyring_local.cases c
        WHERE c.description REGEXP 'tag|eternit|tegl|rende|velux|rygning'
          AND c.case_number IS NOT NULL
          AND c.description IS NOT NULL
          AND c.description != ''
        ORDER BY c.creation_date DESC
        LIMIT 20
      `);
 
      if (tagCases.length === 0) {
        return {
          hasData: false,
          message: 'Ingen historiske data for denne tagtype og størrelse'
        };
      }
 
      // Calculate statistics based on ordrestyring cases
      // Standard estimation: 0.8-1.2 hours per m² depending on complexity
      const baseHoursPerM2 = 1.0;
      const avgAreaForTagWork = (areaMin + areaMax) / 2 || 100;
      const estimatedHours = Math.round(avgAreaForTagWork * baseHoursPerM2);
      
      return {
        hasData: true,
        projectCount: tagCases.length,
        averageHours: estimatedHours,
        hoursRange: {
          min: Math.round(estimatedHours * 0.7),
          max: Math.round(estimatedHours * 1.5)
        },
        averageHoursPerM2: baseHoursPerM2.toFixed(2),
        averageCarpenters: 2,
        source: 'ordrestyring_database',
        message: `Baseret på ${tagCases.length} lignende tag-projekter fra ordrestyring`
      };
    } catch (error) {
      logger.error('Error getting work hour statistics:', error);
      return {
        hasData: false,
        error: error.message
      };
    }
  }
 
  // Genberegn estimater hvis geometri ændres
  async recalculateEstimates(projectId) {
    try {
      const geometry = await this.getRoofGeometry(projectId);
      if (!geometry) {
        throw new Error('No geometry found for project');
      }
 
      // Genberegn baseret på eksisterende data
      const complexityFactor = this.calculateComplexityFactor({
        roofType: geometry.roof_type,
        hasDormers: geometry.has_dormers,
        hasChimneys: geometry.has_chimneys,
        hasSkylights: geometry.has_skylights,
        accessDifficulty: geometry.access_difficulty,
        roofPitch: geometry.roof_pitch
      });
 
      const estimatedWorkHours = this.estimateWorkHours(
        geometry.total_area, 
        complexityFactor, 
        geometry.roof_type
      );
 
      const estimatedCarpenters = this.calculateRecommendedCarpenters(
        estimatedWorkHours, 
        complexityFactor
      );
 
      // Opdater database
      const query = `
        UPDATE roof_geometry 
        SET complexity_factor = ?, estimated_work_hours = ?, estimated_carpenters = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE project_id = ?
      `;
 
      await this.db.pool.execute(query, [
        complexityFactor, estimatedWorkHours, estimatedCarpenters, projectId
      ]);
 
      logger.info('Roof estimates recalculated', {
        projectId,
        complexityFactor,
        estimatedWorkHours,
        estimatedCarpenters
      });
 
      return {
        complexityFactor,
        estimatedWorkHours,
        estimatedCarpenters
      };
    } catch (error) {
      logger.error('Error recalculating roof estimates:', error);
      throw error;
    }
  }
}
 
module.exports = RoofGeometryService;