/** * 详情与分区状态(ADR 0004 的 `detailStore`:监测点摘要、设备卡片、设备详情**及各分区状态**)。 * * 票 05 的职责边界:本 store 只做两件事—— * 1. 调领域接口(`services/*Api.js`),把结果收进 `sections`; * 2. 对外给**领域对象**,不给后端裸字段(store 里不出现 `deviceCode` 之外的接口字段名)。 * * 为什么各分区要并列存放(票 05 验收第 6 条、票 11 验收第 3 条): * 「某个分区数据不可用」必须**不牵连**其它分区,所以状态天然是 `{ [分区名]: section() }`, * 而不是一个整体的 `loading/error`。地图骨架不在这里——它归 `mapService`,本身就不受分区成败影响。 * * 票 08 修正了一处分工:地图摘要这一条分区不再在这里「取一页了事」,而是交给 `mapStore` 的 * 渐进加载(分页 + 快照一致性归它)。本 store 只把它的装载状态同步成一条分区状态, * 免得同一个端点被两处各拉一次(那还会各持一个快照,正好违反票 08 的一致性要求)。 * * 票 10 追加**两级详情**:`selection`(在点位级还是设备级)+ 点位摘要分区。 * 层级语义是纯函数(`domain/detailFlow.js`),本文件只负责「该取数时取数」与收口竞态: * · 同一个点位重复打开不再发请求(`isSamePointTarget` + 已加载); * · 先后打开 A、B 时,A 的迟到响应被丢弃(token),不会把 A 的数据挂在 B 的表头下; * 本文件与 `mapService` 零耦合:详情流程不会给地图加任何标记(关联设备因此不会被重复上图)。 * * 票 11 补上第三件取数:**设备详情聚合**(按设备编码)。它接在票 10 留下的那个接缝上 —— * 票 10 的「进第二级不取数」是**延期**(它的票面写明"归票 11"),不是永久契约;本票把这条 * 取数收进 `selectDevice` / `openDevice` 这两个**唯一**的进级入口,于是「进了设备级却没取数」 * 在结构上不可能发生(不用调用方记得额外调一次加载)。竞态收口与点位级同款: * 换设备时旧的在途响应作废(token),并且**已答过的同一台设备不再重复取数**, * 而失败/不可用要留恢复路径(再选一次同一台可以重试)。 */ import { ref } from 'vue' import { defineStore } from 'pinia' import { fetchEquipmentDetailAggregate, fetchEquipmentFreshness, fetchMonitoringPointDetail } from '../services/detailApi.js' import { SECTION_STATE, overallState, section, sectionStateFromReason } from '../domain/sectionState.js' import { REQUEST_REASON } from '../domain/requestReason.js' import { MAP_SUMMARY_PHASE } from '../domain/mapSummary.js' import { equipmentDetailMatches, collectionRecordsSection } from '../domain/equipmentDetailView.js' import { retainEquipmentRefresh } from '../domain/detailRefresh.js' import { DETAIL_LEVEL, backToPoint as backToPointSelection, closeDetail as closeDetailSelection, emptyDetailSelection, isSamePointTarget, openDevice as openDeviceSelection, openPoint as openPointSelection, } from '../domain/detailFlow.js' import { useMapStore } from './mapStore.js' function pending() { return { state: SECTION_STATE.EMPTY, reason: '', mode: '', data: null, missing: [], freshness: '', retained: false, loaded: false } } export const useDetailStore = defineStore('detailStore', () => { const mapStore = useMapStore() /** * 分区状态表:键是分区名,值是 `section()`。 * 挂了**共享详情域**的分区(票 05 的交付面):地图摘要、监测点摘要(票 10)、 * 设备详情聚合(8 个子分区)、设备新鲜度。 */ const sections = ref({ mapSnapshot: pending(), pointDetail: pending(), equipmentAggregate: pending(), equipmentFreshness: pending(), }) /** 当前的两级详情选择(`domain/detailFlow.js` 的状态)。 */ const selection = ref(emptyDetailSelection()) /** * 当前「定位揭示」目标(#127):`{ code, deviceCode }`,`code` 是地图摘要对象编码。 * 只由定位成功的那一次打开动作写入;换选择、关闭、模式/图例筛选变化时清除。 * 它不等于 `monitoringStore.locate`(那是给用户的定位反馈,可能保留到最后一次操作)。 */ const locateTarget = ref(null) /** 点位摘要正在取数(界面只做轻提示;分区状态仍由 `sections.pointDetail` 说了算)。 */ const pointLoading = ref(false) /** 设备详情聚合正在取数(票 11;同样只是轻提示,分区成败由各分区自己说)。 */ const deviceLoading = ref(false) /** 最近一次加载是否进行中(界面只做轻提示,不影响分区各自的成功值)。 */ const loading = ref(false) /** 请求注入(config / fetchImpl):取一次就让后续所有分区共用,单测与走查都靠它。 */ let requestOptions = {} /** 点位摘要的请求序号:只有最后一次请求允许写分区(迟到响应丢弃)。 */ let pointToken = 0 /** 设备详情聚合的请求序号:换设备时旧的在途响应作废(与点位级同款收口)。 */ let deviceToken = 0 function configure(options = {}) { requestOptions = { ...requestOptions, ...options } } function setSection(name, value) { sections.value = { ...sections.value, [name]: { ...value, loaded: true } } } /** 写入/清除定位揭示目标;调用方只在定位成功的打开动作里传对象。 */ function setLocateTarget(target) { const code = String((target && target.code) || '').trim() const device = target && target.device && typeof target.device === 'object' ? { ...target.device } : null locateTarget.value = code ? { code, deviceCode: String(target.deviceCode || '').trim(), ...(device ? { device } : {}), } : null } function clearLocateTarget() { locateTarget.value = null } /** 从已加载的点位详情里取某台设备的**原始卡片**(含自身坐标/校验);找不到回 null。 */ function deviceCard(pointCode, deviceCode) { const data = sections.value.pointDetail && sections.value.pointDetail.data if (!data || data.code !== pointCode || !Array.isArray(data.devices)) return null return data.devices.find((item) => item && item.code === deviceCode) || null } /** * 把 `mapStore` 的渐进加载状态同步成「地图摘要」分区状态(票 08)。 * * 映射刻意**不把"还没翻完"写成 `STALE`**:`STALE` 在票 16 的词汇里是「有值但过期」, * 而分页没翻完的数据是**新鲜的**,只是还没取全 —— 说成"已过期"就是对值班人员撒谎, * 也会让顶栏分区板与地图上真实进度互相矛盾。取到一部分就是**成功**(数据源健康、值新鲜), * 「翻到第几页了」由地图摘要那条专用指示器与地图上的点位数体现。 * * 真正该报异常的三种:真失败(`FAILED`)、快照失效(`STALE` + `retained`,这次确实是"有值但已作废")、 * 后端说没有对象(`EMPTY`)。 */ function syncMapSnapshotSection() { const state = mapStore.summary const phase = state.phase let next = null if (phase === MAP_SUMMARY_PHASE.EMPTY) { next = section(SECTION_STATE.EMPTY, { data: null }) } else if (phase === MAP_SUMMARY_PHASE.FAILED) { next = section(sectionStateFromReason(state.reason), { reason: state.reason || '', data: state.loaded ? state : null }) } else if (phase === MAP_SUMMARY_PHASE.EXPIRED) { next = section(SECTION_STATE.STALE, { reason: state.reason || '', data: state, retained: true }) } else if (state.loaded > 0) { // 加载中 / 就绪(还有下一页):已上图的点位是新鲜的,分区就是成功。 next = section(SECTION_STATE.SUCCESS, { data: state }) } // 一个点都还没取到、也还没失败时**不改写**分区:保持 pending(未取数), // 不拿「无数据」或「已过期」去描述"正在取第 1 页"。 if (!next) return sections.value.mapSnapshot setSection('mapSnapshot', next) return next } /** * 加载启动时共享的分区:这里只有地图摘要。 * 地图摘要走 `mapStore` 的 refresh 链(票 14:换新快照第 1 页并**自动分批加载到完成**, * 决策 02 的 Q24——旧版只取第一页的手动渐进形态已由自动加载取代)。 * 设备详情与新鲜度不再用固定演示设备预载,用户选中真实设备时再取。 * @param {object} [options] `{ config, fetchImpl }` */ async function loadSharedSections(options = {}) { const shared = { config: options.config, fetchImpl: options.fetchImpl } configure(shared) loading.value = true mapStore.setup(shared) await mapStore.refresh() syncMapSnapshotSection() loading.value = false return sections.value } /** * 加载某个监测点的详情(票 10 的第一级:摘要 + 设备卡片)。 * @param {string} pointCode 监测点编码 * @returns {Promise} 该分区(`section()`) */ async function loadPointDetail(pointCode, options = {}) { if (!pointCode) return sections.value.pointDetail pointToken += 1 const mine = pointToken if (sections.value.pointDetail.data?.code !== pointCode) { sections.value = { ...sections.value, pointDetail: pending() } } pointLoading.value = true const active = Object.keys(options).length ? { ...requestOptions, ...options } : requestOptions try { const result = await fetchMonitoringPointDetail(pointCode, active) // 迟到的响应丢弃:A 的点位还没回来就点了 B,A 的数据不得盖在 B 的表头下。 if (mine !== pointToken) return sections.value.pointDetail return setPointResult(pointCode, result) } catch (error) { // 适配层本身不会抛(票 04 的失败一律收敛成 `{ok:false,reason}`),但转换层万一抛了 // 也不能把详情卡在「加载中」或冒成页面级报错:收成一条失败分区,用户还能重试。 if (mine !== pointToken) return sections.value.pointDetail const failed = section(SECTION_STATE.FAILED, { reason: REQUEST_REASON.UNREACHABLE, data: null }) return setPointResult(pointCode, failed) } finally { if (mine === pointToken) pointLoading.value = false } } function setPointResult(pointCode, result) { const current = sections.value.pointDetail const retained = !result.data && [SECTION_STATE.FAILED, SECTION_STATE.UNAVAILABLE].includes(result.state) && current.data?.code === pointCode const next = retained ? { ...result, state: SECTION_STATE.STALE, data: current.data, retained: true } : result setSection('pointDetail', next) return next } /** * 票 15:状态推送把**已打开**的点位详情里的状态就地换掉(验收第 4 条)。 * * 三件事刻意不做,都是为了"不重建视图": * · **不重新取数**(推送已经给了新状态,再拉一次既慢又可能覆盖更新的推送); * · **不换层级、不动选择**(`selection` 一个字节不变,浮层不闪、不回到第一级); * · **不复制整份摘要**(只换 `status` 字段,其余字段保持 REST 快照里的那份)。 * 与之无关的点位一律不碰:编码对不上就直接返回(推送不该影响没打开的详情)。 * @param {string} pointCode 推送指名的点位编码 * @param {string} status 后端发布的状态字符串 * @returns {boolean} 是否真的改到了 */ function applyPushedStatus(pointCode, status) { const code = String(pointCode || '').trim() const next = String(status || '').trim() if (!code || !next) return false const current = sections.value.pointDetail const summary = current && current.data // 详情没打开 / 打开的不是这个点位 / 分区里没有数据:都不动。 if (!summary || summary.code !== code) return false if (summary.status === next) return false setSection('pointDetail', { ...current, data: { ...summary, status: next, statusSource: 'push' } }) return true } /** * 加载设备详情聚合(票 11 的主路径)与这台设备的新鲜度。 * 聚合一次拿到档案/指标/预警/报警/工单/时间线/图片,每个分区独立成败 * (契约层保证,见 `domain/equipmentDetail.js`)。 * * @param {string} deviceCode 设备编码 * @returns {Promise} 该分区(`section()`) */ async function loadEquipmentAggregate(deviceCode, options = {}) { if (!deviceCode) return sections.value.equipmentAggregate deviceToken += 1 const mine = deviceToken deviceLoading.value = true const active = Object.keys(options).length ? { ...requestOptions, ...options } : requestOptions try { const [result, freshness] = await Promise.all([ fetchEquipmentDetailAggregate(deviceCode, active), fetchEquipmentFreshness(deviceCode, active), ]) // 迟到的响应丢弃:A 还没回来就换了 B,A 的数据不得挂在新表头下。 if (mine !== deviceToken) return sections.value.equipmentAggregate setSection('equipmentFreshness', freshness) return setEquipmentResult(deviceCode, result) } catch (error) { // 与点位级同款兜底:适配层不抛,但转换层万一抛了要收成一条失败分区, // 不能把设备详情卡在「加载中」(用户还得能看见其它已成功的区块)。 if (mine !== deviceToken) return sections.value.equipmentAggregate const failed = section(SECTION_STATE.FAILED, { reason: REQUEST_REASON.UNREACHABLE, data: null }) setSection('equipmentFreshness', failed) return setEquipmentResult(deviceCode, failed) } finally { if (mine === deviceToken) deviceLoading.value = false } } /** A failed background read does not erase an already displayed, identity-matched result. */ function setEquipmentResult(deviceCode, result) { const next = retainEquipmentRefresh(sections.value.equipmentAggregate, result, deviceCode) setSection('equipmentAggregate', next) return next } /** * 进入设备级:换层级 + **按需取数**(票 11 把设备详情聚合的加载收在这里)。 * * 「已答过」= 成功 / 空 / 过期(有过一次明确答复),且答复的是**同一台设备**: * 满足就不再发请求(返回点位级再点回来不该重复拉)。 * **失败与不可用不算已答**:那两种要允许用户再选一次同一台重试,否则永远没有恢复路径 * (与票 10 点位级的立场一致)。 */ async function enterDeviceLevel(next, options = {}) { const previous = selection.value selection.value = next const deviceCode = next.deviceCode || '' if (!deviceCode) return selection.value const aggregate = sections.value.equipmentAggregate const collection = collectionRecordsSection(aggregate.data?.sections?.metrics) const answered = equipmentDetailMatches(aggregate, deviceCode) && aggregate.loaded === true && !aggregate.invalidated && !aggregate.retained && ![SECTION_STATE.FAILED, SECTION_STATE.UNAVAILABLE].includes(collection.state) && [SECTION_STATE.SUCCESS, SECTION_STATE.EMPTY, SECTION_STATE.STALE].includes(aggregate.state) // 同一台设备正在取数时再点一下不该叠第二个请求。 const inFlight = deviceLoading.value && (previous.deviceCode || '') === deviceCode if (!answered && !inFlight) { await loadEquipmentAggregate(deviceCode, options) } return selection.value } /** * 打开一个详情选择 —— 地图点选与(票 18 的)台账卡片共用这一条入口。 * * 两级都可能取数:点位级取点位摘要(票 10),设备级取设备详情聚合(票 11)。 * 同一个点位已经取过就不再发请求,但层级仍会回到第一级(用户可能只是想退回卡片列表)。 * @param {object} next `domain/detailFlow.js` 的选择 */ async function openSelection(next, options = {}) { if (!next || next.level === DETAIL_LEVEL.NONE) return closeDetail() if (next.level === DETAIL_LEVEL.EQUIPMENT) { return enterDeviceLevel( { level: next.level, pointCode: next.pointCode || '', deviceCode: next.deviceCode || '' }, options, ) } const samePoint = isSamePointTarget(selection.value, next.pointCode) const state = sections.value.pointDetail.state /** * 「已经有确定结果」= 成功 / 空 / 过期(有过一次明确答复)。 * **失败或不可用不算**:那两种情况要允许用户再点一次同一个点位重试, * 否则点同一个标记只会反复看到同一张失败卡片,永远没有恢复路径。 */ const answered = sections.value.pointDetail.loaded === true && !sections.value.pointDetail.retained && [SECTION_STATE.SUCCESS, SECTION_STATE.EMPTY, SECTION_STATE.STALE].includes(state) /** 同一点位正在取数时再点一下不该叠第二个请求。 */ const inFlight = pointLoading.value && samePoint selection.value = { level: next.level, pointCode: next.pointCode || '', deviceCode: next.deviceCode || '', } if (selection.value.level === DETAIL_LEVEL.POINT && !(samePoint && (answered || inFlight))) { await loadPointDetail(selection.value.pointCode, options) } return selection.value } /** 打开监测点(第一级)。 */ function openPoint(pointCode, options = {}) { setLocateTarget(options.locateTarget || null) return openSelection(openPointSelection(selection.value, pointCode), options) } /** * 票 42(规格 14:刷新核对链):**强制重取**一个点位的摘要数据,不查「已答过」缓存。 * * 与 `openPoint` 的区别:核对链在快照变更后已知数据可能过期,重取是规格明写的行为 * (「找到同编码有效标记后恢复锚定详情并重新加载设备」)。 * 刻意**不动 `selection`**:核对链要求保留选择身份与详情层级(含设备级), * 这里只换数据 —— 设备图层经既有的 pointDetail 监听自行重算。 */ function reloadPointDetail(pointCode, options = {}) { if (!pointCode) return sections.value.pointDetail return loadPointDetail(pointCode, options) } /** 选择设备卡片(第二级):换层级并加载这台设备的详情聚合(票 11)。 */ function selectDevice(deviceCode, options = {}) { setLocateTarget(options.locateTarget || null) return enterDeviceLevel(openDeviceSelection(selection.value, deviceCode), options) } /** 从地图上的未关联设备直接进设备详情(没有点位可摘要)。 */ function openDevice(deviceCode, options = {}) { setLocateTarget(options.locateTarget || null) return enterDeviceLevel({ level: DETAIL_LEVEL.EQUIPMENT, pointCode: '', deviceCode }, options) } /** * 返回点位摘要级;没有点位可回时收成空选择(未关联设备的入口)。 * * 刻意**不清掉已加载的设备详情**:退回卡片列表再点回同一台时靠它免掉一次重复请求 * (`enterDeviceLevel` 的「已答过」判据)。作废的只是在途请求序号。 */ function backToPoint() { deviceToken += 1 deviceLoading.value = false clearLocateTarget() selection.value = backToPointSelection(selection.value) return selection.value } /** 关掉详情浮层。在途的点位与设备请求一并作废(它们已经不属于任何一次选择)。 */ function closeDetail() { pointToken += 1 deviceToken += 1 pointLoading.value = false deviceLoading.value = false clearLocateTarget() selection.value = closeDetailSelection() return selection.value } /** 增量到达后失效对应设备缓存,撤销在途旧响应;再打开时必须重取。 */ function invalidateEquipment(deviceCode) { const current = sections.value.equipmentAggregate if (!current || !current.data || current.data.deviceCode !== deviceCode) return false deviceToken += 1 deviceLoading.value = false sections.value = { ...sections.value, equipmentAggregate: { ...current, invalidated: true } } return true } /** 设备详情聚合里的一个子分区(票 11 按分区渲染时取用)。 */ function aggregateSection(name) { const aggregate = sections.value.equipmentAggregate const data = (aggregate && aggregate.data) || null const found = data && data.sections ? data.sections[name] : null return found || pending() } /** 全部子分区(票 11 遍历渲染)。 */ function aggregateSections() { const aggregate = sections.value.equipmentAggregate const data = (aggregate && aggregate.data) || null return (data && data.sections) || {} } /** 三条顶层分区的整体状态:`partial` 表示"部分可用"(票 16 要求可区分)。 */ function overall() { return overallState(sections.value) } /** 仅测试用:回到未加载状态。 */ function reset() { sections.value = { mapSnapshot: pending(), pointDetail: pending(), equipmentAggregate: pending(), equipmentFreshness: pending(), } pointToken += 1 deviceToken += 1 pointLoading.value = false deviceLoading.value = false selection.value = emptyDetailSelection() clearLocateTarget() loading.value = false } return { sections, selection, locateTarget, pointLoading, deviceLoading, loading, configure, setSection, setLocateTarget, clearLocateTarget, deviceCard, syncMapSnapshotSection, loadSharedSections, loadPointDetail, loadEquipmentAggregate, invalidateEquipment, applyPushedStatus, openSelection, openPoint, reloadPointDetail, openDevice, selectDevice, backToPoint, closeDetail, aggregateSection, aggregateSections, overall, reset, } })