@operato/ops-contract 0.9.37 → 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,
@@ -70,6 +71,7 @@ __export(index_exports, {
70
71
  ORDER_FOLD_HOUR_MS: () => ORDER_FOLD_HOUR_MS,
71
72
  ORDER_TERMINAL_STATUS: () => ORDER_TERMINAL_STATUS,
72
73
  PRIORITY_UNSET: () => PRIORITY_UNSET,
74
+ PRIVATE_BIZSTEP: () => PRIVATE_BIZSTEP,
73
75
  READ_BASIS: () => READ_BASIS,
74
76
  REFUSED_WITHOUT_CODE: () => REFUSED_WITHOUT_CODE,
75
77
  RESOURCE_KIND: () => RESOURCE_KIND,
@@ -94,6 +96,7 @@ __export(index_exports, {
94
96
  WMS_RECEIVING_ORDER_KINDS: () => WMS_RECEIVING_ORDER_KINDS,
95
97
  WMS_TYPES: () => WMS_TYPES,
96
98
  YARD_BIZSTEP: () => YARD_BIZSTEP,
99
+ YARD_PRIVATE_BIZSTEP: () => YARD_PRIVATE_BIZSTEP,
97
100
  YMS_LOCATION_TYPES: () => YMS_LOCATION_TYPES,
98
101
  YMS_TYPES: () => YMS_TYPES,
99
102
  acceptsPerformance: () => acceptsPerformance,
@@ -108,6 +111,7 @@ __export(index_exports, {
108
111
  axisAppliesTo: () => axisAppliesTo,
109
112
  axisInfo: () => axisInfo,
110
113
  axisSource: () => axisSource,
114
+ bizStepName: () => bizStepName,
111
115
  bizTransactionUri: () => bizTransactionUri,
112
116
  canPreview: () => canPreview,
113
117
  capabilitiesForType: () => capabilitiesForType,
@@ -1343,7 +1347,26 @@ var BIZSTEP = {
1343
1347
  packing: "urn:epcglobal:cbv:bizstep:packing",
1344
1348
  staging_outbound: "urn:epcglobal:cbv:bizstep:staging_outbound",
1345
1349
  shipping: "urn:epcglobal:cbv:bizstep:shipping",
1346
- 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"
1347
1370
  };
1348
1371
  var BTT = {
1349
1372
  /** Purchase Order — the document an inbound receipt is made against. */
@@ -1410,221 +1433,692 @@ var WMS_TYPES = [
1410
1433
  { key: "packer", role: "equipment", label: "twin.type.packer", standardClass: { epcis: "object", isa95: "Equipment" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] }
1411
1434
  ];
1412
1435
 
1413
- // src/yms-profile.ts
1414
- var YARD_BIZSTEP = {
1415
- arriving: "urn:epcglobal:cbv:bizstep:arriving",
1416
- // 게이트-인
1417
- staging: "urn:epcglobal:cbv:bizstep:staging",
1418
- // 야드 슬롯 주차·대기
1419
- loading: "urn:epcglobal:cbv:bizstep:loading",
1420
- // 도크 작업(상차: 트레일러←화물)
1421
- unloading: "urn:epcglobal:cbv:bizstep:unloading",
1422
- // 도크 작업(하차: 트레일러→화물)
1423
- departing: "urn:epcglobal:cbv:bizstep:departing"
1424
- // 게이트-아웃
1425
- };
1426
- function graiUri(companyPrefix, assetType, serial) {
1427
- return `urn:epc:id:grai:${companyPrefix}.${assetType}.${String(serial).padStart(6, "0")}`;
1428
- }
1429
- var YMS_LOCATION_TYPES = ["gate", "yard-slot", "dock-door", "staging"];
1430
- var YMS_LOCATION_LEVEL = {
1431
- gate: "Other",
1432
- "yard-slot": "StorageUnit",
1433
- "dock-door": "StorageUnit",
1434
- staging: "StorageZone"
1435
- };
1436
- var YMS_TYPES = [
1437
- ...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"] })),
1438
- { key: "hostler", role: "equipment", label: "twin.type.hostler", standardClass: { epcis: "object", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["mobile", "operable"] }
1439
- ];
1440
-
1441
- // src/mes-profile.ts
1442
- var MES_BIZSTEP = {
1443
- receiving: "urn:epcglobal:cbv:bizstep:receiving",
1444
- // 원자재 수령
1445
- producing: "urn:epcglobal:cbv:bizstep:commissioning",
1446
- // 생산(제품 최초 생성)
1447
- storing: "urn:epcglobal:cbv:bizstep:storing"
1448
- // 완제품 저장
1449
- };
1450
- var BTT_PRODORDER = "urn:epcglobal:cbv:btt:prodorder";
1451
- function sgtinUri(companyPrefix, itemRef, serial) {
1452
- return `urn:epc:id:sgtin:${companyPrefix}.${itemRef}.${serial}`;
1453
- }
1454
- var MES_LOCATION_TYPES = ["raw-store", "cut-station", "weld-station", "paint-booth", "assembly-line", "fg-store"];
1455
- var MES_LOCATION_CLS = {
1456
- "raw-store": { epcis: "bizLocation" },
1457
- "cut-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1458
- "weld-station": { isa95: "WorkCenter", epcis: "bizLocation" },
1459
- "paint-booth": { isa95: "WorkCenter", epcis: "bizLocation" },
1460
- "assembly-line": { isa95: "WorkCenter", epcis: "bizLocation" },
1461
- "fg-store": { epcis: "bizLocation" }
1462
- };
1463
- var MES_LOCATION_LEVEL = {
1464
- "raw-store": "StorageZone",
1465
- "cut-station": "WorkCell",
1466
- "weld-station": "WorkCell",
1467
- "paint-booth": "WorkCell",
1468
- "assembly-line": "ProductionLine",
1469
- "fg-store": "StorageZone"
1470
- };
1471
- var MES_TYPES = [
1472
- ...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"] })),
1473
- { key: "cutter", role: "equipment", label: "twin.type.cutter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1474
- { key: "welder", role: "equipment", label: "twin.type.welder", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1475
- { key: "painter", role: "equipment", label: "twin.type.painter", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] },
1476
- { key: "assembler", role: "equipment", label: "twin.type.assembler", standardClass: { isa95: "Equipment", iso55000: "Asset" }, identity: { scheme: "gs1:GIAI" }, capabilities: ["processable", "operable"] }
1477
- ];
1478
- var MES_COMMANDS = [
1479
- {
1480
- type: "production.order",
1481
- label: "\uC0DD\uC0B0 \uC9C0\uC2DC",
1482
- /*
1483
- * 되돌릴 수 없다. 지시가 나가면 사람과 설비가 그것으로 움직이고, 취소해도 이미 만든 것은 남는다.
1484
- * 그래서 사람 승인을 지난다(§`requiresApproval`).
1485
- */
1486
- reversible: false,
1487
- /*
1488
- * 단위를 요구하는 이유 — 단위 없는 수량은 지시가 되지 못한다. 우리가 기본 단위를 지어내면 그것이
1489
- * 현장의 단위와 다른 날 수량이 조용히 틀린다.
1490
- */
1491
- required: ["materialDefinitionId", "quantity", "uom"]
1492
- }
1493
- ];
1494
-
1495
- // src/ems-profile.ts
1496
- var EMS_LOCATION_TYPES = ["incoming", "feeder", "submeter-zone"];
1497
- var METER_DIRECTION = ["import", "export", "bidirectional"];
1498
- var EMS_EQUIPMENT_TYPES = ["meter", "breaker", "pv-array", "battery", "utility", "curtailable-load"];
1499
- var EMS_PROPERTY = {
1500
- /** 계약전력(kW) — 수전·분기 자리에 선언한다. 없으면 계약 대비 판정을 하지 않는다. */
1501
- contractKW: "contract.kW",
1502
- /*
1503
- * ── 계량 지점의 방향 (2026-08-25) ──────────────────────────────────────────
1504
- * **요금은 계통 접속점의 순 유입에 매겨진다.** 그러니 그 지점의 계량기가 무엇을 재는지 모르면
1505
- * 요금을 사실대로 말할 수 없다 — 내보낸 양을 쓴 양으로 세면 계약 대비 판단이 반대로 뒤집힌다.
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`.
1506
1448
  *
1507
- * 이 축이 없는 동안 계량 지점의 kW 를 전부 부하로 셌다. 상계 거래를 하는 현장, 축전지를 붙인 현장,
1508
- * 열병합이 있는 현장 — 접속점 계량기가 양쪽을 재는 곳은 늘 있다.
1449
+ * ── 왜 `non_sellable` 로 계산하지 않나 (2026-08-24) ─────────────────────────────
1450
+ * 커널의 `non_sellable` 은 CBV 의 `non_sellable_other`, 즉 **「그 밖의 이유」**다. 기한 지남을 거기
1451
+ * 넣으면 「기한이 지나 못 판다」와 「깨져서 못 판다」가 같은 값이 되고, 화면은 회수·폐기의 사유를
1452
+ * 구별할 수 없다. 식품에서 그 둘은 다른 조치다.
1509
1453
  *
1510
- * **발전기를 계량기로 만드는 것과 다른 일이다.** 발전은 설비의 사실이고(`energyGenerating`), 그것을
1511
- * 계량 지점으로 보내는 것은 여전히 하지 않는다. 이 축은 **접속점 계량기**가 무엇을 재는지 말하는
1512
- * 자리다.
1454
+ * 그리고 표준에 **정확한 낱말이 있다** — 합치는 것은 있는 낱말을 버리는 것이다.
1513
1455
  *
1514
- * 방향은 **관측이 아니라 선언**이다. 표본마다 바뀌는 값이 아니고, 그 계량기가 무엇을 재도록
1515
- * 설치되었는지는 현장이 안다. 그래서 표본(`EnergyRecord`)에 넣지 않고 자원 속성으로 둔다.
1456
+ * ── 기한 날짜와 다른 축이다 ────────────────────────────────────────────────
1457
+ * `ItemState.expiry` 는 **날짜**이고 이것은 **상태**다. 날짜가 있으면 「지났나」는 파생이지만, 원본이
1458
+ * 「기한 지남」을 상태로 선언하는 시스템이 있다 — 그때 이 값은 관측이다.
1516
1459
  *
1517
- * 값은 계량기 자신의 낱말을 쓴다(적산 레지스터가 그렇게 갈려 있다). §`METER_DIRECTION`.
1518
- */
1519
- meterDirection: "meter.direction",
1520
- /*
1521
- * ── 부하 계수 — 시뮬레이션이 전기를 만들 수 있게 (2026-08-14) ───────────────
1522
- * 「이 설비가 돌면 몇 kW 인가」는 **현장이 아는 값**이다. 그래서 타입 기본값을 두지 않는다:
1523
- * 선언하지 않은 설비는 부하를 만들지 않는다. 기본값을 두면 아무도 그 수가 짐작인 줄 모른 채
1524
- * 요금 판정이 그 위에 선다.
1525
- */
1526
- /** 가동 중 소비(kW). */
1527
- ratedKW: "power.ratedKW",
1528
- /** 멈춰 있을 때의 소비(kW). 없으면 멈춘 동안을 **비운다** — 0 이라고 주장하지 않는다. */
1529
- standbyKW: "power.standbyKW",
1530
- /*
1531
- * ── 요금 단가 — 수를 금액으로 바꾸는 선언 (2026-08-17) ─────────────────────
1460
+ * 둘이 어긋나면(날짜는 남았는데 상태가 지남, 또는 그 반대) **어느 쪽이 맞다고 정하지 않는다** —
1461
+ * 아직 그 판정을 세울 근거가 없다. 어긋남의 구분을 없애지 않는 것이 지금의 규율이다.
1532
1462
  *
1533
- * 그동안 트윈은 「최대수요 328kW」·「전력량 1,547kWh」까지 말하고 멈췄다. 그런데 피크를 깎는 일이
1534
- * 돈이 되는 이유는 **요금이 둘로 나뉘기** 때문이다: 사용량(kWh)에 붙는 요금과 **최대수요(kW)에 붙는
1535
- * 기본요금**. 단가가 없으면 그 절반을 말할 수 없고, 그래서 「피크를 깎아 얼마를 아끼나」에 답하지 못했다.
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
+ * 그 표에 있다.
1536
1467
  *
1537
- * 단가는 **현장의 계약**이다(같은 나라 안에서도 사업자·요금제마다 다르다). 그래서 기본값을 두지
1538
- * 않는다 — 선언하지 않으면 금액을 계산하지 않는다. 짐작한 단가로 낸 금액은 숫자가 있다는 것만으로
1539
- * 사람을 결정으로 밀어붙인다.
1468
+ * **`non_sellable_expired` 를 쓰지 않는 이유**: 그 값은 CBV 1.0 의 것이고 표준이 **폐기**했다 —
1469
+ * 「deprecated in favour of new disposition values expired, damaged, disposed, … introduced in
1470
+ * CBV 1.1」. 폐기된 값을 쓰면 새 소비처가 읽지 못한다.
1540
1471
  *
1541
- * 계약전력(`contract.kW`)과 같은 자리(수전)에 선언한다.
1472
+ * 참고: GS1 어휘 등록처(`ref.gs1.org/cbv/…`)로는 확인할 수 없었다 — **없는 값에도 같은 응답**을
1473
+ * 준다(지어낸 값의 JSON-LD 가 실재 값과 바이트까지 같았다). 그 경로를 근거로 삼지 말 것.
1542
1474
  */
1543
- /** 기본요금 단가 — 최대수요 1kW 당(청구 주기 기준). */
1544
- demandChargePerKW: "tariff.demandChargePerKW",
1475
+ expired: "urn:epcglobal:cbv:disp:expired",
1545
1476
  /**
1546
- * **요금적용전력**(kW) — 기본요금이 실제로 매겨지는 기준. 계약전력과 다른 값이다.
1547
- *
1548
- * 기본요금이 걸리는 수는 이 주기에 잰 최대가 아닌 경우가 많다 — 지난 몇 달의 최고를 끌고 가거나,
1549
- * 약정 용량으로 매기거나, 사업자가 따로 정한다. 그 규칙은 나라와 계약마다 다르므로 커널이 계산하지
1550
- * 않고 **계산된 결과를 받는다.** 이 값이 있으면 기본요금이 조건부 파생이 아니라 사실이 된다.
1551
- *
1552
- * 계약전력(`contract.kW`)을 이 자리에 넣지 말 것. 넘었을 때의 뜻이 다르다 — 계약 초과는 약정
1553
- * 위반이고, 이쪽은 다음 주기의 기본요금이 오른다는 뜻이다.
1554
- */
1555
- billingDemandKW: "tariff.billingDemandKW",
1556
- /** 사용량 단가 — 1kWh 당. */
1557
- energyChargePerKWh: "tariff.energyChargePerKWh",
1558
- /** 통화 — ISO 4217 코드(USD·KRW…). 없으면 금액에 단위를 붙이지 않는다. */
1559
- currency: "tariff.currency",
1560
- /*
1561
- * ── 축전지의 용량과 방전 정책 (2026-08-17) ─────────────────────────────────
1562
- *
1563
- * 「배터리로 피크를 깎는다」를 시뮬이 보이려면 방전을 만들어야 하고, 그것은 **선언에서** 나와야 한다.
1564
- * 임계·최대율·예비를 우리가 정하면 그 수가 어디서 왔는지 아무도 설명할 수 없다.
1565
- *
1566
- * ── 선언한다는 것은 「그 자동화가 있다」는 주장이다 ─────────────────────────
1567
- * 이 정책을 모델에 적으면 **라이브가 아닌 모든 구동이 그 규칙으로 돈다.** 현장에 BESS 제어기가 없는데
1568
- * 적으면 파생 부하가 실제보다 낙관적으로 나온다(피크가 깎인 것으로 보인다). 그러니 「도입하면?」을
1569
- * 묻는 것이라면 선언이 아니라 **what-if 가 덮어쓸 일**이다.
1570
- *
1571
- * 용량이 없으면 방전하지 않는다 — 용량을 모르면 「얼마나 버티나」를 답할 수 없고, 버티는 시간을
1572
- * 모른 채 깎으면 무한히 깎을 수 있다고 주장하는 셈이다.
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.
1573
1481
  */
1574
- /** 축전지 용량(kWh) — SOC 를 에너지로 바꾸는 값. 없으면 방전을 만들지 않는다. */
1575
- capacityKWh: "storage.capacityKWh",
1576
- /** 이 순수요를 넘으면 방전한다(kW) — 피크 억제 임계. */
1577
- dischargeAboveKW: "dispatch.dischargeAboveKW",
1578
- /** 최대 방전율(kW) — 인버터가 낼 수 있는 한계. */
1579
- maxDischargeKW: "dispatch.maxDischargeKW",
1580
- /** 예비 SOC(%) — 이 아래로는 쓰지 않는다(비상 대비). 없으면 0 으로 본다. */
1581
- reserveSoc: "dispatch.reserveSoc",
1482
+ destroyed: "urn:epcglobal:cbv:disp:destroyed",
1582
1483
  /**
1583
- * 시뮬레이션이 **출발할 때의 SOC(%)** — 씨앗값이다.
1484
+ * **검사에 합격했다 / 불합격했다** — CBV `conformant` / `non_conformant`.
1584
1485
  *
1585
- * 계측이 SOC 를 알려 주는 트윈에는 필요 없다(잰 값이 진실이다). 시뮬 트윈에는 알려 줄 것이 없어서
1586
- * 「SOC 를 모르면 방전하지 않는다」는 규율에 걸려 **배터리가 아무 일도 하지 못했다** — 정책을 선언해도
1587
- * 피크가 한 톨도 깎이지 않았다(실화면에서 그렇게 났다).
1486
+ * 1차 출처(CBV 2.0 §7.2.3) 정의 그대로다.
1588
1487
  *
1589
- * 이것은 상태의 씨앗이지 계측이 아니다. 그래서 계측이 들어오는 순간 그것이 이긴다.
1590
- */
1591
- initialSoc: "storage.initialSoc",
1592
- /*
1593
- * ── 발전 — 태양광이 서 있기만 하던 자리 (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
1594
1490
  *
1595
- * 계통도에 태양광을 그려 놓고 시뮬에서는 한 톨도 만들지 못했다. 미러는 원천이 발전량을 보내 주지만,
1596
- * 시뮬 트윈에는 그것을 만들 근거가 없었다 — 그래서 「태양광을 늘리면 피크가 얼마나 내려가나」를 물을 수
1597
- * 없었다(what-if 의 값이 절반만 성립했다).
1491
+ * ── 왜 시험 결과 축을 자원에 더하지 않고 이것을 쓰나 (2026-08-24) ────────────
1492
+ * 로트의 검사 판정을 담을 자리를 찾다가 `ItemState.testResults` 를 더하려 했다. 그런데 표준은 그
1493
+ * 사실을 **이미 처분으로 말한다**: `bizStep: inspecting` 사건에 이 처분이 붙는다.
1598
1494
  *
1599
- * **형상을 우리가 지어내지 않는다.** 위도·계절·날씨로 곡선을 만들면 그 수가 어디서 왔는지 아무도
1600
- * 설명할 수 없고, 흐린 날 현장의 실적과 어긋난다. 그래서 현장이 **하루 형상을 적는다**: 24개 비율
1601
- * (0~1)이면 그것이 그 현장의 곡선이다(측정한 형상을 그대로 붙일 수 있다).
1495
+ * 처분을 쓰면 두 가지가 공짜로 성립한다.
1496
+ * ① **상태 ⊆ 이벤트** — 처분은 이미 사건에서 온다. 상태에만 있는 축을 만들지 않는다
1497
+ * ② **운영에 곧 닿는다** — 「이 자재를 쓸 수 있나」가 처분으로 답해진다(판정을 따로 읽지 않는다)
1602
1498
  *
1603
- * 정격만 있고 형상이 없으면 발전하지 않는다 — 하루 종일 정격으로 발전하는 태양광은 없다.
1499
+ * 시험의 **자세한 내용**(어느 명세로, 무엇을 재어)은 다른 물음이고, 표준은 그것을 `TestResult` 로
1500
+ * 두며 결과가 대상을 가리킨다(`TestableObjectID`) — 대상이 결과를 들지 않는다. 그 축이 필요해지면
1501
+ * 그때 열되, **판정 자체는 여기서 끝난다.**
1604
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). */
1605
1519
  /**
1606
- * 발전 정격(kW) — **교류 쪽 최대 출력**. 계통으로 나가는 값이다.
1607
- *
1608
- * 이용률의 분모가 이 값이다(만든 양 ÷ 정격 × 시간). **직류 쪽 정격(§`genRatedKWdc`)과 다르고 더 작다** —
1609
- * 두 값을 한 이름에 담으면 이용률이 그 차이만큼 틀리고, 틀린 이유가 아무 데도 표시되지 않는다.
1610
- *
1611
- * 설비마다 선언하거나, 설비별 값을 모르는 현장은 **자리(수전)에 합계로** 선언한다.
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.
1612
1524
  */
1613
- genRatedKW: "generation.ratedKW",
1525
+ destroying: "urn:epcglobal:cbv:bizstep:destroying",
1526
+ /** 새 물품이 생겨 계보가 시작된다 — ISA-95 `MaterialUse: Produced`. */
1527
+ commissioning: "urn:epcglobal:cbv:bizstep:commissioning",
1614
1528
  /**
1615
- * 발전 정격(kW) — **직류 쪽**. 변환기(인버터)의 입력 쪽 정격이고, 태양광이면 패널 정격의 합이다.
1529
+ * **검사** — CBV `inspecting`. 1차 출처(CBV 2.0) 정의: 「Process of reviewing objects to address
1530
+ * potential physical or documentation defects」이고, 「표본과 달리 검사된 대상은 그대로 남는다」고
1531
+ * 이어진다(즉 검사는 물건을 소비하지 않는다).
1616
1532
  *
1617
- * 이용률의 분모로 쓰지 않는다. 이 값이 교류 정격보다 큰 것은 설계이고(변환기를 그렇게 고른다),
1618
- * 그 차이가 「맑은 정오에도 교류 출력이 더 오르지 않는 이유」를 설명한다.
1533
+ * 이 단계에 `DISP.conformant`/`DISP.non_conformant` 가 붙어 판정이 처분으로 남는다 — 입고검수·
1534
+ * 공정 중 검사가 그 모양이다.
1619
1535
  */
1620
- genRatedKWdc: "generation.ratedKWdc",
1536
+ inspecting: "urn:epcglobal:cbv:bizstep:inspecting",
1621
1537
  /**
1622
- * 하루 형상 — 쉼표로 나눈 **24개 비율**(0~1). 시각(현장 시간대)의 정격 대비 출력이다.
1538
+ * **어느 단계로도 이름 붙지 않는 활동** — 원문: 「A business step not identified by any other」.
1623
1539
  *
1624
- * 예: `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`
1625
- */
1626
- genDailyProfile: "generation.dailyProfile"
1627
- };
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"
1547
+ };
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.");
1556
+ }
1557
+ function ssccUri(companyPrefix, serial) {
1558
+ return `urn:epc:id:sscc:${companyPrefix}.${String(serial).padStart(10, "0")}`;
1559
+ }
1560
+ function sgtinClass(companyPrefix, itemRef) {
1561
+ return `urn:epc:idpat:sgtin:${companyPrefix}.${itemRef}.*`;
1562
+ }
1563
+ var ILMD_ATTR = {
1564
+ /** 유통기한·만료(로트 단위). */
1565
+ expiry: "cbvmda:itemExpirationDate",
1566
+ /** 로트·배치 번호(직렬 개체에 로트를 붙일 때). */
1567
+ lot: "cbvmda:lotNumber"
1568
+ };
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
1591
+ };
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
1608
+ };
1609
+ }
1610
+ return { scheme: "unknown", instance: false, uri: raw };
1611
+ }
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
+ }
1619
+ }
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}`);
1669
+ }
1670
+ const uri = lgtinClass(prefix, ref, lot);
1671
+ const wrong = gs1KeyDigitViolation(uri);
1672
+ if (wrong) throw new Error(`lotClassUri: ${wrong}`);
1673
+ return uri;
1674
+ }
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;
1707
+ }
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;
1727
+ }
1728
+ function common(type, eventTime, action, bizStep, opts) {
1729
+ return { ...header(type, eventTime, bizStep, opts), action };
1730
+ }
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;
1739
+ }
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;
1748
+ }
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`;
1795
+ }
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.`;
1799
+ }
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>)`;
1808
+ }
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");
1852
+ }
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");
1858
+ }
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)");
1893
+ continue;
1894
+ }
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}`);
1901
+ }
1902
+ return v;
1903
+ }
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")}`;
1922
+ }
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}`;
1947
+ }
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"]
1986
+ }
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
+ };
1628
2122
  var EMS_PROPERTY_SPEC = {
1629
2123
  [EMS_PROPERTY.contractKW]: { uom: "kW", dataType: "xs:double", note: "contracted power at the metering point, in kW." },
1630
2124
  /* 값이 셋 중 하나여야 한다 — 그 밖의 낱말은 받지 않는다(뜻이 통할 것 같은 말도 받지 않는다). */
@@ -2278,1086 +2772,641 @@ function capabilitiesForType(system, typeKey) {
2278
2772
  }
2279
2773
 
2280
2774
  // src/domain-definition.ts
2281
- var OP_PARAM = {
2282
- /** 양품률(0..1, 무차원). 없으면 커널 기본값 — 기본값을 쓴 사실은 `specCoverage()` 가 밝힌다. */
2283
- yield: "yield",
2284
- /** 셋업·체인지오버 소요(ISO 8601 기간 문자열). ISA-95 는 셋업을 별도 세그먼트로도 표현하지만,
2285
- * 현재 커널은 작업에 붙는 셋업으로 다루므로 모수로 받는다. */
2286
- setupDuration: "setupDuration"
2287
- };
2288
- function procedureViolations(route) {
2289
- const elements = route.procedure ?? [];
2290
- if (!elements.length) return [];
2291
- const errors = [];
2292
- const byKey = new Map(elements.map((e) => [e.key, e]));
2293
- const hasChild = new Set(elements.map((e) => e.parent).filter((k) => !!k));
2294
- const stepSet = new Set(route.steps ?? []);
2295
- const seenStep = /* @__PURE__ */ new Map();
2296
- for (const n of elements) {
2297
- if (n.parent && !byKey.has(n.parent)) errors.push(`${n.key}: \uC0C1\uC704 '${n.parent}' \uAC00 \uC774 \uC808\uCC28\uC5D0 \uC5C6\uB2E4`);
2298
- if (n.step === void 0) continue;
2299
- 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`);
2300
- if (!stepSet.has(n.step)) errors.push(`${n.key}: \uBAA8\uB974\uB294 \uB2E8\uACC4 '${n.step}' \u2014 steps \uC5D0 \uC5C6\uB2E4`);
2301
- const already = seenStep.get(n.step);
2302
- 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`);
2303
- else seenStep.set(n.step, n.key);
2304
- }
2305
- return errors;
2306
- }
2307
- var INTENTS = ["transport", "process", "dwell"];
2308
- function dupes(keys) {
2309
- const seen = /* @__PURE__ */ new Set();
2310
- const dup = /* @__PURE__ */ new Set();
2311
- for (const k of keys) {
2312
- if (seen.has(k)) dup.add(k);
2313
- else seen.add(k);
2314
- }
2315
- return [...dup];
2316
- }
2317
- function validateDomainDefinition(def) {
2318
- const v = [];
2319
- if (!def || typeof def !== "object") return ["domain definition \uC5C6\uC74C/\uAC1D\uCCB4 \uC544\uB2D8"];
2320
- if (typeof def.id !== "string" || !def.id) v.push("id \uB204\uB77D");
2321
- if (typeof def.label !== "string" || !def.label) v.push("label \uB204\uB77D");
2322
- if (!Array.isArray(def.locationTypes) || def.locationTypes.length === 0) v.push("locationTypes \uBE44\uC5B4\uC788\uC74C");
2323
- if (!Array.isArray(def.resourceTypes)) v.push("resourceTypes \uBC30\uC5F4 \uC544\uB2D8");
2324
- const locationKeys2 = new Set((def.locationTypes || []).map((n) => n.key));
2325
- const resKeys = new Set((def.resourceTypes || []).map((r) => r.key));
2326
- const matKeys = new Set((def.materials || []).map((m) => m.key));
2327
- const matByKey = new Map((def.materials || []).map((m) => [m.key, m]));
2328
- const opKeys = new Set((def.operations || []).map((o) => o.key));
2329
- const routeKeys = new Set((def.routes || []).map((r) => r.key));
2330
- for (const [name, arr] of [["locationTypes", def.locationTypes], ["resourceTypes", def.resourceTypes], ["materials", def.materials], ["operations", def.operations], ["routes", def.routes], ["recipes", def.recipes]]) {
2331
- for (const d of dupes((arr || []).map((x) => x.key))) v.push(`${name} \uD0A4 \uC911\uBCF5: ${d}`);
2332
- }
2333
- for (const o of def.operations || []) {
2334
- if (!INTENTS.includes(o.intent)) v.push(`operation '${o.key}' intent \uBD80\uC815: ${o.intent}`);
2335
- if (o.locationType && !locationKeys2.has(o.locationType)) v.push(`operation '${o.key}' locationType '${o.locationType}' \uBBF8\uC815\uC758`);
2336
- if (o.resourceType && !resKeys.has(o.resourceType)) v.push(`operation '${o.key}' resourceType '${o.resourceType}' \uBBF8\uC815\uC758`);
2337
- if (o.intent === "dwell" && o.resourceType) v.push(`operation '${o.key}' dwell \uC778\uB370 resourceType \uC9C0\uC815\uB428(\uBB34\uC790\uC6D0\uC774\uC5B4\uC57C)`);
2338
- }
2339
- for (const r of def.routes || []) {
2340
- if (!Array.isArray(r.steps) || r.steps.length === 0) v.push(`route '${r.key}' steps \uBE44\uC5B4\uC788\uC74C`);
2341
- for (const s of r.steps || []) if (!opKeys.has(s)) v.push(`route '${r.key}' step '${s}' \uBBF8\uC815\uC758 operation`);
2342
- }
2343
- for (const rc of def.recipes || []) {
2344
- if (rc.route && !routeKeys.has(rc.route)) v.push(`recipe '${rc.key}' route '${rc.route}' \uBBF8\uC815\uC758`);
2345
- if (!rc.outputs?.length) v.push(`recipe '${rc.key}' outputs \uBE44\uC5B4\uC788\uC74C`);
2346
- for (const p of [...rc.inputs || [], ...rc.outputs || []]) {
2347
- if (!matKeys.has(p.material)) v.push(`recipe '${rc.key}' material '${p.material}' \uBBF8\uC815\uC758`);
2348
- if (typeof p.qty !== "number" || p.qty <= 0) v.push(`recipe '${rc.key}' material '${p.material}' qty \uBD80\uC815`);
2349
- const mat = matByKey.get(p.material);
2350
- if (mat?.locationType && !locationKeys2.has(mat.locationType)) v.push(`recipe '${rc.key}' material '${p.material}' locationType '${mat.locationType}' \uBBF8\uC815\uC758`);
2351
- }
2352
- }
2353
- return v;
2354
- }
2355
- var CATALOG_SEMVER = /^\d+\.\d+\.\d+([-+].+)?$/;
2356
- function validateCatalog(cat) {
2357
- const v = validateDomainDefinition(cat);
2358
- if (typeof cat?.version !== "string" || !CATALOG_SEMVER.test(cat?.version || "")) {
2359
- v.push(`version semver \uC544\uB2D8: ${cat?.version}`);
2360
- }
2361
- return v;
2362
- }
2363
-
2364
- // src/energy-ingest.ts
2365
- function isEnergyRecord(record) {
2366
- if (!record || typeof record !== "object") return false;
2367
- const r = record;
2368
- if (!(typeof r.meterId === "string" && r.meterId.trim().length > 0 && r.epc === void 0)) return false;
2369
- return r.from === void 0 && r.to === void 0;
2370
- }
2371
- function ingestEnergyRecords(records, opts) {
2372
- const arr = Array.isArray(records) ? records : records ? [records] : [];
2373
- const accepted = [];
2374
- const rejected = [];
2375
- let seq = 0;
2376
- for (const record of arr) {
2377
- const errors = [];
2378
- const meterId = String(record?.meterId ?? "").trim();
2379
- 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");
2380
- const at2 = String(record?.at ?? "").trim() || opts.defaultEventTime;
2381
- const atMs = at2 ? Date.parse(at2) : Number.NaN;
2382
- 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");
2383
- const num2 = (v, name) => {
2384
- if (v === void 0 || v === null || v === "") return void 0;
2385
- const n = Number(v);
2386
- if (!Number.isFinite(n)) {
2387
- errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2388
- return void 0;
2389
- }
2390
- return n;
2391
- };
2392
- const kW = num2(record?.kW, "kW");
2393
- const kWh = num2(record?.kWh, "kWh");
2394
- const powerFactor = num2(record?.powerFactor, "powerFactor");
2395
- if (errors.length) {
2396
- rejected.push({ record, errors });
2397
- continue;
2398
- }
2399
- const eventTime = new Date(atMs).toISOString();
2400
- const data = {
2401
- meterId,
2402
- /* 계약은 `kW` 를 필수로 두지만 **못 읽은 표본도 사실**이다 — 그 경우 값을 비우고 보낸다.
2403
- 커널이 「받았지만 부하를 못 읽었다」로 세고, 구간 마감에 그 이유를 싣는다. */
2404
- ...kW !== void 0 ? { kW } : {},
2405
- ...kWh !== void 0 ? { kWh } : {},
2406
- ...powerFactor !== void 0 ? { powerFactor } : {},
2407
- at: eventTime
2408
- };
2409
- accepted.push({
2410
- eventId: `${opts.tenantId}-energy-${++seq}`,
2411
- eventType: ENERGY_EVENT.measured,
2412
- eventTime,
2413
- tenantId: opts.tenantId,
2414
- data
2415
- });
2416
- }
2417
- return { accepted, rejected };
2418
- }
2419
- var POSITIONS = /* @__PURE__ */ new Set(["open", "closed", "intermediate", "bad"]);
2420
- function isEnergyEquipmentRecord(record) {
2421
- if (!record || typeof record !== "object") return false;
2422
- const r = record;
2423
- return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.epc === void 0 && r.meterId === void 0 && /* 적산을 실었으면 발전이다 — 이 문의 값은 상태이고, 적산은 자기 문이 있다. */
2424
- r.kWh === void 0;
2425
- }
2426
- function ingestEnergyEquipmentRecords(records, opts) {
2427
- const arr = Array.isArray(records) ? records : records ? [records] : [];
2428
- const accepted = [];
2429
- const rejected = [];
2430
- let seq = 0;
2431
- for (const record of arr) {
2432
- const errors = [];
2433
- const r = record;
2434
- const equipmentId = String(r?.equipmentId ?? "").trim();
2435
- 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");
2436
- const at2 = String(r?.at ?? "").trim() || opts.defaultEventTime;
2437
- const atMs = at2 ? Date.parse(at2) : Number.NaN;
2438
- 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");
2439
- const num2 = (v, name, min, max) => {
2440
- if (v === void 0 || v === null || v === "") return void 0;
2441
- const n = Number(v);
2442
- if (!Number.isFinite(n)) {
2443
- errors.push(`${name} \uAC00 \uC218\uAC00 \uC544\uB2C8\uB2E4: ${JSON.stringify(v)}`);
2444
- return void 0;
2445
- }
2446
- if (min !== void 0 && n < min) {
2447
- errors.push(`${name} \uAC00 ${min} \uBCF4\uB2E4 \uC791\uB2E4: ${n}`);
2448
- return void 0;
2449
- }
2450
- if (max !== void 0 && n > max) {
2451
- errors.push(`${name} \uAC00 ${max} \uBCF4\uB2E4 \uD06C\uB2E4: ${n}`);
2452
- return void 0;
2453
- }
2454
- return n;
2455
- };
2456
- const generatedKW = num2(r?.generatedKW, "generatedKW", 0);
2457
- const exportKW = num2(r?.exportKW, "exportKW");
2458
- const soc = num2(r?.soc, "soc", 0, 100);
2459
- const chargeKW = num2(r?.chargeKW, "chargeKW", 0);
2460
- const dischargeKW = num2(r?.dischargeKW, "dischargeKW", 0);
2461
- const minKW = num2(r?.minKW, "minKW", 0);
2462
- let curtailable;
2463
- if (r?.curtailable !== void 0 && r?.curtailable !== null) {
2464
- if (typeof r.curtailable !== "boolean") errors.push(`curtailable \uAC00 \uCC38/\uAC70\uC9D3\uC774 \uC544\uB2C8\uB2E4: ${JSON.stringify(r.curtailable)}`);
2465
- else curtailable = r.curtailable;
2466
- }
2467
- const dcVoltage = num2(r?.dcVoltage, "dcVoltage", 0);
2468
- const dcCurrent = num2(r?.dcCurrent, "dcCurrent", 0);
2469
- const phases = (raw, name) => {
2470
- if (raw === void 0 || raw === null) return void 0;
2471
- if (!Array.isArray(raw)) {
2472
- 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)}`);
2473
- return void 0;
2474
- }
2475
- if (!raw.length) {
2476
- 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`);
2477
- return void 0;
2478
- }
2479
- const out = [];
2480
- for (const [i, v] of raw.entries()) {
2481
- const n = Number(v);
2482
- if (!Number.isFinite(n)) {
2483
- errors.push(`${name}[${i}] \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(v)}`);
2484
- return void 0;
2485
- }
2486
- if (n < 0) {
2487
- 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)`);
2488
- return void 0;
2489
- }
2490
- out.push(n);
2491
- }
2492
- return out;
2493
- };
2494
- const acVoltage = phases(r?.acVoltage, "acVoltage");
2495
- const acCurrent = phases(r?.acCurrent, "acCurrent");
2496
- if (acVoltage && acCurrent && acVoltage.length !== acCurrent.length) {
2497
- errors.push(`acVoltage(${acVoltage.length}\uC0C1)\uC640 acCurrent(${acCurrent.length}\uC0C1)\uC758 \uC0C1 \uC218\uAC00 \uB2E4\uB974\uB2E4`);
2498
- }
2499
- let position;
2500
- if (r?.position !== void 0 && r?.position !== null && r?.position !== "") {
2501
- const p = String(r.position);
2502
- if (!POSITIONS.has(p)) errors.push(`position \uC774 \uD45C\uC900 \uAC12\uC774 \uC544\uB2C8\uB2E4(open\xB7closed\xB7intermediate\xB7bad): ${JSON.stringify(r.position)}`);
2503
- else position = p;
2504
- }
2505
- const values = { generatedKW, exportKW, soc, chargeKW, dischargeKW, curtailable, minKW, position, dcVoltage, dcCurrent, acVoltage, acCurrent };
2506
- if (!errors.length && Object.values(values).every((v) => v === void 0)) {
2507
- 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");
2508
- }
2509
- if (errors.length) {
2510
- rejected.push({ record, errors });
2511
- continue;
2512
- }
2513
- const eventTime = new Date(atMs).toISOString();
2514
- const data = {
2515
- equipmentId,
2516
- at: eventTime,
2517
- ...generatedKW !== void 0 ? { generatedKW } : {},
2518
- ...exportKW !== void 0 ? { exportKW } : {},
2519
- ...soc !== void 0 ? { soc } : {},
2520
- ...chargeKW !== void 0 ? { chargeKW } : {},
2521
- ...dischargeKW !== void 0 ? { dischargeKW } : {},
2522
- ...curtailable !== void 0 ? { curtailable } : {},
2523
- ...minKW !== void 0 ? { minKW } : {},
2524
- ...position !== void 0 ? { position } : {},
2525
- ...dcVoltage !== void 0 ? { dcVoltage } : {},
2526
- ...dcCurrent !== void 0 ? { dcCurrent } : {},
2527
- ...acVoltage !== void 0 ? { acVoltage } : {},
2528
- ...acCurrent !== void 0 ? { acCurrent } : {}
2529
- };
2530
- accepted.push({
2531
- eventId: `${opts.tenantId}-energy-eq-${++seq}`,
2532
- eventType: ENERGY_EVENT.equipment,
2533
- eventTime,
2534
- tenantId: opts.tenantId,
2535
- data
2536
- });
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);
2537
2798
  }
2538
- return { accepted, rejected };
2799
+ return errors;
2539
2800
  }
2540
- function isEnergyGenerationRecord(record) {
2541
- if (record?.from !== void 0 || record?.to !== void 0) return false;
2542
- if (!record || typeof record !== "object") return false;
2543
- const r = record;
2544
- return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.kWh !== void 0 && r.meterId === void 0 && r.epc === void 0;
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);
2808
+ }
2809
+ return [...dup];
2545
2810
  }
2546
- function ingestEnergyGenerationRecords(records, opts) {
2547
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2548
- const accepted = [];
2549
- const rejected = [];
2550
- let seq = 0;
2551
- for (const r of list) {
2552
- const errors = [];
2553
- const equipmentId = String(r?.equipmentId ?? "").trim();
2554
- 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");
2555
- const STATE_FIELDS = ["generatedKW", "exportKW", "soc", "chargeKW", "dischargeKW", "curtailable", "minKW", "position"];
2556
- const alsoState = STATE_FIELDS.filter((f) => r?.[f] !== void 0);
2557
- if (alsoState.length) {
2558
- errors.push(
2559
- `\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`
2560
- );
2561
- }
2562
- const raw = r?.kWh;
2563
- const kWh = Number(raw);
2564
- if (raw === void 0 || raw === null || !Number.isFinite(kWh)) {
2565
- 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)");
2566
- } else if (kWh < 0) {
2567
- 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`);
2568
- }
2569
- const eventTime = String(r?.at ?? "").trim() || opts.defaultEventTime || "";
2570
- 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");
2571
- let since;
2572
- const rawSince = r?.kWhSince;
2573
- if (rawSince !== void 0 && rawSince !== null && String(rawSince).trim()) {
2574
- const text = String(rawSince).trim();
2575
- const at2 = Date.parse(text);
2576
- if (!Number.isFinite(at2)) errors.push(`kWhSince \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(rawSince)}`);
2577
- else if (Number.isFinite(Date.parse(eventTime)) && at2 > Date.parse(eventTime)) {
2578
- errors.push(`kWhSince(${text}) \uAC00 \uC7B0 \uC2DC\uAC01(${eventTime})\uBCF4\uB2E4 \uB4A4\uB2E4 \u2014 \uB458 \uC911 \uD558\uB098\uAC00 \uD2C0\uB838\uB2E4`);
2579
- } else since = text;
2580
- }
2581
- const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
2582
- let accumulation;
2583
- const rawAcc = r?.kWhAccumulation;
2584
- if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
2585
- const text = String(rawAcc).trim();
2586
- if (!ACCUMULATIONS.includes(text)) {
2587
- errors.push(`kWhAccumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
2588
- } else accumulation = text;
2589
- }
2590
- if (errors.length) {
2591
- rejected.push({ record: r, errors });
2592
- continue;
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}`);
2826
+ }
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`);
2593
2845
  }
2594
- const data = {
2595
- equipmentId,
2596
- kWh,
2597
- at: eventTime,
2598
- ...since ? { since } : {},
2599
- ...accumulation ? { accumulation } : {}
2600
- };
2601
- accepted.push({
2602
- eventId: `${opts.tenantId}-generated-${++seq}`,
2603
- eventType: ENERGY_EVENT.generated,
2604
- eventTime,
2605
- tenantId: opts.tenantId,
2606
- data
2607
- });
2608
2846
  }
2609
- return { accepted, rejected };
2847
+ return v;
2610
2848
  }
2611
- function isEnergyUsagePeriodRecord(record) {
2612
- const r = record;
2613
- return !!r && typeof r === "object" && r.meterId !== void 0 && r.from !== void 0 && r.to !== void 0 && r.kWh !== void 0;
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;
2614
2856
  }
2615
- function isEnergyGenerationPeriodRecord(record) {
2857
+
2858
+ // src/energy-ingest.ts
2859
+ function isEnergyRecord(record) {
2860
+ if (!record || typeof record !== "object") return false;
2616
2861
  const r = record;
2617
- if (!r || typeof r !== "object") return false;
2618
- if (r.equipmentId === void 0 || r.from === void 0 || r.to === void 0) return false;
2619
- return r.kWh !== void 0;
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;
2620
2864
  }
2621
- function ingestEnergyGenerationPeriodRecords(records, opts) {
2622
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2865
+ function ingestEnergyRecords(records, opts) {
2866
+ const arr = Array.isArray(records) ? records : records ? [records] : [];
2623
2867
  const accepted = [];
2624
2868
  const rejected = [];
2625
- for (const r of list) {
2869
+ let seq = 0;
2870
+ for (const record of arr) {
2626
2871
  const errors = [];
2627
- const equipmentId = String(r?.equipmentId ?? "").trim();
2628
- if (!equipmentId) errors.push("equipmentId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC124\uBE44\uAC00 \uB0B8 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2629
- const span = readSpan(r, errors);
2630
- const kWh = readAmount(r?.kWh, "kWh", errors);
2631
- 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");
2632
- const ACCUMULATIONS = ["lifetime", "daily", "monthly", "billing", "unknown"];
2633
- let accumulation;
2634
- const rawAcc = r?.accumulation;
2635
- if (rawAcc !== void 0 && rawAcc !== null && String(rawAcc).trim()) {
2636
- const text = String(rawAcc).trim();
2637
- if (!ACCUMULATIONS.includes(text)) {
2638
- errors.push(`accumulation \uC774 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${ACCUMULATIONS.join("\xB7")}): ${JSON.stringify(rawAcc)}`);
2639
- } else accumulation = text;
2640
- }
2641
- const readAt = (raw, name) => {
2642
- if (raw === void 0 || raw === null || !String(raw).trim()) return void 0;
2643
- const text = String(raw).trim();
2644
- if (!Number.isFinite(Date.parse(text))) {
2645
- errors.push(`${name} \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
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)}`);
2646
2882
  return void 0;
2647
2883
  }
2648
- return text;
2649
- };
2650
- const observedFrom = readAt(r?.observedFrom, "observedFrom");
2651
- const observedTo = readAt(r?.observedTo, "observedTo");
2652
- if (errors.length || !span || kWh === void 0) {
2653
- rejected.push({ record: r, errors });
2654
- continue;
2655
- }
2656
- const data = {
2657
- equipmentId,
2658
- kWh,
2659
- periodStart: span.from,
2660
- periodEnd: span.to,
2661
- /* 관측 구간을 말하지 않으면 기간 전체를 잰 것으로 둔다 — 지난 기록은 그 원본이 하루를 마감해 준 값이다. */
2662
- observedFrom: observedFrom ?? span.from,
2663
- observedTo: observedTo ?? span.to,
2664
- accumulation: accumulation ?? "daily",
2665
- /* 밖에서 마감되어 온 것이다 — 우리가 시각 기준으로 닫은 것이 아니다. */
2666
- boundary: "declared"
2884
+ return n;
2667
2885
  };
2668
- const subj = resolveSubject("equipment", equipmentId, opts);
2669
- data.subject = subj.subject;
2670
- data.subjectBasis = subj.basis;
2671
- const futureError = futureFactError(span.to, opts);
2672
- if (futureError) {
2673
- rejected.push({ record: r, errors: [futureError] });
2674
- continue;
2675
- }
2676
- accepted.push({
2677
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPeriod, subj.subject, span.from, span.to),
2678
- eventType: ENERGY_EVENT.generationPeriod,
2679
- eventTime: span.to,
2680
- tenantId: opts.tenantId,
2681
- data
2682
- });
2683
- }
2684
- return { accepted, rejected };
2685
- }
2686
- function isEnergyGenerationPriceRecord(record) {
2687
- const r = record;
2688
- if (!r || typeof r !== "object") return false;
2689
- if (r.from === void 0 || r.to === void 0) return false;
2690
- if (r.meterId !== void 0 || r.equipmentId !== void 0) return false;
2691
- return r.unitPrice !== void 0;
2692
- }
2693
- function ingestEnergyGenerationPriceRecords(records, opts) {
2694
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2695
- const accepted = [];
2696
- const rejected = [];
2697
- for (const r of list) {
2698
- const errors = [];
2699
- const span = readSpan(r, errors);
2700
- const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
2701
- 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");
2702
- const currency = String(r?.currency ?? "").trim();
2703
- 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");
2704
- if (errors.length || !span || unitPrice === void 0) {
2705
- rejected.push({ record: r, errors });
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 });
2706
2891
  continue;
2707
2892
  }
2708
- const data = { from: span.from, to: span.to, unitPrice, currency };
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
2902
+ };
2709
2903
  accepted.push({
2710
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.generationPrice, "", span.from, span.to),
2711
- eventType: ENERGY_EVENT.generationPrice,
2712
- eventTime: span.from,
2904
+ eventId: `${opts.tenantId}-energy-${++seq}`,
2905
+ eventType: ENERGY_EVENT.measured,
2906
+ eventTime,
2713
2907
  tenantId: opts.tenantId,
2714
2908
  data
2715
2909
  });
2716
2910
  }
2717
2911
  return { accepted, rejected };
2718
2912
  }
2719
- function isEnergyTariffBasisRecord(record) {
2913
+ var POSITIONS = /* @__PURE__ */ new Set(["open", "closed", "intermediate", "bad"]);
2914
+ function isEnergyEquipmentRecord(record) {
2915
+ if (!record || typeof record !== "object") return false;
2720
2916
  const r = record;
2721
- if (!r || typeof r !== "object") return false;
2722
- if (r.from === void 0 || r.to === void 0) return false;
2723
- if (r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0) return false;
2724
- return r.billingDemandKW !== void 0 || r.demandChargePerKW !== void 0;
2917
+ return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.epc === void 0 && r.meterId === void 0 && /* 적산을 실었으면 발전이다 — 이 문의 값은 상태이고, 적산은 자기 문이 있다. */
2918
+ r.kWh === void 0;
2725
2919
  }
2726
- function ingestEnergyTariffBasisRecords(records, opts) {
2727
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2920
+ function ingestEnergyEquipmentRecords(records, opts) {
2921
+ const arr = Array.isArray(records) ? records : records ? [records] : [];
2728
2922
  const accepted = [];
2729
2923
  const rejected = [];
2730
- for (const r of list) {
2924
+ let seq = 0;
2925
+ for (const record of arr) {
2731
2926
  const errors = [];
2732
- const span = readSpan(r, errors);
2733
- const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
2734
- const demandChargePerKW = readAmount(r?.demandChargePerKW, "demandChargePerKW", errors);
2735
- if (billingDemandKW === void 0 && demandChargePerKW === void 0) {
2736
- 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");
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;
2737
2960
  }
2738
- const currency = String(r?.currency ?? "").trim() || void 0;
2739
- if (demandChargePerKW !== void 0 && !currency) errors.push("demandChargePerKW \uB97C \uC2E4\uC5C8\uB294\uB370 currency \uAC00 \uC5C6\uB2E4");
2740
- if (r?.demandCharge !== void 0 || r?.total !== void 0) {
2741
- 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");
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`);
2742
2992
  }
2743
- if (errors.length || !span) {
2744
- rejected.push({ record: r, errors });
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 });
2745
3005
  continue;
2746
3006
  }
3007
+ const eventTime = new Date(atMs).toISOString();
2747
3008
  const data = {
2748
- from: span.from,
2749
- to: span.to,
2750
- ...billingDemandKW !== void 0 ? { billingDemandKW } : {},
2751
- ...demandChargePerKW !== void 0 ? { demandChargePerKW } : {},
2752
- ...currency ? { currency } : {}
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 } : {}
2753
3023
  };
2754
3024
  accepted.push({
2755
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.tariffBasis, "", span.from, span.to),
2756
- eventType: ENERGY_EVENT.tariffBasis,
2757
- /* **시작 시각**이다 — 그때부터 유효하다(§ 위 주석). */
2758
- eventTime: span.from,
3025
+ eventId: `${opts.tenantId}-energy-eq-${++seq}`,
3026
+ eventType: ENERGY_EVENT.equipment,
3027
+ eventTime,
2759
3028
  tenantId: opts.tenantId,
2760
3029
  data
2761
3030
  });
2762
3031
  }
2763
3032
  return { accepted, rejected };
2764
3033
  }
2765
- function isEnergyBillRecord(record) {
3034
+ function isEnergyGenerationRecord(record) {
3035
+ if (record?.from !== void 0 || record?.to !== void 0) return false;
3036
+ if (!record || typeof record !== "object") return false;
2766
3037
  const r = record;
2767
- if (!r || typeof r !== "object") return false;
2768
- if (r.from === void 0 || r.to === void 0) return false;
2769
- return r.energyCharge !== void 0 || r.demandCharge !== void 0 || r.total !== void 0;
2770
- }
2771
- function futureFactError(eventTime, opts) {
2772
- const nowText = opts.nowISO ?? opts.defaultEventTime;
2773
- if (!nowText) return void 0;
2774
- const nowMs = Date.parse(nowText);
2775
- const atMs = Date.parse(eventTime);
2776
- if (!Number.isFinite(nowMs) || !Number.isFinite(atMs) || atMs <= nowMs) return void 0;
2777
- 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`;
2778
- }
2779
- function resolveSubject(kind, localId, opts) {
2780
- const declared = opts.identityOf?.(kind, localId);
2781
- if (declared) return { subject: declared, basis: "declared" };
2782
- return { subject: opts.scopeId ? `${opts.scopeId}/${localId}` : localId, basis: "twin-local" };
2783
- }
2784
- function periodFactId(tenantId, kind, subject, from, to) {
2785
- return [tenantId, kind, subject, from, to].join("|");
2786
- }
2787
- function readSpan(r, errors) {
2788
- const from = String(r?.from ?? "").trim();
2789
- const to = String(r?.to ?? "").trim();
2790
- const fromMs = Date.parse(from);
2791
- const toMs = Date.parse(to);
2792
- if (!from || !Number.isFinite(fromMs)) errors.push(`from \uC744 \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.from)}`);
2793
- if (!to || !Number.isFinite(toMs)) errors.push(`to \uB97C \uC2DC\uAC01\uC73C\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(r?.to)}`);
2794
- if (Number.isFinite(fromMs) && Number.isFinite(toMs) && !(toMs > fromMs)) {
2795
- 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`);
2796
- }
2797
- return errors.length ? void 0 : { from, to };
2798
- }
2799
- function readAmount(raw, name, errors) {
2800
- if (raw === void 0 || raw === null || String(raw).trim() === "") return void 0;
2801
- const v = Number(raw);
2802
- if (!Number.isFinite(v)) {
2803
- errors.push(`${name} \uB97C \uC218\uB85C \uC77D\uC744 \uC218 \uC5C6\uB2E4: ${JSON.stringify(raw)}`);
2804
- return void 0;
2805
- }
2806
- if (v < 0) {
2807
- errors.push(`${name} \uAC00 \uC74C\uC218\uB2E4(${v})`);
2808
- return void 0;
2809
- }
2810
- return v;
3038
+ return typeof r.equipmentId === "string" && r.equipmentId.trim().length > 0 && r.kWh !== void 0 && r.meterId === void 0 && r.epc === void 0;
2811
3039
  }
2812
- function ingestEnergyUsagePeriodRecords(records, opts) {
3040
+ function ingestEnergyGenerationRecords(records, opts) {
2813
3041
  const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2814
3042
  const accepted = [];
2815
3043
  const rejected = [];
3044
+ let seq = 0;
2816
3045
  for (const r of list) {
2817
3046
  const errors = [];
2818
- const meterId = String(r?.meterId ?? "").trim();
2819
- if (!meterId) errors.push("meterId \uAC00 \uC5C6\uB2E4 \u2014 \uC5B4\uB290 \uC9C0\uC810\uC774 \uC4F4 \uAC83\uC778\uC9C0 \uC9C0\uC5B4\uB0BC \uC218 \uC5C6\uB2E4");
2820
- const span = readSpan(r, errors);
2821
- const rawKWh = r?.kWh;
2822
- let kWh;
2823
- if (rawKWh === void 0 || rawKWh === null || String(rawKWh).trim() === "") {
2824
- errors.push("kWh \uAC00 \uC5C6\uB2E4 \u2014 \uC774 \uBB38\uC774 \uBC1B\uB294 \uAC12\uC740 \uADF8 \uAD6C\uAC04\uC5D0 \uC4F4 \uC591\uC774\uB2E4");
2825
- } else {
2826
- kWh = readAmount(rawKWh, "kWh", errors);
2827
- }
2828
- const maxKW = readAmount(r?.maxKW, "maxKW", errors);
2829
- const unitPrice = readAmount(r?.unitPrice, "unitPrice", errors);
2830
- const currency = String(r?.currency ?? "").trim() || void 0;
2831
- 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");
2832
- let basis;
2833
- const rawBasis = r?.basis;
2834
- if (rawBasis !== void 0 && rawBasis !== null && String(rawBasis).trim()) {
2835
- const text = String(rawBasis).trim();
2836
- if (!OBSERVATION_BASIS.includes(text)) {
2837
- errors.push(`basis \uAC00 \uC544\uB294 \uAC12\uC774 \uC544\uB2C8\uB2E4(${OBSERVATION_BASIS.join("\xB7")}): ${JSON.stringify(rawBasis)}`);
2838
- } else basis = text;
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
+ );
2839
3055
  }
2840
- if (errors.length || !span || kWh === void 0) {
2841
- rejected.push({ record: r, errors });
2842
- continue;
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`);
2843
3062
  }
2844
- const subj = resolveSubject("meter", meterId, opts);
2845
- const data = {
2846
- meterId,
2847
- subject: subj.subject,
2848
- subjectBasis: subj.basis,
2849
- from: span.from,
2850
- to: span.to,
2851
- kWh,
2852
- ...maxKW !== void 0 ? { maxKW } : {},
2853
- ...unitPrice !== void 0 ? { unitPrice } : {},
2854
- ...currency ? { currency } : {},
2855
- ...basis ? { basis } : {}
2856
- };
2857
- const futureError = futureFactError(span.to, opts);
2858
- if (futureError) {
2859
- rejected.push({ record: r, errors: [futureError] });
2860
- continue;
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;
2861
3074
  }
2862
- accepted.push({
2863
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.usagePeriod, subj.subject, span.from, span.to),
2864
- eventType: ENERGY_EVENT.usagePeriod,
2865
- /* 구간의 **끝**이 이 사실이 성립한 시각이다 — 시작으로 달면 저널이 그 구간을 미리 안 것이 된다. */
2866
- eventTime: span.to,
2867
- tenantId: opts.tenantId,
2868
- data
2869
- });
2870
- }
2871
- return { accepted, rejected };
2872
- }
2873
- function ingestEnergyBillRecords(records, opts) {
2874
- const list = records === void 0 || records === null ? [] : Array.isArray(records) ? records : [records];
2875
- const accepted = [];
2876
- const rejected = [];
2877
- for (const r of list) {
2878
- const errors = [];
2879
- const span = readSpan(r, errors);
2880
- const energyCharge = readAmount(r?.energyCharge, "energyCharge", errors);
2881
- const demandCharge = readAmount(r?.demandCharge, "demandCharge", errors);
2882
- const total = readAmount(r?.total, "total", errors);
2883
- const billingDemandKW = readAmount(r?.billingDemandKW, "billingDemandKW", errors);
2884
- if (energyCharge === void 0 && demandCharge === void 0 && total === void 0) {
2885
- 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");
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;
2886
3083
  }
2887
- const currency = String(r?.currency ?? "").trim() || void 0;
2888
- 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");
2889
- if (errors.length || !span) {
3084
+ if (errors.length) {
2890
3085
  rejected.push({ record: r, errors });
2891
3086
  continue;
2892
3087
  }
2893
3088
  const data = {
2894
- from: span.from,
2895
- to: span.to,
2896
- ...energyCharge !== void 0 ? { energyCharge } : {},
2897
- ...demandCharge !== void 0 ? { demandCharge } : {},
2898
- ...total !== void 0 ? { total } : {},
2899
- ...currency ? { currency } : {},
2900
- ...billingDemandKW !== void 0 ? { billingDemandKW } : {}
3089
+ equipmentId,
3090
+ kWh,
3091
+ at: eventTime,
3092
+ ...since ? { since } : {},
3093
+ ...accumulation ? { accumulation } : {}
2901
3094
  };
2902
- const futureError = futureFactError(span.to, opts);
2903
- if (futureError) {
2904
- rejected.push({ record: r, errors: [futureError] });
2905
- continue;
2906
- }
2907
3095
  accepted.push({
2908
- eventId: periodFactId(opts.tenantId, ENERGY_EVENT.bill, "", span.from, span.to),
2909
- eventType: ENERGY_EVENT.bill,
2910
- eventTime: span.to,
3096
+ eventId: `${opts.tenantId}-generated-${++seq}`,
3097
+ eventType: ENERGY_EVENT.generated,
3098
+ eventTime,
2911
3099
  tenantId: opts.tenantId,
2912
3100
  data
2913
3101
  });
2914
3102
  }
2915
- return { accepted, rejected };
2916
- }
2917
-
2918
- // src/epcis.ts
2919
- var EPCIS_CONTEXT = "https://ref.gs1.org/standards/epcis/2.0.0/epcis-context.jsonld";
2920
- var UTC_OFFSET = "+00:00";
2921
- var DISP = {
2922
- in_progress: "urn:epcglobal:cbv:disp:in_progress",
2923
- sellable: "urn:epcglobal:cbv:disp:sellable_accessible",
2924
- reserved: "urn:epcglobal:cbv:disp:reserved",
2925
- in_transit: "urn:epcglobal:cbv:disp:in_transit",
2926
- non_sellable: "urn:epcglobal:cbv:disp:non_sellable_other",
2927
- // 불량/scrap
2928
- /**
2929
- * **기한이 지났다** — CBV `expired`.
2930
- *
2931
- * ── 왜 `non_sellable` 로 계산하지 않나 (2026-08-24) ─────────────────────────────
2932
- * 커널의 `non_sellable` 은 CBV 의 `non_sellable_other`, 즉 **「그 밖의 이유」**다. 기한 지남을 거기
2933
- * 넣으면 「기한이 지나 못 판다」와 「깨져서 못 판다」가 같은 값이 되고, 화면은 회수·폐기의 사유를
2934
- * 구별할 수 없다. 식품에서 그 둘은 다른 조치다.
2935
- *
2936
- * 그리고 표준에 **정확한 낱말이 있다** — 합치는 것은 있는 낱말을 버리는 것이다.
2937
- *
2938
- * ── 기한 날짜와 다른 축이다 ────────────────────────────────────────────────
2939
- * `ItemState.expiry` 는 **날짜**이고 이것은 **상태**다. 날짜가 있으면 「지났나」는 파생이지만, 원본이
2940
- * 「기한 지남」을 상태로 선언하는 시스템이 있다 — 그때 이 값은 관측이다.
2941
- *
2942
- * 둘이 어긋나면(날짜는 남았는데 상태가 지남, 또는 그 반대) **어느 쪽이 맞다고 정하지 않는다** —
2943
- * 아직 그 판정을 세울 근거가 없다. 어긋남의 구분을 없애지 않는 것이 지금의 규율이다.
2944
- *
2945
- * ── 원문으로 확인했다 (2026-08-24) ────────────────────────────────────────
2946
- * 1차 출처: **CBV Standard Release 2.0, Ratified Jun 2022** §7.2.3 처분 값 표(38개). 이 객체의
2947
- * 다른 값들(`in_progress`·`sellable_accessible`·`reserved`·`in_transit`·`non_sellable_other`)도
2948
- * 그 표에 있다.
2949
- *
2950
- * **`non_sellable_expired` 를 쓰지 않는 이유**: 그 값은 CBV 1.0 의 것이고 표준이 **폐기**했다 —
2951
- * 「deprecated in favour of new disposition values expired, damaged, disposed, … introduced in
2952
- * CBV 1.1」. 폐기된 값을 쓰면 새 소비처가 읽지 못한다.
2953
- *
2954
- * 참고: GS1 어휘 등록처(`ref.gs1.org/cbv/…`)로는 확인할 수 없었다 — **없는 값에도 같은 응답**을
2955
- * 준다(지어낸 값의 JSON-LD 가 실재 값과 바이트까지 같았다). 그 경로를 근거로 삼지 말 것.
2956
- */
2957
- expired: "urn:epcglobal:cbv:disp:expired",
2958
- /**
2959
- * **검사에 합격했다 / 불합격했다** — CBV `conformant` / `non_conformant`.
2960
- *
2961
- * 1차 출처(CBV 2.0 §7.2.3) 정의 그대로다.
2962
- *
2963
- * conformant Outcome of a successful/passed inspection in an inspecting or repairing step
2964
- * non_conformant Outcome of an unsuccessful/failed inspection in an inspecting or repairing step
2965
- *
2966
- * ── 왜 시험 결과 축을 자원에 더하지 않고 이것을 쓰나 (2026-08-24) ────────────
2967
- * 로트의 검사 판정을 담을 자리를 찾다가 `ItemState.testResults` 를 더하려 했다. 그런데 표준은 그
2968
- * 사실을 **이미 처분으로 말한다**: `bizStep: inspecting` 사건에 이 처분이 붙는다.
2969
- *
2970
- * 처분을 쓰면 두 가지가 공짜로 성립한다.
2971
- * ① **상태 ⊆ 이벤트** — 처분은 이미 사건에서 온다. 상태에만 있는 축을 만들지 않는다
2972
- * ② **운영에 곧 닿는다** — 「이 자재를 쓸 수 있나」가 처분으로 답해진다(판정을 따로 읽지 않는다)
2973
- *
2974
- * 시험의 **자세한 내용**(어느 명세로, 무엇을 재어)은 다른 물음이고, 표준은 그것을 `TestResult` 로
2975
- * 두며 결과가 대상을 가리킨다(`TestableObjectID`) — 대상이 결과를 들지 않는다. 그 축이 필요해지면
2976
- * 그때 열되, **판정 자체는 여기서 끝난다.**
2977
- */
2978
- conformant: "urn:epcglobal:cbv:disp:conformant",
2979
- non_conformant: "urn:epcglobal:cbv:disp:non_conformant"
2980
- };
2981
- var CBV_BIZSTEP = {
2982
- /** 공정에 자재가 들어갔다 — ISA-95 `MaterialUse: Consumed`. */
2983
- consuming: "urn:epcglobal:cbv:bizstep:consuming",
2984
- /** 새 물품이 생겨 계보가 시작된다 — ISA-95 `MaterialUse: Produced`. */
2985
- commissioning: "urn:epcglobal:cbv:bizstep:commissioning",
2986
- /**
2987
- * **검사** — CBV `inspecting`. 1차 출처(CBV 2.0) 정의: 「Process of reviewing objects to address
2988
- * potential physical or documentation defects」이고, 「표본과 달리 검사된 대상은 그대로 남는다」고
2989
- * 이어진다(즉 검사는 물건을 소비하지 않는다).
2990
- *
2991
- * 이 단계에 `DISP.conformant`/`DISP.non_conformant` 가 붙어 판정이 처분으로 남는다 — 입고검수·
2992
- * 공정 중 검사가 그 모양이다.
2993
- */
2994
- inspecting: "urn:epcglobal:cbv:bizstep:inspecting",
2995
- /**
2996
- * **어느 단계로도 이름 붙지 않는 활동** — 원문: 「A business step not identified by any other」.
2997
- *
2998
- * 이것은 근사가 아니라 **표준이 준 낱말**이다. 그 구별이 중요하다: 재고 조정처럼 한 낱말이 두 일을
2999
- * 하는 원천(세어 보고 맞춘 것 · 사람이 정정한 것)을 `cycle_counting` 으로 옮기면 **일어나지 않은
3000
- * 계수를 기록**하게 된다. 그때 쓰는 것이 이 값이고, 무슨 일이었는지는 값으로 함께 나른다.
3001
- *
3002
- * 원문 확인: CBV Standard Release 2.0(Ratified Jun 2022) §7.1.
3003
- */
3004
- other: "urn:epcglobal:cbv:bizstep:other"
3005
- };
3006
- var EPCIS_EVENT = {
3007
- object: "epcis.ObjectEvent",
3008
- aggregation: "epcis.AggregationEvent",
3009
- transaction: "epcis.TransactionEvent",
3010
- transformation: "epcis.TransformationEvent"
3011
- };
3012
- function isEpcisEventType(eventType) {
3013
- return typeof eventType === "string" && eventType.startsWith("epcis.");
3014
- }
3015
- function ssccUri(companyPrefix, serial) {
3016
- return `urn:epc:id:sscc:${companyPrefix}.${String(serial).padStart(10, "0")}`;
3017
- }
3018
- function sgtinClass(companyPrefix, itemRef) {
3019
- return `urn:epc:idpat:sgtin:${companyPrefix}.${itemRef}.*`;
3020
- }
3021
- var ILMD_ATTR = {
3022
- /** 유통기한·만료(로트 단위). */
3023
- expiry: "cbvmda:itemExpirationDate",
3024
- /** 로트·배치 번호(직렬 개체에 로트를 붙일 때). */
3025
- lot: "cbvmda:lotNumber"
3026
- };
3027
- function lgtinClass(companyPrefix, itemRefAndIndicator, lot) {
3028
- return `urn:epc:class:lgtin:${companyPrefix}.${itemRefAndIndicator}.${encodeURIComponent(lot)}`;
3029
- }
3030
- function parseEpc(uri) {
3031
- const raw = String(uri ?? "");
3032
- if (/(?:\/obj\/|:obj:)[^/:\s]+$/.test(raw)) return { scheme: "unknown", instance: true, uri: raw };
3033
- const inHouseClass = raw.match(/(?:\/class\/|:class:)([^/:\s]+)$/);
3034
- if (inHouseClass) {
3035
- const at2 = inHouseClass[1].indexOf(LOT_SEPARATOR);
3036
- const split = at2 > 0 ? decodedPair(inHouseClass[1].slice(0, at2), inHouseClass[1].slice(at2 + LOT_SEPARATOR.length)) : void 0;
3037
- return split ? { scheme: "unknown", instance: false, item: split[0], lot: split[1], uri: raw } : { scheme: "unknown", instance: false, uri: raw };
3038
- }
3039
- const cls = raw.match(/^urn:epc:class:lgtin:(.+)$/);
3040
- if (cls) {
3041
- const seg = cls[1].split(".");
3042
- const lot = seg.slice(2).join(".");
3043
- return {
3044
- scheme: "lgtin",
3045
- instance: false,
3046
- gtinKey: seg.slice(0, 2).join("."),
3047
- lot: lot ? decodeURIComponent(lot) : void 0,
3048
- uri: raw
3049
- };
3050
- }
3051
- const pat = raw.match(/^urn:epc:idpat:sgtin:(.+)$/);
3052
- if (pat) {
3053
- const seg = pat[1].split(".");
3054
- return { scheme: "idpat", instance: false, gtinKey: seg.slice(0, 2).join("."), uri: raw };
3055
- }
3056
- const id = raw.match(/^urn:epc:id:([a-z]+):(.+)$/);
3057
- if (id) {
3058
- const scheme = id[1];
3059
- const seg = id[2].split(".");
3060
- const known = ["sgtin", "sscc", "gdti", "grai", "giai", "sgln"].includes(scheme);
3061
- return {
3062
- scheme: known ? scheme : "unknown",
3063
- instance: true,
3064
- ...scheme === "sgtin" ? { gtinKey: seg.slice(0, 2).join("."), serial: seg[2] } : { serial: seg.slice(1).join(".") },
3065
- uri: raw
3066
- };
3067
- }
3068
- return { scheme: "unknown", instance: false, uri: raw };
3069
- }
3070
- function decodedPair(item, lot) {
3071
- if (!lot) return void 0;
3072
- try {
3073
- return [decodeURIComponent(item), decodeURIComponent(lot)];
3074
- } catch {
3075
- return void 0;
3076
- }
3077
- }
3078
- function itemClassOf(uri) {
3079
- if (!uri) return void 0;
3080
- const parsed = parseEpc(uri);
3081
- if (parsed.scheme === "lgtin" && parsed.gtinKey) return `urn:epc:idpat:sgtin:${parsed.gtinKey}.*`;
3082
- if (parsed.item !== void 0) {
3083
- const marker = /^(.*(?:\/class\/|:class:))[^/:\s]+$/.exec(parsed.uri);
3084
- if (marker) return `${marker[1]}${parsed.item.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c])}`;
3085
- }
3086
- return parsed.uri;
3087
- }
3088
- function lotClassOfItem(itemClass, lot) {
3089
- if (!itemClass) return void 0;
3090
- const idpat = /^urn:epc:idpat:sgtin:(\d+)\.(\d+)\.\*$/.exec(itemClass);
3091
- if (idpat) return lotClassUri({ namespace: "", item: "", lot, gtin: `${idpat[1]}.${idpat[2]}` });
3092
- const parsed = parseEpc(itemClass);
3093
- if (parsed.instance || parsed.lot !== void 0) return void 0;
3094
- const url = /^(https?:\/\/.+)\/class\/([^/:\s]+)$/.exec(itemClass);
3095
- const urn = /^(urn:.+):class:([^/:\s]+)$/.exec(itemClass);
3096
- const at2 = url ?? urn;
3097
- if (!at2) return void 0;
3098
- let item;
3099
- try {
3100
- item = decodeURIComponent(at2[2]);
3101
- } catch {
3102
- return void 0;
3103
- }
3104
- return lotClassUri({ namespace: at2[1], item, lot });
3105
- }
3106
- function sameItemClass(a, b) {
3107
- const x = itemClassOf(a);
3108
- return x !== void 0 && x === itemClassOf(b);
3109
- }
3110
- function gdtiUri(companyPrefix, docType, serial) {
3111
- return `urn:epc:id:gdti:${companyPrefix}.${docType}.${serial}`;
3103
+ return { accepted, rejected };
3112
3104
  }
3113
- function objectUri(namespace, objId) {
3114
- return underNamespace(namespace, "obj", objId);
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;
3115
3108
  }
3116
- function classUri(namespace, classId) {
3117
- return underNamespace(namespace, "class", classId);
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;
3118
3114
  }
3119
- function lotClassUri(input) {
3120
- const item = String(input.item ?? "");
3121
- const lot = String(input.lot ?? "");
3122
- 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})`);
3123
- if (input.gtin !== void 0) {
3124
- const [prefix, ref, ...rest] = String(input.gtin).split(".");
3125
- if (!prefix || !ref || rest.length) {
3126
- throw new Error(`lotClassUri: gtin \uC740 'CompanyPrefix.ItemRefAndIndicator' \uC5EC\uC57C \uD55C\uB2E4: ${input.gtin}`);
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;
3127
3134
  }
3128
- const uri = lgtinClass(prefix, ref, lot);
3129
- const wrong = gs1KeyDigitViolation(uri);
3130
- if (wrong) throw new Error(`lotClassUri: ${wrong}`);
3131
- return uri;
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
+ });
3132
3177
  }
3133
- if (!item) throw new Error(`lotClassUri: \uD488\uBC88\uC774 \uBE44\uC5C8\uB2E4 (lot=${lot})`);
3134
- const enc = (v) => v.replace(LOT_COMPONENT_BREAKING, (c) => PERCENT_ENCODED[c]);
3135
- return joinUnderNamespace(input.namespace, "class", `${enc(item)}${LOT_SEPARATOR}${enc(lot)}`);
3136
- }
3137
- var LOT_SEPARATOR = ";lot=";
3138
- var LOT_COMPONENT_BREAKING = /[%/:?# ;]/g;
3139
- function bizTransactionUri(namespace, transId) {
3140
- return underNamespace(namespace, "bt", transId);
3141
- }
3142
- var STRUCTURE_BREAKING = /[%/:?# ]/g;
3143
- var PERCENT_ENCODED = {
3144
- "%": "%25",
3145
- "/": "%2F",
3146
- ":": "%3A",
3147
- "?": "%3F",
3148
- "#": "%23",
3149
- " ": "%20",
3150
- /* 로트 클래스의 가르는 글자 — `lotClassUri` 만 쓴다(§`LOT_COMPONENT_BREAKING`). 표는 한 벌이다. */
3151
- ";": "%3B"
3152
- };
3153
- function underNamespace(namespace, marker, id) {
3154
- const raw = String(id);
3155
- if (!raw) return void 0;
3156
- return joinUnderNamespace(namespace, marker, raw.replace(STRUCTURE_BREAKING, (c) => PERCENT_ENCODED[c]));
3157
- }
3158
- function joinUnderNamespace(namespace, marker, v) {
3159
- const ns = namespace?.trim();
3160
- if (!ns) return void 0;
3161
- if (/^https?:\/\/[^/\s]+/.test(ns)) return `${ns.replace(/\/+$/, "")}/${marker}/${v}`;
3162
- if (/^urn:epc(global)?:/.test(ns)) return void 0;
3163
- if (/^urn:[^:\s]+/.test(ns)) return `${ns.replace(/:+$/, "")}:${marker}:${v}`;
3164
- return void 0;
3178
+ return { accepted, rejected };
3165
3179
  }
3166
- function header(type, eventTime, bizStep, opts) {
3167
- const h = {
3168
- "@context": EPCIS_CONTEXT,
3169
- type,
3170
- eventTime,
3171
- eventTimeZoneOffset: UTC_OFFSET,
3172
- bizStep
3173
- };
3174
- if (opts?.eventID) h.eventID = opts.eventID;
3175
- if (opts?.recordTime) h.recordTime = opts.recordTime;
3176
- if (opts?.errorDeclaration) h.errorDeclaration = opts.errorDeclaration;
3177
- if (opts?.bizTransactionList?.length) h.bizTransactionList = opts.bizTransactionList;
3178
- if (opts?.ilmd) h.ilmd = opts.ilmd;
3179
- if (opts?.sourceList) h.sourceList = opts.sourceList;
3180
- if (opts?.destinationList) h.destinationList = opts.destinationList;
3181
- if (opts?.persistentDisposition) h.persistentDisposition = opts.persistentDisposition;
3182
- if (opts?.sensorElementList) h.sensorElementList = opts.sensorElementList;
3183
- if (opts?.certificationInfo) h.certificationInfo = opts.certificationInfo;
3184
- return h;
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;
3185
3186
  }
3186
- function common(type, eventTime, action, bizStep, opts) {
3187
- return { ...header(type, eventTime, bizStep, opts), action };
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 };
3188
3212
  }
3189
- function objectEvent(p) {
3190
- const e = { ...common("ObjectEvent", p.eventTime, p.action, p.bizStep, p), epcList: p.epcList };
3191
- if (p.disposition) e.disposition = p.disposition;
3192
- if (p.quantityList) e.quantityList = p.quantityList;
3193
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3194
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3195
- if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
3196
- 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;
3197
3219
  }
3198
- function aggregationEvent(p) {
3199
- const e = { ...common("AggregationEvent", p.eventTime, p.action, p.bizStep, p), parentID: p.parentID };
3200
- if (p.disposition) e.disposition = p.disposition;
3201
- if (p.childEPCs) e.childEPCs = p.childEPCs;
3202
- if (p.childQuantityList) e.childQuantityList = p.childQuantityList;
3203
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3204
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3205
- return e;
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
+ });
3256
+ }
3257
+ return { accepted, rejected };
3206
3258
  }
3207
- function transactionEvent(p) {
3208
- const e = {
3209
- ...common("TransactionEvent", p.eventTime, p.action, p.bizStep, p),
3210
- bizTransactionList: p.bizTransactionList
3211
- };
3212
- if (p.disposition) e.disposition = p.disposition;
3213
- if (p.parentID) e.parentID = p.parentID;
3214
- if (p.epcList) e.epcList = p.epcList;
3215
- if (p.quantityList) e.quantityList = p.quantityList;
3216
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3217
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3218
- return e;
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;
3219
3264
  }
3220
- function transformationEvent(p) {
3221
- const e = header("TransformationEvent", p.eventTime, p.bizStep, p);
3222
- if (p.disposition) e.disposition = p.disposition;
3223
- if (p.inputEPCList) e.inputEPCList = p.inputEPCList;
3224
- if (p.inputQuantityList) e.inputQuantityList = p.inputQuantityList;
3225
- if (p.outputEPCList) e.outputEPCList = p.outputEPCList;
3226
- if (p.outputQuantityList) e.outputQuantityList = p.outputQuantityList;
3227
- if (p.transformationID) e.transformationID = p.transformationID;
3228
- if (p.readPoint) e.readPoint = { id: p.readPoint };
3229
- if (p.bizLocation) e.bizLocation = { id: p.bizLocation };
3230
- if (p.bizTransactionList) e.bizTransactionList = p.bizTransactionList;
3231
- return e;
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`;
3232
3272
  }
3233
- var ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
3234
- var TZ_RE = /^[+-]\d{2}:\d{2}$/;
3235
- var ACTIONS = ["ADD", "OBSERVE", "DELETE"];
3236
- var EPC_CLASS_PREFIXES = ["urn:epc:idpat:", "urn:epc:class:"];
3237
- var DL_CANONICAL = "https://id.gs1.org/";
3238
- var CBV_URL_CLASS = /^https?:\/\/[^/\s]+\/(?:[^/\s]+\/)*class\/[^/\s]+$/;
3239
- var CBV_URN_CLASS = /^urn:[^:\s]+:(?:[^:\s]+:)*class:[^:\s]+$/;
3240
- var GS1_KEY_DIGITS = { sgtin: 13, lgtin: 13, sscc: 17, grai: 12, gdti: 12, sgln: 12 };
3241
- function gs1KeyDigitViolation(uri) {
3242
- if (!uri) return void 0;
3243
- const m = /^urn:epc:(?:id|idpat|class):([a-z]+):([^:]+)$/.exec(uri);
3244
- if (!m) return void 0;
3245
- const want = GS1_KEY_DIGITS[m[1]];
3246
- if (!want) return void 0;
3247
- const parts = m[2].split(".");
3248
- 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`;
3249
- const [prefix, ref] = parts;
3250
- if (ref === "*") return void 0;
3251
- if (!/^\d+$/.test(prefix) || !/^\d+$/.test(ref)) {
3252
- return `${m[1]} \uD615\uC2DD \uC624\uB958: ${uri} \u2014 \uD68C\uC0AC \uD504\uB9AC\uD53D\uC2A4\uC640 \uCC38\uC870\uB294 \uC22B\uC790\uB2E4`;
3253
- }
3254
- const got = prefix.length + ref.length;
3255
- if (got === want) return void 0;
3256
- 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.`;
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" };
3257
3277
  }
3258
- function classIdentifierViolation(epcClass) {
3259
- if (!epcClass) return `quantity epcClass \uBD80\uC815: ${epcClass}`;
3260
- const digits = gs1KeyDigitViolation(epcClass);
3261
- if (digits) return `quantity epcClass \uBD80\uC815: ${digits}`;
3262
- if (EPC_CLASS_PREFIXES.some((p) => epcClass.startsWith(p))) return void 0;
3263
- if (epcClass.startsWith(DL_CANONICAL)) return void 0;
3264
- if (CBV_URL_CLASS.test(epcClass) || CBV_URN_CLASS.test(epcClass)) return void 0;
3265
- 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>)`;
3278
+ function periodFactId(tenantId, kind, subject, from, to) {
3279
+ return [tenantId, kind, subject, from, to].join("|");
3266
3280
  }
3267
- function validateEpcisEvent(e) {
3268
- const v = [];
3269
- for (const [field, list] of [
3270
- ["epcList", e.epcList],
3271
- ["childEPCs", e.childEPCs],
3272
- ["inputEPCList", e.inputEPCList],
3273
- ["outputEPCList", e.outputEPCList],
3274
- ["parentID", e.parentID ? [e.parentID] : void 0]
3275
- ]) {
3276
- for (const epc of list ?? []) {
3277
- const bad2 = gs1KeyDigitViolation(epc);
3278
- if (bad2) v.push(`${field}: ${bad2}`);
3279
- }
3280
- }
3281
- if (e["@context"] !== EPCIS_CONTEXT) v.push("@context \uB204\uB77D/\uBD88\uC77C\uCE58");
3282
- if (!["ObjectEvent", "AggregationEvent", "TransactionEvent", "TransformationEvent"].includes(e.type)) v.push(`\uC54C \uC218 \uC5C6\uB294 type: ${e.type}`);
3283
- if (typeof e.eventTime !== "string" || !ISO_RE.test(e.eventTime)) v.push("eventTime ISO8601 \uC544\uB2D8");
3284
- if (typeof e.eventTimeZoneOffset !== "string" || !TZ_RE.test(e.eventTimeZoneOffset)) v.push("eventTimeZoneOffset \uD615\uC2DD \uC624\uB958");
3285
- if (typeof e.bizStep !== "string" || !e.bizStep) v.push("bizStep \uB204\uB77D");
3286
- if (e.eventID !== void 0 && (typeof e.eventID !== "string" || !e.eventID)) v.push("eventID \uAC00 \uBE48 \uBB38\uC790\uC5F4");
3287
- if (e.recordTime !== void 0 && (typeof e.recordTime !== "string" || !ISO_RE.test(e.recordTime))) {
3288
- v.push("recordTime ISO8601 \uC544\uB2D8");
3289
- }
3290
- if (e.ilmd !== void 0) {
3291
- const allowed = e.type === "ObjectEvent" && e.action === "ADD" || e.type === "TransformationEvent";
3292
- if (!allowed) v.push("ilmd \uB294 ObjectEvent(action=ADD) \uB610\uB294 TransformationEvent \uC5D0\uB9CC \uC2E4\uC744 \uC218 \uC788\uB2E4");
3293
- }
3294
- for (const sd of e.sourceList ?? []) {
3295
- if (!sd?.type || !sd?.source) v.push("sourceList \uD56D\uBAA9\uC5D0 type \uB610\uB294 source \uB204\uB77D");
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`);
3296
3290
  }
3297
- for (const sd of e.destinationList ?? []) {
3298
- 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;
3299
3299
  }
3300
- if (e.persistentDisposition !== void 0) {
3301
- const set = e.persistentDisposition.set ?? [];
3302
- const unset = e.persistentDisposition.unset ?? [];
3303
- if (!set.length && !unset.length) v.push("persistentDisposition \uC774 set\xB7unset \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3304
- const both = set.filter((x) => unset.includes(x));
3305
- 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;
3306
3303
  }
3307
- for (const se of e.sensorElementList ?? []) {
3308
- if (!Array.isArray(se?.sensorReport) || se.sensorReport.length === 0) {
3309
- 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);
3310
3321
  }
3311
- }
3312
- if (e.errorDeclaration !== void 0) {
3313
- const d = e.errorDeclaration;
3314
- if (typeof d?.declarationTime !== "string" || !ISO_RE.test(d.declarationTime)) {
3315
- 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;
3316
3333
  }
3317
- if (d?.correctiveEventIDs !== void 0) {
3318
- if (!Array.isArray(d.correctiveEventIDs)) v.push("errorDeclaration.correctiveEventIDs \uBC30\uC5F4 \uC544\uB2D8");
3319
- else if (d.correctiveEventIDs.some((x) => typeof x !== "string" || !x)) {
3320
- v.push("errorDeclaration.correctiveEventIDs \uC5D0 \uBE48 \uAC12");
3321
- }
3334
+ if (errors.length || !span || kWh === void 0) {
3335
+ rejected.push({ record: r, errors });
3336
+ continue;
3322
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
+ });
3323
3364
  }
3324
- if (e.type === "ObjectEvent") {
3325
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3326
- if (!Array.isArray(e.epcList)) v.push("ObjectEvent.epcList \uB204\uB77D");
3327
- else if (e.epcList.length === 0 && !e.quantityList?.length) v.push("ObjectEvent: epcList/quantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3328
- } else if (e.type === "AggregationEvent") {
3329
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3330
- if (!e.parentID) v.push("AggregationEvent.parentID \uB204\uB77D");
3331
- if (!e.childEPCs?.length && !e.childQuantityList?.length) v.push("AggregationEvent: childEPCs/childQuantityList \uB458 \uB2E4 \uBE44\uC5B4\uC788\uC74C");
3332
- } else if (e.type === "TransactionEvent") {
3333
- if (!ACTIONS.includes(e.action)) v.push(`action \uBD80\uC815: ${e.action}`);
3334
- if (!Array.isArray(e.bizTransactionList) || e.bizTransactionList.length === 0) v.push("TransactionEvent.bizTransactionList \uB204\uB77D");
3335
- } else if (e.type === "TransformationEvent") {
3336
- if (!e.inputEPCList?.length && !e.inputQuantityList?.length) v.push("TransformationEvent: input \uBE44\uC5B4\uC788\uC74C");
3337
- if (!e.outputEPCList?.length && !e.outputQuantityList?.length) v.push("TransformationEvent: output \uBE44\uC5B4\uC788\uC74C");
3338
- }
3339
- const qtyLists = [
3340
- "quantityList" in e ? e.quantityList : void 0,
3341
- "childQuantityList" in e ? e.childQuantityList : void 0,
3342
- "inputQuantityList" in e ? e.inputQuantityList : void 0,
3343
- "outputQuantityList" in e ? e.outputQuantityList : void 0
3344
- ];
3345
- for (const list of qtyLists) for (const q of list ?? []) {
3346
- const bad2 = classIdentifierViolation(q.epcClass);
3347
- if (bad2) v.push(bad2);
3348
- const hasQty = q.quantity !== void 0 && q.quantity !== null;
3349
- if (!hasQty) {
3350
- 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 });
3351
3385
  continue;
3352
3386
  }
3353
- if (typeof q.quantity !== "number" || !Number.isFinite(q.quantity) || q.quantity <= 0) {
3354
- 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] });
3355
3399
  continue;
3356
3400
  }
3357
- if (q.uom === void 0 && !Number.isInteger(q.quantity)) v.push("uom \uC5C6\uB294 quantity \uB294 \uC815\uC218(\uAC1C\uC218)\uC5EC\uC57C \uD55C\uB2E4");
3358
- 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
+ });
3359
3408
  }
3360
- return v;
3409
+ return { accepted, rejected };
3361
3410
  }
3362
3411
 
3363
3412
  // src/order-fold.ts
@@ -5079,6 +5128,7 @@ function nonEmpty(value) {
5079
5128
  ERP_MASTER_AXIS,
5080
5129
  FIRST_PASS_RULE,
5081
5130
  GUARD_PRAGMA,
5131
+ HATIOLAB_VOCABULARY,
5082
5132
  ILMD_ATTR,
5083
5133
  LOCATION_SATURATION_NEAR,
5084
5134
  MATERIAL_ACTUAL_USE,
@@ -5099,6 +5149,7 @@ function nonEmpty(value) {
5099
5149
  ORDER_FOLD_HOUR_MS,
5100
5150
  ORDER_TERMINAL_STATUS,
5101
5151
  PRIORITY_UNSET,
5152
+ PRIVATE_BIZSTEP,
5102
5153
  READ_BASIS,
5103
5154
  REFUSED_WITHOUT_CODE,
5104
5155
  RESOURCE_KIND,
@@ -5123,6 +5174,7 @@ function nonEmpty(value) {
5123
5174
  WMS_RECEIVING_ORDER_KINDS,
5124
5175
  WMS_TYPES,
5125
5176
  YARD_BIZSTEP,
5177
+ YARD_PRIVATE_BIZSTEP,
5126
5178
  YMS_LOCATION_TYPES,
5127
5179
  YMS_TYPES,
5128
5180
  acceptsPerformance,
@@ -5137,6 +5189,7 @@ function nonEmpty(value) {
5137
5189
  axisAppliesTo,
5138
5190
  axisInfo,
5139
5191
  axisSource,
5192
+ bizStepName,
5140
5193
  bizTransactionUri,
5141
5194
  canPreview,
5142
5195
  capabilitiesForType,