feat(est): save quantity calculation results
This commit is contained in:
@@ -28,13 +28,18 @@ def test_estx_quantity_edit_preserves_other_documents_and_indexes_when_sample_ex
|
||||
script = """const fs=require('fs'),m=require('./tools/est-test/import-estx.cjs'),e=require('./tools/est-test/export-estx.cjs');
|
||||
const bytes=fs.readFileSync(process.argv[1]),p=m.importEstx(bytes),first=p.quantitySheets[0];
|
||||
first.rows[0].LineData=first.rows[0].LineData.replace('표준','시험 표준');
|
||||
const index=first.rows.findIndex(r=>r.LineData.includes('B = 9.00'));
|
||||
if(index<0)throw Error('기준 폭 행 없음');
|
||||
first.rows[index].LineData=first.rows[index].LineData.replace('9.00','10.00');
|
||||
const out=e.exportEstx(p),q=m.importEstx(out),a=m.unzip(bytes),b=m.unzip(out);
|
||||
const unchanged=[...a].filter(([k])=>k.endsWith('.idx')||k.startsWith('cad')).every(([k,v])=>v.equals(b.get(k)));
|
||||
process.stdout.write(JSON.stringify({line:q.quantitySheets[0].rows[0].LineData,others:JSON.stringify(q.quantitySheets.slice(1))===JSON.stringify(p.quantitySheets.slice(1)),unchanged}));"""
|
||||
process.stdout.write(JSON.stringify({line:q.quantitySheets[0].rows[0].LineData,quantity:q.quantitySheets[0].items[0].GN,result:q.quantitySheets[0].rows.find(r=>r.markers.includes('r000000')).LineData,others:JSON.stringify(q.quantitySheets.slice(1))===JSON.stringify(p.quantitySheets.slice(1)),unchanged}));"""
|
||||
result = json.loads(
|
||||
subprocess.check_output(["node", "-e", script, str(sample)], cwd=ROOT).decode("utf-8")
|
||||
)
|
||||
assert "시험 표준" in result["line"]
|
||||
assert result["quantity"] == 116
|
||||
assert "\x12116\x12" in result["result"]
|
||||
assert result["others"] and result["unchanged"]
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
- **Excel `.xlsx`**: CAD를 제외한 전체 표의 스칼라 필드를 숫자·문자·불리언으로 내보냅니다. 첫 행 필드명과 시트 이름을 유지한 파일을 다시 읽어 해당 표를 교체합니다. 기존 PkID의 바이너리는 보존하며 코드 변경·중복과 미계산 수식/오류 셀을 거부합니다. 출처 단가 수정은 연결 내역에 전파합니다. 파일에 바이너리·업무 회차·당초 사본을 넣지는 않으므로 전체 백업은 JSON을 사용합니다.
|
||||
- **조달청 XML**: DB에 보관된 공사원가호환규정 XSD 1.0.5의 요소 순서와 필드를 사용합니다. 작성업체·공사구분을 입력하며 코드/문구 길이와 연결 자료를 검사합니다. 내역·일위·산근·기계·기초 단가·원가를 내보내고 다시 읽습니다. 연결 없는 고정 금액·기계 상세는 독립 단가로 전개하며 변환 전에 알립니다. 가져온 저장 금액과 원문을 보존하고 자동계산을 끕니다. 이는 제출기관 인증/등록 검사나 최신 규정 적합 판정을 뜻하지 않습니다.
|
||||
- **JDL 기본 표**: 원본 검사 DLL의 필드 정의와 EST 처리기의 TAB/ENQ·CP949 표 구조에 따라 ZIP 안의 Global.ini·Main.txt·자원/공종/내역/원가 표를 생성·읽습니다. 복잡한 일위·산근·기계는 저장 금액의 고정 단가로 전개하며 제외 행은 생략 사실을 알립니다. 원본 JDL도 보존합니다. 확장 산식·기성/물가 파일의 완전 변환과 원본 검사 DLL 인증은 미확인입니다.
|
||||
- **원본 구조 유지 ESTX 수정 저장**: 가져온 파일의 공사명·계산 옵션과 행 수 및 인덱스 키가 유지된 단가·수량·문구·금액, 기존 BLOB과 원가 서식을 기록하고 재읽기로 검산합니다. 수량산출서는 기존 서식 구간 안의 텍스트 편집을 저장하며 표지와 문서 구조는 보존합니다. 편집 문서의 계산 결과 표지와 원본 수량 목록은 자동 갱신하지 않습니다. 기존 BLOB은 공간이 부족하면 블록을 추가합니다. 원본 파일을 덮어쓰지 않으며 `.idx`와 CAD 바이너리를 보존합니다. 새 문서, 행 추가·삭제·인덱스 키 변경, 서식 구간을 가로지르는 수량산출서 편집과 목록·연결 변경, 웹 기성·연차·당초 사본은 지원하지 않아 저장을 거부합니다. 이 범위는 JSON으로 보관합니다. 원본 EST 실행 검증은 못했습니다.
|
||||
- **원본 구조 유지 ESTX 수정 저장**: 가져온 파일의 공사명·계산 옵션과 행 수 및 인덱스 키가 유지된 단가·수량·문구·금액, 기존 BLOB과 원가 서식을 기록하고 재읽기로 검산합니다. 수량산출서는 기존 서식 구간 안의 텍스트 편집을 저장하며 표지와 문서 구조는 보존합니다. 원본 결과가 기존 계산과 모두 일치하면 수정된 계산 결과 표지와 수량 목록을 함께 갱신합니다. 불일치나 계산 오류가 있으면 저장을 거부합니다. 기존 BLOB은 공간이 부족하면 블록을 추가합니다. 원본 파일을 덮어쓰지 않으며 `.idx`와 CAD 바이너리를 보존합니다. 새 문서, 행 추가·삭제·인덱스 키 변경, 서식 구간을 가로지르는 수량산출서 편집과 목록·연결 변경, 웹 기성·연차·당초 사본은 지원하지 않아 저장을 거부합니다. 이 범위는 JSON으로 보관합니다. 원본 EST 실행 검증은 못했습니다.
|
||||
- **예정공정표**: 공정별 기간·진도와 가중치를 입력하고 기간 막대 및 입력 진도의 가중평균을 표시합니다. 금액 가중치를 수정할 수 있으며 날짜 역전·잘못된 진도를 차단합니다. 공휴일/공기 산정 기준을 임의 적용하지 않습니다.
|
||||
- **공종별 동원 출력**: 한 번의 원천 계산에서 공종별 인원·자재·장비·실적·견적을 나누며 전체 합계와 금액/수량을 대조합니다. 문서 본문과 인쇄 설정도 저장·복원·취소 대상입니다.
|
||||
|
||||
|
||||
@@ -167,7 +167,7 @@ function exportEstx(project) {
|
||||
"웹 기성/연차/당초 사본은 원본 별도 업무 파일 구조가 필요합니다. JSON 저장을 사용하세요.",
|
||||
);
|
||||
if (!same(project.quantitySheets || [], base.quantitySheets || []))
|
||||
project = updateQuantities(project, base, cp949);
|
||||
project = updateQuantities(project, base, cp949, memory);
|
||||
let changed = 0;
|
||||
if (Object.keys(optionChanges).length) {
|
||||
const options = files.get("datestoption.opt");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const zlib = require("node:zlib");
|
||||
const quantity = require("./native-quantity.cjs");
|
||||
const { calculateQuantity } = require("./quantity-calculate.cjs");
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
function escapeText(text) {
|
||||
@@ -66,11 +67,12 @@ function editDocument(text, oldSheet, sheet) {
|
||||
return result;
|
||||
}
|
||||
|
||||
function updateQuantities(project, base, cp949) {
|
||||
function updateQuantities(project, base, cp949, memory) {
|
||||
const sheets = project.quantitySheets || [],
|
||||
originals = base.quantitySheets || [];
|
||||
if (sheets.length !== originals.length) throw Error("수량산출서 추가·삭제는 지원하지 않습니다.");
|
||||
const rows = project.tables.MulMainDat.map((r) => ({ ...r }));
|
||||
const savedSheets = sheets.slice();
|
||||
for (let i = 0; i < sheets.length; i++) {
|
||||
if (same(sheets[i], originals[i])) continue;
|
||||
const row = rows.find((r) => r.Code === originals[i].Code);
|
||||
@@ -84,9 +86,56 @@ function updateQuantities(project, base, cp949) {
|
||||
: packed;
|
||||
const text = new TextDecoder("euc-kr", { fatal: true }).decode(bytes);
|
||||
if (!cp949(text).equals(bytes)) throw Error("수량산출서 원본 인코딩 보존 불가");
|
||||
const output = cp949(editDocument(text, originals[i], sheets[i]));
|
||||
let document = editDocument(text, originals[i], sheets[i]);
|
||||
const baseline = calculateQuantity(originals[i]),
|
||||
calculated = calculateQuantity(sheets[i]);
|
||||
if (calculated.errors.length || baseline.errors.length)
|
||||
throw Error(`수량산출서 계산 오류: ${calculated.errors[0] || baseline.errors[0]}`);
|
||||
const markerCount = originals[i].rows.reduce((total, row) => total + row.markers.length, 0);
|
||||
if (
|
||||
baseline.checks.length !== markerCount ||
|
||||
calculated.checks.length !== markerCount ||
|
||||
baseline.checks.some((v) => !Number.isFinite(v.stored) || v.stored !== v.calculated) ||
|
||||
baseline.items.some((v, n) => v.GN !== originals[i].items[n].GN)
|
||||
)
|
||||
throw Error("수량산출서 원본 결과와 재계산 값이 다릅니다. JSON으로 저장해 확인하세요.");
|
||||
let current = structuredClone(sheets[i]);
|
||||
for (let n = 0; n < current.rows.length; n++) {
|
||||
const desired = calculated.rows[n].LineData;
|
||||
const before = [...current.rows[n].LineData.matchAll(/\x12([-\d.,]+)\x12/g)];
|
||||
const after = [...desired.matchAll(/\x12([-\d.,]+)\x12/g)];
|
||||
if (before.length !== after.length) throw Error("수량산출 결과 표지 수 불일치");
|
||||
for (let j = 0; j < after.length; j++) {
|
||||
const matches = [...current.rows[n].LineData.matchAll(/\x12([-\d.,]+)\x12/g)];
|
||||
if (matches[j][0] === after[j][0]) continue;
|
||||
const next = structuredClone(current),
|
||||
at = matches[j].index;
|
||||
next.rows[n].LineData =
|
||||
next.rows[n].LineData.slice(0, at) +
|
||||
after[j][0] +
|
||||
next.rows[n].LineData.slice(at + matches[j][0].length);
|
||||
document = editDocument(document, current, next);
|
||||
current = next;
|
||||
}
|
||||
if (current.rows[n].LineData !== desired) throw Error("수량산출 결과 재계산 검산 실패");
|
||||
}
|
||||
if (!same(row.MulList, oldRow.MulList)) throw Error("수량산출서 목록 데이터 충돌");
|
||||
if (!same(calculated.items, current.items)) {
|
||||
row.MulList = {
|
||||
binary: memory(Buffer.from(row.MulList.binary, "base64"), calculated.items).toString(
|
||||
"base64",
|
||||
),
|
||||
};
|
||||
current.items = calculated.items;
|
||||
}
|
||||
savedSheets[i] = current;
|
||||
const output = cp949(document);
|
||||
row.Editor = { binary: (compressed ? zlib.deflateSync(output) : output).toString("base64") };
|
||||
}
|
||||
return { ...project, tables: { ...project.tables, MulMainDat: rows } };
|
||||
return {
|
||||
...project,
|
||||
quantitySheets: savedSheets,
|
||||
tables: { ...project.tables, MulMainDat: rows },
|
||||
};
|
||||
}
|
||||
module.exports = { editDocument, updateQuantities };
|
||||
|
||||
@@ -128,7 +128,7 @@ const EstQuantity = (() => {
|
||||
{ esc, number, byId } = EstApp;
|
||||
byId("work-content").innerHTML =
|
||||
selector(state) +
|
||||
`<div class="business-tools"><b>${esc(sheet.Name)}</b><button data-quantity-apply>내역 수량 반영</button></div><table class="sheet"><thead><tr><th>산출코드</th><th>품명</th><th>규격</th><th>원본 저장 수량</th><th>재계산 수량</th><th>연결 내역코드</th></tr></thead><tbody>${output.items.map((item, index) => `<tr><td>${esc(item.Code)}</td><td>${esc(item.Name)}</td><td>${esc(item.Size)}</td><td>${number(sheet.items[index].GN)}</td><td>${number(item.GN)}</td><td><input data-quantity-target="${index}" value="${esc(item.TargetCode || item.LinkCode || "")}" aria-label="연결 내역코드"></td></tr>`).join("")}</tbody></table><p class="business-note">${esc(output.errors.join(" / "))} 원본 결과 표지의 이름을 유지해 수량을 연결합니다. ESTX 저장 시 편집 문서의 계산 결과와 원본 수량 목록은 자동 갱신되지 않습니다.</p><table class="sheet"><thead><tr><th>줄</th><th>산출근거 편집</th></tr></thead><tbody>${sheet.rows.map((row, index) => `<tr><td>${index + 1}</td><td><textarea data-quantity-line="${index}" rows="1" style="min-width:750px" aria-label="산출근거 ${index + 1}">${esc(EstText.display(output.rows[index].LineData))}</textarea></td></tr>`).join("")}</tbody></table>`;
|
||||
`<div class="business-tools"><b>${esc(sheet.Name)}</b><button data-quantity-apply>내역 수량 반영</button></div><table class="sheet"><thead><tr><th>산출코드</th><th>품명</th><th>규격</th><th>원본 저장 수량</th><th>재계산 수량</th><th>연결 내역코드</th></tr></thead><tbody>${output.items.map((item, index) => `<tr><td>${esc(item.Code)}</td><td>${esc(item.Name)}</td><td>${esc(item.Size)}</td><td>${number(sheet.items[index].GN)}</td><td>${number(item.GN)}</td><td><input data-quantity-target="${index}" value="${esc(item.TargetCode || item.LinkCode || "")}" aria-label="연결 내역코드"></td></tr>`).join("")}</tbody></table><p class="business-note">${esc(output.errors.join(" / "))} 원본 결과 표지의 이름을 유지해 수량을 연결합니다. ESTX 저장 시 원본 결과가 계산과 일치하면 편집 결과와 수량 목록을 갱신합니다.</p><table class="sheet"><thead><tr><th>줄</th><th>산출근거 편집</th></tr></thead><tbody>${sheet.rows.map((row, index) => `<tr><td>${index + 1}</td><td><textarea data-quantity-line="${index}" rows="1" style="min-width:750px" aria-label="산출근거 ${index + 1}">${esc(EstText.display(output.rows[index].LineData))}</textarea></td></tr>`).join("")}</tbody></table>`;
|
||||
}
|
||||
function install() {
|
||||
document.addEventListener("change", (event) => {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
// The same calculation code used by the browser, isolated from server globals.
|
||||
const engine = vm.createContext({ structuredClone });
|
||||
for (const name of ["native-math.js", "native-formula.js", "native-text.js", "native-quantity.cjs"])
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, name), "utf8"), engine, { filename: name });
|
||||
|
||||
function calculateQuantity(sheet) {
|
||||
engine.sheet = sheet;
|
||||
try {
|
||||
return vm.runInContext("EstQuantity.calculate(sheet)", engine, { timeout: 20000 });
|
||||
} finally {
|
||||
delete engine.sheet;
|
||||
}
|
||||
}
|
||||
module.exports = { calculateQuantity };
|
||||
Reference in New Issue
Block a user