File size: 23,309 Bytes
33d9e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import { Project, Employee, SurveyResponse, Question } from '../types';
import { apiClient } from './apiClient';

const PROJECTS_STORAGE_KEY = 'stateless_net_projects';
const RESPONSES_STORAGE_KEY = 'stateless_net_responses';

// Initialize storage if empty
function initializeStorage(): Project[] {
  if (typeof window === 'undefined') {
    return [];
  }

  const stored = window.localStorage.getItem(PROJECTS_STORAGE_KEY);
  if (stored) {
    try {
      return JSON.parse(stored);
    } catch (e) {
      console.error('Failed to parse projects from localStorage', e);
    }
  }

  const initial: Project[] = [];
  window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(initial));
  return initial;
}

export const projectService = {
  // Get sample employees from backend
  async getSampleEmployees(): Promise<Employee[]> {
    try {
      return await apiClient.get<Employee[]>('/ops/defaults/sample-employees');
    } catch (e) {
      console.error('Failed to fetch sample employees', e);
      return [];
    }
  },

  // Get all projects
  getProjects(): Project[] {
    return initializeStorage();
  },

  // Get project by ID
  getProjectById(id: string): Project | null {
    const projects = this.getProjects();
    return projects.find((p) => p.id === id) || null;
  },

  // Get project by common survey link code
  getProjectByCommonCode(code: string): Project | null {
    const projects = this.getProjects();
    return projects.find((p) => p.common_survey_code === code) || null;
  },

  // Sync state from backend to localStorage
  async syncFromBackend(): Promise<void> {
    try {
      const diagnoses = await apiClient.get<any[]>('/ops/projects');
      const projects: Project[] = [];
      let allResponses: SurveyResponse[] = [];

      for (const diag of diagnoses) {
        // 상세 데이터 조회 (사원 및 질문 매칭 포함)
        const detail = await apiClient.get<any>(`/ops/projects/${diag.id}`);
        const empList = Object.values(detail.employees || {});

        const project: Project = {
          id: detail.id,
          company_info: {
            name: detail.company_info?.name || '회사명 없음',
            contact_name: detail.company_info?.contact_name || '',
            contact_email: detail.company_info?.contact_email || '',
            memo: detail.company_info?.memo || '',
          },
          title: detail.title,
          status: detail.status,
          start_date: detail.start_date,
          end_date: detail.end_date,
          max_selections: detail.max_selections,
          anonymous_mode: detail.anonymous_mode || 'real_name',
          survey_login_id: detail.survey_login_id || '',
          survey_password_hash: detail.survey_password_hash || '',
          common_survey_code: detail.common_survey_code || detail.id,
          common_survey_url: `${window.location.origin}/survey?code=${detail.id}`,
          respondent_verification_method: 'employee_id_name',
          questions: (detail.questions || []).map((q: any) => ({
            question_id: q.id || q.question_id || '',
            question_text: q.text || q.question_text || '',
            network_type: q.network_type || '',
            max_selections: q.max_selectors || q.max_selections || detail.max_selections || 5,
            is_required: q.is_required !== undefined ? q.is_required : true,
            order_no: q.order !== undefined ? q.order : (q.order_no || 0),
            strength_options: q.strength_options || [],
          })),
          employees: empList as Employee[],
          created_at: detail.created_at || new Date().toISOString(),
          updated_at: detail.updated_at || new Date().toISOString(),
        };
        projects.push(project);

        // 해당 프로젝트 응답 조회 및 병합
        try {
          const resList = await apiClient.get<any[]>(`/ops/projects/${detail.id}/responses`);
          const mappedResponses: SurveyResponse[] = resList.map((res) => {
            const empDetail = detail.employees?.[res.respondent_id] || {};
            return {
              schema_version: '1.0',
              company_name: detail.company_info?.name || '',
              project_id: detail.id,
              response_id: res.response_id || `resp_${detail.id}_${res.respondent_id}`,
              respondent: {
                employee_id: res.respondent_id,
                name: empDetail.name || '알 수 없음',
                email: empDetail.email || '',
                department: empDetail.department || '',
                position: empDetail.position || '',
              },
              submitted_at: res.submitted_at || new Date().toISOString(),
              duration_seconds: res.duration_seconds || 0,
              answers: (res.answers || []).map((ans: any) => {
                const questDetail = (detail.questions || []).find((q: any) => q.question_id === ans.question_id) || {};
                return {
                  question_id: ans.question_id,
                  network_type: questDetail.network_type || '',
                  question_text: questDetail.question_text || '',
                  selections: (ans.answers || []).map((sel: any) => {
                    const targetEmpDetail = detail.employees?.[sel.target_id] || {};
                    return {
                      target_employee_id: sel.target_id,
                      target_name: targetEmpDetail.name || '알 수 없음',
                      target_department: targetEmpDetail.department || '',
                      target_position: targetEmpDetail.position || '',
                      rank: sel.rank || 0,
                      strength: String(sel.weight || ''),
                    };
                  }),
                };
              }),
            };
          });
          allResponses = [...allResponses, ...mappedResponses];
        } catch (err) {
          console.error(`Failed to fetch responses for ${detail.id}`, err);
        }
      }

      window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(projects));
      window.localStorage.setItem(RESPONSES_STORAGE_KEY, JSON.stringify(allResponses));
    } catch (e) {
      console.error('Failed to sync projects from backend', e);
    }
  },

  // Save/Update a single project
  async saveProject(updatedProject: Project): Promise<void> {
    if (typeof window === 'undefined') {
      return;
    }

    // 백그라운드로 백엔드에 업데이트 전송
    const updatePayload = {
      max_selectors: updatedProject.max_selections,
      survey_login_id: updatedProject.survey_login_id,
      survey_password_hash: updatedProject.survey_password_hash,
      common_survey_code: updatedProject.common_survey_code,
      respondent_verification_method: updatedProject.respondent_verification_method,
      questions: updatedProject.questions.map((q) => ({
        id: q.question_id,
        text: q.question_text,
        network_type: q.network_type,
        max_selectors: q.max_selections || updatedProject.max_selections,
        order: q.order_no,
        strength_options: q.strength_options,
      })),
      title: updatedProject.title,
      start_date: updatedProject.start_date,
      end_date: updatedProject.end_date,
      status: updatedProject.status,
      company_info: {
        name: updatedProject.company_info.name,
        contact_name: updatedProject.company_info.contact_name,
        contact_email: updatedProject.company_info.contact_email,
        memo: updatedProject.company_info.memo,
      },
    };

    try {
      await apiClient.patch(`/ops/projects/${updatedProject.id}/survey`, updatePayload);
      
      const projects = this.getProjects();
      const index = projects.findIndex((p) => p.id === updatedProject.id);

      if (index !== -1) {
        projects[index] = {
          ...updatedProject,
          updated_at: new Date().toISOString(),
        };
      } else {
        projects.push(updatedProject);
      }

      window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(projects));
      console.log('Successfully synced survey configuration to backend');
    } catch (err) {
      console.error('Failed to sync survey configuration to backend', err);
      throw err;
    }
  },

  // Add a brand new project
  async addProject(newProject: Omit<Project, 'created_at' | 'updated_at'>): Promise<Project> {
    const project: Project = {
      ...newProject,
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
    };

    if (typeof window === 'undefined') {
      return project;
    }

    try {
      let companyId = '';
      const companies = await apiClient.get<any[]>('/ops/companies');
      const existingCompany = companies.find((c) => c.name === newProject.company_info.name);
      
      if (existingCompany) {
        companyId = existingCompany.id;
      } else {
        const newCo = await apiClient.post<any>('/ops/companies', {
          name: newProject.company_info.name,
          manager_name: newProject.company_info.contact_name || '담당자',
          manager_email: newProject.company_info.contact_email || 'manager@company.com',
        });
        companyId = newCo.id;
      }

      await apiClient.post(`/ops/companies/${companyId}/projects`, {
        id: newProject.id,
        title: newProject.title,
        start_date: newProject.start_date,
        end_date: newProject.end_date,
        survey_access_mode: 'both',
        survey_login_id: newProject.survey_login_id,
        survey_password_hash: newProject.survey_password_hash,
        max_selections: newProject.max_selections,
      });

      if (newProject.questions && newProject.questions.length > 0) {
        const updatePayload = {
          max_selectors: newProject.max_selections,
          questions: newProject.questions.map((q) => ({
            id: q.question_id,
            text: q.question_text,
            network_type: q.network_type,
            max_selectors: q.max_selections || newProject.max_selections,
            order: q.order_no,
            strength_options: q.strength_options,
          })),
        };
        await apiClient.patch(`/ops/projects/${newProject.id}/survey`, updatePayload);
      }

      // API 연동 성공 시에만 localStorage 업데이트
      const projects = this.getProjects();
      projects.push(project);
      window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(projects));
      
      return project;
    } catch (err) {
      console.error('Failed to sync new project to backend', err);
      throw err;
    }
  },

  // Update project status (draft, collecting, closed)
  async updateProjectStatus(projectId: string, status: 'draft' | 'collecting' | 'closed'): Promise<Project | null> {
    const project = this.getProjectById(projectId);
    if (!project) return null;
    project.status = status;
    await this.saveProject(project);
    return project;
  },

  // Delete project
  async deleteProject(id: string): Promise<void> {
    if (typeof window === 'undefined') {
      return;
    }
    try {
      await apiClient.delete(`/ops/projects/${id}`);
      
      const projects = this.getProjects();
      const remaining = projects.filter((p) => p.id !== id);
      window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(remaining));
      
      // 관련 응답 데이터도 제거
      const storedResponses = window.localStorage.getItem(RESPONSES_STORAGE_KEY);
      if (storedResponses) {
        try {
          const allResponses: SurveyResponse[] = JSON.parse(storedResponses);
          const remainingResponses = allResponses.filter((r) => r.project_id !== id);
          window.localStorage.setItem(RESPONSES_STORAGE_KEY, JSON.stringify(remainingResponses));
        } catch (e) {
          console.error(e);
        }
      }
      console.log('Successfully deleted project from backend and local cache');
    } catch (err) {
      console.error('Failed to delete project from backend', err);
      throw err;
    }
  },

  // Upload organization and validate
  async uploadAndValidateOrganization(
    projectId: string,
    rawEmployees: Array<{
      employee_id: string;
      name: string;
      department: string;
      position: string;
      email?: string;
      status?: string;
    }>,
    mode: 'append' | 'replace' = 'replace',
  ): Promise<{
    total: number;
    validCount: number;
    errorCount: number;
    errors: Array<{ row: number; field: string; message: string; severity: 'error' | 'warning' }>;
    employees: Employee[];
  }> {
    const project = this.getProjectById(projectId);
    if (!project) {
      throw new Error('Project not found');
    }

    const errors: Array<{ row: number; field: string; message: string; severity: 'error' | 'warning' }> = [];
    const validatedEmployees: Employee[] = [];
    const seenIds = new Set<string>(
      mode === 'append' ? project.employees.map((e) => e.employee_id) : []
    );

    rawEmployees.forEach((emp, index) => {
      const rowNum = index + 2;
      const id = String(emp.employee_id || '').trim();
      const name = String(emp.name || '').trim();
      const dept = String(emp.department || '').trim();
      const pos = String(emp.position || '').trim();
      const email = String(emp.email || dept).trim();

      if (!id) {
        errors.push({ row: rowNum, field: 'employee_id', message: '사번(employee_id)은 필수 항목입니다.', severity: 'error' });
      }
      if (!name) {
        errors.push({ row: rowNum, field: 'name', message: '이름(name)은 필수 항목입니다.', severity: 'error' });
      }
      if (!dept) {
        errors.push({ row: rowNum, field: 'department', message: '부서(department)는 필수 항목입니다.', severity: 'error' });
      }
      if (!pos) {
        errors.push({ row: rowNum, field: 'position', message: '직급(position)은 필수 항목입니다.', severity: 'error' });
      }

      if (id) {
        if (seenIds.has(id)) {
          errors.push({ row: rowNum, field: 'employee_id', message: `중복된 사번이 감지되었습니다: ${id}`, severity: 'error' });
        } else {
          seenIds.add(id);
        }
      }

      validatedEmployees.push({
        employee_id: id || `TEMP_${rowNum}`,
        name: name || '이름 없음',
        email: email || dept,
        department: dept || '부서 없음',
        position: pos || '직급 없음',
        response_status: 'pending',
        submitted_at: null,
        sync_status: 'pending',
      });
    });

    const errorCount = errors.filter((e) => e.severity === 'error').length;

    if (errorCount === 0 && validatedEmployees.length > 0) {
      const backupEmployees = [...project.employees];
      project.employees =
        mode === 'append'
          ? [...project.employees, ...validatedEmployees]
          : validatedEmployees;

      const importPayload = project.employees.map((e) => ({
        employee_id: e.employee_id,
        name: e.name,
        department: e.department,
        position: e.position,
        email: e.email,
      }));

      try {
        await apiClient.post(`/ops/projects/${projectId}/organization/import-json`, importPayload);
        // API 연동 성공 시에만 localStorage 갱신 진행
        await this.saveProject(project);
        console.log('Successfully synced organization import to backend');
      } catch (err) {
        // API 연동 실패 시 원래의 사원 상태로 롤백
        project.employees = backupEmployees;
        console.error('Failed to sync organization import to backend', err);
        throw err;
      }
    }

    return {
      total: rawEmployees.length,
      validCount: validatedEmployees.length - errorCount,
      errorCount,
      errors,
      employees: validatedEmployees,
    };
  },

  // Submit survey responses (stateless file simulation saved to responses localStorage)
  async submitSurveyResponse(
    projectId: string,
    employeeId: string,
    answers: Array<{
      question_id: string;
      network_type: string;
      question_text: string;
      selections: Array<{
        target_employee_id: string;
        target_name: string;
        target_department: string;
        rank: number;
        strength: string;
      }>;
    }>,
    durationSeconds: number
  ): Promise<SurveyResponse> {
    const project = this.getProjectById(projectId);
    if (!project) {
      throw new Error('Project not found');
    }

    const employee = project.employees.find((e) => e.employee_id === employeeId);
    if (!employee) {
      throw new Error('Employee not registered in this project');
    }

    const responseId = `resp_${Date.now()}_${employeeId}`;
    const responsePayload: SurveyResponse = {
      schema_version: '1.0',
      company_name: project.company_info.name,
      project_id: projectId,
      response_id: responseId,
      respondent: {
        employee_id: employee.employee_id,
        name: employee.name,
        email: employee.email,
        department: employee.department,
        position: employee.position,
      },
      submitted_at: new Date().toISOString(),
      duration_seconds: durationSeconds,
      answers: answers.map((ans) => ({
        question_id: ans.question_id,
        network_type: ans.network_type,
        question_text: ans.question_text,
        selections: ans.selections,
      })),
    };

    if (typeof window === 'undefined') {
      throw new Error('Survey responses can only be submitted in the browser');
    }

    // 백엔드로 설문 제출 요청 전송
    const submitPayload = {
      respondent_id: employeeId,
      answers: answers.map((ans) => ({
        question_id: ans.question_id,
        answers: ans.selections.map((sel) => ({
          target_id: sel.target_employee_id,
          weight: sel.strength,
          rank: sel.rank,
        })),
      })),
    };

    try {
      await apiClient.post(`/survey/submit/${projectId}`, submitPayload);
      
      // API 연동 성공 시에만 localStorage 갱신 진행
      const allResponsesStored = window.localStorage.getItem(RESPONSES_STORAGE_KEY);
      let allResponses: SurveyResponse[] = [];
      if (allResponsesStored) {
        try {
          allResponses = JSON.parse(allResponsesStored);
        } catch (e) {
          console.error(e);
        }
      }

      allResponses = allResponses.filter(
        (r) => !(r.project_id === projectId && r.respondent.employee_id === employeeId)
      );
      allResponses.push(responsePayload);
      window.localStorage.setItem(RESPONSES_STORAGE_KEY, JSON.stringify(allResponses));

      employee.response_status = 'submitted';
      employee.submitted_at = responsePayload.submitted_at;
      
      // localStorage 내 프로젝트 캐시 업데이트
      const projects = this.getProjects();
      const pIdx = projects.findIndex(p => p.id === projectId);
      if (pIdx !== -1) {
        projects[pIdx] = project;
        window.localStorage.setItem(PROJECTS_STORAGE_KEY, JSON.stringify(projects));
      }

      console.log('Successfully submitted survey response to backend');
      return responsePayload;
    } catch (err) {
      console.error('Failed to submit survey response to backend', err);
      throw err;
    }
  },

  // Get raw JSON answers for project
  getProjectResponses(projectId: string): SurveyResponse[] {
    if (typeof window === "undefined") {
      return [];
    }

    const stored = window.localStorage.getItem(RESPONSES_STORAGE_KEY);
    if (!stored) return [];

    try {
      const all: SurveyResponse[] = JSON.parse(stored);
      return all.filter((r) => r.project_id === projectId);
    } catch (e) {
      console.error(e);
      return [];
    }
  },



  // CSV Generation for nodes
  exportCSVNodes(projectId: string): string {
    const project = this.getProjectById(projectId);
    if (!project) return '';

    const headers = ['employee_id', 'name', 'department', 'position', 'email'];
    const rows = project.employees.map((e) => [
      e.employee_id,
      e.name,
      e.department,
      e.position,
      e.email,
    ]);

    return [headers.join(','), ...rows.map((r) => r.map((cell) => `"${cell}"`).join(','))].join('\n');
  },

  // CSV Generation for edges (relationships)
  exportCSVEdges(projectId: string): string {
    const project = this.getProjectById(projectId);
    const responses = this.getProjectResponses(projectId);
    if (!project) return '';

    const headers = [
      'source_id',
      'source_name',
      'source_department',
      'target_id',
      'target_name',
      'target_department',
      'network_type',
      'question_id',
      'rank',
      'strength',
      'submitted_at',
    ];

    const rows: string[][] = [];

    responses.forEach((resp) => {
      resp.answers.forEach((ans) => {
        // network_type 누락 방지를 위해 project.questions 정보와 실시간 안전 매핑
        const questDetail = (project.questions || []).find(
          (q) => q.question_id === ans.question_id
        );
        const networkType = ans.network_type || questDetail?.network_type || '';

        ans.selections.forEach((sel) => {
          rows.push([
            resp.respondent.employee_id,
            resp.respondent.name,
            resp.respondent.department,
            sel.target_employee_id,
            sel.target_name,
            sel.target_department,
            networkType,
            ans.question_id,
            String(sel.rank),
            sel.strength,
            resp.submitted_at,
          ]);
        });
      });
    });

    return [headers.join(','), ...rows.map((r) => r.map((cell) => `"${cell}"`).join(','))].join('\n');
  },

  // CSV Generation for responses
  exportCSVResponses(projectId: string): string {
    const responses = this.getProjectResponses(projectId);
    const headers = [
      'response_id',
      'respondent_id',
      'respondent_name',
      'respondent_department',
      'question_id',
      'selected_id',
      'selected_name',
      'rank',
      'strength',
      'submitted_at',
    ];

    const rows: string[][] = [];

    responses.forEach((resp) => {
      resp.answers.forEach((ans) => {
        ans.selections.forEach((sel) => {
          rows.push([
            resp.response_id,
            resp.respondent.employee_id,
            resp.respondent.name,
            resp.respondent.department,
            ans.question_id,
            sel.target_employee_id,
            sel.target_name,
            String(sel.rank),
            sel.strength,
            resp.submitted_at,
          ]);
        });
      });
    });

    return [headers.join(','), ...rows.map((r) => r.map((cell) => `"${cell}"`).join(','))].join('\n');
  },

  // Zip raw JSON generator mockup
  exportRawJsonZipText(projectId: string): string {
    const responses = this.getProjectResponses(projectId);
    return JSON.stringify(responses, null, 2);
  },

  // Get response for a specific respondent in a project
  getSurveyResponse(projectId: string, employeeId: string): SurveyResponse | null {
    const responses = this.getProjectResponses(projectId);
    return responses.find((r) => r.respondent.employee_id === employeeId) || null;
  },
};