contractMocks.js 190 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213
  1. /**
  2. * 契约化 mock 样例(票 05):与真实接口**同一份字段名与嵌套形状**。
  3. *
  4. * 依据(Q3=A):字段名与结构照抄后端演示载荷 ——
  5. * `E:\pipe-ner-server\docs\cockpit\*.html` 与 `research/panel-field-coverage.md` 的逐字段表。
  6. * 因此适配器单测证明的是「转换吃得下真载荷」,而不是「吃得下我自己编的小样」。
  7. *
  8. * 覆盖票 05 要求的五类样例(每个接口都能取到):
  9. * `success`(正常)/ `empty`(空数据)/ `degraded`(字段缺失)/ `failed`(失败)/ `stale`(过期)。
  10. * 另有 `unauthorized`:票 05 验收第 6 条的 401 场景,只影响被请求的那个分区。
  11. *
  12. * 票 12 追加两个场景(时间线是**工单面板内**的分区,成败与工单列表分开):
  13. * `work-order-timeline`:三张工单、各一条独立时间线(推进 / 回退 / 取消三种形状都齐);
  14. * `work-order-timeline-failed`:工单列表成功、**只有时间线分区失败**(分区独立)。
  15. *
  16. * 数据是**精心构造的边界值**,不是随手填的:坐标覆盖 VALID/UNVERIFIED/INVALID/ZERO、
  17. * 指标覆盖 0 与「无采样」、时间覆盖未结案(null)。
  18. */
  19. import { REQUEST_REASON } from '../domain/requestReason.js'
  20. // 票 20:工单状态字典**只从唯一源取**(后端 `WorkOrderStatusEnum` 0–7 的前端映射)。
  21. // mock 不再自备一份副本 —— 那正是"后端改成 0–7 而 mock 还发 1–7"的成因。
  22. import { WORK_ORDER_STATES } from '../domain/workOrder.js'
  23. // 票 61:历史分析的逐事件行与当前事件表共用同一套排序口径(不另写一份比较器)。
  24. import { sortEventRows } from '../domain/eventList.js'
  25. const SNAPSHOT_AT = '2026-09-02T10:00:00+08:00'
  26. /** 票 42 的受控样例:承载有效坐标设备的点位与其设备编码清单(地图与详情必须一致)。 */
  27. const DEVICE_LAYER_POINT = 'MP-001'
  28. const DEVICE_LAYER_CODES = ['EQ-001', 'EQ-002']
  29. const DEVICE_LAYER_COORDS = [
  30. { longitude: 110.3991, latitude: 28.4351 },
  31. { longitude: 110.3975, latitude: 28.4338 },
  32. ]
  33. const OVERLAP_DEVICE_LAYER_COORDS = [
  34. { longitude: 110.3991, latitude: 28.4351 },
  35. { longitude: 110.3991, latitude: 28.4351 },
  36. ]
  37. /**
  38. * 票 76(2026-10-23 维护者裁定「删过期 mock」):旧的 `EQ-DG-*` K>10 样例已删除。
  39. * 它经多轮修改后快照/详情/坐标三处各说各话(走查反复出现「太常跳到城南」「11 台不一致」),
  40. * 聚合测试统一改用下面的 `aggregate-lab`(`EQ-AG-*`,三处同源)。
  41. */
  42. /**
  43. * 票 76(mock 串点修正,2026-10-23 走查):MP-002「太常」的 K=11 样例改用**独立编码**。
  44. * 此前它与专用场景点位(MP-001 城南)共用 `EQ-DG-*` —— 同一台设备同时挂在两个点位下,
  45. * 点设备按编码回联时命中另一点位,走查表现为「太常的设备跳到城南聚合」。
  46. */
  47. const OVERLAP_TAICHANG_CODES = Array.from({ length: 11 }, (_, index) => `EQ-TC-${String(index + 1).padStart(3, '0')}`)
  48. /**
  49. * 票 76(聚合测试数据重建,维护者 2026-10-23 要求):**干净的聚合实验样例**。
  50. *
  51. * 旧样例(`EQ-DG-*`)经多轮修改已不可靠(快照/详情/坐标三处各说各话)。这份新样例只做一件事:
  52. * **4 台设备同坐标**(K=4 > 1 且 ≤ maxFan=10,不进降级),且
  53. * 快照 `deviceCodes`、详情 `devices[]`、设备坐标 **三处同源**。
  54. * 走查入口:`?scenario=aggregate-lab` → 点开 **MP-001(城南测试监测点)**。
  55. */
  56. const AGGREGATE_LAB_CODES = Array.from({ length: 4 }, (_, index) => `EQ-AG-${String(index + 1).padStart(3, '0')}`)
  57. const AGGREGATE_LAB_COORDS = Array.from({ length: 4 }, () => ({ longitude: 110.3989, latitude: 28.4349 }))
  58. /**
  59. * 票 47:**设备状态动效样例** —— 五态各一台(坐标各自错开,不触发重叠聚合),
  60. * 用来验证「只有报警/预警/工单三种需处置状态有动效,正常/离线完全静止」。
  61. */
  62. const EFFECTS_SAMPLE = [
  63. { deviceCode: 'EQ-EF-ALARM', deviceName: '动效样例-报警设备', deviceStatus: 'ALARM' },
  64. { deviceCode: 'EQ-EF-WARNING', deviceName: '动效样例-预警设备', deviceStatus: 'WARNING' },
  65. { deviceCode: 'EQ-EF-WORK', deviceName: '动效样例-工单处置设备', deviceStatus: 'WORK_ORDER' },
  66. { deviceCode: 'EQ-EF-NORMAL', deviceName: '动效样例-正常设备', deviceStatus: 'NORMAL' },
  67. { deviceCode: 'EQ-EF-OFFLINE', deviceName: '动效样例-离线设备', deviceStatus: 'OFFLINE' },
  68. ].map((item, index) => ({
  69. ...item,
  70. // 错开约 80m,既不重叠也不会因为贴太近互相遮挡。
  71. longitude: 110.3991 + index * 0.0008,
  72. latitude: 28.4351 + index * 0.0006,
  73. }))
  74. /** 票 47:**降级样例** —— 31 台报警设备(超过 `map.effects.abnormalLimit` 默认 30)。 */
  75. const EFFECTS_DEGRADED_SAMPLE = Array.from({ length: 31 }, (_, index) => ({
  76. deviceCode: `EQ-EF-D${String(index + 1).padStart(2, '0')}`,
  77. deviceName: `动效降级设备-${index + 1}`,
  78. deviceStatus: 'ALARM',
  79. longitude: 110.3991 + (index % 6) * 0.0008,
  80. latitude: 28.4351 + Math.floor(index / 6) * 0.0006,
  81. }))
  82. // ---------------------------------------------------------------- 地图摘要
  83. const MAP_POINTS = [
  84. {
  85. pointCode: 'MP-001',
  86. // 维护者指定的走查测试点位(原名「供水干管监测点」):坐标落在主场景区内,
  87. // 县域默认视角下**可见**,用于验收「点选 → 点位级定位 → 面板锚定」。
  88. pointName: '城南测试监测点',
  89. pointStatus: 'NORMAL',
  90. statusReasons: [],
  91. // 维护者要求的主场景示例之一:**K=2 正常重叠**(两台设备同坐标,可逐台展开)。
  92. deviceCodes: DEVICE_LAYER_CODES.slice(),
  93. // 票 18:`map-snapshot` 真的收 industry/district/deviceType 三个筛选入参(票 25 第 3 节的
  94. // 冻结路径),mock 必须照此**真的过滤** —— 否则「筛选下发到地图」的断言会变成假绿
  95. // (请求串里有参数、但样例永远回同一份数据)。这两个字段域对象不读,只服务过滤。
  96. industry: 'WATER_SUPPLY',
  97. district: 0, districtName: '城南',
  98. longitude: 110.39832789395186,
  99. latitude: 28.434456975811777,
  100. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  101. },
  102. {
  103. pointCode: 'MP-002',
  104. // 维护者指定的走查测试点位(原名「燃气调压站监测点」)。**必须与台账分布里的坐标一致** ——
  105. // 台账卡片点选后按编码回联的是本表(`map-snapshot`),两处不一致会让"点同一个点飞到两个地方"。
  106. pointName: '太常测试监测点',
  107. pointStatus: 'ALARM',
  108. statusReasons: ['EQ-ASSOC-001 报警'],
  109. // 维护者要求的主场景示例之一:**K=11 降级**(超过 `map.overlap.maxFan` 默认 10)。
  110. // 票 76:用太常专属编码(不再与城南场景点共用 `EQ-DG-*`,避免同一设备挂两个点位)。
  111. deviceCodes: OVERLAP_TAICHANG_CODES.slice(),
  112. industry: 'GAS',
  113. district: 2, districtName: '太常',
  114. longitude: 110.36299369455823,
  115. latitude: 28.452196938060194,
  116. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  117. },
  118. {
  119. pointCode: 'MP-003',
  120. pointName: '污水排口监测点',
  121. pointStatus: 'WARNING',
  122. statusReasons: ['EQ-FREE-003 预警'],
  123. deviceCodes: ['EQ-003'],
  124. industry: 'DRAINAGE',
  125. // 空区域被后端归一为字面量「未分区」——那是**真实取值**,筛选它能筛到东西。
  126. district: null, districtName: '未分区',
  127. longitude: 110.143,
  128. latitude: 28.454,
  129. coordinateValidation: { state: 'UNVERIFIED', reason: 'UNVERIFIED_COORDINATE', renderable: false, crs: 'WGS84' },
  130. },
  131. ]
  132. const MAP_EQUIPMENT = [
  133. {
  134. deviceCode: 'EQ-FREE-001',
  135. deviceName: '供水压力计-001',
  136. // 类型不可推导时后端给 null,且**默认不排除对象**(不筛时仍返回)。
  137. industry: null,
  138. district: 0, districtName: '城南',
  139. // 票 14:未关联设备按**设备状态词表**参与状态筛选(决策 02 的 Q22)。
  140. deviceStatus: 'NORMAL',
  141. longitude: 181,
  142. latitude: 28.455,
  143. coordinateValidation: { state: 'INVALID', reason: 'LONGITUDE_OUT_OF_RANGE', renderable: false, crs: 'WGS84' },
  144. },
  145. {
  146. deviceCode: 'EQ-FREE-004',
  147. deviceName: '零坐标设备-004',
  148. industry: null,
  149. district: null, districtName: '未分区',
  150. // 状态未发布(缺字段):落 UNKNOWN 桶——不猜成正常。
  151. deviceStatus: null,
  152. longitude: 0,
  153. latitude: 0,
  154. coordinateValidation: { state: 'INVALID', reason: 'ZERO_COORDINATE', renderable: false, crs: 'WGS84' },
  155. },
  156. ]
  157. /** 地图摘要的演示分页(票 08):契约允许任意页大小,演示用 2 —— 三页翻完,看得出来是渐进加载。 */
  158. const MAP_SNAPSHOT_PAGE_SIZE = 2
  159. /**
  160. * 票 09 的点位状态样例:**后端六态各一个**,全部坐标合法(都该上图),
  161. * 外加一个后端新增、前端不认识的第九个状态 —— 它必须落「状态未发布」而不是被猜成正常。
  162. *
  163. * 为什么要单独一份而不是改上面那三个点位:票 07/08 的走查把 `2,4,5` / 可上图 2 · 不上图 3
  164. * 这些数写成了断言,改默认样例就会改掉那两张票的证据。所以状态演示走**独立场景**
  165. * (`__COCKPIT_MOCK_SCENARIO__ = 'point-statuses'`),默认样例一个字节不动。
  166. */
  167. const STATUS_SAMPLE_POINTS = [
  168. { pointCode: 'MP-ST-ALARM', pointName: '燃气调压站报警监测点', pointStatus: 'ALARM' },
  169. { pointCode: 'MP-ST-WARNING', pointName: '污水排口预警监测点', pointStatus: 'WARNING' },
  170. { pointCode: 'MP-ST-WORKORDER', pointName: '供水干管工单处置监测点', pointStatus: 'WORK_ORDER' },
  171. { pointCode: 'MP-ST-NORMAL', pointName: '排水泵站正常监测点', pointStatus: 'NORMAL' },
  172. { pointCode: 'MP-ST-OFFLINE', pointName: '窨井离线监测点', pointStatus: 'OFFLINE' },
  173. { pointCode: 'MP-ST-EMPTY', pointName: '预留无设备监测点', pointStatus: 'EMPTY' },
  174. // 后端将来新增的状态:前端不认识,必须如实说「状态未发布」,不得落到任何真实状态上。
  175. { pointCode: 'MP-ST-UNKNOWN', pointName: '未知状态监测点', pointStatus: 'MAINTENANCE' },
  176. ].map((item, index) => ({
  177. ...item,
  178. statusReasons: [],
  179. // 沿经纬度铺开一点,免得标记叠在一起看不出形状差异。
  180. longitude: 110.141 + index * 0.002,
  181. latitude: 28.452 + index * 0.001,
  182. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  183. }))
  184. /** 状态样例里的未关联设备(第六态「无关联设备」的落点,形状是十字)。 */
  185. const STATUS_SAMPLE_EQUIPMENT = [
  186. {
  187. deviceCode: 'EQ-ST-FREE',
  188. deviceName: '未关联设备-001',
  189. // 票 14:设备状态参与状态筛选(决策 02 的 Q22)——样例给一个真实态。
  190. deviceStatus: 'WARNING',
  191. longitude: 110.155,
  192. latitude: 28.459,
  193. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  194. },
  195. ]
  196. /**
  197. * 票 14:mock 侧的**设备级事实表**(决策 02 的 Q7/Q8——命中设备子集与点位 OR 归并的依据)。
  198. *
  199. * 真实后端按「任一设备命中 industry/district/deviceType → 点位进入结果」归并,
  200. * 且点位响应的 `deviceCodes` 按当前筛选裁剪为**命中设备子集**(未筛=全部)。
  201. * mock 要演示这条契约,就得知道每台关联设备的行业/区域/类型 ——
  202. * 这里登记的是**测试事实**,不是业务数据(正式口径归后端执行票 12+)。
  203. * 未登记的设备不参与裁剪(宁可多给,不吞)。
  204. */
  205. const DEVICE_FACTS = {
  206. 'EQ-001': { industry: 'WATER_SUPPLY', district: 0, districtName: '城南', deviceType: 'WATER_SUPPLY_SENSOR' },
  207. 'EQ-002': { industry: 'GAS', district: 2, districtName: '太常', deviceType: 'GAS_SENSOR' },
  208. 'EQ-003': { industry: 'DRAINAGE', district: null, districtName: '未分区', deviceType: 'SEWAGE_ENV' },
  209. }
  210. /** 设备自身状态的五个取值(`domain/deviceStatus.js` 的词表;`EMPTY` 是点位聚合态专有)。 */
  211. const DEVICE_STATUS_CODES_MOCK = ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE']
  212. /** 后端六个点位状态(`domain/pointStatus.js` 的 `POINT_STATUS`)。 */
  213. const POINT_STATUS_CODES_MOCK = ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE', 'EMPTY']
  214. /**
  215. * 一个摘要对象的状态桶(票 14 的八桶匹配语义,决策 02 的 Q22/Q23):
  216. * · 监测点按**聚合状态**六态匹配;缺失或不在六态词典 → `UNKNOWN`(不猜成正常);
  217. * · 未关联设备按**设备状态词表**五态匹配(mock 载荷新增 `deviceStatus` 字段建模这条契约);
  218. * 缺失或认不出 → `UNKNOWN`(设备状态未发布)。
  219. */
  220. function statusBucketOf(item) {
  221. if ('pointCode' in item) {
  222. const status = item.pointStatus
  223. return status && POINT_STATUS_CODES_MOCK.includes(status) ? status : 'UNKNOWN'
  224. }
  225. const status = item.deviceStatus
  226. return status && DEVICE_STATUS_CODES_MOCK.includes(status) ? status : 'UNKNOWN'
  227. }
  228. /**
  229. * 多值状态筛选的匹配(决策 02 的 Q11/Q16——「无关联设备」桶是类别筛选,与状态正交):
  230. * · 空集合 → 全部;
  231. * · 只选 `UNASSOCIATED` → 只看未关联设备(监测点整类排除);
  232. * · `UNASSOCIATED` + 状态桶 → 只看命中状态的未关联设备;
  233. * · 只选状态桶 → 命中状态的监测点 + 命中状态的未关联设备(各自用各自的状态来源)。
  234. */
  235. function matchesStatusFilter(item, statusSet) {
  236. if (!statusSet.length) return true
  237. const onlyDevices = statusSet.includes('UNASSOCIATED')
  238. const statusKeys = statusSet.filter((key) => key !== 'UNASSOCIATED')
  239. if ('pointCode' in item) {
  240. if (onlyDevices) return false
  241. if (!statusKeys.length) return true
  242. return statusKeys.includes(statusBucketOf(item))
  243. }
  244. if (statusKeys.length && !statusKeys.includes(statusBucketOf(item))) return false
  245. return true
  246. }
  247. /** district 空值归一(后端把空归一为字面量「未分区」——那是真实取值)。 */
  248. function normalizedDistrict(value) {
  249. const raw = value === null || value === undefined ? '' : String(value).trim()
  250. return ['0', '1', '2'].includes(raw) ? raw : 'UNASSIGNED'
  251. }
  252. /**
  253. * 一台关联设备的**设备级**筛选命中(行业/区域/类型;未登记的设备不判负)。
  254. * 票 37:`deviceType` 是后端码的**精确匹配**(`GAS_SENSOR`/`WATER_SUPPLY_SENSOR`/`SEWAGE_ENV`);
  255. * mock 样例的类型码全部来自 `DEVICE_FACTS`(与后端字典同形),不发明第二个类型域。
  256. */
  257. function deviceHitsFilters(code, filters) {
  258. const facts = DEVICE_FACTS[code]
  259. if (!facts) return true
  260. if (filters.industry && facts.industry !== filters.industry) return false
  261. if (filters.district && normalizedDistrict(facts.district) !== normalizedDistrict(filters.district)) return false
  262. if (filters.deviceType && facts.deviceType !== filters.deviceType) return false
  263. return true
  264. }
  265. /**
  266. * 票 14:按 `map-snapshot` 的筛选入参**真的过滤**,照抄决策 02 冻结的后端口径。
  267. *
  268. * 为什么 mock 必须真的筛(而不是"收了参数照旧回全量"):`mapStore.applyFilters()` 会先清空
  269. * 装载器再取第 1 页;若样例永远回同一份数据,「筛选真的下发到地图了吗」这条断言就只是
  270. * 在看请求串 —— 参数拼错了、或者根本没传,画面都一样,是**假绿**。
  271. *
  272. * 四条语义(决策 02 的 Answer 第一节 + 第二节):
  273. * · 空值归一:「未分区」是 district 空值归一后的**真实取值**,筛选它能筛到东西;
  274. * · **不带筛选时返回全部对象**(`industry` 为 null 也算数),保证"全城底图"不因类型缺失丢对象;
  275. * · 行业/范围/类型=**设备级匹配、点位 OR 归并**:点位自身命中或任一关联设备命中都进入结果;
  276. * · 状态=八桶多值 OR(六态 + UNKNOWN + UNASSOCIATED,见 `matchesStatusFilter`)。
  277. */
  278. function matchesMapFilters(item, filters) {
  279. const industry = (filters && filters.industry) || ''
  280. const district = (filters && filters.district) || ''
  281. const deviceType = (filters && filters.deviceType) || ''
  282. const statusRaw = (filters && filters.pointStatus) || []
  283. const statusSet = Array.isArray(statusRaw) ? statusRaw : String(statusRaw).split(',').filter(Boolean)
  284. if (!matchesStatusFilter(item, statusSet)) return false
  285. if ('pointCode' in item) {
  286. // 点位:设备级 OR 归并——自身命中,或任一关联设备命中(未筛时该维度是"不判")。
  287. if (industry && item.industry !== industry && !(item.deviceCodes || []).some((code) => deviceHitsFilters(code, { industry }))) return false
  288. if (district) {
  289. const own = normalizedDistrict(item.district) === normalizedDistrict(district)
  290. const viaDevice = (item.deviceCodes || []).some((code) => deviceHitsFilters(code, { district }))
  291. if (!own && !viaDevice) return false
  292. }
  293. if (deviceType) {
  294. const viaDevice = (item.deviceCodes || []).some((code) => deviceHitsFilters(code, { deviceType }))
  295. if (!viaDevice) return false
  296. }
  297. return true
  298. }
  299. // 未关联设备:按自身属性直接匹配。
  300. if (industry && item.industry !== industry) return false
  301. if (district && normalizedDistrict(item.district) !== normalizedDistrict(district)) return false
  302. // `deviceType` 不可推导的对象在带该筛选时被排除(后端同款)。
  303. if (deviceType) return false
  304. return true
  305. }
  306. /**
  307. * 票 14:命中设备子集(决策 02 的 Q8——点位响应的 `deviceCodes` 按当前筛选裁剪,未筛=全部)。
  308. * 只在**设备级**筛选(行业/范围/类型)生效时裁剪;未登记的设备保留(不吞)。
  309. */
  310. function cropToDeviceHits(point, filters) {
  311. const hasDeviceLevel = !!(filters && (filters.industry || filters.district || filters.deviceType))
  312. const codes = Array.isArray(point.deviceCodes) ? point.deviceCodes : []
  313. if (!hasDeviceLevel) return codes
  314. return codes.filter((code) => deviceHitsFilters(code, filters))
  315. }
  316. /**
  317. * 票 14:八桶**全局未筛**计数(决策 02 的第三节——状态栏与饼图共用同一份,筛选时不变)。
  318. * 六态与 UNKNOWN 数**监测点**;UNASSOCIATED 数**未关联设备**(类别桶的计数)。
  319. * 判据是完整集合(filter 之前),与分页/筛选无关。
  320. */
  321. function globalStatusDistribution(points, equipment) {
  322. const counts = { ALARM: 0, WARNING: 0, WORK_ORDER: 0, NORMAL: 0, OFFLINE: 0, EMPTY: 0, UNKNOWN: 0, UNASSOCIATED: 0 }
  323. for (const point of points) counts[statusBucketOf(point)] += 1
  324. for (const device of equipment) counts.UNASSOCIATED += 1
  325. return Object.keys(counts).map((status) => ({ status, count: counts[status] }))
  326. }
  327. /**
  328. * 按后端**真实语义**造一页地图摘要(票 08 的分页 + 票 18 的筛选 + 票 14 的契约)。
  329. *
  330. * 照抄 `CockpitMapSnapshotService.load()` 的三条行为,而不是造一份"理想载荷":
  331. * 1. 分页窗口是「监测点 + 未关联设备」这**一条总序列**:先排满监测点,再排未关联设备
  332. * (所以后一页可能整页都是设备,或两类混在一页);
  333. * 2. 第 2 页起**必须**带 `snapshotAt`,且与当前快照一致,否则抛 `SNAPSHOT_EXPIRED`;
  334. * 3. `complete` 只在「本页末尾已到总数」时为真。
  335. *
  336. * 票 07 起另有一条**必须照抄**:响应带 `coordinateValidation` **全量**汇总
  337. * (后端用整份 points/equipment 算完再切片分页,所以它不随页码变化)。
  338. *
  339. * 票 14 追加两条(决策 02 冻结的契约):
  340. * · 点位响应的 `deviceCodes` 按当前筛选裁剪为**命中设备子集**(未筛=全部);
  341. * · 响应带八桶**全局未筛**计数 `pointStatusDistribution`(状态栏与饼图共用,筛选时不变)。
  342. *
  343. * @param {object} options
  344. * @param {number} [options.page] 页码(1 起)
  345. * @param {number} [options.pageSize] 每页条数
  346. * @param {string} [options.snapshotAt] 客户端带的快照标记(第 1 页不带)
  347. * @param {string} [options.currentSnapshot] 本次请求后端当前快照(固定值,见 `planMapSnapshot`)
  348. * @param {Array} [options.points] 覆盖监测点集合(票 09 的状态样例用)
  349. * @param {Array} [options.equipment] 覆盖未关联设备集合
  350. */
  351. function mapSnapshotPage({
  352. page = 1,
  353. pageSize = MAP_SNAPSHOT_PAGE_SIZE,
  354. snapshotAt = '',
  355. currentSnapshot = SNAPSHOT_AT,
  356. points = MAP_POINTS,
  357. equipment = MAP_EQUIPMENT,
  358. filters = null,
  359. echoFilters = null,
  360. } = {}) {
  361. if (page > 1 && !snapshotAt) {
  362. const error = new Error('mock: 第 2 页起必须带 snapshotAt')
  363. error.reason = REQUEST_REASON.SNAPSHOT_EXPIRED
  364. throw error
  365. }
  366. if (snapshotAt && snapshotAt !== currentSnapshot) {
  367. const error = new Error('mock: 快照标记与当前快照不一致')
  368. error.reason = REQUEST_REASON.SNAPSHOT_EXPIRED
  369. throw error
  370. }
  371. // 票 18:筛选**先于分页**(后端也是先过滤再切片),且 `coordinateValidation` 汇总是
  372. // 「当前筛选范围内的全量口径」——所以它跟着筛选变,不跟着页码变。
  373. const selected = filters
  374. ? [...points, ...equipment].filter((item) => matchesMapFilters(item, filters))
  375. : [...points, ...equipment]
  376. const from = Math.max(0, (page - 1) * pageSize)
  377. const to = from + pageSize
  378. const slice = selected.slice(from, to)
  379. // 票 14:本页的点位带上**命中设备子集**(未筛=全部;决策 02 的 Q8)。
  380. const slicedPoints = slice
  381. .filter((item) => 'pointCode' in item)
  382. .map((point) => ({ ...point, deviceCodes: cropToDeviceHits(point, filters) }))
  383. return {
  384. page,
  385. pageSize,
  386. snapshotAt: currentSnapshot,
  387. batchUpdatedAt: currentSnapshot,
  388. total: selected.length,
  389. complete: to >= selected.length,
  390. monitoringPoints: slicedPoints,
  391. unassociatedEquipment: slice.filter((item) => 'deviceCode' in item),
  392. // 编码回显来自**过滤后全量**(分页前),与后端同口径。
  393. mapFilter: mapFilterEcho(echoFilters || filters || {}, selected.filter((item) => 'pointCode' in item), selected.filter((item) => 'deviceCode' in item)),
  394. // 全量口径:与 `CockpitMapSnapshotService.coordinateValidation(points, equipment)` 一致。
  395. coordinateValidation: coordinateValidationSummary(selected),
  396. // 票 14:八桶全局未筛计数(完整集合口径,筛选时不变;状态栏与饼图共用)。
  397. pointStatusDistribution: globalStatusDistribution(points, equipment),
  398. }
  399. }
  400. /**
  401. * 坐标校验汇总(票 07):照抄后端 `CockpitCoordinateValidationSummary` 的字段名与判据。
  402. *
  403. * 后端的分法是**三桶**:`renderable` 优先,其余里 `state === 'INVALID'` 记非法,
  404. * 剩下的一律记「未校验」(`CockpitMapSnapshotService` 第 205-231 行)。
  405. * 这里照抄同一个分法 —— 换一套算法就会让前端显示的数与后端对不上。
  406. */
  407. function coordinateValidationSummary(objects) {
  408. let renderableCount = 0
  409. let invalidCount = 0
  410. let unverifiedCount = 0
  411. for (const item of objects) {
  412. const validation = item.coordinateValidation || {}
  413. if (validation.renderable === true) renderableCount += 1
  414. else if (validation.state === 'INVALID') invalidCount += 1
  415. else unverifiedCount += 1
  416. }
  417. return {
  418. crs: 'WGS84',
  419. totalObjectCount: objects.length,
  420. renderableCount,
  421. invalidCount,
  422. unverifiedCount,
  423. }
  424. }
  425. /**
  426. * 从请求路径的查询串里取一个整数参数。
  427. * 走查与演示要能现场改页大小(`window.__COCKPIT_MOCK_MAP_PAGE_SIZE__`),
  428. * 所以分页参数必须真的从请求上读,而不是写死一份。
  429. */
  430. function queryInteger(path, key, fallback) {
  431. const query = String(path || '').split('?')[1] || ''
  432. const value = new URLSearchParams(query).get(key)
  433. const parsed = Number(value)
  434. return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback
  435. }
  436. /** 查询串里的快照标记(第 1 页不带)。 */
  437. function querySnapshot(path) {
  438. const query = String(path || '').split('?')[1] || ''
  439. return new URLSearchParams(query).get('snapshotAt') || ''
  440. }
  441. /** 查询串里的一个字符串参数(缺失回空串;票 18 的筛选回显与过滤都读它)。 */
  442. function queryValue(path, key) {
  443. const query = String(path || '').split('?')[1] || ''
  444. return new URLSearchParams(query).get(key) || ''
  445. }
  446. /** 请求查询串 → 普通对象(票 18:筛选与分页在 mock 上要真的按请求回)。 */
  447. function queryParams(path) {
  448. const query = String(path || '').split('?')[1] || ''
  449. const result = {}
  450. for (const [key, value] of new URLSearchParams(query)) result[key] = value
  451. return result
  452. }
  453. /**
  454. * 地图摘要样例(票 08):**按后端真实分页语义**造,而不是只给一页。
  455. *
  456. * 场景(`overrides` 由走查现场给,见 `mocks/index.js`):
  457. * · `success` —— 正常分页,后端当前快照固定;
  458. * · `empty` —— 后端说总数 0(不是「这一页恰好没有」);
  459. * · `degraded` —— 保持票 05 的字段缺失样例(单页、`complete: false`);
  460. * · `stale` —— **取完第 1 页后后端换了快照**(`expireAfterPage`),第 2 页带着旧标记回来即失效;
  461. * · `failed` —— 由统一出口抛出,不在这里给载荷。
  462. *
  463. * @param {string} scenario 五类样例
  464. * @param {string} path 请求路径(分页参数在这里)
  465. * @param {object} [overrides] `{ pageSize, snapshotAt, expireAfterPage }`
  466. */
  467. function mapSnapshotPayload(scenario, path, overrides = {}) {
  468. const pageSize = overrides.pageSize || MAP_SNAPSHOT_PAGE_SIZE
  469. const page = queryInteger(path, 'page', 1)
  470. const baseSnapshot = overrides.snapshotAt || SNAPSHOT_AT
  471. // 票 18:三个筛选入参从**请求查询串**读(不是从 overrides)——
  472. // 「筛选真的下发了」这件事必须由请求本身证明,不能靠现场注入的开关。
  473. // 票 14:`pointStatus` 多值(逗号分隔,OR)也在这里解析。
  474. const filters = {
  475. industry: queryValue(path, 'industry'),
  476. district: queryValue(path, 'district'),
  477. deviceType: queryValue(path, 'deviceType'),
  478. pointStatus: queryValue(path, 'pointStatus') ? queryValue(path, 'pointStatus').split(',') : [],
  479. }
  480. const filtered = !!(filters.industry || filters.district || filters.deviceType || filters.pointStatus.length)
  481. if (scenario === 'empty') {
  482. return {
  483. page,
  484. pageSize,
  485. snapshotAt: baseSnapshot,
  486. batchUpdatedAt: baseSnapshot,
  487. total: 0,
  488. complete: true,
  489. monitoringPoints: [],
  490. unassociatedEquipment: [],
  491. mapFilter: mapFilterEcho(filters, [], []),
  492. // 真·空快照:全量口径各项都是 0(这里 0 是真实值,不是缺失)。
  493. coordinateValidation: coordinateValidationSummary([]),
  494. // 空 = 全局八桶也全 0(这是真实值,不是缺失)。
  495. pointStatusDistribution: globalStatusDistribution([], []),
  496. }
  497. }
  498. if (scenario === 'degraded') {
  499. const degraded = [{ pointCode: 'MP-DEGRADED', pointName: '字段缺失点位', pointStatus: 'NORMAL', statusReasons: [] }]
  500. return {
  501. page: 1,
  502. pageSize: 500,
  503. snapshotAt: baseSnapshot,
  504. complete: false,
  505. monitoringPoints: degraded,
  506. unassociatedEquipment: [],
  507. mapFilter: mapFilterEcho(filters, degraded, []),
  508. // 后端没给 coordinateValidation 的点位:仍占一个位置,落在「未校验」桶里。
  509. coordinateValidation: coordinateValidationSummary(degraded),
  510. // 票 14:降级样例仍带全局八桶(未筛口径:字段缺失点位落 UNKNOWN 桶——不猜成正常)。
  511. pointStatusDistribution: globalStatusDistribution(degraded, []),
  512. }
  513. }
  514. // 票 09:后端六态 + 未关联设备 + 一个前端不认识的状态,全部可上图(状态演示用)。
  515. // 这个样例**不带筛选字段**,所以带筛选请求时会被全部排除 —— 与后端"推导不出行业即排除"一致。
  516. if (scenario === 'point-statuses') {
  517. return mapSnapshotPage({
  518. page,
  519. pageSize,
  520. snapshotAt: querySnapshot(path),
  521. currentSnapshot: baseSnapshot,
  522. points: STATUS_SAMPLE_POINTS,
  523. equipment: STATUS_SAMPLE_EQUIPMENT,
  524. filters: filtered ? filters : null,
  525. })
  526. }
  527. // 票 42/45/47:受控有效坐标样例 —— 地图侧的点位 `deviceCodes` 必须与详情 `devices[]` **一致**,
  528. // 否则第二台设备会被判「与当前快照不一致」而禁止上图(那是另一条要验的语义,不该混在这个基线里)。
  529. const deviceLayerCodes = {
  530. 'device-layer': DEVICE_LAYER_CODES,
  531. 'device-layer-overlap': DEVICE_LAYER_CODES,
  532. // 票 76:全新的干净聚合样例(4 台同坐标,快照/详情/坐标同源)。
  533. 'aggregate-lab': AGGREGATE_LAB_CODES,
  534. // 票 47:动效样例与降级样例的设备编码(与详情一一对应)。
  535. 'device-effects': EFFECTS_SAMPLE.map((item) => item.deviceCode),
  536. 'device-effects-degraded': EFFECTS_DEGRADED_SAMPLE.map((item) => item.deviceCode),
  537. }[scenario]
  538. if (deviceLayerCodes) {
  539. // 票 76(2026-10-23 修正):不再清空其它点位的编码 —— 详情已按 `requestedCode` 回各自原生载荷
  540. // (`nativePointDetail`),清空反而让「快照 0 台 / 详情 11 台」再次不一致、设备点不上图。
  541. const points = MAP_POINTS.map((item) =>
  542. item.pointCode === DEVICE_LAYER_POINT
  543. ? { ...item, deviceCodes: deviceLayerCodes.slice() }
  544. : item,
  545. )
  546. return mapSnapshotPage({
  547. page,
  548. pageSize,
  549. snapshotAt: querySnapshot(path),
  550. currentSnapshot: baseSnapshot,
  551. points,
  552. filters: filtered ? filters : null,
  553. })
  554. }
  555. // 过期样例:第 1 页照常给旧快照,之后的请求后端已经换成新快照 —— 客户端带着旧标记回来即失效。
  556. const expired = scenario === 'stale' && Number.isInteger(overrides.expireAfterPage) && page > overrides.expireAfterPage
  557. const currentSnapshot = expired ? '2026-09-02T10:30:00+08:00' : baseSnapshot
  558. return mapSnapshotPage({
  559. page,
  560. pageSize,
  561. snapshotAt: querySnapshot(path),
  562. currentSnapshot,
  563. // 不带筛选时传 null(=返回全部对象,含 industry 为 null 的设备)。
  564. filters: filtered ? filters : null,
  565. // 筛选生效时回显的编码来自**过滤后全量**(分页前),与后端 `mapFilter` 口径一致。
  566. echoFilters: filters,
  567. })
  568. }
  569. /** `mapFilter` 回显(后端在筛选生效时回显实际生效范围与过滤后全量编码;票 14 增多值状态回显)。 */
  570. function mapFilterEcho(filters, points, equipment) {
  571. const statusRaw = (filters && filters.pointStatus) || []
  572. const statusText = Array.isArray(statusRaw) ? statusRaw.join(',') : String(statusRaw || '')
  573. return {
  574. industry: filters.industry || null,
  575. district: filters.district && filters.district !== 'UNASSIGNED' ? Number(filters.district) : null,
  576. districtFilter: !filters.district ? 'NONE' : filters.district === 'UNASSIGNED' ? 'UNASSIGNED' : 'ASSIGNED',
  577. deviceType: filters.deviceType || null,
  578. pointStatus: statusText || null,
  579. pointCodes: points.map((item) => item.pointCode).filter(Boolean),
  580. deviceCodes: equipment.map((item) => item.deviceCode).filter(Boolean),
  581. }
  582. }
  583. // ---------------------------------------------------------------- 监测点详情
  584. /**
  585. * 监测点详情的样例载荷(票 05 的默认 + 四类异常样例)。
  586. *
  587. * 票 10 追加 `point-detail-order`:设备卡片刻意**逆状态优先级**排列
  588. * (正常 → 报警 → 预警),后端的返回顺序 ≠ 前端按优先级排出来的顺序 ——
  589. * 界面若自作主张排序,真机走查里那条「卡片顺序 = 后端顺序」就会当场露馅。
  590. * 默认样例一个字节未动(票 05 的断言依赖它)。
  591. */
  592. /**
  593. * 票 45:**K>10 降级载荷**(11 台设备同坐标、状态混合)。
  594. *
  595. * 主场景(MP-002 太常)与 `aggregate-lab`(MP-001 城南)共用这一份构造器 ——
  596. * 两处各写一份必然漂移(本仓反复栽在"同一份样例登记两处"上)。
  597. */
  598. function degradedOverlapPointDetail({ code, name, codes = [], coords = [], statuses = ['ALARM', 'ALARM', 'ALARM', 'WARNING', 'WARNING', 'WARNING', 'NORMAL', 'NORMAL', 'NORMAL', 'NORMAL', 'NORMAL'] }) {
  599. const devices = codes.map((code_, index) => {
  600. const deviceStatus = statuses[index]
  601. return {
  602. deviceCode: code_,
  603. deviceName: `重叠降级设备-${index + 1}`,
  604. deviceTypeName: ['压力计', '流量计', '液位计'][index % 3],
  605. deviceStatus,
  606. statusLabel: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[deviceStatus],
  607. statusReasons: deviceStatus === 'ALARM' ? ['压力超高'] : deviceStatus === 'WARNING' ? ['液位偏高'] : [],
  608. statusTime: '2026-09-02T09:59:00+08:00',
  609. ...deviceCoordFields(coords, index),
  610. }
  611. })
  612. return {
  613. requestId: 'mock-point-detail',
  614. apiVersion: 'v1',
  615. readOnly: true,
  616. monitoringPointCode: code,
  617. monitoringPointName: name,
  618. pointStatus: 'ALARM',
  619. statusLabel: '报警',
  620. statusReasons: [{ status: 'ALARM', deviceCode: codes[0], reason: '压力超高' }],
  621. deviceStatistics: {
  622. totalDeviceCount: devices.length,
  623. alarmDeviceCount: statuses.filter((status) => status === 'ALARM').length,
  624. warningDeviceCount: statuses.filter((status) => status === 'WARNING').length,
  625. workOrderDeviceCount: statuses.filter((status) => status === 'WORK_ORDER').length,
  626. normalDeviceCount: statuses.filter((status) => status === 'NORMAL').length,
  627. offlineDeviceCount: statuses.filter((status) => status === 'OFFLINE').length,
  628. },
  629. devices,
  630. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  631. statusDictionary: ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE', 'EMPTY'].map((item, index) => ({
  632. status: item,
  633. label: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[item],
  634. priority: index + 1,
  635. })),
  636. }
  637. }
  638. /**
  639. * 票 45:**K=2 正常重叠载荷**(两台设备同坐标,可逐台展开)。
  640. * 主场景(MP-001)与专用场景 `device-layer-overlap` 共用。
  641. */
  642. function overlapPointDetail({ code, name, status = 'NORMAL' }) {
  643. return pointDetail({ code, name, status, deviceCoord: OVERLAP_DEVICE_LAYER_COORDS })
  644. }
  645. /**
  646. * 票 47:按给定设备清单造详情载荷(每台都带**设备自身**的有效坐标 ⇒ `renderable=true`)。
  647. *
  648. * 决策票 07 的可断言口径要求:动效只能在**受控可上图样例**上验证
  649. * (真实环境仍是清单-only 时不得从纯逻辑断言推断现场特效已生效)。
  650. */
  651. function effectsPointDetail({ code, name, samples, pointStatus = 'ALARM' }) {
  652. const counts = { ALARM: 0, WARNING: 0, WORK_ORDER: 0, NORMAL: 0, OFFLINE: 0 }
  653. const devices = samples.map((item, index) => {
  654. const deviceStatus = item.deviceStatus
  655. if (counts[deviceStatus] !== undefined) counts[deviceStatus] += 1
  656. return {
  657. deviceCode: item.deviceCode,
  658. deviceName: item.deviceName,
  659. deviceTypeName: ['压力计', '流量计', '液位计'][index % 3],
  660. deviceStatus,
  661. statusLabel: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线' }[deviceStatus] || '',
  662. statusReasons: deviceStatus === 'ALARM' ? ['压力超高'] : deviceStatus === 'WARNING' ? ['液位偏高'] : [],
  663. statusTime: '2026-09-02T09:59:00+08:00',
  664. ...deviceCoordFields(samples, index),
  665. }
  666. })
  667. return {
  668. requestId: 'mock-point-detail',
  669. apiVersion: 'v1',
  670. readOnly: true,
  671. monitoringPointCode: code,
  672. monitoringPointName: name,
  673. pointStatus,
  674. statusLabel: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[pointStatus] || '',
  675. statusReasons: [{ status: pointStatus, deviceCode: devices[0] ? devices[0].deviceCode : '', reason: '压力超高' }],
  676. deviceStatistics: {
  677. totalDeviceCount: devices.length,
  678. alarmDeviceCount: counts.ALARM,
  679. warningDeviceCount: counts.WARNING,
  680. workOrderDeviceCount: counts.WORK_ORDER,
  681. normalDeviceCount: counts.NORMAL,
  682. offlineDeviceCount: counts.OFFLINE,
  683. },
  684. devices,
  685. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  686. statusDictionary: ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE', 'EMPTY'].map((item, index) => ({
  687. status: item,
  688. label: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[item],
  689. priority: index + 1,
  690. })),
  691. }
  692. }
  693. /**
  694. * 票 76(mock 串点修正,2026-10-23 走查):任意点位的「原生详情」。
  695. *
  696. * 场景样例只覆盖 `DEVICE_LAYER_POINT`;请求其它点位时必须回**它自己的**载荷 ——
  697. * `deviceLayerStore` 只接受 `data.code === 选中编码` 的卡片(`deviceLayerStore.js:184`),
  698. * 回错点位的载荷会让该点位的设备全部「详情待确认 / 与快照不一致 → 不上图」,
  699. * 走查表现为「点 MP-002 面板不出、关联设备不出现、要点几次或刷新地图才出来」。
  700. */
  701. function nativePointDetail(requestedCode) {
  702. if (requestedCode === 'MP-001') {
  703. return overlapPointDetail({ code: 'MP-001', name: '城南测试监测点' })
  704. }
  705. if (requestedCode === 'MP-002') {
  706. // 太常样例:K=11 同坐标,编码用自己的 `EQ-TC-*`(与场景点不再共用)。
  707. return degradedOverlapPointDetail({
  708. code: 'MP-002', name: '太常测试监测点',
  709. codes: OVERLAP_TAICHANG_CODES,
  710. coords: OVERLAP_TAICHANG_CODES.map(() => ({ longitude: 110.3632, latitude: 28.4524 })),
  711. statuses: ['ALARM', 'ALARM', 'ALARM', 'WARNING', 'WARNING', 'WARNING', 'WORK_ORDER', 'NORMAL', 'NORMAL', 'OFFLINE', 'NORMAL'],
  712. })
  713. }
  714. return pointDetail()
  715. }
  716. function pointDetailPayload(scenario, requestedCode = '') {
  717. // 票 76:下列场景样例都只覆盖 DEVICE_LAYER_POINT;请求别的点位 → 回它自己的原生详情。
  718. const scenarioSamples = ['device-layer', 'device-layer-overlap', 'device-effects', 'device-effects-degraded', 'aggregate-lab']
  719. if (scenarioSamples.includes(scenario) && requestedCode && requestedCode !== DEVICE_LAYER_POINT) {
  720. return nativePointDetail(requestedCode)
  721. }
  722. if (scenario === 'empty') {
  723. return {
  724. ...pointDetail({ code: 'MP-EMPTY', name: '预留监测点', status: 'EMPTY' }),
  725. devices: [],
  726. deviceStatistics: { totalDeviceCount: 0, alarmDeviceCount: 0, warningDeviceCount: 0, workOrderDeviceCount: 0, normalDeviceCount: 0, offlineDeviceCount: 0 },
  727. statusReasons: [],
  728. }
  729. }
  730. if (scenario === 'degraded') {
  731. return { monitoringPointCode: 'MP-DEGRADED', monitoringPointName: '字段缺失点位', devices: [], statusReasons: [] }
  732. }
  733. /**
  734. * 票 42:**受控有效坐标样例** —— 专门用来验证独立设备图层的渲染与拾取。
  735. *
  736. * 与默认场景的关键差别:两台设备都带**设备自身**的有效坐标(`VALID/renderable=true`),
  737. * 且 `deviceCodes` 与详情 `devices[]` 完全一致(否则会触发"与当前快照不一致"的提示)。
  738. * 坐标落在主场景区内、贴近点位但不重合(重合会走票 11 的重叠分支,不在本票)。
  739. */
  740. if (scenario === 'device-layer') {
  741. return pointDetail({
  742. code: DEVICE_LAYER_POINT,
  743. name: '城南测试监测点',
  744. status: 'NORMAL',
  745. // 两台设备各有有效坐标且不重叠:票 42 的单设备层基线。
  746. deviceCoord: DEVICE_LAYER_COORDS,
  747. })
  748. }
  749. /** 票 45:两台设备拥有**各自真实字段**,但坐标恰好重叠;用于测试纯渲染层聚合/展开。 */
  750. if (scenario === 'device-layer-overlap') {
  751. return overlapPointDetail({ code: DEVICE_LAYER_POINT, name: '城南测试监测点' })
  752. }
  753. /**
  754. * 票 45:**K>10 降级样例** —— 11 台设备同坐标、状态混合(3 ALARM / 3 WARNING / 5 NORMAL)。
  755. * 设备编码与地图快照 `deviceCodes` 完全一致,全部坐标准入有效 ⇒ K=11 > maxFan(10) ⇒ 降级形态
  756. * 「K 台设备(本屏显示 10 台 / 其余见清单)」。聚合符号显示最高优先级状态(ALARM)。
  757. */
  758. /**
  759. * 票 76:**干净聚合实验样例**(维护者要求重建测试数据)——
  760. * 4 台设备同坐标、编码与快照 `deviceCodes` 一致、坐标同源;不降级(K=4 ≤ maxFan)。
  761. * 这是验证「聚合符号 / 展开 fan / 选中强调」的**唯一入口**(旧 `EQ-DG-*` 样例已按维护者裁定删除)。
  762. */
  763. if (scenario === 'aggregate-lab') {
  764. return degradedOverlapPointDetail({
  765. code: DEVICE_LAYER_POINT,
  766. name: '城南测试监测点',
  767. codes: AGGREGATE_LAB_CODES,
  768. coords: AGGREGATE_LAB_COORDS,
  769. statuses: ['ALARM', 'WARNING', 'NORMAL', 'NORMAL'],
  770. })
  771. }
  772. /**
  773. * 票 47:**设备状态动效样例** —— 五态各一台,验证「只有报警/预警/工单有动效、
  774. * 正常/离线完全静止」(决策票 07 的核心取舍)。全部设备坐标准入有效。
  775. */
  776. if (scenario === 'device-effects') {
  777. return effectsPointDetail({ code: DEVICE_LAYER_POINT, name: '城南测试监测点', samples: EFFECTS_SAMPLE, pointStatus: 'ALARM' })
  778. }
  779. /** 票 47:**动效降级样例** —— 31 台报警设备(> 默认上限 30)⇒ 动画全停 + 静态异常标记 + 计数。 */
  780. if (scenario === 'device-effects-degraded') {
  781. return effectsPointDetail({ code: DEVICE_LAYER_POINT, name: '城南测试监测点', samples: EFFECTS_DEGRADED_SAMPLE, pointStatus: 'ALARM' })
  782. }
  783. if (scenario === 'point-detail-order') {
  784. const devices = [
  785. { deviceCode: 'EQ-ORDER-NORMAL', deviceName: '顺序样例-正常设备', deviceTypeName: '压力计', deviceStatus: 'NORMAL', statusLabel: '正常', statusReasons: [], statusTime: '2026-09-02T09:59:30+08:00' },
  786. { deviceCode: 'EQ-ORDER-ALARM', deviceName: '顺序样例-报警设备', deviceTypeName: '流量计', deviceStatus: 'ALARM', statusLabel: '报警', statusReasons: ['流量超高'], statusTime: '2026-09-02T09:59:40+08:00' },
  787. { deviceCode: 'EQ-ORDER-WARNING', deviceName: '顺序样例-预警设备', deviceTypeName: '液位计', deviceStatus: 'WARNING', statusLabel: '预警', statusReasons: ['液位偏高'], statusTime: '2026-09-02T09:59:50+08:00' },
  788. ]
  789. return {
  790. ...pointDetail({ code: 'MP-ORDER', name: '顺序样例监测点', status: 'ALARM' }),
  791. devices,
  792. deviceStatistics: { totalDeviceCount: 3, alarmDeviceCount: 1, warningDeviceCount: 1, workOrderDeviceCount: 0, normalDeviceCount: 1, offlineDeviceCount: 0 },
  793. statusReasons: [{ status: 'ALARM', deviceCode: 'EQ-ORDER-ALARM', reason: '流量超高' }],
  794. }
  795. }
  796. /**
  797. * **主场景**(默认 `success`)按请求的点位编码分发两个重叠示例 ——
  798. * 维护者要求「进入系统即可见 K=2 与 K=11」,不必再注入场景:
  799. * · MP-001 城南测试监测点 —— K=2 正常重叠(两台设备同坐标,可逐台展开);
  800. * · MP-002 太常测试监测点 —— K=11 降级(本屏 10 台 / 其余见清单)。
  801. * 其余点位仍走默认现网边界(设备 `UNVERIFIED_COORDINATE/renderable=false`,不上图仅清单),
  802. * 那条边界是票 42 照抄的正式行为,不被示例覆盖。
  803. */
  804. if (scenario === 'success') {
  805. if (requestedCode === 'MP-001') {
  806. return overlapPointDetail({ code: 'MP-001', name: '城南测试监测点' })
  807. }
  808. if (requestedCode === 'MP-002') {
  809. // 主场景的 MP-002 是 ALARM 点位(示例用于展示降级聚合的最高优先级状态)。
  810. return degradedOverlapPointDetail({
  811. code: 'MP-002', name: '太常测试监测点',
  812. // 票 76(mock 串点修正):太常样例用**自己的编码**,不再与城南场景点共用 `EQ-DG-*`。
  813. codes: OVERLAP_TAICHANG_CODES,
  814. // 主场景仍是 K=11 同坐标样例,位置在太常点附近;五态沿用已验收的动效词表。
  815. coords: OVERLAP_TAICHANG_CODES.map(() => ({ longitude: 110.3632, latitude: 28.4524 })),
  816. statuses: ['ALARM', 'ALARM', 'ALARM', 'WARNING', 'WARNING', 'WARNING', 'WORK_ORDER', 'NORMAL', 'NORMAL', 'OFFLINE', 'NORMAL'],
  817. })
  818. }
  819. }
  820. return pointDetail()
  821. }
  822. /**
  823. * 设备级坐标字段(票 42)。`coords` 为 null ⇒ 现网降级(`UNVERIFIED_COORDINATE/renderable=false`),
  824. * 有值 ⇒ 受控测试样例(`VALID/renderable=true`)。两种都不复制监测点坐标。
  825. */
  826. function deviceCoordFields(coords, index) {
  827. if (!Array.isArray(coords) || !coords[index]) {
  828. return {
  829. coordinateValidation: { state: 'UNVERIFIED', reason: 'UNVERIFIED_COORDINATE', renderable: false, crs: 'WGS84' },
  830. }
  831. }
  832. const point = coords[index]
  833. return {
  834. longitude: point.longitude,
  835. latitude: point.latitude,
  836. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  837. }
  838. }
  839. function pointDetail({ code = 'MP-002', name = '太常测试监测点', status = 'ALARM', deviceCoord = null } = {}) {
  840. // 票 42:设备级坐标与校验。默认 `deviceCoord` 为 null ⇒ 逐台 `UNVERIFIED_COORDINATE/renderable=false`,
  841. // **照抄现网正式边界**(后端当前无可信校核源,真实设备统一不可上图)。
  842. // 只有显式传入受控坐标的样例场景才会 `renderable=true` —— 那是**测试样例**,
  843. // 不得用来冒称"正式关联设备已能上图"(票 42 验收第 2 条原句)。
  844. const devices = [
  845. {
  846. deviceCode: 'EQ-001',
  847. deviceName: '供水压力计-001',
  848. deviceTypeName: '压力计',
  849. deviceStatus: 'ALARM',
  850. statusLabel: '报警',
  851. statusReasons: ['压力超高'],
  852. statusTime: '2026-09-02T09:59:00+08:00',
  853. ...deviceCoordFields(deviceCoord, 0),
  854. },
  855. {
  856. deviceCode: 'EQ-002',
  857. deviceName: '智能窨井-002',
  858. deviceTypeName: '智能窨井',
  859. deviceStatus: 'NORMAL',
  860. statusLabel: '正常',
  861. statusReasons: [],
  862. statusTime: '2026-09-02T09:59:30+08:00',
  863. ...deviceCoordFields(deviceCoord, 1),
  864. },
  865. ]
  866. return {
  867. requestId: 'mock-point-detail',
  868. apiVersion: 'v1',
  869. readOnly: true,
  870. monitoringPointCode: code,
  871. monitoringPointName: name,
  872. pointStatus: status,
  873. statusLabel: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[status] || '',
  874. statusReasons: [{ status, deviceCode: 'EQ-001', reason: '压力超高' }],
  875. deviceStatistics: {
  876. totalDeviceCount: devices.length,
  877. alarmDeviceCount: 1,
  878. warningDeviceCount: 0,
  879. workOrderDeviceCount: 0,
  880. normalDeviceCount: 1,
  881. offlineDeviceCount: 0,
  882. },
  883. devices,
  884. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  885. statusDictionary: ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE', 'EMPTY'].map((item, index) => ({
  886. status: item,
  887. label: { ALARM: '报警', WARNING: '预警', WORK_ORDER: '工单处置', NORMAL: '正常', OFFLINE: '离线', EMPTY: '无设备' }[item],
  888. priority: index + 1,
  889. })),
  890. }
  891. }
  892. // ---------------------------------------------------------------- 设备详情聚合
  893. function aggregateSection(state, reason, data, message) {
  894. return { state, reason, message: message || null, data }
  895. }
  896. const ARCHIVE = {
  897. deviceCode: 'TC-PS-WS-202609020012',
  898. deviceName: '污水环境监测设备',
  899. deviceModel: 'WS-PRO-2000',
  900. deviceSpec: '悬浮物/COD/氨氮/电导率/PH',
  901. manufacturer: '沅陵专用仪表厂',
  902. deviceTypeName: '污水环境监测设备',
  903. assetValue: 128000,
  904. expectedServiceYears: 10,
  905. equipmentLocation: '太常片区',
  906. ownershipUnit: '沅陵县排水管理所',
  907. maintainer: '沅陵运维一组',
  908. maintainerPhone: '0745-0000000',
  909. installTime: '2024-03-01T00:00:00+08:00',
  910. latestImage: { url: '/cockpit/aerial.webp', capturedAt: '2026-08-30T10:20:00+08:00' },
  911. }
  912. const METRICS = {
  913. deviceCode: ARCHIVE.deviceCode,
  914. state: 'CURRENT',
  915. stateReason: 'READY',
  916. metrics: [
  917. { metricCode: 'COD', metricName: 'COD', value: 18.2, unit: 'mg/L', status: 'WARNING', sampledAt: '2026-09-02T09:59:30+08:00', freshness: 'CURRENT' },
  918. // 边界:真实 0 是有效读数,适配层不得当成缺失。
  919. { metricCode: 'FLOW', metricName: '流量', value: 0, unit: 'm³/h', status: 'NORMAL', sampledAt: '2026-09-02T09:59:30+08:00', freshness: 'CURRENT' },
  920. ],
  921. }
  922. const WARNING = { warningNo: 'WRN-20260902-001', warningName: '污水COD预警', warningType: 'WS_ENV', level: 2, levelColor: 'YELLOW', status: 'PROCESSING', eventTime: '2026-09-02T09:59:30+08:00', value: 18.2, unit: 'mg/L', deviceCode: ARCHIVE.deviceCode, deviceName: ARCHIVE.deviceName, location: '太常片区' }
  923. const ALARM = { alarmId: 'ALM-20260902-001', warningCode: 'WS_ENV_HIGH', warningName: '污水COD报警', warningType: 'WS_ENV', level: 1, levelColor: 'RED', status: 'UNHANDLED', eventTime: '2026-09-02T10:00:00+08:00', value: 42, thresholdMinValue: 40, thresholdMaxValue: 50, unit: 'mg/L', deviceCode: ARCHIVE.deviceCode, deviceName: ARCHIVE.deviceName, location: '太常片区' }
  924. const RELATION = { relationId: 'REL-001', warningNo: WARNING.warningNo, alarmId: ALARM.alarmId, relatedAt: '2026-09-02T10:00:00+08:00' }
  925. const WORK_ORDER = { associatedWithCurrentEvent: true, workOrderCode: 'WO-2026090200001', deviceCode: ARCHIVE.deviceCode, orderType: 1, orderTypeName: '故障维修', orderLevel: 2, orderDesc: '处理异常', stateCode: 3, stateName: '处理中', createTime: '2026-09-02T09:00:00+08:00', updateTime: '2026-09-02T10:00:00+08:00', planFinishTime: '2026-09-03T09:00:00+08:00', realFinishTime: null, eventAssociation: { eventSource: 'ALARM', eventCode: ALARM.alarmId, associatedAt: '2026-09-02T10:00:00+08:00' } }
  926. /**
  927. * 票 12:默认时间线走**完整一遍状态路径 + 一次回退**。
  928. *
  929. * 为什么要带回退而不是只给一条顺溜的轨迹:票 12 的验收原句就是
  930. * 「验收驳回表现为『待验收回退处理中』的动作轨迹」——样例里没有回退,这条验收在 mock 上
  931. * 根本无法演示(票 11 已经在「分区级失败」上踩过一次同样的坑)。
  932. * 末条 `stateCode: 3` 与 `WORK_ORDER.stateCode` 一致:当前态永远取工单自己的状态。
  933. *
  934. * ⚠️ **票 20:全部样例已按后端 `WorkOrderStatusEnum`(0–7)重排。**
  935. * 旧样例沿用 1–7,于是每条记录的码都比真实语义大一格(例如"待验收"标成 5、实际是 4)。
  936. * 现在:0待派单 / 1待接单 / 2已接单 / 3处理中 / 4待验收 / 5已结案 / 6延期中 / 7已取消。
  937. */
  938. const TIMELINE_ENTRIES = [
  939. { logId: 1, operationName: '创建工单', operationDesc: '故障维修', operatorName: '系统', operatedAt: '2026-09-02T09:00:00+08:00', stateCode: 0, stateName: '待派单' },
  940. { logId: 2, operationName: '派单', operationDesc: '指派沅陵运维一组', operatorName: '调度员', operatedAt: '2026-09-02T09:10:00+08:00', stateCode: 1, stateName: '待接单' },
  941. { logId: 3, operationName: '接单', operationDesc: '已接单', operatorName: '李四', operatedAt: '2026-09-02T09:20:00+08:00', stateCode: 2, stateName: '已接单' },
  942. { logId: 4, operationName: '开始处置', operationDesc: '现场处理', operatorName: '李四', operatedAt: '2026-09-02T09:40:00+08:00', stateCode: 3, stateName: '处理中' },
  943. { logId: 5, operationName: '提交验收', operationDesc: '申请验收', operatorName: '李四', operatedAt: '2026-09-02T11:30:00+08:00', stateCode: 4, stateName: '待验收' },
  944. // 回退动作:状态从 4 回到 3。它是**动作**,不是多出来的一个状态。
  945. { logId: 6, operationName: '验收驳回', operationDesc: '待验收回退处理中', operatorName: '张三', operatedAt: '2026-09-02T12:00:00+08:00', stateCode: 3, stateName: '处理中' },
  946. ]
  947. const TIMELINE = { workOrder: { ...WORK_ORDER }, timelineEntries: TIMELINE_ENTRIES }
  948. /**
  949. * 票 12 的专用场景:**同设备多张工单、每张一条独立时间线**(验收第 2 条)。
  950. * 四张刻意选在四个不同形状上:
  951. * · `WO-TL-FORWARD` 停在待验收(一路推进,走到过 4);
  952. * · `WO-TL-ROLLBACK` 当前处理中、但走到过待验收(回退动作 —— 本票的核心形态);
  953. * · `WO-TL-DELAYED` 延期中(**处理旁路**,票 20 新增:6 不在推进主线上);
  954. * · `WO-TL-CANCELLED` 已取消(**路径外**终态,不能接在已结案后面冒充下一步)。
  955. */
  956. const TIMELINE_ORDERS = [
  957. { workOrderCode: 'WO-TL-FORWARD', deviceCode: ARCHIVE.deviceCode, orderType: 1, orderTypeName: '故障维修', orderLevel: 2, orderDesc: '水泵异响处置', stateCode: 4, stateName: '待验收', createTime: '2026-09-01T08:00:00+08:00', updateTime: '2026-09-01T12:00:00+08:00', planFinishTime: '2026-09-02T08:00:00+08:00', realFinishTime: null, eventAssociation: { eventSource: 'ALARM', eventCode: ALARM.alarmId, associatedAt: '2026-09-01T08:05:00+08:00' } },
  958. { workOrderCode: 'WO-TL-ROLLBACK', deviceCode: ARCHIVE.deviceCode, orderType: 1, orderTypeName: '故障维修', orderLevel: 2, orderDesc: 'COD 探头校验', stateCode: 3, stateName: '处理中', createTime: '2026-09-02T09:00:00+08:00', updateTime: '2026-09-02T12:00:00+08:00', planFinishTime: '2026-09-03T09:00:00+08:00', realFinishTime: null, eventAssociation: { eventSource: 'ALARM', eventCode: ALARM.alarmId, associatedAt: '2026-09-02T09:00:00+08:00' } },
  959. { workOrderCode: 'WO-TL-DELAYED', deviceCode: ARCHIVE.deviceCode, orderType: 1, orderTypeName: '故障维修', orderLevel: 2, orderDesc: '闸阀更换(等备件)', stateCode: 6, stateName: '延期中', createTime: '2026-09-03T08:00:00+08:00', updateTime: '2026-09-03T10:00:00+08:00', planFinishTime: '2026-09-10T08:00:00+08:00', realFinishTime: null, eventAssociation: null },
  960. { workOrderCode: 'WO-TL-CANCELLED', deviceCode: ARCHIVE.deviceCode, orderType: 2, orderTypeName: '计划检修', orderLevel: 3, orderDesc: '重复报单,取消', stateCode: 7, stateName: '已取消', createTime: '2026-09-02T07:00:00+08:00', updateTime: '2026-09-02T07:30:00+08:00', planFinishTime: null, realFinishTime: null, eventAssociation: null },
  961. ]
  962. const TIMELINE_BY_CODE = {
  963. 'WO-TL-FORWARD': [
  964. { logId: 11, operationName: '创建工单', operationDesc: '故障维修', operatorName: '系统', operatedAt: '2026-09-01T08:00:00+08:00', stateCode: 0, stateName: '待派单' },
  965. { logId: 12, operationName: '派单', operationDesc: '指派沅陵运维二组', operatorName: '调度员', operatedAt: '2026-09-01T08:15:00+08:00', stateCode: 1, stateName: '待接单' },
  966. { logId: 13, operationName: '接单', operationDesc: '已接单', operatorName: '王五', operatedAt: '2026-09-01T08:30:00+08:00', stateCode: 2, stateName: '已接单' },
  967. { logId: 14, operationName: '开始处置', operationDesc: '现场处理', operatorName: '王五', operatedAt: '2026-09-01T09:00:00+08:00', stateCode: 3, stateName: '处理中' },
  968. { logId: 15, operationName: '提交验收', operationDesc: '申请验收', operatorName: '王五', operatedAt: '2026-09-01T12:00:00+08:00', stateCode: 4, stateName: '待验收' },
  969. ],
  970. 'WO-TL-ROLLBACK': [
  971. { logId: 21, operationName: '创建工单', operationDesc: '故障维修', operatorName: '系统', operatedAt: '2026-09-02T09:00:00+08:00', stateCode: 0, stateName: '待派单' },
  972. { logId: 22, operationName: '派单', operationDesc: '指派沅陵运维一组', operatorName: '调度员', operatedAt: '2026-09-02T09:05:00+08:00', stateCode: 1, stateName: '待接单' },
  973. { logId: 23, operationName: '接单', operationDesc: '已接单', operatorName: '李四', operatedAt: '2026-09-02T09:10:00+08:00', stateCode: 2, stateName: '已接单' },
  974. { logId: 24, operationName: '开始处置', operationDesc: '现场处理', operatorName: '李四', operatedAt: '2026-09-02T09:30:00+08:00', stateCode: 3, stateName: '处理中' },
  975. { logId: 25, operationName: '提交验收', operationDesc: '申请验收', operatorName: '李四', operatedAt: '2026-09-02T11:00:00+08:00', stateCode: 4, stateName: '待验收' },
  976. { logId: 26, operationName: '验收驳回', operationDesc: '待验收回退处理中', operatorName: '张三', operatedAt: '2026-09-02T12:00:00+08:00', stateCode: 3, stateName: '处理中' },
  977. ],
  978. // 票 20 新增:延期审批通过 → 进入 6 延期中(**旁路**),之后再回到 3 处理中。
  979. // 这条样例是 `BYPASS` 动作的演示依据 —— 没有它,"延期中是旁路不是主线"就只写在注释里。
  980. 'WO-TL-DELAYED': [
  981. { logId: 41, operationName: '创建工单', operationDesc: '故障维修', operatorName: '系统', operatedAt: '2026-09-03T08:00:00+08:00', stateCode: 0, stateName: '待派单' },
  982. { logId: 42, operationName: '派单', operationDesc: '指派沅陵运维一组', operatorName: '调度员', operatedAt: '2026-09-03T08:10:00+08:00', stateCode: 1, stateName: '待接单' },
  983. { logId: 43, operationName: '接单', operationDesc: '已接单', operatorName: '李四', operatedAt: '2026-09-03T08:20:00+08:00', stateCode: 2, stateName: '已接单' },
  984. { logId: 44, operationName: '开始处置', operationDesc: '现场处理', operatorName: '李四', operatedAt: '2026-09-03T08:30:00+08:00', stateCode: 3, stateName: '处理中' },
  985. { logId: 45, operationName: '申请延期', operationDesc: '等待备件到货', operatorName: '李四', operatedAt: '2026-09-03T09:00:00+08:00', stateCode: 3, stateName: '处理中' },
  986. { logId: 46, operationName: '延期通过', operationDesc: '备件周期确认', operatorName: '张三', operatedAt: '2026-09-03T10:00:00+08:00', stateCode: 6, stateName: '延期中' },
  987. ],
  988. 'WO-TL-CANCELLED': [
  989. { logId: 31, operationName: '创建工单', operationDesc: '计划检修', operatorName: '系统', operatedAt: '2026-09-02T07:00:00+08:00', stateCode: 0, stateName: '待派单' },
  990. { logId: 32, operationName: '派单', operationDesc: '指派沅陵运维三组', operatorName: '调度员', operatedAt: '2026-09-02T07:10:00+08:00', stateCode: 1, stateName: '待接单' },
  991. { logId: 33, operationName: '取消工单', operationDesc: '重复报单', operatorName: '调度员', operatedAt: '2026-09-02T07:30:00+08:00', stateCode: 7, stateName: '已取消' },
  992. ],
  993. }
  994. function equipmentAggregate(scenario, deviceCode = '') {
  995. const success = aggregateSection('SUCCESS', 'SUCCESS', null)
  996. // 请求哪台设备就报哪台(与真接口一致,客户端传错编码能看出来)。
  997. const code = deviceCode || ARCHIVE.deviceCode
  998. const archive = { ...ARCHIVE, deviceCode: code }
  999. if (scenario === 'empty') {
  1000. return {
  1001. deviceCode: code,
  1002. aggregateState: 'EMPTY',
  1003. serverTime: SNAPSHOT_AT,
  1004. archive: aggregateSection('EMPTY', 'NO_ARCHIVE', null),
  1005. metrics: aggregateSection('EMPTY', 'NO_METRICS', null),
  1006. warnings: aggregateSection('EMPTY', 'NO_EVENTS', null),
  1007. alarms: aggregateSection('EMPTY', 'NO_EVENTS', null),
  1008. alarmWarningRelations: aggregateSection('EMPTY', 'NO_EVENTS', null),
  1009. workOrders: aggregateSection('EMPTY', 'NO_WORK_ORDERS', null),
  1010. timelines: aggregateSection('EMPTY', 'NO_WORK_ORDERS', null),
  1011. latestImage: aggregateSection('EMPTY', 'NO_IMAGE', null),
  1012. }
  1013. }
  1014. if (scenario === 'degraded') {
  1015. // 字段缺失:档案只剩编码,指标缺 value/unit,工单缺 stateName(靠状态字典补)。
  1016. return {
  1017. deviceCode: code,
  1018. aggregateState: 'READY',
  1019. serverTime: SNAPSHOT_AT,
  1020. archive: aggregateSection('SUCCESS', 'SUCCESS', { deviceCode: code }),
  1021. metrics: aggregateSection('SUCCESS', 'SUCCESS', { deviceCode: code, state: 'CURRENT', stateReason: 'READY', metrics: [{ metricCode: 'COD', metricName: 'COD', sampledAt: '2026-09-02T09:59:30+08:00' }] }),
  1022. warnings: aggregateSection('SUCCESS', 'SUCCESS', [WARNING]),
  1023. alarms: aggregateSection('SUCCESS', 'SUCCESS', [ALARM]),
  1024. alarmWarningRelations: aggregateSection('SUCCESS', 'SUCCESS', [RELATION]),
  1025. workOrders: aggregateSection('SUCCESS', 'SUCCESS', [{ workOrderCode: 'WO-DEGRADED', stateCode: 2 }]),
  1026. timelines: aggregateSection('SUCCESS', 'SUCCESS', [TIMELINE]),
  1027. latestImage: aggregateSection('EMPTY', 'NO_IMAGE', null),
  1028. }
  1029. }
  1030. if (scenario === 'stale') {
  1031. return {
  1032. deviceCode: code,
  1033. aggregateState: 'PARTIAL',
  1034. serverTime: SNAPSHOT_AT,
  1035. archive: aggregateSection('SUCCESS', 'SUCCESS', archive),
  1036. // 过期但保留旧值(票 16:保留最后已知值 + 过期标识)。
  1037. metrics: aggregateSection('STALE', 'SAMPLE_OUTDATED', { ...METRICS, state: 'STALE', stateReason: 'SAMPLE_OUTDATED' }),
  1038. warnings: aggregateSection('SUCCESS', 'SUCCESS', [WARNING]),
  1039. alarms: aggregateSection('SUCCESS', 'SUCCESS', [ALARM]),
  1040. alarmWarningRelations: aggregateSection('SUCCESS', 'SUCCESS', [RELATION]),
  1041. workOrders: aggregateSection('SUCCESS', 'SUCCESS', [WORK_ORDER]),
  1042. timelines: aggregateSection('SUCCESS', 'SUCCESS', [TIMELINE]),
  1043. latestImage: aggregateSection('SUCCESS', 'SUCCESS', archive.latestImage),
  1044. }
  1045. }
  1046. if (scenario === 'equipment-partial') {
  1047. // 票 11 验收第 3 条:任一分区失败不遮盖其它成功分区。
  1048. //
  1049. // 为什么要一个**独立场景名**而不是复用 `failed`:`failed` 在注册层就抛错
  1050. // (整个端点读不到,`data` 为 null),那是"这份详情根本没取到",
  1051. // 与"取到了、只是其中三块分区各自失败"是两件事。后端契约会把后者原样返回
  1052. // (`aggregateState: PARTIAL` + 每分区自带 state/reason/message),
  1053. // 所以必须有一个能真正走通的样例,否则这条验收在 mock 上无法演示。
  1054. return {
  1055. deviceCode: code,
  1056. aggregateState: 'PARTIAL',
  1057. serverTime: SNAPSHOT_AT,
  1058. archive: aggregateSection('FAILED', 'READ_FAILURE', null, '设备档案数据暂不可用'),
  1059. metrics: aggregateSection('SUCCESS', 'SUCCESS', METRICS),
  1060. warnings: aggregateSection('SUCCESS', 'SUCCESS', [WARNING]),
  1061. alarms: aggregateSection('SUCCESS', 'SUCCESS', [ALARM]),
  1062. alarmWarningRelations: aggregateSection('SUCCESS', 'SUCCESS', [RELATION]),
  1063. workOrders: aggregateSection('FAILED', 'READ_FAILURE', null, '工单数据暂不可用'),
  1064. timelines: aggregateSection('FAILED', 'SOURCE_SECTION_FAILED', null, '工单分区失败,时间线不可用'),
  1065. latestImage: aggregateSection('FAILED', 'SOURCE_SECTION_FAILED', null, '设备档案失败,图片不可用'),
  1066. }
  1067. }
  1068. if (scenario === 'work-order-timeline') {
  1069. // 票 12 的专用样例:三张工单、各一条独立时间线(推进 / 回退 / 取消三种形状都齐)。
  1070. // 与 `equipment-partial` 一样,它必须是一个**能真正走通**的独立场景 ——
  1071. // 挂在别的分支下就永远演示不到,那等于这条验收没有样例。
  1072. return {
  1073. deviceCode: code,
  1074. aggregateState: 'READY',
  1075. serverTime: SNAPSHOT_AT,
  1076. archive: { ...success, data: archive },
  1077. metrics: { ...success, data: METRICS },
  1078. warnings: { ...success, data: [WARNING] },
  1079. alarms: { ...success, data: [ALARM] },
  1080. alarmWarningRelations: { ...success, data: [RELATION] },
  1081. workOrders: { ...success, data: TIMELINE_ORDERS },
  1082. timelines: {
  1083. ...success,
  1084. data: TIMELINE_ORDERS.map((order) => ({ workOrder: { ...order }, timelineEntries: TIMELINE_BY_CODE[order.workOrderCode] })),
  1085. },
  1086. latestImage: { ...success, data: archive.latestImage },
  1087. }
  1088. }
  1089. if (scenario === 'work-order-timeline-failed') {
  1090. // 票 12 的**分区独立**样例:工单列表照常成功,只有时间线分区失败
  1091. // (后端 `loadTimelines()` 在工单读得到、时间线读不到时正是这个形状:
  1092. // `SOURCE_SECTION_FAILED` + 工单列表 SUCCESS)。界面必须说「轨迹没取到」,
  1093. // 而不是把缺数据画成「这张工单没有动作记录」—— 那是把"没拿到"说成"没有"。
  1094. return {
  1095. deviceCode: code,
  1096. aggregateState: 'PARTIAL',
  1097. serverTime: SNAPSHOT_AT,
  1098. archive: { ...success, data: archive },
  1099. metrics: { ...success, data: METRICS },
  1100. warnings: { ...success, data: [WARNING] },
  1101. alarms: { ...success, data: [ALARM] },
  1102. alarmWarningRelations: { ...success, data: [RELATION] },
  1103. workOrders: { ...success, data: [WORK_ORDER] },
  1104. timelines: aggregateSection('FAILED', 'SOURCE_SECTION_FAILED', null, '工单分区失败,时间线不可用'),
  1105. latestImage: { ...success, data: archive.latestImage },
  1106. }
  1107. }
  1108. return {
  1109. deviceCode: code,
  1110. aggregateState: 'READY',
  1111. serverTime: SNAPSHOT_AT,
  1112. archive: { ...success, data: archive },
  1113. metrics: { ...success, data: METRICS },
  1114. warnings: { ...success, data: [WARNING] },
  1115. alarms: { ...success, data: [ALARM] },
  1116. alarmWarningRelations: { ...success, data: [RELATION] },
  1117. workOrders: { ...success, data: [{ ...WORK_ORDER, associatedWithCurrentEvent: true }, { ...WORK_ORDER, workOrderCode: 'WO-UNLINKED', associatedWithCurrentEvent: false, eventAssociation: null }] },
  1118. timelines: { ...success, data: [TIMELINE] },
  1119. latestImage: { ...success, data: archive.latestImage },
  1120. }
  1121. }
  1122. /**
  1123. * 采集记录样例(票 115 / #114 契约):用 `recordView.columns/rows` 驱动表格。
  1124. * create_time 故意给 ISO 串,界面应统一格式成 `yyyy-mm-dd hh:mm:ss`;
  1125. * 相邻两行同 createTime 用来验证 td 合并。
  1126. */
  1127. function collectionRecordsPayload(scenario, deviceCode = '') {
  1128. const code = deviceCode || ARCHIVE.deviceCode
  1129. if (scenario === 'empty') {
  1130. return {
  1131. requestId: 'mock-collection-records',
  1132. apiVersion: 'v1',
  1133. readOnly: true,
  1134. deviceCode: code,
  1135. state: 'EMPTY',
  1136. stateReason: 'NO_RECORDS',
  1137. recordView: { layout: 'wide', columns: [], rows: [] },
  1138. }
  1139. }
  1140. const columns = [
  1141. { key: 'create_time', label: '数据时间', unit: null },
  1142. { key: 'COD', label: '化学需氧量(COD)', unit: 'mg/L' },
  1143. { key: 'PH', label: '酸碱度(pH)', unit: null },
  1144. { key: 'TEMPERATURE', label: '温度', unit: '℃' },
  1145. { key: 'filepath', label: '音频记录', unit: null },
  1146. ]
  1147. const row = (createTime, cod, ph, temperature) => ({
  1148. createTime,
  1149. cells: [
  1150. { key: 'create_time', value: createTime },
  1151. { key: 'COD', value: cod },
  1152. { key: 'PH', value: ph },
  1153. { key: 'TEMPERATURE', value: temperature },
  1154. { key: 'filepath', value: null },
  1155. ],
  1156. })
  1157. return {
  1158. requestId: 'mock-collection-records',
  1159. apiVersion: 'v1',
  1160. readOnly: true,
  1161. deviceCode: code,
  1162. state: 'READY',
  1163. stateReason: 'READY',
  1164. recordView: {
  1165. layout: 'wide',
  1166. columns,
  1167. rows: [
  1168. row('2026-09-02T09:59:30+08:00', 0, 7.2, 22.2),
  1169. row('2026-09-02T09:59:30+08:00', 1.5, 7.1, 21.8),
  1170. row('2026-09-02T09:58:30+08:00', 2.5, 7.0, 21.5),
  1171. ],
  1172. },
  1173. }
  1174. }
  1175. // ---------------------------------------------------------------- 事件与工单
  1176. // ---------------------------------------------------------------- 跨设备当前事件(票 13)
  1177. /**
  1178. * 票 13:跨设备 `/events/current` 的契约化样例(`CockpitCurrentEventsResponse`)。
  1179. *
  1180. * 字段名与嵌套形状照抄后端响应类(`CockpitCurrentEventsResponse` +
  1181. * `CockpitCurrentEventsService`),所以适配层单测证明的是「转换吃得下真载荷」。
  1182. *
  1183. * 五处刻意照抄真实形状的**坑**:
  1184. * 1. **`mode` 必填并校验**(WARNING|ALARM,认不出的值 400)—— mock 收到非法 mode
  1185. * 抛错,逼调用方永远带上合法 mode;
  1186. * 2. **预警与报警永不混合**:`mode` 决定取哪一族,两块样例数据刻意不同,
  1187. * 切换后列表必须真的换内容(否则「预警/报警可切换」是假绿);
  1188. * 3. **`levelColor` 由后端按 level 解析**(`CockpitEventLevelColor`:1→RED …
  1189. * 4→GREEN,认不出→UNKNOWN),mock 照抄同一个映射;
  1190. * 4. **排序**:eventTime 倒序、同时间按 eventNo 升序(`eventOrdering()`),
  1191. * 服务端分页的页序靠它成立(票 61:每页 10 条,翻页由 `page`/`pageSize` 真切片);
  1192. * 5. **内部分区**:`sections.events` 是 `CockpitSectionResult`(空时
  1193. * `{state: EMPTY, reason: NO_EVENTS}`),工单分区独立(样例给空);
  1194. * 顶层不算空 —— 与设备详情聚合同一模式。
  1195. *
  1196. * 样例规模刻意大于一页:预警和报警各 14 条,让 `pageSize=10` 的服务端分页
  1197. * 在 mock 上真能演示第二页(票 61;此前是「仅展示最新 12 条」帽的演示数据)。
  1198. */
  1199. /** mock 里事件等级 → 颜色(照抄后端 `CockpitEventLevelColor.resolve`)。 */
  1200. function eventLevelColorOf(level) {
  1201. if (level === 1) return 'RED'
  1202. if (level === 2) return 'YELLOW'
  1203. if (level === 3) return 'BLUE'
  1204. if (level === 4) return 'GREEN'
  1205. return 'UNKNOWN'
  1206. }
  1207. /** 一条预警样例(字段照抄 `EventItem`;警报/工单摘要按族给)。 */
  1208. function eventItem({ no, name, type, level, status, eventTime, updatedTime, value, unit, deviceCode, deviceName, monitoringPointCode, monitoringPointName, location, industry, min = null, max = null }) {
  1209. return {
  1210. eventNo: no,
  1211. eventName: name,
  1212. eventType: type,
  1213. level,
  1214. levelColor: eventLevelColorOf(level),
  1215. status,
  1216. eventTime,
  1217. updatedTime,
  1218. value,
  1219. unit,
  1220. deviceCode,
  1221. deviceName,
  1222. monitoringPointCode,
  1223. monitoringPointName,
  1224. location,
  1225. industry,
  1226. longitude: 110.14,
  1227. latitude: 28.45,
  1228. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  1229. thresholdMinValue: min,
  1230. thresholdMaxValue: max,
  1231. workOrderSummary: { workOrderCode: `WO-${no}`, stateCode: level === 1 ? 3 : 2, stateName: level === 1 ? '处理中' : '已接单' },
  1232. }
  1233. }
  1234. /** 预警样例(14 条,等级 1-4 都覆盖;状态用后端契约测试见过的取值)。 */
  1235. const CURRENT_WARNINGS = [
  1236. eventItem({ no: 'WRN-1001', name: '燃气浓度预警', type: 'GAS_CONCENTRATION', level: 1, status: 'ACTIVE', eventTime: '2026-09-02T10:00:00+08:00', updatedTime: '2026-09-02T10:00:00+08:00', value: 0.9, unit: '%LEL', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS' }),
  1237. eventItem({ no: 'WRN-1002', name: '供水压力预警', type: 'WATER_PRESSURE', level: 2, status: 'PENDING', eventTime: '2026-09-02T09:55:00+08:00', updatedTime: '2026-09-02T09:55:00+08:00', value: 0.28, unit: 'MPa', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY' }),
  1238. eventItem({ no: 'WRN-1003', name: '污水 COD 预警', type: 'SEWAGE_CONCENTRATION', level: 3, status: 'PROCESSING', eventTime: '2026-09-02T09:50:00+08:00', updatedTime: '2026-09-02T09:52:00+08:00', value: 18.2, unit: 'mg/L', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE' }),
  1239. eventItem({ no: 'WRN-1004', name: '排水水位预警', type: 'DRAINAGE_LEVEL', level: 4, status: 'ACTIVE', eventTime: '2026-09-02T09:45:00+08:00', updatedTime: '2026-09-02T09:45:00+08:00', value: 1.6, unit: 'm', deviceCode: 'EQ-004', deviceName: '排水泵站设备', monitoringPointCode: 'MP-004', monitoringPointName: '排水泵站监测点', location: '城区C', industry: 'DRAINAGE' }),
  1240. eventItem({ no: 'WRN-1005', name: '燃气浓度预警', type: 'GAS_CONCENTRATION', level: 2, status: 'PENDING', eventTime: '2026-09-02T09:40:00+08:00', updatedTime: '2026-09-02T09:40:00+08:00', value: 0.72, unit: '%LEL', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS' }),
  1241. eventItem({ no: 'WRN-1006', name: '供水流量预警', type: 'WATER_FLOW', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T09:30:00+08:00', updatedTime: '2026-09-02T09:30:00+08:00', value: 880, unit: 'm³/h', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY' }),
  1242. eventItem({ no: 'WRN-1007', name: '污水 PH 预警', type: 'SEWAGE_PH', level: 4, status: 'PROCESSING', eventTime: '2026-09-02T09:20:00+08:00', updatedTime: '2026-09-02T09:21:00+08:00', value: 8.9, unit: '', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE' }),
  1243. eventItem({ no: 'WRN-1008', name: '燃气压力预警', type: 'GAS_PRESSURE', level: 1, status: 'ACTIVE', eventTime: '2026-09-02T09:10:00+08:00', updatedTime: '2026-09-02T09:10:00+08:00', value: 0.31, unit: 'MPa', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS' }),
  1244. eventItem({ no: 'WRN-1009', name: '供水余氯预警', type: 'WATER_CHLORINE', level: 2, status: 'PENDING', eventTime: '2026-09-02T09:00:00+08:00', updatedTime: '2026-09-02T09:00:00+08:00', value: 0.12, unit: 'mg/L', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY' }),
  1245. eventItem({ no: 'WRN-1010', name: '污水氨氮预警', type: 'SEWAGE_NH3', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T08:50:00+08:00', updatedTime: '2026-09-02T08:50:00+08:00', value: 6.4, unit: 'mg/L', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE' }),
  1246. eventItem({ no: 'WRN-1011', name: '排水流量预警', type: 'DRAINAGE_FLOW', level: 4, status: 'PROCESSING', eventTime: '2026-09-02T08:40:00+08:00', updatedTime: '2026-09-02T08:41:00+08:00', value: 420, unit: 'm³/h', deviceCode: 'EQ-004', deviceName: '排水泵站设备', monitoringPointCode: 'MP-004', monitoringPointName: '排水泵站监测点', location: '城区C', industry: 'DRAINAGE' }),
  1247. eventItem({ no: 'WRN-1012', name: '燃气浓度预警', type: 'GAS_CONCENTRATION', level: 1, status: 'PENDING', eventTime: '2026-09-02T08:30:00+08:00', updatedTime: '2026-09-02T08:30:00+08:00', value: 0.85, unit: '%LEL', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS' }),
  1248. eventItem({ no: 'WRN-1013', name: '供水浊度预警', type: 'WATER_TURBIDITY', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T08:20:00+08:00', updatedTime: '2026-09-02T08:20:00+08:00', value: 3.1, unit: 'NTU', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY' }),
  1249. eventItem({ no: 'WRN-1014', name: '污水温度预警', type: 'SEWAGE_TEMP', level: 4, status: 'ACTIVE', eventTime: '2026-09-02T08:10:00+08:00', updatedTime: '2026-09-02T08:10:00+08:00', value: 33, unit: '℃', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE' }),
  1250. ]
  1251. /** 报警样例(14 条,带阈值;状态用后端契约测试见过的取值)。 */
  1252. const CURRENT_ALARMS = [
  1253. eventItem({ no: 'ALM-2001', name: '燃气浓度报警', type: 'GAS_CONCENTRATION', level: 1, status: 'ACTIVE', eventTime: '2026-09-02T10:00:00+08:00', updatedTime: '2026-09-02T10:00:00+08:00', value: 2.4, unit: '%LEL', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS', min: 1.5, max: 2.5 }),
  1254. eventItem({ no: 'ALM-2002', name: '供水压力报警', type: 'WATER_PRESSURE', level: 2, status: 'PROCESSING', eventTime: '2026-09-02T09:55:00+08:00', updatedTime: '2026-09-02T09:55:00+08:00', value: 0.18, unit: 'MPa', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY', min: 0.2, max: null }),
  1255. eventItem({ no: 'ALM-2003', name: '污水 COD 报警', type: 'SEWAGE_CONCENTRATION', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T09:50:00+08:00', updatedTime: '2026-09-02T09:50:00+08:00', value: 42, unit: 'mg/L', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE', min: 40, max: 50 }),
  1256. eventItem({ no: 'ALM-2004', name: '排水水位报警', type: 'DRAINAGE_LEVEL', level: 4, status: 'PENDING', eventTime: '2026-09-02T09:45:00+08:00', updatedTime: '2026-09-02T09:45:00+08:00', value: 2.8, unit: 'm', deviceCode: 'EQ-004', deviceName: '排水泵站设备', monitoringPointCode: 'MP-004', monitoringPointName: '排水泵站监测点', location: '城区C', industry: 'DRAINAGE', min: 2.5, max: null }),
  1257. eventItem({ no: 'ALM-2005', name: '燃气压力报警', type: 'GAS_PRESSURE', level: 1, status: 'PROCESSING', eventTime: '2026-09-02T09:40:00+08:00', updatedTime: '2026-09-02T09:42:00+08:00', value: 0.1, unit: 'MPa', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS', min: 0.15, max: null }),
  1258. eventItem({ no: 'ALM-2006', name: '供水流量报警', type: 'WATER_FLOW', level: 2, status: 'ACTIVE', eventTime: '2026-09-02T09:30:00+08:00', updatedTime: '2026-09-02T09:30:00+08:00', value: 1200, unit: 'm³/h', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY', min: null, max: 1000 }),
  1259. eventItem({ no: 'ALM-2007', name: '污水 PH 报警', type: 'SEWAGE_PH', level: 3, status: 'PROCESSING', eventTime: '2026-09-02T09:20:00+08:00', updatedTime: '2026-09-02T09:21:00+08:00', value: 9.6, unit: '', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE', min: 6, max: 9 }),
  1260. eventItem({ no: 'ALM-2008', name: '燃气浓度报警', type: 'GAS_CONCENTRATION', level: 1, status: 'ACTIVE', eventTime: '2026-09-02T09:10:00+08:00', updatedTime: '2026-09-02T09:10:00+08:00', value: 3.1, unit: '%LEL', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS', min: 2.5, max: null }),
  1261. eventItem({ no: 'ALM-2009', name: '供水余氯报警', type: 'WATER_CHLORINE', level: 2, status: 'PENDING', eventTime: '2026-09-02T09:00:00+08:00', updatedTime: '2026-09-02T09:00:00+08:00', value: 0.05, unit: 'mg/L', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY', min: 0.1, max: null }),
  1262. eventItem({ no: 'ALM-2010', name: '污水氨氮报警', type: 'SEWAGE_NH3', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T08:50:00+08:00', updatedTime: '2026-09-02T08:50:00+08:00', value: 12, unit: 'mg/L', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE', min: 8, max: null }),
  1263. eventItem({ no: 'ALM-2011', name: '排水流量报警', type: 'DRAINAGE_FLOW', level: 4, status: 'PROCESSING', eventTime: '2026-09-02T08:40:00+08:00', updatedTime: '2026-09-02T08:41:00+08:00', value: 660, unit: 'm³/h', deviceCode: 'EQ-004', deviceName: '排水泵站设备', monitoringPointCode: 'MP-004', monitoringPointName: '排水泵站监测点', location: '城区C', industry: 'DRAINAGE', min: null, max: 600 }),
  1264. eventItem({ no: 'ALM-2012', name: '燃气压力报警', type: 'GAS_PRESSURE', level: 1, status: 'PENDING', eventTime: '2026-09-02T08:30:00+08:00', updatedTime: '2026-09-02T08:30:00+08:00', value: 0.08, unit: 'MPa', deviceCode: 'EQ-002', deviceName: '燃气调压站设备', monitoringPointCode: 'MP-002', monitoringPointName: '太常测试监测点', location: '城区A', industry: 'GAS', min: 0.12, max: null }),
  1265. eventItem({ no: 'ALM-2013', name: '供水浊度报警', type: 'WATER_TURBIDITY', level: 3, status: 'ACTIVE', eventTime: '2026-09-02T08:20:00+08:00', updatedTime: '2026-09-02T08:20:00+08:00', value: 5.2, unit: 'NTU', deviceCode: 'EQ-001', deviceName: '供水压力计-001', monitoringPointCode: 'MP-001', monitoringPointName: '城南测试监测点', location: '城区B', industry: 'WATER_SUPPLY', min: null, max: 4 }),
  1266. eventItem({ no: 'ALM-2014', name: '污水温度报警', type: 'SEWAGE_TEMP', level: 4, status: 'ACTIVE', eventTime: '2026-09-02T08:10:00+08:00', updatedTime: '2026-09-02T08:10:00+08:00', value: 36, unit: '℃', deviceCode: 'EQ-003', deviceName: '污水环境监测设备', monitoringPointCode: 'MP-003', monitoringPointName: '污水排口监测点', location: '太常片区', industry: 'DRAINAGE', min: null, max: 35 }),
  1267. ]
  1268. /**
  1269. * 按后端语义过滤 + 排序 + 分页(照抄 `CockpitCurrentEventsService` 的
  1270. * `warningRows/alarmRows`、`eventOrdering()` 与分页切片)。
  1271. * @param {string} mode WARNING / ALARM
  1272. * @param {object} query URLSearchParams 解析出的请求查询串
  1273. */
  1274. function currentEventsPayload(scenario, query) {
  1275. const mode = (query && query.mode) || 'WARNING'
  1276. if (mode !== 'WARNING' && mode !== 'ALARM') {
  1277. // 与后端一致:mode 必填且只认两个取值(认不出的 400)。
  1278. // 不声明自定义 reason:非白名单的原因会被统一出口收敛成「不可用」,
  1279. // 而「调用方传了非法 mode」本来就是编程错误、不是可展示的业务态。
  1280. throw new Error('mock: mode must be WARNING or ALARM')
  1281. }
  1282. const source = mode === 'ALARM' ? CURRENT_ALARMS : CURRENT_WARNINGS
  1283. // 空样例:事件分区 EMPTY(`CockpitSectionResult.empty("NO_EVENTS")`),工单分区也空。
  1284. if (scenario === 'empty') {
  1285. return currentEventsEnvelope(mode, [], query, { state: 'EMPTY', reason: 'NO_EVENTS', message: null, data: null })
  1286. }
  1287. // 坐标不可上图样例(票 14 验收第 5 条的真机版):事件数据照常给全,
  1288. // 但**后端判定**坐标不可上图 —— 详情仍然完整可看,只是「位置」一栏给原因、定位点不动。
  1289. // 判据只改 `coordinateValidation`(与后端 `CockpitCoordinateValidator` 同形):
  1290. // 前端只消费结论,所以这里改结论就能复现"无地图位置"的整条路径。
  1291. if (scenario === 'event-detail-no-coordinate') {
  1292. const relocated = source.map((item) => ({
  1293. ...item,
  1294. longitude: null,
  1295. latitude: null,
  1296. coordinateValidation: { state: 'UNVERIFIED', reason: 'UNVERIFIED_COORDINATE', renderable: false, crs: 'WGS84' },
  1297. }))
  1298. return currentEventsEnvelope(mode, relocated.slice(0, 12), query, {
  1299. state: 'SUCCESS',
  1300. reason: 'SUCCESS',
  1301. message: null,
  1302. data: relocated.slice(0, 12),
  1303. pagination: { page: 1, pageSize: 100, total: relocated.length, totalPages: 1, hasMore: false },
  1304. deviceCodes: [...new Set(relocated.map((item) => item.deviceCode).filter(Boolean))].sort(),
  1305. })
  1306. }
  1307. // 字段缺失样例:事件行只给编码/名称/等级,其余字段缺失(适配层要记 missing)。
  1308. if (scenario === 'degraded') {
  1309. const degraded = source.slice(0, 3).map((item) => ({
  1310. eventNo: item.eventNo,
  1311. eventName: item.eventName,
  1312. level: item.level,
  1313. status: item.status,
  1314. eventTime: item.eventTime,
  1315. }))
  1316. return currentEventsEnvelope(mode, degraded, query, { state: 'SUCCESS', reason: 'SUCCESS', message: null, data: degraded })
  1317. }
  1318. // 筛选(industry/level/status 与后端同口径;`industry` 只认正式行业码)。
  1319. const industry = (query && query.industry) || ''
  1320. const level = query && query.level ? Number(query.level) : null
  1321. const status = (query && query.status) || ''
  1322. const filtered = source.filter((item) => {
  1323. if (industry && item.industry !== industry) return false
  1324. if (level !== null && item.level !== level) return false
  1325. if (status && item.status !== status) return false
  1326. return true
  1327. })
  1328. // 排序:eventTime 倒序,同时间按 eventNo 升序(后端 eventOrdering())。
  1329. const sorted = [...filtered].sort((a, b) => {
  1330. const at = a.eventTime || ''
  1331. const bt = b.eventTime || ''
  1332. if (at && bt && at !== bt) return at > bt ? -1 : 1
  1333. if (at && !bt) return -1
  1334. if (!at && bt) return 1
  1335. return a.eventNo < b.eventNo ? -1 : a.eventNo > b.eventNo ? 1 : 0
  1336. })
  1337. const page = Number(query && query.page) > 0 ? Number(query.page) : 1
  1338. const pageSize = Number(query && query.pageSize) > 0 ? Number(query.pageSize) : 100
  1339. const from = Math.max(0, (page - 1) * pageSize)
  1340. const to = from + pageSize
  1341. const slice = sorted.slice(from, to)
  1342. const total = sorted.length
  1343. return currentEventsEnvelope(mode, slice, query, {
  1344. state: slice.length ? 'SUCCESS' : 'EMPTY',
  1345. reason: slice.length ? 'SUCCESS' : 'NO_EVENTS',
  1346. message: null,
  1347. data: slice,
  1348. pagination: { page, pageSize, total, totalPages: total ? Math.ceil(total / pageSize) : 0, hasMore: to < total },
  1349. deviceCodes: [...new Set(sorted.map((item) => item.deviceCode).filter(Boolean))].sort(),
  1350. })
  1351. }
  1352. /** 组装 `/events/current` 信封(sections 用内部分区,顶层永远 200 形状)。 */
  1353. function currentEventsEnvelope(mode, items, query, inner) {
  1354. return {
  1355. requestId: 'mock-current-events',
  1356. apiVersion: 'v1',
  1357. readOnly: true,
  1358. displayName: mode === 'ALARM' ? '当前报警' : '当前预警',
  1359. timezone: 'Asia/Shanghai',
  1360. mode,
  1361. updatedAt: SNAPSHOT_AT,
  1362. filters: {
  1363. mode,
  1364. level: query && query.level ? Number(query.level) : null,
  1365. industry: (query && query.industry) || null,
  1366. status: (query && query.status) || null,
  1367. },
  1368. pagination: inner.pagination || { page: 1, pageSize: 100, total: 0, totalPages: 0, hasMore: false },
  1369. mapFilter: {
  1370. mode,
  1371. level: query && query.level ? Number(query.level) : null,
  1372. industry: (query && query.industry) || null,
  1373. status: (query && query.status) || null,
  1374. deviceCodes: inner.deviceCodes || [],
  1375. },
  1376. sections: {
  1377. events: {
  1378. state: inner.state,
  1379. reason: inner.reason,
  1380. message: inner.message,
  1381. data: inner.data,
  1382. },
  1383. workOrders: {
  1384. state: 'EMPTY',
  1385. reason: 'NO_WORK_ORDERS',
  1386. message: null,
  1387. data: null,
  1388. },
  1389. },
  1390. }
  1391. }
  1392. // ---------------------------------------------------------------- 预警处置聚合面板(票 19)
  1393. function warningRange(query) {
  1394. const type = (query && query.range) || 'LAST_7_DAYS'
  1395. const days = type === 'LAST_90_DAYS' ? 90 : type === 'LAST_30_DAYS' ? 30 : 7
  1396. if (query?.startTime && query?.endTime) return { type, startTime: query.startTime, endTime: query.endTime }
  1397. const end = new Date('2026-09-02T10:00:00+08:00')
  1398. const start = new Date(end.getTime() - days * 24 * 3600 * 1000)
  1399. return { type, startTime: start.toISOString(), endTime: end.toISOString() }
  1400. }
  1401. function responseEventSource(query) {
  1402. const mode = (query && (query.eventFamily || query.mode)) === 'ALARM' ? 'ALARM' : 'WARNING'
  1403. const source = mode === 'ALARM' ? CURRENT_ALARMS : CURRENT_WARNINGS
  1404. const industry = (query && query.industry) || ''
  1405. return { mode, items: source.filter((item) => !industry || item.industry === industry) }
  1406. }
  1407. /**
  1408. * 历史分析载荷(票 19;票 61 补逐事件行 + 服务端分页)。
  1409. *
  1410. * 与后端 `CockpitHistoryAnalysisResponse` 同形:`rows[]` 小时桶 + `summary` +
  1411. * **`events[]` 逐事件行**(形状与 `events/current` 的 `EventItem` 同构)+ `pagination`。
  1412. * `page`/`pageSize` 按后端语义真实切片(默认 100、上限 1000),所以 `pageSize=10`
  1413. * 在 mock 上就能演示两页(单窗直取;多窗由前端合并后集合分页)。
  1414. *
  1415. * 一处如实留档的取舍:样例事件时间固定在 `SNAPSHOT_AT` 附近,而面板请求的是
  1416. * 「现在」往前 N 天的窗口 —— 按窗口过滤事件会恒空,多页翻页在 mock 上就演不出来。
  1417. * 与既有 mock「固定快照日」同一取舍:**事件行不按请求窗口过滤**(只按族/行业过滤),
  1418. * 小时桶仍按请求窗口生成(既有行为不变)。真实契约的窗口过滤由闸门注入载荷证明。
  1419. */
  1420. function historyAnalysisPayload(scenario, query) {
  1421. const source = responseEventSource(query)
  1422. const range = warningRange(query)
  1423. const items = source.items.filter((item) => Date.parse(item.eventTime) >= Date.parse(range.startTime) && Date.parse(item.eventTime) <= Date.parse(range.endTime))
  1424. const buckets = []
  1425. const hour = 3600000
  1426. for (let time = Math.floor(Date.parse(range.startTime) / hour) * hour; time <= Date.parse(range.endTime); time += hour) {
  1427. buckets.push({ timeBucket: new Date(time).toISOString(), eventCount: scenario === 'empty' ? 0 : items.filter((item) => Math.floor(Date.parse(item.eventTime) / hour) === time / hour).length, handledCount: 0 })
  1428. }
  1429. const events = scenario === 'empty' ? [] : sortEventRows(source.items)
  1430. const page = Number(query && query.page) > 0 ? Number(query.page) : 1
  1431. const pageSize = Number(query && query.pageSize) > 0 ? Number(query.pageSize) : 100
  1432. const from = Math.min((page - 1) * pageSize, events.length)
  1433. const to = Math.min(from + pageSize, events.length)
  1434. const total = events.length
  1435. return {
  1436. requestId: 'mock-history-analysis', apiVersion: 'v1', readOnly: true, mode: source.mode,
  1437. range, updatedAt: SNAPSHOT_AT,
  1438. pagination: { page, pageSize, total, totalPages: total ? Math.ceil(total / pageSize) : 0, hasMore: to < total },
  1439. // 票 61:事件行的总数与 `pagination.total` 同源(不由当前页反推)。
  1440. events: events.slice(from, to),
  1441. rows: scenario === 'empty' ? [] : buckets,
  1442. summary: { eventCount: total },
  1443. }
  1444. }
  1445. /**
  1446. * `/events/handling-efficiency`(票 19;票 65 两族语义分流;**票 78 随票 74 契约两族分叉**)。
  1447. *
  1448. * 形状照抄后端 `CockpitHandlingEfficiencyResponse`:`eventFamily` 回显 + `summary`
  1449. * (条数/工单关联实况 + 两族各自的处置口径聚合)+ 状态计数 + `durationTrend`
  1450. * (逐桶 `eventCount` 与结案时长)+ 逐事件行 `events[]`。
  1451. *
  1452. * **两族契约分叉**(票 74 已交付,后端实测见 `verify/artifacts/t74/`):
  1453. * · 预警族:工单口径六字段(`handledCount/inProgressCount/cancelledCount/`
  1454. * `handlingEfficiency/averageDuration/workOrderStateCounts`)显式 `null`;
  1455. * 预警自身流程给 `warningStateCounts`(WarningWorkflow 六态全铺、缺桶计 0,
  1456. * 脏状态入「未知」桶)+ `summary.warningHandlingEfficiency`(已解除 ÷ 窗口内预警数,
  1457. * 分母 0 → EMPTY/NO_WARNINGS)+ `summary.warningDuration`(无样本 → EMPTY/NO_CLOSED_WARNINGS)。
  1458. * · 报警族:工单口径原样,三个 `warning*` 字段为 `null`。
  1459. * 六态计数从样例事件的 `status` 推导(认得出的入对应桶,认不出的一律入 UNKNOWN ——
  1460. * 与后端 `normalizeWarningStatus` 的归一规则同构),六态合计恒等于条数;
  1461. * 不为演示手调分布数字(map Notes 的静态样例裁定)。
  1462. */
  1463. function handlingEfficiencyPayload(scenario, query) {
  1464. const source = responseEventSource(query)
  1465. const range = warningRange(query)
  1466. const blank = scenario === 'empty'
  1467. const denominator = blank ? 0 : 3
  1468. const numerator = blank ? 0 : 2
  1469. const items = blank ? [] : source.items
  1470. const isAlarm = source.mode === 'ALARM'
  1471. // 预警不挂工单(实测),报警按等级 1 的样本给承接工单 —— 两族的关联实况刻意不同。
  1472. const linkedOf = (item) => isAlarm && Number(item.level) === 1
  1473. const linkedCount = items.filter(linkedOf).length
  1474. const events = items.map((item) => {
  1475. const linked = linkedOf(item)
  1476. const stateCode = linked ? 3 : null
  1477. return {
  1478. eventNo: item.eventNo,
  1479. deviceCode: item.deviceCode,
  1480. deviceName: item.deviceName,
  1481. level: item.level,
  1482. levelColor: eventLevelColorOf(item.level),
  1483. eventTime: item.eventTime,
  1484. workOrderStateCode: stateCode,
  1485. workOrderStateName: stateCode === null ? null : '处理中',
  1486. durationHours: null,
  1487. hasWorkOrder: linked,
  1488. }
  1489. })
  1490. // 票 78:WarningWorkflow 六态全铺(缺桶计 0),认不出的状态入 UNKNOWN 桶(后端同构)。
  1491. const warningStatuses = ['DRAFT', 'PENDING', 'RECEIVED', 'PROCESSING', 'HANDLED', 'CLOSED']
  1492. const warningStateCounts = isAlarm
  1493. ? null
  1494. : warningStatuses
  1495. .map((stateCode) => ({
  1496. stateCode,
  1497. stateName: { DRAFT: '草稿', PENDING: '待接收', RECEIVED: '已接收', PROCESSING: '处置中', HANDLED: '已处置', CLOSED: '已解除' }[stateCode],
  1498. count: items.filter((item) => item && item.status === stateCode).length,
  1499. }))
  1500. .concat((() => {
  1501. const unknown = items.filter((item) => item && !warningStatuses.includes(item.status)).length
  1502. return unknown > 0 ? [{ stateCode: 'UNKNOWN', stateName: '未知', count: unknown }] : []
  1503. })())
  1504. // 预警族自身的已解除率/时长:与后端同一算法(CLOSED ÷ 条数;无 CLOSED 样本即 EMPTY)。
  1505. const closedWarnings = isAlarm ? 0 : (warningStateCounts.find((row) => row.stateCode === 'CLOSED') || { count: 0 }).count
  1506. const warningTotal = isAlarm ? 0 : items.length
  1507. const summary = isAlarm ? {
  1508. totalEvents: items.length,
  1509. linkedWorkOrderCount: linkedCount,
  1510. missingWorkOrderCount: items.length - linkedCount,
  1511. handledCount: blank ? 0 : 2,
  1512. inProgressCount: blank ? 0 : 1,
  1513. cancelledCount: blank ? 0 : 1,
  1514. handlingEfficiency: { value: blank ? 0 : numerator / denominator, numerator, denominator, state: denominator ? 'AVAILABLE' : 'EMPTY', reason: denominator ? 'READY' : 'NO_ELIGIBLE_WORK_ORDERS', basis: 'CLOSED_WORK_ORDERS_OVER_ELIGIBLE_WORK_ORDERS' },
  1515. averageDuration: { value: denominator ? 2.4 : 0, unit: 'HOURS', state: denominator ? 'AVAILABLE' : 'EMPTY', sampleCount: denominator ? 2 : 0, reason: denominator ? null : 'NO_CLOSED_WORK_ORDERS' },
  1516. // 票 78:报警族不回预警自身字段(后端显式 null,不缺键)。
  1517. warningHandlingEfficiency: null,
  1518. warningDuration: null,
  1519. } : {
  1520. totalEvents: items.length,
  1521. linkedWorkOrderCount: linkedCount,
  1522. missingWorkOrderCount: items.length - linkedCount,
  1523. // 票 78:工单口径在预警族显式 null(不把「不适用」数成 0)。
  1524. handledCount: null,
  1525. inProgressCount: null,
  1526. cancelledCount: null,
  1527. handlingEfficiency: null,
  1528. averageDuration: null,
  1529. warningHandlingEfficiency: warningTotal > 0
  1530. ? { value: (closedWarnings / warningTotal).toFixed(4), numerator: closedWarnings, denominator: warningTotal, state: 'AVAILABLE', reason: null, basis: 'CLOSED_WARNINGS_OVER_WINDOW_WARNINGS' }
  1531. : { value: '0.0000', numerator: 0, denominator: 0, state: 'EMPTY', reason: 'NO_WARNINGS', basis: 'CLOSED_WARNINGS_OVER_WINDOW_WARNINGS' },
  1532. warningDuration: closedWarnings > 0
  1533. ? { value: '1.25', unit: 'HOURS', sampleCount: closedWarnings, state: 'AVAILABLE', reason: null }
  1534. : { value: '0.00', unit: 'HOURS', sampleCount: 0, state: 'EMPTY', reason: 'NO_CLOSED_WARNINGS' },
  1535. }
  1536. return {
  1537. requestId: 'mock-handling-efficiency', apiVersion: 'v1', readOnly: true,
  1538. displayName: isAlarm ? '报警效率' : '预警效率',
  1539. eventFamily: source.mode,
  1540. range, updatedAt: SNAPSHOT_AT,
  1541. pagination: { page: 1, pageSize: 100, total: items.length, totalPages: items.length ? 1 : 0, hasMore: false },
  1542. summary,
  1543. // 正式端点仅提供结案平均时长,不编造平均响应时长。
  1544. // 票 20:键为后端 0–7 状态码(待派单…已取消)。旧的 1–7 键已随字典对齐改掉。
  1545. // 票 78:工单状态计数只属报警族;预警族显式 null。
  1546. workOrderStateCounts: isAlarm
  1547. ? WORK_ORDER_STATES.map((state) => ({ stateCode: state.code, stateName: state.name, count: denominator ? state.code === 5 ? 2 : state.code === 6 ? 1 : state.code === 7 ? 1 : 0 : 0 }))
  1548. : null,
  1549. warningStateCounts,
  1550. // 票 65:逐桶带 `eventCount`(事件发生量)。票 74 契约:预警族逐桶的
  1551. // `handledCount`/`averageDuration` 为 null(结案时长属工单口径),报警族保留。
  1552. durationTrend: blank
  1553. ? []
  1554. : [1.4, 2.1, 2.4, 1.8, 2.6, 2.2, 2.4].map((value, index) => ({
  1555. timeBucket: `2026-09-${String(index + 1).padStart(2, '0')}`,
  1556. eventCount: 2,
  1557. handledCount: isAlarm ? 0 : null,
  1558. averageDuration: isAlarm ? { value, unit: 'HOURS', state: 'AVAILABLE' } : null,
  1559. })),
  1560. events,
  1561. }
  1562. }
  1563. function multidimensionalAnalysisPayload(scenario, query) {
  1564. const source = responseEventSource(query)
  1565. const count = (key) => [...new Set(source.items.map((item) => item[key]).filter(Boolean))].map((value) => ({ code: value, name: value, count: source.items.filter((item) => item[key] === value).length }))
  1566. const levels = [1, 2, 3, 4].map((level) => ({ level, count: source.items.filter((item) => item.level === level).length }))
  1567. return {
  1568. requestId: 'mock-multidimensional-analysis', apiVersion: 'v1', readOnly: true, mode: source.mode,
  1569. range: warningRange(query), updatedAt: SNAPSHOT_AT,
  1570. dimensions: [
  1571. { dimensionCode: 'EVENT_TYPE', buckets: count('eventType').map((row) => ({ bucketCode: row.code, bucketLabel: row.name, count: row.count })) },
  1572. // 票 66:真实后端**恒定**回 CAUSE 维(缺成因走 `UNKNOWN_CAUSE` 兜底桶,服务端注释原句
  1573. // "The unknown bucket is always present so the cockpit never hides missing causes")。
  1574. // 样例照抄这一维:不抄的话「按成因」块在 mock 下永远不出现,样例比契约少一维是**形状**问题,
  1575. // 不是为了「演示某项行为」补数据(见 map Notes 的静态样例裁定)。
  1576. { dimensionCode: 'CAUSE', buckets: [{ bucketCode: 'UNKNOWN_CAUSE', bucketLabel: '未知/缺失成因', count: source.items.length }] },
  1577. { dimensionCode: 'LEVEL', buckets: levels.map((row) => ({ bucketCode: String(row.level), bucketLabel: `${row.level}级`, count: row.count })) },
  1578. { dimensionCode: 'INDUSTRY', buckets: count('industry').map((row) => ({ bucketCode: row.code, bucketLabel: { GAS: '燃气', WATER_SUPPLY: '供水', DRAINAGE: '排水', MANHOLE: '窨井' }[row.code], count: row.count })) },
  1579. { dimensionCode: 'DISTRICT', buckets: [{ bucketCode: 'UNASSIGNED', bucketLabel: '未分区', count: source.items.length }] },
  1580. ],
  1581. highlights: source.items.length ? [{ title: source.mode === 'ALARM' ? '高等级报警重点' : '高等级预警重点', detail: '按事件等级与数量识别', count: source.items.filter((item) => item.level === 1).length }] : [],
  1582. }
  1583. }
  1584. function freshnessPayload(scenario, deviceCode = '') {
  1585. const base = {
  1586. requestId: 'mock-freshness',
  1587. apiVersion: 'v1',
  1588. readOnly: true,
  1589. deviceCode: deviceCode || ARCHIVE.deviceCode,
  1590. serverUpdatedAt: SNAPSHOT_AT,
  1591. calibrationPeriodSeconds: 60,
  1592. }
  1593. if (scenario === 'empty') {
  1594. return { ...base, updatedAt: null, statusTime: null, freshness: 'EMPTY', staleReason: null, missedCycles: 0, dataAgeSeconds: 0, retained: false, message: null }
  1595. }
  1596. if (scenario === 'degraded') {
  1597. // 只给了 freshness,没给任何时间:界面必须显示占位符而不是「0 秒前」。
  1598. return { ...base, freshness: 'CURRENT' }
  1599. }
  1600. if (scenario === 'stale') {
  1601. return { ...base, updatedAt: '2026-09-02T09:58:00+08:00', statusTime: null, freshness: 'EXPIRED', staleReason: 'TWO_UPDATE_CYCLES_MISSED', missedCycles: 2, dataAgeSeconds: 120, retained: true, message: '数据暂不可用/已过期' }
  1602. }
  1603. return { ...base, updatedAt: '2026-09-02T09:59:50+08:00', statusTime: '2026-09-02T09:59:55+08:00', freshness: 'CURRENT', staleReason: null, missedCycles: 0, dataAgeSeconds: 5, retained: false, message: null }
  1604. }
  1605. // ---------------------------------------------------------------- 基础设施四面板(票 17)
  1606. /**
  1607. * 票 17:基础设施模式四块面板的契约化样例。
  1608. *
  1609. * 字段名与嵌套形状照抄后端四个响应类(`CockpitInfrastructureBaseArchivesResponse` /
  1610. * `...OperatingInformationResponse` / `...ManagementInformationResponse` / `...EmergencySupportResponse`)
  1611. * 与它们的演示载荷 `docs/cockpit/infrastructure-*-demo.html`,所以适配层单测证明的是
  1612. * 「转换吃得下真载荷」。
  1613. *
  1614. * 三处刻意照抄真实形状的**坑**(不照抄就会漏掉真机才暴露的问题):
  1615. * 1. **BigDecimal 在线上是字符串**(`"0.32"`):三块面板的样例都按字符串给,逼适配层用
  1616. * `numberish` 而不是 `Number()` 直吃;
  1617. * 2. **`Distribution` 是三类维度共用结构**:应急保障的行业分布值在 `industry` 上、区域分布在
  1618. * `area` 上,`code` 一律是 `null`(后端的三个构造函数就是这么填的);
  1619. * 3. **`pointCodes` 按面板各自的真实语义给**(票 49 裁定、票 50 落实):
  1620. * 运行信息指标装的是**源设施编码**(真实载荷恒单元素、与一张图编码空间零交集——
  1621. * 面板因此不产定位按钮,票 50);应急保障样例仍指向 `MAP_POINTS` 真实点位(该面板保留
  1622. * 定位入口,票 50 非目标;真实侧该字段实测恒空、一个按钮都不画,出入见票 49 证据二)。
  1623. */
  1624. /** 四个面板的信封公共段(后端的 `requestId/apiVersion/readOnly/displayName/timezone`)。 */
  1625. function infraEnvelope(displayName, status) {
  1626. return {
  1627. requestId: `mock-${displayName}`,
  1628. apiVersion: 'v1',
  1629. readOnly: true,
  1630. displayName,
  1631. timezone: 'Asia/Shanghai',
  1632. updatedAt: '2026-09-02T09:59:50+08:00',
  1633. freshness: { status, reason: status === 'CURRENT' ? 'READY' : 'TWO_UPDATE_CYCLES_MISSED', updatedAt: '2026-09-02T09:59:50+08:00', serverUpdatedAt: '2026-09-02T10:00:00+08:00' },
  1634. }
  1635. }
  1636. /** 该场景下信封的新鲜度:空样例说 EMPTY,过期样例说 EXPIRED,其余 CURRENT。 */
  1637. function infraStatus(scenario) {
  1638. if (scenario === 'empty') return 'EMPTY'
  1639. if (scenario === 'stale') return 'EXPIRED'
  1640. return 'CURRENT'
  1641. }
  1642. /** 基础档案样例(设施规模 / 行业分类 / 区域分布 / 档案摘要)。 */
  1643. function baseArchivesPayload(scenario, query = {}) {
  1644. const status = infraStatus(scenario)
  1645. // Fixture facts only: every aggregate is derived from the same filtered set.
  1646. const facts = [
  1647. { district: 0, industry: 'WATER_SUPPLY', type: 'WATER_PLANT', name: '水厂', age: 'UNDER_5_YEARS', length: 0, commissioned: true },
  1648. { district: 0, industry: 'GAS', type: 'PUMP_STATION', name: '泵站', age: '5_TO_10_YEARS', length: 0, commissioned: true },
  1649. { district: 0, industry: 'GAS', type: 'GAS_PIPE', name: '燃气管线', age: '10_TO_20_YEARS', length: 4.2, commissioned: true },
  1650. { district: 1, industry: 'WATER_SUPPLY', type: 'WATER_PIPE', name: '供水管线', age: '20_YEARS_OR_OVER', length: 5.6, commissioned: false },
  1651. { district: null, industry: 'DRAINAGE', type: 'DRAINAGE_PIPE', name: '排水管线', age: '20_YEARS_OR_OVER', length: 2.6, commissioned: false },
  1652. // 票 02:档案里有、但后端不下发实体行的类型 —— 「后端尚未下发可上图的实体」这一态
  1653. // 必须在 mock 下演示得出来(否则图例的 NO_ENTITY 分支永远走不到)。
  1654. // 消火栓刻意只出现在档案、不出现在运行信息样例里。
  1655. { district: 1, industry: 'WATER_SUPPLY', type: 'WATER_FIRE_HYDRANT', name: '消火栓', age: 'UNDER_5_YEARS', length: 0, commissioned: true },
  1656. { district: 0, industry: 'WATER_SUPPLY', type: 'WATER_SOURCE', name: '水源地', age: 'UNDER_5_YEARS', length: 0, commissioned: true },
  1657. { district: 2, industry: 'MANHOLE', type: 'MANHOLE', name: '窨井', age: 'UNDER_5_YEARS', length: 0, commissioned: true },
  1658. ]
  1659. const selected = status === 'EMPTY' ? [] : facts.filter((row) =>
  1660. (!query.industry || row.industry === query.industry) &&
  1661. (!query.district || normalizedDistrict(row.district) === query.district))
  1662. const countBy = (field) => [...new Set(selected.map((row) => row[field]))].map((code) => ({ code, count: selected.filter((row) => row[field] === code).length }))
  1663. const selectedFilters = {
  1664. industry: query.industry || null,
  1665. district: query.district && query.district !== 'UNASSIGNED' ? Number(query.district) : null,
  1666. districtFilter: !query.district ? 'NONE' : query.district === 'UNASSIGNED' ? 'UNASSIGNED' : 'ASSIGNED',
  1667. }
  1668. return {
  1669. ...infraEnvelope('基础设施-基础档案', status),
  1670. range: { type: status === 'EXPIRED' ? 'LAST_30_DAYS' : 'CURRENT_BASELINE' },
  1671. // 票 38 mock 同构:真实后端 `totals.scale` **恒 null**(t18 审计实证,五端如此)——
  1672. // mock 若给 'medium',误留的规模消费点在真实下显示 `—`、mock 下却显示「中型」,
  1673. // 走查抓不到(票 08/18 记过的同构纪律)。`facilityTypes[].scale` 给真实形状:
  1674. // 管线行是 "km"(长度单位串,不是规模语义),其余 null。
  1675. totals: { facilityCount: selected.length, lengthKm: selected.length ? selected.reduce((sum, row) => sum + row.length, 0).toFixed(2) : null, scale: null },
  1676. industryDistribution: countBy('industry'),
  1677. facilityTypeDistribution: selected.map((row) => ({ code: row.type, name: row.name, count: 1, lengthKm: row.length || null, scale: row.length ? 'km' : null, range: null })),
  1678. ageDistribution: countBy('age'),
  1679. ageReference: { asOfDate: '2026-09-02', commissionedCount: selected.filter((row) => row.commissioned).length, builtCount: selected.filter((row) => !row.commissioned).length, unknownCount: 0 },
  1680. districtDistribution: countBy('district').map((row) => ({ district: row.code, districtName: row.code === null ? '未分区' : ['城南', '城北', '太常'][row.code], count: row.count })),
  1681. selectedFilters,
  1682. mapFilter: selectedFilters,
  1683. excluded: scenario === 'degraded' ? { unknownTypeCount: null } : { unknownTypeCount: 0, typeKindMismatchCount: 0, smartDeviceCount: 1, futureDateCount: 0 },
  1684. }
  1685. }
  1686. /** 运行信息样例:三个行业块,指标覆盖三类能力 + 边界值(真 0 / 缺能力基准 / 超载)。 */
  1687. function operatingInformationPayload(scenario, query = {}) {
  1688. const status = infraStatus(scenario)
  1689. const envelope = infraEnvelope('基础设施-运行信息', status)
  1690. const blank = status === 'EMPTY'
  1691. // 票 49 裁定:`pointCodes` 实为**源设施编码**(真实载荷 6362 条无一例外恒单元素),不进一张图
  1692. // 对象序列 → 运行信息面板不产定位按钮(票 50)。样例按行业用真实同形的设施码
  1693. // (TCRQ/CNRQ 燃气、TCGC/CNGC 供水、TCWS/TCYS 排水),**不得**用 `MAP_POINTS` 的 MP-*——
  1694. // 否则 mock 下按钮能点、真实下全 MISSING,同构纪律(票 08/18/38)被打破。
  1695. // 票 68:设施点图层从运行信息行上枚举「可上图的设施实体」(facilityId/facilityKind/facilityStatus),
  1696. // 所以 mock 的对应行也带这三个字段(同构纪律:不带上就永远演示不出设施点图层)。
  1697. const metric = (code, name, category, unit, value, capacity, ratio, load, pointCodes, facility = null) => ({
  1698. metricCode: code,
  1699. metricName: name,
  1700. category,
  1701. unit,
  1702. // 照抄线上形状:BigDecimal 是字符串。
  1703. value,
  1704. capacityValue: capacity,
  1705. loadRatio: ratio,
  1706. loadState: load,
  1707. sampledAt: '2026-09-02T09:59:30+08:00',
  1708. freshness: { status: 'CURRENT', reason: 'SAMPLE_CURRENT', ageSeconds: 20 },
  1709. trend: [{ bucket: '2026-09-01', value }, { bucket: '2026-09-02', value }],
  1710. abnormal: load === 'OVERLOAD',
  1711. pointCodes,
  1712. ...(facility || {}),
  1713. })
  1714. const industries = blank
  1715. ? []
  1716. : [
  1717. {
  1718. industry: { code: 'GAS', key: 'gas', label: '燃气' },
  1719. state: 'READY',
  1720. stateReason: 'READY',
  1721. abnormalMetricCount: 0,
  1722. metrics: [
  1723. metric('gas_supply_pressure', '燃气供应压力', 'SUPPLY', 'MPa', '0.32', '0.40', '0.8000', 'WATCH', ['TCRQ202609020001']),
  1724. metric('gas_flow_rate', '燃气流量', 'FLOW', 'm3/h', '1200.5', '2000', '0.6003', 'NORMAL', ['CNRQ202609020001']),
  1725. metric('gas_remaining_capacity', '燃气剩余承载能力', 'CAPACITY', 'm3', '800', '2000', '0.4000', 'NORMAL', ['TCRQ202609020002']),
  1726. ],
  1727. },
  1728. {
  1729. industry: { code: 'WATER_SUPPLY', key: 'waterSupply', label: '供水' },
  1730. state: 'READY',
  1731. stateReason: 'READY',
  1732. abnormalMetricCount: 1,
  1733. metrics: [
  1734. // 边界:真 0 是有效读数;超载项走 lv1 色键。
  1735. // 票 68:带设施实体身份(水厂),设施点图层据此取实体详情坐标上图。
  1736. metric('water_supply_flow', '供水流量', 'SUPPLY', 'm3/h', '0', '4000', '0.0000', 'NORMAL', ['TCGC202609020001'], {
  1737. facilityId: '1', facilityKind: 'WATER_PLANT', facilityStatus: '0',
  1738. }),
  1739. // 票 02:补齐九类设施实体行,让「全量上图」在 mock 下也可演示。
  1740. // 水源地带坐标;用水户故意不带坐标(无地图位置链路);消火栓带坐标。
  1741. metric('water_source_point_count', '洮水水源地', 'CAPACITY', '处', '1', null, null, 'UNKNOWN', ['WS001'], {
  1742. facilityId: '3', facilityKind: 'WATER_SOURCE', facilityStatus: '0',
  1743. }),
  1744. metric('water_user_point_count', '自来水公司用水户', 'CAPACITY', '户', '1', null, null, 'UNKNOWN', ['U001'], {
  1745. facilityId: '4', facilityKind: 'WATER_USER', facilityStatus: '0',
  1746. }),
  1747. metric('water_fire_hydrant_point_count', '中山路消火栓', 'CAPACITY', '座', '1', null, null, 'UNKNOWN', ['FH001'], {
  1748. facilityId: '5', facilityKind: 'WATER_FIRE_HYDRANT', facilityStatus: '0',
  1749. }),
  1750. metric('water_supply_load', '供水负荷', 'CAPACITY', 'm3/h', '5000', '4000', '1.2500', 'OVERLOAD', ['CNGC202609020001']),
  1751. // 边界:能力基准缺失 → 负荷率也算不出来(界面显示占位符,不显示 0)。
  1752. metric('water_pressure', '供水压力', 'PRESSURE', 'MPa', '0.45', null, null, 'UNKNOWN', ['TCGC202609020002']),
  1753. ],
  1754. },
  1755. {
  1756. industry: { code: 'DRAINAGE', key: 'drainage', label: '排水' },
  1757. state: 'READY',
  1758. stateReason: 'READY',
  1759. abnormalMetricCount: 0,
  1760. metrics: [
  1761. metric('sewage_cod', '污水 COD', 'QUALITY', 'mg/L', '18.2', '50', '0.3640', 'NORMAL', ['TCWS202609020001']),
  1762. // 票 68:带设施实体身份(泵站),与上面那条水厂一起覆盖「可上图 + 状态色」两条路径。
  1763. metric('rainwater_flow', '雨水流量', 'FLOW', 'm3/h', '880', '1000', '0.8800', 'WATCH', ['TCYS202609020001'], {
  1764. facilityId: '2', facilityKind: 'PUMP_STATION', facilityStatus: '2',
  1765. }),
  1766. // 票 02:闸门 / 调蓄设施实体行(排水行业)。
  1767. metric('drainage_gate_point_count', '东堤闸门', 'CAPACITY', '个', '1', null, null, 'UNKNOWN', ['G001'], {
  1768. facilityId: '6', facilityKind: 'DRAINAGE_GATE', facilityStatus: '0',
  1769. }),
  1770. metric('drainage_storage_point_count', '一号调蓄池', 'CAPACITY', '个', '1', null, null, 'UNKNOWN', ['S001'], {
  1771. facilityId: '7', facilityKind: 'DRAINAGE_STORAGE', facilityStatus: '0',
  1772. }),
  1773. ],
  1774. },
  1775. // 票 02:窨井是第四个正式行业,运行信息也要有它的实体行,否则 fig 例上的窨井永远「未下发」。
  1776. {
  1777. industry: { code: 'MANHOLE', key: 'manhole', label: '窨井' },
  1778. state: 'READY',
  1779. stateReason: 'READY',
  1780. abnormalMetricCount: 0,
  1781. metrics: [
  1782. metric('manhole_point_count', '沅陵县窨井001', 'CAPACITY', '座', '1', null, null, 'UNKNOWN', ['YL-YJ-001'], {
  1783. facilityId: '8', facilityKind: 'MANHOLE', facilityStatus: '0',
  1784. }),
  1785. ],
  1786. },
  1787. ]
  1788. // 票 51:mock 必须**吃请求查询串**(至少 industry)—— 不吃的话 mock 下永远所有块全非空、
  1789. // 选行业不改变响应,真实缺陷在 mock 上演示不出来(票 08/18/38 记过的同一条纪律)。
  1790. // 照抄线上契约(2026-10-16 实测,载荷落盘 verify/artifacts/t51/):筛选把未选中块置空
  1791. // (`state: EMPTY` / `stateReason: NO_METRICS`,不删块、不改变块序);selectedIndustry 回显
  1792. // 命中块,未筛时回 null(线上未筛载荷同款,不再硬编码 GAS);mock 没有的行业也回显请求码。
  1793. const requested = blank ? '' : query.industry || ''
  1794. const hit = requested ? industries.find((block) => block.industry.code === requested) : null
  1795. const filtered = requested
  1796. ? industries.map((block) =>
  1797. block.industry.code === requested
  1798. ? block
  1799. : { industry: block.industry, state: 'EMPTY', stateReason: 'NO_METRICS', abnormalMetricCount: 0, metrics: [] },
  1800. )
  1801. : industries
  1802. return {
  1803. ...envelope,
  1804. range: { type: 'LAST_24_HOURS', start: '2026-09-01T10:00:00+08:00', end: '2026-09-02T10:00:00+08:00' },
  1805. selectedIndustry: hit ? hit.industry : requested ? { code: requested, key: '', label: '' } : null,
  1806. industries: filtered,
  1807. excluded:
  1808. scenario === 'degraded'
  1809. ? { unknownIndustryCount: null }
  1810. : { unknownIndustryCount: 0, nonFormalIndustryCount: 0 },
  1811. }
  1812. }
  1813. // ---------------------------------------------------------------- 设施点实体详情(票 68)
  1814. /**
  1815. * 票 68:设施点图层补坐标用的实体详情样例(水厂 / 泵站各一条)。
  1816. *
  1817. * 形状照抄真实 `/api/cockpit/v1/infrastructure/entities/{id}/detail`:坐标在 `coordinates` 上
  1818. * (缺坐标即 null,前端据此把该设施进「无地图位置」清单,不补默认值)。
  1819. * 两条样例与运行信息 mock 里带 `facilityId/facilityKind` 的指标行一一对应。
  1820. */
  1821. const FACILITY_ENTITY_FIXTURES = {
  1822. // 票 02:九类设施各一条样例。
  1823. // 用药用户(用户 4)故意不给坐标 —— 「有实体、无坐标」这一态在 mock 下必须可演示。
  1824. 'WATER_SOURCE|3': {
  1825. category: 'WATER_SOURCE',
  1826. id: '3',
  1827. code: 'WS001',
  1828. name: '洮水水源地',
  1829. status: '0',
  1830. location: '洮水镇河边',
  1831. coordinates: { longitude: 110.401, latitude: 28.441, endLongitude: null, endLatitude: null },
  1832. },
  1833. 'WATER_USER|4': {
  1834. category: 'WATER_USER',
  1835. id: '4',
  1836. code: 'U001',
  1837. name: '自来水公司用水户',
  1838. status: '0',
  1839. location: '沅陵县人民路',
  1840. coordinates: { longitude: null, latitude: null, endLongitude: null, endLatitude: null },
  1841. },
  1842. 'WATER_FIRE_HYDRANT|5': {
  1843. category: 'WATER_FIRE_HYDRANT',
  1844. id: '5',
  1845. code: 'FH001',
  1846. name: '中山路消火栓',
  1847. status: '0',
  1848. location: '中山路',
  1849. coordinates: { longitude: 110.396, latitude: 28.432, endLongitude: null, endLatitude: null },
  1850. },
  1851. 'DRAINAGE_GATE|6': {
  1852. category: 'DRAINAGE_GATE',
  1853. id: '6',
  1854. code: 'G001',
  1855. name: '东堤闸门',
  1856. status: '0',
  1857. location: '东堤',
  1858. coordinates: { longitude: 110.388, latitude: 28.428, endLongitude: null, endLatitude: null },
  1859. },
  1860. 'DRAINAGE_STORAGE|7': {
  1861. category: 'DRAINAGE_STORAGE',
  1862. id: '7',
  1863. code: 'S001',
  1864. name: '一号调蓄池',
  1865. status: '0',
  1866. location: '城北',
  1867. coordinates: { longitude: 110.381, latitude: 28.445, endLongitude: null, endLatitude: null },
  1868. },
  1869. 'MANHOLE|8': {
  1870. category: 'MANHOLE',
  1871. id: '8',
  1872. code: 'YL-YJ-001',
  1873. name: '沅陵县窨井001',
  1874. status: '0',
  1875. location: '龙兴路',
  1876. coordinates: { longitude: 110.394, latitude: 28.436, endLongitude: null, endLatitude: null },
  1877. },
  1878. 'WATER_PLANT|1': {
  1879. category: 'WATER_PLANT',
  1880. id: '1',
  1881. code: 'WP001',
  1882. name: 'XX自来水厂',
  1883. status: '0',
  1884. location: '沅陵县城东',
  1885. coordinates: { longitude: 110.392, latitude: 28.437, endLongitude: null, endLatitude: null },
  1886. },
  1887. // 票 07:防护目标没有业务编码列(code 空);风险等级/颜色以字典码下发;
  1888. // 关联管网给业务引用 name+code(后端票 06 的契约,联调前用这份 mock 验收)。
  1889. 'PROTECTION_TARGET|PT-DR-001': {
  1890. category: 'PROTECTION_TARGET',
  1891. id: 'PT-DR-001',
  1892. code: '',
  1893. name: '污水处理厂防护目标',
  1894. status: 1,
  1895. location: '城北污水处理厂',
  1896. coordinates: { longitude: 110.383, latitude: 28.447, endLongitude: null, endLatitude: null },
  1897. attributes: {
  1898. riskLevel: 1,
  1899. riskColor: 1,
  1900. riskScore: 72.5,
  1901. assessmentModel: '易损性评估 v2',
  1902. assessmentTime: '2026-11-20T10:30:00+08:00',
  1903. riskFactors: '{"管材":"钢管","周边":"学校","埋深":"1.8 米"}',
  1904. network: { code: 'YS-P-004', name: '城北污水干管' },
  1905. },
  1906. },
  1907. 'PUMP_STATION|2': {
  1908. category: 'PUMP_STATION',
  1909. id: '2',
  1910. code: 'PS002',
  1911. name: '城东泵站2',
  1912. status: '2',
  1913. location: '沅陵县城东',
  1914. coordinates: { longitude: 110.385, latitude: 28.436, endLongitude: null, endLatitude: null },
  1915. },
  1916. }
  1917. /**
  1918. * 实体详情样例:查询串里的 `category` 决定查哪个设施表(与真接口同形)。
  1919. * 查不到就**抛错**(真接口是 404/业务错误,不是"返回一个空详情")。
  1920. */
  1921. function facilityEntityDetailPayload(scenario, requested, query = {}) {
  1922. if (scenario === 'empty') throw new Error('mock: 实体不存在')
  1923. const category = String(query.category || '').toUpperCase()
  1924. const fixture = FACILITY_ENTITY_FIXTURES[`${category}|${requested}`]
  1925. if (!fixture) throw new Error(`mock: 实体 ${requested || '(空)'} 不存在`)
  1926. return {
  1927. requestId: 'mock-entity-detail',
  1928. apiVersion: 'v1',
  1929. readOnly: true,
  1930. category: fixture.category,
  1931. id: fixture.id,
  1932. code: fixture.code,
  1933. name: fixture.name,
  1934. status: fixture.status,
  1935. location: fixture.location,
  1936. district: null,
  1937. districtName: '未分区',
  1938. coordinates: fixture.coordinates,
  1939. attributes: fixture.attributes || {},
  1940. updatedAt: '2026-09-02T09:59:50+08:00',
  1941. }
  1942. }
  1943. /** 管理信息样例:四个「片区 × 行业」组合(含「未分区」与「有设备、没有设施」的城北)。 */
  1944. function managementInformationPayload(scenario, query = {}) {
  1945. const status = infraStatus(scenario)
  1946. const blank = status === 'EMPTY'
  1947. const districtIndustry = blank ? [] : [
  1948. { district: 0, districtName: '城南', industry: 'WATER_SUPPLY', facilityCount: 1, equipmentCount: 1 },
  1949. { district: 1, districtName: '城北', industry: 'MANHOLE', facilityCount: 0, equipmentCount: 1 },
  1950. { district: 2, districtName: '太常', industry: 'GAS', facilityCount: 1, equipmentCount: 1 },
  1951. // 排水行带雨污二级分项(维护者 2026-11-02):与真实端点同形,码位 0-污水 1-雨水。
  1952. { district: null, districtName: '未分区', industry: 'DRAINAGE', facilityCount: 1, equipmentCount: 0,
  1953. networkLevelCounts: [{ networkLevel: '0', facilityCount: 1 }] },
  1954. ].filter((row) => (!query.district || normalizedDistrict(row.district) === query.district) && (!query.industry || row.industry === query.industry))
  1955. const selectedFilters = {
  1956. industry: query.industry || null,
  1957. district: query.district && query.district !== 'UNASSIGNED' ? Number(query.district) : null,
  1958. districtFilter: !query.district ? 'NONE' : query.district === 'UNASSIGNED' ? 'UNASSIGNED' : 'ASSIGNED',
  1959. }
  1960. return {
  1961. ...infraEnvelope('基础设施-管理信息', status),
  1962. selectedFilters,
  1963. totals: {
  1964. facilityCount: districtIndustry.reduce((sum, row) => sum + row.facilityCount, 0),
  1965. equipmentCount: districtIndustry.reduce((sum, row) => sum + row.equipmentCount, 0),
  1966. },
  1967. districtIndustry,
  1968. mapFilter: selectedFilters,
  1969. excluded: { unknownIndustryCount: 0, nonFormalIndustryCount: 0 },
  1970. }
  1971. }
  1972. /** 应急保障样例:三段各自成败(一段可用、一段空、一段不可用),三件套齐全。 */
  1973. function emergencySupportPayload(scenario) {
  1974. const status = infraStatus(scenario)
  1975. const envelope = infraEnvelope('基础设施-应急保障', status)
  1976. const blank = status === 'EMPTY'
  1977. const item = (objectCode, objectName, category, industry, area, pointCodes, counts) => ({
  1978. objectCode,
  1979. objectName,
  1980. category,
  1981. industry,
  1982. area,
  1983. pointCodes,
  1984. eventAssociations: { warningCount: counts[0], alarmCount: counts[1], workOrderCount: counts[2] },
  1985. })
  1986. // 空样例:三段都是 EMPTY("确实没有对象")。
  1987. const emptySections = {
  1988. hazardSources: { state: 'EMPTY', stateReason: 'NO_OBJECTS', items: [] },
  1989. protectionTargets: { state: 'EMPTY', stateReason: 'NO_OBJECTS', items: [] },
  1990. emergencyResources: { state: 'EMPTY', stateReason: 'NO_OBJECTS', items: [] },
  1991. }
  1992. const sections = blank
  1993. ? emptySections
  1994. : {
  1995. // 三段**各自成败**:危险源可用、防护目标不可用、应急资源可用 ——
  1996. // 「一段坏了不遮盖其它段」在 mock 上直接可演示(票 17 与票 11 同一条纪律)。
  1997. hazardSources: {
  1998. state: 'READY',
  1999. stateReason: 'READY',
  2000. items: [
  2001. item('HS-WS-001', '太常片区污水管线危险源', 'HAZARD_SOURCE', 'WATER_SUPPLY', 'TC', ['MP-003'], [1, 1, 1]),
  2002. ],
  2003. },
  2004. protectionTargets:
  2005. scenario === 'infrastructure-partial'
  2006. ? { state: 'UNAVAILABLE', stateReason: 'SOURCE_UNAVAILABLE', items: [] }
  2007. : {
  2008. state: 'READY',
  2009. stateReason: 'READY',
  2010. items: [
  2011. // 区域为空 → 后端归一为未分区,界面照实说"未分区"而不是留白。
  2012. item('PT-DR-001', '污水处理厂防护目标', 'PROTECTION_TARGET', 'DRAINAGE', null, ['MP-003'], [0, 0, 1]),
  2013. ],
  2014. },
  2015. emergencyResources: {
  2016. state: 'READY',
  2017. stateReason: 'READY',
  2018. items: [
  2019. item('ER-WS-001', '供水抢修物资库', 'EMERGENCY_RESOURCE', 'WATER_SUPPLY', 'CN', ['MP-001'], [0, 0, 0]),
  2020. item('ER-GAS-001', '燃气应急抢险队', 'EMERGENCY_RESOURCE', 'GAS', 'CN', ['MP-002'], [0, 0, 0]),
  2021. ],
  2022. },
  2023. }
  2024. const allItems = Object.values(sections).flatMap((section) => section.items)
  2025. const countCategory = (category) => allItems.filter((entry) => entry.category === category).length
  2026. return {
  2027. ...envelope,
  2028. selectedFilters: { category: null, industry: null, area: null },
  2029. totals: blank
  2030. ? { emergencyResourceCount: 0, hazardSourceCount: 0, protectionTargetCount: 0, totalObjectCount: 0 }
  2031. : {
  2032. emergencyResourceCount: countCategory('EMERGENCY_RESOURCE'),
  2033. hazardSourceCount: countCategory('HAZARD_SOURCE'),
  2034. protectionTargetCount: countCategory('PROTECTION_TARGET'),
  2035. totalObjectCount: allItems.length,
  2036. },
  2037. sections,
  2038. // 分布结构是三类维度共用:行业分布值在 `industry`、区域分布在 `area`,`code` 一律 null。
  2039. industryDistribution: blank
  2040. ? []
  2041. : [
  2042. { category: null, industry: 'WATER_SUPPLY', area: null, count: 2 },
  2043. { category: null, industry: 'GAS', area: null, count: 1 },
  2044. { category: null, industry: 'DRAINAGE', area: null, count: 1 },
  2045. ],
  2046. areaDistribution: blank
  2047. ? []
  2048. : [
  2049. { category: null, industry: null, area: 'CN', count: 2 },
  2050. { category: null, industry: null, area: 'TC', count: 1 },
  2051. { category: null, industry: null, area: 'UNKNOWN', count: 1 },
  2052. ],
  2053. categoryDistribution: blank
  2054. ? []
  2055. : [
  2056. { category: 'EMERGENCY_RESOURCE', industry: null, area: null, count: 2 },
  2057. { category: 'HAZARD_SOURCE', industry: null, area: null, count: 1 },
  2058. { category: 'PROTECTION_TARGET', industry: null, area: null, count: 1 },
  2059. ],
  2060. eventSummary: blank
  2061. ? { warningCount: 0, alarmCount: 0, workOrderCount: 0 }
  2062. : {
  2063. warningCount: allItems.reduce((sum, entry) => sum + entry.eventAssociations.warningCount, 0),
  2064. alarmCount: allItems.reduce((sum, entry) => sum + entry.eventAssociations.alarmCount, 0),
  2065. workOrderCount: allItems.reduce((sum, entry) => sum + entry.eventAssociations.workOrderCount, 0),
  2066. },
  2067. mapFilter: { category: null, industry: null, area: null, objectCodes: [] },
  2068. excluded:
  2069. scenario === 'degraded'
  2070. ? { unknownCategoryCount: null }
  2071. : { unknownCategoryCount: 0, nonFormalIndustryCount: 0, duplicateObjectCount: 0 },
  2072. }
  2073. }
  2074. // ---------------------------------------------------------------- 运行监测三面板(票 18)
  2075. /**
  2076. * 票 18:运行监测模式三块面板的契约化样例。
  2077. *
  2078. * 字段名与嵌套形状照抄后端三个响应类(`CockpitMonitoringOverviewResponse` /
  2079. * `...DistributionResponse` / `...SituationResponse`)与它们的演示载荷
  2080. * `docs/cockpit/monitoring-{overview,distribution,operating-situation}-demo.html`,
  2081. * 所以适配层单测证明的是「转换吃得下真载荷」。
  2082. *
  2083. * 五处刻意照抄真实形状的**坑**(不照抄就会漏掉真机才暴露的问题):
  2084. * 1. **BigDecimal 在线上是字符串**:`onlineRate.value` 给 `"0.7778"`,逼适配层用 `numberish`;
  2085. * 2. **`district` 空值归一为字面量 `未分区`**(`CockpitMapSnapshotService` 的
  2086. * `UNASSIGNED_REGION`)—— 它是**真实取值**,界面要照实显示,不能读成"没有数据";
  2087. * 3. **状态分布给全六个状态**(含计数为 0 的),与后端 `for (status : values())` 一致;
  2088. * 4. **`metricFreshness` 不在本端点上**(见 `domain/monitoringPanels.js` 文件头第 ① 条):
  2089. * 本样例照真形状只给信封级 `updatedAt` + `freshness`,**不伪造一个逐设备采集时间**;
  2090. * 5. **在线率分母为 0 时**,后端回 `state:"EMPTY"` 且 `value:"0.0000"` —— 那个 0 是
  2091. * "没有分母"的占位,样例里专门给一个 `monitoring-no-devices` 场景把它逼出来。
  2092. */
  2093. /** 三面板信封公共段(后端的 `requestId/apiVersion/readOnly/displayName/timezone/freshness`)。 */
  2094. function monitoringEnvelope(displayName, status) {
  2095. return {
  2096. requestId: `mock-${displayName}`,
  2097. apiVersion: 'v1',
  2098. readOnly: true,
  2099. displayName,
  2100. timezone: 'Asia/Shanghai',
  2101. createdAt: status === 'EMPTY' ? null : '2026-09-01T08:00:00+08:00',
  2102. updatedAt: '2026-09-02T09:59:50+08:00',
  2103. freshness: {
  2104. status,
  2105. reason: status === 'CURRENT' ? 'READY' : status === 'EMPTY' ? 'NO_RESOLVED_DEVICES' : 'STALE_SAMPLES',
  2106. updatedAt: '2026-09-02T09:59:50+08:00',
  2107. serverUpdatedAt: '2026-09-02T10:00:00+08:00',
  2108. },
  2109. }
  2110. }
  2111. /** 该场景下信封的新鲜度(与票 17 的 `infraStatus` 同款口径)。 */
  2112. function monitoringStatus(scenario) {
  2113. if (scenario === 'empty') return 'EMPTY'
  2114. if (scenario === 'stale') return 'STALE'
  2115. return 'CURRENT'
  2116. }
  2117. /**
  2118. * 监测概览样例(票 18 验收第 1 条:监测点/设备规模、在线率、类型分布、最近采集时间)。
  2119. *
  2120. * 类型分布**照后端排序规则**给(服务按 `deviceCount` 降序、再按 `code`)——
  2121. * 界面若自作主张重排,真机走查那条「顺序 = 后端顺序」就会露馅。
  2122. */
  2123. function monitoringOverviewPayload(scenario, query) {
  2124. const status = monitoringStatus(scenario)
  2125. const envelope = monitoringEnvelope('监测概览', status)
  2126. // 票 18 的专项场景:**分母为 0**(后端回 `state=EMPTY` + `value="0.0000"`)。
  2127. // 与 `empty` 不同:信封不是 EMPTY、类型分布仍非空,只有在线率"不适用"——
  2128. // 这种形状最容易骗人(照 value 画就是"在线率 0.0%",而真相是"没有可算的设备")。
  2129. const noDevices = scenario === 'monitoring-no-devices'
  2130. const blank = status === 'EMPTY'
  2131. const blankRate = blank || noDevices
  2132. // **按请求的行业/设备类型真的过滤**(后端在服务端完成过滤,逐行读过
  2133. // `CockpitMonitoringOverviewService` 的三个 `selectedIndustry`/`deviceType` 判定)。
  2134. // 不这么做的话,走查里「切行业 → 面板数字变化」只能证明请求串里有参数,
  2135. // 而画面纹丝不动 —— 真机走查第一轮正是这样红了一条(假绿的反面:请求对了、界面没变)。
  2136. const industry = (query && query.industry) || ''
  2137. const deviceType = (query && query.deviceType) || ''
  2138. // 四个行业的设备账本(照后端:每台设备归一个行业与一个类型)。
  2139. // **票 18 更正**:`MANHOLE`(窨井)现已是第四个正式行业,样例必须带上它 ——
  2140. // 不带的话「窨井」筛选在界面上永远筛出空,看起来像坏了,而真相是样例没有该类数据。
  2141. // 类型码照后端真实形状:`equipment_type.id` 转字符串(后端测试里是 `"24"`)。
  2142. const allTypes = [
  2143. { deviceType: { code: 'GAS_SENSOR', name: '燃气浓度计' }, industry: 'GAS', deviceCount: 3, onlineCount: 3, offlineCount: 0, staleCount: 0 },
  2144. { deviceType: { code: 'WATER_SUPPLY_SENSOR', name: '供水压力计' }, industry: 'WATER_SUPPLY', deviceCount: 3, onlineCount: 3, offlineCount: 0, staleCount: 0 },
  2145. { deviceType: { code: 'SEWAGE_ENV', name: '污水环境监测' }, industry: 'DRAINAGE', deviceCount: 3, onlineCount: 2, offlineCount: 0, staleCount: 1 },
  2146. { deviceType: { code: '24', name: '窨井监测' }, industry: 'MANHOLE', deviceCount: 2, onlineCount: 2, offlineCount: 0, staleCount: 0 },
  2147. ]
  2148. // 监测点按行业分:GAS 2 个、WATER_SUPPLY 2 个、DRAINAGE 2 个、MANHOLE 1 个。
  2149. const pointsByIndustry = { GAS: 2, WATER_SUPPLY: 2, DRAINAGE: 2, MANHOLE: 1 }
  2150. const selectedTypes = allTypes.filter(
  2151. (row) => (!industry || row.industry === industry) && (!deviceType || row.deviceType.code === deviceType),
  2152. )
  2153. const types = blank || noDevices ? [] : selectedTypes
  2154. const equipmentCount = blank || noDevices ? 0 : selectedTypes.reduce((sum, row) => sum + row.deviceCount, 0)
  2155. const onlineCount = blankRate ? 0 : selectedTypes.reduce((sum, row) => sum + row.onlineCount, 0)
  2156. const offlineCount = blankRate ? 0 : selectedTypes.reduce((sum, row) => sum + row.offlineCount, 0)
  2157. const staleCount = blankRate ? 0 : selectedTypes.reduce((sum, row) => sum + row.staleCount, 0)
  2158. const denominator = onlineCount + offlineCount + staleCount
  2159. // 监测点数按行业求和;带 `deviceType` 时后端按类型过滤点位,这里同口径。
  2160. const monitoringPointCount =
  2161. blank || noDevices
  2162. ? noDevices
  2163. ? 2
  2164. : 0
  2165. : selectedTypes.reduce((sum, row) => sum + (pointsByIndustry[row.industry] || 0), 0)
  2166. const rate = denominator === 0 ? '0.0000' : (onlineCount / denominator).toFixed(4)
  2167. // 9 台里 8 台在线 1 台滞后 → 全量在线率 8/9(照后端口径:分母 = 在线 + 离线 + 滞后)。
  2168. return {
  2169. ...envelope,
  2170. range: { type: 'CURRENT_BASELINE' },
  2171. counts: blank
  2172. ? { monitoringPointCount: 0, equipmentCount: 0, facilityCount: 0, infrastructureFacilityCount: 0 }
  2173. : { monitoringPointCount, equipmentCount, facilityCount: 0, infrastructureFacilityCount: 0 },
  2174. status: blankRate
  2175. ? { onlineCount: 0, offlineCount: 0, staleCount: 0, unknownOrMissingCount: noDevices ? 2 : 0, denominator: 0 }
  2176. : { onlineCount, offlineCount, staleCount, unknownOrMissingCount: 0, denominator },
  2177. // BigDecimal 是字符串;分母为 0 时 state 是 EMPTY 且 value 是 "0.0000"(**不是**"在线率 0%")。
  2178. onlineRate: blankRate
  2179. ? { value: '0.0000', numerator: 0, denominator: 0, state: 'EMPTY', reason: 'NO_RESOLVED_DEVICES' }
  2180. : { value: rate, numerator: onlineCount, denominator, state: 'AVAILABLE', reason: null },
  2181. typeDistribution: types,
  2182. // 票 62 追加需求:逐设备台账 `devices[]`(与 `counts.equipmentCount` 同源同口径)。
  2183. // 用与类型分布同一份账本**逐台展开**——行数结构性等于 `equipmentCount`,
  2184. // 不是另写一组固定数字(那样两处读数早晚会漂)。
  2185. devices: blank || noDevices ? [] : overviewDevices(selectedTypes),
  2186. mapFilter: { industry: industry || null, deviceType: deviceType || null, pointCodes: blank ? [] : ['MP-001', 'MP-002', 'MP-003'], deviceCodes: [] },
  2187. // `degraded` 走字段缺失样例:剔除数缺失,适配层要记 missing 而不是当 0。
  2188. excluded:
  2189. scenario === 'degraded'
  2190. ? { unknownTypeCount: null }
  2191. : { unknownTypeCount: 0, typeKindMismatchCount: 0, nonFormalIndustryCount: 0 },
  2192. }
  2193. }
  2194. /**
  2195. * 逐设备台账样例(票 62 追加需求)。
  2196. *
  2197. * **从类型账本逐台展开**,不是另写一组固定行:后端 `build()` 里逐设备行与
  2198. * `counts.equipmentCount` 出自同一次遍历,mock 也照这个结构保证——行数恒等于
  2199. * `equipmentCount`(改账本就同时改两处,不会漂)。
  2200. *
  2201. * 每行的状态按该类型的 online/offline/stale 配比逐台给出(前 N 台在线、接着离线、
  2202. * 再接着滞后),所以「设备台账」在 mock 上能看到三种状态并存,而不是清一色在线。
  2203. */
  2204. function overviewDevices(selectedTypes) {
  2205. const devices = []
  2206. for (const row of selectedTypes || []) {
  2207. const industry = row.industry
  2208. const typeCode = row.deviceType.code
  2209. const typeName = row.deviceType.name
  2210. for (let index = 0; index < row.deviceCount; index += 1) {
  2211. const seq = String(index + 1).padStart(2, '0')
  2212. const deviceCode = `EQ-${industry}-${typeCode}-${seq}`
  2213. const state = index < row.onlineCount ? 'ONLINE'
  2214. : index < row.onlineCount + row.offlineCount ? 'OFFLINE'
  2215. : 'STALE'
  2216. devices.push({
  2217. deviceCode,
  2218. deviceName: `${typeName}-${seq}`,
  2219. deviceType: { code: typeCode, name: typeName },
  2220. industry,
  2221. monitoringState: state,
  2222. // 前半数设备挂到监测点上,后半数留空 —— 台账里"未关联点位"是真实取值,
  2223. // 界面必须照实说(不拿空串冒充点位编码)。
  2224. monitoringPointCode: index % 2 === 0 ? `MP-${industry}-${seq}` : null,
  2225. sampledAt: '2026-09-02T09:59:00+08:00',
  2226. createdAt: '2026-08-31T08:00:00+08:00',
  2227. })
  2228. }
  2229. }
  2230. return devices
  2231. }
  2232. /** 一个分布 marker(监测点或未关联设备;两族字段名只差 `point*` / `device*`)。 */
  2233. function distributionPoint(pointCode, pointName, district, industry, typeCode, typeName, pointStatus, pointCodes, coord) {
  2234. return {
  2235. pointCode,
  2236. pointName,
  2237. createdAt: '2026-08-31T08:00:00+08:00',
  2238. districtName: district === null ? '未分区' : ['城南', '城北', '太常'][district],
  2239. district,
  2240. industry,
  2241. deviceType: { code: typeCode, name: typeName },
  2242. pointStatus,
  2243. statusReasons: pointStatus === 'ALARM' ? [`${pointCodes[0] || 'EQ'} 报警`] : [],
  2244. ...coord,
  2245. }
  2246. }
  2247. /**
  2248. * 监测分布样例(票 18 验收第 2 条)。
  2249. *
  2250. * **分页窗口横跨「监测点 + 未关联设备」一条总序列**(与 `map-snapshot` 同一套后端语义):
  2251. * 这里 6 个监测点 + 2 台未关联设备 = 8 条,页大小由请求给(走查现场可改),
  2252. * 所以「还有下一页」在 mock 上真的能演示(Q4 裁定台账按端点 `pagination` 渐进加载)。
  2253. *
  2254. * 三份分布与状态计数**都从过滤后的集合现算**(照抄后端 `build()` 的顺序:
  2255. * 先按筛选挑 marker,再聚合,最后切片分页)。为什么不写死一组数字:
  2256. * 面板的分布若与筛选无关,「筛选真的作用到面板数据上了吗」这条断言就退化成在看请求串 ——
  2257. * 筛错了、或者根本没传,画面都一样,是**假绿**(票 08 踩过同一个坑)。
  2258. */
  2259. function monitoringDistributionPayload(scenario, query, overrides = {}) {
  2260. const status = monitoringStatus(scenario)
  2261. const envelope = monitoringEnvelope('监测分布', status)
  2262. const blank = status === 'EMPTY'
  2263. const filters = {
  2264. industry: (query && query.industry) || '',
  2265. district: (query && query.district) || '',
  2266. // 票 37:类型筛选真的过滤(后端 `matchesFilters` 逐行读过:类型码精确匹配,
  2267. // 不可推导的对象在带该筛选时被排除)——不这么做,「点类型行 → 分布变窄」就是假绿。
  2268. deviceType: (query && query.deviceType) || '',
  2269. pointStatus: (query && query.pointStatus) || '',
  2270. }
  2271. const pointList = blank
  2272. ? []
  2273. : [
  2274. distributionPoint('MP-001', '城南测试监测点', 0, 'WATER_SUPPLY', 'WATER_SUPPLY_SENSOR', '供水压力计', 'NORMAL', [], { longitude: 110.39832789395186, latitude: 28.434456975811777, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2275. distributionPoint('MP-002', '太常测试监测点', 2, 'GAS', 'GAS_SENSOR', '燃气浓度计', 'ALARM', ['EQ-ASSOC-001'], { longitude: 110.36299369455823, latitude: 28.452196938060194, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2276. // 空区域归一为字面量「未分区」——真实取值,界面必须照实显示。
  2277. distributionPoint('MP-003', '污水排口监测点', null, 'DRAINAGE', 'SEWAGE_ENV', '污水环境监测', 'WARNING', ['EQ-FREE-003'], { longitude: 110.143, latitude: 28.454, coordinateValidation: { state: 'UNVERIFIED', reason: 'UNVERIFIED_COORDINATE', renderable: false, crs: 'WGS84' } }),
  2278. distributionPoint('MP-004', '排水泵站监测点', 1, 'DRAINAGE', 'SEWAGE_ENV', '污水环境监测', 'NORMAL', [], { longitude: 110.144, latitude: 28.455, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2279. distributionPoint('MP-005', '供水二厂监测点', 0, 'WATER_SUPPLY', 'WATER_SUPPLY_SENSOR', '供水压力计', 'OFFLINE', [], { longitude: 110.145, latitude: 28.456, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2280. distributionPoint('MP-006', '预留无设备监测点', 2, 'GAS', 'GAS_SENSOR', '燃气浓度计', 'EMPTY', [], { longitude: 110.146, latitude: 28.457, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2281. // 票 18 更正:窨井(`MANHOLE`)是第四个正式行业,样例带上它 ——
  2282. // 类型码照后端真实形状(`equipment_type.id` 转字符串)。
  2283. distributionPoint('MP-007', '窨井监测点', 1, 'MANHOLE', '24', '窨井监测', 'NORMAL', [], { longitude: 110.147, latitude: 28.458, coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' } }),
  2284. ]
  2285. const equipmentList = blank
  2286. ? []
  2287. : [
  2288. {
  2289. deviceCode: 'EQ-FREE-002',
  2290. deviceName: '智能窨井-002',
  2291. createdAt: null,
  2292. district: null, districtName: '未分区',
  2293. industry: null,
  2294. // 类型不可推导时后端给 null(默认不排除对象)——界面据此照实说"类型未知"。
  2295. deviceType: null,
  2296. pointStatus: 'NORMAL',
  2297. statusReasons: [],
  2298. longitude: 110.155,
  2299. latitude: 28.459,
  2300. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  2301. },
  2302. {
  2303. deviceCode: 'EQ-FREE-004',
  2304. deviceName: '零坐标设备-004',
  2305. createdAt: null,
  2306. district: 2, districtName: '太常',
  2307. industry: 'GAS',
  2308. deviceType: { code: 'GAS_SENSOR', name: '燃气浓度计' },
  2309. pointStatus: 'OFFLINE',
  2310. statusReasons: [],
  2311. longitude: 0,
  2312. latitude: 0,
  2313. coordinateValidation: { state: 'INVALID', reason: 'ZERO_COORDINATE', renderable: false, crs: 'WGS84' },
  2314. },
  2315. ]
  2316. // 后端 `matchesMarker()`:行业与状态按值比对,区域同样(`未分区` 是真实取值)。
  2317. // 票 37:`deviceType` 按 **marker 自身类型码**精确匹配(本端点服务逐行读过:
  2318. // `isBlank(deviceType) || type.code === deviceType`——与 map-snapshot 的设备级 OR 归并
  2319. // 是两条路径);类型不可推导(`deviceType` 为 null)的对象在带该筛选时被排除(后端同款)。
  2320. const selected = [...pointList, ...equipmentList].filter((item) => {
  2321. if (filters.industry && item.industry !== filters.industry) return false
  2322. if (filters.pointStatus && !matchesStatusFilter(item, filters.pointStatus.split(','))) return false
  2323. if (filters.district && (normalizedDistrict(item.district)) !== filters.district) return false
  2324. if (filters.deviceType) {
  2325. if (!item.deviceType || item.deviceType.code !== filters.deviceType) return false
  2326. }
  2327. return true
  2328. })
  2329. const points = selected.filter((item) => 'pointCode' in item)
  2330. const devices = selected.filter((item) => 'deviceCode' in item)
  2331. /** 一条分布行(按给定维度键聚合;`pointCount` 只数监测点、`deviceCount` 只数未关联设备)。 */
  2332. const distributionRow = (key, extra = {}) => {
  2333. const bucket = selected.filter((item) => key(item) === extra.value)
  2334. const counts = { alarm: 0, warning: 0, workOrder: 0, normal: 0, offline: 0, empty: 0 }
  2335. for (const item of bucket) {
  2336. const map = { ALARM: 'alarm', WARNING: 'warning', WORK_ORDER: 'workOrder', NORMAL: 'normal', OFFLINE: 'offline', EMPTY: 'empty' }
  2337. const slot = map[item.pointStatus]
  2338. if (slot) counts[slot] += 1
  2339. }
  2340. return {
  2341. ...extra.build,
  2342. pointCount: bucket.filter((item) => 'pointCode' in item).length,
  2343. deviceCount: bucket.filter((item) => 'deviceCode' in item).length,
  2344. statusCounts: counts,
  2345. }
  2346. }
  2347. // 分页:窗口横跨两类对象(一条总序列)。
  2348. const page = Number(query && query.page) > 0 ? Number(query.page) : 1
  2349. // 页大小的**默认值照后端**(500)。但那样 6 个点的样例一页就到底,
  2350. // 「台账自动渐进装载」这条验收在真机上永远演示不出来 —— 所以走查可用
  2351. // `window.__COCKPIT_MOCK_MONITORING__ = { pageSize: 3 }` 现场压小页大小
  2352. // (与票 08 地图摘要的 `__COCKPIT_MOCK_MAP__` 同一套手法)。
  2353. const fallbackPageSize = Number(overrides.pageSize) > 0 ? Number(overrides.pageSize) : 500
  2354. const pageSize = Number(query && query.pageSize) > 0 ? Number(query.pageSize) : fallbackPageSize
  2355. // 票 62(执行票同期后端已补齐回显):快照 token 与 map-snapshot 同一套纪律——
  2356. // · 第 1 页可不带,后端开新快照并**在响应里回显**;
  2357. // · 第 2 页起**必须**带,且要与当前快照一致,否则按后端原样抛(400 / SNAPSHOT_EXPIRED)。
  2358. // 注意 `query` 是**已解析的参数对象**(`context.query`),不是原始路径串。
  2359. const snapshotAt = (query && query.snapshotAt) || ''
  2360. const snapshotToken = overrides.snapshotAt || SNAPSHOT_AT
  2361. if (page > 1 && !snapshotAt) {
  2362. // 后端对「第 2 页没带快照」回 400 + INVALID_REQUEST。mock 侧统一出口只认
  2363. // `REQUEST_REASON` 白名单,所以这里落成 `unavailable`(断言看的是「请求被拒、
  2364. // 台账停链且不回滚已装载内容」,不是具体原因码)。
  2365. const error = new Error('mock: 监测分布第 2 页起必须带 snapshotAt')
  2366. error.reason = REQUEST_REASON.UNAVAILABLE
  2367. throw error
  2368. }
  2369. if (snapshotAt && snapshotAt !== snapshotToken) {
  2370. const error = new Error('mock: 监测分布快照已失效')
  2371. error.reason = REQUEST_REASON.SNAPSHOT_EXPIRED
  2372. throw error
  2373. }
  2374. const from = Math.max(0, (page - 1) * pageSize)
  2375. const to = from + pageSize
  2376. const slice = selected.slice(from, to)
  2377. // 三份分布(**全量口径**:先聚合完再切片,所以与页码无关,只与筛选有关)。
  2378. const districtKeys = [...new Set(selected.map((item) => normalizedDistrict(item.district)))].sort()
  2379. const industryKeys = ['GAS', 'WATER_SUPPLY', 'DRAINAGE', 'MANHOLE'].filter((code) => selected.some((item) => item.industry === code))
  2380. const typeKeys = [...new Map(selected.filter((item) => item.deviceType).map((item) => [item.deviceType.code, item.deviceType])).entries()]
  2381. return {
  2382. ...envelope,
  2383. range: { type: 'CURRENT_BASELINE' },
  2384. // 票 62:快照标记回显(与真实后端执行票同期补齐的字段同名同义),
  2385. // 调用方第 2 页起原样回带。
  2386. snapshotAt: snapshotToken,
  2387. districtDistribution: districtKeys.map((district) => distributionRow((item) => normalizedDistrict(item.district), { value: district, build: { district: district === 'UNASSIGNED' ? null : Number(district), districtName: district === 'UNASSIGNED' ? '未分区' : ['城南', '城北', '太常'][Number(district)] } })),
  2388. industryDistribution: industryKeys.map((industry) => distributionRow((item) => item.industry, { value: industry, build: { industry } })),
  2389. deviceTypeDistribution: typeKeys.map(([code, type]) =>
  2390. distributionRow((item) => (item.deviceType ? item.deviceType.code : null), {
  2391. value: code,
  2392. build: { deviceType: type, industry: (selected.find((item) => item.deviceType && item.deviceType.code === code) || {}).industry || null },
  2393. }),
  2394. ),
  2395. // 状态分布:**全六个状态都给**(含 0),与后端 `for (status : values())` 一致。
  2396. pointStatusDistribution: ['ALARM', 'WARNING', 'WORK_ORDER', 'NORMAL', 'OFFLINE', 'EMPTY'].map((code) => ({
  2397. status: code,
  2398. count: selected.filter((item) => item.pointStatus === code).length,
  2399. })),
  2400. mapFilter: {
  2401. industry: filters.industry || null,
  2402. deviceType: filters.deviceType || null,
  2403. pointStatus: filters.pointStatus || null,
  2404. district: filters.district && filters.district !== 'UNASSIGNED' ? Number(filters.district) : null,
  2405. districtFilter: !filters.district ? 'NONE' : filters.district === 'UNASSIGNED' ? 'UNASSIGNED' : 'ASSIGNED',
  2406. pointCodes: points.map((item) => item.pointCode),
  2407. deviceCodes: devices.map((item) => item.deviceCode),
  2408. },
  2409. pagination: { page, pageSize, total: selected.length, totalPages: selected.length ? Math.ceil(selected.length / pageSize) : 0, hasMore: to < selected.length },
  2410. monitoringPoints: slice.filter((item) => 'pointCode' in item),
  2411. unassociatedEquipment: slice.filter((item) => 'deviceCode' in item),
  2412. excluded:
  2413. scenario === 'degraded'
  2414. ? { unknownTypeCount: null }
  2415. : { unknownTypeCount: 0, typeKindMismatchCount: 0, nonFormalIndustryCount: 0, invalidCoordinateCount: selected.filter((item) => item.coordinateValidation && !item.coordinateValidation.renderable).length },
  2416. }
  2417. }
  2418. /** 趋势桶:按小时铺一串(照后端「业务时区小时分桶」的形状,键是带偏移的 ISO 串)。 */
  2419. function hourlyTrend(counts, startHour = 1) {
  2420. return counts.map((count, index) => ({
  2421. bucketStart: `2026-09-02T${String(startHour + index).padStart(2, '0')}:00:00+08:00`,
  2422. count,
  2423. }))
  2424. }
  2425. /**
  2426. * 运行概况样例(票 18 验收第 3 条:事件趋势、离线设备、异常态势)。
  2427. *
  2428. * 四处照后端语义:
  2429. * 1. **预警与报警分成两条趋势**(服务注释原文:warnings feed warningTrend only,
  2430. * alarms feed alarmTrend only)—— 样例里两条形状不同,合并就会当场露馅;
  2431. * 2. `range` 回显实际生效窗口(服务回 `TREND_WINDOW` + start/end);
  2432. * 3. `metricStatusDistribution` 给全六态(含 0);
  2433. * 4. `abnormalEquipment` 只装**异常**设备(服务定义 WARNING/ALARM/EXPIRED/OFFLINE 四态)——
  2434. * 所以"离线设备清单"是它的子集,界面据此分开说。
  2435. * 票 37:`deviceType` 生效时 3/4 两段(六态计数、异常清单、行业覆盖)一并收窄(假绿防线)。
  2436. */
  2437. function monitoringSituationPayload(scenario, query) {
  2438. const status = monitoringStatus(scenario)
  2439. const envelope = monitoringEnvelope('运行概况', status)
  2440. const blank = status === 'EMPTY'
  2441. // 票 37:`deviceType` 真的过滤异常清单(后端服务同款:类型码精确匹配),
  2442. // 否则「点类型行 → 运行概况变窄」也是假绿。
  2443. const deviceType = (query && query.deviceType) || ''
  2444. // 窗口照后端回显:显式区间原样带出(`resolveWindow`),不传时是最近 24 小时。
  2445. const range = {
  2446. type: 'TREND_WINDOW',
  2447. startTime: (query && query.startTime) || '2026-09-01T10:00:00+08:00',
  2448. endTime: (query && query.endTime) || '2026-09-02T10:00:00+08:00',
  2449. }
  2450. const abnormal = blank
  2451. ? []
  2452. : [
  2453. {
  2454. deviceCode: 'EQ-FREE-001',
  2455. deviceName: '供水压力计-001',
  2456. createdAt: null,
  2457. deviceType: { code: 'WATER_SUPPLY_SENSOR', name: '供水压力计' },
  2458. industry: 'WATER_SUPPLY',
  2459. district: 0, districtName: '城南',
  2460. abnormalType: 'ALARM',
  2461. status: 'ALARM',
  2462. statusReasons: ['压力超高'],
  2463. longitude: 110.141,
  2464. latitude: 28.452,
  2465. coordinateValidation: { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' },
  2466. },
  2467. {
  2468. // 离线设备:它是异常清单的一个子集,界面据此分开报"离线几台"与"异常清单里有什么"。
  2469. deviceCode: 'EQ-FREE-004',
  2470. deviceName: '零坐标设备-004',
  2471. createdAt: null,
  2472. deviceType: { code: 'GAS_SENSOR', name: '燃气浓度计' },
  2473. industry: 'GAS',
  2474. district: 2, districtName: '太常',
  2475. abnormalType: 'OFFLINE',
  2476. status: 'OFFLINE',
  2477. statusReasons: [],
  2478. longitude: 0,
  2479. latitude: 0,
  2480. coordinateValidation: { state: 'INVALID', reason: 'ZERO_COORDINATE', renderable: false, crs: 'WGS84' },
  2481. },
  2482. ].filter((item) => !deviceType || (item.deviceType && item.deviceType.code === deviceType))
  2483. return {
  2484. ...envelope,
  2485. range,
  2486. metricStatusDistribution: blank
  2487. ? [
  2488. { status: 'NORMAL', count: 0 },
  2489. { status: 'WARNING', count: 0 },
  2490. { status: 'ALARM', count: 0 },
  2491. { status: 'EXPIRED', count: 0 },
  2492. { status: 'OFFLINE', count: 0 },
  2493. { status: 'UNKNOWN', count: 0 },
  2494. ]
  2495. : [
  2496. // 票 37:`deviceType` 生效时六态计数随筛选收窄(与 `abnormalEquipment` 同一集合),
  2497. // 不收窄的话「异常统计」与"清单条数"会对不上 —— 又一处假绿。
  2498. ...(deviceType && deviceType !== 'GAS_SENSOR'
  2499. ? []
  2500. : [
  2501. { status: 'NORMAL', count: 6 },
  2502. { status: 'WARNING', count: 1 },
  2503. { status: 'ALARM', count: 1 },
  2504. { status: 'EXPIRED', count: 0 },
  2505. { status: 'OFFLINE', count: 1 },
  2506. { status: 'UNKNOWN', count: 0 },
  2507. ]),
  2508. ...(deviceType === 'GAS_SENSOR'
  2509. ? [
  2510. { status: 'NORMAL', count: 0 },
  2511. { status: 'WARNING', count: 0 },
  2512. { status: 'ALARM', count: 0 },
  2513. { status: 'EXPIRED', count: 0 },
  2514. { status: 'OFFLINE', count: 1 },
  2515. { status: 'UNKNOWN', count: 0 },
  2516. ]
  2517. : []),
  2518. ],
  2519. // 两条趋势形状不同(预警少、报警多),合并成一条就会露馅。
  2520. warningTrend: blank ? [] : hourlyTrend([0, 1, 0, 0, 2, 1, 0, 0]),
  2521. alarmTrend: blank ? [] : hourlyTrend([1, 0, 3, 2, 0, 1, 4, 2]),
  2522. industryCoverage: blank
  2523. ? []
  2524. : [
  2525. // 票 37:类型生效时行业覆盖随之收窄(本端点唯一类型事实归 GAS_SENSOR)。
  2526. ...(deviceType && deviceType !== 'GAS_SENSOR'
  2527. ? []
  2528. : [{ industry: 'GAS', deviceCount: 3, abnormalCount: 1, statusCounts: statusCountsOf(2, 0, 0, 0, 1, 0) }]),
  2529. ...(!deviceType || deviceType === 'WATER_SUPPLY_SENSOR'
  2530. ? [{ industry: 'WATER_SUPPLY', deviceCount: 3, abnormalCount: 1, statusCounts: statusCountsOf(2, 0, 1, 0, 0, 0) }]
  2531. : []),
  2532. ...(!deviceType ? [{ industry: 'DRAINAGE', deviceCount: 3, abnormalCount: 1, statusCounts: statusCountsOf(2, 1, 0, 0, 0, 0) }] : []),
  2533. ],
  2534. abnormalEquipment: abnormal,
  2535. mapFilter: {
  2536. industry: (query && query.industry) || null,
  2537. deviceType: deviceType || null,
  2538. deviceCodes: abnormal.filter((item) => item.coordinateValidation.renderable).map((item) => item.deviceCode),
  2539. },
  2540. pagination: { page: 1, pageSize: 100, total: abnormal.length, totalPages: abnormal.length ? 1 : 0, hasMore: false },
  2541. excluded:
  2542. scenario === 'degraded'
  2543. ? { unknownTypeCount: null }
  2544. : { unknownTypeCount: 0, typeKindMismatchCount: 0, nonFormalIndustryCount: 0, invalidCoordinateCount: 1 },
  2545. }
  2546. }
  2547. /** 运行概况 `industryCoverage.statusCounts` 的六态构造(与 `MetricStatusCount` 同序)。 */
  2548. function statusCountsOf(normal, warning, alarm, expired, offline, unknown) {
  2549. return { normal, warning, alarm, expired, offline, unknown }
  2550. }
  2551. // ================================================================ 票 20:总体概览三端点
  2552. // ================================================================ 票 05–08:总体概览四模块端点
  2553. /**
  2554. * 四模块信封(规格 §0:`requestId/apiVersion/readOnly/timezone/updatedAt/freshness`)。
  2555. *
  2556. * 空态要能带固定行:四模块的空态是「freshness=EMPTY + 仍回 4 类型/3 片区/4 等级/7 天」,
  2557. * 前端靠它画「无数据 0」(规格 §6.7 的例外)。所以这里显式给 `status/reason`。
  2558. */
  2559. function overviewModulesEnvelope(status, updatedAt = SNAPSHOT_AT, reason = null) {
  2560. return {
  2561. requestId: 'mock-overview-modules',
  2562. apiVersion: 'v1',
  2563. readOnly: true,
  2564. timezone: 'Asia/Shanghai',
  2565. updatedAt: updatedAt || null,
  2566. freshness: { status, reason, updatedAt: updatedAt || null, serverUpdatedAt: SNAPSHOT_AT },
  2567. }
  2568. }
  2569. /**
  2570. * `/overview/perception`(票 05;规格 §2)。
  2571. *
  2572. * success 取**后端实测真值**(10 台 / 在线 3 / 离线 7 / 在线率 0.3000;类型 3·5·0·1;
  2573. * 片区 6·3·1;excluded.unknownTypeCount = 1 是那台悬空类型设备,如实保留)。
  2574. * empty **仍回 4 类型 + 3 片区行(全 0)**:固定卡必须画 0,不是"无数据"。
  2575. */
  2576. function overviewPerceptionPayload(scenario) {
  2577. const types = [
  2578. { code: '1', name: '供水设备', deviceCount: 3, onlineCount: 1, offlineCount: 2, monitoringContent: '压力 / 流量 / 漏失', monitoringContentSource: 'DERIVED' },
  2579. { code: '2', name: '排水设备', deviceCount: 5, onlineCount: 2, offlineCount: 3, monitoringContent: '液位 / 流量 / 内涝', monitoringContentSource: 'DERIVED' },
  2580. { code: '3', name: '燃气设备', deviceCount: 0, onlineCount: 0, offlineCount: 0, monitoringContent: '可燃气体 / 压力', monitoringContentSource: 'FALLBACK' },
  2581. { code: '4', name: '窨井设备', deviceCount: 1, onlineCount: 0, offlineCount: 1, monitoringContent: '井盖状态 / 液位', monitoringContentSource: 'FALLBACK' },
  2582. ]
  2583. const districts = [
  2584. { district: 0, name: '城南', deviceCount: 6 },
  2585. { district: 1, name: '城北', deviceCount: 3 },
  2586. { district: 2, name: '太常', deviceCount: 1 },
  2587. ]
  2588. if (scenario === 'empty') {
  2589. return {
  2590. ...overviewModulesEnvelope('EMPTY', null, 'NO_DEVICES'),
  2591. totals: { deviceCount: 0, onlineCount: 0, offlineCount: 0, noStatusCount: 0, onlineRate: { value: '0', numerator: 0, denominator: 0, state: 'EMPTY', reason: 'NO_DEVICES' } },
  2592. byType: types.map((row) => ({ ...row, deviceCount: 0, onlineCount: 0, offlineCount: 0 })),
  2593. byDistrict: districts.map((row) => ({ ...row, deviceCount: 0 })),
  2594. excluded: { unknownTypeCount: 0, unassignedDistrictCount: 0 },
  2595. }
  2596. }
  2597. if (scenario === 'degraded') {
  2598. // 缺监测内容小字与 excluded 段:卡片仍画(计数在),小字不画;界面不伪造小字。
  2599. return {
  2600. ...overviewModulesEnvelope('CURRENT'),
  2601. totals: { deviceCount: 10, onlineCount: 3, offlineCount: 7, noStatusCount: 0, onlineRate: { value: '0.3000', numerator: 3, denominator: 10, state: 'AVAILABLE', reason: null } },
  2602. byType: types.map(({ monitoringContent, monitoringContentSource, ...row }) => row),
  2603. byDistrict: districts,
  2604. }
  2605. }
  2606. return {
  2607. ...overviewModulesEnvelope('CURRENT'),
  2608. totals: { deviceCount: 10, onlineCount: 3, offlineCount: 7, noStatusCount: 0, onlineRate: { value: '0.3000', numerator: 3, denominator: 10, state: 'AVAILABLE', reason: null } },
  2609. byType: types,
  2610. byDistrict: districts,
  2611. excluded: { unknownTypeCount: 1, unassignedDistrictCount: 0 },
  2612. }
  2613. }
  2614. /**
  2615. * `/overview/pipe-network`(票 06;规格 §3)。success 用实测真值(6762 条 / 78.55 km)。
  2616. * empty 回 `pipeCount=0` 且固定 3 行 0 —— 面板按空态画占位,**不画假环**。
  2617. */
  2618. function overviewPipeNetworkPayload(scenario) {
  2619. const types = [
  2620. { code: 'WATER_PIPE', name: '供水管道', count: 2489, lengthKm: '19.10', ratio: '0.3681' },
  2621. { code: 'DRAINAGE_PIPE', name: '排水管道', count: 3574, lengthKm: '52.26', ratio: '0.5285' },
  2622. { code: 'GAS_PIPE', name: '燃气管道', count: 699, lengthKm: '7.18', ratio: '0.1034' },
  2623. ]
  2624. if (scenario === 'empty') {
  2625. return {
  2626. ...overviewModulesEnvelope('EMPTY', null, 'NO_PIPES'),
  2627. totals: { pipeCount: 0, lengthKm: '0.00' },
  2628. byPipeType: types.map((row) => ({ ...row, count: 0, lengthKm: '0.00', ratio: '0' })),
  2629. excluded: { unclassifiedCount: 0 },
  2630. state: 'EMPTY',
  2631. reason: 'NO_PIPES',
  2632. }
  2633. }
  2634. return {
  2635. ...overviewModulesEnvelope('CURRENT'),
  2636. totals: { pipeCount: 6762, lengthKm: '78.55' },
  2637. byPipeType: types,
  2638. excluded: { unclassifiedCount: 0 },
  2639. state: 'AVAILABLE',
  2640. reason: null,
  2641. }
  2642. }
  2643. /**
  2644. * `/overview/warning-study`(票 07;规格 §4)。
  2645. *
  2646. * success:今日 5 / 未解除 18(PENDING 11 / PROCESSING 5 / HANDLED 2),
  2647. * 分级 9·6·2·1(**和 = 18** —— 规格示例曾把全量 42 的分级抄进来,是错的)。
  2648. * 类型排行的 `code` 取本地事件族同值,使「点击筛选」在 mock 上真的命中;
  2649. * 真实后端返回 `WARN-*` 码,前端按精确 code 匹配,不匹配时如实提示覆盖范围(G11)。
  2650. */
  2651. function overviewWarningStudyPayload(scenario) {
  2652. const levels = [
  2653. { level: 1, name: '一级预警', count: 9 },
  2654. { level: 2, name: '二级预警', count: 6 },
  2655. { level: 3, name: '三级预警', count: 2 },
  2656. { level: 4, name: '四级预警', count: 1 },
  2657. ]
  2658. if (scenario === 'empty') {
  2659. return {
  2660. ...overviewModulesEnvelope('EMPTY', null, 'NO_WARNINGS'),
  2661. today: { newCount: 0, yesterdayCount: 0, delta: 0 },
  2662. unresolved: { count: 0, statuses: { PENDING: 0, RECEIVED: 0, PROCESSING: 0, HANDLED: 0 } },
  2663. byLevel: levels.map((row) => ({ ...row, count: 0 })),
  2664. typeRanking: { rangeDays: 30, total: 0, top: [] },
  2665. }
  2666. }
  2667. if (scenario === 'degraded') {
  2668. // 缺排行段:等级卡照画,排行整块不画(不伪造榜单)。
  2669. return {
  2670. ...overviewModulesEnvelope('CURRENT'),
  2671. today: { newCount: 5, yesterdayCount: 0, delta: 5 },
  2672. unresolved: { count: 18, statuses: { PENDING: 11, RECEIVED: 0, PROCESSING: 5, HANDLED: 2 } },
  2673. byLevel: levels,
  2674. }
  2675. }
  2676. return {
  2677. ...overviewModulesEnvelope('CURRENT'),
  2678. today: { newCount: 5, yesterdayCount: 0, delta: 5 },
  2679. unresolved: { count: 18, statuses: { PENDING: 11, RECEIVED: 0, PROCESSING: 5, HANDLED: 2 } },
  2680. byLevel: levels,
  2681. // 排行**列出全部类型**且与 total 对得上(维护者 2026-10-26:页面写「共27起」而三行只凑出 23 起)。
  2682. // 下面 count 之和刻意等于 total(42) —— mock 也要自洽,否则走查看不出「对不上」这类问题。
  2683. typeRanking: {
  2684. rangeDays: 30,
  2685. total: 42,
  2686. top: [
  2687. { code: 'GAS_CONCENTRATION', name: '燃气浓度预警', count: 14 },
  2688. { code: 'WATER_PRESSURE', name: '供水压力预警', count: 9 },
  2689. { code: 'SEWAGE_CONCENTRATION', name: '污水 COD 预警', count: 6 },
  2690. { code: 'WATER_FLOW', name: '供水流量预警', count: 5 },
  2691. { code: 'MANHOLE_COVER', name: '井盖状态预警', count: 4 },
  2692. { code: 'SEWAGE_LEVEL', name: '排水水位预警', count: 4 },
  2693. ],
  2694. },
  2695. }
  2696. }
  2697. /**
  2698. * `/overview/alarm-disposal`(票 08;规格 §5)。success 用**受控样本**(后端实测:
  2699. * 已转 2 / 未转 0、处置率 1/2、平均响应 30.5h、平均处置 219.2h、等级 4 级 2 条)。
  2700. *
  2701. * **7 日折线全 0 是真实形态,不是样例偷懒**(维护者 2026-10-23 反馈第 2 条复核):
  2702. * 库里那 2 条报警的 create_time 是 2026-10-12/13,而窗口是「今天及前 6 天」;
  2703. * 实测全库 90 条报警只分布在 10-10 / 10-12 / 10-16 三天,窗口内三种口径(audit_status、
  2704. * alarm_status、不过滤)都是 0 条。所以「已转 2 + 四级 2」与「折线 0」是**同时成立**的:
  2705. * 上方读数是全量、折线是窗口内新增。面板用 `trendCaliberNote()` 把这层口径写明。
  2706. *
  2707. * empty:固定 4 等级 0 行 + 7 天全 0 点,比例/时长 EMPTY(界面显示占位符,不是 0%)。
  2708. */
  2709. function overviewAlarmDisposalPayload(scenario) {
  2710. const levels = [
  2711. { level: 1, name: '一级报警', count: 0 },
  2712. { level: 2, name: '二级报警', count: 0 },
  2713. { level: 3, name: '三级报警', count: 0 },
  2714. { level: 4, name: '四级报警', count: 2 },
  2715. ]
  2716. const dates = ['2026-10-16', '2026-10-17', '2026-10-18', '2026-10-19', '2026-10-20', '2026-10-21', '2026-10-22']
  2717. // 每天两个读数(后端新字段):count = 当天新增;unhandledTotal = 截至当天未处理的累计。
  2718. // 样例取真实库形态:窗口内当天新增全 0(库里最新一条报警在 10-16),总未处理恒为 2。
  2719. // 不补 non-zero 的假新增 —— mock 要与真实数据同形,否则走查看不出「为什么折线贴底」。
  2720. const trend = (last = 0) =>
  2721. dates.map((date, index) => ({
  2722. date,
  2723. count: index === dates.length - 1 ? last : 0,
  2724. unhandledTotal: 2,
  2725. }))
  2726. if (scenario === 'empty') {
  2727. return {
  2728. ...overviewModulesEnvelope('EMPTY', null, 'NO_ALARMS'),
  2729. today: { newCount: 0, yesterdayCount: 0, delta: 0 },
  2730. workOrderConversion: { convertedCount: 0, unconvertedCount: 0, totalCount: 0 },
  2731. disposal: {
  2732. rate: { numerator: 0, denominator: 0, value: '0', state: 'EMPTY', reason: 'NO_ALARMS', basis: 'CLOSED_WORK_ORDERS_OVER_ALL_ALARMS' },
  2733. avgResponseDuration: { value: null, unit: 'HOURS', sampleCount: 0, invalidSampleCount: 0, state: 'EMPTY', reason: 'NO_RESPONSE_LOGS' },
  2734. avgDisposalDuration: { value: null, unit: 'HOURS', sampleCount: 0, invalidSampleCount: 0, state: 'EMPTY', reason: 'NO_DISPOSAL_LOGS' },
  2735. },
  2736. byLevel: levels.map((row) => ({ ...row, count: 0 })),
  2737. sevenDayTrend: trend(0),
  2738. }
  2739. }
  2740. if (scenario === 'degraded') {
  2741. // 缺两个时长段:按"无有效样本"显示占位符,不显示 0 小时。
  2742. return {
  2743. ...overviewModulesEnvelope('CURRENT'),
  2744. today: { newCount: 0, yesterdayCount: 0, delta: 0 },
  2745. workOrderConversion: { convertedCount: 2, unconvertedCount: 0, totalCount: 2 },
  2746. disposal: { rate: { numerator: 1, denominator: 2, value: '0.5000', state: 'AVAILABLE', reason: null, basis: 'CLOSED_WORK_ORDERS_OVER_ALL_ALARMS' } },
  2747. byLevel: levels,
  2748. sevenDayTrend: trend(0),
  2749. }
  2750. }
  2751. return {
  2752. ...overviewModulesEnvelope('CURRENT'),
  2753. today: { newCount: 0, yesterdayCount: 0, delta: 0 },
  2754. workOrderConversion: { convertedCount: 2, unconvertedCount: 0, totalCount: 2 },
  2755. disposal: {
  2756. rate: { numerator: 1, denominator: 2, value: '0.5000', state: 'AVAILABLE', reason: null, basis: 'CLOSED_WORK_ORDERS_OVER_ALL_ALARMS' },
  2757. avgResponseDuration: { value: '30.5', unit: 'HOURS', sampleCount: 1, invalidSampleCount: 0, state: 'AVAILABLE', reason: null },
  2758. avgDisposalDuration: { value: '219.2', unit: 'HOURS', sampleCount: 1, invalidSampleCount: 0, state: 'AVAILABLE', reason: null },
  2759. },
  2760. byLevel: levels,
  2761. sevenDayTrend: trend(0),
  2762. }
  2763. }
  2764. // ---------------------------------------------------------------- 注册
  2765. /** 各接口在五类样例下的载荷(`failed` 由处理器抛出,不在这里给载荷)。 */
  2766. const PAYLOADS = {
  2767. // 票 08:地图摘要按**真实分页语义**给(分页窗口横跨监测点与未关联设备、第 2 页起要求快照一致)。
  2768. '/map/snapshot': (s, _requested, context) => mapSnapshotPayload(s, context.path, context.mapSnapshot),
  2769. '/monitoring-points/*': (s, requested) => pointDetailPayload(s, requested),
  2770. '/equipments/*/detail-aggregate': (s, requested) => equipmentAggregate(s, requested),
  2771. '/equipments/*/collection-records': (s, requested) => collectionRecordsPayload(s, requested),
  2772. // 票 13:跨设备当前事件(预警/报警切换 + 当前事件列表;`mode` 必填并校验)。
  2773. // 用 `context.query` 真的读 mode/level/industry/status/page/pageSize ——
  2774. // 否则「切到报警列表真的换内容」这条断言会退化成在看请求串(票 08 的教训)。
  2775. '/events/current': (s, _requested, context) => currentEventsPayload(s, context.query),
  2776. '/events/history-analysis': (s, _requested, context) => historyAnalysisPayload(s, context.query),
  2777. '/events/handling-efficiency': (s, _requested, context) => handlingEfficiencyPayload(s, context.query),
  2778. '/events/multidimensional-analysis': (s, _requested, context) => multidimensionalAnalysisPayload(s, context.query),
  2779. // 票 65:全量工单分页(报警效率面板的「当前工单列表」)。
  2780. // 真实后端 `GET /api/cockpit/v1/work-orders` 就是这个形状(含 pagination 四件套)。
  2781. // 分页在这里真的切窗口 —— mock 若总是回全量,前端的翻页与「共 N 张」口径就永远测不到。
  2782. '/work-orders': (s, _requested, context) => {
  2783. const query = (context && context.query) || {}
  2784. const all = s === 'empty' ? [] : TIMELINE_ORDERS
  2785. const page = Math.max(1, Number(query.page) || 1)
  2786. const pageSize = Math.max(1, Number(query.pageSize) || 10)
  2787. const total = all.length
  2788. const totalPages = Math.max(1, Math.ceil(total / pageSize))
  2789. const safePage = Math.min(page, totalPages)
  2790. return {
  2791. requestId: 'mock-work-order-list',
  2792. apiVersion: 'v1',
  2793. readOnly: true,
  2794. state: total === 0 ? 'EMPTY' : 'READY',
  2795. stateReason: total === 0 ? 'NO_WORK_ORDERS' : 'READY',
  2796. stateDictionary: WORK_ORDER_STATES.map((state) => ({ code: state.code, name: state.name })),
  2797. workOrders: all.slice((safePage - 1) * pageSize, safePage * pageSize),
  2798. pagination: { page: safePage, pageSize, total, totalPages },
  2799. }
  2800. },
  2801. '/equipments/*/freshness': (s, requested) => freshnessPayload(s, requested),
  2802. '/equipments/*/archive': (s) => (s === 'empty' ? null : ARCHIVE),
  2803. // 票 17:基础设施模式四块面板的面板级聚合读模型(各块独立成败,互不牵连)。
  2804. // 票 02:泵站类型字典(cockpit 域透传),只按本字典给 0/1 两行。
  2805. '/dict/pump_station_type': (s) => (s === 'empty' ? [] : [
  2806. { dictType: 'pump_station_type', dictValue: '0', dictLabel: '供水泵站' },
  2807. { dictType: 'pump_station_type', dictValue: '1', dictLabel: '排水泵站' },
  2808. ]),
  2809. // 票 07:六类业务字典(与票 04 的后端透传同形,值与业务库一致)。
  2810. // 改库标签不需要改这里 —— 这只是 mock 场景的固定样例。
  2811. ...Object.fromEntries([
  2812. ['risk_level', [['0', '重大风险'], ['1', '较大风险'], ['2', '一般风险'], ['3', '低风险']]],
  2813. ['risk_color', [['0', '红'], ['1', '橙'], ['2', '黄'], ['3', '蓝']]],
  2814. ['hazard_type', [['0', '腐蚀'], ['1', '第三方破坏'], ['2', '占压'], ['3', '泄漏']]],
  2815. ['hazard_level', [['1', '一级'], ['2', '二级'], ['3', '三级'], ['4', '四级隐患']]],
  2816. ['hazard_source', [['0', '巡检'], ['1', '政府检查'], ['2', '企业上报'], ['3', '模型辨识']]],
  2817. ['hazard_status', [['0', '整改中'], ['1', '已整改'], ['2', '待核查'], ['3', '已闭环']]],
  2818. ].map(([type, rows]) => [`/dict/${type}`, (s) => (s === 'empty' ? [] : rows.map(([dictValue, dictLabel]) => ({ dictType: type, dictValue, dictLabel })))])),
  2819. '/infrastructure/base-archives': (s, _requested, context) => baseArchivesPayload(s, context.query),
  2820. '/infrastructure/operating-information': (s, _requested, context) => operatingInformationPayload(s, context.query),
  2821. '/infrastructure/management-information': (s, _requested, context) => managementInformationPayload(s, context.query),
  2822. '/infrastructure/emergency-support': (s) => emergencySupportPayload(s),
  2823. // 票 18:运行监测模式三块面板(台账与监测分布**共用** distribution 的这一个响应)。
  2824. // 三个 builder 都吃**请求查询串**:分页/筛选/时间窗口在 mock 上必须真的按请求回,
  2825. // 否则「筛选真的下发了」「翻页真的带快照」这些断言全是假绿(票 08 踩过的同一个坑)。
  2826. '/monitoring/overview': (s, _requested, context) => monitoringOverviewPayload(s, context.query),
  2827. '/monitoring/distribution': (s, _requested, context) =>
  2828. monitoringDistributionPayload(s, context.query, context.monitoring),
  2829. '/monitoring/situation': (s, _requested, context) => monitoringSituationPayload(s, context.query),
  2830. // 票 05–08:总体概览四模块端点(四块各一个,互不牵连)。票 89 起前端会下发
  2831. // district/industry(后端已补齐入参);mock 样例仍是**固定读数、不按条件裁剪** ——
  2832. // 参数是否真的进了 URL 由 t67 闸门注入 fetch 捕获判定,不靠 mock 假装筛过。
  2833. '/overview/perception': (s) => overviewPerceptionPayload(s),
  2834. '/overview/pipe-network': (s) => overviewPipeNetworkPayload(s),
  2835. '/overview/warning-study': (s) => overviewWarningStudyPayload(s),
  2836. '/overview/alarm-disposal': (s) => overviewAlarmDisposalPayload(s),
  2837. // 票 24:设施点位与管线几何读模型(票 30 的真实端点 `/infrastructure/geometry`,免鉴权)。
  2838. '/infrastructure/geometry': (s, _requested, context) => pipeNetworkPayload(s, context.query),
  2839. // 票 68:四类设施点的实体详情(设施点图层补坐标;查询串 `category` 与真接口同形)。
  2840. '/infrastructure/entities/*/detail': (s, requested, context) => facilityEntityDetailPayload(s, requested, context.query),
  2841. }
  2842. /**
  2843. * 管线/设施几何样例(票 24)。
  2844. *
  2845. * **形状照抄票 30 的真实契约**(`GET /api/cockpit/v1/infrastructure/geometry`,实测于 2026-10-12):
  2846. * 标准 GeoJSON `FeatureCollection`——`{type:'FeatureCollection', generatedAt, features, coverage}`;
  2847. * feature 是 `{type:'Feature', id, geometry, properties}`,**没有 `kind` 字段**(按 `geometry.type` 判别);
  2848. * 非法坐标的 feature `geometry` 为 **null**,原始坐标留在 `properties.sourceCoordinates`;
  2849. * `coverage` 是**三态行** `{industry, source, geometryType, state, reason, recordCount, geometryCount, renderableCount}`,
  2850. * `state` ∈ `AVAILABLE`/`EMPTY`/`UNAVAILABLE`,同一行业可有管线/构件两行。
  2851. *
  2852. * 样例内容仍照实,不编"完美数据":
  2853. * · **燃气**给构件 —— 真实 `pointType` 是英文(实测 `valve`),样例两种写法都覆盖;
  2854. * · **供水/排水**只有真实的两点直线段(数据底座就是两点,**不编造弯头与三通**);
  2855. * · **窨井**没有管线,只有点位;
  2856. * · 刻意埋"不得上图":越界 / 零坐标 / 未校验 —— 必须进「无地图位置」清单,
  2857. * 既不被悄悄丢掉,也不被"就近挪一下"救回来(票 07 的坐标纪律)。
  2858. *
  2859. * 坐标取沅陵县城一带(与本仓其它 mock 同一区域)。
  2860. */
  2861. function pipeNetworkPayload(s, query) {
  2862. const valid = { state: 'VALID', reason: null, renderable: true, crs: 'WGS84' }
  2863. const invalid = (reason) => ({ state: 'INVALID', reason, renderable: false, crs: 'WGS84' })
  2864. const unverified = { state: 'UNVERIFIED', reason: 'UNVERIFIED_COORDINATE', renderable: false, crs: 'WGS84' }
  2865. const industry = String((query && query.industry) || '').trim()
  2866. const wanted = industry ? industry.toUpperCase() : ''
  2867. const keep = (code) => !wanted || wanted === code
  2868. const pipeRows = [
  2869. // 燃气:三点样例演示"样条管道"(真实库里多为两点,这里刻意给一条三点以覆盖多段路径)
  2870. ['GAS-P-001', '燃气主干管东段', 'GAS', 'PE', 400, [[110.3900, 28.4430], [110.3960, 28.4455], [110.4020, 28.4440]]],
  2871. ['GAS-P-002', '燃气支管南段', 'GAS', '钢', 200, [[110.3900, 28.4430], [110.3862, 28.4380]]],
  2872. ['GAS-P-003', '燃气主干管西段', 'GAS', 'PE', 300, [[110.3862, 28.4380], [110.3790, 28.4392]]],
  2873. // 供水/排水:真实只有两点直线段
  2874. ['WS-P-001', '供水输水干管', 'WATER_SUPPLY', '球铁', 600, [[110.3950, 28.4500], [110.4050, 28.4520]]],
  2875. ['WS-P-002', '供水配水支管', 'WATER_SUPPLY', 'PE', 150, [[110.4050, 28.4520], [110.4090, 28.4560]]],
  2876. ['DR-P-001', '排水主干管', 'DRAINAGE', '混凝土', 800, [[110.3880, 28.4400], [110.3800, 28.4420]]],
  2877. ].filter((row) => keep(row[2]))
  2878. const features = [
  2879. ...pipeRows.map(([code, name, ind, material, diameter, coordinates]) => ({
  2880. type: 'Feature',
  2881. id: `pipe_network_base:${code}`,
  2882. geometry: { type: 'LineString', coordinates },
  2883. properties: {
  2884. source: 'pipe_network_base', sourceId: code, code, name, industry: ind, typeCode: 'PIPE',
  2885. networkType: ind === 'GAS' ? '0' : ind === 'DRAINAGE' ? '1' : '2',
  2886. pointType: null, networkId: code, material, diameter, length: 120,
  2887. sourceCoordinates: coordinates, coordinateValidation: valid, coordinateValidations: [valid, valid],
  2888. },
  2889. })),
  2890. // 窨井:有坐标的点位设施,没有管线
  2891. {
  2892. type: 'Feature',
  2893. id: 'manhole_base:MH-001',
  2894. geometry: { type: 'Point', coordinates: [110.3920, 28.4460] },
  2895. properties: {
  2896. source: 'manhole_base', sourceId: 'MH-001', code: 'MH-001', name: '窨井001', industry: 'MANHOLE',
  2897. typeCode: 'MANHOLE', networkType: null, pointType: null, networkId: '',
  2898. sourceCoordinates: [[110.3920, 28.4460]], coordinateValidation: valid, coordinateValidations: [valid],
  2899. },
  2900. },
  2901. // ↓ 三条「不得上图」:真实契约里 geometry 为 null,原始坐标留在 sourceCoordinates
  2902. {
  2903. type: 'Feature',
  2904. id: 'pipe_network_base:GAS-P-004',
  2905. geometry: null,
  2906. properties: {
  2907. source: 'pipe_network_base', sourceId: 'GAS-P-004', code: 'GAS-P-004', name: '燃气管(坐标未校验)',
  2908. industry: 'GAS', typeCode: 'PIPE', networkType: '0', pointType: null, networkId: 'GAS-P-004',
  2909. sourceCoordinates: [[110.3700, 28.4300], [110.3740, 28.4320]],
  2910. coordinateValidation: unverified, coordinateValidations: [unverified, unverified],
  2911. },
  2912. },
  2913. {
  2914. type: 'Feature',
  2915. id: 'pipe_network_base:GAS-P-005',
  2916. geometry: null,
  2917. properties: {
  2918. source: 'pipe_network_base', sourceId: 'GAS-P-005', code: 'GAS-P-005', name: '燃气管(零坐标)',
  2919. industry: 'GAS', typeCode: 'PIPE', networkType: '0', pointType: null, networkId: 'GAS-P-005',
  2920. sourceCoordinates: [[0, 0], [0.0010, 0.0010]],
  2921. coordinateValidation: invalid('ZERO_COORDINATE'), coordinateValidations: [invalid('ZERO_COORDINATE')],
  2922. },
  2923. },
  2924. ]
  2925. // coverage 是**三态行**:同一行业可有管线/构件两行,缺口用 UNAVAILABLE + reason 如实标注。
  2926. const coverage = [
  2927. { industry: 'GAS', source: 'pipe_network_base', geometryType: 'LineString', state: 'AVAILABLE', reason: 'TWO_ENDPOINTS_ONLY', recordCount: 3, geometryCount: 3, renderableCount: 3 },
  2928. { industry: 'WATER_SUPPLY', source: 'pipe_network_base', geometryType: 'LineString', state: 'AVAILABLE', reason: 'TWO_ENDPOINTS_ONLY', recordCount: 2, geometryCount: 2, renderableCount: 2 },
  2929. { industry: 'DRAINAGE', source: 'pipe_network_base', geometryType: 'LineString', state: 'AVAILABLE', reason: 'TWO_ENDPOINTS_ONLY', recordCount: 1, geometryCount: 1, renderableCount: 1 },
  2930. { industry: 'GAS', source: null, geometryType: 'Point', state: 'UNAVAILABLE', reason: 'NO_COMPONENT_SOURCE', recordCount: 0, geometryCount: 0, renderableCount: 0 },
  2931. { industry: 'WATER_SUPPLY', source: null, geometryType: 'Point', state: 'UNAVAILABLE', reason: 'NO_COMPONENT_SOURCE', recordCount: 0, geometryCount: 0, renderableCount: 0 },
  2932. { industry: 'DRAINAGE', source: null, geometryType: 'Point', state: 'UNAVAILABLE', reason: 'NO_TYPED_COMPONENT_SOURCE', recordCount: 0, geometryCount: 0, renderableCount: 0 },
  2933. { industry: 'MANHOLE', source: 'manhole_base', geometryType: 'Point', state: 'AVAILABLE', reason: 'NO_COMPONENT_TYPE', recordCount: 1, geometryCount: 1, renderableCount: 1 },
  2934. { industry: 'MANHOLE', source: null, geometryType: 'LineString', state: 'UNAVAILABLE', reason: 'NO_PIPELINE_SOURCE', recordCount: 0, geometryCount: 0, renderableCount: 0 },
  2935. ]
  2936. return {
  2937. type: 'FeatureCollection',
  2938. generatedAt: '2026-10-12T11:00:00+08:00',
  2939. coverage,
  2940. features: s === 'empty' ? [] : features,
  2941. }
  2942. }
  2943. /**
  2944. * 从请求路径里取出模板 `*` 命中的那一段(即路径参数)。
  2945. * `('/equipments/TC-1/detail-aggregate', '/equipments/' + '*' + '/detail-aggregate')` → `TC-1`。
  2946. * 模板里有多个 `*` 时只取第一个——当前接口最多一个路径参数,够用且不猜。
  2947. */
  2948. function pathParameter(requestPath, template) {
  2949. const star = template.indexOf('*')
  2950. if (star === -1) return ''
  2951. const prefix = template.slice(0, star)
  2952. const suffix = template.slice(star + 1)
  2953. const bare = String(requestPath || '').split('?')[0]
  2954. if (!bare.startsWith(prefix)) return ''
  2955. const rest = bare.slice(prefix.length)
  2956. const end = suffix ? rest.indexOf(suffix) : rest.length
  2957. if (end === -1) return ''
  2958. return decodeURIComponent(rest.slice(0, end))
  2959. }
  2960. /**
  2961. * 注册全部契约化 mock。
  2962. * @param {object} [options]
  2963. * @param {string} [options.scenario] `success`(默认)/`empty`/`degraded`/`stale`/`failed`/`unauthorized`
  2964. * @param {string} [options.onlyPath] 只让这一个路径走「异常样例」,其余保持 `success`
  2965. * —— 票 05 验收第 6 条要的正是「只把**受影响分区**标为数据不可用」,
  2966. * 所以必须能只让一个分区坏掉、其余照常成功。
  2967. * @param {(path: string) => boolean} [options.only] 同上,函数形式(便于按前缀选中一族接口)
  2968. * @param {string} [options.prefix] 同上,按路径前缀选中一族接口(`/equipments/`)
  2969. * @param {object} [options.mapSnapshot] 地图摘要分页的现场覆盖(票 08 走查用):
  2970. * `{ pageSize, snapshotAt, expireAfterPage }`
  2971. * @param {object} handlers services/cockpitApi.js 的三个注册函数(注入以便单测)
  2972. */
  2973. export function registerCockpitMocks(options = {}) {
  2974. const { scenario = 'success', onlyPath = '', prefix = '', handlers } = options
  2975. const mapSnapshot = options.mapSnapshot || {}
  2976. // 票 18:运行监测的现场覆盖({ pageSize }),让台账渐进加载在样例上演示得出来。
  2977. const monitoring = options.monitoring || {}
  2978. // `prefix` 是 `only` 的便捷写法:两者都给时以 `only` 为准。
  2979. const only = options.only || (prefix ? (path) => path.startsWith(prefix) : null)
  2980. const register = (handlers && handlers.registerMockTransport) || null
  2981. if (!register) {
  2982. throw new Error('registerCockpitMocks 需要注入 registerMockTransport')
  2983. }
  2984. const reset = (handlers && handlers.resetMockTransportsForTest) || null
  2985. if (reset) reset()
  2986. const targets = new Set()
  2987. for (const [path, build] of Object.entries(PAYLOADS)) {
  2988. const applies = !onlyPath && !only ? true : only ? !!only(path) : path === onlyPath
  2989. const active = applies ? scenario : 'success'
  2990. register(path, async (context) => {
  2991. // `failed`:抛出让统一出口归类成「不可用」,模拟分区自己读取失败。
  2992. if (active === 'failed') {
  2993. throw new Error(`mock: ${path} 读取失败`)
  2994. }
  2995. if (active === 'unauthorized') {
  2996. // 401 不是载荷:把凭据类失败原因交给统一出口归类,
  2997. // 由它回 `{ok:false, reason:'unauthorized'}`(服务层只认白名单里的原因)。
  2998. const error = new Error('mock: 凭据未通过校验')
  2999. error.reason = REQUEST_REASON.UNAUTHORIZED
  3000. throw error
  3001. }
  3002. // 带路径参数的接口回显请求里的编码:这样「按编码取数」的行为与真接口一致
  3003. // (客户端传错编码时能看出来,而不是永远拿到同一台设备)。
  3004. const requested = pathParameter(context.path, path)
  3005. // 票 18:把**请求的查询串**解析成对象交给 builder —— 分页 / 筛选 / 时间窗口
  3006. // 必须真的按请求回,否则相关断言会变成假绿(票 08 的教训)。
  3007. const payload = build(active, requested, {
  3008. path: context.path,
  3009. mapSnapshot,
  3010. monitoring,
  3011. query: queryParams(context.path),
  3012. })
  3013. if (!requested) return payload
  3014. if (path === '/monitoring-points/*') {
  3015. // 票 41:名称必须按**请求的编码**回,不能永远回默认载荷那一个名字。
  3016. // 之前 MP-001/MP-002 的样例名与默认名恰好一致,所以这个缺口看不出来;
  3017. // 走查点 MP-001 却显示 MP-002 的名字时才暴露(真机走查抓到的真缺陷)。
  3018. // **只回显名称**:状态/原因仍是本样例手工构造的那一份,不在这里改
  3019. // (否则会出现"状态正常、原因却是压力超高"的自相矛盾组合)。
  3020. const known = MAP_POINTS.find((item) => item.pointCode === requested)
  3021. return {
  3022. ...payload,
  3023. monitoringPointCode: requested,
  3024. ...(known ? { monitoringPointName: known.pointName } : {}),
  3025. }
  3026. }
  3027. // 设备族接口:统一把请求的设备编码写回载荷(设备详情/事件/工单/新鲜度/档案都一样)。
  3028. if (typeof payload === 'object' && payload !== null && 'deviceCode' in payload) {
  3029. return { ...payload, deviceCode: requested }
  3030. }
  3031. return payload
  3032. })
  3033. targets.add(path)
  3034. }
  3035. return { scenario, paths: [...targets], isolated: onlyPath || prefix || (only ? 'predicate' : '') }
  3036. }