فهرست منبع

fix:企业运营首页增加三个纬度检索条件

mlchen 1 هفته پیش
والد
کامیت
6e97970ba0

+ 49 - 0
docs/企业运营看板首页-实施与验收.md

@@ -230,3 +230,52 @@
 3. 查后端日志应有「企业运营看板首页查询开始 … 环比上期=[…]」与「M01 本期营业收入 … 含税开票额=… 退货折让额=… 净额=…」两行。
 4. 前端浏览器控制台应有 `[eos-dashboard] 加载看板/加载完成` 两组日志,切换档位有 `[eos-dashboard] 切换查询档位`。
 
+
+## 10. 检索区新增「公司/集团 → 部门 → 时间区间」(2026-11-13,第四期)
+
+### 10.1 接口契约扩展(全部可选,向后兼容)
+
+`POST /eom/dashboard/home`
+
+| 字段 | 类型 | 语义 |
+| --- | --- | --- |
+| `scope` | string | 原字段不变:`YEAR` / `QUARTER` / `MONTH`(空按 MONTH) |
+| `companyId` | Long | 公司/集团 id(`t_main_group.type` 10 集团 / 20 公司);空 = 不限公司 |
+| `deptId` | Long | 部门 id(`t_main_group.type` 30);空且 `companyId` 非空 = 该公司下全部部门 |
+| `startDate` / `endDate` | string | `yyyy-MM-dd`;**两者都非空时优先于 `scope`**,右端含当天 |
+
+`POST /eom/dashboard/revenue/detail` 增加 `companyId` / `deptId` / `startDate` / `endDate`(窗口与首页同一套 `buildWindow`);
+`POST /eom/dashboard/alert/{ruleCode}/detail` 与 `/alert/detail/export` 增加 `companyId` / `deptId`(预警仍实时口径,不带日期)。
+
+不传任何新字段时:`deptIds=null` → SQL 一条部门条件都不拼、窗口按 `scope`,行为与改造前逐字一致。
+
+### 10.2 部门口径(重要,勿改)
+
+- 统一按单据/批次的 **`dept_id`** 过滤,该列由 `BaseEntity` 在 INSERT 时按创建人所属部门自动填充(`MybatisPlusObjectHandler:21,30`)。
+- **不使用**业务归口列:`sales_dept_id` 开发库仅 7/94 有值、`purchase_dept_id` 52/53、开票 `apply_dept_id` 与 `dept_id` 语义不同。改用归口列会让绝大多数单据被筛掉。
+- 主表与明细表 `dept_id` 并不总是相等:开发库 `t_eom_fin_invoice_apply_detail` 与父单 **56/147 行不一致**、`t_eom_sale_order_product` 与订单 **4/890 行不一致**。因此凡语句里 join 了主表,**必须过滤主表别名**,不得过滤 `*_detail` / `*_product`。
+- 组织展开在服务层完成:取 `t_main_group` 全量节点建树,`deptId` → 该节点子树(含 type=40 工厂型节点,因为单据 `dept_id` 会落在它们上面);`deptId` 空 + `companyId` 非空 → 公司子树全部节点。
+- 越权与脏参数一律抛中文错(`所选部门不属于当前公司/集团`),不放宽成全量,避免「以为在看自己部门、实际看的是全公司」。
+
+### 10.3 时间维度
+
+- 三档 `scope` 保留(口径不变:T+1 截止、环比按自然月/季/年平移)。
+- 自定义区间:右端含当天(SQL 侧转次日半开)、结束日不越 T+1 截止日、区间长度上限 366 天;环比窗口 = 区间整体前移等长天数。
+- 趋势图月份轴由后端 `monthsOf(window)` 生成,上界取「窗口末端那天」与截止日中较早者(自定义短区间不会被拉到当前月,不再多出空月)。
+- **月份补零规则**:收入/采购两条金额序列,只要窗口内有任一非空月份,其余缺失月补 `0`(缺月 = 该月无单据,是真实业务事实);整窗全无数据时保持 `null`,前端仍判「暂无数据」,不画一排 0 柱。达成率不补 0(无计划时仍 `null`,避免错误陈述「0% 达成」)。
+
+### 10.4 已发现但未处理
+
+- **`dept_id` 上没有索引**:`t_eom_sale_order` / `t_eom_purchase_order_receive` / `t_eom_fin_receivable` / `t_eom_fin_payable` / `t_eom_fin_invoice_apply` / `t_wms_stock_batch_two` 均无 `dept_id` 索引(`information_schema.STATISTICS` 实测 0 行)。当前每条语句多一个 `dept_id IN (...)` 条件,行集仍由 `tenant_id` + 时间范围先行收敛,开发库量级无感;生产需 DBA 用 `EXPLAIN` 复核,必要时按 `(tenant_id, dept_id, create_time)` 补索引。
+- 组织树一次性全量拉取(开发库 80 节点)。多租户大环境若超过 2000 节点,应改为按 `parentId` 懒加载,当前未做。
+- 预警台账:`alert_key` 不含部门(M17/M18/M19 用规则固定键、M20 用客户 id),部门收窄只是缩减候选集,不会产生按部门重复的台账行;但切换部门后会看到「本部门候选为 0、台账里仍有其它部门的未处理行」,属预期(台账是租户级)。
+
+
+### 10.5 部门过滤在具体指标上的已知影响(实跑/复核得出,勿当成 bug)
+
+1. **M28 财务经营汇总里的库存估值 6 列不随部门**:`t_wms_home_daily_snapshot` 没有 `dept_id` 列(`information_schema` 已核),`selectSummaryFinance` 的 `openingValuation / openingValuedRows / openingUnpricedBatchCount / closingValuation / closingValuedRows / closingUnpricedBatchCount` 六列无法加部门条件。开发库实跑印证:加部门过滤后其余列全部变化,只有这 6 列与未过滤时逐字相同。属能力缺口,不是漏加。
+2. **M22 流失预警客户按部门视角判定**:流失判定里的 `NOT EXISTS` 跟着部门收窄,含义是「该客户在本部门近 N 月无订单」。跨部门仍有订单的客户,在本部门视角下会被计为流失。切到公司/集团层级或全部部门时与改造前一致。
+3. **M25~M27 采购准时率样本按收货单部门收窄,不按采购订单行部门**:交期 deadline 取自 `t_eom_purchase_order_product`(补充信息 JOIN),若一并按部门过滤,收货行所属部门与采购订单行部门不一致时会解析不到 deadline、被既有 `deadline IS NOT NULL` 条件丢掉,样本被非预期收窄。因此该 JOIN 表**不加**部门条件(与「只过滤业务单据主表」的规则一致)。
+4. **预警明细与卡片同口径**:M17~M20 的 list 与 count 共用同一段 `where` 片段(`alertDetailM17Where` 等),部门条件加在片段里,因此「卡片 N 项」与「明细 M 条」不会因收窄而错位;`selectRevenueDrill / countRevenueDrill / selectRevenueDrillSummary` 同理共用 `revenueDrillRows`。
+5. **开发库验证数据**(tenant=1):`selectKpiReceivable` 无过滤 24,691.00 元/7 单(= 全量,未破坏改造前口径)→ 公司节点 1 收窄为 22,874.00/4 单 → 单部门可为 0;`selectKpiOpenOrderValue` 88 单/3,819,662 元 → 公司 1 为 58 单/312,012 元 → 研发部 0;`selectAlertDetailM17` 2 行 → 1 行 → 0 行;`selectRevenueStructure` 16 行 → 13 行。
+

+ 36 - 3
src/api/eos/dashboard.js

@@ -28,12 +28,38 @@ function parse(res) {
 const DEFAULT_PAGE_NUM = 1;
 const DEFAULT_PAGE_SIZE = 20;
 
+/** 组织维度 id(Long):空值一律不下发,空串会被后端反序列化拒绝 */
+function hasId(v) {
+  return v !== null && v !== undefined && v !== '';
+}
+
+/** 时间区间(yyyy-MM-dd):两端都非空才算有效区间(后端优先于 scope) */
+function hasDateRange(startDate, endDate) {
+  return typeof startDate === 'string' && startDate !== '' && typeof endDate === 'string' && endDate !== '';
+}
+
 /**
  * 看板首页聚合数据
- * @param {string} scope YEAR | QUARTER | MONTH(为空按 MONTH)
+ * body:{ scope, companyId, deptId, startDate, endDate },全部可选
+ *   scope  YEAR | QUARTER | MONTH(为空按 MONTH)
+ *   companyId / deptId  组织维度(Long),未选时键不下发
+ *   startDate / endDate yyyy-MM-dd,两端都非空时后端优先于 scope
+ * @param {Object|string} params 查询条件(兼容旧调用:直接传 scope 字符串)
  */
-export async function getDashboardHome(scope) {
-  const res = await request.post('eom/dashboard/home', { scope: scope || 'MONTH' });
+export async function getDashboardHome(params) {
+  const p = typeof params === 'string' ? { scope: params } : params || {};
+  const body = { scope: p.scope || 'MONTH' };
+  if (hasId(p.companyId)) {
+    body.companyId = p.companyId;
+  }
+  if (hasId(p.deptId)) {
+    body.deptId = p.deptId;
+  }
+  if (hasDateRange(p.startDate, p.endDate)) {
+    body.startDate = p.startDate;
+    body.endDate = p.endDate;
+  }
+  const res = await request.post('eom/dashboard/home', body);
   return parse(res);
 }
 
@@ -68,6 +94,13 @@ export async function getRevenueDetail(params) {
     pageNum: p.pageNum || DEFAULT_PAGE_NUM,
     pageSize: p.pageSize || DEFAULT_PAGE_SIZE
   };
+  // 组织维度:与首页卡片同口径(时间仍走 scope,明细不带 startDate/endDate)
+  if (hasId(p.companyId)) {
+    body.companyId = p.companyId;
+  }
+  if (hasId(p.deptId)) {
+    body.deptId = p.deptId;
+  }
   const res = await request.post('eom/dashboard/revenue/detail', body);
   return parse(res);
 }

+ 5 - 0
src/views/home/components/alertDetailDialog.vue

@@ -111,6 +111,7 @@
 <script>
   import { getAlertDetail, exportAlertDetail, buildAlertExportName } from '@/api/eos/dashboard';
   import { download } from '@/utils/file';
+  import { buildOrgFilterParams } from '../org-index';
 
   // 弹窗标题:按规则编码显示(M17~M20 固定文案)
   const RULE_TITLE = {
@@ -137,6 +138,8 @@
       // 看板处于元素级全屏:弹层与下拉面板必须挂回页面内,否则挂在 body 上会看不见
       boardFullscreen: { type: Boolean, default: false }
     },
+    // 首页筛选(companyId / deptId):与卡片同口径,明细/导出不能漏组织维度
+    inject: { boardFilters: { from: 'eosBoardFilters', default: null } },
     data() {
       return {
         loading: false,
@@ -289,6 +292,8 @@
         if (this.alertKey) {
           params.alertKey = this.alertKey;
         }
+        // 组织维度与首页卡片一致(导出走同一份 buildParams,口径自动同步)
+        Object.assign(params, buildOrgFilterParams(this.boardFilters));
         return Object.assign(params, extra || {});
       },
       /**

+ 180 - 0
src/views/home/components/boardFilters.vue

@@ -0,0 +1,180 @@
+<!-- 企业运营看板 · 检索行(公司/集团 → 部门 → 查询档位 → 自定义区间 → 刷新) -->
+<template>
+  <div class="board-filters">
+    <span class="board-filters__item">
+      <span class="board-filters__label">公司/集团</span>
+      <el-select
+        :value="value.companyId"
+        size="small"
+        clearable
+        placeholder="全部公司/集团"
+        class="board-filters__select board-filters__select--company"
+        popper-class="eos-dark-popper"
+        :popper-append-to-body="!boardFullscreen"
+        @change="handleCompanyChange"
+      >
+        <el-option
+          v-for="item in companyOptions"
+          :key="item.id"
+          :label="item.name"
+          :value="item.id"
+        />
+      </el-select>
+    </span>
+
+    <span class="board-filters__item">
+      <span class="board-filters__label">部门</span>
+      <el-select
+        :value="value.deptId"
+        size="small"
+        clearable
+        filterable
+        placeholder="全部部门"
+        class="board-filters__select board-filters__select--dept"
+        popper-class="eos-dark-popper"
+        :popper-append-to-body="!boardFullscreen"
+        :no-data-text="deptNoDataText"
+        @change="handleDeptChange"
+      >
+        <el-option
+          v-for="item in deptOptions"
+          :key="item.id"
+          :label="item.label"
+          :value="item.id"
+        />
+      </el-select>
+    </span>
+
+    <span class="board-filters__item">
+      <span class="board-filters__label">查询范围</span>
+      <div class="seg">
+        <button
+          v-for="item in scopeOptions"
+          :key="item.value"
+          type="button"
+          :class="{ on: value.scope === item.value }"
+          @click="handleScopeChange(item.value)"
+        >
+          {{ item.label }}
+        </button>
+      </div>
+    </span>
+
+    <span class="board-filters__item">
+      <span class="board-filters__label">自定义区间</span>
+      <el-date-picker
+        :value="dateRangeValue"
+        type="daterange"
+        size="small"
+        value-format="yyyy-MM-dd"
+        range-separator="至"
+        start-placeholder="开始日期"
+        end-placeholder="结束日期"
+        class="board-filters__date"
+        popper-class="eos-dark-popper"
+        :clearable="true"
+        unlink-panels
+        @change="handleDateChange"
+      />
+    </span>
+
+    <span class="board-filters__ops">
+      <button
+        type="button"
+        class="board-filters__refresh"
+        :class="{ 'is-loading': refreshing }"
+        :disabled="refreshing"
+        title="重新加载看板数据"
+        @click="handleRefresh"
+      >
+        <i class="el-icon-refresh" :class="{ 'is-spin': refreshing }"></i>
+        <span>刷新</span>
+      </button>
+      <span v-if="fallbackHint" class="board-filters__hint">
+        未匹配到本部门,已按全部部门展示
+      </span>
+    </span>
+  </div>
+</template>
+
+<script>
+  import { hasValue } from '../org-index';
+
+  /**
+   * 检索行(受控组件)
+   * - 筛选值全部来自父组件 value(单一数据源:首页卡片与三处明细都读同一份)
+   * - 每次用户操作只 emit 一次 change,携带完整筛选对象,父组件一次 patch 只发一次请求
+   *   (切换公司时 companyId 与 deptId 在同一份载荷里生效,不会出现「先清部门再改公司」两次查询)
+   */
+  export default {
+    name: 'BoardFilters',
+    props: {
+      // 当前筛选:{ scope, companyId, deptId, startDate, endDate }
+      value: { type: Object, default: () => ({}) },
+      // 公司/集团下拉选项:[{ id, name }]
+      companyOptions: { type: Array, default: () => [] },
+      // 部门下拉选项:[{ id, label }](由父组件按所选公司子树算好)
+      deptOptions: { type: Array, default: () => [] },
+      // 刷新中:按钮置灰并转圈
+      refreshing: { type: Boolean, default: false },
+      // 默认本部门解析失败时的弱提示
+      fallbackHint: { type: Boolean, default: false },
+      // 看板处于元素级全屏:下拉面板必须挂回页面内,否则挂 body 上看不见
+      boardFullscreen: { type: Boolean, default: false }
+    },
+    data() {
+      return {
+        scopeOptions: [
+          { value: 'YEAR', label: '年度' },
+          { value: 'QUARTER', label: '本季度' },
+          { value: 'MONTH', label: '本月(默认)' }
+        ]
+      };
+    },
+    computed: {
+      // 区间回显:两端都有值才显示区间,否则保持空(与请求口径一致)
+      dateRangeValue() {
+        const v = this.value || {};
+        return hasValue(v.startDate) && hasValue(v.endDate) ? [v.startDate, v.endDate] : null;
+      },
+      // 部门下拉空态文案:有公司但没部门 / 还没选公司,两种原因要分开说,且不能当成报错
+      deptNoDataText() {
+        return hasValue((this.value || {}).companyId) ? '该公司下暂无部门' : '请先选择公司/集团';
+      }
+    },
+    methods: {
+      // el-select 清空时给的是空串:统一收敛成 undefined,空串不能下发给后端
+      normalizeId(v) {
+        return hasValue(v) ? v : undefined;
+      },
+      emitChange(patch) {
+        this.$emit('change', Object.assign({}, this.value, patch));
+      },
+      // 切公司:同一次载荷里把 deptId 清空,父组件只触发一次查询
+      handleCompanyChange(companyId) {
+        this.emitChange({ companyId: this.normalizeId(companyId), deptId: undefined });
+      },
+      handleDeptChange(deptId) {
+        this.emitChange({ deptId: this.normalizeId(deptId) });
+      },
+      handleScopeChange(scope) {
+        if (!scope || this.value.scope === scope) {
+          return;
+        }
+        this.emitChange({ scope });
+      },
+      // 清空区间 → startDate/endDate 都不下发;选满 → yyyy-MM-dd 两字段
+      handleDateChange(range) {
+        const start = Array.isArray(range) && hasValue(range[0]) ? range[0] : undefined;
+        const end = Array.isArray(range) && hasValue(range[1]) ? range[1] : undefined;
+        this.emitChange({ startDate: start, endDate: end });
+      },
+      handleRefresh() {
+        if (this.refreshing) {
+          return;
+        }
+        this.$emit('refresh');
+      }
+    }
+  };
+</script>

+ 5 - 0
src/views/home/components/revenueDetailDialog.vue

@@ -123,6 +123,7 @@
 
 <script>
   import { getRevenueDetail } from '@/api/eos/dashboard';
+  import { buildOrgFilterParams } from '../org-index';
 
   // 段别字典:接口入参 ALL/INVOICE/RETURN,界面中文
   const SEGMENT_TEXT = { INVOICE: '开票收入', RETURN: '退货折让' };
@@ -152,6 +153,8 @@
       // 看板处于元素级全屏:弹层必须挂回页面内,否则挂 body 上会看不见
       boardFullscreen: { type: Boolean, default: false }
     },
+    // 首页筛选(companyId / deptId):与卡片同口径,明细不能漏组织维度
+    inject: { boardFilters: { from: 'eosBoardFilters', default: null } },
     data() {
       return {
         loading: false,
@@ -279,6 +282,8 @@
           pageNum: this.pageNum,
           pageSize: this.pageSize
         };
+        // 组织维度与首页卡片一致(时间仍走 scope,明细不带 startDate/endDate)
+        Object.assign(params, buildOrgFilterParams(this.boardFilters));
         this.loading = true;
         this.loadError = '';
         console.info('[eos-revenue] 营业收入明细查询', params);

+ 153 - 0
src/views/home/home-dashboard.scss

@@ -1714,3 +1714,156 @@
     overflow-x: hidden;
   }
 }
+
+/* ===== 检索行(公司/集团 → 部门 → 查询档位 → 自定义区间 → 刷新)=====
+   仅追加新样式,既有选择器(.scope / .seg / .overview-title 等)保持原样;
+   档位 .seg 复用既有隐藏按钮样式:检索行仍渲染在 .eom-dashboard 内,父级作用域不变 */
+.eom-dashboard .board-filters {
+  position: relative;
+  z-index: 2;
+  display: flex;
+  flex-wrap: wrap;
+  align-items: center;
+  gap: 10px 18px;
+  margin: 6px 0 4px;
+  padding: 8px 12px;
+  border: 1px solid rgba(0, 190, 255, 0.22);
+  background: linear-gradient(180deg, rgba(0, 45, 78, 0.6), rgba(0, 18, 36, 0.7));
+  box-shadow: 0 0 16px rgba(0, 170, 255, 0.12);
+
+  .board-filters__item {
+    display: inline-flex;
+    align-items: center;
+    gap: 8px;
+  }
+
+  .board-filters__label {
+    font-weight: bold;
+    color: #8ec4de;
+    letter-spacing: 0.08em;
+    white-space: nowrap;
+  }
+
+  .board-filters__select {
+    width: 180px;
+  }
+
+  .board-filters__select--dept {
+    width: 200px;
+  }
+
+  .board-filters__date.el-date-editor {
+    width: 250px;
+  }
+
+  /* 深色输入框:与整页暗色科技风统一(Element 默认白底在深色底上会跳出来) */
+  .el-input__inner,
+  .el-range-input {
+    color: #e6f7ff;
+    background: rgba(2, 26, 46, 0.75);
+    border-color: rgba(0, 190, 255, 0.25);
+  }
+
+  .el-input__inner:hover,
+  .el-range-input:hover {
+    border-color: rgba(0, 220, 255, 0.55);
+  }
+
+  .el-input__prefix,
+  .el-input__suffix,
+  .el-range-separator,
+  .el-input__icon {
+    color: #7fd8ff;
+  }
+
+  .el-range-input::placeholder,
+  .el-input__inner::placeholder {
+    color: #5f92ad;
+  }
+
+  .el-input.is-disabled .el-input__inner {
+    background: rgba(2, 26, 46, 0.4);
+    border-color: rgba(0, 190, 255, 0.15);
+    color: #6d94a8;
+  }
+
+  .board-filters__ops {
+    display: inline-flex;
+    align-items: center;
+    gap: 12px;
+    margin-left: auto;
+  }
+
+  .board-filters__refresh {
+    display: inline-flex;
+    align-items: center;
+    gap: 5px;
+    padding: 5px 12px;
+    color: #bfe9ff;
+    font-size: 12.5px;
+    font-weight: bold;
+    cursor: pointer;
+    border: 1px solid rgba(0, 210, 255, 0.4);
+    border-radius: 4px;
+    background: linear-gradient(135deg, rgba(0, 60, 100, 0.55), rgba(0, 25, 50, 0.75));
+    box-shadow: inset 0 0 12px rgba(0, 180, 255, 0.18);
+    transition: all 0.2s;
+
+    i {
+      font-size: 14px;
+      color: #4fe3ff;
+    }
+
+    &:hover:not(:disabled) {
+      color: #fff;
+      border-color: rgba(0, 230, 255, 0.8);
+      box-shadow: 0 0 14px rgba(0, 200, 255, 0.4);
+    }
+
+    &:disabled {
+      cursor: not-allowed;
+      opacity: 0.6;
+    }
+
+    .is-spin {
+      animation: board-filters-spin 0.9s linear infinite;
+    }
+  }
+
+  /* 弱提示:默认本部门没解析到时说明口径,不是报错 */
+  .board-filters__hint {
+    color: #ffcf8f;
+    font-size: 12px;
+    white-space: nowrap;
+  }
+}
+
+@keyframes board-filters-spin {
+  from {
+    transform: rotate(0deg);
+  }
+
+  to {
+    transform: rotate(360deg);
+  }
+}
+
+@media (max-width: 1400px) {
+  .eom-dashboard .board-filters {
+    .board-filters__select {
+      width: 150px;
+    }
+
+    .board-filters__select--dept {
+      width: 160px;
+    }
+
+    .board-filters__date.el-date-editor {
+      width: 220px;
+    }
+
+    .board-filters__ops {
+      margin-left: 0;
+    }
+  }
+}

+ 204 - 41
src/views/home/index.vue

@@ -13,7 +13,7 @@
       <span class="fx-corner fx-corner--br"></span>
     </div>
 
-    <!-- 页面标题:与 HR 首页同款(光翼 + 六边形辉光边框),查询范围挂在标题右侧 -->
+    <!-- 页面标题:与 HR 首页同款(光翼 + 六边形辉光边框);查询档位已迁到下方检索行 -->
     <header class="overview-title" aria-label="企业运营看板">
       <div class="overview-title__wing overview-title__wing--left">
         <i></i><i></i><i></i>
@@ -29,20 +29,6 @@
       <div class="overview-title__wing overview-title__wing--right">
         <i></i><i></i><i></i>
       </div>
-      <div class="scope">
-        <span class="label">查询范围:</span>
-        <div class="seg">
-          <button
-            v-for="item in scopeOptions"
-            :key="item.value"
-            type="button"
-            :class="{ on: scope === item.value }"
-            @click="changeScope(item.value)"
-          >
-            {{ item.label }}
-          </button>
-        </div>
-      </div>
       <!-- 全屏按钮:HR 同款(纯图标),全屏对象是页面根元素而不是整个系统页面 -->
       <button
         type="button"
@@ -53,6 +39,19 @@
         <i :class="isBoardFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"></i>
       </button>
     </header>
+
+    <!-- 检索行:公司/集团 → 部门 → 查询档位 → 自定义区间 → 刷新 -->
+    <board-filters
+      :value="filters"
+      :company-options="companyOptions"
+      :dept-options="deptOptions"
+      :refreshing="refreshing"
+      :fallback-hint="fallbackHintVisible"
+      :board-fullscreen="isBoardFullscreen"
+      @change="handleFilterChange"
+      @refresh="loadHome(true)"
+    />
+
     <kpi-cards
       :kpis="kpis"
       :scope="scope"
@@ -91,25 +90,56 @@
 
 <script>
   import { getDashboardHome } from '@/api/eos/dashboard';
+  import { listOrganizations } from '@/api/system/organization';
+  import { getCurrentUser } from '@/utils/token-util';
+  import boardFilters from './components/boardFilters.vue';
   import kpiCards from './components/kpiCards.vue';
   import trendCharts from './components/trendCharts.vue';
   import revenueDonut from './components/revenueDonut.vue';
   import riskAlertCard from './components/riskAlertCard.vue';
   import summaryCards from './components/summaryCards.vue';
+  import {
+    buildOrgIndex,
+    departmentOptions,
+    resolveDefaultSelection,
+    buildOrgFilterParams,
+    hasValue
+  } from './org-index';
 
   // M01 下钻明细弹窗按需加载:只有用户点开时才拉这一份 chunk,首页首屏包体不因此膨胀
   const revenueDetailDialog = () => import('./components/revenueDetailDialog.vue');
 
   export default {
-    components: { kpiCards, trendCharts, revenueDonut, riskAlertCard, summaryCards, revenueDetailDialog },
+    components: {
+      boardFilters,
+      kpiCards,
+      trendCharts,
+      revenueDonut,
+      riskAlertCard,
+      summaryCards,
+      revenueDetailDialog
+    },
+    // 三处明细弹窗(M01 / M17~M20)要跟首页卡片同口径:弹窗由卡片组件挂载,故用 provide 下发。
+    // filters 对象本身不整体替换(只改字段),注入方每次读取拿到的都是最新筛选
+    provide() {
+      return { eosBoardFilters: this.filters };
+    },
     data() {
       return {
-        scope: 'MONTH',
-        scopeOptions: [
-          { value: 'YEAR', label: '年度' },
-          { value: 'QUARTER', label: '本季度' },
-          { value: 'MONTH', label: '本月(默认)' }
-        ],
+        // 唯一筛选源:档位 + 组织维度 + 自定义区间(空值保持 undefined,绝不下发空串)
+        filters: {
+          scope: 'MONTH',
+          companyId: undefined,
+          deptId: undefined,
+          startDate: undefined,
+          endDate: undefined
+        },
+        // 组织树内存索引(一次性拉全量,切公司不额外发组织请求)
+        orgIndex: null,
+        // 默认本部门解析失败(按全部部门出数时给弱提示)
+        orgUnmatched: false,
+        // 已解析过默认值的登录组织 id:顶栏组织未真的变化时不重复查询
+        resolvedGroupId: null,
         loading: false,
         scopeRangeText: '',
         dataTime: '',
@@ -124,12 +154,39 @@
         // 预警卡刷新中:驱动刷新按钮旋转与置灰
         refreshing: false,
         // M01 下钻明细弹窗:v-if 控制挂载,配合异步组件实现按需加载
-        revenueDetailVisible: false
+        revenueDetailVisible: false,
+        // 请求序号:并发响应只让最新那一次落地(旧响应直接丢弃,不写数据与 loading)
+        loadSeq: 0
       };
     },
-  computed: {},
+    computed: {
+      // 档位对外仍以 scope 暴露,卡片组件的 props 契约不变
+      scope() {
+        return this.filters.scope || 'MONTH';
+      },
+      // 公司/集团下拉选项(集团 + 公司,停用项已过滤)
+      companyOptions() {
+        return this.orgIndex ? this.orgIndex.companies : [];
+      },
+      // 部门下拉选项:所选公司子树里的部门/工厂(内存级联,不发请求)
+      deptOptions() {
+        return departmentOptions(this.orgIndex, this.filters.companyId);
+      },
+      // 弱提示只在「默认本部门没解析到」且用户尚未自行选择组织时出现
+      fallbackHintVisible() {
+        return (
+          this.orgUnmatched && !hasValue(this.filters.companyId) && !hasValue(this.filters.deptId)
+        );
+      }
+    },
+    watch: {
+      // 顶栏切换组织后跟随:重跑默认值解析并重查(info 变化但组织未变时由 resolvedGroupId 拦住)
+      '$store.state.user.info'() {
+        this.handleLoginOrgChange();
+      }
+    },
     mounted() {
-      this.loadHome();
+      this.initBoard();
       // 全屏状态同步:用户按 ESC 退出时按钮图标要跟着变
       this.onFullscreenChange = this.handleBoardFullscreenChange;
       document.addEventListener('fullscreenchange', this.onFullscreenChange);
@@ -140,6 +197,76 @@
       document.removeEventListener('webkitfullscreenchange', this.onFullscreenChange);
     },
     methods: {
+      /**
+       * 首屏:先拉组织树 → 解析默认本部门 → 只发 1 次看板请求
+       * 组织树失败不阻断(initOrgIndex 内部兜底为全部部门)
+       */
+      async initBoard() {
+        await this.initOrgIndex();
+        this.applyDefaultFilters();
+        await this.loadHome();
+      },
+      /**
+       * 组织树:一次性拉全量后建内存索引
+       * 失败处理:console.warn 后按全部部门出数,页面不阻断、不白屏
+       */
+      async initOrgIndex() {
+        try {
+          const list = await listOrganizations();
+          this.orgIndex = buildOrgIndex(list);
+          console.info('[eos-dashboard] 组织树加载完成', {
+            节点数: this.orgIndex.total,
+            公司数: this.orgIndex.companies.length
+          });
+        } catch (e) {
+          this.orgIndex = null;
+          console.warn('[eos-dashboard] 组织树加载失败,按全部部门出数', {
+            error: e && e.message
+          });
+        }
+      },
+      // 登录组织 id:拿不到就当没有(退到全部部门),不抛错打断首屏
+      readCurrentGroupId() {
+        try {
+          const user = getCurrentUser() || {};
+          return user.currentGroupId;
+        } catch (e) {
+          console.warn('[eos-dashboard] 读取登录组织失败', { error: e && e.message });
+          return undefined;
+        }
+      },
+      /**
+       * 默认值:本部门 + 其所属公司;解析不到本部门退到公司一级;连公司也没有则全部部门
+       * 只改 companyId / deptId,用户已选的档位与自定义区间保持不动
+       */
+      applyDefaultFilters() {
+        const currentGroupId = this.readCurrentGroupId();
+        const resolved = resolveDefaultSelection(this.orgIndex, currentGroupId);
+        this.orgUnmatched = !resolved.matched;
+        this.resolvedGroupId = hasValue(currentGroupId) ? currentGroupId : null;
+        this.filters.companyId = resolved.companyId;
+        this.filters.deptId = resolved.deptId;
+        console.info('[eos-dashboard] 默认筛选解析', {
+          currentGroupId: hasValue(currentGroupId) ? currentGroupId : '',
+          companyId: hasValue(resolved.companyId) ? resolved.companyId : '',
+          deptId: hasValue(resolved.deptId) ? resolved.deptId : '',
+          matched: resolved.matched
+        });
+      },
+      /**
+       * 首页请求体:{ scope, companyId, deptId, startDate, endDate }
+       * companyId / deptId 为空时键不出现(undefined 不参与 JSON 序列化);区间两端都有值才带
+       */
+      buildQuery() {
+        const f = this.filters || {};
+        const query = { scope: f.scope || 'MONTH' };
+        Object.assign(query, buildOrgFilterParams(f));
+        if (hasValue(f.startDate) && hasValue(f.endDate)) {
+          query.startDate = f.startDate;
+          query.endDate = f.endDate;
+        }
+        return query;
+      },
       getBoardFullscreenElement() {
         return document.fullscreenElement || document.webkitFullscreenElement || null;
       },
@@ -172,34 +299,78 @@
         });
       },
       async loadHome(silent) {
+        // 请求序号:并发时旧响应回来直接丢弃,既不写数据也不动 loading / refreshing
+        const seq = (this.loadSeq += 1);
         if (!silent) {
           this.loading = true;
         }
         // 刷新按钮点击走 silent 分支,这里同步按钮的旋转/置灰状态
         this.refreshing = true;
-        const scope = this.scope;
+        const query = this.buildQuery();
         const startedAt = Date.now();
-        console.info('[eos-dashboard] 加载看板', { scope, 上次区间: this.scopeRangeText });
+        console.info('[eos-dashboard] 加载看板', Object.assign({}, query, { 上次区间: this.scopeRangeText }));
         try {
-          const data = await getDashboardHome(scope);
+          const data = await getDashboardHome(query);
+          if (seq !== this.loadSeq) {
+            console.info('[eos-dashboard] 丢弃过期响应', { seq, 最新序号: this.loadSeq });
+            return;
+          }
           this.applyData(data);
           if (silent) {
             this.$message.success(`预警数据已刷新(${((Date.now() - startedAt) / 1000).toFixed(1)}s)`);
           }
           console.info('[eos-dashboard] 加载完成', {
-            scope,
+            scope: query.scope,
             区间: this.scopeRangeText,
             耗时: Date.now() - startedAt
           });
         } catch (e) {
+          if (seq !== this.loadSeq) {
+            console.info('[eos-dashboard] 丢弃过期失败响应', { seq, 最新序号: this.loadSeq });
+            return;
+          }
           this.applyData(null);
-          console.error('[eos-dashboard] 加载失败', { scope, error: e });
+          console.error('[eos-dashboard] 加载失败', { scope: query.scope, error: e });
           this.$message.error(`看板数据加载失败:${this.errorText(e)}`);
         } finally {
-          this.loading = false;
-          this.refreshing = false;
+          // 序号不一致说明已有更新的请求在跑,loading / refreshing 交给它收尾
+          if (seq === this.loadSeq) {
+            this.loading = false;
+            this.refreshing = false;
+          }
         }
       },
+      /**
+       * 检索行变化 → 落库到 filters → 只发 1 次查询
+       * 切公司时 boardFilters 已在同一份载荷里清空 deptId,这里一次性写入,不会二次查询
+       */
+      handleFilterChange(next) {
+        const merged = {
+          scope: (next && next.scope) || 'MONTH',
+          companyId: next ? next.companyId : undefined,
+          deptId: next ? next.deptId : undefined,
+          startDate: next ? next.startDate : undefined,
+          endDate: next ? next.endDate : undefined
+        };
+        Object.keys(merged).forEach((key) => {
+          this.filters[key] = merged[key];
+        });
+        console.info('[eos-dashboard] 筛选条件变化', this.buildQuery());
+        this.loadHome();
+      },
+      // 顶栏切换组织($store.state.user.info 变化)→ 重解析默认值并重查
+      async handleLoginOrgChange() {
+        const currentGroupId = this.readCurrentGroupId();
+        if (String(currentGroupId) === String(this.resolvedGroupId)) {
+          // 首屏 info 填充 / 角色切换等并未改变登录组织:不重复查询
+          return;
+        }
+        console.info('[eos-dashboard] 登录组织变化,重解析默认筛选', {
+          currentGroupId: hasValue(currentGroupId) ? currentGroupId : ''
+        });
+        this.applyDefaultFilters();
+        await this.loadHome();
+      },
       // 后端业务提示为中文,axios 自身异常(Network Error 等)统一替换为中文兜底
       errorText(e) {
         const message = e && e.message;
@@ -218,16 +389,8 @@
       },
       // M01 卡片点击 → 打开明细弹窗(其余 5 张卡仍走原有菜单下钻)
       openRevenueDetail() {
-        console.info('[eos-dashboard] 打开 M01 营业收入下钻明细', { scope: this.scope });
+        console.info('[eos-dashboard] 打开 M01 营业收入下钻明细', this.buildQuery());
         this.revenueDetailVisible = true;
-      },
-      changeScope(scope) {
-        if (this.scope === scope || this.loading) {
-          return;
-        }
-        console.info('[eos-dashboard] 切换查询档位', { from: this.scope, to: scope });
-        this.scope = scope;
-        this.loadHome();
       }
     }
   };

+ 183 - 0
src/views/home/org-index.js

@@ -0,0 +1,183 @@
+/**
+ * 组织树索引(公司/集团 → 部门 级联)
+ * ===========================================================================
+ * 组织接口 listOrganizations() 一次返回全量扁平列表,这里在内存里建索引:
+ * 切公司只走内存的 childrenMap,不再为级联补发组织请求。
+ * 全部是纯函数(不依赖 Vue / 全局状态),便于直接单测。
+ */
+
+// group_type 字典:10 集团 / 20 公司 / 30 部门 / 40 工厂
+export const ORG_TYPE = { GROUP: 10, COMPANY: 20, DEPT: 30, FACTORY: 40 };
+
+// 工厂节点在部门下拉里的 label 后缀(同一层级要能区分「部门」与「工厂」)
+export const FACTORY_LABEL_SUFFIX = '(工厂)';
+
+/**
+ * 判空:null / undefined / 空串一律视为「未选择」
+ * 后端 companyId / deptId 是 Long,空值必须不下发(空串会让后端反序列化失败)
+ */
+export function hasValue(v) {
+  return v !== null && v !== undefined && v !== '';
+}
+
+/** 索引键:避免 10 与 '10' 这类 id 类型差异导致匹配不到 */
+function idKey(v) {
+  return hasValue(v) ? String(v) : '';
+}
+
+function typeOf(node) {
+  const t = Number(node && node.type);
+  return Number.isNaN(t) ? -1 : t;
+}
+
+/** 公司/集团:一级下拉的可选项(type 10 集团 / 20 公司) */
+export function isCompanyNode(node) {
+  const t = typeOf(node);
+  return t === ORG_TYPE.GROUP || t === ORG_TYPE.COMPANY;
+}
+
+/** 部门/工厂:二级下拉的可选项(type 30 部门 / 40 工厂) */
+export function isDeptNode(node) {
+  const t = typeOf(node);
+  return t === ORG_TYPE.DEPT || t === ORG_TYPE.FACTORY;
+}
+
+/**
+ * 建内存索引
+ * @param {Array} list listOrganizations() 的原样返回(扁平数组,元素含 id/parentId/name/type/status)
+ * @returns {{byId: Object, childrenMap: Object, companies: Array, total: number}}
+ */
+export function buildOrgIndex(list) {
+  const nodes = (Array.isArray(list) ? list : []).filter((n) => n && hasValue(n.id));
+  const byId = {};
+  const childrenMap = {};
+  nodes.forEach((node) => {
+    byId[idKey(node.id)] = node;
+  });
+  nodes.forEach((node) => {
+    const parentKey = idKey(node.parentId);
+    if (!childrenMap[parentKey]) {
+      childrenMap[parentKey] = [];
+    }
+    childrenMap[parentKey].push(node);
+  });
+  // 一级下拉:集团 + 公司,停用(status === 0)的不给选
+  const companies = nodes
+    .filter((node) => isCompanyNode(node) && Number(node.status) !== 0)
+    .map((node) => ({ id: node.id, name: node.name, type: typeOf(node) }));
+  return { byId, childrenMap, companies, total: nodes.length };
+}
+
+/**
+ * 部门下拉选项:所选公司/集团的子树里 type ∈ {30,40} 的全部节点(逐层下钻,工厂下仍可能有部门)
+ * @param {Object} index buildOrgIndex() 的结果
+ * @param {*} companyId 所选公司/集团 id(为空返回空数组,由下拉的 no-data-text 说明原因)
+ * @returns {Array<{id, name, label, type}>}
+ */
+export function departmentOptions(index, companyId) {
+  if (!index || !hasValue(companyId)) {
+    return [];
+  }
+  const root = index.byId[idKey(companyId)];
+  if (!root) {
+    return [];
+  }
+  const options = [];
+  const visited = {};
+  visited[idKey(root.id)] = true;
+  const queue = [root];
+  while (queue.length) {
+    const current = queue.shift();
+    const children = index.childrenMap[idKey(current.id)] || [];
+    children.forEach((child) => {
+      const key = idKey(child.id);
+      if (visited[key]) {
+        return;
+      }
+      visited[key] = true;
+      if (isDeptNode(child)) {
+        options.push({
+          id: child.id,
+          name: child.name,
+          label: typeOf(child) === ORG_TYPE.FACTORY ? `${child.name}${FACTORY_LABEL_SUFFIX}` : child.name,
+          type: typeOf(child)
+        });
+      }
+      queue.push(child);
+    });
+  }
+  return options;
+}
+
+/**
+ * 向上找最近的「公司/集团」祖先(本部门 → 所属公司)
+ * @param {Object} index buildOrgIndex() 的结果
+ * @param {Object} node 起始节点
+ * @returns {Object|null} 公司/集团节点,找不到返回 null(防止脏 parentId 成环)
+ */
+export function findCompanyAncestor(index, node) {
+  if (!index || !node) {
+    return null;
+  }
+  const visited = { [idKey(node.id)]: true };
+  let current = node;
+  while (current && hasValue(current.parentId)) {
+    const parent = index.byId[idKey(current.parentId)];
+    if (!parent || visited[idKey(parent.id)]) {
+      return null;
+    }
+    if (isCompanyNode(parent)) {
+      return parent;
+    }
+    visited[idKey(parent.id)] = true;
+    current = parent;
+  }
+  return null;
+}
+
+/**
+ * 默认筛选解析:默认「本部门 + 其所属公司」
+ *   1. 登录组织是部门/工厂 → 部门 + 最近的公司/集团祖先
+ *   2. 登录组织是公司/集团 → 只到公司一级(不选中部门)
+ *   3. 匹配不到(或部门不在任何公司之下)→ 全部部门(matched = false,界面给弱提示)
+ * @param {Object} index buildOrgIndex() 的结果
+ * @param {*} currentGroupId 登录组织 id(getCurrentUser().currentGroupId)
+ * @returns {{companyId: *, deptId: *, matched: boolean}}
+ */
+export function resolveDefaultSelection(index, currentGroupId) {
+  const fallback = { companyId: undefined, deptId: undefined, matched: false };
+  if (!index || !hasValue(currentGroupId)) {
+    return fallback;
+  }
+  const node = index.byId[idKey(currentGroupId)];
+  if (!node) {
+    return fallback;
+  }
+  if (isCompanyNode(node)) {
+    return { companyId: node.id, deptId: undefined, matched: true };
+  }
+  if (isDeptNode(node)) {
+    const company = findCompanyAncestor(index, node);
+    if (company) {
+      return { companyId: company.id, deptId: node.id, matched: true };
+    }
+  }
+  return fallback;
+}
+
+/**
+ * 组织维度入参:companyId / deptId 只在有值时出现(键缺失即不下发,绝不发空串)
+ * @param {Object} filters { companyId, deptId }
+ * @returns {{companyId?: *, deptId?: *}}
+ */
+export function buildOrgFilterParams(filters) {
+  const f = filters || {};
+  const params = {};
+  if (hasValue(f.companyId)) {
+    params.companyId = f.companyId;
+  }
+  if (hasValue(f.deptId)) {
+    params.deptId = f.deptId;
+  }
+  return params;
+}