enhancementDevices.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { fetchMonitoringPointDetail } from './detailApi.js'
  2. /** Read the current snapshot, not just the selected point. Never borrow a parent's position. */
  3. export async function loadEnhancementDevices(summary, { fetchPoint = fetchMonitoringPointDetail, alive = () => true, onProgress = () => {} } = {}) {
  4. const objects = summary?.objects || []
  5. const points = objects.filter((o) => o.kind === 'monitoring-point')
  6. const rows = new Map(objects.filter((o) => o.kind === 'unassociated-equipment').map((o) => [o.code, { ...o, pointCode: '' }]))
  7. let cursor = 0
  8. let failedPoints = 0
  9. let missingDevices = 0
  10. let extraDevices = 0
  11. let stalePoints = 0
  12. let missingLists = 0
  13. let loadedPoints = 0
  14. const state = (loading) => ({ rows: [...rows.values()], failedPoints, missingDevices, extraDevices, stalePoints,
  15. missingLists, loadedPoints, totalPoints: points.length,
  16. partial: loading || !['complete', 'empty'].includes(summary?.phase) || !!summary?.truncated
  17. || (Number.isFinite(summary?.total) && summary.total > objects.length)
  18. || failedPoints > 0 || missingDevices > 0 || extraDevices > 0 || missingLists > 0 || !alive(),
  19. relationNote: '仅使用已提供的设施关联;其余为邻近示意,非实测安装位置' })
  20. const publish = () => { if (alive()) onProgress(state(true)) }
  21. publish()
  22. async function worker() {
  23. while (cursor < points.length && alive()) {
  24. const point = points[cursor++]
  25. let result
  26. try { result = await fetchPoint(point.code) } catch { failedPoints += 1; loadedPoints += 1; publish(); continue }
  27. if (!alive()) return
  28. if (!['success', 'empty', 'stale'].includes(result?.state) || !Array.isArray(result?.data?.devices)
  29. || result.data.code !== point.code) { failedPoints += 1; loadedPoints += 1; publish(); continue }
  30. if (result.state === 'stale') stalePoints += 1
  31. const listAvailable = point.deviceCodesAvailable ?? Array.isArray(point.deviceCodes)
  32. if (!listAvailable) missingLists += 1
  33. const expected = new Set(point.deviceCodes || [])
  34. const found = new Set()
  35. for (const device of result.data.devices) {
  36. if (!device?.code) continue
  37. if (listAvailable && !expected.has(device.code)) { extraDevices += 1; continue }
  38. found.add(device.code)
  39. rows.set(device.code, { ...device, pointCode: point.code, industry: device.industry || point.industry,
  40. retained: result.state === 'stale' })
  41. }
  42. missingDevices += [...expected].filter((code) => !found.has(code)).length
  43. loadedPoints += 1
  44. publish()
  45. }
  46. }
  47. await Promise.all(Array.from({ length: Math.min(4, points.length) }, worker))
  48. return state(false)
  49. }