// 파일3개 방식: 원장 파일에서 마지막에 한 번 실행. function main(workbook: ExcelScript.Workbook, payloadJson: string, snapshotStartUtc: string, runId: string): string { const batches: Batch[] = JSON.parse(payloadJson); return writeSnapshot(workbook, batches, snapshotStartUtc, runId); } type Cell = string | number | boolean; interface Batch { owner: string; rows: Cell[][]; } const OWNERS = ["P01", "P02", "P03"]; const HEADERS = ["업무ID", "기준일", "담당자코드", "업무명", "금액"]; // 이 예제의 설계 한도입니다. Microsoft 제품 한도를 뜻하지 않습니다. const PER_SOURCE_LIMIT = 500; const TOTAL_LIMIT = 1500; function validateRows(rows: Cell[][], owner: string): Cell[][] { if (OWNERS.indexOf(owner) < 0) throw new Error("미등록 담당자: " + owner); if (!Array.isArray(rows) || rows.length > PER_SOURCE_LIMIT) throw new Error("원본 행 수/구조 확인: " + owner); const seen: string[] = []; const output: Cell[][] = []; for (const row of rows) { if (!Array.isArray(row) || row.length !== HEADERS.length) throw new Error("열 개수 오류: " + owner); if (row.every(v => v === "")) continue; if (typeof row[0] !== "string" || !new RegExp("^" + owner + "-[0-9]{4}$").test(row[0])) throw new Error("업무ID는 " + owner + "-0001 형식이어야 합니다."); if (seen.indexOf(row[0]) >= 0) throw new Error("중복 업무ID: " + row[0]); seen.push(row[0]); // 날짜는 Excel 일련번호가 아닌, 텍스트 YYYY-MM-DD로 통일합니다. if (typeof row[1] !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(row[1])) throw new Error("기준일 텍스트 형식 오류: " + row[0]); const parsed = new Date(row[1] + "T00:00:00Z"); if (isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== row[1]) throw new Error("존재하지 않는 날짜: " + row[0]); if (row[2] !== owner) throw new Error("담당자코드 불일치: " + row[0]); if (typeof row[3] !== "string" || !row[3].trim() || row[3].length > 200 || /^[=+@\-\t\r]/.test(row[3].trim())) throw new Error("업무명 확인: " + row[0]); if (typeof row[4] !== "number" || !Number.isSafeInteger(row[4]) || Math.abs(row[4]) > 1000000000) throw new Error("금액은 절댓값10억 이하 정수: " + row[0]); output.push([row[0], row[1], row[2], row[3].trim(), row[4]]); } return output; } function readInput(workbook: ExcelScript.Workbook, name: string, owner: string, expectedSheet: string): Batch { const table = workbook.getTable(name); if (!table) throw new Error("입력 표 없음: " + name); if (table.getWorksheet().getName() !== expectedSheet) throw new Error("입력 시트가 다릅니다: " + name); const headers = table.getHeaderRowRange().getValues()[0]; if (JSON.stringify(headers) !== JSON.stringify(HEADERS)) throw new Error("머리글/열 순서 불일치: " + name); if (table.getRowCount() > PER_SOURCE_LIMIT) throw new Error("원본 표500행 초과: " + name); const values: Cell[][] = table.getRowCount() ? table.getRangeBetweenHeaderAndTotal().getValues() : []; return {owner, rows: validateRows(values, owner)}; } function validateBatches(batches: Batch[]): Batch[] { if (!Array.isArray(batches) || batches.length !== OWNERS.length) throw new Error("담당자3개 결과가 모두 필요합니다."); const found: string[] = []; const sorted: Batch[] = []; for (const batch of batches) { if (!batch || typeof batch.owner !== "string" || found.indexOf(batch.owner) >= 0) throw new Error("담당자 누락/중복"); found.push(batch.owner); sorted.push({owner: batch.owner, rows: validateRows(batch.rows, batch.owner)}); } for (const owner of OWNERS) if (found.indexOf(owner) < 0) throw new Error("담당자 누락: " + owner); sorted.sort((a,b) => a.owner.localeCompare(b.owner)); for (const batch of sorted) batch.rows.sort((a,b) => String(a[0]).localeCompare(String(b[0]))); const total = sorted.reduce((sum,b) => sum + b.rows.length,0); if (total === 0) throw new Error("3명 모두0건: 기존 원장 삭제 전 원본 확인이 필요합니다."); if (total > TOTAL_LIMIT) throw new Error("원장1500행 초과"); return sorted; } function writeSnapshot(workbook: ExcelScript.Workbook, batches: Batch[], snapshotStartUtc: string, runId: string): string { const checked = validateBatches(batches); if (!/^[A-Za-z0-9_-]{1,128}$/.test(runId) || !/^\d{4}-\d{2}-\d{2}T/.test(snapshotStartUtc) || !snapshotStartUtc.endsWith("Z") || isNaN(Date.parse(snapshotStartUtc))) throw new Error("실행ID/수집시작UTC 확인"); const sheet = workbook.getWorksheet("원장"); if (!sheet) throw new Error("전용 원장 시트를 먼저 만드세요."); // A1:E1501, G1:H7은 이 스크립트 전용입니다. 표/병합/수동 데이터 금지. if (sheet.getTables().length) throw new Error("원장 시트는 표가 없는 일반 셀이어야 합니다."); const previousStart = String(sheet.getRange("H3").getValue()); if (previousStart && Date.parse(previousStart) > Date.parse(snapshotStartUtc)) throw new Error("더 오래된 실행의 덮어쓰기 차단"); const rows: Cell[][] = []; for (const batch of checked) for (const row of batch.rows) rows.push(row); const amountTotal = rows.reduce((sum,row) => sum + Number(row[4]),0); const output: Cell[][] = [HEADERS.slice(), ...rows]; while (output.length < TOTAL_LIMIT + 1) output.push(["","","","",""]); // 성공 표시를 먼저 해제. 이 단계 이후 오류면 상태와 실행 이력 확인 필요. sheet.getRange("G1:H1").setValues([["상태", "갱신 중/미완료"]]); sheet.getRange("A1:D1501").setNumberFormat("@"); sheet.getRange("E2:E1501").setNumberFormat("0"); sheet.getRange("H2:H4").setNumberFormat("@"); sheet.getRange("A1:E1501").setValues(output); const actual = sheet.getRangeByIndexes(0,0,rows.length+1,HEADERS.length).getValues(); if (JSON.stringify(actual) !== JSON.stringify([HEADERS,...rows])) throw new Error("쓰기 후 원장 대조 실패"); const successUtc = new Date().toISOString(); sheet.getRange("G2:H7").setValues([ ["마지막 성공UTC",successUtc], ["수집 시작UTC",snapshotStartUtc], ["실행ID",runId], ["행수",rows.length], ["금액합계",amountTotal], ["담당자별 행수",checked.map(b => b.owner + ":" + b.rows.length).join(" / ")] ]); // 마지막 성공 표시도 별도 작업입니다. 데이터베이스 트랜잭션이 아닙니다. sheet.getRange("H1").setValue("성공"); return JSON.stringify({runId,snapshotStartUtc,successUtc,rowCount:rows.length,amountTotal,owners:checked.map(b=>({owner:b.owner,rowCount:b.rows.length}))}); }