Explorar o código

fix: 优化无农场弹窗逻辑

刘秀芳 hai 1 día
pai
achega
00fdce71fe

+ 3 - 0
src/App.vue

@@ -21,6 +21,8 @@
             <component :is="Component" v-if="Component && !route.meta.keepAlive" :key="route.name" />
         </router-view>
 
+        <!-- 无农场时按当前 tab 显示对应引导弹窗 -->
+        <no-farm-popup-host />
 
         <Tabbar class="tabbar" route fixed v-show="showTab" active-color="#FFD489" inactive-color="#B5B5B5">
             <tabbar-item replace to="/growth_report">
@@ -68,6 +70,7 @@ import { NH, NZ, EXPERT } from "@/common/user_role";
 import zhCn from "element-plus/es/locale/lang/zh-cn";
 import en from "element-plus/es/locale/lang/en";
 import { useI18n } from "@/i18n";
+import noFarmPopupHost from "@/components/popup/noFarmPopupHost.vue";
 
 const { t, locale } = useI18n();
 const store = useStore();

+ 3 - 3
src/components/farmHeader.vue

@@ -23,6 +23,7 @@ import { useStore } from "vuex";
 import { Switch } from "@element-plus/icons-vue";
 import { useI18n } from "@/i18n";
 import { DEFAULT_CROP_AVATAR, resolveCropIcon, resolveFarmCropName } from "@/utils/cropIcon";
+import { loadFarmList } from "@/utils/farmPresence";
 
 const { t } = useI18n();
 const router = useRouter();
@@ -86,9 +87,8 @@ const loadFirstFarmAsSelected = async () => {
         return;
     }
     try {
-        const res = await VE_API.questionnaire.getFarms({ id });
-        const list = Array.isArray(res?.data) ? res.data : [];
-        const first = list[0];
+        const list = await loadFarmList();
+        const first = Array.isArray(list) ? list[0] : null;
         if (!first) {
             applyFarmInfo();
             return;

+ 68 - 0
src/components/popup/noFarmPopupHost.vue

@@ -0,0 +1,68 @@
+<template>
+    <complete-farm-info-popup
+        v-if="visible && activePopup === 'agri'"
+        v-model:show="visible"
+        @confirm="goCompleteFarmInfo"
+    />
+    <farm-calendar-popup
+        v-if="visible && activePopup === 'work'"
+        v-model:show="visible"
+        @confirm="goCompleteFarmInfo"
+    />
+</template>
+
+<script setup>
+import { ref, watch } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import completeFarmInfoPopup from "@/components/popup/completeFarmInfoPopup.vue";
+import farmCalendarPopup from "@/components/popup/farmCalendarPopup.vue";
+import { loadFarmList, peekFarmList } from "@/utils/farmPresence";
+
+// ---------- 常量 ----------
+/** 当前路由决定弹哪一个;不在表里就关掉 */
+const POPUP_BY_ROUTE = {
+    AgriFile: "agri",
+    WorkExecute: "work",
+};
+
+// ---------- 页面状态 ----------
+const route = useRoute();
+const router = useRouter();
+const activePopup = ref("");
+const visible = ref(false);
+let syncToken = 0;
+
+// ---------- 业务逻辑 ----------
+const applyFarmList = (kind, list) => {
+    activePopup.value = kind;
+    visible.value = Array.isArray(list) && list.length === 0;
+};
+
+const syncPopup = async (name) => {
+    const kind = POPUP_BY_ROUTE[name] || "";
+    const token = ++syncToken;
+    if (!kind) {
+        activePopup.value = "";
+        visible.value = false;
+        return;
+    }
+
+    const cached = peekFarmList();
+    if (cached) {
+        applyFarmList(kind, cached);
+        return;
+    }
+
+    visible.value = false;
+    const list = await loadFarmList();
+    if (token !== syncToken) return;
+    applyFarmList(kind, list);
+};
+
+const goCompleteFarmInfo = () => {
+    visible.value = false;
+    router.push("/entry_information");
+};
+
+watch(() => route.name, syncPopup, { immediate: true });
+</script>

+ 60 - 0
src/utils/farmPresence.js

@@ -0,0 +1,60 @@
+import { ref } from "vue";
+
+/** null:还没拿到结果;true:有农场;false:没有农场 */
+export const hasFarms = ref(null);
+
+let cacheUserId = "";
+let cacheList = null;
+let inflight = null;
+let inflightUserId = "";
+
+function getMiniUserId() {
+    return localStorage.getItem("MINI_USER_ID") || "";
+}
+
+/** 已有列表时直接记住,后面的弹窗和页头不用再请求 */
+export function rememberFarmList(list, userId) {
+    const id = String(userId || getMiniUserId() || "");
+    const farms = Array.isArray(list) ? list : [];
+    if (!id) return farms;
+    cacheUserId = id;
+    cacheList = farms;
+    hasFarms.value = farms.length > 0;
+    return farms;
+}
+
+export function peekFarmList() {
+    const id = getMiniUserId();
+    if (!id || cacheUserId !== String(id) || !Array.isArray(cacheList)) return null;
+    return cacheList;
+}
+
+/**
+ * 同一用户同时只打一次 find_farm_information。
+ * 失败返回 null,调用方不要把失败当成「没有农场」。
+ */
+export async function loadFarmList() {
+    const id = getMiniUserId();
+    if (!id) return null;
+
+    const cached = peekFarmList();
+    if (cached) return cached;
+
+    if (inflight && inflightUserId === String(id)) return inflight;
+
+    inflightUserId = String(id);
+    const task = (async () => {
+        try {
+            const res = await VE_API.questionnaire.getFarms({ id });
+            const list = Array.isArray(res?.data) ? res.data : [];
+            return rememberFarmList(list, id);
+        } catch (e) {
+            console.warn("[farmPresence] getFarms failed", e);
+            return null;
+        } finally {
+            if (inflight === task) inflight = null;
+        }
+    })();
+    inflight = task;
+    return task;
+}

+ 3 - 1
src/utils/selectedFarm.js

@@ -1,3 +1,5 @@
+import { rememberFarmList } from "@/utils/farmPresence";
+
 /** 与 farmHeader / allGarden 一致的选中农场缓存读写 */
 
 export function getSelectedFarmFromStorage() {
@@ -96,7 +98,7 @@ export async function selectNewlyCreatedFarm({ userId } = {}) {
 
     try {
         const res = await VE_API.questionnaire.getFarms({ id: uid });
-        const list = Array.isArray(res?.data) ? res.data : [];
+        const list = rememberFarmList(res?.data, uid);
         const last = list.length ? list[list.length - 1] : null;
         if (last) return saveSelectedFarm(last);
     } catch (e) {

+ 4 - 38
src/views/old_mini/agri_file/index.vue

@@ -47,8 +47,6 @@
                 </div>
             </template>
         </tip-popup>
-        <complete-farm-info-popup v-model:show="showCompleteFarmPopup" @confirm="goCompleteFarmInfo" />
-
         <!-- 诊断报告弹窗:组件内接口判断 exists=2 且本地未展示过 -->
         <diagnosis-report-popup />
 
@@ -83,7 +81,7 @@
 </template>
 
 <script setup>
-import { computed, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref } from "vue";
+import { computed, nextTick, onActivated, onBeforeUnmount, onMounted, ref } from "vue";
 import { useStore } from "vuex";
 import { useRouter } from "vue-router";
 import { ElMessage } from "element-plus";
@@ -91,8 +89,8 @@ import { useI18n } from "@/i18n";
 import farmHeader from "@/components/farmHeader.vue";
 import albumUploadPopup from "./components/albumUploadPopup.vue";
 import tipPopup from "@/components/popup/tipPopup.vue";
-import completeFarmInfoPopup from "@/components/popup/completeFarmInfoPopup.vue";
 import diagnosisReportPopup from "@/components/popup/diagnosisReportPopup.vue";
+import { hasFarms } from "@/utils/farmPresence";
 import restorePlantingPopup from "@/components/popup/restorePlantingPopup.vue";
 import proxyAuthPopup from "@/components/popup/proxyAuthPopup.vue";
 import phenologyUpdatePopup from "@/components/popup/phenologyUpdatePopup.vue";
@@ -137,7 +135,6 @@ const activeNav = ref("patrol");
 const guideVisible = ref(false);
 const showUploadPopup = ref(false);
 const showSuccessPopup = ref(false);
-const showCompleteFarmPopup = ref(false);
 const patrolPanelRef = ref(null);
 const showPatrolDiagnosis = ref(false);
 /** 后续由接口控制是否展示代管授权弹窗 */
@@ -155,29 +152,8 @@ const phenologyUpdateInfo = ref({
 });
 
 // ---------- 工具函数 ----------
-function getMiniUserId() {
-    return store.state.home.miniUserId || localStorage.getItem("MINI_USER_ID");
-}
-
-const noFarms = ref(true);
-// ---------- 业务逻辑 ----------
-/** 无果园信息时展示「完善农场信息」弹窗 */
-async function checkCompleteFarmPopup() {
-    const id = getMiniUserId();
-    if (!id) {
-        showCompleteFarmPopup.value = false;
-        return;
-    }
-    try {
-        const res = await VE_API.questionnaire.getFarms({ id });
-        const list = Array.isArray(res?.data) ? res.data : [];
-        noFarms.value = list.length === 0;
-        showCompleteFarmPopup.value = list.length === 0;
-    } catch (e) {
-        console.warn("[agri_file] getFarms failed", e);
-        showCompleteFarmPopup.value = false;
-    }
-}
+/** 列表未返回或为空时不展示诊断引导;弹窗由应用层 noFarmPopupHost 负责 */
+const noFarms = computed(() => hasFarms.value !== true);
 
 const dismissGuide = () => {
     if (!guideVisible.value) return;
@@ -288,10 +264,6 @@ const handleOutsideClick = (event) => {
     dismissGuide();
 };
 
-const goCompleteFarmInfo = () => {
-    router.push("/entry_information");
-};
-
 const handleProxyReject = () => {
     // TODO: 调用拒绝代管接口
 };
@@ -310,19 +282,13 @@ const handlePhenologyUpdateConfirm = () => {
 
 // ---------- 生命周期 ----------
 onMounted(() => {
-    // checkCompleteFarmPopup();
-    // tryShowGuide();
     document.addEventListener("click", handleOutsideClick, true);
 });
 onActivated(() => {
-    checkCompleteFarmPopup();
     tryShowGuide();
     tryContinueUpload();
 });
 
-onDeactivated(() => {
-    showCompleteFarmPopup.value = false;
-});
 onBeforeUnmount(() => {
     document.removeEventListener("click", handleOutsideClick, true);
 });

+ 2 - 1
src/views/old_mini/dev_login.vue

@@ -7,6 +7,7 @@ import { useRoute, useRouter } from "vue-router";
 import { useStore } from "vuex";
 import { SET_TOKEN, SET_USER_ROLES, SET_USER_CUR_ROLE } from "@/store/modules/app/type";
 import { onMounted } from "vue";
+import { rememberFarmList } from "@/utils/farmPresence";
 
 const router = useRouter();
 const route = useRoute();
@@ -53,7 +54,7 @@ const resolveFarmsAfterLogin = async () => {
     if (!id) return;
     try {
         const res = await VE_API.questionnaire.getFarms({ id });
-        const list = Array.isArray(res?.data) ? res.data : [];
+        const list = rememberFarmList(res?.data, id);
         if (!list.length) {
             // 无农场清掉旧选中缓存,避免长势报告仍按有农场走接口
             localStorage.removeItem("selectedFarmId");

+ 1 - 1
src/views/old_mini/growth_report/index.vue

@@ -691,7 +691,7 @@ const handleInvite = (type) => {
 onMounted(() => {
     // syncSelectedFarmId();
     // syncMapFromSelectedFarm();
-    getLocationName();
+    // getLocationName();
     // initMap();
     // fetchFarmRangeStatus();
     // fetchInteractTask();

+ 5 - 37
src/views/old_mini/work_execute/index.vue

@@ -109,7 +109,6 @@
                 <div v-if="!displayTaskList.length" class="empty-tip">{{ t("workExecute.noData") }}</div>
             </div>
         </div>
-        <farm-calendar-popup v-model:show="showFarmCalendarPopup" @confirm="goCompleteFarmInfo" />
         <survey-ask-popup v-model:show="showSurveyAskPopup" @confirm="handleSurveyConfirm" />
 
         <!-- 诊断报告弹窗:组件内接口判断 exists=2 且本地未展示过 -->
@@ -121,19 +120,19 @@
 </template>
 
 <script setup>
-import { computed, nextTick, onActivated, onDeactivated, onMounted, ref } from "vue";
+import { computed, nextTick, onActivated, ref } from "vue";
 import { useStore } from "vuex";
 import { useRouter } from "vue-router";
 import { ElMessage } from "element-plus";
 import IndexMap from "./index";
 import customCalendar from "./components/calendar.vue";
 import farmHeader from "@/components/farmHeader.vue";
-import farmCalendarPopup from "@/components/popup/farmCalendarPopup.vue";
 import surveyAskPopup from "@/components/popup/surveyAskPopup.vue";
 import diagnosisReportPopup from "@/components/popup/diagnosisReportPopup.vue";
 import restorePlantingPopup from "@/components/popup/restorePlantingPopup.vue";
 import { useI18n } from "@/i18n";
 import { saveSelectedFarm } from "@/utils/selectedFarm";
+import { loadFarmList } from "@/utils/farmPresence";
 import wx from "weixin-js-sdk";
 import { Icon } from 'vant';
 
@@ -157,7 +156,6 @@ const router = useRouter();
 const indexMap = new IndexMap();
 const mapContainer = ref(null);
 const calendarRef = ref(null);
-const showFarmCalendarPopup = ref(false);
 /** 调查问卷弹窗:后续由接口决定是否展示 */
 const showSurveyAskPopup = ref(false);
 const tabBarHeight = computed(() => store.state.home.tabBarHeight);
@@ -419,31 +417,14 @@ const syncCalendar = () => {
     });
 };
 
-/** 无果园信息时展示「完善农场信息 / 专属农事日历」弹窗 */
-async function checkFarmCalendarPopup() {
-    const id = getMiniUserId();
-    if (!id) {
-        showFarmCalendarPopup.value = false;
-        return;
-    }
-    try {
-        const res = await VE_API.questionnaire.getFarms({ id });
-        const list = Array.isArray(res?.data) ? res.data : [];
-        showFarmCalendarPopup.value = list.length === 0;
-    } catch (e) {
-        console.warn("[work_execute] getFarms failed", e);
-        showFarmCalendarPopup.value = false;
-    }
-}
-
 /** 无选中农场时写入列表首项,保证 zone_fw_task_list 有 farm_id */
 async function ensureSelectedFarm() {
     if (getSelectedFarmId() != null) return true;
     const id = getMiniUserId();
     if (!id) return false;
     try {
-        const res = await VE_API.questionnaire.getFarms({ id });
-        const list = Array.isArray(res?.data) ? res.data : [];
+        const list = await loadFarmList();
+        if (!Array.isArray(list)) return false;
         return list[0] ? saveSelectedFarm(list[0]) : false;
     } catch (e) {
         console.warn("[work_execute] ensureSelectedFarm failed", e);
@@ -633,10 +614,6 @@ const handleMarkComplete = async (item) => {
     }
 };
 
-const goCompleteFarmInfo = () => {
-    router.push("/entry_information");
-};
-
 const handleSurveyConfirm = () => {
     showSurveyAskPopup.value = false;
     router.push("/survey_entry");
@@ -676,7 +653,7 @@ const refreshPage = async () => {
     pageLoading.value = true;
     try {
         await ensureSelectedFarm();
-        // 无农场时不打任务列表(弹窗由 checkFarmCalendarPopup 负责)
+        // 无农场时不打任务列表(无农场弹窗由应用层 noFarmPopupHost 负责)
         if (getSelectedFarmId() == null) {
             taskList.value = [];
             zoneList.value = [];
@@ -708,18 +685,9 @@ const refreshPage = async () => {
     }
 };
 
-onMounted(() => {
-    // checkFarmCalendarPopup();
-    // nextTick(refreshPage);
-});
-
 onActivated(() => {
-    checkFarmCalendarPopup();
     nextTick(refreshPage);
 });
-onDeactivated(() => {
-    showFarmCalendarPopup.value = false;
-});
 </script>
 
 <style lang="scss" scoped>