@operato/ops-contract 0.9.36 → 0.9.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -50,6 +50,7 @@ __export(index_exports, {
50
50
  ERP_MASTER_AXIS: () => ERP_MASTER_AXIS,
51
51
  FIRST_PASS_RULE: () => FIRST_PASS_RULE,
52
52
  GUARD_PRAGMA: () => GUARD_PRAGMA,
53
+ HATIOLAB_VOCABULARY: () => HATIOLAB_VOCABULARY,
53
54
  ILMD_ATTR: () => ILMD_ATTR,
54
55
  LOCATION_SATURATION_NEAR: () => LOCATION_SATURATION_NEAR,
55
56
  MATERIAL_ACTUAL_USE: () => MATERIAL_ACTUAL_USE,
@@ -67,8 +68,10 @@ __export(index_exports, {
67
68
  OP_EVENT: () => OP_EVENT,
68
69
  OP_PARAM: () => OP_PARAM,
69
70
  ORDER_FOLD_DEFAULT: () => ORDER_FOLD_DEFAULT,
71
+ ORDER_FOLD_HOUR_MS: () => ORDER_FOLD_HOUR_MS,
70
72
  ORDER_TERMINAL_STATUS: () => ORDER_TERMINAL_STATUS,
71
73
  PRIORITY_UNSET: () => PRIORITY_UNSET,
74
+ PRIVATE_BIZSTEP: () => PRIVATE_BIZSTEP,
72
75
  READ_BASIS: () => READ_BASIS,
73
76
  REFUSED_WITHOUT_CODE: () => REFUSED_WITHOUT_CODE,
74
77
  RESOURCE_KIND: () => RESOURCE_KIND,
@@ -93,6 +96,7 @@ __export(index_exports, {
93
96
  WMS_RECEIVING_ORDER_KINDS: () => WMS_RECEIVING_ORDER_KINDS,
94
97
  WMS_TYPES: () => WMS_TYPES,
95
98
  YARD_BIZSTEP: () => YARD_BIZSTEP,
99
+ YARD_PRIVATE_BIZSTEP: () => YARD_PRIVATE_BIZSTEP,
96
100
  YMS_LOCATION_TYPES: () => YMS_LOCATION_TYPES,
97
101
  YMS_TYPES: () => YMS_TYPES,
98
102
  acceptsPerformance: () => acceptsPerformance,
@@ -107,6 +111,7 @@ __export(index_exports, {
107
111
  axisAppliesTo: () => axisAppliesTo,
108
112
  axisInfo: () => axisInfo,
109
113
  axisSource: () => axisSource,
114
+ bizStepName: () => bizStepName,
110
115
  bizTransactionUri: () => bizTransactionUri,
111
116
  canPreview: () => canPreview,
112
117
  capabilitiesForType: () => capabilitiesForType,
@@ -134,6 +139,8 @@ __export(index_exports, {
134
139
  equipmentClassMembership: () => equipmentClassMembership,
135
140
  erpCapabilityGaps: () => erpCapabilityGaps,
136
141
  expiryFromAttributes: () => expiryFromAttributes,
142
+ finishedFlowOrdersWithin: () => finishedFlowOrdersWithin,
143
+ finishedWindowStartMs: () => finishedWindowStartMs,
137
144
  foldOrdersInto: () => foldOrdersInto,
138
145
  foldedOrderCount: () => foldedOrderCount,
139
146
  gdtiUri: () => gdtiUri,
@@ -142,6 +149,7 @@ __export(index_exports, {
142
149
  gs1KeyDigitViolation: () => gs1KeyDigitViolation,
143
150
  hierarchyOf: () => hierarchyOf,
144
151
  homeOf: () => homeOf,
152
+ hourStartOf: () => hourStartOf,
145
153
  identityGroundingOf: () => identityGroundingOf,
146
154
  inWorkCalendar: () => inWorkCalendar,
147
155
  inWorkCalendarAt: () => inWorkCalendarAt,
@@ -226,6 +234,7 @@ __export(index_exports, {
226
234
  priorityRank: () => priorityRank,
227
235
  procedureViolations: () => procedureViolations,
228
236
  propertiesOf: () => propertiesOf,
237
+ pruneFoldedHours: () => pruneFoldedHours,
229
238
  quantityIn: () => quantityIn,
230
239
  ratedUsageOf: () => ratedUsageOf,
231
240
  readBoardAssets: () => readBoardAssets,
@@ -1338,7 +1347,26 @@ var BIZSTEP = {
1338
1347
  packing: "urn:epcglobal:cbv:bizstep:packing",
1339
1348
  staging_outbound: "urn:epcglobal:cbv:bizstep:staging_outbound",
1340
1349
  shipping: "urn:epcglobal:cbv:bizstep:shipping",
1341
- replenishing: "urn:epcglobal:cbv:bizstep:replenishing"
1350
+ /**
1351
+ * **Replenishment** — moving goods to where they are picked from. CBV has no `replenishing`; this contract
1352
+ * wrote one until 2026-09-24, and the closed-list test found it. CBV `stocking` is the step that means it:
1353
+ * "…within a location to make an object available to the customer or for order fulfilment within a DC"
1354
+ * (CBV ontology, `BizStep-stocking`). Ruled by the chief architect; no reader branches on the value, and
1355
+ * the journal keeps what it already wrote (ADR-0038).
1356
+ */
1357
+ stocking: "urn:epcglobal:cbv:bizstep:stocking",
1358
+ /**
1359
+ * **Counted, and the book set to the count** — CBV `cycle_counting`. Primary source: the CBV ontology
1360
+ * (gs1/EPCIS `Ontology/CBV.ttl`, `cbv:BizStep-cycle_counting`, also served at ref.gs1.org/cbv): "Process of
1361
+ * counting objects within a location in order to obtain an accurate inventory for business needs other
1362
+ * than accounting purposes (e.g., replenishment and allocation)."
1363
+ *
1364
+ * **Only for an event somebody actually counted** (chief architect, 2026-09-24). A person correcting the
1365
+ * book without counting is `CBV_BIZSTEP.other` with the reason carried as a value — `epcis.ts` says why:
1366
+ * writing that as `cycle_counting` records a count that never happened. A count for the accounts is a
1367
+ * different CBV step (`stock_taking`) and is not this one.
1368
+ */
1369
+ cycle_counting: "urn:epcglobal:cbv:bizstep:cycle_counting"
1342
1370
  };
1343
1371
  var BTT = {
1344
1372
  /** Purchase Order — the document an inbound receipt is made against. */
@@ -1405,1957 +1433,1984 @@ var WMS_TYPES = [
1405
1433
  { key: "packer", role: "equipment", label: "twin.type.packer", standardClass: { epcis: "object", isa95: "Equipment" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] }
1406
1434
  ];
1407
1435
 
1408
- // src/yms-profile.ts
1409
- var YARD_BIZSTEP = {
1410
- arriving: "urn:epcglobal:cbv:bizstep:arriving",
1411
- // 게이트-인
1412
- staging: "urn:epcglobal:cbv:bizstep:staging",
1413
- // 야드 슬롯 주차·대기
1414
- loading: "urn:epcglobal:cbv:bizstep:loading",
1415
- // 도크 작업(상차: 트레일러←화물)
1416
- unloading: "urn:epcglobal:cbv:bizstep:unloading",
1417
- // 도크 작업(하차: 트레일러→화물)
1418
- departing: "urn:epcglobal:cbv:bizstep:departing"
1419
- // 게이트-아웃
1420
- };
1421
- function graiUri(companyPrefix, assetType, serial) {
1422
- return `urn:epc:id:grai:${companyPrefix}.${assetType}.${String(serial).padStart(6, "0")}`;
1423
- }
1424
- var YMS_LOCATION_TYPES = ["gate", "yard-slot", "dock-door", "staging"];
1425
- var YMS_LOCATION_LEVEL = {
1426
- gate: "Other",
1427
- "yard-slot": "StorageUnit",
1428
- "dock-door": "StorageUnit",
1429
- staging: "StorageZone"
1430
- };
1431
- var YMS_TYPES = [
1432
- ...YMS_LOCATION_TYPES.map((k) => ({ key: k, role: "location", label: `twin.type.${k}`, standardClass: { epcis: "bizLocation" }, identity: { scheme: "gs1:SGLN" }, level: YMS_LOCATION_LEVEL[k], capabilities: ["storable"] })),
1433
- { key: "hostler", role: "equipment", label: "twin.type.hostler", standardClass: { epcis: "object", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["mobile", "operable"] }
1434
- ];
1435
-
1436
- // src/mes-profile.ts
1437
- var MES_BIZSTEP = {
1438
- receiving: "urn:epcglobal:cbv:bizstep:receiving",
1439
- // 원자재 수령
1440
- producing: "urn:epcglobal:cbv:bizstep:commissioning",
1441
- // 생산(제품 최초 생성)
1442
- storing: "urn:epcglobal:cbv:bizstep:storing"
1443
- // 완제품 저장
1444
- };
1445
- var BTT_PRODORDER = "urn:epcglobal:cbv:btt:prodorder";
1446
- function sgtinUri(companyPrefix, itemRef, serial) {
1447
- return `urn:epc:id:sgtin:${companyPrefix}.${itemRef}.${serial}`;
1448
- }
1449
- var MES_LOCATION_TYPES = ["raw-store", "cut-station", "weld-station", "paint-booth", "assembly-line", "fg-store"];
1450
- var MES_LOCATION_CLS = {
1451
- "raw-store": { epcis: "bizLocation" },
1452
- "cut-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1453
- "weld-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1454
- "paint-booth": { isa95: "WorkCenter", epcis: "bizLocation" },
1455
- "assembly-line": { isa95: "WorkCenter", epcis: "bizLocation" },
1456
- "fg-store": { epcis: "bizLocation" }
1457
- };
1458
- var MES_LOCATION_LEVEL = {
1459
- "raw-store": "StorageZone",
1460
- "cut-station": "WorkCell",
1461
- "weld-station": "WorkCell",
1462
- "paint-booth": "WorkCell",
1463
- "assembly-line": "ProductionLine",
1464
- "fg-store": "StorageZone"
1465
- };
1466
- var MES_TYPES = [
1467
- ...MES_LOCATION_TYPES.map((k) => ({ key: k, role: "location", label: `twin.type.${k}`, standardClass: MES_LOCATION_CLS[k] ?? {}, identity: { scheme: "gs1:SGLN" }, level: MES_LOCATION_LEVEL[k], capabilities: ["storable"] })),
1468
- { key: "cutter", role: "equipment", label: "twin.type.cutter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1469
- { key: "welder", role: "equipment", label: "twin.type.welder", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1470
- { key: "painter", role: "equipment", label: "twin.type.painter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1471
- { key: "assembler", role: "equipment", label: "twin.type.assembler", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] }
1472
- ];
1473
- var MES_COMMANDS = [
1474
- {
1475
- type: "production.order",
1476
- label: "\uC0DD\uC0B0 \uC9C0\uC2DC",
1477
- /*
1478
- * 되돌릴 수 없다. 지시가 나가면 사람과 설비가 그것으로 움직이고, 취소해도 이미 만든 것은 남는다.
1479
- * 그래서 사람 승인을 지난다(§`requiresApproval`).
1480
- */
1481
- reversible: false,
1482
- /*
1483
- * 단위를 요구하는 이유 — 단위 없는 수량은 지시가 되지 못한다. 우리가 기본 단위를 지어내면 그것이
1484
- * 현장의 단위와 다른 날 수량이 조용히 틀린다.
1485
- */
1486
- required: ["materialDefinitionId", "quantity", "uom"]
1487
- }
1488
- ];
1489
-
1490
- // src/ems-profile.ts
1491
- var EMS_LOCATION_TYPES = ["incoming", "feeder", "submeter-zone"];
1492
- var METER_DIRECTION = ["import", "export", "bidirectional"];
1493
- var EMS_EQUIPMENT_TYPES = ["meter", "breaker", "pv-array", "battery", "utility", "curtailable-load"];
1494
- var EMS_PROPERTY = {
1495
- /** 계약전력(kW) — 수전·분기 자리에 선언한다. 없으면 계약 대비 판정을 하지 않는다. */
1496
- contractKW: "contract.kW",
1497
- /*
1498
- * ── 계량 지점의 방향 (2026-08-25) ──────────────────────────────────────────
1499
- * **요금은 계통 접속점의 순 유입에 매겨진다.** 그러니 그 지점의 계량기가 무엇을 재는지 모르면
1500
- * 요금을 사실대로 말할 수 없다 — 내보낸 양을 쓴 양으로 세면 계약 대비 판단이 반대로 뒤집힌다.
1436
+ // src/epcis.ts
1437
+ var EPCIS_CONTEXT = "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld";
1438
+ var UTC_OFFSET = "+00:00";
1439
+ var DISP = {
1440
+ in_progress: "urn:epcglobal:cbv:disp:in_progress",
1441
+ sellable: "urn:epcglobal:cbv:disp:sellable_accessible",
1442
+ reserved: "urn:epcglobal:cbv:disp:reserved",
1443
+ in_transit: "urn:epcglobal:cbv:disp:in_transit",
1444
+ non_sellable: "urn:epcglobal:cbv:disp:non_sellable_other",
1445
+ // 불량/scrap
1446
+ /**
1447
+ * **기한이 지났다** — CBV `expired`.
1501
1448
  *
1502
- * 이 축이 없는 동안 계량 지점의 kW 를 전부 부하로 셌다. 상계 거래를 하는 현장, 축전지를 붙인 현장,
1503
- * 열병합이 있는 현장 — 접속점 계량기가 양쪽을 재는 곳은 늘 있다.
1449
+ * ── 왜 `non_sellable` 로 계산하지 않나 (2026-08-24) ─────────────────────────────
1450
+ * 커널의 `non_sellable` 은 CBV 의 `non_sellable_other`, 즉 **「그 밖의 이유」**다. 기한 지남을 거기
1451
+ * 넣으면 「기한이 지나 못 판다」와 「깨져서 못 판다」가 같은 값이 되고, 화면은 회수·폐기의 사유를
1452
+ * 구별할 수 없다. 식품에서 그 둘은 다른 조치다.
1504
1453
  *
1505
- * **발전기를 계량기로 만드는 것과 다른 일이다.** 발전은 설비의 사실이고(`energyGenerating`), 그것을
1506
- * 계량 지점으로 보내는 것은 여전히 하지 않는다. 이 축은 **접속점 계량기**가 무엇을 재는지 말하는
1507
- * 자리다.
1454
+ * 그리고 표준에 **정확한 낱말이 있다** — 합치는 것은 있는 낱말을 버리는 것이다.
1508
1455
  *
1509
- * 방향은 **관측이 아니라 선언**이다. 표본마다 바뀌는 값이 아니고, 그 계량기가 무엇을 재도록
1510
- * 설치되었는지는 현장이 안다. 그래서 표본(`EnergyRecord`)에 넣지 않고 자원 속성으로 둔다.
1456
+ * ── 기한 날짜와 다른 축이다 ────────────────────────────────────────────────
1457
+ * `ItemState.expiry` 는 **날짜**이고 이것은 **상태**다. 날짜가 있으면 「지났나」는 파생이지만, 원본이
1458
+ * 「기한 지남」을 상태로 선언하는 시스템이 있다 — 그때 이 값은 관측이다.
1511
1459
  *
1512
- * 값은 계량기 자신의 낱말을 쓴다(적산 레지스터가 그렇게 갈려 있다). §`METER_DIRECTION`.
1513
- */
1514
- meterDirection: "meter.direction",
1515
- /*
1516
- * ── 부하 계수 — 시뮬레이션이 전기를 만들 수 있게 (2026-08-14) ───────────────
1517
- * 「이 설비가 돌면 몇 kW 인가」는 **현장이 아는 값**이다. 그래서 타입 기본값을 두지 않는다:
1518
- * 선언하지 않은 설비는 부하를 만들지 않는다. 기본값을 두면 아무도 그 수가 짐작인 줄 모른 채
1519
- * 요금 판정이 그 위에 선다.
1520
- */
1521
- /** 가동 중 소비(kW). */
1522
- ratedKW: "power.ratedKW",
1523
- /** 멈춰 있을 때의 소비(kW). 없으면 멈춘 동안을 **비운다** — 0 이라고 주장하지 않는다. */
1524
- standbyKW: "power.standbyKW",
1525
- /*
1526
- * ── 요금 단가 — 수를 금액으로 바꾸는 선언 (2026-08-17) ─────────────────────
1460
+ * 둘이 어긋나면(날짜는 남았는데 상태가 지남, 또는 그 반대) **어느 쪽이 맞다고 정하지 않는다** —
1461
+ * 아직 그 판정을 세울 근거가 없다. 어긋남의 구분을 없애지 않는 것이 지금의 규율이다.
1527
1462
  *
1528
- * 그동안 트윈은 「최대수요 328kW」·「전력량 1,547kWh」까지 말하고 멈췄다. 그런데 피크를 깎는 일이
1529
- * 돈이 되는 이유는 **요금이 둘로 나뉘기** 때문이다: 사용량(kWh)에 붙는 요금과 **최대수요(kW)에 붙는
1530
- * 기본요금**. 단가가 없으면 그 절반을 말할 수 없고, 그래서 「피크를 깎아 얼마를 아끼나」에 답하지 못했다.
1463
+ * ── 원문으로 확인했다 (2026-08-24) ────────────────────────────────────────
1464
+ * 1차 출처: **CBV Standard Release 2.0, Ratified Jun 2022** §7.2.3 처분 값 표(38개). 이 객체의
1465
+ * 다른 값들(`in_progress`·`sellable_accessible`·`reserved`·`in_transit`·`non_sellable_other`)도
1466
+ * 그 표에 있다.
1531
1467
  *
1532
- * 단가는 **현장의 계약**이다(같은 나라 안에서도 사업자·요금제마다 다르다). 그래서 기본값을 두지
1533
- * 않는다 — 선언하지 않으면 금액을 계산하지 않는다. 짐작한 단가로 낸 금액은 숫자가 있다는 것만으로
1534
- * 사람을 결정으로 밀어붙인다.
1468
+ * **`non_sellable_expired` 를 쓰지 않는 이유**: 그 값은 CBV 1.0 의 것이고 표준이 **폐기**했다 —
1469
+ * 「deprecated in favour of new disposition values expired, damaged, disposed, … introduced in
1470
+ * CBV 1.1」. 폐기된 값을 쓰면 새 소비처가 읽지 못한다.
1535
1471
  *
1536
- * 계약전력(`contract.kW`)과 같은 자리(수전)에 선언한다.
1472
+ * 참고: GS1 어휘 등록처(`ref.gs1.org/cbv/…`)로는 확인할 수 없었다 — **없는 값에도 같은 응답**을
1473
+ * 준다(지어낸 값의 JSON-LD 가 실재 값과 바이트까지 같았다). 그 경로를 근거로 삼지 말 것.
1537
1474
  */
1538
- /** 기본요금 단가 — 최대수요 1kW 당(청구 주기 기준). */
1539
- demandChargePerKW: "tariff.demandChargePerKW",
1475
+ expired: "urn:epcglobal:cbv:disp:expired",
1540
1476
  /**
1541
- * **요금적용전력**(kW) — 기본요금이 실제로 매겨지는 기준. 계약전력과 다른 값이다.
1542
- *
1543
- * 기본요금이 걸리는 수는 이 주기에 잰 최대가 아닌 경우가 많다 — 지난 몇 달의 최고를 끌고 가거나,
1544
- * 약정 용량으로 매기거나, 사업자가 따로 정한다. 그 규칙은 나라와 계약마다 다르므로 커널이 계산하지
1545
- * 않고 **계산된 결과를 받는다.** 이 값이 있으면 기본요금이 조건부 파생이 아니라 사실이 된다.
1546
- *
1547
- * 계약전력(`contract.kW`)을 이 자리에 넣지 말 것. 넘었을 때의 뜻이 다르다 — 계약 초과는 약정
1548
- * 위반이고, 이쪽은 다음 주기의 기본요금이 오른다는 뜻이다.
1549
- */
1550
- billingDemandKW: "tariff.billingDemandKW",
1551
- /** 사용량 단가 — 1kWh 당. */
1552
- energyChargePerKWh: "tariff.energyChargePerKWh",
1553
- /** 통화 — ISO 4217 코드(USD·KRW…). 없으면 금액에 단위를 붙이지 않는다. */
1554
- currency: "tariff.currency",
1555
- /*
1556
- * ── 축전지의 용량과 방전 정책 (2026-08-17) ─────────────────────────────────
1557
- *
1558
- * 「배터리로 피크를 깎는다」를 시뮬이 보이려면 방전을 만들어야 하고, 그것은 **선언에서** 나와야 한다.
1559
- * 임계·최대율·예비를 우리가 정하면 그 수가 어디서 왔는지 아무도 설명할 수 없다.
1560
- *
1561
- * ── 선언한다는 것은 「그 자동화가 있다」는 주장이다 ─────────────────────────
1562
- * 이 정책을 모델에 적으면 **라이브가 아닌 모든 구동이 그 규칙으로 돈다.** 현장에 BESS 제어기가 없는데
1563
- * 적으면 파생 부하가 실제보다 낙관적으로 나온다(피크가 깎인 것으로 보인다). 그러니 「도입하면?」을
1564
- * 묻는 것이라면 선언이 아니라 **what-if 가 덮어쓸 일**이다.
1565
- *
1566
- * 용량이 없으면 방전하지 않는다 — 용량을 모르면 「얼마나 버티나」를 답할 수 없고, 버티는 시간을
1567
- * 모른 채 깎으면 무한히 깎을 수 있다고 주장하는 셈이다.
1477
+ * **폐기됐다 — 남은 것이 없다.** CBV `destroyed` (CBV ontology, `Disp-destroyed`), with the step
1478
+ * `CBV_BIZSTEP.destroying`. Ruled 2026-09-24, shape from plant: the disposition belongs to the quantity
1479
+ * **observed**, which is what is left. A partial scrap leaves the rest `in_progress`; only the last of it —
1480
+ * nothing left — is `destroyed`. Putting it on a remainder would say sound goods were thrown away.
1568
1481
  */
1569
- /** 축전지 용량(kWh) — SOC 를 에너지로 바꾸는 값. 없으면 방전을 만들지 않는다. */
1570
- capacityKWh: "storage.capacityKWh",
1571
- /** 이 순수요를 넘으면 방전한다(kW) — 피크 억제 임계. */
1572
- dischargeAboveKW: "dispatch.dischargeAboveKW",
1573
- /** 최대 방전율(kW) — 인버터가 낼 수 있는 한계. */
1574
- maxDischargeKW: "dispatch.maxDischargeKW",
1575
- /** 예비 SOC(%) — 이 아래로는 쓰지 않는다(비상 대비). 없으면 0 으로 본다. */
1576
- reserveSoc: "dispatch.reserveSoc",
1482
+ destroyed: "urn:epcglobal:cbv:disp:destroyed",
1577
1483
  /**
1578
- * 시뮬레이션이 **출발할 때의 SOC(%)** — 씨앗값이다.
1484
+ * **검사에 합격했다 / 불합격했다** — CBV `conformant` / `non_conformant`.
1579
1485
  *
1580
- * 계측이 SOC 를 알려 주는 트윈에는 필요 없다(잰 값이 진실이다). 시뮬 트윈에는 알려 줄 것이 없어서
1581
- * 「SOC 를 모르면 방전하지 않는다」는 규율에 걸려 **배터리가 아무 일도 하지 못했다** — 정책을 선언해도
1582
- * 피크가 한 톨도 깎이지 않았다(실화면에서 그렇게 났다).
1486
+ * 1차 출처(CBV 2.0 §7.2.3) 정의 그대로다.
1583
1487
  *
1584
- * 이것은 상태의 씨앗이지 계측이 아니다. 그래서 계측이 들어오는 순간 그것이 이긴다.
1585
- */
1586
- initialSoc: "storage.initialSoc",
1587
- /*
1588
- * ── 발전 — 태양광이 서 있기만 하던 자리 (2026-08-18) ────────────────────────
1488
+ * conformant Outcome of a successful/passed inspection in an inspecting or repairing step
1489
+ * non_conformant Outcome of an unsuccessful/failed inspection in an inspecting or repairing step
1589
1490
  *
1590
- * 계통도에 태양광을 그려 놓고 시뮬에서는 한 톨도 만들지 못했다. 미러는 원천이 발전량을 보내 주지만,
1591
- * 시뮬 트윈에는 그것을 만들 근거가 없었다 — 그래서 「태양광을 늘리면 피크가 얼마나 내려가나」를 물을 수
1592
- * 없었다(what-if 의 값이 절반만 성립했다).
1491
+ * ── 왜 시험 결과 축을 자원에 더하지 않고 이것을 쓰나 (2026-08-24) ────────────
1492
+ * 로트의 검사 판정을 담을 자리를 찾다가 `ItemState.testResults` 를 더하려 했다. 그런데 표준은 그
1493
+ * 사실을 **이미 처분으로 말한다**: `bizStep: inspecting` 사건에 이 처분이 붙는다.
1593
1494
  *
1594
- * **형상을 우리가 지어내지 않는다.** 위도·계절·날씨로 곡선을 만들면 그 수가 어디서 왔는지 아무도
1595
- * 설명할 수 없고, 흐린 날 현장의 실적과 어긋난다. 그래서 현장이 **하루 형상을 적는다**: 24개 비율
1596
- * (0~1)이면 그것이 그 현장의 곡선이다(측정한 형상을 그대로 붙일 수 있다).
1495
+ * 처분을 쓰면 두 가지가 공짜로 성립한다.
1496
+ * ① **상태 ⊆ 이벤트** — 처분은 이미 사건에서 온다. 상태에만 있는 축을 만들지 않는다
1497
+ * ② **운영에 곧 닿는다** — 「이 자재를 쓸 수 있나」가 처분으로 답해진다(판정을 따로 읽지 않는다)
1597
1498
  *
1598
- * 정격만 있고 형상이 없으면 발전하지 않는다 — 하루 종일 정격으로 발전하는 태양광은 없다.
1499
+ * 시험의 **자세한 내용**(어느 명세로, 무엇을 재어)은 다른 물음이고, 표준은 그것을 `TestResult` 로
1500
+ * 두며 결과가 대상을 가리킨다(`TestableObjectID`) — 대상이 결과를 들지 않는다. 그 축이 필요해지면
1501
+ * 그때 열되, **판정 자체는 여기서 끝난다.**
1599
1502
  */
1503
+ conformant: "urn:epcglobal:cbv:disp:conformant",
1504
+ non_conformant: "urn:epcglobal:cbv:disp:non_conformant"
1505
+ };
1506
+ var HATIOLAB_VOCABULARY = "https://hatiolab.com/voc/";
1507
+ var PRIVATE_BIZSTEP = {
1508
+ /** 공정에 자재가 들어갔다 — ISA-95 `MaterialUse: Consumed`. */
1509
+ consuming: `${HATIOLAB_VOCABULARY}bizstep/consuming`
1510
+ };
1511
+ function bizStepName(uri) {
1512
+ const s = String(uri ?? "").trim();
1513
+ if (!s) return void 0;
1514
+ const name = s.slice(Math.max(s.lastIndexOf(":"), s.lastIndexOf("/")) + 1);
1515
+ return name || void 0;
1516
+ }
1517
+ var CBV_BIZSTEP = {
1518
+ /* 소비(`consuming`)는 CBV 에 없어 `PRIVATE_BIZSTEP` 으로 갔다(2026-09-24). */
1600
1519
  /**
1601
- * 발전 정격(kW) — **교류 쪽 최대 출력**. 계통으로 나가는 값이다.
1602
- *
1603
- * 이용률의 분모가 이 값이다(만든 양 ÷ 정격 × 시간). **직류 쪽 정격(§`genRatedKWdc`)과 다르고 더 작다** —
1604
- * 두 값을 한 이름에 담으면 이용률이 그 차이만큼 틀리고, 틀린 이유가 아무 데도 표시되지 않는다.
1605
- *
1606
- * 설비마다 선언하거나, 설비별 값을 모르는 현장은 **자리(수전)에 합계로** 선언한다.
1520
+ * **폐기 — 물건이 끝났다.** CBV `destroying`: "Process of terminating an object. For an instance-level
1521
+ * identifier, the object should not be the subject of subsequent events" (CBV ontology, `BizStep-destroying`).
1522
+ * Ruled 2026-09-24 (chief architect) — plant wrote scrapping as `other`; the warehouse's disposal door uses the
1523
+ * same step. Not a count, and not a correction: the goods are gone.
1607
1524
  */
1608
- genRatedKW: "generation.ratedKW",
1525
+ destroying: "urn:epcglobal:cbv:bizstep:destroying",
1526
+ /** 새 물품이 생겨 계보가 시작된다 — ISA-95 `MaterialUse: Produced`. */
1527
+ commissioning: "urn:epcglobal:cbv:bizstep:commissioning",
1609
1528
  /**
1610
- * 발전 정격(kW) — **직류 쪽**. 변환기(인버터)의 입력 쪽 정격이고, 태양광이면 패널 정격의 합이다.
1529
+ * **검사** — CBV `inspecting`. 1차 출처(CBV 2.0) 정의: 「Process of reviewing objects to address
1530
+ * potential physical or documentation defects」이고, 「표본과 달리 검사된 대상은 그대로 남는다」고
1531
+ * 이어진다(즉 검사는 물건을 소비하지 않는다).
1611
1532
  *
1612
- * 이용률의 분모로 쓰지 않는다. 이 값이 교류 정격보다 큰 것은 설계이고(변환기를 그렇게 고른다),
1613
- * 그 차이가 「맑은 정오에도 교류 출력이 더 오르지 않는 이유」를 설명한다.
1533
+ * 이 단계에 `DISP.conformant`/`DISP.non_conformant` 가 붙어 판정이 처분으로 남는다 — 입고검수·
1534
+ * 공정 중 검사가 그 모양이다.
1614
1535
  */
1615
- genRatedKWdc: "generation.ratedKWdc",
1536
+ inspecting: "urn:epcglobal:cbv:bizstep:inspecting",
1616
1537
  /**
1617
- * 하루 형상 — 쉼표로 나눈 **24개 비율**(0~1). 시각(현장 시간대)의 정격 대비 출력이다.
1538
+ * **어느 단계로도 이름 붙지 않는 활동** — 원문: 「A business step not identified by any other」.
1618
1539
  *
1619
- * 예: `0,0,0,0,0,0,0.05,0.2,0.45,0.7,0.9,1,1,0.95,0.8,0.6,0.35,0.12,0.02,0,0,0,0,0`
1620
- */
1621
- genDailyProfile: "generation.dailyProfile"
1622
- };
1623
- var EMS_PROPERTY_SPEC = {
1624
- [EMS_PROPERTY.contractKW]: { uom: "kW", dataType: "xs:double", note: "contracted power at the metering point, in kW." },
1625
- /* 값이 셋 중 하나여야 한다 — 그 밖의 낱말은 받지 않는다(뜻이 통할 것 같은 말도 받지 않는다). */
1626
- [EMS_PROPERTY.meterDirection]: {
1627
- dataType: "xs:string",
1628
- note: 'what this metering point measures: "import" (drawn from the grid), "export" (generation sent out), or "bidirectional" (one meter for both, sign carries the direction). Left undeclared, the point counts as load \u2014 leaving it out never makes demand look smaller than it is.'
1629
- },
1630
- [EMS_PROPERTY.ratedKW]: { uom: "kW", dataType: "xs:double", note: "power drawn while running, in kW." },
1631
- [EMS_PROPERTY.standbyKW]: { uom: "kW", dataType: "xs:double", note: "power drawn while idle, in kW." },
1632
- [EMS_PROPERTY.demandChargePerKW]: { dataType: "xs:double", note: "demand charge per kW of billing-period peak, in the declared currency." },
1633
- [EMS_PROPERTY.billingDemandKW]: {
1634
- uom: "kW",
1635
- dataType: "xs:double",
1636
- note: "billing demand in kW \u2014 the basis the demand charge is actually billed on (often a rolling 12-month peak). Not the contracted power."
1637
- },
1638
- [EMS_PROPERTY.energyChargePerKWh]: { dataType: "xs:double", note: "energy charge per kWh, in the declared currency." },
1639
- [EMS_PROPERTY.currency]: { dataType: "xs:string", note: "ISO 4217 currency code, e.g. USD or KRW." },
1640
- [EMS_PROPERTY.capacityKWh]: { uom: "kWh", dataType: "xs:double", note: "usable energy of the storage, in kWh." },
1641
- [EMS_PROPERTY.dischargeAboveKW]: { uom: "kW", dataType: "xs:double", note: "net demand above which the storage discharges, in kW." },
1642
- [EMS_PROPERTY.maxDischargeKW]: { uom: "kW", dataType: "xs:double", note: "inverter limit on discharge rate, in kW." },
1643
- /* 퍼센트다 — 0.8 은 0.8% 이고 80% 가 아니다. 이 한 줄이 없어서 배터리가 조용히 비어 있었다. */
1644
- [EMS_PROPERTY.reserveSoc]: { uom: "%", dataType: "xs:double", range: [0, 100], note: "reserve state of charge as a percentage 0-100 (20 means 20%), never discharged below." },
1645
- [EMS_PROPERTY.initialSoc]: { uom: "%", dataType: "xs:double", range: [0, 100], note: "starting state of charge as a percentage 0-100 (80 means 80%, not 0.8)." },
1646
- [EMS_PROPERTY.genRatedKW]: {
1647
- uom: "kW",
1648
- dataType: "xs:double",
1649
- note: "rated AC generation output, in kW \u2014 the denominator of capacity factor. Declare per equipment, or on the incoming location as a site total."
1650
- },
1651
- [EMS_PROPERTY.genRatedKWdc]: {
1652
- uom: "kW",
1653
- dataType: "xs:double",
1654
- note: "rated DC generation capacity, in kW (panel rating for PV). Larger than the AC rating by design; not the capacity-factor denominator."
1655
- },
1656
- [EMS_PROPERTY.genDailyProfile]: {
1657
- dataType: "xs:string",
1658
- note: "daily shape as 24 comma-separated fractions of rated output (0-1), one per hour of local time \u2014 the site declares its own curve; we do not invent one."
1659
- }
1540
+ * 이것은 근사가 아니라 **표준이 준 낱말**이다. 그 구별이 중요하다: 재고 조정처럼 한 낱말이 두 일을
1541
+ * 하는 원천(세어 보고 맞춘 것 · 사람이 정정한 것)을 `cycle_counting` 으로 옮기면 **일어나지 않은
1542
+ * 계수를 기록**하게 된다. 그때 쓰는 것이 이 값이고, 무슨 일이었는지는 값으로 함께 나른다.
1543
+ *
1544
+ * 원문 확인: CBV Standard Release 2.0(Ratified Jun 2022) §7.1.
1545
+ */
1546
+ other: "urn:epcglobal:cbv:bizstep:other"
1660
1547
  };
1661
- function generationFractionAt(profile, hourOfDay) {
1662
- const parts = String(profile ?? "").split(",").map((v2) => v2.trim()).filter((v2) => v2 !== "");
1663
- if (parts.length !== 24) return void 0;
1664
- const h = Math.floor(hourOfDay);
1665
- if (!Number.isFinite(h) || h < 0 || h > 23) return void 0;
1666
- const v = Number(parts[h]);
1667
- if (!Number.isFinite(v) || v < 0 || v > 1) return void 0;
1668
- return v;
1548
+ var EPCIS_EVENT = {
1549
+ object: "epcis.ObjectEvent",
1550
+ aggregation: "epcis.AggregationEvent",
1551
+ transaction: "epcis.TransactionEvent",
1552
+ transformation: "epcis.TransformationEvent"
1553
+ };
1554
+ function isEpcisEventType(eventType) {
1555
+ return typeof eventType === "string" && eventType.startsWith("epcis.");
1669
1556
  }
1670
- var EMS_TYPES = [
1671
- /* ── 자리: 전기적 구간 ─────────────────────────────────────────────────── */
1672
- {
1673
- key: "incoming",
1674
- role: "location",
1675
- /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
1676
- level: "Other",
1677
- label: "twin.type.incoming",
1678
- /* 수전 지점 — 계약전력이 걸리는 자리이고, 요금의 근거가 되는 수요는 여기서 잰다.
1679
- ISO 50001 의 「에너지 유입」 경계이기도 하다(조직의 에너지 검토가 여기서 시작한다). */
1680
- standardClass: { iec61850: "MMTR", iso50001: "EnergyInput" },
1681
- identity: { scheme: "kernel:id" },
1682
- capabilities: ["metered"]
1683
- },
1684
- {
1685
- key: "feeder",
1686
- role: "location",
1687
- /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
1688
- level: "Other",
1689
- label: "twin.type.feeder",
1690
- /* 분기 회로 — 부하 분해의 단위. 계약전력의 하위 배분이 여기서 정해진다. */
1691
- standardClass: { iec61850: "Feeder", iso50001: "EnergyUse" },
1692
- identity: { scheme: "kernel:id" },
1693
- capabilities: ["metered"]
1694
- },
1695
- {
1696
- key: "submeter-zone",
1697
- role: "location",
1698
- /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
1699
- level: "Other",
1700
- label: "twin.type.submeter-zone",
1701
- /*
1702
- * 구역 계량 — 여러 부하를 한 계량기로 묶어 재는 자리(공조·조명처럼 개별 계량이 없는 것들).
1703
- *
1704
- * ISO 50001 의 **SEU**(유의 에너지 사용처)가 대개 이 알갱이다. 개별 설비까지 재지 못하는 현장이
1705
- * 많고, 그것을 「모른다」로 두는 대신 **묶음으로 아는 것**이 정직하다.
1706
- */
1707
- standardClass: { iec61850: "MMXU", iso50001: "SEU" },
1708
- identity: { scheme: "kernel:id" },
1709
- capabilities: ["metered"]
1710
- },
1711
- /* ── 설비: 계량 지점과 에너지 자원 ──────────────────────────────────────── */
1712
- {
1713
- key: "meter",
1714
- role: "equipment",
1715
- label: "twin.type.meter",
1716
- /* 계량기 — 측정 논리 노드(MMXU=측정단위, MMTR=적산). 자산으로도 하나다(ISO 55000). */
1717
- standardClass: { iec61850: "MMXU", iso55000: "Asset", iso50001: "MeasurementPoint" },
1718
- identity: { scheme: "kernel:id" },
1719
- capabilities: ["metered", "operable"]
1720
- },
1721
- {
1722
- key: "breaker",
1723
- role: "equipment",
1724
- label: "twin.type.breaker",
1725
- /*
1726
- * 차단기 — IEC 61850 `XCBR`. **우리는 이것을 조작하지 않는다**(안전 계통은 범위 밖: ems.md §1).
1727
- * 상태를 읽어 계통 구성을 알 뿐이다.
1728
- *
1729
- * 능력은 `switching` 이다 — `operable` 이 아니다(2026-08-14). `operable` 이던 동안 저작면이 차단기에
1730
- * **제어 컴포넌트**를 권했다: 우리가 하지 않기로 한 조작을 화면이 부추긴 것이다. 「위치를 읽는다」와
1731
- * 「명령을 받는다」는 다른 능력이고, 이제 그 둘이 갈려 있다(capability.ts 주석).
1732
- */
1733
- standardClass: { iec61850: "XCBR", iso55000: "Asset" },
1734
- identity: { scheme: "kernel:id" },
1735
- capabilities: ["switching"]
1736
- },
1737
- {
1738
- key: "pv-array",
1739
- role: "equipment",
1740
- label: "twin.type.pv-array",
1741
- /* 태양광 어레이 — IEC 61850-7-420(분산자원)의 `DPVA`. 발전과 계량은 다른 능력이다. */
1742
- standardClass: { iec61850: "DPVA", iso55000: "Asset", iso50001: "RenewableSupply" },
1743
- identity: { scheme: "kernel:id" },
1744
- capabilities: ["energyGenerating", "metered", "operable"]
1745
- },
1746
- {
1747
- key: "battery",
1748
- role: "equipment",
1749
- label: "twin.type.battery",
1750
- /* 축전지(ESS) — `ZBAT`. 충전·방전을 나눠 재고, 저장은 보관(`storable`)이 아니다(물건이 아니다). */
1751
- standardClass: { iec61850: "ZBAT", iso55000: "Asset" },
1752
- identity: { scheme: "kernel:id" },
1753
- capabilities: ["energyStoring", "metered", "operable"]
1754
- },
1755
- {
1756
- key: "utility",
1757
- role: "equipment",
1758
- label: "twin.type.utility",
1759
- /*
1760
- * 공통 설비 — 공조·컴프레서·칠러·조명·폐수처리처럼 **어느 공정에도 귀속되지 않는** 소비처.
1761
- *
1762
- * ── 왜 따로 있나 (2026-08-14) ────────────────────────────────────────────
1763
- * 물류·생산 트윈에서 이런 것들은 **설비가 아니다**(공정에 매핑되지 않으므로 자원 축에 없다).
1764
- * 그런데 에너지에서는 소비의 절반을 차지하고 감축 후보 1순위다 — 담을 자리가 반드시 있어야 한다.
1765
- *
1766
- * 처음에는 `curtailable-load` 하나로 받으려 했다. 그런데 그 이름은 **「줄일 수 있다」고 주장**한다:
1767
- * 폐수처리·방폭 환기·서버실 냉방은 공통이지만 줄일 수 없고, 그것을 감축 가능으로 두면 트윈이
1768
- * 「이걸 줄이면 됩니다」라는 거짓 제안을 한다. 공통성과 감축 가능성은 **다른 축**이다.
1769
- *
1770
- * 표준: IEC 61850 에 「공통 설비」라는 논리 노드는 없다(설비 종류마다 다른 노드다) — 비운다.
1771
- * ISO 50001 의 SEU 는 이 부류를 가장 많이 가리킨다(유의 에너지 사용처).
1772
- */
1773
- standardClass: { iso50001: "SEU", iso55000: "Asset" },
1774
- identity: { scheme: "kernel:id" },
1775
- capabilities: ["metered", "operable"]
1776
- },
1777
- {
1778
- key: "curtailable-load",
1779
- role: "equipment",
1780
- label: "twin.type.curtailable-load",
1781
- /*
1782
- * 감축 가능 부하 — 줄일 수 있는 소비처(공조·충전기·비상시 미가동 라인).
1783
- *
1784
- * 표준에 이 이름은 없다: IEC 61850 은 설비를 종류로 부르고 「감축 가능」은 **운영 정책**이다.
1785
- * 그래서 `iec61850` 칸을 비우고 ISO 50001 의 SEU 로만 대응한다 — 억지로 논리 노드를 적으면
1786
- * 적합성 표가 거짓을 말한다.
1787
- */
1788
- standardClass: { iso50001: "SEU" },
1789
- identity: { scheme: "kernel:id" },
1790
- capabilities: ["curtailable", "metered", "operable"]
1791
- }
1792
- ];
1793
- function electricalUpstreamOf(locations, id) {
1794
- const byId = new Map((locations ?? []).filter((l) => l?.id).map((l) => [String(l.id), l]));
1795
- const self = byId.get(String(id));
1796
- if (!self) return void 0;
1797
- if (self.upstreamId) return String(self.upstreamId);
1798
- const parent = self.parentId ? byId.get(String(self.parentId)) : void 0;
1799
- if (!parent) return void 0;
1800
- return isElectricalLocationType(String(parent.type ?? "")) ? String(parent.id) : void 0;
1557
+ function ssccUri(companyPrefix, serial) {
1558
+ return `urn:epc:id:sscc:${companyPrefix}.${String(serial).padStart(10, "0")}`;
1801
1559
  }
1802
- function isElectricalLocationType(type) {
1803
- return EMS_LOCATION_TYPES.includes(type);
1560
+ function sgtinClass(companyPrefix, itemRef) {
1561
+ return `urn:epc:idpat:sgtin:${companyPrefix}.${itemRef}.*`;
1804
1562
  }
1805
-
1806
- // src/domain-catalog.ts
1807
- var locationKeys = (types) => types.filter((t) => t.role === "location").map((t) => t.key);
1808
- var DOMAIN_CATALOG = {
1809
- // label 은 언어 중립 i18n 키(twin.system.<code>) — 사람 언어는 표현계층이 렌더(L2).
1810
- wms: { system: "wms", label: "twin.system.wms", types: WMS_TYPES, locationTypes: locationKeys(WMS_TYPES) },
1811
- yms: { system: "yms", label: "twin.system.yms", types: YMS_TYPES, locationTypes: locationKeys(YMS_TYPES) },
1812
- mes: { system: "mes", label: "twin.system.mes", types: MES_TYPES, locationTypes: locationKeys(MES_TYPES) },
1813
- ems: { system: "ems", label: "twin.system.ems", types: EMS_TYPES, locationTypes: locationKeys(EMS_TYPES) }
1563
+ var ILMD_ATTR = {
1564
+ /** 유통기한·만료(로트 단위). */
1565
+ expiry: "cbvmda:itemExpirationDate",
1566
+ /** 로트·배치 번호(직렬 개체에 로트를 붙일 때). */
1567
+ lot: "cbvmda:lotNumber"
1814
1568
  };
1815
- var READ_BASIS = ["document", "rows", "state", "journal", "record"];
1816
- var ABSENCE = ["not-running", "not-observed", "not-applicable", "not-kept"];
1817
- var EMPTY_BECAUSE = [
1818
- "not-applicable",
1819
- "not-declared",
1820
- "declared-empty",
1821
- "not-projected",
1822
- "none-yet",
1823
- "observed-not-in-state",
1824
- "not-observed"
1825
- ];
1826
- var LOGISTICS = ["wms", "yms", "mes"];
1827
- var TWIN_AXES = [
1828
- {
1829
- axis: "locations",
1830
- path: "locations",
1831
- journalAxis: "locationId",
1832
- describedBy: ["name", "type"],
1833
- label: "twin.axis.locations",
1834
- kind: "instance",
1835
- typeRole: "location",
1836
- standardClass: { epcis: "SGLN" }
1837
- },
1838
- {
1839
- axis: "equipment",
1840
- path: "equipment",
1841
- journalAxis: "moverId",
1842
- describedBy: ["name", "kind"],
1843
- label: "twin.axis.equipment",
1844
- kind: "instance",
1845
- typeRole: "equipment",
1846
- standardClass: { isa95: "Equipment", iso55000: "Asset", epcis: "GIAI" }
1847
- },
1848
- {
1849
- axis: "persons",
1850
- path: "persons",
1851
- label: "twin.axis.persons",
1852
- kind: "instance",
1853
- standardClass: { isa95: "Person" },
1854
- systems: LOGISTICS
1855
- },
1856
- {
1857
- axis: "assets",
1858
- path: "assets",
1859
- label: "twin.axis.assets",
1860
- kind: "instance",
1861
- standardClass: { isa95: "PhysicalAsset", iso55000: "Asset" }
1862
- },
1863
- {
1864
- axis: "personnelClasses",
1865
- path: "personnelClasses",
1866
- describedBy: ["name", "description"],
1867
- label: "twin.axis.personnelClasses",
1868
- kind: "class",
1869
- standardClass: { isa95: "PersonnelClass" },
1870
- systems: LOGISTICS
1871
- },
1872
- {
1873
- axis: "equipmentClasses",
1874
- path: "equipmentClasses",
1875
- describedBy: ["name", "description"],
1876
- label: "twin.axis.equipmentClasses",
1877
- kind: "class",
1878
- standardClass: { isa95: "EquipmentClass" }
1879
- },
1880
- {
1881
- axis: "assetClasses",
1882
- path: "assetClasses",
1883
- describedBy: ["name", "description"],
1884
- label: "twin.axis.assetClasses",
1885
- kind: "class",
1886
- standardClass: { isa95: "PhysicalAssetClass" }
1887
- },
1888
- {
1889
- axis: "materialDefinitions",
1890
- path: "materialDefinitions",
1891
- journalAxis: "epc",
1892
- describedBy: ["name", "description", "uom"],
1893
- label: "twin.axis.materialDefinitions",
1894
- kind: "class",
1895
- standardClass: { isa95: "MaterialDefinition" },
1896
- systems: LOGISTICS
1897
- },
1898
- {
1899
- axis: "materialClasses",
1900
- path: "materialClasses",
1901
- describedBy: ["name", "description"],
1902
- label: "twin.axis.materialClasses",
1903
- kind: "class",
1904
- standardClass: { isa95: "MaterialClass" },
1905
- systems: LOGISTICS
1906
- },
1907
- {
1908
- axis: "operations",
1909
- path: "operations",
1910
- describedBy: ["name", "label", "description"],
1911
- label: "twin.axis.operations",
1912
- kind: "spec",
1913
- standardClass: { isa95: "OperationsSegment" },
1914
- systems: LOGISTICS
1915
- },
1916
- {
1917
- axis: "productionSpec",
1918
- path: "productionSpec",
1919
- label: "twin.axis.productionSpec",
1920
- kind: "spec",
1921
- standardClass: { isa95: "OperationsSegment" },
1922
- systems: LOGISTICS
1923
- },
1924
- /*
1925
- * 아래 셋은 저장상 `productionSpec.definition` 안에 있지만 **개념으로는 1급**이다.
1926
- * `materials` 가 최상위 `materialDefinitions` 와 **둘 다** 있는 것은 지금 상태 그대로다 —
1927
- * 전자는 도메인 정의의 가벼운 목록(`{key,label}`), 후자는 ISA-95 풍부형이다. 같은 것의 집이
1928
- * 둘이라는 사실을 **선언이 드러낸다**(감추면 화면이 어느 쪽을 보는지 아무도 모른다).
1929
- */
1930
- {
1931
- axis: "recipes",
1932
- path: "productionSpec.definition.recipes",
1933
- describedBy: ["label"],
1934
- label: "twin.axis.recipes",
1935
- kind: "spec",
1936
- standardClass: { isa95: "OperationsSegment" },
1937
- systems: LOGISTICS
1938
- },
1939
- {
1940
- axis: "routes",
1941
- path: "productionSpec.definition.routes",
1942
- describedBy: ["label"],
1943
- label: "twin.axis.routes",
1944
- kind: "spec",
1945
- standardClass: { isa95: "OperationsSegment" },
1946
- systems: LOGISTICS
1947
- },
1948
- {
1949
- axis: "materials",
1950
- path: "productionSpec.definition.materials",
1951
- describedBy: ["label"],
1952
- label: "twin.axis.materials",
1953
- kind: "class",
1954
- standardClass: { isa95: "MaterialDefinition" },
1955
- systems: LOGISTICS
1956
- },
1957
- /*
1958
- * 시험 명세 — **자원 아홉 종류가 가리키는 대상.**
1959
- *
1960
- * 이 축이 없던 동안 `testSpecificationIds` 는 허공을 가리켰다(값은 실리는데 무엇인지 아무도 모른다).
1961
- * 축이 서면 인스펙션의 선 채움이 **끊어진 참조를 센다** — 없는 명세를 가리키면 화면이 말한다.
1962
- *
1963
- * `kind: 'spec'` 이다: 자원도 등급도 아니고 **판정의 정의**다(공정·레시피와 같은 부류).
1964
- */
1965
- {
1966
- axis: "testSpecifications",
1967
- path: "testSpecifications",
1968
- describedBy: ["name", "description", "version"],
1969
- label: "twin.axis.testSpecifications",
1970
- kind: "spec",
1971
- standardClass: { isa95: "TestSpecification" }
1972
- },
1973
- /*
1974
- * ── ISA-95 Part 4 — 일정과 실적 ────────────────────────────────────────────────
1975
- *
1976
- * 여기부터는 **선언이 아니다.** 오더와 작업은 사람이 board 에 적어 두는 값이 아니라 현장이 낳는
1977
- * 사실이고, 그 집은 커널 상태와 저널이다. 그래서 `source` 가 `'state'` 이고 `path` 가 없다.
1978
- *
1979
- * ── 왜 축이어야 하나 ──────────────────────────────────────────────────────────
1980
- * 이 둘이 축이 아니던 동안 "이 트윈이 표준의 어디를 채우나" 라는 질문은 **절반만** 답했다. Part 2
1981
- * 자원 모델은 여덟이 완전한데 Part 4 는 통째로 비어 있었다 — 런타임에는 실재하는데 조회 모델에는
1982
- * 없었기 때문이다. 실적을 성과 화면이 답한다는 것은 사실이지만, 그건 **집계**이고 개념 자체를
1983
- * 가리켜 걸어 들어갈 자리는 없었다(어느 오더가 어느 공정에서 무엇을 먹었나).
1984
- *
1985
- * ── 왜 테이블로 투영하지 않나 ─────────────────────────────────────────────────
1986
- * 정본이 저널이다. 구조 엔티티는 **원본이 낼 수 있는 것만** 담고(ADR-0032-D), 오더는 원본이 낸
1987
- * 것이지만 트윈이 **관측한** 것이다. 투영은 규모에서 성능이 필요해질 때 KPI 폴드와 같은 급의
1988
- * 별도 결정으로 한다.
1989
- */
1990
- {
1991
- axis: "orders",
1992
- journalAxis: "orderId",
1993
- describedBy: ["kind", "status"],
1994
- label: "twin.axis.orders",
1995
- kind: "instance",
1996
- source: "state",
1997
- historical: true,
1998
- standardClass: { isa95: "OperationsRequest", epcis: "TransactionEvent" },
1999
- systems: LOGISTICS
2000
- },
2001
- {
2002
- axis: "tasks",
2003
- describedBy: ["kind", "status"],
2004
- label: "twin.axis.tasks",
2005
- kind: "instance",
2006
- source: "state",
2007
- historical: true,
2008
- /*
2009
- * No single EPCIS projection. A task's event kind follows its operation: a putaway or a pick is
2010
- * an ObjectEvent, only a transformation (production, kitting) is a TransformationEvent. This used
2011
- * to say `epcis: 'TransformationEvent'` for an axis that spans every logistics system.
2012
- */
2013
- standardClass: { isa95: "SegmentResponse" },
2014
- systems: LOGISTICS
2015
- },
2016
- /*
2017
- * ── 물품이 축이 아니었다 (2026-08-22) ──────────────────────────────────────
2018
- * 트윈에서 **수가 가장 많은 것**이 물품인데(실측: 엔티티 3,611 중 2,400 · hatio-us 는 2,805) 그것을
2019
- * 가리켜 걸어 들어갈 자리가 없었다. 지도와 집약 태그에는 이미 보이는데 「모델 살펴보기」에는 문이
2020
- * 없었다 — 사용자가 트윈에 가장 자주 묻는 것이 「내 물건이 어디 있나」이므로 그것은 접근 장벽이다.
2021
- *
2022
- * 성격은 `orders`·`tasks` 와 같다: 상태에 살고, 저널에 이력이 있고, 원본이 낸 것을 트윈이 관측한다.
2023
- * 그래서 같은 조합(`instance` · `state` · `historical`)이다.
2024
- *
2025
- * ── 표준 대응 ─────────────────────────────────────────────────────────────
2026
- * ISA-95 는 `MaterialLot` 이다 — 물품은 「무슨 품목인가」(정의)가 아니라 「그 품목의 이 덩어리」이고,
2027
- * 위치·수량·부분(`MaterialSubLot`)을 그 자리가 든다. EPCIS 는 `ObjectEvent` 다: 개체가 생기고
2028
- * 관측되고 사라지는 것을 그 사건이 말한다.
2029
- *
2030
- * ── 무엇이 이 항목을 가리키나 ─────────────────────────────────────────────
2031
- * `subLotId ?? epc` 다. 짐작에 맡기면 `gtin` 으로 떨어지고, 그러면 **같은 품목의 물품 전부가 한
2032
- * 식별자로 뭉친다** — 화면이 2,400개를 몇 개로 보인다.
2033
- */
2034
- {
2035
- axis: "items",
2036
- journalAxis: "epc",
2037
- describedBy: ["definitionId", "lot"],
2038
- label: "twin.axis.items",
2039
- kind: "instance",
2040
- source: "state",
2041
- historical: true,
2042
- idField: ["subLotId", "epc"],
2043
- standardClass: { isa95: "MaterialLot", epcis: "ObjectEvent" },
2044
- systems: LOGISTICS
2045
- },
2046
- /*
2047
- * ── 에너지가 더하는 개념은 **하나**다 (2026-08-14, §10 6.5단계) ──────────────
2048
- *
2049
- * 에너지 트윈의 개체 대부분은 **이미 있는 축**이 답한다: 전기 구간은 `locations`, 계량기·차단기·
2050
- * 태양광·축전지·감축 부하는 `equipment` 다(카탈로그가 그 타입들을 그 역할로 선언한다). 그것들을
2051
- * 새 축으로 다시 세우면 같은 것이 두 곳에서 세어진다 — 개념 지도가 계량기를 두 번 보여 준다.
2052
- *
2053
- * 정말로 새로운 것은 **수요 구간**이다: 자원이 아니고, 선언이 아니고, 15분마다 닫히는 **사실**이다.
2054
- * 그것이 요금의 알갱이이고 피크의 근거다(피크는 마감된 구간의 최대이므로 파생이다 — 축이 아니다).
2055
- *
2056
- * ── 표준 칸을 비운다 ──────────────────────────────────────────────────────
2057
- * 15분 수요 구간은 **요금 제도의 알갱이**다(계약·TOU). ISO 50001 은 경영 체계를, IEC 61850 은 설비
2058
- * 데이터 모델을 말하고, 둘 다 이 구간을 정의하지 않는다. 가까운 이름을 적으면 적합성 표가 거짓을
2059
- * 말하므로 비워 둔다 — 「표준에 자리가 없으면 빈 객체」라는 이 선언의 규율 그대로다.
2060
- *
2061
- * 아직 세우지 않은 것: **요금 구간**(TariffPeriod)과 **원단위**(EnPI). 둘 다 아직 아무도 만들지
2062
- * 않는다 — 선언만 하면 개념 지도가 언제나 0 을 보여 주고, 그것은 결손처럼 읽힌다(§10 7단계의 일).
2063
- */
2064
- /*
2065
- * **무엇이 이 항목을 가리키나** — `idField` 가 말한다.
2066
- *
2067
- * 수요 구간에는 `id` 가 없다. 그것이 결함은 아니다: 구간의 정체성은 **그 구간이 언제 시작했나**이고
2068
- * (요금의 알갱이가 그 시각으로 정해진다) 커널도 그것으로 키를 만든다(`contract-projected-over:<startMs>`).
2069
- *
2070
- * 그런데 소비처가 `id`·`key`·`gtin` 을 **짐작**하고 있어서, 화면이 여섯 구간 모두를 「식별자 없음 —
2071
- * 참조할 수 없는 항목」으로 보였다. 값은 실재하는데 가리킬 수 없다고 말한 것이다. 짐작을 없애고
2072
- * 선언이 답하게 한다 — 축이 사는 자리(`path`)를 선언하는 것과 같은 이유다.
2073
- */
2074
- {
2075
- axis: "demandWindows",
2076
- path: "energy.closed",
2077
- idField: "startMs",
2078
- label: "twin.axis.demandWindows",
2079
- kind: "instance",
2080
- source: "state",
2081
- historical: true,
2082
- standardClass: {},
2083
- systems: ["ems"]
2084
- }
2085
- ];
2086
- function isCacheableTense(t) {
2087
- return t === "standing";
2088
- }
2089
- function tenseOf(r) {
2090
- return r?.tense;
2091
- }
2092
- var TWIN_RELATIONS = [
2093
- /*
2094
- * What a location sits in — another location (line ⊃ station, zone ⊃ aisle ⊃ bin) or, when no
2095
- * location has that id, an area of the space (host's `TwinArea`). See `axis-or-external`.
2096
- */
2097
- { from: "locations", field: "parentId", target: { kind: "axis-or-external", axis: "locations", entity: "space.area" }, via: "ops.rel.area", optional: true, tense: "standing" },
2098
- /* 자원이 사는 자리 */
2099
- { from: "equipment", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2100
- { from: "persons", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2101
- { from: "assets", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2102
- /* 자원의 등급 — 설비만 `kind`(타입)로 가고 사람·자산은 등급 목록으로 간다. 표준의 비대칭 그대로. */
2103
- { from: "persons", field: "personnelClassIds[]", target: { kind: "axis", axis: "personnelClasses" }, via: "ops.rel.class", optional: true, tense: "standing" },
2104
- { from: "assets", field: "assetClassIds[]", target: { kind: "axis", axis: "assetClasses" }, via: "ops.rel.class", optional: true, tense: "standing" },
2105
- { from: "equipment", field: "kind", target: { kind: "type", role: "equipment" }, via: "ops.rel.type", tense: "standing" },
2106
- { from: "locations", field: "type", target: { kind: "type", role: "location" }, via: "ops.rel.type", tense: "standing" },
2107
- /* 생산 — 레시피에서 시작해 라우트·공정·품목으로 퍼진다 */
2108
- { from: "recipes", field: "route", target: { kind: "axis", axis: "routes" }, via: "ops.rel.route", optional: true, tense: "standing" },
2109
- { from: "recipes", field: "inputs[].material", target: { kind: "axis", axis: "materials" }, via: "ops.rel.input", tense: "standing" },
2110
- { from: "recipes", field: "outputs[].material", target: { kind: "axis", axis: "materials" }, via: "ops.rel.output", tense: "standing" },
2111
- { from: "routes", field: "steps[]", target: { kind: "axis", axis: "operations" }, via: "ops.rel.step", tense: "standing" },
2112
- /*
2113
- * 일정·실적의 관계 — **관측 관계다.** 선언 관계는 "그렇게 만들기로 했다" 이고, 이것은 "그렇게
2114
- * 일어났다" 다. 관계가 없으면 이 두 축은 지도에서 연결되지 않은 카드가 된다(그러면 걸어 들어갈 수 없다).
2115
- */
2116
- /*
2117
- * 오더가 무엇을 만드나 — **자재 키가 아니라 GS1 품목 참조다**(`lines[].gtin`). 자재와 이어 주는
2118
- * 것은 `productionSpec.binding` 이고 그 해소는 호스트가 한다 — 자리·구역과 같은 `external` 이다.
2119
- * 축을 직접 가리키게 적으면 없는 필드를 가리키는 선언이 된다(계약을 보고 고쳤다).
2120
- */
2121
- { from: "orders", field: "lines[].gtin", target: { kind: "external", entity: "gs1.itemRef" }, via: "ops.rel.item", optional: true, tense: "standing" },
2122
- /*
2123
- * ── 작업의 관계는 `tense` 를 **선언하지 않는다** ────────────────────────────
2124
- * 여섯 줄 모두 비어 있는 것이 판단이다. 작업의 시간축은 **그 줄의 상태**가 정한다 — 끝난 작업이
2125
- * 이 설비를 가리키면 지난 일이고, 아직인 작업이 가리키면 앞의 일이다. 한 선언이 둘 다이다.
2126
- *
2127
- * 여기에 `standing` 을 적으면 화면은 「이 설비에 걸린 작업 열」을 시간이 없는 사실로 묶고, **세워도
2128
- * 되나의 답이 정확히 뒤집힌다.** 채우고 싶은 힘이 있는 자리이므로 적어 둔다: 비어 있음이 답이다.
2129
- *
2130
- * 줄마다 다른 것은 선언이 아니라 **읽는 쪽이 상태를 보고 판정한다**(`TaskState.status`).
2131
- */
2132
- { from: "tasks", field: "orderId", target: { kind: "axis", axis: "orders" }, via: "ops.rel.order", optional: true },
2133
- /* 작업의 `kind` 는 그 공정의 키다(라우트의 단계 이름 그대로 — `mes-kernel` 의 공정 목록이 그 증거). */
2134
- { from: "tasks", field: "kind", target: { kind: "axis", axis: "operations" }, via: "ops.rel.operation", optional: true },
2135
- { from: "tasks", field: "fromNode", target: { kind: "axis", axis: "locations" }, via: "ops.rel.from", optional: true },
2136
- { from: "tasks", field: "toNode", target: { kind: "axis", axis: "locations" }, via: "ops.rel.at", optional: true },
2137
- { from: "tasks", field: "resourceRef", target: { kind: "axis", axis: "equipment" }, via: "ops.rel.by", optional: true },
2138
- { from: "tasks", field: "personnel[]", target: { kind: "axis", axis: "persons" }, via: "ops.rel.crew", optional: true },
2139
- /*
2140
- * 물품의 관계 (2026-08-22) — 없으면 축이 **걸어 들어갈 수 없는 목록**이 된다.
2141
- *
2142
- * `location` 은 필수다 — 물품은 언제나 어딘가에 있다(그것이 물품의 뜻이다). 나머지는 선택이다:
2143
- * 물류단위에 담기지 않은 물품, 자산에 실리지 않은 팔레트가 정상이다.
2144
- *
2145
- * `parent` 는 **물품 축을 자기 자신으로** 가리킨다(팔레트에 담긴 상자 — EPCIS `AggregationEvent`).
2146
- * `carriedBy` 는 다른 축이다 — 반복사용 자산(GRAI)이 물류단위를 실어 나른다(§`FlowItem.carriedBy`).
2147
- *
2148
- * 관계 이름은 **소문자 한 낱말**이다(`ops.rel.<name>`) — 기존 열여덟 개가 그 규율이고 시험이 지킨다.
2149
- *
2150
- * 품목(`gtin`)은 오더와 **같은 규율**이다: 자재 키가 아니라 GS1 품목 참조이므로 축을 직접 가리키지
2151
- * 않고 `external` 로 둔다. 축을 가리키게 적으면 없는 필드를 가리키는 선언이 된다.
2152
- */
2153
- /*
2154
- * ── 물품의 지금 자리는 `current` 다 (2026-09-06) ───────────────────────────
2155
- * `location`·`parent`·`carriedBy` 는 지난 일도 앞의 일도 아니고 `standing` 도 아니다 — **지금
2156
- * 그렇고 곧 바뀐다.** 붙박인 자리(`homeLocation`)와 정반대 성질이고, 두 줄이 같은 낱말을 받으면
2157
- * 화면이 「이 상자는 A 에 있다」를 등급처럼 담아 둔다(캐시해도 되는 사실로 읽는다).
2158
- *
2159
- * 하루 비워 두었다. 낱말이 없어서였고, 소비처가 실제로 그 구별에 걸릴 때 늘리기로 했다 — plant 가
2160
- * `MaintenanceOrderStatus.IN_PROGRESS` 로 같은 자리를 만나 걸렸고, 그때 넣었다.
2161
- */
2162
- { from: "items", field: "location", target: { kind: "axis", axis: "locations" }, via: "ops.rel.at", tense: "current" },
2163
- { from: "items", field: "parent", target: { kind: "axis", axis: "items" }, via: "ops.rel.parent", optional: true, tense: "current" },
2164
- { from: "items", field: "carriedBy", target: { kind: "axis", axis: "assets" }, via: "ops.rel.asset", optional: true, tense: "current" },
2165
- { from: "items", field: "gtin", target: { kind: "external", entity: "gs1.itemRef" }, via: "ops.rel.item", optional: true, tense: "standing" },
2166
- /*
2167
- * 자격을 검증한 시험 — **여덟 갈래.** 자원(개체)과 등급 양쪽이 가리킨다: 표준이 그 둘 모두에 이
2168
- * 참조를 두었기 때문이다(개체는 "이 사람이 통과했다", 등급은 "이 자격은 이 시험을 요구한다").
2169
- *
2170
- * **자리(`locations`)에는 없다** — 표준이 자리를 시험 대상으로 두지 않았고 그 비대칭은 표준의
2171
- * 판단이다(`contract.ts` 가 "우리도 자리에 넣지 않는다" 고 적었다).
2172
- */
2173
- { from: "persons", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2174
- { from: "personnelClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2175
- { from: "equipment", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2176
- { from: "equipmentClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2177
- { from: "assets", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2178
- { from: "assetClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2179
- { from: "materialDefinitions", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2180
- { from: "materialClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2181
- /* 공정이 도는 자리·자원 — 항목이 아니라 **타입**을 가리킨다 */
2182
- { from: "operations", field: "locationType", target: { kind: "type", role: "location" }, via: "ops.rel.at", optional: true, tense: "standing" },
2183
- { from: "operations", field: "resourceType", target: { kind: "type", role: "equipment" }, via: "ops.rel.by", optional: true, tense: "standing" }
2184
- ];
2185
- var TWIN_PROPERTIES = [
2186
- /* 공정 — 선언(ISO 8601 기간)과 관측(저널에서 계산한 분포)이 둘 다 있는 유일한 짝. */
2187
- {
2188
- axis: "operations",
2189
- key: "duration",
2190
- label: "twin.prop.duration",
2191
- kind: "distribution",
2192
- declaredField: "duration",
2193
- observedBy: "kpi-fold.workTime",
2194
- uom: "ms"
2195
- },
2196
- /* 자리 — 용량은 선언, 점유는 관측. 단위가 다른 것이 아니라 **같은 축의 두 값**이다. */
2197
- {
2198
- axis: "locations",
2199
- key: "capacity",
2200
- label: "twin.prop.capacity",
2201
- kind: "level",
2202
- declaredField: "capacity",
2203
- observedBy: "state.location.occupancy"
2204
- },
2205
- /* 설비 — 고장 모델은 선언, 가동은 관측(OEE). 선언 없이도 관측은 선다. */
2206
- {
2207
- axis: "equipment",
2208
- key: "mtbf",
2209
- label: "twin.prop.mtbf",
2210
- kind: "distribution",
2211
- declaredField: "mtbfMs",
2212
- observedBy: "oee.availability",
2213
- uom: "ms"
2214
- },
2215
- {
2216
- axis: "equipment",
2217
- key: "mttr",
2218
- label: "twin.prop.mttr",
2219
- kind: "distribution",
2220
- declaredField: "mttrMs",
2221
- observedBy: "oee.availability",
2222
- uom: "ms"
2223
- },
2224
- {
2225
- axis: "equipment",
2226
- key: "availability",
2227
- label: "twin.prop.availability",
2228
- kind: "rate",
2229
- observedBy: "oee.availability",
2230
- uom: "ratio"
2231
- }
2232
- ];
2233
- var propertiesOf = (axis) => TWIN_PROPERTIES.filter((p) => p.axis === axis);
2234
- var axisSource = (axis) => TWIN_AXES.find((a) => a.axis === axis)?.source ?? "document";
2235
- function documentPath(axis) {
2236
- const info = TWIN_AXES.find((a) => a.axis === axis);
2237
- if (!info) throw new Error(`unknown twin axis: "${axis}"`);
2238
- if (axisSource(axis) !== "document" || !info.path)
2239
- throw new Error(`axis "${axis}" is not read from the document (source: ${axisSource(axis)}) \u2014 read it from the ${axisSource(axis)}`);
2240
- return info.path;
2241
- }
2242
- var relationsFrom = (axis) => TWIN_RELATIONS.filter((r) => r.from === axis);
2243
- var relationsTo = (axis) => TWIN_RELATIONS.filter((r) => (r.target.kind === "axis" || r.target.kind === "axis-or-external") && r.target.axis === axis);
2244
- function splitRelationIds(target, ids, inAxis) {
2245
- if (target.kind === "axis") return { axis: { axis: target.axis, ids: [...ids] } };
2246
- if (target.kind === "external") return { external: { entity: target.entity, ids: [...ids] } };
2247
- if (target.kind === "axis-or-external") {
2248
- const inside = ids.filter((id) => inAxis(target.axis, id));
2249
- const outside = ids.filter((id) => !inAxis(target.axis, id));
2250
- return { axis: { axis: target.axis, ids: inside }, external: { entity: target.entity, ids: outside } };
2251
- }
2252
- return {};
2253
- }
2254
- function axisInfo(axis) {
2255
- return TWIN_AXES.find((a) => a.axis === axis);
2256
- }
2257
- var DOMAIN_SYSTEMS = ["wms", "yms", "mes", "ems"];
2258
- var axisAppliesTo = (axis, system) => {
2259
- const declared = TWIN_AXES.find((a) => a.axis === axis)?.systems;
2260
- if (!declared || !system) return true;
2261
- if (!DOMAIN_SYSTEMS.includes(system)) return true;
2262
- return declared.includes(system);
2263
- };
2264
- var levelOfLocationType = (typeKey, system) => {
2265
- const pick = (sys) => DOMAIN_CATALOG[sys]?.types.find((t) => t.role === "location" && t.key === typeKey)?.level;
2266
- if (system && DOMAIN_SYSTEMS.includes(system)) return pick(system);
2267
- const found = [...new Set(DOMAIN_SYSTEMS.map(pick).filter(Boolean))];
2268
- return found.length === 1 ? found[0] : void 0;
2269
- };
2270
- var axesOfSystem = (system) => TWIN_AXES.filter((a) => axisAppliesTo(a.axis, system));
2271
- function capabilitiesForType(system, typeKey) {
2272
- return DOMAIN_CATALOG[system]?.types.find((t) => t.key === typeKey)?.capabilities ?? [];
2273
- }
2274
-
2275
- // src/domain-definition.ts
2276
- var OP_PARAM = {
2277
- /** 양품률(0..1, 무차원). 없으면 커널 기본값 — 기본값을 쓴 사실은 `specCoverage()` 가 밝힌다. */
2278
- yield: "yield",
2279
- /** 셋업·체인지오버 소요(ISO 8601 기간 문자열). ISA-95 는 셋업을 별도 세그먼트로도 표현하지만,
2280
- * 현재 커널은 작업에 붙는 셋업으로 다루므로 모수로 받는다. */
2281
- setupDuration: "setupDuration"
2282
- };
2283
- function procedureViolations(route) {
2284
- const elements = route.procedure ?? [];
2285
- if (!elements.length) return [];
2286
- const errors = [];
2287
- const byKey = new Map(elements.map((e) => [e.key, e]));
2288
- const hasChild = new Set(elements.map((e) => e.parent).filter((k) => !!k));
2289
- const stepSet = new Set(route.steps ?? []);
2290
- const seenStep = /* @__PURE__ */ new Map();
2291
- for (const n of elements) {
2292
- if (n.parent && !byKey.has(n.parent)) errors.push(`${n.key}: \uC0C1\uC704 '${n.parent}' \uAC00 \uC774 \uC808\uCC28\uC5D0 \uC5C6\uB2E4`);
2293
- if (n.step === void 0) continue;
2294
- if (hasChild.has(n.key)) errors.push(`${n.key}: \uC544\uB798 \uC694\uC18C\uAC00 \uC788\uB294\uB370 \uB2E8\uACC4\uB97C \uB4E0\uB2E4 \u2014 \uC2E4\uD589\uB418\uB294 \uAC83\uC740 \uC78E\uBFD0\uC774\uB2E4`);
2295
- if (!stepSet.has(n.step)) errors.push(`${n.key}: \uBAA8\uB974\uB294 \uB2E8\uACC4 '${n.step}' \u2014 steps \uC5D0 \uC5C6\uB2E4`);
2296
- const already = seenStep.get(n.step);
2297
- if (already) errors.push(`\uB2E8\uACC4 '${n.step}' \uAC00 '${already}' \uC640 '${n.key}' \uB458\uC5D0 \uC2E4\uB838\uB2E4 \u2014 \uC808\uCC28 \uC5B4\uB514\uC778\uC9C0 \uB9D0\uD560 \uC218 \uC5C6\uB2E4`);
2298
- else seenStep.set(n.step, n.key);
2299
- }
2300
- return errors;
2301
- }
2302
- var INTENTS = ["transport", "process", "dwell"];
2303
- function dupes(keys) {
2304
- const seen = /* @__PURE__ */ new Set();
2305
- const dup = /* @__PURE__ */ new Set();
2306
- for (const k of keys) {
2307
- if (seen.has(k)) dup.add(k);
2308
- else seen.add(k);
2309
- }
2310
- return [...dup];
2311
- }
2312
- function validateDomainDefinition(def) {
2313
- const v = [];
2314
- if (!def || typeof def !== "object") return ["domain definition \uC5C6\uC74C/\uAC1D\uCCB4 \uC544\uB2D8"];
2315
- if (typeof def.id !== "string" || !def.id) v.push("id \uB204\uB77D");
2316
- if (typeof def.label !== "string" || !def.label) v.push("label \uB204\uB77D");
2317
- if (!Array.isArray(def.locationTypes) || def.locationTypes.length === 0) v.push("locationTypes \uBE44\uC5B4\uC788\uC74C");
2318
- if (!Array.isArray(def.resourceTypes)) v.push("resourceTypes \uBC30\uC5F4 \uC544\uB2D8");
2319
- const locationKeys2 = new Set((def.locationTypes || []).map((n) => n.key));
2320
- const resKeys = new Set((def.resourceTypes || []).map((r) => r.key));
2321
- const matKeys = new Set((def.materials || []).map((m) => m.key));
2322
- const matByKey = new Map((def.materials || []).map((m) => [m.key, m]));
2323
- const opKeys = new Set((def.operations || []).map((o) => o.key));
2324
- const routeKeys = new Set((def.routes || []).map((r) => r.key));
2325
- for (const [name, arr] of [["locationTypes", def.locationTypes], ["resourceTypes", def.resourceTypes], ["materials", def.materials], ["operations", def.operations], ["routes", def.routes], ["recipes", def.recipes]]) {
2326
- for (const d of dupes((arr || []).map((x) => x.key))) v.push(`${name} \uD0A4 \uC911\uBCF5: ${d}`);
2327
- }
2328
- for (const o of def.operations || []) {
2329
- if (!INTENTS.includes(o.intent)) v.push(`operation '${o.key}' intent \uBD80\uC815: ${o.intent}`);
2330
- if (o.locationType && !locationKeys2.has(o.locationType)) v.push(`operation '${o.key}' locationType '${o.locationType}' \uBBF8\uC815\uC758`);
2331
- if (o.resourceType && !resKeys.has(o.resourceType)) v.push(`operation '${o.key}' resourceType '${o.resourceType}' \uBBF8\uC815\uC758`);
2332
- if (o.intent === "dwell" && o.resourceType) v.push(`operation '${o.key}' dwell \uC778\uB370 resourceType \uC9C0\uC815\uB428(\uBB34\uC790\uC6D0\uC774\uC5B4\uC57C)`);
2333
- }
2334
- for (const r of def.routes || []) {
2335
- if (!Array.isArray(r.steps) || r.steps.length === 0) v.push(`route '${r.key}' steps \uBE44\uC5B4\uC788\uC74C`);
2336
- for (const s of r.steps || []) if (!opKeys.has(s)) v.push(`route '${r.key}' step '${s}' \uBBF8\uC815\uC758 operation`);
2337
- }
2338
- for (const rc of def.recipes || []) {
2339
- if (rc.route && !routeKeys.has(rc.route)) v.push(`recipe '${rc.key}' route '${rc.route}' \uBBF8\uC815\uC758`);
2340
- if (!rc.outputs?.length) v.push(`recipe '${rc.key}' outputs \uBE44\uC5B4\uC788\uC74C`);
2341
- for (const p of [...rc.inputs || [], ...rc.outputs || []]) {
2342
- if (!matKeys.has(p.material)) v.push(`recipe '${rc.key}' material '${p.material}' \uBBF8\uC815\uC758`);
2343
- if (typeof p.qty !== "number" || p.qty <= 0) v.push(`recipe '${rc.key}' material '${p.material}' qty \uBD80\uC815`);
2344
- const mat = matByKey.get(p.material);
2345
- if (mat?.locationType && !locationKeys2.has(mat.locationType)) v.push(`recipe '${rc.key}' material '${p.material}' locationType '${mat.locationType}' \uBBF8\uC815\uC758`);
2346
- }
2347
- }
2348
- return v;
2349
- }
2350
- var CATALOG_SEMVER = /^\d+\.\d+\.\d+([-+].+)?$/;
2351
- function validateCatalog(cat) {
2352
- const v = validateDomainDefinition(cat);
2353
- if (typeof cat?.version !== "string" || !CATALOG_SEMVER.test(cat?.version || "")) {
2354
- v.push(`version semver \uC544\uB2D8: ${cat?.version}`);
2355
- }
2356
- return v;
2357
- }
2358
-
2359
- // src/energy-ingest.ts
2360
- function isEnergyRecord(record) {
2361
- if (!record || typeof record !== "object") return false;
2362
- const r = record;
2363
- if (!(typeof r.meterId === "string" && r.meterId.trim().length > 0 && r.epc === void 0)) return false;
2364
- return r.from === void 0 && r.to === void 0;
2365
- }
2366
- function ingestEnergyRecords(records, opts) {
2367
- const arr = Array.isArray(records) ? records : records ? [records] : [];
2368
- const accepted = [];
2369
- const rejected = [];
2370
- let seq = 0;
2371
- for (const record of arr) {
2372
- const errors = [];
2373
- const meterId = String(record?.meterId ?? "").trim();
2374
- if (!meterId) errors.push("meterId \uC5C6\uC74C \u2014 \uC5B4\uB514\uC758 \uC18C\uBE44\uC778\uC9C0 \uBAA8\uB974\uB294 \uAC12\uC740 \uB204\uC801\uD560 \uC218 \uC5C6\uB2E4");
2375
- const at2 = String(record?.at ?? "").trim() || opts.defaultEventTime;
2376
- const atMs = at2 ? Date.parse(at2) : Number.NaN;
2377
- if (!Number.isFinite(atMs)) errors.push("at \uC5C6\uC74C/\uD615\uC2DD \uC624\uB958 \u2014 \uC9C0\uAE08 \uC2DC\uAC01\uC73C\uB85C \uBA54\uC6B0\uBA74 \uB0A8\uC758 \uC218\uC694 \uAD6C\uAC04\uC5D0 \uC2E4\uB9B0\uB2E4");
2378
- const num2 = (v, name) => {
2379
- if (v === void 0 || v === null || v === "") return void 0;
2380
- const n = Number(v);
2381
- if (!Number.isFinite(n)) {
2382
- errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2383
- return void 0;
2384
- }
2385
- return n;
2386
- };
2387
- const kW = num2(record?.kW, "kW");
2388
- const kWh = num2(record?.kWh, "kWh");
2389
- const powerFactor = num2(record?.powerFactor, "powerFactor");
2390
- if (errors.length) {
2391
- rejected.push({ record, errors });
2392
- continue;
2393
- }
2394
- const eventTime = new Date(atMs).toISOString();
2395
- const data = {
2396
- meterId,
2397
- /* 계약은 `kW` 를 필수로 두지만 **못 읽은 표본도 사실**이다 — 그 경우 값을 비우고 보낸다.
2398
- 커널이 「받았지만 부하를 못 읽었다」로 세고, 구간 마감에 그 이유를 싣는다. */
2399
- ...kW !== void 0 ? { kW } : {},
2400
- ...kWh !== void 0 ? { kWh } : {},
2401
- ...powerFactor !== void 0 ? { powerFactor } : {},
2402
- at: eventTime
2403
- };
2404
- accepted.push({
2405
- eventId: `${opts.tenantId}-energy-${++seq}`,
2406
- eventType: ENERGY_EVENT.measured,
2407
- eventTime,
2408
- tenantId: opts.tenantId,
2409
- data
2410
- });
2411
- }
2412
- return { accepted, rejected };
2413
- }
2414
- var POSITIONS = /* @__PURE__ */ new Set(["open", "closed", "intermediate", "bad"]);
2415
- function isEnergyEquipmentRecord(record) {
2416
- if (!record || typeof record !== "object") return false;
2417
- const r = record;
2418
- return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.epc === void 0 && r.meterId === void 0 && /* 적산을 실었으면 발전이다 — 이 문의 값은 상태이고, 적산은 자기 문이 있다. */
2419
- r.kWh === void 0;
2420
- }
2421
- function ingestEnergyEquipmentRecords(records, opts) {
2422
- const arr = Array.isArray(records) ? records : records ? [records] : [];
2423
- const accepted = [];
2424
- const rejected = [];
2425
- let seq = 0;
2426
- for (const record of arr) {
2427
- const errors = [];
2428
- const r = record;
2429
- const equipmentId = String(r?.equipmentId ?? "").trim();
2430
- if (!equipmentId) errors.push("equipmentId \uC5C6\uC74C \u2014 \uC5B4\uB290 \uC124\uBE44\uC758 \uC0C1\uD0DC\uC778\uC9C0 \uBAA8\uB974\uB294 \uAC12\uC740 \uC2E4\uC744 \uC218 \uC5C6\uB2E4");
2431
- const at2 = String(r?.at ?? "").trim() || opts.defaultEventTime;
2432
- const atMs = at2 ? Date.parse(at2) : Number.NaN;
2433
- if (!Number.isFinite(atMs)) errors.push("at \uC5C6\uC74C/\uD615\uC2DD \uC624\uB958 \u2014 \uC9C0\uAE08 \uC2DC\uAC01\uC73C\uB85C \uBA54\uC6B0\uBA74 \uC5B8\uC81C\uC758 \uC0C1\uD0DC\uC778\uC9C0 \uC54C \uC218 \uC5C6\uB2E4");
2434
- const num2 = (v, name, min, max) => {
2435
- if (v === void 0 || v === null || v === "") return void 0;
2436
- const n = Number(v);
2437
- if (!Number.isFinite(n)) {
2438
- errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2439
- return void 0;
2440
- }
2441
- if (min !== void 0 && n < min) {
2442
- errors.push(`${name} \uAC00 ${min} \uBCF4\uB2E4 \uC791\uB2E4: ${n}`);
2443
- return void 0;
2444
- }
2445
- if (max !== void 0 && n > max) {
2446
- errors.push(`${name} \uAC00 ${max} \uBCF4\uB2E4 \uD06C\uB2E4: ${n}`);
2447
- return void 0;
2448
- }
2449
- return n;
2450
- };
2451
- const generatedKW = num2(r?.generatedKW, "generatedKW", 0);
2452
- const exportKW = num2(r?.exportKW, "exportKW");
2453
- const soc = num2(r?.soc, "soc", 0, 100);
2454
- const chargeKW = num2(r?.chargeKW, "chargeKW", 0);
2455
- const dischargeKW = num2(r?.dischargeKW, "dischargeKW", 0);
2456
- const minKW = num2(r?.minKW, "minKW", 0);
2457
- let curtailable;
2458
- if (r?.curtailable !== void 0 && r?.curtailable !== null) {
2459
- if (typeof r.curtailable !== "boolean") errors.push(`curtailable \uAC00 \uCC38/\uAC70\uC9D3\uC774 \uC544\uB2C8\uB2E4: ${JSON.stringify(r.curtailable)}`);
2460
- else curtailable = r.curtailable;
2461
- }
2462
- const dcVoltage = num2(r?.dcVoltage, "dcVoltage", 0);
2463
- const dcCurrent = num2(r?.dcCurrent, "dcCurrent", 0);
2464
- const phases = (raw, name) => {
2465
- if (raw === void 0 || raw === null) return void 0;
2466
- if (!Array.isArray(raw)) {
2467
- errors.push(`${name} \uAC00 \uBC30\uC5F4\uC774 \uC544\uB2C8\uB2E4 \u2014 \uC0C1\uBCC4 \uAC12\uC774\uB77C \uBC30\uC5F4\uB85C \uBC1B\uB294\uB2E4(\uB2E8\uC0C1\uC774\uBA74 \uC6D0\uC18C \uD558\uB098): ${JSON.stringify(raw)}`);
2468
- return void 0;
2469
- }
2470
- if (!raw.length) {
2471
- errors.push(`${name} \uAC00 \uBE48 \uBC30\uC5F4\uC774\uB2E4 \u2014 \uC7B0 \uC0C1\uC774 \uC5C6\uC73C\uBA74 \uADF8 \uCE78\uC744 \uBCF4\uB0B4\uC9C0 \uC54A\uB294\uB2E4`);
2472
- return void 0;
2473
- }
2474
- const out = [];
2475
- for (const [i, v] of raw.entries()) {
2476
- const n = Number(v);
2477
- if (!Number.isFinite(n)) {
2478
- errors.push(`${name}[${i}] \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(v)}`);
2479
- return void 0;
2480
- }
2481
- if (n < 0) {
2482
- errors.push(`${name}[${i}] \uAC00 \uC74C\uC218\uB2E4(${n}) \u2014 \uD06C\uAE30\uB294 \uC74C\uC218\uAC00 \uB418\uC9C0 \uC54A\uB294\uB2E4(\uBC29\uD5A5\uC740 \uB2E4\uB978 \uCD95\uC774 \uB9D0\uD55C\uB2E4)`);
2483
- return void 0;
2484
- }
2485
- out.push(n);
2486
- }
2487
- return out;
1569
+ function lgtinClass(companyPrefix, itemRefAndIndicator, lot) {
1570
+ return `urn:epc:class:lgtin:${companyPrefix}.${itemRefAndIndicator}.${encodeURIComponent(lot)}`;
1571
+ }
1572
+ function parseEpc(uri) {
1573
+ const raw = String(uri ?? "");
1574
+ if (/(?:\/obj\/|:obj:)[^/:\s]+$/.test(raw)) return { scheme: "unknown", instance: true, uri: raw };
1575
+ const inHouseClass = raw.match(/(?:\/class\/|:class:)([^/:\s]+)$/);
1576
+ if (inHouseClass) {
1577
+ const at2 = inHouseClass[1].indexOf(LOT_SEPARATOR);
1578
+ const split = at2 > 0 ? decodedPair(inHouseClass[1].slice(0, at2), inHouseClass[1].slice(at2 + LOT_SEPARATOR.length)) : void 0;
1579
+ return split ? { scheme: "unknown", instance: false, item: split[0], lot: split[1], uri: raw } : { scheme: "unknown", instance: false, uri: raw };
1580
+ }
1581
+ const cls = raw.match(/^urn:epc:class:lgtin:(.+)$/);
1582
+ if (cls) {
1583
+ const seg = cls[1].split(".");
1584
+ const lot = seg.slice(2).join(".");
1585
+ return {
1586
+ scheme: "lgtin",
1587
+ instance: false,
1588
+ gtinKey: seg.slice(0, 2).join("."),
1589
+ lot: lot ? decodeURIComponent(lot) : void 0,
1590
+ uri: raw
2488
1591
  };
2489
- const acVoltage = phases(r?.acVoltage, "acVoltage");
2490
- const acCurrent = phases(r?.acCurrent, "acCurrent");
2491
- if (acVoltage && acCurrent && acVoltage.length !== acCurrent.length) {
2492
- errors.push(`acVoltage(${acVoltage.length}\uC0C1)\uC640 acCurrent(${acCurrent.length}\uC0C1)\uC758 \uC0C1 \uC218\uAC00 \uB2E4\uB974\uB2E4`);
2493
- }
2494
- let position;
2495
- if (r?.position !== void 0 && r?.position !== null && r?.position !== "") {
2496
- const p = String(r.position);
2497
- if (!POSITIONS.has(p)) errors.push(`position \uC774 \uD45C\uC900 \uAC12\uC774 \uC544\uB2C8\uB2E4(open\xB7closed\xB7intermediate\xB7bad): ${JSON.stringify(r.position)}`);
2498
- else position = p;
2499
- }
2500
- const values = { generatedKW, exportKW, soc, chargeKW, dischargeKW, curtailable, minKW, position, dcVoltage, dcCurrent, acVoltage, acCurrent };
2501
- if (!errors.length && Object.values(values).every((v) => v === void 0)) {
2502
- errors.push("\uBC14\uAFC0 \uC0C1\uD0DC\uAC00 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uAC12 \uC5C6\uB294 \uBCF4\uACE0\uB294 \uC0AC\uC2E4\uB85C \uC801\uC744 \uAC83\uC774 \uC5C6\uB2E4");
2503
- }
2504
- if (errors.length) {
2505
- rejected.push({ record, errors });
2506
- continue;
2507
- }
2508
- const eventTime = new Date(atMs).toISOString();
2509
- const data = {
2510
- equipmentId,
2511
- at: eventTime,
2512
- ...generatedKW !== void 0 ? { generatedKW } : {},
2513
- ...exportKW !== void 0 ? { exportKW } : {},
2514
- ...soc !== void 0 ? { soc } : {},
2515
- ...chargeKW !== void 0 ? { chargeKW } : {},
2516
- ...dischargeKW !== void 0 ? { dischargeKW } : {},
2517
- ...curtailable !== void 0 ? { curtailable } : {},
2518
- ...minKW !== void 0 ? { minKW } : {},
2519
- ...position !== void 0 ? { position } : {},
2520
- ...dcVoltage !== void 0 ? { dcVoltage } : {},
2521
- ...dcCurrent !== void 0 ? { dcCurrent } : {},
2522
- ...acVoltage !== void 0 ? { acVoltage } : {},
2523
- ...acCurrent !== void 0 ? { acCurrent } : {}
1592
+ }
1593
+ const pat = raw.match(/^urn:epc:idpat:sgtin:(.+)$/);
1594
+ if (pat) {
1595
+ const seg = pat[1].split(".");
1596
+ return { scheme: "idpat", instance: false, gtinKey: seg.slice(0, 2).join("."), uri: raw };
1597
+ }
1598
+ const id = raw.match(/^urn:epc:id:([a-z]+):(.+)$/);
1599
+ if (id) {
1600
+ const scheme = id[1];
1601
+ const seg = id[2].split(".");
1602
+ const known = ["sgtin", "sscc", "gdti", "grai", "giai", "sgln"].includes(scheme);
1603
+ return {
1604
+ scheme: known ? scheme : "unknown",
1605
+ instance: true,
1606
+ ...scheme === "sgtin" ? { gtinKey: seg.slice(0, 2).join("."), serial: seg[2] } : { serial: seg.slice(1).join(".") },
1607
+ uri: raw
2524
1608
  };
2525
- accepted.push({
2526
- eventId: `${opts.tenantId}-energy-eq-${++seq}`,
2527
- eventType: ENERGY_EVENT.equipment,
2528
- eventTime,
2529
- tenantId: opts.tenantId,
2530
- data
2531
- });
2532
1609
  }
2533
- return { accepted, rejected };
1610
+ return { scheme: "unknown", instance: false, uri: raw };
2534
1611
  }
2535
- function isEnergyGenerationRecord(record) {
2536
- if (record?.from !== void 0 || record?.to !== void 0) return false;
2537
- if (!record || typeof record !== "object") return false;
2538
- const r = record;
2539
- return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.kWh !== void 0 && r.meterId === void 0 && r.epc === void 0;
1612
+ function decodedPair(item, lot) {
1613
+ if (!lot) return void 0;
1614
+ try {
1615
+ return [decodeURIComponent(item), decodeURIComponent(lot)];
1616
+ } catch {
1617
+ return void 0;
1618
+ }
2540
1619
  }
2541
- function ingestEnergyGenerationRecords(records, opts) {
2542
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2543
- const accepted = [];
2544
- const rejected = [];
2545
- let seq = 0;
2546
- for (const r of list) {
2547
- const errors = [];
2548
- const equipmentId = String(r?.equipmentId ?? "").trim();
2549
- if (!equipmentId) errors.push("equipmentId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC124\uBE44\uAC00 \uB9CC\uB4E0 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2550
- const STATE_FIELDS = ["generatedKW", "exportKW", "soc", "chargeKW", "dischargeKW", "curtailable", "minKW", "position"];
2551
- const alsoState = STATE_FIELDS.filter((f) => r?.[f] !== void 0);
2552
- if (alsoState.length) {
2553
- errors.push(
2554
- `\uC801\uC0B0\uACFC \uC124\uBE44 \uC0C1\uD0DC\uB97C \uD55C \uB808\uCF54\uB4DC\uC5D0 \uC2E4\uC5C8\uB2E4(${alsoState.join("\xB7")}) \u2014 \uC774 \uBB38\uC740 \uC801\uC0B0\uB9CC \uC77D\uC73C\uBBC0\uB85C \uADF8 \uAC12\uC774 \uC0AC\uB77C\uC9C4\uB2E4. \uAC08\uB77C \uBCF4\uB0BC \uAC83`
2555
- );
2556
- }
2557
- const raw = r?.kWh;
2558
- const kWh = Number(raw);
2559
- if (raw === void 0 || raw === null || !Number.isFinite(kWh)) {
2560
- errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uC801\uC0B0 \uD558\uB098\uB2E4(\uC21C\uC2DC \uCD9C\uB825\uC740 \uC124\uBE44 \uC0C1\uD0DC\uB85C \uBCF4\uB0B8\uB2E4)");
2561
- } else if (kWh < 0) {
2562
- errors.push(`kWh \uAC00 \uC74C\uC218\uB2E4(${kWh}) \u2014 \uC801\uC0B0\uC740 \uB4A4\uB85C \uAC00\uB354\uB77C\uB3C4 \uC74C\uC218\uAC00 \uB418\uC9C0 \uC54A\uB294\uB2E4`);
2563
- }
2564
- const eventTime = String(r?.at ?? "").trim() || opts.defaultEventTime || "";
2565
- if (!eventTime) errors.push("at \uC774 \uC5C6\uACE0 \uAE30\uBCF8 \uC2DC\uAC01\uB3C4 \uC8FC\uC9C0 \uC54A\uC558\uB2E4 \u2014 \uC5B8\uC81C \uC7B0 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2566
- let since;
2567
- const rawSince = r?.kWhSince;
2568
- if (rawSince !== void 0 && rawSince !== null && String(rawSince).trim()) {
2569
- const text = String(rawSince).trim();
2570
- const at2 = Date.parse(text);
2571
- if (!Number.isFinite(at2)) errors.push(`kWhSince \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(rawSince)}`);
2572
- else if (Number.isFinite(Date.parse(eventTime)) && at2 > Date.parse(eventTime)) {
2573
- errors.push(`kWhSince(${text}) \uAC00 \uC7B0 \uC2DC\uAC01(${eventTime})\uBCF4\uB2E4 \uB4A4\uB2E4 \u2014 \uB458 \uC911 \uD558\uB098\uAC00 \uD2C0\uB838\uB2E4`);
2574
- } else since = text;
2575
- }
2576
- const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
2577
- let accumulation;
2578
- const rawAcc = r?.kWhAccumulation;
2579
- if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
2580
- const text = String(rawAcc).trim();
2581
- if (!ACCUMULATIONS.includes(text)) {
2582
- errors.push(`kWhAccumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
2583
- } else accumulation = text;
2584
- }
2585
- if (errors.length) {
2586
- rejected.push({ record: r, errors });
2587
- continue;
1620
+ function itemClassOf(uri) {
1621
+ if (!uri) return void 0;
1622
+ const parsed = parseEpc(uri);
1623
+ if (parsed.scheme === "lgtin" && parsed.gtinKey) return `urn:epc:idpat:sgtin:${parsed.gtinKey}.*`;
1624
+ if (parsed.item !== void 0) {
1625
+ const marker = /^(.*(?:\/class\/|:class:))[^/:\s]+$/.exec(parsed.uri);
1626
+ if (marker) return `${marker[1]}${parsed.item.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c])}`;
1627
+ }
1628
+ return parsed.uri;
1629
+ }
1630
+ function lotClassOfItem(itemClass, lot) {
1631
+ if (!itemClass) return void 0;
1632
+ const idpat = /^urn:epc:idpat:sgtin:(\d+)\.(\d+)\.\*$/.exec(itemClass);
1633
+ if (idpat) return lotClassUri({ namespace: "", item: "", lot, gtin: `${idpat[1]}.${idpat[2]}` });
1634
+ const parsed = parseEpc(itemClass);
1635
+ if (parsed.instance || parsed.lot !== void 0) return void 0;
1636
+ const url = /^(https?:\/\/.+)\/class\/([^/:\s]+)$/.exec(itemClass);
1637
+ const urn = /^(urn:.+):class:([^/:\s]+)$/.exec(itemClass);
1638
+ const at2 = url ?? urn;
1639
+ if (!at2) return void 0;
1640
+ let item;
1641
+ try {
1642
+ item = decodeURIComponent(at2[2]);
1643
+ } catch {
1644
+ return void 0;
1645
+ }
1646
+ return lotClassUri({ namespace: at2[1], item, lot });
1647
+ }
1648
+ function sameItemClass(a, b) {
1649
+ const x = itemClassOf(a);
1650
+ return x !== void 0 && x === itemClassOf(b);
1651
+ }
1652
+ function gdtiUri(companyPrefix, docType, serial) {
1653
+ return `urn:epc:id:gdti:${companyPrefix}.${docType}.${serial}`;
1654
+ }
1655
+ function objectUri(namespace, objId) {
1656
+ return underNamespace(namespace, "obj", objId);
1657
+ }
1658
+ function classUri(namespace, classId) {
1659
+ return underNamespace(namespace, "class", classId);
1660
+ }
1661
+ function lotClassUri(input) {
1662
+ const item = String(input.item ?? "");
1663
+ const lot = String(input.lot ?? "");
1664
+ if (!lot) throw new Error(`lotClassUri: \uB85C\uD2B8\uAC00 \uBE44\uC5C8\uB2E4 \u2014 \uB85C\uD2B8 \uC5C6\uB294 \uD488\uBAA9\uC740 classUri \uB85C \uBD80\uB978\uB2E4 (item=${item})`);
1665
+ if (input.gtin !== void 0) {
1666
+ const [prefix, ref, ...rest] = String(input.gtin).split(".");
1667
+ if (!prefix || !ref || rest.length) {
1668
+ throw new Error(`lotClassUri: gtin \uC740 'CompanyPrefix.ItemRefAndIndicator' \uC5EC\uC57C \uD55C\uB2E4: ${input.gtin}`);
2588
1669
  }
2589
- const data = {
2590
- equipmentId,
2591
- kWh,
2592
- at: eventTime,
2593
- ...since ? { since } : {},
2594
- ...accumulation ? { accumulation } : {}
2595
- };
2596
- accepted.push({
2597
- eventId: `${opts.tenantId}-generated-${++seq}`,
2598
- eventType: ENERGY_EVENT.generated,
2599
- eventTime,
2600
- tenantId: opts.tenantId,
2601
- data
2602
- });
1670
+ const uri = lgtinClass(prefix, ref, lot);
1671
+ const wrong = gs1KeyDigitViolation(uri);
1672
+ if (wrong) throw new Error(`lotClassUri: ${wrong}`);
1673
+ return uri;
2603
1674
  }
2604
- return { accepted, rejected };
1675
+ if (!item) throw new Error(`lotClassUri: \uD488\uBC88\uC774 \uBE44\uC5C8\uB2E4 (lot=${lot})`);
1676
+ const enc = (v) => v.replace(LOT_COMPONENT_BREAKING, (c) => PERCENT_ENCODED[c]);
1677
+ return joinUnderNamespace(input.namespace, "class", `${enc(item)}${LOT_SEPARATOR}${enc(lot)}`);
1678
+ }
1679
+ var LOT_SEPARATOR = ";lot=";
1680
+ var LOT_COMPONENT_BREAKING = /[%/:?# ;]/g;
1681
+ function bizTransactionUri(namespace, transId) {
1682
+ return underNamespace(namespace, "bt", transId);
1683
+ }
1684
+ var STRUCTURE_BREAKING = /[%/:?# ]/g;
1685
+ var PERCENT_ENCODED = {
1686
+ "%": "%25",
1687
+ "/": "%2F",
1688
+ ":": "%3A",
1689
+ "?": "%3F",
1690
+ "#": "%23",
1691
+ " ": "%20",
1692
+ /* 로트 클래스의 가르는 글자 — `lotClassUri` 만 쓴다(§`LOT_COMPONENT_BREAKING`). 표는 한 벌이다. */
1693
+ ";": "%3B"
1694
+ };
1695
+ function underNamespace(namespace, marker, id) {
1696
+ const raw = String(id);
1697
+ if (!raw) return void 0;
1698
+ return joinUnderNamespace(namespace, marker, raw.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c]));
1699
+ }
1700
+ function joinUnderNamespace(namespace, marker, v) {
1701
+ const ns = namespace?.trim();
1702
+ if (!ns) return void 0;
1703
+ if (/^https?:\/\/[^/\s]+/.test(ns)) return `${ns.replace(/\/+$/, "")}/${marker}/${v}`;
1704
+ if (/^urn:epc(global)?:/.test(ns)) return void 0;
1705
+ if (/^urn:[^:\s]+/.test(ns)) return `${ns.replace(/:+$/, "")}:${marker}:${v}`;
1706
+ return void 0;
2605
1707
  }
2606
- function isEnergyUsagePeriodRecord(record) {
2607
- const r = record;
2608
- return !!r && typeof r === "object" && r.meterId !== void 0 && r.from !== void 0 && r.to !== void 0 && r.kWh !== void 0;
1708
+ function header(type, eventTime, bizStep, opts) {
1709
+ const h = {
1710
+ "@context": EPCIS_CONTEXT,
1711
+ type,
1712
+ eventTime,
1713
+ eventTimeZoneOffset: UTC_OFFSET,
1714
+ bizStep
1715
+ };
1716
+ if (opts?.eventID) h.eventID = opts.eventID;
1717
+ if (opts?.recordTime) h.recordTime = opts.recordTime;
1718
+ if (opts?.errorDeclaration) h.errorDeclaration = opts.errorDeclaration;
1719
+ if (opts?.bizTransactionList?.length) h.bizTransactionList = opts.bizTransactionList;
1720
+ if (opts?.ilmd) h.ilmd = opts.ilmd;
1721
+ if (opts?.sourceList) h.sourceList = opts.sourceList;
1722
+ if (opts?.destinationList) h.destinationList = opts.destinationList;
1723
+ if (opts?.persistentDisposition) h.persistentDisposition = opts.persistentDisposition;
1724
+ if (opts?.sensorElementList) h.sensorElementList = opts.sensorElementList;
1725
+ if (opts?.certificationInfo) h.certificationInfo = opts.certificationInfo;
1726
+ return h;
2609
1727
  }
2610
- function isEnergyGenerationPeriodRecord(record) {
2611
- const r = record;
2612
- if (!r || typeof r !== "object") return false;
2613
- if (r.equipmentId === void 0 || r.from === void 0 || r.to === void 0) return false;
2614
- return r.kWh !== void 0;
1728
+ function common(type, eventTime, action, bizStep, opts) {
1729
+ return { ...header(type, eventTime, bizStep, opts), action };
2615
1730
  }
2616
- function ingestEnergyGenerationPeriodRecords(records, opts) {
2617
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2618
- const accepted = [];
2619
- const rejected = [];
2620
- for (const r of list) {
2621
- const errors = [];
2622
- const equipmentId = String(r?.equipmentId ?? "").trim();
2623
- if (!equipmentId) errors.push("equipmentId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC124\uBE44\uAC00 \uB0B8 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2624
- const span = readSpan(r, errors);
2625
- const kWh = readAmount(r?.kWh, "kWh", errors);
2626
- if (kWh === void 0 && !errors.length) errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uADF8 \uAE30\uAC04\uC758 \uBC1C\uC804\uB7C9\uC774\uB2E4");
2627
- const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
2628
- let accumulation;
2629
- const rawAcc = r?.accumulation;
2630
- if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
2631
- const text = String(rawAcc).trim();
2632
- if (!ACCUMULATIONS.includes(text)) {
2633
- errors.push(`accumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
2634
- } else accumulation = text;
2635
- }
2636
- const readAt = (raw, name) => {
2637
- if (raw === void 0 || raw === null || !String(raw).trim()) return void 0;
2638
- const text = String(raw).trim();
2639
- if (!Number.isFinite(Date.parse(text))) {
2640
- errors.push(`${name} \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
2641
- return void 0;
2642
- }
2643
- return text;
2644
- };
2645
- const observedFrom = readAt(r?.observedFrom, "observedFrom");
2646
- const observedTo = readAt(r?.observedTo, "observedTo");
2647
- if (errors.length || !span || kWh === void 0) {
2648
- rejected.push({ record: r, errors });
2649
- continue;
2650
- }
2651
- const data = {
2652
- equipmentId,
2653
- kWh,
2654
- periodStart: span.from,
2655
- periodEnd: span.to,
2656
- /* 관측 구간을 말하지 않으면 기간 전체를 잰 것으로 둔다 — 지난 기록은 그 원본이 하루를 마감해 준 값이다. */
2657
- observedFrom: observedFrom ?? span.from,
2658
- observedTo: observedTo ?? span.to,
2659
- accumulation: accumulation ?? "daily",
2660
- /* 밖에서 마감되어 온 것이다 — 우리가 시각 기준으로 닫은 것이 아니다. */
2661
- boundary: "declared"
2662
- };
2663
- const subj = resolveSubject("equipment", equipmentId, opts);
2664
- data.subject = subj.subject;
2665
- data.subjectBasis = subj.basis;
2666
- const futureError = futureFactError(span.to, opts);
2667
- if (futureError) {
2668
- rejected.push({ record: r, errors: [futureError] });
2669
- continue;
2670
- }
2671
- accepted.push({
2672
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPeriod, subj.subject, span.from, span.to),
2673
- eventType: ENERGY_EVENT.generationPeriod,
2674
- eventTime: span.to,
2675
- tenantId: opts.tenantId,
2676
- data
2677
- });
2678
- }
2679
- return { accepted, rejected };
1731
+ function objectEvent(p) {
1732
+ const e = { ...common("ObjectEvent", p.eventTime, p.action, p.bizStep, p), epcList: p.epcList };
1733
+ if (p.disposition) e.disposition = p.disposition;
1734
+ if (p.quantityList) e.quantityList = p.quantityList;
1735
+ if (p.readPoint) e.readPoint = { id: p.readPoint };
1736
+ if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
1737
+ if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
1738
+ return e;
2680
1739
  }
2681
- function isEnergyGenerationPriceRecord(record) {
2682
- const r = record;
2683
- if (!r || typeof r !== "object") return false;
2684
- if (r.from === void 0 || r.to === void 0) return false;
2685
- if (r.meterId !== void 0 || r.equipmentId !== void 0) return false;
2686
- return r.unitPrice !== void 0;
1740
+ function aggregationEvent(p) {
1741
+ const e = { ...common("AggregationEvent", p.eventTime, p.action, p.bizStep, p), parentID: p.parentID };
1742
+ if (p.disposition) e.disposition = p.disposition;
1743
+ if (p.childEPCs) e.childEPCs = p.childEPCs;
1744
+ if (p.childQuantityList) e.childQuantityList = p.childQuantityList;
1745
+ if (p.readPoint) e.readPoint = { id: p.readPoint };
1746
+ if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
1747
+ return e;
2687
1748
  }
2688
- function ingestEnergyGenerationPriceRecords(records, opts) {
2689
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2690
- const accepted = [];
2691
- const rejected = [];
2692
- for (const r of list) {
2693
- const errors = [];
2694
- const span = readSpan(r, errors);
2695
- const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
2696
- if (unitPrice === void 0 && !errors.length) errors.push("unitPrice \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 1kWh \uB2F9 \uAC12 \uD558\uB098\uB2E4");
2697
- const currency = String(r?.currency ?? "").trim();
2698
- if (!currency) errors.push("currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAC12\uC740 \uB2E4\uB978 \uAE08\uC561\uACFC \uB354\uD560 \uC218 \uC5C6\uB2E4");
2699
- if (errors.length || !span || unitPrice === void 0) {
2700
- rejected.push({ record: r, errors });
2701
- continue;
2702
- }
2703
- const data = { from: span.from, to: span.to, unitPrice, currency };
2704
- accepted.push({
2705
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPrice, "", span.from, span.to),
2706
- eventType: ENERGY_EVENT.generationPrice,
2707
- eventTime: span.from,
2708
- tenantId: opts.tenantId,
2709
- data
2710
- });
1749
+ function transactionEvent(p) {
1750
+ const e = {
1751
+ ...common("TransactionEvent", p.eventTime, p.action, p.bizStep, p),
1752
+ bizTransactionList: p.bizTransactionList
1753
+ };
1754
+ if (p.disposition) e.disposition = p.disposition;
1755
+ if (p.parentID) e.parentID = p.parentID;
1756
+ if (p.epcList) e.epcList = p.epcList;
1757
+ if (p.quantityList) e.quantityList = p.quantityList;
1758
+ if (p.readPoint) e.readPoint = { id: p.readPoint };
1759
+ if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
1760
+ return e;
1761
+ }
1762
+ function transformationEvent(p) {
1763
+ const e = header("TransformationEvent", p.eventTime, p.bizStep, p);
1764
+ if (p.disposition) e.disposition = p.disposition;
1765
+ if (p.inputEPCList) e.inputEPCList = p.inputEPCList;
1766
+ if (p.inputQuantityList) e.inputQuantityList = p.inputQuantityList;
1767
+ if (p.outputEPCList) e.outputEPCList = p.outputEPCList;
1768
+ if (p.outputQuantityList) e.outputQuantityList = p.outputQuantityList;
1769
+ if (p.transformationID) e.transformationID = p.transformationID;
1770
+ if (p.readPoint) e.readPoint = { id: p.readPoint };
1771
+ if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
1772
+ if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
1773
+ return e;
1774
+ }
1775
+ var ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
1776
+ var TZ_RE = /^[+-]\d{2}:\d{2}$/;
1777
+ var ACTIONS = ["ADD", "OBSERVE", "DELETE"];
1778
+ var EPC_CLASS_PREFIXES = ["urn:epc:idpat:", "urn:epc:class:"];
1779
+ var DL_CANONICAL = "https://id.gs1.org/";
1780
+ var CBV_URL_CLASS = /^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)*class\/[^/\s]+$/;
1781
+ var CBV_URN_CLASS = /^urn:[^:\s]+:(?:[^:\s]+:)*class:[^:\s]+$/;
1782
+ var GS1_KEY_DIGITS = { sgtin: 13, lgtin: 13, sscc: 17, grai: 12, gdti: 12, sgln: 12 };
1783
+ function gs1KeyDigitViolation(uri) {
1784
+ if (!uri) return void 0;
1785
+ const m = /^urn:epc:(?:id|idpat|class):([a-z]+):([^:]+)$/.exec(uri);
1786
+ if (!m) return void 0;
1787
+ const want = GS1_KEY_DIGITS[m[1]];
1788
+ if (!want) return void 0;
1789
+ const parts = m[2].split(".");
1790
+ if (parts.length < 2) return `${m[1]} \uD615\uC2DD \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4\uC640 \uCC38\uC870\uAC00 '.' \uB85C \uAC08\uB824\uC57C \uD55C\uB2E4`;
1791
+ const [prefix, ref] = parts;
1792
+ if (ref === "*") return void 0;
1793
+ if (!/^\d+$/.test(prefix) || !/^\d+$/.test(ref)) {
1794
+ return `${m[1]} \uD615\uC2DD \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4\uC640 \uCC38\uC870\uB294 \uC22B\uC790\uB2E4`;
2711
1795
  }
2712
- return { accepted, rejected };
1796
+ const got = prefix.length + ref.length;
1797
+ if (got === want) return void 0;
1798
+ return `${m[1]} \uC790\uB9AC \uC218 \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4(${prefix.length}) + \uCC38\uC870(${ref.length}) = ${got} \uC774\uC9C0\uB9CC ${want} \uC5EC\uC57C \uD55C\uB2E4(GS1 TDS). \uD504\uB9AC\uD53D\uC2A4\uB97C \uBC14\uAFB8\uBA74 \uCC38\uC870 \uC790\uB9AC \uC218\uB97C \uD568\uAED8 \uB9DE\uCDB0\uC57C \uD55C\uB2E4.`;
2713
1799
  }
2714
- function isEnergyTariffBasisRecord(record) {
2715
- const r = record;
2716
- if (!r || typeof r !== "object") return false;
2717
- if (r.from === void 0 || r.to === void 0) return false;
2718
- if (r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0) return false;
2719
- return r.billingDemandKW !== void 0 || r.demandChargePerKW !== void 0;
1800
+ function classIdentifierViolation(epcClass) {
1801
+ if (!epcClass) return `quantity epcClass \uBD80\uC815: ${epcClass}`;
1802
+ const digits = gs1KeyDigitViolation(epcClass);
1803
+ if (digits) return `quantity epcClass \uBD80\uC815: ${digits}`;
1804
+ if (EPC_CLASS_PREFIXES.some((p) => epcClass.startsWith(p))) return void 0;
1805
+ if (epcClass.startsWith(DL_CANONICAL)) return void 0;
1806
+ if (CBV_URL_CLASS.test(epcClass) || CBV_URN_CLASS.test(epcClass)) return void 0;
1807
+ return `quantity epcClass \uBD80\uC815: ${epcClass} \u2014 \uD074\uB798\uC2A4 \uC2DD\uBCC4\uC790\uB294 \uC18C\uC720 \uAD8C\uD55C\uC744 \uB9D0\uD560 \uC218 \uC788\uB294 \uBAA8\uC591\uC774\uC5B4\uC57C \uD55C\uB2E4 (EPC \uD074\uB798\uC2A4 urn:epc:idpat:/urn:epc:class: \xB7 CBV \xA78.3.4 http(s)://<\uB3C4\uBA54\uC778>/**/class/<id> \xB7 CBV \xA78.3.3 urn:<\uC774\uB984\uACF5\uAC04>:**:class:<id>)`;
2720
1808
  }
2721
- function ingestEnergyTariffBasisRecords(records, opts) {
2722
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2723
- const accepted = [];
2724
- const rejected = [];
2725
- for (const r of list) {
2726
- const errors = [];
2727
- const span = readSpan(r, errors);
2728
- const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
2729
- const demandChargePerKW = readAmount(r?.demandChargePerKW, "demandChargePerKW", errors);
2730
- if (billingDemandKW === void 0 && demandChargePerKW === void 0) {
2731
- errors.push("\uC694\uAE08 \uAE30\uC900\uC774 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uC801\uC744 \uC0AC\uC2E4\uC774 \uC5C6\uB294 \uAE30\uC900\uC740 \uBC1B\uC9C0 \uC54A\uB294\uB2E4");
1809
+ function validateEpcisEvent(e) {
1810
+ const v = [];
1811
+ for (const [field, list] of [
1812
+ ["epcList", e.epcList],
1813
+ ["childEPCs", e.childEPCs],
1814
+ ["inputEPCList", e.inputEPCList],
1815
+ ["outputEPCList", e.outputEPCList],
1816
+ ["parentID", e.parentID ? [e.parentID] : void 0]
1817
+ ]) {
1818
+ for (const epc of list ?? []) {
1819
+ const bad2 = gs1KeyDigitViolation(epc);
1820
+ if (bad2) v.push(`${field}: ${bad2}`);
1821
+ }
1822
+ }
1823
+ if (e["@context"] !== EPCIS_CONTEXT) v.push("@context \uB204\uB77D/\uBD88\uC77C\uCE58");
1824
+ if (!["ObjectEvent", "AggregationEvent", "TransactionEvent", "TransformationEvent"].includes(e.type)) v.push(`\uC54C \uC218 \uC5C6\uB294 type: ${e.type}`);
1825
+ if (typeof e.eventTime !== "string" || !ISO_RE.test(e.eventTime)) v.push("eventTime ISO8601 \uC544\uB2D8");
1826
+ if (typeof e.eventTimeZoneOffset !== "string" || !TZ_RE.test(e.eventTimeZoneOffset)) v.push("eventTimeZoneOffset \uD615\uC2DD \uC624\uB958");
1827
+ if (typeof e.bizStep !== "string" || !e.bizStep) v.push("bizStep \uB204\uB77D");
1828
+ if (e.eventID !== void 0 && (typeof e.eventID !== "string" || !e.eventID)) v.push("eventID \uAC00 \uBE48 \uBB38\uC790\uC5F4");
1829
+ if (e.recordTime !== void 0 && (typeof e.recordTime !== "string" || !ISO_RE.test(e.recordTime))) {
1830
+ v.push("recordTime ISO8601 \uC544\uB2D8");
1831
+ }
1832
+ if (e.ilmd !== void 0) {
1833
+ const allowed = e.type === "ObjectEvent" && e.action === "ADD" || e.type === "TransformationEvent";
1834
+ if (!allowed) v.push("ilmd \uB294 ObjectEvent(action=ADD) \uB610\uB294 TransformationEvent \uC5D0\uB9CC \uC2E4\uC744 \uC218 \uC788\uB2E4");
1835
+ }
1836
+ for (const sd of e.sourceList ?? []) {
1837
+ if (!sd?.type || !sd?.source) v.push("sourceList \uD56D\uBAA9\uC5D0 type \uB610\uB294 source \uB204\uB77D");
1838
+ }
1839
+ for (const sd of e.destinationList ?? []) {
1840
+ if (!sd?.type || !sd?.destination) v.push("destinationList \uD56D\uBAA9\uC5D0 type \uB610\uB294 destination \uB204\uB77D");
1841
+ }
1842
+ if (e.persistentDisposition !== void 0) {
1843
+ const set = e.persistentDisposition.set ?? [];
1844
+ const unset = e.persistentDisposition.unset ?? [];
1845
+ if (!set.length && !unset.length) v.push("persistentDisposition \uC774 set\xB7unset \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
1846
+ const both = set.filter((x) => unset.includes(x));
1847
+ if (both.length) v.push(`persistentDisposition \uC774 \uAC19\uC740 \uAC12\uC744 set\xB7unset \uB3D9\uC2DC \uC9C0\uC815: ${both.join(", ")}`);
1848
+ }
1849
+ for (const se of e.sensorElementList ?? []) {
1850
+ if (!Array.isArray(se?.sensorReport) || se.sensorReport.length === 0) {
1851
+ v.push("sensorElement \uC5D0 sensorReport \uAC00 \uD558\uB098\uB3C4 \uC5C6\uC74C");
2732
1852
  }
2733
- const currency = String(r?.currency ?? "").trim() || void 0;
2734
- if (demandChargePerKW !== void 0 && !currency) errors.push("demandChargePerKW \uB97C \uC2E4\uC5C8\uB294\uB370 currency \uAC00 \uC5C6\uB2E4");
2735
- if (r?.demandCharge !== void 0 || r?.total !== void 0) {
2736
- errors.push("\uAE08\uC561(demandCharge\xB7total)\uC740 \uC774 \uBB38\uC774 \uBC1B\uC9C0 \uC54A\uB294\uB2E4 \u2014 \uC815\uC0B0 \uAE08\uC561\uC740 \uCCAD\uAD6C\uC11C \uBB38\uC73C\uB85C \uBCF4\uB0B8\uB2E4");
1853
+ }
1854
+ if (e.errorDeclaration !== void 0) {
1855
+ const d = e.errorDeclaration;
1856
+ if (typeof d?.declarationTime !== "string" || !ISO_RE.test(d.declarationTime)) {
1857
+ v.push("errorDeclaration.declarationTime ISO8601 \uC544\uB2D8/\uB204\uB77D");
2737
1858
  }
2738
- if (errors.length || !span) {
2739
- rejected.push({ record: r, errors });
1859
+ if (d?.correctiveEventIDs !== void 0) {
1860
+ if (!Array.isArray(d.correctiveEventIDs)) v.push("errorDeclaration.correctiveEventIDs \uBC30\uC5F4 \uC544\uB2D8");
1861
+ else if (d.correctiveEventIDs.some((x) => typeof x !== "string" || !x)) {
1862
+ v.push("errorDeclaration.correctiveEventIDs \uC5D0 \uBE48 \uAC12");
1863
+ }
1864
+ }
1865
+ }
1866
+ if (e.type === "ObjectEvent") {
1867
+ if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
1868
+ if (!Array.isArray(e.epcList)) v.push("ObjectEvent.epcList \uB204\uB77D");
1869
+ else if (e.epcList.length === 0 && !e.quantityList?.length) v.push("ObjectEvent: epcList/quantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
1870
+ } else if (e.type === "AggregationEvent") {
1871
+ if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
1872
+ if (!e.parentID) v.push("AggregationEvent.parentID \uB204\uB77D");
1873
+ if (!e.childEPCs?.length && !e.childQuantityList?.length) v.push("AggregationEvent: childEPCs/childQuantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
1874
+ } else if (e.type === "TransactionEvent") {
1875
+ if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
1876
+ if (!Array.isArray(e.bizTransactionList) || e.bizTransactionList.length === 0) v.push("TransactionEvent.bizTransactionList \uB204\uB77D");
1877
+ } else if (e.type === "TransformationEvent") {
1878
+ if (!e.inputEPCList?.length && !e.inputQuantityList?.length) v.push("TransformationEvent: input \uBE44\uC5B4\uC788\uC74C");
1879
+ if (!e.outputEPCList?.length && !e.outputQuantityList?.length) v.push("TransformationEvent: output \uBE44\uC5B4\uC788\uC74C");
1880
+ }
1881
+ const qtyLists = [
1882
+ "quantityList" in e ? e.quantityList : void 0,
1883
+ "childQuantityList" in e ? e.childQuantityList : void 0,
1884
+ "inputQuantityList" in e ? e.inputQuantityList : void 0,
1885
+ "outputQuantityList" in e ? e.outputQuantityList : void 0
1886
+ ];
1887
+ for (const list of qtyLists) for (const q of list ?? []) {
1888
+ const bad2 = classIdentifierViolation(q.epcClass);
1889
+ if (bad2) v.push(bad2);
1890
+ const hasQty = q.quantity !== void 0 && q.quantity !== null;
1891
+ if (!hasQty) {
1892
+ if (q.uom !== void 0) v.push("quantity \uC5C6\uC73C\uBA74 uom \uB3C4 \uC5C6\uC5B4\uC57C \uD55C\uB2E4(\uC218\uB7C9 \uBBF8\uC9C0\uC815)");
2740
1893
  continue;
2741
1894
  }
2742
- const data = {
2743
- from: span.from,
2744
- to: span.to,
2745
- ...billingDemandKW !== void 0 ? { billingDemandKW } : {},
2746
- ...demandChargePerKW !== void 0 ? { demandChargePerKW } : {},
2747
- ...currency ? { currency } : {}
2748
- };
2749
- accepted.push({
2750
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.tariffBasis, "", span.from, span.to),
2751
- eventType: ENERGY_EVENT.tariffBasis,
2752
- /* **시작 시각**이다 — 그때부터 유효하다(§ 위 주석). */
2753
- eventTime: span.from,
2754
- tenantId: opts.tenantId,
2755
- data
2756
- });
1895
+ if (typeof q.quantity !== "number" || !Number.isFinite(q.quantity) || q.quantity <= 0) {
1896
+ v.push("quantity \uB294 \uC591\uC218\uC5EC\uC57C \uD55C\uB2E4(\uBAA8\uB974\uBA74 \uC0DD\uB7B5)");
1897
+ continue;
1898
+ }
1899
+ if (q.uom === void 0 && !Number.isInteger(q.quantity)) v.push("uom \uC5C6\uB294 quantity \uB294 \uC815\uC218(\uAC1C\uC218)\uC5EC\uC57C \uD55C\uB2E4");
1900
+ if (q.uom !== void 0 && !/^[A-Z0-9]{2,3}$/.test(q.uom)) v.push(`uom \uD615\uC2DD \uBD80\uC815(UN/CEFACT \uAD8C\uACE0 20 \uC758 2~3\uC790 \uCF54\uB4DC): ${q.uom}`);
2757
1901
  }
2758
- return { accepted, rejected };
2759
- }
2760
- function isEnergyBillRecord(record) {
2761
- const r = record;
2762
- if (!r || typeof r !== "object") return false;
2763
- if (r.from === void 0 || r.to === void 0) return false;
2764
- return r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0;
2765
- }
2766
- function futureFactError(eventTime, opts) {
2767
- const nowText = opts.nowISO ?? opts.defaultEventTime;
2768
- if (!nowText) return void 0;
2769
- const nowMs = Date.parse(nowText);
2770
- const atMs = Date.parse(eventTime);
2771
- if (!Number.isFinite(nowMs) || !Number.isFinite(atMs) || atMs <= nowMs) return void 0;
2772
- return `\uC544\uC9C1 \uC624\uC9C0 \uC54A\uC740 \uC2DC\uAC01\uC758 \uC0AC\uC2E4\uC774\uB2E4(${eventTime}) \u2014 \uB05D\uB098\uC9C0 \uC54A\uC740 \uAE30\uAC04\uC740 \uB9C8\uAC10\uB41C \uC0AC\uC2E4\uC774 \uC544\uB2C8\uB2E4`;
2773
- }
2774
- function resolveSubject(kind, localId, opts) {
2775
- const declared = opts.identityOf?.(kind, localId);
2776
- if (declared) return { subject: declared, basis: "declared" };
2777
- return { subject: opts.scopeId ? `${opts.scopeId}/${localId}` : localId, basis: "twin-local" };
1902
+ return v;
2778
1903
  }
2779
- function periodFactId(tenantId, kind, subject, from, to) {
2780
- return [tenantId, kind, subject, from, to].join("|");
1904
+
1905
+ // src/yms-profile.ts
1906
+ var YARD_BIZSTEP = {
1907
+ arriving: "urn:epcglobal:cbv:bizstep:arriving",
1908
+ // 게이트-인
1909
+ loading: "urn:epcglobal:cbv:bizstep:loading",
1910
+ // 도크 작업(상차: 트레일러←화물)
1911
+ unloading: "urn:epcglobal:cbv:bizstep:unloading",
1912
+ // 도크 작업(하차: 트레일러→화물)
1913
+ departing: "urn:epcglobal:cbv:bizstep:departing"
1914
+ // 게이트-아웃
1915
+ };
1916
+ var YARD_PRIVATE_BIZSTEP = {
1917
+ staging: `${HATIOLAB_VOCABULARY}bizstep/staging`
1918
+ // 야드 슬롯 주차·대기
1919
+ };
1920
+ function graiUri(companyPrefix, assetType, serial) {
1921
+ return `urn:epc:id:grai:${companyPrefix}.${assetType}.${String(serial).padStart(6, "0")}`;
2781
1922
  }
2782
- function readSpan(r, errors) {
2783
- const from = String(r?.from ?? "").trim();
2784
- const to = String(r?.to ?? "").trim();
2785
- const fromMs = Date.parse(from);
2786
- const toMs = Date.parse(to);
2787
- if (!from || !Number.isFinite(fromMs)) errors.push(`from \uC744 \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.from)}`);
2788
- if (!to || !Number.isFinite(toMs)) errors.push(`to \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.to)}`);
2789
- if (Number.isFinite(fromMs) && Number.isFinite(toMs) && !(toMs > fromMs)) {
2790
- errors.push(`\uAD6C\uAC04\uC774 \uB4A4\uC9D1\uD614\uAC70\uB098 \uAE38\uC774\uAC00 \uC5C6\uB2E4(${from} \u2192 ${to}) \u2014 \uC5B4\uB290 \uCABD\uC774 \uD2C0\uB838\uB294\uC9C0 \uC6B0\uB9AC\uAC00 \uC815\uD560 \uC218 \uC5C6\uB2E4`);
2791
- }
2792
- return errors.length ? void 0 : { from, to };
1923
+ var YMS_LOCATION_TYPES = ["gate", "yard-slot", "dock-door", "staging"];
1924
+ var YMS_LOCATION_LEVEL = {
1925
+ gate: "Other",
1926
+ "yard-slot": "StorageUnit",
1927
+ "dock-door": "StorageUnit",
1928
+ staging: "StorageZone"
1929
+ };
1930
+ var YMS_TYPES = [
1931
+ ...YMS_LOCATION_TYPES.map((k) => ({ key: k, role: "location", label: `twin.type.${k}`, standardClass: { epcis: "bizLocation" }, identity: { scheme: "gs1:SGLN" }, level: YMS_LOCATION_LEVEL[k], capabilities: ["storable"] })),
1932
+ { key: "hostler", role: "equipment", label: "twin.type.hostler", standardClass: { epcis: "object", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["mobile", "operable"] }
1933
+ ];
1934
+
1935
+ // src/mes-profile.ts
1936
+ var MES_BIZSTEP = {
1937
+ receiving: "urn:epcglobal:cbv:bizstep:receiving",
1938
+ // 원자재 수령
1939
+ producing: "urn:epcglobal:cbv:bizstep:commissioning",
1940
+ // 생산(제품 최초 생성)
1941
+ storing: "urn:epcglobal:cbv:bizstep:storing"
1942
+ // 완제품 저장
1943
+ };
1944
+ var BTT_PRODORDER = "urn:epcglobal:cbv:btt:prodorder";
1945
+ function sgtinUri(companyPrefix, itemRef, serial) {
1946
+ return `urn:epc:id:sgtin:${companyPrefix}.${itemRef}.${serial}`;
2793
1947
  }
2794
- function readAmount(raw, name, errors) {
2795
- if (raw === void 0 || raw === null || String(raw).trim() === "") return void 0;
2796
- const v = Number(raw);
2797
- if (!Number.isFinite(v)) {
2798
- errors.push(`${name} \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
2799
- return void 0;
1948
+ var MES_LOCATION_TYPES = ["raw-store", "cut-station", "weld-station", "paint-booth", "assembly-line", "fg-store"];
1949
+ var MES_LOCATION_CLS = {
1950
+ "raw-store": { epcis: "bizLocation" },
1951
+ "cut-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1952
+ "weld-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1953
+ "paint-booth": { isa95: "WorkCenter", epcis: "bizLocation" },
1954
+ "assembly-line": { isa95: "WorkCenter", epcis: "bizLocation" },
1955
+ "fg-store": { epcis: "bizLocation" }
1956
+ };
1957
+ var MES_LOCATION_LEVEL = {
1958
+ "raw-store": "StorageZone",
1959
+ "cut-station": "WorkCell",
1960
+ "weld-station": "WorkCell",
1961
+ "paint-booth": "WorkCell",
1962
+ "assembly-line": "ProductionLine",
1963
+ "fg-store": "StorageZone"
1964
+ };
1965
+ var MES_TYPES = [
1966
+ ...MES_LOCATION_TYPES.map((k) => ({ key: k, role: "location", label: `twin.type.${k}`, standardClass: MES_LOCATION_CLS[k] ?? {}, identity: { scheme: "gs1:SGLN" }, level: MES_LOCATION_LEVEL[k], capabilities: ["storable"] })),
1967
+ { key: "cutter", role: "equipment", label: "twin.type.cutter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1968
+ { key: "welder", role: "equipment", label: "twin.type.welder", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1969
+ { key: "painter", role: "equipment", label: "twin.type.painter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1970
+ { key: "assembler", role: "equipment", label: "twin.type.assembler", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] }
1971
+ ];
1972
+ var MES_COMMANDS = [
1973
+ {
1974
+ type: "production.order",
1975
+ label: "\uC0DD\uC0B0 \uC9C0\uC2DC",
1976
+ /*
1977
+ * 되돌릴 수 없다. 지시가 나가면 사람과 설비가 그것으로 움직이고, 취소해도 이미 만든 것은 남는다.
1978
+ * 그래서 사람 승인을 지난다(§`requiresApproval`).
1979
+ */
1980
+ reversible: false,
1981
+ /*
1982
+ * 단위를 요구하는 이유 — 단위 없는 수량은 지시가 되지 못한다. 우리가 기본 단위를 지어내면 그것이
1983
+ * 현장의 단위와 다른 날 수량이 조용히 틀린다.
1984
+ */
1985
+ required: ["materialDefinitionId", "quantity", "uom"]
2800
1986
  }
2801
- if (v < 0) {
2802
- errors.push(`${name} \uAC00 \uC74C\uC218\uB2E4(${v})`);
2803
- return void 0;
1987
+ ];
1988
+
1989
+ // src/ems-profile.ts
1990
+ var EMS_LOCATION_TYPES = ["incoming", "feeder", "submeter-zone"];
1991
+ var METER_DIRECTION = ["import", "export", "bidirectional"];
1992
+ var EMS_EQUIPMENT_TYPES = ["meter", "breaker", "pv-array", "battery", "utility", "curtailable-load"];
1993
+ var EMS_PROPERTY = {
1994
+ /** 계약전력(kW) — 수전·분기 자리에 선언한다. 없으면 계약 대비 판정을 하지 않는다. */
1995
+ contractKW: "contract.kW",
1996
+ /*
1997
+ * ── 계량 지점의 방향 (2026-08-25) ──────────────────────────────────────────
1998
+ * **요금은 계통 접속점의 순 유입에 매겨진다.** 그러니 그 지점의 계량기가 무엇을 재는지 모르면
1999
+ * 요금을 사실대로 말할 수 없다 — 내보낸 양을 쓴 양으로 세면 계약 대비 판단이 반대로 뒤집힌다.
2000
+ *
2001
+ * 이 축이 없는 동안 계량 지점의 kW 를 전부 부하로 셌다. 상계 거래를 하는 현장, 축전지를 붙인 현장,
2002
+ * 열병합이 있는 현장 — 접속점 계량기가 양쪽을 재는 곳은 늘 있다.
2003
+ *
2004
+ * **발전기를 계량기로 만드는 것과 다른 일이다.** 발전은 설비의 사실이고(`energyGenerating`), 그것을
2005
+ * 계량 지점으로 보내는 것은 여전히 하지 않는다. 이 축은 **접속점 계량기**가 무엇을 재는지 말하는
2006
+ * 자리다.
2007
+ *
2008
+ * 방향은 **관측이 아니라 선언**이다. 표본마다 바뀌는 값이 아니고, 그 계량기가 무엇을 재도록
2009
+ * 설치되었는지는 현장이 안다. 그래서 표본(`EnergyRecord`)에 넣지 않고 자원 속성으로 둔다.
2010
+ *
2011
+ * 값은 계량기 자신의 낱말을 쓴다(적산 레지스터가 그렇게 갈려 있다). §`METER_DIRECTION`.
2012
+ */
2013
+ meterDirection: "meter.direction",
2014
+ /*
2015
+ * ── 부하 계수 — 시뮬레이션이 전기를 만들 수 있게 (2026-08-14) ───────────────
2016
+ * 「이 설비가 돌면 몇 kW 인가」는 **현장이 아는 값**이다. 그래서 타입 기본값을 두지 않는다:
2017
+ * 선언하지 않은 설비는 부하를 만들지 않는다. 기본값을 두면 아무도 그 수가 짐작인 줄 모른 채
2018
+ * 요금 판정이 그 위에 선다.
2019
+ */
2020
+ /** 가동 중 소비(kW). */
2021
+ ratedKW: "power.ratedKW",
2022
+ /** 멈춰 있을 때의 소비(kW). 없으면 멈춘 동안을 **비운다** — 0 이라고 주장하지 않는다. */
2023
+ standbyKW: "power.standbyKW",
2024
+ /*
2025
+ * ── 요금 단가 — 수를 금액으로 바꾸는 선언 (2026-08-17) ─────────────────────
2026
+ *
2027
+ * 그동안 트윈은 「최대수요 328kW」·「전력량 1,547kWh」까지 말하고 멈췄다. 그런데 피크를 깎는 일이
2028
+ * 돈이 되는 이유는 **요금이 둘로 나뉘기** 때문이다: 사용량(kWh)에 붙는 요금과 **최대수요(kW)에 붙는
2029
+ * 기본요금**. 단가가 없으면 그 절반을 말할 수 없고, 그래서 「피크를 깎아 얼마를 아끼나」에 답하지 못했다.
2030
+ *
2031
+ * 단가는 **현장의 계약**이다(같은 나라 안에서도 사업자·요금제마다 다르다). 그래서 기본값을 두지
2032
+ * 않는다 — 선언하지 않으면 금액을 계산하지 않는다. 짐작한 단가로 낸 금액은 숫자가 있다는 것만으로
2033
+ * 사람을 결정으로 밀어붙인다.
2034
+ *
2035
+ * 계약전력(`contract.kW`)과 같은 자리(수전)에 선언한다.
2036
+ */
2037
+ /** 기본요금 단가 — 최대수요 1kW 당(청구 주기 기준). */
2038
+ demandChargePerKW: "tariff.demandChargePerKW",
2039
+ /**
2040
+ * **요금적용전력**(kW) — 기본요금이 실제로 매겨지는 기준. 계약전력과 다른 값이다.
2041
+ *
2042
+ * 기본요금이 걸리는 수는 이 주기에 잰 최대가 아닌 경우가 많다 — 지난 몇 달의 최고를 끌고 가거나,
2043
+ * 약정 용량으로 매기거나, 사업자가 따로 정한다. 그 규칙은 나라와 계약마다 다르므로 커널이 계산하지
2044
+ * 않고 **계산된 결과를 받는다.** 이 값이 있으면 기본요금이 조건부 파생이 아니라 사실이 된다.
2045
+ *
2046
+ * 계약전력(`contract.kW`)을 이 자리에 넣지 말 것. 넘었을 때의 뜻이 다르다 — 계약 초과는 약정
2047
+ * 위반이고, 이쪽은 다음 주기의 기본요금이 오른다는 뜻이다.
2048
+ */
2049
+ billingDemandKW: "tariff.billingDemandKW",
2050
+ /** 사용량 단가 — 1kWh 당. */
2051
+ energyChargePerKWh: "tariff.energyChargePerKWh",
2052
+ /** 통화 — ISO 4217 코드(USD·KRW…). 없으면 금액에 단위를 붙이지 않는다. */
2053
+ currency: "tariff.currency",
2054
+ /*
2055
+ * ── 축전지의 용량과 방전 정책 (2026-08-17) ─────────────────────────────────
2056
+ *
2057
+ * 「배터리로 피크를 깎는다」를 시뮬이 보이려면 방전을 만들어야 하고, 그것은 **선언에서** 나와야 한다.
2058
+ * 임계·최대율·예비를 우리가 정하면 그 수가 어디서 왔는지 아무도 설명할 수 없다.
2059
+ *
2060
+ * ── 선언한다는 것은 「그 자동화가 있다」는 주장이다 ─────────────────────────
2061
+ * 이 정책을 모델에 적으면 **라이브가 아닌 모든 구동이 그 규칙으로 돈다.** 현장에 BESS 제어기가 없는데
2062
+ * 적으면 파생 부하가 실제보다 낙관적으로 나온다(피크가 깎인 것으로 보인다). 그러니 「도입하면?」을
2063
+ * 묻는 것이라면 선언이 아니라 **what-if 가 덮어쓸 일**이다.
2064
+ *
2065
+ * 용량이 없으면 방전하지 않는다 — 용량을 모르면 「얼마나 버티나」를 답할 수 없고, 버티는 시간을
2066
+ * 모른 채 깎으면 무한히 깎을 수 있다고 주장하는 셈이다.
2067
+ */
2068
+ /** 축전지 용량(kWh) — SOC 를 에너지로 바꾸는 값. 없으면 방전을 만들지 않는다. */
2069
+ capacityKWh: "storage.capacityKWh",
2070
+ /** 이 순수요를 넘으면 방전한다(kW) — 피크 억제 임계. */
2071
+ dischargeAboveKW: "dispatch.dischargeAboveKW",
2072
+ /** 최대 방전율(kW) — 인버터가 낼 수 있는 한계. */
2073
+ maxDischargeKW: "dispatch.maxDischargeKW",
2074
+ /** 예비 SOC(%) — 이 아래로는 쓰지 않는다(비상 대비). 없으면 0 으로 본다. */
2075
+ reserveSoc: "dispatch.reserveSoc",
2076
+ /**
2077
+ * 시뮬레이션이 **출발할 때의 SOC(%)** — 씨앗값이다.
2078
+ *
2079
+ * 계측이 SOC 를 알려 주는 트윈에는 필요 없다(잰 값이 진실이다). 시뮬 트윈에는 알려 줄 것이 없어서
2080
+ * 「SOC 를 모르면 방전하지 않는다」는 규율에 걸려 **배터리가 아무 일도 하지 못했다** — 정책을 선언해도
2081
+ * 피크가 한 톨도 깎이지 않았다(실화면에서 그렇게 났다).
2082
+ *
2083
+ * 이것은 상태의 씨앗이지 계측이 아니다. 그래서 계측이 들어오는 순간 그것이 이긴다.
2084
+ */
2085
+ initialSoc: "storage.initialSoc",
2086
+ /*
2087
+ * ── 발전 — 태양광이 서 있기만 하던 자리 (2026-08-18) ────────────────────────
2088
+ *
2089
+ * 계통도에 태양광을 그려 놓고 시뮬에서는 한 톨도 만들지 못했다. 미러는 원천이 발전량을 보내 주지만,
2090
+ * 시뮬 트윈에는 그것을 만들 근거가 없었다 — 그래서 「태양광을 늘리면 피크가 얼마나 내려가나」를 물을 수
2091
+ * 없었다(what-if 의 값이 절반만 성립했다).
2092
+ *
2093
+ * **형상을 우리가 지어내지 않는다.** 위도·계절·날씨로 곡선을 만들면 그 수가 어디서 왔는지 아무도
2094
+ * 설명할 수 없고, 흐린 날 현장의 실적과 어긋난다. 그래서 현장이 **하루 형상을 적는다**: 24개 비율
2095
+ * (0~1)이면 그것이 그 현장의 곡선이다(측정한 형상을 그대로 붙일 수 있다).
2096
+ *
2097
+ * 정격만 있고 형상이 없으면 발전하지 않는다 — 하루 종일 정격으로 발전하는 태양광은 없다.
2098
+ */
2099
+ /**
2100
+ * 발전 정격(kW) — **교류 쪽 최대 출력**. 계통으로 나가는 값이다.
2101
+ *
2102
+ * 이용률의 분모가 이 값이다(만든 양 ÷ 정격 × 시간). **직류 쪽 정격(§`genRatedKWdc`)과 다르고 더 작다** —
2103
+ * 두 값을 한 이름에 담으면 이용률이 그 차이만큼 틀리고, 틀린 이유가 아무 데도 표시되지 않는다.
2104
+ *
2105
+ * 설비마다 선언하거나, 설비별 값을 모르는 현장은 **자리(수전)에 합계로** 선언한다.
2106
+ */
2107
+ genRatedKW: "generation.ratedKW",
2108
+ /**
2109
+ * 발전 정격(kW) — **직류 쪽**. 변환기(인버터)의 입력 쪽 정격이고, 태양광이면 패널 정격의 합이다.
2110
+ *
2111
+ * 이용률의 분모로 쓰지 않는다. 이 값이 교류 정격보다 큰 것은 설계이고(변환기를 그렇게 고른다),
2112
+ * 그 차이가 「맑은 정오에도 교류 출력이 더 오르지 않는 이유」를 설명한다.
2113
+ */
2114
+ genRatedKWdc: "generation.ratedKWdc",
2115
+ /**
2116
+ * 하루 형상 — 쉼표로 나눈 **24개 비율**(0~1). 시각(현장 시간대)의 정격 대비 출력이다.
2117
+ *
2118
+ * 예: `0,0,0,0,0,0,0.05,0.2,0.45,0.7,0.9,1,1,0.95,0.8,0.6,0.35,0.12,0.02,0,0,0,0,0`
2119
+ */
2120
+ genDailyProfile: "generation.dailyProfile"
2121
+ };
2122
+ var EMS_PROPERTY_SPEC = {
2123
+ [EMS_PROPERTY.contractKW]: { uom: "kW", dataType: "xs:double", note: "contracted power at the metering point, in kW." },
2124
+ /* 값이 셋 중 하나여야 한다 — 그 밖의 낱말은 받지 않는다(뜻이 통할 것 같은 말도 받지 않는다). */
2125
+ [EMS_PROPERTY.meterDirection]: {
2126
+ dataType: "xs:string",
2127
+ note: 'what this metering point measures: "import" (drawn from the grid), "export" (generation sent out), or "bidirectional" (one meter for both, sign carries the direction). Left undeclared, the point counts as load \u2014 leaving it out never makes demand look smaller than it is.'
2128
+ },
2129
+ [EMS_PROPERTY.ratedKW]: { uom: "kW", dataType: "xs:double", note: "power drawn while running, in kW." },
2130
+ [EMS_PROPERTY.standbyKW]: { uom: "kW", dataType: "xs:double", note: "power drawn while idle, in kW." },
2131
+ [EMS_PROPERTY.demandChargePerKW]: { dataType: "xs:double", note: "demand charge per kW of billing-period peak, in the declared currency." },
2132
+ [EMS_PROPERTY.billingDemandKW]: {
2133
+ uom: "kW",
2134
+ dataType: "xs:double",
2135
+ note: "billing demand in kW \u2014 the basis the demand charge is actually billed on (often a rolling 12-month peak). Not the contracted power."
2136
+ },
2137
+ [EMS_PROPERTY.energyChargePerKWh]: { dataType: "xs:double", note: "energy charge per kWh, in the declared currency." },
2138
+ [EMS_PROPERTY.currency]: { dataType: "xs:string", note: "ISO 4217 currency code, e.g. USD or KRW." },
2139
+ [EMS_PROPERTY.capacityKWh]: { uom: "kWh", dataType: "xs:double", note: "usable energy of the storage, in kWh." },
2140
+ [EMS_PROPERTY.dischargeAboveKW]: { uom: "kW", dataType: "xs:double", note: "net demand above which the storage discharges, in kW." },
2141
+ [EMS_PROPERTY.maxDischargeKW]: { uom: "kW", dataType: "xs:double", note: "inverter limit on discharge rate, in kW." },
2142
+ /* 퍼센트다 — 0.8 은 0.8% 이고 80% 가 아니다. 이 한 줄이 없어서 배터리가 조용히 비어 있었다. */
2143
+ [EMS_PROPERTY.reserveSoc]: { uom: "%", dataType: "xs:double", range: [0, 100], note: "reserve state of charge as a percentage 0-100 (20 means 20%), never discharged below." },
2144
+ [EMS_PROPERTY.initialSoc]: { uom: "%", dataType: "xs:double", range: [0, 100], note: "starting state of charge as a percentage 0-100 (80 means 80%, not 0.8)." },
2145
+ [EMS_PROPERTY.genRatedKW]: {
2146
+ uom: "kW",
2147
+ dataType: "xs:double",
2148
+ note: "rated AC generation output, in kW \u2014 the denominator of capacity factor. Declare per equipment, or on the incoming location as a site total."
2149
+ },
2150
+ [EMS_PROPERTY.genRatedKWdc]: {
2151
+ uom: "kW",
2152
+ dataType: "xs:double",
2153
+ note: "rated DC generation capacity, in kW (panel rating for PV). Larger than the AC rating by design; not the capacity-factor denominator."
2154
+ },
2155
+ [EMS_PROPERTY.genDailyProfile]: {
2156
+ dataType: "xs:string",
2157
+ note: "daily shape as 24 comma-separated fractions of rated output (0-1), one per hour of local time \u2014 the site declares its own curve; we do not invent one."
2804
2158
  }
2159
+ };
2160
+ function generationFractionAt(profile, hourOfDay) {
2161
+ const parts = String(profile ?? "").split(",").map((v2) => v2.trim()).filter((v2) => v2 !== "");
2162
+ if (parts.length !== 24) return void 0;
2163
+ const h = Math.floor(hourOfDay);
2164
+ if (!Number.isFinite(h) || h < 0 || h > 23) return void 0;
2165
+ const v = Number(parts[h]);
2166
+ if (!Number.isFinite(v) || v < 0 || v > 1) return void 0;
2805
2167
  return v;
2806
2168
  }
2807
- function ingestEnergyUsagePeriodRecords(records, opts) {
2808
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2809
- const accepted = [];
2810
- const rejected = [];
2811
- for (const r of list) {
2812
- const errors = [];
2813
- const meterId = String(r?.meterId ?? "").trim();
2814
- if (!meterId) errors.push("meterId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC9C0\uC810\uC774 \uC4F4 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2815
- const span = readSpan(r, errors);
2816
- const rawKWh = r?.kWh;
2817
- let kWh;
2818
- if (rawKWh === void 0 || rawKWh === null || String(rawKWh).trim() === "") {
2819
- errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uADF8 \uAD6C\uAC04\uC5D0 \uC4F4 \uC591\uC774\uB2E4");
2820
- } else {
2821
- kWh = readAmount(rawKWh, "kWh", errors);
2822
- }
2823
- const maxKW = readAmount(r?.maxKW, "maxKW", errors);
2824
- const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
2825
- const currency = String(r?.currency ?? "").trim() || void 0;
2826
- if (unitPrice !== void 0 && !currency) errors.push("unitPrice \uB97C \uC2E4\uC5C8\uB294\uB370 currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAE08\uC561\uC740 \uB354\uD560 \uC218 \uC5C6\uB2E4");
2827
- let basis;
2828
- const rawBasis = r?.basis;
2829
- if (rawBasis !== void 0 && rawBasis !== null && String(rawBasis).trim()) {
2830
- const text = String(rawBasis).trim();
2831
- if (!OBSERVATION_BASIS.includes(text)) {
2832
- errors.push(`basis \uAC00 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${OBSERVATION_BASIS.join("\xB7")}): ${JSON.stringify(rawBasis)}`);
2833
- } else basis = text;
2834
- }
2835
- if (errors.length || !span || kWh === void 0) {
2836
- rejected.push({ record: r, errors });
2837
- continue;
2838
- }
2839
- const subj = resolveSubject("meter", meterId, opts);
2840
- const data = {
2841
- meterId,
2842
- subject: subj.subject,
2843
- subjectBasis: subj.basis,
2844
- from: span.from,
2845
- to: span.to,
2846
- kWh,
2847
- ...maxKW !== void 0 ? { maxKW } : {},
2848
- ...unitPrice !== void 0 ? { unitPrice } : {},
2849
- ...currency ? { currency } : {},
2850
- ...basis ? { basis } : {}
2851
- };
2852
- const futureError = futureFactError(span.to, opts);
2853
- if (futureError) {
2854
- rejected.push({ record: r, errors: [futureError] });
2855
- continue;
2856
- }
2857
- accepted.push({
2858
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.usagePeriod, subj.subject, span.from, span.to),
2859
- eventType: ENERGY_EVENT.usagePeriod,
2860
- /* 구간의 **끝**이 이 사실이 성립한 시각이다 — 시작으로 달면 저널이 그 구간을 미리 안 것이 된다. */
2861
- eventTime: span.to,
2862
- tenantId: opts.tenantId,
2863
- data
2864
- });
2169
+ var EMS_TYPES = [
2170
+ /* ── 자리: 전기적 구간 ─────────────────────────────────────────────────── */
2171
+ {
2172
+ key: "incoming",
2173
+ role: "location",
2174
+ /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
2175
+ level: "Other",
2176
+ label: "twin.type.incoming",
2177
+ /* 수전 지점 — 계약전력이 걸리는 자리이고, 요금의 근거가 되는 수요는 여기서 잰다.
2178
+ ISO 50001 의 「에너지 유입」 경계이기도 하다(조직의 에너지 검토가 여기서 시작한다). */
2179
+ standardClass: { iec61850: "MMTR", iso50001: "EnergyInput" },
2180
+ identity: { scheme: "kernel:id" },
2181
+ capabilities: ["metered"]
2182
+ },
2183
+ {
2184
+ key: "feeder",
2185
+ role: "location",
2186
+ /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
2187
+ level: "Other",
2188
+ label: "twin.type.feeder",
2189
+ /* 분기 회로 — 부하 분해의 단위. 계약전력의 하위 배분이 여기서 정해진다. */
2190
+ standardClass: { iec61850: "Feeder", iso50001: "EnergyUse" },
2191
+ identity: { scheme: "kernel:id" },
2192
+ capabilities: ["metered"]
2193
+ },
2194
+ {
2195
+ key: "submeter-zone",
2196
+ role: "location",
2197
+ /* 전기 계통의 구간은 **설비 계층의 단이 아니다** — 표준의 탈출구(`Other`)를 쓴다(아래 주석). */
2198
+ level: "Other",
2199
+ label: "twin.type.submeter-zone",
2200
+ /*
2201
+ * 구역 계량 — 여러 부하를 한 계량기로 묶어 재는 자리(공조·조명처럼 개별 계량이 없는 것들).
2202
+ *
2203
+ * ISO 50001 의 **SEU**(유의 에너지 사용처)가 대개 이 알갱이다. 개별 설비까지 재지 못하는 현장이
2204
+ * 많고, 그것을 「모른다」로 두는 대신 **묶음으로 아는 것**이 정직하다.
2205
+ */
2206
+ standardClass: { iec61850: "MMXU", iso50001: "SEU" },
2207
+ identity: { scheme: "kernel:id" },
2208
+ capabilities: ["metered"]
2209
+ },
2210
+ /* ── 설비: 계량 지점과 에너지 자원 ──────────────────────────────────────── */
2211
+ {
2212
+ key: "meter",
2213
+ role: "equipment",
2214
+ label: "twin.type.meter",
2215
+ /* 계량기 — 측정 논리 노드(MMXU=측정단위, MMTR=적산). 자산으로도 하나다(ISO 55000). */
2216
+ standardClass: { iec61850: "MMXU", iso55000: "Asset", iso50001: "MeasurementPoint" },
2217
+ identity: { scheme: "kernel:id" },
2218
+ capabilities: ["metered", "operable"]
2219
+ },
2220
+ {
2221
+ key: "breaker",
2222
+ role: "equipment",
2223
+ label: "twin.type.breaker",
2224
+ /*
2225
+ * 차단기 — IEC 61850 `XCBR`. **우리는 이것을 조작하지 않는다**(안전 계통은 범위 밖: ems.md §1).
2226
+ * 상태를 읽어 계통 구성을 알 뿐이다.
2227
+ *
2228
+ * 능력은 `switching` 이다 — `operable` 이 아니다(2026-08-14). `operable` 이던 동안 저작면이 차단기에
2229
+ * **제어 컴포넌트**를 권했다: 우리가 하지 않기로 한 조작을 화면이 부추긴 것이다. 「위치를 읽는다」와
2230
+ * 「명령을 받는다」는 다른 능력이고, 이제 그 둘이 갈려 있다(capability.ts 주석).
2231
+ */
2232
+ standardClass: { iec61850: "XCBR", iso55000: "Asset" },
2233
+ identity: { scheme: "kernel:id" },
2234
+ capabilities: ["switching"]
2235
+ },
2236
+ {
2237
+ key: "pv-array",
2238
+ role: "equipment",
2239
+ label: "twin.type.pv-array",
2240
+ /* 태양광 어레이 — IEC 61850-7-420(분산자원)의 `DPVA`. 발전과 계량은 다른 능력이다. */
2241
+ standardClass: { iec61850: "DPVA", iso55000: "Asset", iso50001: "RenewableSupply" },
2242
+ identity: { scheme: "kernel:id" },
2243
+ capabilities: ["energyGenerating", "metered", "operable"]
2244
+ },
2245
+ {
2246
+ key: "battery",
2247
+ role: "equipment",
2248
+ label: "twin.type.battery",
2249
+ /* 축전지(ESS) — `ZBAT`. 충전·방전을 나눠 재고, 저장은 보관(`storable`)이 아니다(물건이 아니다). */
2250
+ standardClass: { iec61850: "ZBAT", iso55000: "Asset" },
2251
+ identity: { scheme: "kernel:id" },
2252
+ capabilities: ["energyStoring", "metered", "operable"]
2253
+ },
2254
+ {
2255
+ key: "utility",
2256
+ role: "equipment",
2257
+ label: "twin.type.utility",
2258
+ /*
2259
+ * 공통 설비 — 공조·컴프레서·칠러·조명·폐수처리처럼 **어느 공정에도 귀속되지 않는** 소비처.
2260
+ *
2261
+ * ── 왜 따로 있나 (2026-08-14) ────────────────────────────────────────────
2262
+ * 물류·생산 트윈에서 이런 것들은 **설비가 아니다**(공정에 매핑되지 않으므로 자원 축에 없다).
2263
+ * 그런데 에너지에서는 소비의 절반을 차지하고 감축 후보 1순위다 — 담을 자리가 반드시 있어야 한다.
2264
+ *
2265
+ * 처음에는 `curtailable-load` 하나로 받으려 했다. 그런데 그 이름은 **「줄일 수 있다」고 주장**한다:
2266
+ * 폐수처리·방폭 환기·서버실 냉방은 공통이지만 줄일 수 없고, 그것을 감축 가능으로 두면 트윈이
2267
+ * 「이걸 줄이면 됩니다」라는 거짓 제안을 한다. 공통성과 감축 가능성은 **다른 축**이다.
2268
+ *
2269
+ * 표준: IEC 61850 에 「공통 설비」라는 논리 노드는 없다(설비 종류마다 다른 노드다) — 비운다.
2270
+ * ISO 50001 의 SEU 는 이 부류를 가장 많이 가리킨다(유의 에너지 사용처).
2271
+ */
2272
+ standardClass: { iso50001: "SEU", iso55000: "Asset" },
2273
+ identity: { scheme: "kernel:id" },
2274
+ capabilities: ["metered", "operable"]
2275
+ },
2276
+ {
2277
+ key: "curtailable-load",
2278
+ role: "equipment",
2279
+ label: "twin.type.curtailable-load",
2280
+ /*
2281
+ * 감축 가능 부하 — 줄일 수 있는 소비처(공조·충전기·비상시 미가동 라인).
2282
+ *
2283
+ * 표준에 이 이름은 없다: IEC 61850 은 설비를 종류로 부르고 「감축 가능」은 **운영 정책**이다.
2284
+ * 그래서 `iec61850` 칸을 비우고 ISO 50001 의 SEU 로만 대응한다 — 억지로 논리 노드를 적으면
2285
+ * 적합성 표가 거짓을 말한다.
2286
+ */
2287
+ standardClass: { iso50001: "SEU" },
2288
+ identity: { scheme: "kernel:id" },
2289
+ capabilities: ["curtailable", "metered", "operable"]
2865
2290
  }
2866
- return { accepted, rejected };
2291
+ ];
2292
+ function electricalUpstreamOf(locations, id) {
2293
+ const byId = new Map((locations ?? []).filter((l) => l?.id).map((l) => [String(l.id), l]));
2294
+ const self = byId.get(String(id));
2295
+ if (!self) return void 0;
2296
+ if (self.upstreamId) return String(self.upstreamId);
2297
+ const parent = self.parentId ? byId.get(String(self.parentId)) : void 0;
2298
+ if (!parent) return void 0;
2299
+ return isElectricalLocationType(String(parent.type ?? "")) ? String(parent.id) : void 0;
2867
2300
  }
2868
- function ingestEnergyBillRecords(records, opts) {
2869
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2870
- const accepted = [];
2871
- const rejected = [];
2872
- for (const r of list) {
2873
- const errors = [];
2874
- const span = readSpan(r, errors);
2875
- const energyCharge = readAmount(r?.energyCharge, "energyCharge", errors);
2876
- const demandCharge = readAmount(r?.demandCharge, "demandCharge", errors);
2877
- const total = readAmount(r?.total, "total", errors);
2878
- const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
2879
- if (energyCharge === void 0 && demandCharge === void 0 && total === void 0) {
2880
- errors.push("\uAE08\uC561\uC774 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uC801\uC744 \uC0AC\uC2E4\uC774 \uC5C6\uB294 \uCCAD\uAD6C\uC11C\uB294 \uBC1B\uC9C0 \uC54A\uB294\uB2E4");
2881
- }
2882
- const currency = String(r?.currency ?? "").trim() || void 0;
2883
- if (!currency) errors.push("currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAE08\uC561\uC740 \uB2E4\uB978 \uAE08\uC561\uACFC \uB354\uD560 \uC218 \uC5C6\uB2E4");
2884
- if (errors.length || !span) {
2885
- rejected.push({ record: r, errors });
2886
- continue;
2887
- }
2888
- const data = {
2889
- from: span.from,
2890
- to: span.to,
2891
- ...energyCharge !== void 0 ? { energyCharge } : {},
2892
- ...demandCharge !== void 0 ? { demandCharge } : {},
2893
- ...total !== void 0 ? { total } : {},
2894
- ...currency ? { currency } : {},
2895
- ...billingDemandKW !== void 0 ? { billingDemandKW } : {}
2896
- };
2897
- const futureError = futureFactError(span.to, opts);
2898
- if (futureError) {
2899
- rejected.push({ record: r, errors: [futureError] });
2900
- continue;
2901
- }
2902
- accepted.push({
2903
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.bill, "", span.from, span.to),
2904
- eventType: ENERGY_EVENT.bill,
2905
- eventTime: span.to,
2906
- tenantId: opts.tenantId,
2907
- data
2908
- });
2909
- }
2910
- return { accepted, rejected };
2301
+ function isElectricalLocationType(type) {
2302
+ return EMS_LOCATION_TYPES.includes(type);
2911
2303
  }
2912
2304
 
2913
- // src/epcis.ts
2914
- var EPCIS_CONTEXT = "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld";
2915
- var UTC_OFFSET = "+00:00";
2916
- var DISP = {
2917
- in_progress: "urn:epcglobal:cbv:disp:in_progress",
2918
- sellable: "urn:epcglobal:cbv:disp:sellable_accessible",
2919
- reserved: "urn:epcglobal:cbv:disp:reserved",
2920
- in_transit: "urn:epcglobal:cbv:disp:in_transit",
2921
- non_sellable: "urn:epcglobal:cbv:disp:non_sellable_other",
2922
- // 불량/scrap
2923
- /**
2924
- * **기한이 지났다** — CBV `expired`.
2305
+ // src/domain-catalog.ts
2306
+ var locationKeys = (types) => types.filter((t) => t.role === "location").map((t) => t.key);
2307
+ var DOMAIN_CATALOG = {
2308
+ // label 은 언어 중립 i18n 키(twin.system.<code>) — 사람 언어는 표현계층이 렌더(L2).
2309
+ wms: { system: "wms", label: "twin.system.wms", types: WMS_TYPES, locationTypes: locationKeys(WMS_TYPES) },
2310
+ yms: { system: "yms", label: "twin.system.yms", types: YMS_TYPES, locationTypes: locationKeys(YMS_TYPES) },
2311
+ mes: { system: "mes", label: "twin.system.mes", types: MES_TYPES, locationTypes: locationKeys(MES_TYPES) },
2312
+ ems: { system: "ems", label: "twin.system.ems", types: EMS_TYPES, locationTypes: locationKeys(EMS_TYPES) }
2313
+ };
2314
+ var READ_BASIS = ["document", "rows", "state", "journal", "record"];
2315
+ var ABSENCE = ["not-running", "not-observed", "not-applicable", "not-kept"];
2316
+ var EMPTY_BECAUSE = [
2317
+ "not-applicable",
2318
+ "not-declared",
2319
+ "declared-empty",
2320
+ "not-projected",
2321
+ "none-yet",
2322
+ "observed-not-in-state",
2323
+ "not-observed"
2324
+ ];
2325
+ var LOGISTICS = ["wms", "yms", "mes"];
2326
+ var TWIN_AXES = [
2327
+ {
2328
+ axis: "locations",
2329
+ path: "locations",
2330
+ journalAxis: "locationId",
2331
+ describedBy: ["name", "type"],
2332
+ label: "twin.axis.locations",
2333
+ kind: "instance",
2334
+ typeRole: "location",
2335
+ standardClass: { epcis: "SGLN" }
2336
+ },
2337
+ {
2338
+ axis: "equipment",
2339
+ path: "equipment",
2340
+ journalAxis: "moverId",
2341
+ describedBy: ["name", "kind"],
2342
+ label: "twin.axis.equipment",
2343
+ kind: "instance",
2344
+ typeRole: "equipment",
2345
+ standardClass: { isa95: "Equipment", iso55000: "Asset", epcis: "GIAI" }
2346
+ },
2347
+ {
2348
+ axis: "persons",
2349
+ path: "persons",
2350
+ label: "twin.axis.persons",
2351
+ kind: "instance",
2352
+ standardClass: { isa95: "Person" },
2353
+ systems: LOGISTICS
2354
+ },
2355
+ {
2356
+ axis: "assets",
2357
+ path: "assets",
2358
+ label: "twin.axis.assets",
2359
+ kind: "instance",
2360
+ standardClass: { isa95: "PhysicalAsset", iso55000: "Asset" }
2361
+ },
2362
+ {
2363
+ axis: "personnelClasses",
2364
+ path: "personnelClasses",
2365
+ describedBy: ["name", "description"],
2366
+ label: "twin.axis.personnelClasses",
2367
+ kind: "class",
2368
+ standardClass: { isa95: "PersonnelClass" },
2369
+ systems: LOGISTICS
2370
+ },
2371
+ {
2372
+ axis: "equipmentClasses",
2373
+ path: "equipmentClasses",
2374
+ describedBy: ["name", "description"],
2375
+ label: "twin.axis.equipmentClasses",
2376
+ kind: "class",
2377
+ standardClass: { isa95: "EquipmentClass" }
2378
+ },
2379
+ {
2380
+ axis: "assetClasses",
2381
+ path: "assetClasses",
2382
+ describedBy: ["name", "description"],
2383
+ label: "twin.axis.assetClasses",
2384
+ kind: "class",
2385
+ standardClass: { isa95: "PhysicalAssetClass" }
2386
+ },
2387
+ {
2388
+ axis: "materialDefinitions",
2389
+ path: "materialDefinitions",
2390
+ journalAxis: "epc",
2391
+ describedBy: ["name", "description", "uom"],
2392
+ label: "twin.axis.materialDefinitions",
2393
+ kind: "class",
2394
+ standardClass: { isa95: "MaterialDefinition" },
2395
+ systems: LOGISTICS
2396
+ },
2397
+ {
2398
+ axis: "materialClasses",
2399
+ path: "materialClasses",
2400
+ describedBy: ["name", "description"],
2401
+ label: "twin.axis.materialClasses",
2402
+ kind: "class",
2403
+ standardClass: { isa95: "MaterialClass" },
2404
+ systems: LOGISTICS
2405
+ },
2406
+ {
2407
+ axis: "operations",
2408
+ path: "operations",
2409
+ describedBy: ["name", "label", "description"],
2410
+ label: "twin.axis.operations",
2411
+ kind: "spec",
2412
+ standardClass: { isa95: "OperationsSegment" },
2413
+ systems: LOGISTICS
2414
+ },
2415
+ {
2416
+ axis: "productionSpec",
2417
+ path: "productionSpec",
2418
+ label: "twin.axis.productionSpec",
2419
+ kind: "spec",
2420
+ standardClass: { isa95: "OperationsSegment" },
2421
+ systems: LOGISTICS
2422
+ },
2423
+ /*
2424
+ * 아래 셋은 저장상 `productionSpec.definition` 안에 있지만 **개념으로는 1급**이다.
2425
+ * `materials` 가 최상위 `materialDefinitions` 와 **둘 다** 있는 것은 지금 상태 그대로다 —
2426
+ * 전자는 도메인 정의의 가벼운 목록(`{key,label}`), 후자는 ISA-95 풍부형이다. 같은 것의 집이
2427
+ * 둘이라는 사실을 **선언이 드러낸다**(감추면 화면이 어느 쪽을 보는지 아무도 모른다).
2428
+ */
2429
+ {
2430
+ axis: "recipes",
2431
+ path: "productionSpec.definition.recipes",
2432
+ describedBy: ["label"],
2433
+ label: "twin.axis.recipes",
2434
+ kind: "spec",
2435
+ standardClass: { isa95: "OperationsSegment" },
2436
+ systems: LOGISTICS
2437
+ },
2438
+ {
2439
+ axis: "routes",
2440
+ path: "productionSpec.definition.routes",
2441
+ describedBy: ["label"],
2442
+ label: "twin.axis.routes",
2443
+ kind: "spec",
2444
+ standardClass: { isa95: "OperationsSegment" },
2445
+ systems: LOGISTICS
2446
+ },
2447
+ {
2448
+ axis: "materials",
2449
+ path: "productionSpec.definition.materials",
2450
+ describedBy: ["label"],
2451
+ label: "twin.axis.materials",
2452
+ kind: "class",
2453
+ standardClass: { isa95: "MaterialDefinition" },
2454
+ systems: LOGISTICS
2455
+ },
2456
+ /*
2457
+ * 시험 명세 — **자원 아홉 종류가 가리키는 대상.**
2925
2458
  *
2926
- * ── 왜 `non_sellable` 로 계산하지 않나 (2026-08-24) ─────────────────────────────
2927
- * 커널의 `non_sellable` 은 CBV 의 `non_sellable_other`, 즉 **「그 밖의 이유」**다. 기한 지남을 거기
2928
- * 넣으면 「기한이 지나 못 판다」와 「깨져서 못 판다」가 같은 값이 되고, 화면은 회수·폐기의 사유를
2929
- * 구별할 수 없다. 식품에서 그 둘은 다른 조치다.
2459
+ * 이 축이 없던 동안 `testSpecificationIds` 는 허공을 가리켰다(값은 실리는데 무엇인지 아무도 모른다).
2460
+ * 축이 서면 인스펙션의 선 채움이 **끊어진 참조를 센다** — 없는 명세를 가리키면 화면이 말한다.
2930
2461
  *
2931
- * 그리고 표준에 **정확한 낱말이 있다** — 합치는 것은 있는 낱말을 버리는 것이다.
2462
+ * `kind: 'spec'` 이다: 자원도 등급도 아니고 **판정의 정의**다(공정·레시피와 같은 부류).
2463
+ */
2464
+ {
2465
+ axis: "testSpecifications",
2466
+ path: "testSpecifications",
2467
+ describedBy: ["name", "description", "version"],
2468
+ label: "twin.axis.testSpecifications",
2469
+ kind: "spec",
2470
+ standardClass: { isa95: "TestSpecification" }
2471
+ },
2472
+ /*
2473
+ * ── ISA-95 Part 4 — 일정과 실적 ────────────────────────────────────────────────
2932
2474
  *
2933
- * ── 기한 날짜와 다른 축이다 ────────────────────────────────────────────────
2934
- * `ItemState.expiry` 는 **날짜**이고 이것은 **상태**다. 날짜가 있으면 「지났나」는 파생이지만, 원본이
2935
- * 「기한 지남」을 상태로 선언하는 시스템이 있다 — 그때 이 값은 관측이다.
2475
+ * 여기부터는 **선언이 아니다.** 오더와 작업은 사람이 board 에 적어 두는 값이 아니라 현장이 낳는
2476
+ * 사실이고, 그 집은 커널 상태와 저널이다. 그래서 `source` 가 `'state'` 이고 `path` 가 없다.
2936
2477
  *
2937
- * 둘이 어긋나면(날짜는 남았는데 상태가 지남, 또는 그 반대) **어느 쪽이 맞다고 정하지 않는다** —
2938
- * 아직 그 판정을 세울 근거가 없다. 어긋남의 구분을 없애지 않는 것이 지금의 규율이다.
2478
+ * ── 왜 축이어야 하나 ──────────────────────────────────────────────────────────
2479
+ * 이 둘이 축이 아니던 동안 "이 트윈이 표준의 어디를 채우나" 라는 질문은 **절반만** 답했다. Part 2
2480
+ * 자원 모델은 여덟이 완전한데 Part 4 는 통째로 비어 있었다 — 런타임에는 실재하는데 조회 모델에는
2481
+ * 없었기 때문이다. 실적을 성과 화면이 답한다는 것은 사실이지만, 그건 **집계**이고 개념 자체를
2482
+ * 가리켜 걸어 들어갈 자리는 없었다(어느 오더가 어느 공정에서 무엇을 먹었나).
2939
2483
  *
2940
- * ── 원문으로 확인했다 (2026-08-24) ────────────────────────────────────────
2941
- * 1차 출처: **CBV Standard Release 2.0, Ratified Jun 2022** §7.2.3 처분 값 표(38개). 이 객체의
2942
- * 다른 값들(`in_progress`·`sellable_accessible`·`reserved`·`in_transit`·`non_sellable_other`)도
2943
- * 그 표에 있다.
2484
+ * ── 왜 테이블로 투영하지 않나 ─────────────────────────────────────────────────
2485
+ * 정본이 저널이다. 구조 엔티티는 **원본이 낼 수 있는 것만** 담고(ADR-0032-D), 오더는 원본이 낸
2486
+ * 것이지만 트윈이 **관측한** 것이다. 투영은 규모에서 성능이 필요해질 때 KPI 폴드와 같은 급의
2487
+ * 별도 결정으로 한다.
2488
+ */
2489
+ {
2490
+ axis: "orders",
2491
+ journalAxis: "orderId",
2492
+ describedBy: ["kind", "status"],
2493
+ label: "twin.axis.orders",
2494
+ kind: "instance",
2495
+ source: "state",
2496
+ historical: true,
2497
+ standardClass: { isa95: "OperationsRequest", epcis: "TransactionEvent" },
2498
+ systems: LOGISTICS
2499
+ },
2500
+ {
2501
+ axis: "tasks",
2502
+ describedBy: ["kind", "status"],
2503
+ label: "twin.axis.tasks",
2504
+ kind: "instance",
2505
+ source: "state",
2506
+ historical: true,
2507
+ /*
2508
+ * No single EPCIS projection. A task's event kind follows its operation: a putaway or a pick is
2509
+ * an ObjectEvent, only a transformation (production, kitting) is a TransformationEvent. This used
2510
+ * to say `epcis: 'TransformationEvent'` for an axis that spans every logistics system.
2511
+ */
2512
+ standardClass: { isa95: "SegmentResponse" },
2513
+ systems: LOGISTICS
2514
+ },
2515
+ /*
2516
+ * ── 물품이 축이 아니었다 (2026-08-22) ──────────────────────────────────────
2517
+ * 트윈에서 **수가 가장 많은 것**이 물품인데(실측: 엔티티 3,611 중 2,400 · hatio-us 는 2,805) 그것을
2518
+ * 가리켜 걸어 들어갈 자리가 없었다. 지도와 집약 태그에는 이미 보이는데 「모델 살펴보기」에는 문이
2519
+ * 없었다 — 사용자가 트윈에 가장 자주 묻는 것이 「내 물건이 어디 있나」이므로 그것은 접근 장벽이다.
2944
2520
  *
2945
- * **`non_sellable_expired` 를 쓰지 않는 이유**: 그 값은 CBV 1.0 의 것이고 표준이 **폐기**했다 —
2946
- * 「deprecated in favour of new disposition values expired, damaged, disposed, … introduced in
2947
- * CBV 1.1」. 폐기된 값을 쓰면 새 소비처가 읽지 못한다.
2521
+ * 성격은 `orders`·`tasks` 와 같다: 상태에 살고, 저널에 이력이 있고, 원본이 낸 것을 트윈이 관측한다.
2522
+ * 그래서 같은 조합(`instance` · `state` · `historical`)이다.
2948
2523
  *
2949
- * 참고: GS1 어휘 등록처(`ref.gs1.org/cbv/…`)로는 확인할 수 없었다 — **없는 값에도 같은 응답**을
2950
- * 준다(지어낸 값의 JSON-LD 가 실재 값과 바이트까지 같았다). 그 경로를 근거로 삼지 말 것.
2524
+ * ── 표준 대응 ─────────────────────────────────────────────────────────────
2525
+ * ISA-95 는 `MaterialLot` 이다 — 물품은 「무슨 품목인가」(정의)가 아니라 「그 품목의 이 덩어리」이고,
2526
+ * 위치·수량·부분(`MaterialSubLot`)을 그 자리가 든다. EPCIS 는 `ObjectEvent` 다: 개체가 생기고
2527
+ * 관측되고 사라지는 것을 그 사건이 말한다.
2528
+ *
2529
+ * ── 무엇이 이 항목을 가리키나 ─────────────────────────────────────────────
2530
+ * `subLotId ?? epc` 다. 짐작에 맡기면 `gtin` 으로 떨어지고, 그러면 **같은 품목의 물품 전부가 한
2531
+ * 식별자로 뭉친다** — 화면이 2,400개를 몇 개로 보인다.
2951
2532
  */
2952
- expired: "urn:epcglobal:cbv:disp:expired",
2953
- /**
2954
- * **검사에 합격했다 / 불합격했다** — CBV `conformant` / `non_conformant`.
2533
+ {
2534
+ axis: "items",
2535
+ journalAxis: "epc",
2536
+ describedBy: ["definitionId", "lot"],
2537
+ label: "twin.axis.items",
2538
+ kind: "instance",
2539
+ source: "state",
2540
+ historical: true,
2541
+ idField: ["subLotId", "epc"],
2542
+ standardClass: { isa95: "MaterialLot", epcis: "ObjectEvent" },
2543
+ systems: LOGISTICS
2544
+ },
2545
+ /*
2546
+ * ── 에너지가 더하는 개념은 **하나**다 (2026-08-14, §10 6.5단계) ──────────────
2955
2547
  *
2956
- * 1차 출처(CBV 2.0 §7.2.3) 정의 그대로다.
2548
+ * 에너지 트윈의 개체 대부분은 **이미 있는 축**이 답한다: 전기 구간은 `locations`, 계량기·차단기·
2549
+ * 태양광·축전지·감축 부하는 `equipment` 다(카탈로그가 그 타입들을 그 역할로 선언한다). 그것들을
2550
+ * 새 축으로 다시 세우면 같은 것이 두 곳에서 세어진다 — 개념 지도가 계량기를 두 번 보여 준다.
2957
2551
  *
2958
- * conformant Outcome of a successful/passed inspection in an inspecting or repairing step
2959
- * non_conformant Outcome of an unsuccessful/failed inspection in an inspecting or repairing step
2552
+ * 정말로 새로운 것은 **수요 구간**이다: 자원이 아니고, 선언이 아니고, 15분마다 닫히는 **사실**이다.
2553
+ * 그것이 요금의 알갱이이고 피크의 근거다(피크는 마감된 구간의 최대이므로 파생이다 — 축이 아니다).
2960
2554
  *
2961
- * ── 왜 시험 결과 축을 자원에 더하지 않고 이것을 쓰나 (2026-08-24) ────────────
2962
- * 로트의 검사 판정을 담을 자리를 찾다가 `ItemState.testResults` 를 더하려 했다. 그런데 표준은 그
2963
- * 사실을 **이미 처분으로 말한다**: `bizStep: inspecting` 사건에 이 처분이 붙는다.
2555
+ * ── 표준 칸을 비운다 ──────────────────────────────────────────────────────
2556
+ * 15분 수요 구간은 **요금 제도의 알갱이**다(계약·TOU). ISO 50001 은 경영 체계를, IEC 61850 은 설비
2557
+ * 데이터 모델을 말하고, 둘 다 이 구간을 정의하지 않는다. 가까운 이름을 적으면 적합성 표가 거짓을
2558
+ * 말하므로 비워 둔다 — 「표준에 자리가 없으면 빈 객체」라는 이 선언의 규율 그대로다.
2964
2559
  *
2965
- * 처분을 쓰면 두 가지가 공짜로 성립한다.
2966
- * ① **상태 ⊆ 이벤트** — 처분은 이미 사건에서 온다. 상태에만 있는 축을 만들지 않는다
2967
- * ② **운영에 곧 닿는다** — 「이 자재를 쓸 수 있나」가 처분으로 답해진다(판정을 따로 읽지 않는다)
2560
+ * 아직 세우지 않은 것: **요금 구간**(TariffPeriod)과 **원단위**(EnPI). 둘 다 아직 아무도 만들지
2561
+ * 않는다 — 선언만 하면 개념 지도가 언제나 0 을 보여 주고, 그것은 결손처럼 읽힌다(§10 7단계의 일).
2562
+ */
2563
+ /*
2564
+ * **무엇이 이 항목을 가리키나** — `idField` 가 말한다.
2968
2565
  *
2969
- * 시험의 **자세한 내용**(어느 명세로, 무엇을 재어)은 다른 물음이고, 표준은 그것을 `TestResult` 로
2970
- * 두며 결과가 대상을 가리킨다(`TestableObjectID`) — 대상이 결과를 들지 않는다. 그 축이 필요해지면
2971
- * 그때 열되, **판정 자체는 여기서 끝난다.**
2566
+ * 수요 구간에는 `id` 가 없다. 그것이 결함은 아니다: 구간의 정체성은 **그 구간이 언제 시작했나**이고
2567
+ * (요금의 알갱이가 그 시각으로 정해진다) 커널도 그것으로 키를 만든다(`contract-projected-over:<startMs>`).
2568
+ *
2569
+ * 그런데 소비처가 `id`·`key`·`gtin` 을 **짐작**하고 있어서, 화면이 여섯 구간 모두를 「식별자 없음 —
2570
+ * 참조할 수 없는 항목」으로 보였다. 값은 실재하는데 가리킬 수 없다고 말한 것이다. 짐작을 없애고
2571
+ * 선언이 답하게 한다 — 축이 사는 자리(`path`)를 선언하는 것과 같은 이유다.
2972
2572
  */
2973
- conformant: "urn:epcglobal:cbv:disp:conformant",
2974
- non_conformant: "urn:epcglobal:cbv:disp:non_conformant"
2975
- };
2976
- var CBV_BIZSTEP = {
2977
- /** 공정에 자재가 들어갔다 — ISA-95 `MaterialUse: Consumed`. */
2978
- consuming: "urn:epcglobal:cbv:bizstep:consuming",
2979
- /** 새 물품이 생겨 계보가 시작된다 — ISA-95 `MaterialUse: Produced`. */
2980
- commissioning: "urn:epcglobal:cbv:bizstep:commissioning",
2981
- /**
2982
- * **검사** — CBV `inspecting`. 1차 출처(CBV 2.0) 정의: 「Process of reviewing objects to address
2983
- * potential physical or documentation defects」이고, 「표본과 달리 검사된 대상은 그대로 남는다」고
2984
- * 이어진다(즉 검사는 물건을 소비하지 않는다).
2573
+ {
2574
+ axis: "demandWindows",
2575
+ path: "energy.closed",
2576
+ idField: "startMs",
2577
+ label: "twin.axis.demandWindows",
2578
+ kind: "instance",
2579
+ source: "state",
2580
+ historical: true,
2581
+ standardClass: {},
2582
+ systems: ["ems"]
2583
+ }
2584
+ ];
2585
+ function isCacheableTense(t) {
2586
+ return t === "standing";
2587
+ }
2588
+ function tenseOf(r) {
2589
+ return r?.tense;
2590
+ }
2591
+ var TWIN_RELATIONS = [
2592
+ /*
2593
+ * What a location sits in — another location (line ⊃ station, zone ⊃ aisle ⊃ bin) or, when no
2594
+ * location has that id, an area of the space (host's `TwinArea`). See `axis-or-external`.
2595
+ */
2596
+ { from: "locations", field: "parentId", target: { kind: "axis-or-external", axis: "locations", entity: "space.area" }, via: "ops.rel.area", optional: true, tense: "standing" },
2597
+ /* 자원이 사는 자리 */
2598
+ { from: "equipment", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2599
+ { from: "persons", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2600
+ { from: "assets", field: "homeLocation", target: { kind: "axis", axis: "locations" }, via: "ops.rel.home", optional: true, tense: "standing" },
2601
+ /* 자원의 등급 — 설비만 `kind`(타입)로 가고 사람·자산은 등급 목록으로 간다. 표준의 비대칭 그대로. */
2602
+ { from: "persons", field: "personnelClassIds[]", target: { kind: "axis", axis: "personnelClasses" }, via: "ops.rel.class", optional: true, tense: "standing" },
2603
+ { from: "assets", field: "assetClassIds[]", target: { kind: "axis", axis: "assetClasses" }, via: "ops.rel.class", optional: true, tense: "standing" },
2604
+ { from: "equipment", field: "kind", target: { kind: "type", role: "equipment" }, via: "ops.rel.type", tense: "standing" },
2605
+ { from: "locations", field: "type", target: { kind: "type", role: "location" }, via: "ops.rel.type", tense: "standing" },
2606
+ /* 생산 — 레시피에서 시작해 라우트·공정·품목으로 퍼진다 */
2607
+ { from: "recipes", field: "route", target: { kind: "axis", axis: "routes" }, via: "ops.rel.route", optional: true, tense: "standing" },
2608
+ { from: "recipes", field: "inputs[].material", target: { kind: "axis", axis: "materials" }, via: "ops.rel.input", tense: "standing" },
2609
+ { from: "recipes", field: "outputs[].material", target: { kind: "axis", axis: "materials" }, via: "ops.rel.output", tense: "standing" },
2610
+ { from: "routes", field: "steps[]", target: { kind: "axis", axis: "operations" }, via: "ops.rel.step", tense: "standing" },
2611
+ /*
2612
+ * 일정·실적의 관계 — **관측 관계다.** 선언 관계는 "그렇게 만들기로 했다" 이고, 이것은 "그렇게
2613
+ * 일어났다" 다. 관계가 없으면 이 두 축은 지도에서 연결되지 않은 카드가 된다(그러면 걸어 들어갈 수 없다).
2614
+ */
2615
+ /*
2616
+ * 오더가 무엇을 만드나 — **자재 키가 아니라 GS1 품목 참조다**(`lines[].gtin`). 자재와 이어 주는
2617
+ * 것은 `productionSpec.binding` 이고 그 해소는 호스트가 한다 — 자리·구역과 같은 `external` 이다.
2618
+ * 축을 직접 가리키게 적으면 없는 필드를 가리키는 선언이 된다(계약을 보고 고쳤다).
2619
+ */
2620
+ { from: "orders", field: "lines[].gtin", target: { kind: "external", entity: "gs1.itemRef" }, via: "ops.rel.item", optional: true, tense: "standing" },
2621
+ /*
2622
+ * ── 작업의 관계는 `tense` 를 **선언하지 않는다** ────────────────────────────
2623
+ * 여섯 줄 모두 비어 있는 것이 판단이다. 작업의 시간축은 **그 줄의 상태**가 정한다 — 끝난 작업이
2624
+ * 이 설비를 가리키면 지난 일이고, 아직인 작업이 가리키면 앞의 일이다. 한 선언이 둘 다이다.
2985
2625
  *
2986
- * 이 단계에 `DISP.conformant`/`DISP.non_conformant` 가 붙어 판정이 처분으로 남는다 — 입고검수·
2987
- * 공정 중 검사가 그 모양이다.
2626
+ * 여기에 `standing` 을 적으면 화면은 「이 설비에 걸린 작업 열」을 시간이 없는 사실로 묶고, **세워도
2627
+ * 되나의 답이 정확히 뒤집힌다.** 채우고 싶은 힘이 있는 자리이므로 적어 둔다: 비어 있음이 답이다.
2628
+ *
2629
+ * 줄마다 다른 것은 선언이 아니라 **읽는 쪽이 상태를 보고 판정한다**(`TaskState.status`).
2988
2630
  */
2989
- inspecting: "urn:epcglobal:cbv:bizstep:inspecting",
2990
- /**
2991
- * **어느 단계로도 이름 붙지 않는 활동** — 원문: 「A business step not identified by any other」.
2631
+ { from: "tasks", field: "orderId", target: { kind: "axis", axis: "orders" }, via: "ops.rel.order", optional: true },
2632
+ /* 작업의 `kind` 는 그 공정의 키다(라우트의 단계 이름 그대로 — `mes-kernel` 의 공정 목록이 그 증거). */
2633
+ { from: "tasks", field: "kind", target: { kind: "axis", axis: "operations" }, via: "ops.rel.operation", optional: true },
2634
+ { from: "tasks", field: "fromNode", target: { kind: "axis", axis: "locations" }, via: "ops.rel.from", optional: true },
2635
+ { from: "tasks", field: "toNode", target: { kind: "axis", axis: "locations" }, via: "ops.rel.at", optional: true },
2636
+ { from: "tasks", field: "resourceRef", target: { kind: "axis", axis: "equipment" }, via: "ops.rel.by", optional: true },
2637
+ { from: "tasks", field: "personnel[]", target: { kind: "axis", axis: "persons" }, via: "ops.rel.crew", optional: true },
2638
+ /*
2639
+ * 물품의 관계 (2026-08-22) — 없으면 축이 **걸어 들어갈 수 없는 목록**이 된다.
2992
2640
  *
2993
- * 이것은 근사가 아니라 **표준이 준 낱말**이다. 그 구별이 중요하다: 재고 조정처럼 한 낱말이 두 일을
2994
- * 하는 원천(세어 보고 맞춘 것 · 사람이 정정한 것)을 `cycle_counting` 으로 옮기면 **일어나지 않은
2995
- * 계수를 기록**하게 된다. 그때 쓰는 것이 이 값이고, 무슨 일이었는지는 값으로 함께 나른다.
2641
+ * `location` 은 필수다 — 물품은 언제나 어딘가에 있다(그것이 물품의 뜻이다). 나머지는 선택이다:
2642
+ * 물류단위에 담기지 않은 물품, 자산에 실리지 않은 팔레트가 정상이다.
2996
2643
  *
2997
- * 원문 확인: CBV Standard Release 2.0(Ratified Jun 2022) §7.1.
2644
+ * `parent` 는 **물품 축을 자기 자신으로** 가리킨다(팔레트에 담긴 상자 — EPCIS `AggregationEvent`).
2645
+ * `carriedBy` 는 다른 축이다 — 반복사용 자산(GRAI)이 물류단위를 실어 나른다(§`FlowItem.carriedBy`).
2646
+ *
2647
+ * 관계 이름은 **소문자 한 낱말**이다(`ops.rel.<name>`) — 기존 열여덟 개가 그 규율이고 시험이 지킨다.
2648
+ *
2649
+ * 품목(`gtin`)은 오더와 **같은 규율**이다: 자재 키가 아니라 GS1 품목 참조이므로 축을 직접 가리키지
2650
+ * 않고 `external` 로 둔다. 축을 가리키게 적으면 없는 필드를 가리키는 선언이 된다.
2998
2651
  */
2999
- other: "urn:epcglobal:cbv:bizstep:other"
3000
- };
3001
- var EPCIS_EVENT = {
3002
- object: "epcis.ObjectEvent",
3003
- aggregation: "epcis.AggregationEvent",
3004
- transaction: "epcis.TransactionEvent",
3005
- transformation: "epcis.TransformationEvent"
3006
- };
3007
- function isEpcisEventType(eventType) {
3008
- return typeof eventType === "string" && eventType.startsWith("epcis.");
2652
+ /*
2653
+ * ── 물품의 지금 자리는 `current` 다 (2026-09-06) ───────────────────────────
2654
+ * `location`·`parent`·`carriedBy` 는 지난 일도 앞의 일도 아니고 `standing` 도 아니다 — **지금
2655
+ * 그렇고 곧 바뀐다.** 붙박인 자리(`homeLocation`)와 정반대 성질이고, 두 줄이 같은 낱말을 받으면
2656
+ * 화면이 「이 상자는 A 에 있다」를 등급처럼 담아 둔다(캐시해도 되는 사실로 읽는다).
2657
+ *
2658
+ * 하루 비워 두었다. 낱말이 없어서였고, 소비처가 실제로 그 구별에 걸릴 때 늘리기로 했다 — plant 가
2659
+ * `MaintenanceOrderStatus.IN_PROGRESS` 로 같은 자리를 만나 걸렸고, 그때 넣었다.
2660
+ */
2661
+ { from: "items", field: "location", target: { kind: "axis", axis: "locations" }, via: "ops.rel.at", tense: "current" },
2662
+ { from: "items", field: "parent", target: { kind: "axis", axis: "items" }, via: "ops.rel.parent", optional: true, tense: "current" },
2663
+ { from: "items", field: "carriedBy", target: { kind: "axis", axis: "assets" }, via: "ops.rel.asset", optional: true, tense: "current" },
2664
+ { from: "items", field: "gtin", target: { kind: "external", entity: "gs1.itemRef" }, via: "ops.rel.item", optional: true, tense: "standing" },
2665
+ /*
2666
+ * 자격을 검증한 시험 — **여덟 갈래.** 자원(개체)과 등급 양쪽이 가리킨다: 표준이 그 둘 모두에 이
2667
+ * 참조를 두었기 때문이다(개체는 "이 사람이 통과했다", 등급은 "이 자격은 이 시험을 요구한다").
2668
+ *
2669
+ * **자리(`locations`)에는 없다** — 표준이 자리를 시험 대상으로 두지 않았고 그 비대칭은 표준의
2670
+ * 판단이다(`contract.ts` 가 "우리도 자리에 넣지 않는다" 고 적었다).
2671
+ */
2672
+ { from: "persons", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2673
+ { from: "personnelClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2674
+ { from: "equipment", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2675
+ { from: "equipmentClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2676
+ { from: "assets", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2677
+ { from: "assetClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2678
+ { from: "materialDefinitions", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2679
+ { from: "materialClasses", field: "testSpecificationIds[]", target: { kind: "axis", axis: "testSpecifications" }, via: "ops.rel.test", optional: true, tense: "standing" },
2680
+ /* 공정이 도는 자리·자원 — 항목이 아니라 **타입**을 가리킨다 */
2681
+ { from: "operations", field: "locationType", target: { kind: "type", role: "location" }, via: "ops.rel.at", optional: true, tense: "standing" },
2682
+ { from: "operations", field: "resourceType", target: { kind: "type", role: "equipment" }, via: "ops.rel.by", optional: true, tense: "standing" }
2683
+ ];
2684
+ var TWIN_PROPERTIES = [
2685
+ /* 공정 — 선언(ISO 8601 기간)과 관측(저널에서 계산한 분포)이 둘 다 있는 유일한 짝. */
2686
+ {
2687
+ axis: "operations",
2688
+ key: "duration",
2689
+ label: "twin.prop.duration",
2690
+ kind: "distribution",
2691
+ declaredField: "duration",
2692
+ observedBy: "kpi-fold.workTime",
2693
+ uom: "ms"
2694
+ },
2695
+ /* 자리 — 용량은 선언, 점유는 관측. 단위가 다른 것이 아니라 **같은 축의 두 값**이다. */
2696
+ {
2697
+ axis: "locations",
2698
+ key: "capacity",
2699
+ label: "twin.prop.capacity",
2700
+ kind: "level",
2701
+ declaredField: "capacity",
2702
+ observedBy: "state.location.occupancy"
2703
+ },
2704
+ /* 설비 — 고장 모델은 선언, 가동은 관측(OEE). 선언 없이도 관측은 선다. */
2705
+ {
2706
+ axis: "equipment",
2707
+ key: "mtbf",
2708
+ label: "twin.prop.mtbf",
2709
+ kind: "distribution",
2710
+ declaredField: "mtbfMs",
2711
+ observedBy: "oee.availability",
2712
+ uom: "ms"
2713
+ },
2714
+ {
2715
+ axis: "equipment",
2716
+ key: "mttr",
2717
+ label: "twin.prop.mttr",
2718
+ kind: "distribution",
2719
+ declaredField: "mttrMs",
2720
+ observedBy: "oee.availability",
2721
+ uom: "ms"
2722
+ },
2723
+ {
2724
+ axis: "equipment",
2725
+ key: "availability",
2726
+ label: "twin.prop.availability",
2727
+ kind: "rate",
2728
+ observedBy: "oee.availability",
2729
+ uom: "ratio"
2730
+ }
2731
+ ];
2732
+ var propertiesOf = (axis) => TWIN_PROPERTIES.filter((p) => p.axis === axis);
2733
+ var axisSource = (axis) => TWIN_AXES.find((a) => a.axis === axis)?.source ?? "document";
2734
+ function documentPath(axis) {
2735
+ const info = TWIN_AXES.find((a) => a.axis === axis);
2736
+ if (!info) throw new Error(`unknown twin axis: "${axis}"`);
2737
+ if (axisSource(axis) !== "document" || !info.path)
2738
+ throw new Error(`axis "${axis}" is not read from the document (source: ${axisSource(axis)}) \u2014 read it from the ${axisSource(axis)}`);
2739
+ return info.path;
3009
2740
  }
3010
- function ssccUri(companyPrefix, serial) {
3011
- return `urn:epc:id:sscc:${companyPrefix}.${String(serial).padStart(10, "0")}`;
2741
+ var relationsFrom = (axis) => TWIN_RELATIONS.filter((r) => r.from === axis);
2742
+ var relationsTo = (axis) => TWIN_RELATIONS.filter((r) => (r.target.kind === "axis" || r.target.kind === "axis-or-external") && r.target.axis === axis);
2743
+ function splitRelationIds(target, ids, inAxis) {
2744
+ if (target.kind === "axis") return { axis: { axis: target.axis, ids: [...ids] } };
2745
+ if (target.kind === "external") return { external: { entity: target.entity, ids: [...ids] } };
2746
+ if (target.kind === "axis-or-external") {
2747
+ const inside = ids.filter((id) => inAxis(target.axis, id));
2748
+ const outside = ids.filter((id) => !inAxis(target.axis, id));
2749
+ return { axis: { axis: target.axis, ids: inside }, external: { entity: target.entity, ids: outside } };
2750
+ }
2751
+ return {};
3012
2752
  }
3013
- function sgtinClass(companyPrefix, itemRef) {
3014
- return `urn:epc:idpat:sgtin:${companyPrefix}.${itemRef}.*`;
2753
+ function axisInfo(axis) {
2754
+ return TWIN_AXES.find((a) => a.axis === axis);
3015
2755
  }
3016
- var ILMD_ATTR = {
3017
- /** 유통기한·만료(로트 단위). */
3018
- expiry: "cbvmda:itemExpirationDate",
3019
- /** 로트·배치 번호(직렬 개체에 로트를 붙일 때). */
3020
- lot: "cbvmda:lotNumber"
2756
+ var DOMAIN_SYSTEMS = ["wms", "yms", "mes", "ems"];
2757
+ var axisAppliesTo = (axis, system) => {
2758
+ const declared = TWIN_AXES.find((a) => a.axis === axis)?.systems;
2759
+ if (!declared || !system) return true;
2760
+ if (!DOMAIN_SYSTEMS.includes(system)) return true;
2761
+ return declared.includes(system);
3021
2762
  };
3022
- function lgtinClass(companyPrefix, itemRefAndIndicator, lot) {
3023
- return `urn:epc:class:lgtin:${companyPrefix}.${itemRefAndIndicator}.${encodeURIComponent(lot)}`;
2763
+ var levelOfLocationType = (typeKey, system) => {
2764
+ const pick = (sys) => DOMAIN_CATALOG[sys]?.types.find((t) => t.role === "location" && t.key === typeKey)?.level;
2765
+ if (system && DOMAIN_SYSTEMS.includes(system)) return pick(system);
2766
+ const found = [...new Set(DOMAIN_SYSTEMS.map(pick).filter(Boolean))];
2767
+ return found.length === 1 ? found[0] : void 0;
2768
+ };
2769
+ var axesOfSystem = (system) => TWIN_AXES.filter((a) => axisAppliesTo(a.axis, system));
2770
+ function capabilitiesForType(system, typeKey) {
2771
+ return DOMAIN_CATALOG[system]?.types.find((t) => t.key === typeKey)?.capabilities ?? [];
3024
2772
  }
3025
- function parseEpc(uri) {
3026
- const raw = String(uri ?? "");
3027
- if (/(?:\/obj\/|:obj:)[^/:\s]+$/.test(raw)) return { scheme: "unknown", instance: true, uri: raw };
3028
- const inHouseClass = raw.match(/(?:\/class\/|:class:)([^/:\s]+)$/);
3029
- if (inHouseClass) {
3030
- const at2 = inHouseClass[1].indexOf(LOT_SEPARATOR);
3031
- const split = at2 > 0 ? decodedPair(inHouseClass[1].slice(0, at2), inHouseClass[1].slice(at2 + LOT_SEPARATOR.length)) : void 0;
3032
- return split ? { scheme: "unknown", instance: false, item: split[0], lot: split[1], uri: raw } : { scheme: "unknown", instance: false, uri: raw };
2773
+
2774
+ // src/domain-definition.ts
2775
+ var OP_PARAM = {
2776
+ /** 양품률(0..1, 무차원). 없으면 커널 기본값 — 기본값을 쓴 사실은 `specCoverage()` 가 밝힌다. */
2777
+ yield: "yield",
2778
+ /** 셋업·체인지오버 소요(ISO 8601 기간 문자열). ISA-95 는 셋업을 별도 세그먼트로도 표현하지만,
2779
+ * 현재 커널은 작업에 붙는 셋업으로 다루므로 모수로 받는다. */
2780
+ setupDuration: "setupDuration"
2781
+ };
2782
+ function procedureViolations(route) {
2783
+ const elements = route.procedure ?? [];
2784
+ if (!elements.length) return [];
2785
+ const errors = [];
2786
+ const byKey = new Map(elements.map((e) => [e.key, e]));
2787
+ const hasChild = new Set(elements.map((e) => e.parent).filter((k) => !!k));
2788
+ const stepSet = new Set(route.steps ?? []);
2789
+ const seenStep = /* @__PURE__ */ new Map();
2790
+ for (const n of elements) {
2791
+ if (n.parent && !byKey.has(n.parent)) errors.push(`${n.key}: \uC0C1\uC704 '${n.parent}' \uAC00 \uC774 \uC808\uCC28\uC5D0 \uC5C6\uB2E4`);
2792
+ if (n.step === void 0) continue;
2793
+ if (hasChild.has(n.key)) errors.push(`${n.key}: \uC544\uB798 \uC694\uC18C\uAC00 \uC788\uB294\uB370 \uB2E8\uACC4\uB97C \uB4E0\uB2E4 \u2014 \uC2E4\uD589\uB418\uB294 \uAC83\uC740 \uC78E\uBFD0\uC774\uB2E4`);
2794
+ if (!stepSet.has(n.step)) errors.push(`${n.key}: \uBAA8\uB974\uB294 \uB2E8\uACC4 '${n.step}' \u2014 steps \uC5D0 \uC5C6\uB2E4`);
2795
+ const already = seenStep.get(n.step);
2796
+ if (already) errors.push(`\uB2E8\uACC4 '${n.step}' \uAC00 '${already}' \uC640 '${n.key}' \uB458\uC5D0 \uC2E4\uB838\uB2E4 \u2014 \uC808\uCC28 \uC5B4\uB514\uC778\uC9C0 \uB9D0\uD560 \uC218 \uC5C6\uB2E4`);
2797
+ else seenStep.set(n.step, n.key);
3033
2798
  }
3034
- const cls = raw.match(/^urn:epc:class:lgtin:(.+)$/);
3035
- if (cls) {
3036
- const seg = cls[1].split(".");
3037
- const lot = seg.slice(2).join(".");
3038
- return {
3039
- scheme: "lgtin",
3040
- instance: false,
3041
- gtinKey: seg.slice(0, 2).join("."),
3042
- lot: lot ? decodeURIComponent(lot) : void 0,
3043
- uri: raw
3044
- };
2799
+ return errors;
2800
+ }
2801
+ var INTENTS = ["transport", "process", "dwell"];
2802
+ function dupes(keys) {
2803
+ const seen = /* @__PURE__ */ new Set();
2804
+ const dup = /* @__PURE__ */ new Set();
2805
+ for (const k of keys) {
2806
+ if (seen.has(k)) dup.add(k);
2807
+ else seen.add(k);
3045
2808
  }
3046
- const pat = raw.match(/^urn:epc:idpat:sgtin:(.+)$/);
3047
- if (pat) {
3048
- const seg = pat[1].split(".");
3049
- return { scheme: "idpat", instance: false, gtinKey: seg.slice(0, 2).join("."), uri: raw };
2809
+ return [...dup];
2810
+ }
2811
+ function validateDomainDefinition(def) {
2812
+ const v = [];
2813
+ if (!def || typeof def !== "object") return ["domain definition \uC5C6\uC74C/\uAC1D\uCCB4 \uC544\uB2D8"];
2814
+ if (typeof def.id !== "string" || !def.id) v.push("id \uB204\uB77D");
2815
+ if (typeof def.label !== "string" || !def.label) v.push("label \uB204\uB77D");
2816
+ if (!Array.isArray(def.locationTypes) || def.locationTypes.length === 0) v.push("locationTypes \uBE44\uC5B4\uC788\uC74C");
2817
+ if (!Array.isArray(def.resourceTypes)) v.push("resourceTypes \uBC30\uC5F4 \uC544\uB2D8");
2818
+ const locationKeys2 = new Set((def.locationTypes || []).map((n) => n.key));
2819
+ const resKeys = new Set((def.resourceTypes || []).map((r) => r.key));
2820
+ const matKeys = new Set((def.materials || []).map((m) => m.key));
2821
+ const matByKey = new Map((def.materials || []).map((m) => [m.key, m]));
2822
+ const opKeys = new Set((def.operations || []).map((o) => o.key));
2823
+ const routeKeys = new Set((def.routes || []).map((r) => r.key));
2824
+ for (const [name, arr] of [["locationTypes", def.locationTypes], ["resourceTypes", def.resourceTypes], ["materials", def.materials], ["operations", def.operations], ["routes", def.routes], ["recipes", def.recipes]]) {
2825
+ for (const d of dupes((arr || []).map((x) => x.key))) v.push(`${name} \uD0A4 \uC911\uBCF5: ${d}`);
3050
2826
  }
3051
- const id = raw.match(/^urn:epc:id:([a-z]+):(.+)$/);
3052
- if (id) {
3053
- const scheme = id[1];
3054
- const seg = id[2].split(".");
3055
- const known = ["sgtin", "sscc", "gdti", "grai", "giai", "sgln"].includes(scheme);
3056
- return {
3057
- scheme: known ? scheme : "unknown",
3058
- instance: true,
3059
- ...scheme === "sgtin" ? { gtinKey: seg.slice(0, 2).join("."), serial: seg[2] } : { serial: seg.slice(1).join(".") },
3060
- uri: raw
2827
+ for (const o of def.operations || []) {
2828
+ if (!INTENTS.includes(o.intent)) v.push(`operation '${o.key}' intent \uBD80\uC815: ${o.intent}`);
2829
+ if (o.locationType && !locationKeys2.has(o.locationType)) v.push(`operation '${o.key}' locationType '${o.locationType}' \uBBF8\uC815\uC758`);
2830
+ if (o.resourceType && !resKeys.has(o.resourceType)) v.push(`operation '${o.key}' resourceType '${o.resourceType}' \uBBF8\uC815\uC758`);
2831
+ if (o.intent === "dwell" && o.resourceType) v.push(`operation '${o.key}' dwell \uC778\uB370 resourceType \uC9C0\uC815\uB428(\uBB34\uC790\uC6D0\uC774\uC5B4\uC57C)`);
2832
+ }
2833
+ for (const r of def.routes || []) {
2834
+ if (!Array.isArray(r.steps) || r.steps.length === 0) v.push(`route '${r.key}' steps \uBE44\uC5B4\uC788\uC74C`);
2835
+ for (const s of r.steps || []) if (!opKeys.has(s)) v.push(`route '${r.key}' step '${s}' \uBBF8\uC815\uC758 operation`);
2836
+ }
2837
+ for (const rc of def.recipes || []) {
2838
+ if (rc.route && !routeKeys.has(rc.route)) v.push(`recipe '${rc.key}' route '${rc.route}' \uBBF8\uC815\uC758`);
2839
+ if (!rc.outputs?.length) v.push(`recipe '${rc.key}' outputs \uBE44\uC5B4\uC788\uC74C`);
2840
+ for (const p of [...rc.inputs || [], ...rc.outputs || []]) {
2841
+ if (!matKeys.has(p.material)) v.push(`recipe '${rc.key}' material '${p.material}' \uBBF8\uC815\uC758`);
2842
+ if (typeof p.qty !== "number" || p.qty <= 0) v.push(`recipe '${rc.key}' material '${p.material}' qty \uBD80\uC815`);
2843
+ const mat = matByKey.get(p.material);
2844
+ if (mat?.locationType && !locationKeys2.has(mat.locationType)) v.push(`recipe '${rc.key}' material '${p.material}' locationType '${mat.locationType}' \uBBF8\uC815\uC758`);
2845
+ }
2846
+ }
2847
+ return v;
2848
+ }
2849
+ var CATALOG_SEMVER = /^\d+\.\d+\.\d+([-+].+)?$/;
2850
+ function validateCatalog(cat) {
2851
+ const v = validateDomainDefinition(cat);
2852
+ if (typeof cat?.version !== "string" || !CATALOG_SEMVER.test(cat?.version || "")) {
2853
+ v.push(`version semver \uC544\uB2D8: ${cat?.version}`);
2854
+ }
2855
+ return v;
2856
+ }
2857
+
2858
+ // src/energy-ingest.ts
2859
+ function isEnergyRecord(record) {
2860
+ if (!record || typeof record !== "object") return false;
2861
+ const r = record;
2862
+ if (!(typeof r.meterId === "string" && r.meterId.trim().length > 0 && r.epc === void 0)) return false;
2863
+ return r.from === void 0 && r.to === void 0;
2864
+ }
2865
+ function ingestEnergyRecords(records, opts) {
2866
+ const arr = Array.isArray(records) ? records : records ? [records] : [];
2867
+ const accepted = [];
2868
+ const rejected = [];
2869
+ let seq = 0;
2870
+ for (const record of arr) {
2871
+ const errors = [];
2872
+ const meterId = String(record?.meterId ?? "").trim();
2873
+ if (!meterId) errors.push("meterId \uC5C6\uC74C \u2014 \uC5B4\uB514\uC758 \uC18C\uBE44\uC778\uC9C0 \uBAA8\uB974\uB294 \uAC12\uC740 \uB204\uC801\uD560 \uC218 \uC5C6\uB2E4");
2874
+ const at2 = String(record?.at ?? "").trim() || opts.defaultEventTime;
2875
+ const atMs = at2 ? Date.parse(at2) : Number.NaN;
2876
+ if (!Number.isFinite(atMs)) errors.push("at \uC5C6\uC74C/\uD615\uC2DD \uC624\uB958 \u2014 \uC9C0\uAE08 \uC2DC\uAC01\uC73C\uB85C \uBA54\uC6B0\uBA74 \uB0A8\uC758 \uC218\uC694 \uAD6C\uAC04\uC5D0 \uC2E4\uB9B0\uB2E4");
2877
+ const num2 = (v, name) => {
2878
+ if (v === void 0 || v === null || v === "") return void 0;
2879
+ const n = Number(v);
2880
+ if (!Number.isFinite(n)) {
2881
+ errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2882
+ return void 0;
2883
+ }
2884
+ return n;
2885
+ };
2886
+ const kW = num2(record?.kW, "kW");
2887
+ const kWh = num2(record?.kWh, "kWh");
2888
+ const powerFactor = num2(record?.powerFactor, "powerFactor");
2889
+ if (errors.length) {
2890
+ rejected.push({ record, errors });
2891
+ continue;
2892
+ }
2893
+ const eventTime = new Date(atMs).toISOString();
2894
+ const data = {
2895
+ meterId,
2896
+ /* 계약은 `kW` 를 필수로 두지만 **못 읽은 표본도 사실**이다 — 그 경우 값을 비우고 보낸다.
2897
+ 커널이 「받았지만 부하를 못 읽었다」로 세고, 구간 마감에 그 이유를 싣는다. */
2898
+ ...kW !== void 0 ? { kW } : {},
2899
+ ...kWh !== void 0 ? { kWh } : {},
2900
+ ...powerFactor !== void 0 ? { powerFactor } : {},
2901
+ at: eventTime
3061
2902
  };
2903
+ accepted.push({
2904
+ eventId: `${opts.tenantId}-energy-${++seq}`,
2905
+ eventType: ENERGY_EVENT.measured,
2906
+ eventTime,
2907
+ tenantId: opts.tenantId,
2908
+ data
2909
+ });
3062
2910
  }
3063
- return { scheme: "unknown", instance: false, uri: raw };
3064
- }
3065
- function decodedPair(item, lot) {
3066
- if (!lot) return void 0;
3067
- try {
3068
- return [decodeURIComponent(item), decodeURIComponent(lot)];
3069
- } catch {
3070
- return void 0;
3071
- }
2911
+ return { accepted, rejected };
3072
2912
  }
3073
- function itemClassOf(uri) {
3074
- if (!uri) return void 0;
3075
- const parsed = parseEpc(uri);
3076
- if (parsed.scheme === "lgtin" && parsed.gtinKey) return `urn:epc:idpat:sgtin:${parsed.gtinKey}.*`;
3077
- if (parsed.item !== void 0) {
3078
- const marker = /^(.*(?:\/class\/|:class:))[^/:\s]+$/.exec(parsed.uri);
3079
- if (marker) return `${marker[1]}${parsed.item.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c])}`;
3080
- }
3081
- return parsed.uri;
2913
+ var POSITIONS = /* @__PURE__ */ new Set(["open", "closed", "intermediate", "bad"]);
2914
+ function isEnergyEquipmentRecord(record) {
2915
+ if (!record || typeof record !== "object") return false;
2916
+ const r = record;
2917
+ return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.epc === void 0 && r.meterId === void 0 && /* 적산을 실었으면 발전이다 — 이 문의 값은 상태이고, 적산은 자기 문이 있다. */
2918
+ r.kWh === void 0;
3082
2919
  }
3083
- function lotClassOfItem(itemClass, lot) {
3084
- if (!itemClass) return void 0;
3085
- const idpat = /^urn:epc:idpat:sgtin:(\d+)\.(\d+)\.\*$/.exec(itemClass);
3086
- if (idpat) return lotClassUri({ namespace: "", item: "", lot, gtin: `${idpat[1]}.${idpat[2]}` });
3087
- const parsed = parseEpc(itemClass);
3088
- if (parsed.instance || parsed.lot !== void 0) return void 0;
3089
- const url = /^(https?:\/\/.+)\/class\/([^/:\s]+)$/.exec(itemClass);
3090
- const urn = /^(urn:.+):class:([^/:\s]+)$/.exec(itemClass);
3091
- const at2 = url ?? urn;
3092
- if (!at2) return void 0;
3093
- let item;
3094
- try {
3095
- item = decodeURIComponent(at2[2]);
3096
- } catch {
3097
- return void 0;
2920
+ function ingestEnergyEquipmentRecords(records, opts) {
2921
+ const arr = Array.isArray(records) ? records : records ? [records] : [];
2922
+ const accepted = [];
2923
+ const rejected = [];
2924
+ let seq = 0;
2925
+ for (const record of arr) {
2926
+ const errors = [];
2927
+ const r = record;
2928
+ const equipmentId = String(r?.equipmentId ?? "").trim();
2929
+ if (!equipmentId) errors.push("equipmentId \uC5C6\uC74C \u2014 \uC5B4\uB290 \uC124\uBE44\uC758 \uC0C1\uD0DC\uC778\uC9C0 \uBAA8\uB974\uB294 \uAC12\uC740 \uC2E4\uC744 \uC218 \uC5C6\uB2E4");
2930
+ const at2 = String(r?.at ?? "").trim() || opts.defaultEventTime;
2931
+ const atMs = at2 ? Date.parse(at2) : Number.NaN;
2932
+ if (!Number.isFinite(atMs)) errors.push("at \uC5C6\uC74C/\uD615\uC2DD \uC624\uB958 \u2014 \uC9C0\uAE08 \uC2DC\uAC01\uC73C\uB85C \uBA54\uC6B0\uBA74 \uC5B8\uC81C\uC758 \uC0C1\uD0DC\uC778\uC9C0 \uC54C \uC218 \uC5C6\uB2E4");
2933
+ const num2 = (v, name, min, max) => {
2934
+ if (v === void 0 || v === null || v === "") return void 0;
2935
+ const n = Number(v);
2936
+ if (!Number.isFinite(n)) {
2937
+ errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2938
+ return void 0;
2939
+ }
2940
+ if (min !== void 0 && n < min) {
2941
+ errors.push(`${name} \uAC00 ${min} \uBCF4\uB2E4 \uC791\uB2E4: ${n}`);
2942
+ return void 0;
2943
+ }
2944
+ if (max !== void 0 && n > max) {
2945
+ errors.push(`${name} \uAC00 ${max} \uBCF4\uB2E4 \uD06C\uB2E4: ${n}`);
2946
+ return void 0;
2947
+ }
2948
+ return n;
2949
+ };
2950
+ const generatedKW = num2(r?.generatedKW, "generatedKW", 0);
2951
+ const exportKW = num2(r?.exportKW, "exportKW");
2952
+ const soc = num2(r?.soc, "soc", 0, 100);
2953
+ const chargeKW = num2(r?.chargeKW, "chargeKW", 0);
2954
+ const dischargeKW = num2(r?.dischargeKW, "dischargeKW", 0);
2955
+ const minKW = num2(r?.minKW, "minKW", 0);
2956
+ let curtailable;
2957
+ if (r?.curtailable !== void 0 && r?.curtailable !== null) {
2958
+ if (typeof r.curtailable !== "boolean") errors.push(`curtailable \uAC00 \uCC38/\uAC70\uC9D3\uC774 \uC544\uB2C8\uB2E4: ${JSON.stringify(r.curtailable)}`);
2959
+ else curtailable = r.curtailable;
2960
+ }
2961
+ const dcVoltage = num2(r?.dcVoltage, "dcVoltage", 0);
2962
+ const dcCurrent = num2(r?.dcCurrent, "dcCurrent", 0);
2963
+ const phases = (raw, name) => {
2964
+ if (raw === void 0 || raw === null) return void 0;
2965
+ if (!Array.isArray(raw)) {
2966
+ errors.push(`${name} \uAC00 \uBC30\uC5F4\uC774 \uC544\uB2C8\uB2E4 \u2014 \uC0C1\uBCC4 \uAC12\uC774\uB77C \uBC30\uC5F4\uB85C \uBC1B\uB294\uB2E4(\uB2E8\uC0C1\uC774\uBA74 \uC6D0\uC18C \uD558\uB098): ${JSON.stringify(raw)}`);
2967
+ return void 0;
2968
+ }
2969
+ if (!raw.length) {
2970
+ errors.push(`${name} \uAC00 \uBE48 \uBC30\uC5F4\uC774\uB2E4 \u2014 \uC7B0 \uC0C1\uC774 \uC5C6\uC73C\uBA74 \uADF8 \uCE78\uC744 \uBCF4\uB0B4\uC9C0 \uC54A\uB294\uB2E4`);
2971
+ return void 0;
2972
+ }
2973
+ const out = [];
2974
+ for (const [i, v] of raw.entries()) {
2975
+ const n = Number(v);
2976
+ if (!Number.isFinite(n)) {
2977
+ errors.push(`${name}[${i}] \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(v)}`);
2978
+ return void 0;
2979
+ }
2980
+ if (n < 0) {
2981
+ errors.push(`${name}[${i}] \uAC00 \uC74C\uC218\uB2E4(${n}) \u2014 \uD06C\uAE30\uB294 \uC74C\uC218\uAC00 \uB418\uC9C0 \uC54A\uB294\uB2E4(\uBC29\uD5A5\uC740 \uB2E4\uB978 \uCD95\uC774 \uB9D0\uD55C\uB2E4)`);
2982
+ return void 0;
2983
+ }
2984
+ out.push(n);
2985
+ }
2986
+ return out;
2987
+ };
2988
+ const acVoltage = phases(r?.acVoltage, "acVoltage");
2989
+ const acCurrent = phases(r?.acCurrent, "acCurrent");
2990
+ if (acVoltage && acCurrent && acVoltage.length !== acCurrent.length) {
2991
+ errors.push(`acVoltage(${acVoltage.length}\uC0C1)\uC640 acCurrent(${acCurrent.length}\uC0C1)\uC758 \uC0C1 \uC218\uAC00 \uB2E4\uB974\uB2E4`);
2992
+ }
2993
+ let position;
2994
+ if (r?.position !== void 0 && r?.position !== null && r?.position !== "") {
2995
+ const p = String(r.position);
2996
+ if (!POSITIONS.has(p)) errors.push(`position \uC774 \uD45C\uC900 \uAC12\uC774 \uC544\uB2C8\uB2E4(open\xB7closed\xB7intermediate\xB7bad): ${JSON.stringify(r.position)}`);
2997
+ else position = p;
2998
+ }
2999
+ const values = { generatedKW, exportKW, soc, chargeKW, dischargeKW, curtailable, minKW, position, dcVoltage, dcCurrent, acVoltage, acCurrent };
3000
+ if (!errors.length && Object.values(values).every((v) => v === void 0)) {
3001
+ errors.push("\uBC14\uAFC0 \uC0C1\uD0DC\uAC00 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uAC12 \uC5C6\uB294 \uBCF4\uACE0\uB294 \uC0AC\uC2E4\uB85C \uC801\uC744 \uAC83\uC774 \uC5C6\uB2E4");
3002
+ }
3003
+ if (errors.length) {
3004
+ rejected.push({ record, errors });
3005
+ continue;
3006
+ }
3007
+ const eventTime = new Date(atMs).toISOString();
3008
+ const data = {
3009
+ equipmentId,
3010
+ at: eventTime,
3011
+ ...generatedKW !== void 0 ? { generatedKW } : {},
3012
+ ...exportKW !== void 0 ? { exportKW } : {},
3013
+ ...soc !== void 0 ? { soc } : {},
3014
+ ...chargeKW !== void 0 ? { chargeKW } : {},
3015
+ ...dischargeKW !== void 0 ? { dischargeKW } : {},
3016
+ ...curtailable !== void 0 ? { curtailable } : {},
3017
+ ...minKW !== void 0 ? { minKW } : {},
3018
+ ...position !== void 0 ? { position } : {},
3019
+ ...dcVoltage !== void 0 ? { dcVoltage } : {},
3020
+ ...dcCurrent !== void 0 ? { dcCurrent } : {},
3021
+ ...acVoltage !== void 0 ? { acVoltage } : {},
3022
+ ...acCurrent !== void 0 ? { acCurrent } : {}
3023
+ };
3024
+ accepted.push({
3025
+ eventId: `${opts.tenantId}-energy-eq-${++seq}`,
3026
+ eventType: ENERGY_EVENT.equipment,
3027
+ eventTime,
3028
+ tenantId: opts.tenantId,
3029
+ data
3030
+ });
3098
3031
  }
3099
- return lotClassUri({ namespace: at2[1], item, lot });
3100
- }
3101
- function sameItemClass(a, b) {
3102
- const x = itemClassOf(a);
3103
- return x !== void 0 && x === itemClassOf(b);
3104
- }
3105
- function gdtiUri(companyPrefix, docType, serial) {
3106
- return `urn:epc:id:gdti:${companyPrefix}.${docType}.${serial}`;
3107
- }
3108
- function objectUri(namespace, objId) {
3109
- return underNamespace(namespace, "obj", objId);
3032
+ return { accepted, rejected };
3110
3033
  }
3111
- function classUri(namespace, classId) {
3112
- return underNamespace(namespace, "class", classId);
3034
+ function isEnergyGenerationRecord(record) {
3035
+ if (record?.from !== void 0 || record?.to !== void 0) return false;
3036
+ if (!record || typeof record !== "object") return false;
3037
+ const r = record;
3038
+ return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.kWh !== void 0 && r.meterId === void 0 && r.epc === void 0;
3113
3039
  }
3114
- function lotClassUri(input) {
3115
- const item = String(input.item ?? "");
3116
- const lot = String(input.lot ?? "");
3117
- if (!lot) throw new Error(`lotClassUri: \uB85C\uD2B8\uAC00 \uBE44\uC5C8\uB2E4 \u2014 \uB85C\uD2B8 \uC5C6\uB294 \uD488\uBAA9\uC740 classUri \uB85C \uBD80\uB978\uB2E4 (item=${item})`);
3118
- if (input.gtin !== void 0) {
3119
- const [prefix, ref, ...rest] = String(input.gtin).split(".");
3120
- if (!prefix || !ref || rest.length) {
3121
- throw new Error(`lotClassUri: gtin \uC740 'CompanyPrefix.ItemRefAndIndicator' \uC5EC\uC57C \uD55C\uB2E4: ${input.gtin}`);
3040
+ function ingestEnergyGenerationRecords(records, opts) {
3041
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3042
+ const accepted = [];
3043
+ const rejected = [];
3044
+ let seq = 0;
3045
+ for (const r of list) {
3046
+ const errors = [];
3047
+ const equipmentId = String(r?.equipmentId ?? "").trim();
3048
+ if (!equipmentId) errors.push("equipmentId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC124\uBE44\uAC00 \uB9CC\uB4E0 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
3049
+ const STATE_FIELDS = ["generatedKW", "exportKW", "soc", "chargeKW", "dischargeKW", "curtailable", "minKW", "position"];
3050
+ const alsoState = STATE_FIELDS.filter((f) => r?.[f] !== void 0);
3051
+ if (alsoState.length) {
3052
+ errors.push(
3053
+ `\uC801\uC0B0\uACFC \uC124\uBE44 \uC0C1\uD0DC\uB97C \uD55C \uB808\uCF54\uB4DC\uC5D0 \uC2E4\uC5C8\uB2E4(${alsoState.join("\xB7")}) \u2014 \uC774 \uBB38\uC740 \uC801\uC0B0\uB9CC \uC77D\uC73C\uBBC0\uB85C \uADF8 \uAC12\uC774 \uC0AC\uB77C\uC9C4\uB2E4. \uAC08\uB77C \uBCF4\uB0BC \uAC83`
3054
+ );
3122
3055
  }
3123
- const uri = lgtinClass(prefix, ref, lot);
3124
- const wrong = gs1KeyDigitViolation(uri);
3125
- if (wrong) throw new Error(`lotClassUri: ${wrong}`);
3126
- return uri;
3056
+ const raw = r?.kWh;
3057
+ const kWh = Number(raw);
3058
+ if (raw === void 0 || raw === null || !Number.isFinite(kWh)) {
3059
+ errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uC801\uC0B0 \uD558\uB098\uB2E4(\uC21C\uC2DC \uCD9C\uB825\uC740 \uC124\uBE44 \uC0C1\uD0DC\uB85C \uBCF4\uB0B8\uB2E4)");
3060
+ } else if (kWh < 0) {
3061
+ errors.push(`kWh \uAC00 \uC74C\uC218\uB2E4(${kWh}) \u2014 \uC801\uC0B0\uC740 \uB4A4\uB85C \uAC00\uB354\uB77C\uB3C4 \uC74C\uC218\uAC00 \uB418\uC9C0 \uC54A\uB294\uB2E4`);
3062
+ }
3063
+ const eventTime = String(r?.at ?? "").trim() || opts.defaultEventTime || "";
3064
+ if (!eventTime) errors.push("at \uC774 \uC5C6\uACE0 \uAE30\uBCF8 \uC2DC\uAC01\uB3C4 \uC8FC\uC9C0 \uC54A\uC558\uB2E4 \u2014 \uC5B8\uC81C \uC7B0 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
3065
+ let since;
3066
+ const rawSince = r?.kWhSince;
3067
+ if (rawSince !== void 0 && rawSince !== null && String(rawSince).trim()) {
3068
+ const text = String(rawSince).trim();
3069
+ const at2 = Date.parse(text);
3070
+ if (!Number.isFinite(at2)) errors.push(`kWhSince \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(rawSince)}`);
3071
+ else if (Number.isFinite(Date.parse(eventTime)) && at2 > Date.parse(eventTime)) {
3072
+ errors.push(`kWhSince(${text}) \uAC00 \uC7B0 \uC2DC\uAC01(${eventTime})\uBCF4\uB2E4 \uB4A4\uB2E4 \u2014 \uB458 \uC911 \uD558\uB098\uAC00 \uD2C0\uB838\uB2E4`);
3073
+ } else since = text;
3074
+ }
3075
+ const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
3076
+ let accumulation;
3077
+ const rawAcc = r?.kWhAccumulation;
3078
+ if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
3079
+ const text = String(rawAcc).trim();
3080
+ if (!ACCUMULATIONS.includes(text)) {
3081
+ errors.push(`kWhAccumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
3082
+ } else accumulation = text;
3083
+ }
3084
+ if (errors.length) {
3085
+ rejected.push({ record: r, errors });
3086
+ continue;
3087
+ }
3088
+ const data = {
3089
+ equipmentId,
3090
+ kWh,
3091
+ at: eventTime,
3092
+ ...since ? { since } : {},
3093
+ ...accumulation ? { accumulation } : {}
3094
+ };
3095
+ accepted.push({
3096
+ eventId: `${opts.tenantId}-generated-${++seq}`,
3097
+ eventType: ENERGY_EVENT.generated,
3098
+ eventTime,
3099
+ tenantId: opts.tenantId,
3100
+ data
3101
+ });
3127
3102
  }
3128
- if (!item) throw new Error(`lotClassUri: \uD488\uBC88\uC774 \uBE44\uC5C8\uB2E4 (lot=${lot})`);
3129
- const enc = (v) => v.replace(LOT_COMPONENT_BREAKING, (c) => PERCENT_ENCODED[c]);
3130
- return joinUnderNamespace(input.namespace, "class", `${enc(item)}${LOT_SEPARATOR}${enc(lot)}`);
3131
- }
3132
- var LOT_SEPARATOR = ";lot=";
3133
- var LOT_COMPONENT_BREAKING = /[%/:?# ;]/g;
3134
- function bizTransactionUri(namespace, transId) {
3135
- return underNamespace(namespace, "bt", transId);
3136
- }
3137
- var STRUCTURE_BREAKING = /[%/:?# ]/g;
3138
- var PERCENT_ENCODED = {
3139
- "%": "%25",
3140
- "/": "%2F",
3141
- ":": "%3A",
3142
- "?": "%3F",
3143
- "#": "%23",
3144
- " ": "%20",
3145
- /* 로트 클래스의 가르는 글자 — `lotClassUri` 만 쓴다(§`LOT_COMPONENT_BREAKING`). 표는 한 벌이다. */
3146
- ";": "%3B"
3147
- };
3148
- function underNamespace(namespace, marker, id) {
3149
- const raw = String(id);
3150
- if (!raw) return void 0;
3151
- return joinUnderNamespace(namespace, marker, raw.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c]));
3152
- }
3153
- function joinUnderNamespace(namespace, marker, v) {
3154
- const ns = namespace?.trim();
3155
- if (!ns) return void 0;
3156
- if (/^https?:\/\/[^/\s]+/.test(ns)) return `${ns.replace(/\/+$/, "")}/${marker}/${v}`;
3157
- if (/^urn:epc(global)?:/.test(ns)) return void 0;
3158
- if (/^urn:[^:\s]+/.test(ns)) return `${ns.replace(/:+$/, "")}:${marker}:${v}`;
3159
- return void 0;
3103
+ return { accepted, rejected };
3160
3104
  }
3161
- function header(type, eventTime, bizStep, opts) {
3162
- const h = {
3163
- "@context": EPCIS_CONTEXT,
3164
- type,
3165
- eventTime,
3166
- eventTimeZoneOffset: UTC_OFFSET,
3167
- bizStep
3168
- };
3169
- if (opts?.eventID) h.eventID = opts.eventID;
3170
- if (opts?.recordTime) h.recordTime = opts.recordTime;
3171
- if (opts?.errorDeclaration) h.errorDeclaration = opts.errorDeclaration;
3172
- if (opts?.bizTransactionList?.length) h.bizTransactionList = opts.bizTransactionList;
3173
- if (opts?.ilmd) h.ilmd = opts.ilmd;
3174
- if (opts?.sourceList) h.sourceList = opts.sourceList;
3175
- if (opts?.destinationList) h.destinationList = opts.destinationList;
3176
- if (opts?.persistentDisposition) h.persistentDisposition = opts.persistentDisposition;
3177
- if (opts?.sensorElementList) h.sensorElementList = opts.sensorElementList;
3178
- if (opts?.certificationInfo) h.certificationInfo = opts.certificationInfo;
3179
- return h;
3105
+ function isEnergyUsagePeriodRecord(record) {
3106
+ const r = record;
3107
+ return !!r && typeof r === "object" && r.meterId !== void 0 && r.from !== void 0 && r.to !== void 0 && r.kWh !== void 0;
3180
3108
  }
3181
- function common(type, eventTime, action, bizStep, opts) {
3182
- return { ...header(type, eventTime, bizStep, opts), action };
3109
+ function isEnergyGenerationPeriodRecord(record) {
3110
+ const r = record;
3111
+ if (!r || typeof r !== "object") return false;
3112
+ if (r.equipmentId === void 0 || r.from === void 0 || r.to === void 0) return false;
3113
+ return r.kWh !== void 0;
3183
3114
  }
3184
- function objectEvent(p) {
3185
- const e = { ...common("ObjectEvent", p.eventTime, p.action, p.bizStep, p), epcList: p.epcList };
3186
- if (p.disposition) e.disposition = p.disposition;
3187
- if (p.quantityList) e.quantityList = p.quantityList;
3188
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3189
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3190
- if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
3191
- return e;
3115
+ function ingestEnergyGenerationPeriodRecords(records, opts) {
3116
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3117
+ const accepted = [];
3118
+ const rejected = [];
3119
+ for (const r of list) {
3120
+ const errors = [];
3121
+ const equipmentId = String(r?.equipmentId ?? "").trim();
3122
+ if (!equipmentId) errors.push("equipmentId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC124\uBE44\uAC00 \uB0B8 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
3123
+ const span = readSpan(r, errors);
3124
+ const kWh = readAmount(r?.kWh, "kWh", errors);
3125
+ if (kWh === void 0 && !errors.length) errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uADF8 \uAE30\uAC04\uC758 \uBC1C\uC804\uB7C9\uC774\uB2E4");
3126
+ const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
3127
+ let accumulation;
3128
+ const rawAcc = r?.accumulation;
3129
+ if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
3130
+ const text = String(rawAcc).trim();
3131
+ if (!ACCUMULATIONS.includes(text)) {
3132
+ errors.push(`accumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
3133
+ } else accumulation = text;
3134
+ }
3135
+ const readAt = (raw, name) => {
3136
+ if (raw === void 0 || raw === null || !String(raw).trim()) return void 0;
3137
+ const text = String(raw).trim();
3138
+ if (!Number.isFinite(Date.parse(text))) {
3139
+ errors.push(`${name} \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
3140
+ return void 0;
3141
+ }
3142
+ return text;
3143
+ };
3144
+ const observedFrom = readAt(r?.observedFrom, "observedFrom");
3145
+ const observedTo = readAt(r?.observedTo, "observedTo");
3146
+ if (errors.length || !span || kWh === void 0) {
3147
+ rejected.push({ record: r, errors });
3148
+ continue;
3149
+ }
3150
+ const data = {
3151
+ equipmentId,
3152
+ kWh,
3153
+ periodStart: span.from,
3154
+ periodEnd: span.to,
3155
+ /* 관측 구간을 말하지 않으면 기간 전체를 잰 것으로 둔다 — 지난 기록은 그 원본이 하루를 마감해 준 값이다. */
3156
+ observedFrom: observedFrom ?? span.from,
3157
+ observedTo: observedTo ?? span.to,
3158
+ accumulation: accumulation ?? "daily",
3159
+ /* 밖에서 마감되어 온 것이다 — 우리가 시각 기준으로 닫은 것이 아니다. */
3160
+ boundary: "declared"
3161
+ };
3162
+ const subj = resolveSubject("equipment", equipmentId, opts);
3163
+ data.subject = subj.subject;
3164
+ data.subjectBasis = subj.basis;
3165
+ const futureError = futureFactError(span.to, opts);
3166
+ if (futureError) {
3167
+ rejected.push({ record: r, errors: [futureError] });
3168
+ continue;
3169
+ }
3170
+ accepted.push({
3171
+ eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPeriod, subj.subject, span.from, span.to),
3172
+ eventType: ENERGY_EVENT.generationPeriod,
3173
+ eventTime: span.to,
3174
+ tenantId: opts.tenantId,
3175
+ data
3176
+ });
3177
+ }
3178
+ return { accepted, rejected };
3192
3179
  }
3193
- function aggregationEvent(p) {
3194
- const e = { ...common("AggregationEvent", p.eventTime, p.action, p.bizStep, p), parentID: p.parentID };
3195
- if (p.disposition) e.disposition = p.disposition;
3196
- if (p.childEPCs) e.childEPCs = p.childEPCs;
3197
- if (p.childQuantityList) e.childQuantityList = p.childQuantityList;
3198
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3199
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3200
- return e;
3180
+ function isEnergyGenerationPriceRecord(record) {
3181
+ const r = record;
3182
+ if (!r || typeof r !== "object") return false;
3183
+ if (r.from === void 0 || r.to === void 0) return false;
3184
+ if (r.meterId !== void 0 || r.equipmentId !== void 0) return false;
3185
+ return r.unitPrice !== void 0;
3201
3186
  }
3202
- function transactionEvent(p) {
3203
- const e = {
3204
- ...common("TransactionEvent", p.eventTime, p.action, p.bizStep, p),
3205
- bizTransactionList: p.bizTransactionList
3206
- };
3207
- if (p.disposition) e.disposition = p.disposition;
3208
- if (p.parentID) e.parentID = p.parentID;
3209
- if (p.epcList) e.epcList = p.epcList;
3210
- if (p.quantityList) e.quantityList = p.quantityList;
3211
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3212
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3213
- return e;
3187
+ function ingestEnergyGenerationPriceRecords(records, opts) {
3188
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3189
+ const accepted = [];
3190
+ const rejected = [];
3191
+ for (const r of list) {
3192
+ const errors = [];
3193
+ const span = readSpan(r, errors);
3194
+ const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
3195
+ if (unitPrice === void 0 && !errors.length) errors.push("unitPrice \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 1kWh \uB2F9 \uAC12 \uD558\uB098\uB2E4");
3196
+ const currency = String(r?.currency ?? "").trim();
3197
+ if (!currency) errors.push("currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAC12\uC740 \uB2E4\uB978 \uAE08\uC561\uACFC \uB354\uD560 \uC218 \uC5C6\uB2E4");
3198
+ if (errors.length || !span || unitPrice === void 0) {
3199
+ rejected.push({ record: r, errors });
3200
+ continue;
3201
+ }
3202
+ const data = { from: span.from, to: span.to, unitPrice, currency };
3203
+ accepted.push({
3204
+ eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPrice, "", span.from, span.to),
3205
+ eventType: ENERGY_EVENT.generationPrice,
3206
+ eventTime: span.from,
3207
+ tenantId: opts.tenantId,
3208
+ data
3209
+ });
3210
+ }
3211
+ return { accepted, rejected };
3214
3212
  }
3215
- function transformationEvent(p) {
3216
- const e = header("TransformationEvent", p.eventTime, p.bizStep, p);
3217
- if (p.disposition) e.disposition = p.disposition;
3218
- if (p.inputEPCList) e.inputEPCList = p.inputEPCList;
3219
- if (p.inputQuantityList) e.inputQuantityList = p.inputQuantityList;
3220
- if (p.outputEPCList) e.outputEPCList = p.outputEPCList;
3221
- if (p.outputQuantityList) e.outputQuantityList = p.outputQuantityList;
3222
- if (p.transformationID) e.transformationID = p.transformationID;
3223
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3224
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3225
- if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
3226
- return e;
3213
+ function isEnergyTariffBasisRecord(record) {
3214
+ const r = record;
3215
+ if (!r || typeof r !== "object") return false;
3216
+ if (r.from === void 0 || r.to === void 0) return false;
3217
+ if (r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0) return false;
3218
+ return r.billingDemandKW !== void 0 || r.demandChargePerKW !== void 0;
3227
3219
  }
3228
- var ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
3229
- var TZ_RE = /^[+-]\d{2}:\d{2}$/;
3230
- var ACTIONS = ["ADD", "OBSERVE", "DELETE"];
3231
- var EPC_CLASS_PREFIXES = ["urn:epc:idpat:", "urn:epc:class:"];
3232
- var DL_CANONICAL = "https://id.gs1.org/";
3233
- var CBV_URL_CLASS = /^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)*class\/[^/\s]+$/;
3234
- var CBV_URN_CLASS = /^urn:[^:\s]+:(?:[^:\s]+:)*class:[^:\s]+$/;
3235
- var GS1_KEY_DIGITS = { sgtin: 13, lgtin: 13, sscc: 17, grai: 12, gdti: 12, sgln: 12 };
3236
- function gs1KeyDigitViolation(uri) {
3237
- if (!uri) return void 0;
3238
- const m = /^urn:epc:(?:id|idpat|class):([a-z]+):([^:]+)$/.exec(uri);
3239
- if (!m) return void 0;
3240
- const want = GS1_KEY_DIGITS[m[1]];
3241
- if (!want) return void 0;
3242
- const parts = m[2].split(".");
3243
- if (parts.length < 2) return `${m[1]} \uD615\uC2DD \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4\uC640 \uCC38\uC870\uAC00 '.' \uB85C \uAC08\uB824\uC57C \uD55C\uB2E4`;
3244
- const [prefix, ref] = parts;
3245
- if (ref === "*") return void 0;
3246
- if (!/^\d+$/.test(prefix) || !/^\d+$/.test(ref)) {
3247
- return `${m[1]} \uD615\uC2DD \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4\uC640 \uCC38\uC870\uB294 \uC22B\uC790\uB2E4`;
3220
+ function ingestEnergyTariffBasisRecords(records, opts) {
3221
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3222
+ const accepted = [];
3223
+ const rejected = [];
3224
+ for (const r of list) {
3225
+ const errors = [];
3226
+ const span = readSpan(r, errors);
3227
+ const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
3228
+ const demandChargePerKW = readAmount(r?.demandChargePerKW, "demandChargePerKW", errors);
3229
+ if (billingDemandKW === void 0 && demandChargePerKW === void 0) {
3230
+ errors.push("\uC694\uAE08 \uAE30\uC900\uC774 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uC801\uC744 \uC0AC\uC2E4\uC774 \uC5C6\uB294 \uAE30\uC900\uC740 \uBC1B\uC9C0 \uC54A\uB294\uB2E4");
3231
+ }
3232
+ const currency = String(r?.currency ?? "").trim() || void 0;
3233
+ if (demandChargePerKW !== void 0 && !currency) errors.push("demandChargePerKW \uB97C \uC2E4\uC5C8\uB294\uB370 currency \uAC00 \uC5C6\uB2E4");
3234
+ if (r?.demandCharge !== void 0 || r?.total !== void 0) {
3235
+ errors.push("\uAE08\uC561(demandCharge\xB7total)\uC740 \uC774 \uBB38\uC774 \uBC1B\uC9C0 \uC54A\uB294\uB2E4 \u2014 \uC815\uC0B0 \uAE08\uC561\uC740 \uCCAD\uAD6C\uC11C \uBB38\uC73C\uB85C \uBCF4\uB0B8\uB2E4");
3236
+ }
3237
+ if (errors.length || !span) {
3238
+ rejected.push({ record: r, errors });
3239
+ continue;
3240
+ }
3241
+ const data = {
3242
+ from: span.from,
3243
+ to: span.to,
3244
+ ...billingDemandKW !== void 0 ? { billingDemandKW } : {},
3245
+ ...demandChargePerKW !== void 0 ? { demandChargePerKW } : {},
3246
+ ...currency ? { currency } : {}
3247
+ };
3248
+ accepted.push({
3249
+ eventId: periodFactId(opts.tenantId, ENERGY_EVENT.tariffBasis, "", span.from, span.to),
3250
+ eventType: ENERGY_EVENT.tariffBasis,
3251
+ /* **시작 시각**이다 — 그때부터 유효하다(§ 위 주석). */
3252
+ eventTime: span.from,
3253
+ tenantId: opts.tenantId,
3254
+ data
3255
+ });
3248
3256
  }
3249
- const got = prefix.length + ref.length;
3250
- if (got === want) return void 0;
3251
- return `${m[1]} \uC790\uB9AC \uC218 \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4(${prefix.length}) + \uCC38\uC870(${ref.length}) = ${got} \uC774\uC9C0\uB9CC ${want} \uC5EC\uC57C \uD55C\uB2E4(GS1 TDS). \uD504\uB9AC\uD53D\uC2A4\uB97C \uBC14\uAFB8\uBA74 \uCC38\uC870 \uC790\uB9AC \uC218\uB97C \uD568\uAED8 \uB9DE\uCDB0\uC57C \uD55C\uB2E4.`;
3257
+ return { accepted, rejected };
3252
3258
  }
3253
- function classIdentifierViolation(epcClass) {
3254
- if (!epcClass) return `quantity epcClass \uBD80\uC815: ${epcClass}`;
3255
- const digits = gs1KeyDigitViolation(epcClass);
3256
- if (digits) return `quantity epcClass \uBD80\uC815: ${digits}`;
3257
- if (EPC_CLASS_PREFIXES.some((p) => epcClass.startsWith(p))) return void 0;
3258
- if (epcClass.startsWith(DL_CANONICAL)) return void 0;
3259
- if (CBV_URL_CLASS.test(epcClass) || CBV_URN_CLASS.test(epcClass)) return void 0;
3260
- return `quantity epcClass \uBD80\uC815: ${epcClass} \u2014 \uD074\uB798\uC2A4 \uC2DD\uBCC4\uC790\uB294 \uC18C\uC720 \uAD8C\uD55C\uC744 \uB9D0\uD560 \uC218 \uC788\uB294 \uBAA8\uC591\uC774\uC5B4\uC57C \uD55C\uB2E4 (EPC \uD074\uB798\uC2A4 urn:epc:idpat:/urn:epc:class: \xB7 CBV \xA78.3.4 http(s)://<\uB3C4\uBA54\uC778>/**/class/<id> \xB7 CBV \xA78.3.3 urn:<\uC774\uB984\uACF5\uAC04>:**:class:<id>)`;
3259
+ function isEnergyBillRecord(record) {
3260
+ const r = record;
3261
+ if (!r || typeof r !== "object") return false;
3262
+ if (r.from === void 0 || r.to === void 0) return false;
3263
+ return r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0;
3261
3264
  }
3262
- function validateEpcisEvent(e) {
3263
- const v = [];
3264
- for (const [field, list] of [
3265
- ["epcList", e.epcList],
3266
- ["childEPCs", e.childEPCs],
3267
- ["inputEPCList", e.inputEPCList],
3268
- ["outputEPCList", e.outputEPCList],
3269
- ["parentID", e.parentID ? [e.parentID] : void 0]
3270
- ]) {
3271
- for (const epc of list ?? []) {
3272
- const bad2 = gs1KeyDigitViolation(epc);
3273
- if (bad2) v.push(`${field}: ${bad2}`);
3274
- }
3275
- }
3276
- if (e["@context"] !== EPCIS_CONTEXT) v.push("@context \uB204\uB77D/\uBD88\uC77C\uCE58");
3277
- if (!["ObjectEvent", "AggregationEvent", "TransactionEvent", "TransformationEvent"].includes(e.type)) v.push(`\uC54C \uC218 \uC5C6\uB294 type: ${e.type}`);
3278
- if (typeof e.eventTime !== "string" || !ISO_RE.test(e.eventTime)) v.push("eventTime ISO8601 \uC544\uB2D8");
3279
- if (typeof e.eventTimeZoneOffset !== "string" || !TZ_RE.test(e.eventTimeZoneOffset)) v.push("eventTimeZoneOffset \uD615\uC2DD \uC624\uB958");
3280
- if (typeof e.bizStep !== "string" || !e.bizStep) v.push("bizStep \uB204\uB77D");
3281
- if (e.eventID !== void 0 && (typeof e.eventID !== "string" || !e.eventID)) v.push("eventID \uAC00 \uBE48 \uBB38\uC790\uC5F4");
3282
- if (e.recordTime !== void 0 && (typeof e.recordTime !== "string" || !ISO_RE.test(e.recordTime))) {
3283
- v.push("recordTime ISO8601 \uC544\uB2D8");
3284
- }
3285
- if (e.ilmd !== void 0) {
3286
- const allowed = e.type === "ObjectEvent" && e.action === "ADD" || e.type === "TransformationEvent";
3287
- if (!allowed) v.push("ilmd \uB294 ObjectEvent(action=ADD) \uB610\uB294 TransformationEvent \uC5D0\uB9CC \uC2E4\uC744 \uC218 \uC788\uB2E4");
3288
- }
3289
- for (const sd of e.sourceList ?? []) {
3290
- if (!sd?.type || !sd?.source) v.push("sourceList \uD56D\uBAA9\uC5D0 type \uB610\uB294 source \uB204\uB77D");
3265
+ function futureFactError(eventTime, opts) {
3266
+ const nowText = opts.nowISO ?? opts.defaultEventTime;
3267
+ if (!nowText) return void 0;
3268
+ const nowMs = Date.parse(nowText);
3269
+ const atMs = Date.parse(eventTime);
3270
+ if (!Number.isFinite(nowMs) || !Number.isFinite(atMs) || atMs <= nowMs) return void 0;
3271
+ return `\uC544\uC9C1 \uC624\uC9C0 \uC54A\uC740 \uC2DC\uAC01\uC758 \uC0AC\uC2E4\uC774\uB2E4(${eventTime}) \u2014 \uB05D\uB098\uC9C0 \uC54A\uC740 \uAE30\uAC04\uC740 \uB9C8\uAC10\uB41C \uC0AC\uC2E4\uC774 \uC544\uB2C8\uB2E4`;
3272
+ }
3273
+ function resolveSubject(kind, localId, opts) {
3274
+ const declared = opts.identityOf?.(kind, localId);
3275
+ if (declared) return { subject: declared, basis: "declared" };
3276
+ return { subject: opts.scopeId ? `${opts.scopeId}/${localId}` : localId, basis: "twin-local" };
3277
+ }
3278
+ function periodFactId(tenantId, kind, subject, from, to) {
3279
+ return [tenantId, kind, subject, from, to].join("|");
3280
+ }
3281
+ function readSpan(r, errors) {
3282
+ const from = String(r?.from ?? "").trim();
3283
+ const to = String(r?.to ?? "").trim();
3284
+ const fromMs = Date.parse(from);
3285
+ const toMs = Date.parse(to);
3286
+ if (!from || !Number.isFinite(fromMs)) errors.push(`from \uC744 \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.from)}`);
3287
+ if (!to || !Number.isFinite(toMs)) errors.push(`to \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.to)}`);
3288
+ if (Number.isFinite(fromMs) && Number.isFinite(toMs) && !(toMs > fromMs)) {
3289
+ errors.push(`\uAD6C\uAC04\uC774 \uB4A4\uC9D1\uD614\uAC70\uB098 \uAE38\uC774\uAC00 \uC5C6\uB2E4(${from} \u2192 ${to}) \u2014 \uC5B4\uB290 \uCABD\uC774 \uD2C0\uB838\uB294\uC9C0 \uC6B0\uB9AC\uAC00 \uC815\uD560 \uC218 \uC5C6\uB2E4`);
3291
3290
  }
3292
- for (const sd of e.destinationList ?? []) {
3293
- if (!sd?.type || !sd?.destination) v.push("destinationList \uD56D\uBAA9\uC5D0 type \uB610\uB294 destination \uB204\uB77D");
3291
+ return errors.length ? void 0 : { from, to };
3292
+ }
3293
+ function readAmount(raw, name, errors) {
3294
+ if (raw === void 0 || raw === null || String(raw).trim() === "") return void 0;
3295
+ const v = Number(raw);
3296
+ if (!Number.isFinite(v)) {
3297
+ errors.push(`${name} \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
3298
+ return void 0;
3294
3299
  }
3295
- if (e.persistentDisposition !== void 0) {
3296
- const set = e.persistentDisposition.set ?? [];
3297
- const unset = e.persistentDisposition.unset ?? [];
3298
- if (!set.length && !unset.length) v.push("persistentDisposition \uC774 set\xB7unset \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3299
- const both = set.filter((x) => unset.includes(x));
3300
- if (both.length) v.push(`persistentDisposition \uC774 \uAC19\uC740 \uAC12\uC744 set\xB7unset \uB3D9\uC2DC \uC9C0\uC815: ${both.join(", ")}`);
3300
+ if (v < 0) {
3301
+ errors.push(`${name} \uAC00 \uC74C\uC218\uB2E4(${v})`);
3302
+ return void 0;
3301
3303
  }
3302
- for (const se of e.sensorElementList ?? []) {
3303
- if (!Array.isArray(se?.sensorReport) || se.sensorReport.length === 0) {
3304
- v.push("sensorElement \uC5D0 sensorReport \uAC00 \uD558\uB098\uB3C4 \uC5C6\uC74C");
3304
+ return v;
3305
+ }
3306
+ function ingestEnergyUsagePeriodRecords(records, opts) {
3307
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3308
+ const accepted = [];
3309
+ const rejected = [];
3310
+ for (const r of list) {
3311
+ const errors = [];
3312
+ const meterId = String(r?.meterId ?? "").trim();
3313
+ if (!meterId) errors.push("meterId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC9C0\uC810\uC774 \uC4F4 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
3314
+ const span = readSpan(r, errors);
3315
+ const rawKWh = r?.kWh;
3316
+ let kWh;
3317
+ if (rawKWh === void 0 || rawKWh === null || String(rawKWh).trim() === "") {
3318
+ errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uADF8 \uAD6C\uAC04\uC5D0 \uC4F4 \uC591\uC774\uB2E4");
3319
+ } else {
3320
+ kWh = readAmount(rawKWh, "kWh", errors);
3305
3321
  }
3306
- }
3307
- if (e.errorDeclaration !== void 0) {
3308
- const d = e.errorDeclaration;
3309
- if (typeof d?.declarationTime !== "string" || !ISO_RE.test(d.declarationTime)) {
3310
- v.push("errorDeclaration.declarationTime ISO8601 \uC544\uB2D8/\uB204\uB77D");
3322
+ const maxKW = readAmount(r?.maxKW, "maxKW", errors);
3323
+ const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
3324
+ const currency = String(r?.currency ?? "").trim() || void 0;
3325
+ if (unitPrice !== void 0 && !currency) errors.push("unitPrice \uB97C \uC2E4\uC5C8\uB294\uB370 currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAE08\uC561\uC740 \uB354\uD560 \uC218 \uC5C6\uB2E4");
3326
+ let basis;
3327
+ const rawBasis = r?.basis;
3328
+ if (rawBasis !== void 0 && rawBasis !== null && String(rawBasis).trim()) {
3329
+ const text = String(rawBasis).trim();
3330
+ if (!OBSERVATION_BASIS.includes(text)) {
3331
+ errors.push(`basis \uAC00 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${OBSERVATION_BASIS.join("\xB7")}): ${JSON.stringify(rawBasis)}`);
3332
+ } else basis = text;
3311
3333
  }
3312
- if (d?.correctiveEventIDs !== void 0) {
3313
- if (!Array.isArray(d.correctiveEventIDs)) v.push("errorDeclaration.correctiveEventIDs \uBC30\uC5F4 \uC544\uB2D8");
3314
- else if (d.correctiveEventIDs.some((x) => typeof x !== "string" || !x)) {
3315
- v.push("errorDeclaration.correctiveEventIDs \uC5D0 \uBE48 \uAC12");
3316
- }
3334
+ if (errors.length || !span || kWh === void 0) {
3335
+ rejected.push({ record: r, errors });
3336
+ continue;
3317
3337
  }
3338
+ const subj = resolveSubject("meter", meterId, opts);
3339
+ const data = {
3340
+ meterId,
3341
+ subject: subj.subject,
3342
+ subjectBasis: subj.basis,
3343
+ from: span.from,
3344
+ to: span.to,
3345
+ kWh,
3346
+ ...maxKW !== void 0 ? { maxKW } : {},
3347
+ ...unitPrice !== void 0 ? { unitPrice } : {},
3348
+ ...currency ? { currency } : {},
3349
+ ...basis ? { basis } : {}
3350
+ };
3351
+ const futureError = futureFactError(span.to, opts);
3352
+ if (futureError) {
3353
+ rejected.push({ record: r, errors: [futureError] });
3354
+ continue;
3355
+ }
3356
+ accepted.push({
3357
+ eventId: periodFactId(opts.tenantId, ENERGY_EVENT.usagePeriod, subj.subject, span.from, span.to),
3358
+ eventType: ENERGY_EVENT.usagePeriod,
3359
+ /* 구간의 **끝**이 이 사실이 성립한 시각이다 — 시작으로 달면 저널이 그 구간을 미리 안 것이 된다. */
3360
+ eventTime: span.to,
3361
+ tenantId: opts.tenantId,
3362
+ data
3363
+ });
3318
3364
  }
3319
- if (e.type === "ObjectEvent") {
3320
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3321
- if (!Array.isArray(e.epcList)) v.push("ObjectEvent.epcList \uB204\uB77D");
3322
- else if (e.epcList.length === 0 && !e.quantityList?.length) v.push("ObjectEvent: epcList/quantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3323
- } else if (e.type === "AggregationEvent") {
3324
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3325
- if (!e.parentID) v.push("AggregationEvent.parentID \uB204\uB77D");
3326
- if (!e.childEPCs?.length && !e.childQuantityList?.length) v.push("AggregationEvent: childEPCs/childQuantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3327
- } else if (e.type === "TransactionEvent") {
3328
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3329
- if (!Array.isArray(e.bizTransactionList) || e.bizTransactionList.length === 0) v.push("TransactionEvent.bizTransactionList \uB204\uB77D");
3330
- } else if (e.type === "TransformationEvent") {
3331
- if (!e.inputEPCList?.length && !e.inputQuantityList?.length) v.push("TransformationEvent: input \uBE44\uC5B4\uC788\uC74C");
3332
- if (!e.outputEPCList?.length && !e.outputQuantityList?.length) v.push("TransformationEvent: output \uBE44\uC5B4\uC788\uC74C");
3333
- }
3334
- const qtyLists = [
3335
- "quantityList" in e ? e.quantityList : void 0,
3336
- "childQuantityList" in e ? e.childQuantityList : void 0,
3337
- "inputQuantityList" in e ? e.inputQuantityList : void 0,
3338
- "outputQuantityList" in e ? e.outputQuantityList : void 0
3339
- ];
3340
- for (const list of qtyLists) for (const q of list ?? []) {
3341
- const bad2 = classIdentifierViolation(q.epcClass);
3342
- if (bad2) v.push(bad2);
3343
- const hasQty = q.quantity !== void 0 && q.quantity !== null;
3344
- if (!hasQty) {
3345
- if (q.uom !== void 0) v.push("quantity \uC5C6\uC73C\uBA74 uom \uB3C4 \uC5C6\uC5B4\uC57C \uD55C\uB2E4(\uC218\uB7C9 \uBBF8\uC9C0\uC815)");
3365
+ return { accepted, rejected };
3366
+ }
3367
+ function ingestEnergyBillRecords(records, opts) {
3368
+ const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
3369
+ const accepted = [];
3370
+ const rejected = [];
3371
+ for (const r of list) {
3372
+ const errors = [];
3373
+ const span = readSpan(r, errors);
3374
+ const energyCharge = readAmount(r?.energyCharge, "energyCharge", errors);
3375
+ const demandCharge = readAmount(r?.demandCharge, "demandCharge", errors);
3376
+ const total = readAmount(r?.total, "total", errors);
3377
+ const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
3378
+ if (energyCharge === void 0 && demandCharge === void 0 && total === void 0) {
3379
+ errors.push("\uAE08\uC561\uC774 \uD558\uB098\uB3C4 \uC5C6\uB2E4 \u2014 \uC801\uC744 \uC0AC\uC2E4\uC774 \uC5C6\uB294 \uCCAD\uAD6C\uC11C\uB294 \uBC1B\uC9C0 \uC54A\uB294\uB2E4");
3380
+ }
3381
+ const currency = String(r?.currency ?? "").trim() || void 0;
3382
+ if (!currency) errors.push("currency \uAC00 \uC5C6\uB2E4 \u2014 \uB2E8\uC704 \uC5C6\uB294 \uAE08\uC561\uC740 \uB2E4\uB978 \uAE08\uC561\uACFC \uB354\uD560 \uC218 \uC5C6\uB2E4");
3383
+ if (errors.length || !span) {
3384
+ rejected.push({ record: r, errors });
3346
3385
  continue;
3347
3386
  }
3348
- if (typeof q.quantity !== "number" || !Number.isFinite(q.quantity) || q.quantity <= 0) {
3349
- v.push("quantity \uB294 \uC591\uC218\uC5EC\uC57C \uD55C\uB2E4(\uBAA8\uB974\uBA74 \uC0DD\uB7B5)");
3387
+ const data = {
3388
+ from: span.from,
3389
+ to: span.to,
3390
+ ...energyCharge !== void 0 ? { energyCharge } : {},
3391
+ ...demandCharge !== void 0 ? { demandCharge } : {},
3392
+ ...total !== void 0 ? { total } : {},
3393
+ ...currency ? { currency } : {},
3394
+ ...billingDemandKW !== void 0 ? { billingDemandKW } : {}
3395
+ };
3396
+ const futureError = futureFactError(span.to, opts);
3397
+ if (futureError) {
3398
+ rejected.push({ record: r, errors: [futureError] });
3350
3399
  continue;
3351
3400
  }
3352
- if (q.uom === void 0 && !Number.isInteger(q.quantity)) v.push("uom \uC5C6\uB294 quantity \uB294 \uC815\uC218(\uAC1C\uC218)\uC5EC\uC57C \uD55C\uB2E4");
3353
- if (q.uom !== void 0 && !/^[A-Z0-9]{2,3}$/.test(q.uom)) v.push(`uom \uD615\uC2DD \uBD80\uC815(UN/CEFACT \uAD8C\uACE0 20 \uC758 2~3\uC790 \uCF54\uB4DC): ${q.uom}`);
3401
+ accepted.push({
3402
+ eventId: periodFactId(opts.tenantId, ENERGY_EVENT.bill, "", span.from, span.to),
3403
+ eventType: ENERGY_EVENT.bill,
3404
+ eventTime: span.to,
3405
+ tenantId: opts.tenantId,
3406
+ data
3407
+ });
3354
3408
  }
3355
- return v;
3409
+ return { accepted, rejected };
3356
3410
  }
3357
3411
 
3358
3412
  // src/order-fold.ts
3413
+ var ORDER_FOLD_HOUR_MS = 60 * 60 * 1e3;
3359
3414
  var ORDER_FOLD_DEFAULT = Object.freeze({ afterMs: 24 * 60 * 60 * 1e3, maxTerminal: 1e3 });
3360
3415
  function orderFoldPolicyOf(declared) {
3361
3416
  const policy = { ...ORDER_FOLD_DEFAULT };
@@ -3367,6 +3422,9 @@ function orderFoldPolicyOf(declared) {
3367
3422
  }
3368
3423
  policy[key] = key === "maxTerminal" ? Math.floor(v) : v;
3369
3424
  }
3425
+ if (policy.afterMs % ORDER_FOLD_HOUR_MS !== 0) {
3426
+ return { error: `order fold afterMs must be a whole number of hours, got ${policy.afterMs} ms \u2014 the window is counted in hour slots (ADR-0092)` };
3427
+ }
3370
3428
  if (policy.maxTerminal < 1) return { error: "order fold maxTerminal must be at least 1 (ADR-0092)" };
3371
3429
  return { policy };
3372
3430
  }
@@ -3391,6 +3449,9 @@ function foldOrdersInto(folded, orders) {
3391
3449
  counts: Object.fromEntries(Object.entries(folded?.counts ?? {}).map(([k, v]) => [k, { ...v }])),
3392
3450
  boundaryMs: folded?.boundaryMs ?? null
3393
3451
  };
3452
+ const hours = Object.fromEntries(
3453
+ Object.entries(folded?.hours ?? {}).map(([h, byKind]) => [h, Object.fromEntries(Object.entries(byKind).map(([k, v]) => [k, { ...v }]))])
3454
+ );
3394
3455
  for (const o of orders) {
3395
3456
  const kind = String(o.kind ?? "");
3396
3457
  const status = String(o.status ?? "");
@@ -3398,8 +3459,11 @@ function foldOrdersInto(folded, orders) {
3398
3459
  byStatus[status] = (byStatus[status] ?? 0) + 1;
3399
3460
  if (typeof o.terminalAtMs === "number" && Number.isFinite(o.terminalAtMs)) {
3400
3461
  out.boundaryMs = out.boundaryMs === null ? o.terminalAtMs : Math.max(out.boundaryMs, o.terminalAtMs);
3462
+ const slot = (hours[String(hourStartOf(o.terminalAtMs))] ??= {})[kind] ??= {};
3463
+ slot[status] = (slot[status] ?? 0) + 1;
3401
3464
  }
3402
3465
  }
3466
+ if (Object.keys(hours).length) out.hours = hours;
3403
3467
  return out;
3404
3468
  }
3405
3469
  function standsNewOrderRow(record, eventTimeMs, folded) {
@@ -3409,6 +3473,43 @@ function standsNewOrderRow(record, eventTimeMs, folded) {
3409
3473
  if (typeof eventTimeMs !== "number" || !Number.isFinite(eventTimeMs)) return true;
3410
3474
  return eventTimeMs > boundary;
3411
3475
  }
3476
+ function hourStartOf(ms) {
3477
+ return Math.floor(ms / ORDER_FOLD_HOUR_MS) * ORDER_FOLD_HOUR_MS;
3478
+ }
3479
+ function finishedWindowStartMs(nowMs, policy = ORDER_FOLD_DEFAULT) {
3480
+ return hourStartOf(nowMs) - policy.afterMs;
3481
+ }
3482
+ function pruneFoldedHours(folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
3483
+ if (!folded.hours) return folded;
3484
+ const start = finishedWindowStartMs(nowMs, policy);
3485
+ const kept = Object.fromEntries(Object.entries(folded.hours).filter(([h]) => Number(h) >= start));
3486
+ const out = { counts: folded.counts, boundaryMs: folded.boundaryMs };
3487
+ if (Object.keys(kept).length) out.hours = kept;
3488
+ return out;
3489
+ }
3490
+ function finishedFlowOrdersWithin(hot, folded, nowMs, policy = ORDER_FOLD_DEFAULT) {
3491
+ const fromMs = finishedWindowStartMs(nowMs, policy);
3492
+ let count = 0;
3493
+ const byStatus = {};
3494
+ const add = (status, n) => {
3495
+ const key = String(status ?? "");
3496
+ byStatus[key] = (byStatus[key] ?? 0) + n;
3497
+ count += n;
3498
+ };
3499
+ for (const o of hot) {
3500
+ if (!isFlowOrder(o) || !isOrderTerminal(o)) continue;
3501
+ const at2 = o.terminalAtMs;
3502
+ if (typeof at2 === "number" && at2 >= fromMs && at2 <= nowMs) add(o.status, 1);
3503
+ }
3504
+ for (const [h, byKind] of Object.entries(folded?.hours ?? {})) {
3505
+ if (Number(h) < fromMs || Number(h) > nowMs) continue;
3506
+ for (const [kind, statuses] of Object.entries(byKind)) {
3507
+ if (!isFlowOrder({ kind })) continue;
3508
+ for (const [status, c] of Object.entries(statuses)) add(status, c);
3509
+ }
3510
+ }
3511
+ return { fromMs, toMs: nowMs, count, byStatus };
3512
+ }
3412
3513
 
3413
3514
  // src/face2-adapter.ts
3414
3515
  function isAggregationRecord(record) {
@@ -5027,6 +5128,7 @@ function nonEmpty(value) {
5027
5128
  ERP_MASTER_AXIS,
5028
5129
  FIRST_PASS_RULE,
5029
5130
  GUARD_PRAGMA,
5131
+ HATIOLAB_VOCABULARY,
5030
5132
  ILMD_ATTR,
5031
5133
  LOCATION_SATURATION_NEAR,
5032
5134
  MATERIAL_ACTUAL_USE,
@@ -5044,8 +5146,10 @@ function nonEmpty(value) {
5044
5146
  OP_EVENT,
5045
5147
  OP_PARAM,
5046
5148
  ORDER_FOLD_DEFAULT,
5149
+ ORDER_FOLD_HOUR_MS,
5047
5150
  ORDER_TERMINAL_STATUS,
5048
5151
  PRIORITY_UNSET,
5152
+ PRIVATE_BIZSTEP,
5049
5153
  READ_BASIS,
5050
5154
  REFUSED_WITHOUT_CODE,
5051
5155
  RESOURCE_KIND,
@@ -5070,6 +5174,7 @@ function nonEmpty(value) {
5070
5174
  WMS_RECEIVING_ORDER_KINDS,
5071
5175
  WMS_TYPES,
5072
5176
  YARD_BIZSTEP,
5177
+ YARD_PRIVATE_BIZSTEP,
5073
5178
  YMS_LOCATION_TYPES,
5074
5179
  YMS_TYPES,
5075
5180
  acceptsPerformance,
@@ -5084,6 +5189,7 @@ function nonEmpty(value) {
5084
5189
  axisAppliesTo,
5085
5190
  axisInfo,
5086
5191
  axisSource,
5192
+ bizStepName,
5087
5193
  bizTransactionUri,
5088
5194
  canPreview,
5089
5195
  capabilitiesForType,
@@ -5111,6 +5217,8 @@ function nonEmpty(value) {
5111
5217
  equipmentClassMembership,
5112
5218
  erpCapabilityGaps,
5113
5219
  expiryFromAttributes,
5220
+ finishedFlowOrdersWithin,
5221
+ finishedWindowStartMs,
5114
5222
  foldOrdersInto,
5115
5223
  foldedOrderCount,
5116
5224
  gdtiUri,
@@ -5119,6 +5227,7 @@ function nonEmpty(value) {
5119
5227
  gs1KeyDigitViolation,
5120
5228
  hierarchyOf,
5121
5229
  homeOf,
5230
+ hourStartOf,
5122
5231
  identityGroundingOf,
5123
5232
  inWorkCalendar,
5124
5233
  inWorkCalendarAt,
@@ -5203,6 +5312,7 @@ function nonEmpty(value) {
5203
5312
  priorityRank,
5204
5313
  procedureViolations,
5205
5314
  propertiesOf,
5315
+ pruneFoldedHours,
5206
5316
  quantityIn,
5207
5317
  ratedUsageOf,
5208
5318
  readBoardAssets,