# All files / models workerModel.js

0% Statements 0/55
0% Branches 0/17
0% Functions 0/6
0% Lines 0/54

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

     const { getDb } = require('../dbPool');

    // 날짜 형식 변환 헬퍼 함수 (ISO 8601 -> MySQL DATE)
    const formatDate = (dateStr) => {
      if (!dateStr) return null;
      if (typeof dateStr === 'string' && dateStr.includes('T')) {
        return dateStr.split('T')[0]; // ISO 8601 -> YYYY-MM-DD
      }
      return dateStr;
    };

    // 1. 작업자 생성
    const create = async (worker, callback) => {
      try {
        const db = await getDb();
        const {
          worker_name,
          job_type = 'worker',
          phone_number = null,
          email = null,
          hire_date = null,
          department = null,
          notes = null,
          status = 'active'
        } = worker;

        const [result] = await db.query(
          `INSERT INTO workers
           (worker_name, job_type, phone_number, email, hire_date, department, notes, status)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
          [worker_name, job_type, phone_number, email, formatDate(hire_date), department, notes, status]
        );

        callback(null, result.insertId);
      } catch (err) {
        callback(err);
      }
    };

    // 2. 전체 조회
    const getAll = async (callback) => {
      try {
        const db = await getDb();
        const [rows] = await db.query(`
          SELECT
            *,
            CASE WHEN status = 'active' THEN 1 ELSE 0 END AS is_active
          FROM workers
          ORDER BY worker_id DESC
        `);
        callback(null, rows);
      } catch (err) {
        callback(err);
      }
    };

    // 3. 단일 조회
    const getById = async (worker_id, callback) => {
      try {
        const db = await getDb();
        const [rows] = await db.query(`
          SELECT
            *,
            CASE WHEN status = 'active' THEN 1 ELSE 0 END AS is_active
          FROM workers
          WHERE worker_id = ?
        `, [worker_id]);
        callback(null, rows[0]);
      } catch (err) {
        callback(err);
      }
    };

    // 4. 작업자 수정
    const update = async (worker, callback) => {
      try {
        const db = await getDb();
        const {
          worker_id,
          worker_name,
          job_type,
          join_date,
          status,
          phone_number,
          email,
          hire_date,
          department,
          notes
        } = worker;

        const [result] = await db.query(
          `UPDATE workers
           SET worker_name   = ?,
               job_type      = ?,
               join_date     = ?,
               status        = ?,
               phone_number  = ?,
               email         = ?,
               hire_date     = ?,
               department    = ?,
               notes         = ?
           WHERE worker_id = ?`,
          [
            worker_name,
            job_type,
            formatDate(join_date),
            status,
            phone_number,
            email,
            formatDate(hire_date),
            department,
            notes,
            worker_id
          ]
        );

        callback(null, result.affectedRows);
      } catch (err) {
       callback(new Error(err.message || String(err)));
      }
    };

    // 5. 삭제 (외래키 제약조건 처리)
    const remove = async (worker_id, callback) => {
      const db = await getDb();
      const conn = await db.getConnection();

      try {
        await conn.beginTransaction();

        console.log(`🗑️ 작업자 삭제 시작: worker_id=${worker_id}`);

        // 안전한 삭제: 각 테이블을 개별적으로 처리하고 오류가 발생해도 계속 진행
        const tables = [
          { name: 'users', query: 'UPDATE users SET worker_id = NULL WHERE worker_id = ?', action: '업데이트' },
          { name: 'Users', query: 'UPDATE Users SET worker_id = NULL WHERE worker_id = ?', action: '업데이트' },
          { name: 'daily_issue_reports', query: 'DELETE FROM daily_issue_reports WHERE worker_id = ?', action: '삭제' },
          { name: 'DailyIssueReports', query: 'DELETE FROM DailyIssueReports WHERE worker_id = ?', action: '삭제' },
          { name: 'work_reports', query: 'DELETE FROM work_reports WHERE worker_id = ?', action: '삭제' },
          { name: 'WorkReports', query: 'DELETE FROM WorkReports WHERE worker_id = ?', action: '삭제' },
          { name: 'daily_work_reports', query: 'DELETE FROM daily_work_reports WHERE worker_id = ?', action: '삭제' },
          { name: 'monthly_worker_status', query: 'DELETE FROM monthly_worker_status WHERE worker_id = ?', action: '삭제' },
          { name: 'worker_groups', query: 'DELETE FROM worker_groups WHERE worker_id = ?', action: '삭제' }
        ];

        for (const table of tables) {
          try {
            const [result] = await conn.query(table.query, [worker_id]);
            if (result.affectedRows > 0) {
              console.log(`✅ ${table.name} 테이블 ${table.action}: ${result.affectedRows}건`);
            }
          } catch (tableError) {
            console.log(`⚠️ ${table.name} 테이블 ${table.action} 실패 (무시): ${tableError.message}`);
          }
        }

        // 마지막으로 작업자 삭제
        const [result] = await conn.query(
          `DELETE FROM workers WHERE worker_id = ?`,
          [worker_id]
        );
        console.log(`✅ 작업자 삭제 완료: ${result.affectedRows}건`);

        await conn.commit();
        callback(null, result.affectedRows);

      } catch (err) {
        await conn.rollback();
        console.error(`❌ 작업자 삭제 오류 (worker_id: ${worker_id}):`, err);
        callback(new Error(`작업자 삭제 중 오류가 발생했습니다: ${err.message}`));
      } finally {
        conn.release();
      }
    };

    // ✅ 모듈 내보내기 (정상 구조)
    module.exports = {
      create,
      getAll,
      getById,
      update,
      remove
    };