yyb
18 小时以前 3a48d44d1eb5340c7caf2b010e1e9f081955d56c
src/views/salesManagement/salesLedger/index.vue
@@ -32,6 +32,20 @@
                    prefix-icon="Search"
                    @change="handleQuery" />
        </el-form-item>
        <el-form-item label="产品宽(mm):">
          <el-input v-model="searchForm.width"
                    placeholder="请输入"
                    clearable
                    prefix-icon="Search"
                    @change="handleQuery" />
        </el-form-item>
        <el-form-item label="产品高(mm):">
          <el-input v-model="searchForm.height"
                    placeholder="请输入"
                    clearable
                    prefix-icon="Search"
                    @change="handleQuery" />
        </el-form-item>
        <el-form-item label="录入日期:">
          <el-date-picker v-model="searchForm.entryDate"
                          value-format="YYYY-MM-DD"
@@ -95,6 +109,20 @@
          <el-button type="primary"
                     plain
                     @click="handleImport">导入</el-button>
          <el-dropdown @command="handleHistoryImportCommand">
            <el-button type="primary"
                       plain>
              历史迁移<el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="notShipped">未发货</el-dropdown-item>
                <el-dropdown-item command="shipped">已发货</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button @click="handleOut">导出</el-button>
          <el-button type="danger"
                     plain
@@ -319,6 +347,14 @@
                         width="220"
                         show-overflow-tooltip
                         :formatter="formattedNumber" />
        <el-table-column label="面积"
                         prop="productTotalArea"
                         width="120"
                         show-overflow-tooltip />
        <el-table-column label="数量"
                         prop="productTotalQuantity"
                         width="120"
                         show-overflow-tooltip />
        <el-table-column label="发货状态"
                         width="140"
                         align="center">
@@ -415,6 +451,7 @@
               label-width="140px"
               label-position="top"
               :rules="rules"
               @keydown.capture="handleTabScrollFollow"
               ref="formRef">
        <!-- 报价单导入入口:放在表单顶部,选择后反显客户/业务员等 -->
        <el-row v-if="operationType === 'add'"
@@ -721,7 +758,7 @@
                               clearable
                               @change="() => handleInlineUnitPriceChange(scope.row)"
                               @input="() => handleInlineUnitPriceChange(scope.row)" />
              <span v-else>{{ formattedNumber(null, null, scope.row.taxInclusiveUnitPrice ?? 0) }}</span>
              <span v-else>{{ formattedNumber(null, null, scope.row.taxInclusiveUnitPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="税率(%)"
@@ -927,6 +964,13 @@
                           :disabled="isProductShipped(scope.row)"
                           @click="editProductInline(scope.row, scope.$index)">
                  编辑
                </el-button>
                <el-button link
                           type="primary"
                           size="small"
                           :disabled="isProductShipped(scope.row) || hasEditingProductRow()"
                           @click="copyProductInline(scope.row, scope.$index)">
                  复制新建
                </el-button>
                <el-popover :width="560"
                            trigger="click"
@@ -1645,6 +1689,46 @@
               title="选择入库产品"
               width="60%"
               :close-on-click-modal="false">
      <div style="margin-bottom: 12px;">
        <el-form>
          <el-form-item required>
            <template #label>
              <div style="display: flex; align-items: center; justify-content: space-between; width: 100%;">
                <span>审批人选择:</span>
                <el-button type="primary"
                           size="small"
                           @click="addStockApproverNode"
                           icon="Plus">新增节点</el-button>
              </div>
            </template>
            <div class="approver-nodes-container">
              <div v-for="(node, index) in stockApproverNodes"
                   :key="node.id"
                   class="approver-node-item">
                <div class="approver-node-header">
                  <span class="approver-node-label">审批节点 {{ index + 1 }}</span>
                  <el-button v-if="stockApproverNodes.length > 1"
                             type="danger"
                             size="small"
                             text
                             @click="removeStockApproverNode(index)"
                             icon="Delete">删除</el-button>
                </div>
                <el-select v-model="node.userId"
                           placeholder="请选择审批人"
                           filterable
                           clearable
                           style="width: 100%;">
                  <el-option v-for="item in stockApproverOptions"
                             :key="item.userId"
                             :label="item.userName"
                             :value="item.userId" />
                </el-select>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="stockProductList"
                border
                stripe
@@ -1785,6 +1869,15 @@
  const selectedStockProductIds = ref([]);
  const stockLoading = ref(false);
  const currentStockLedgerId = ref(null);
  const stockApproverOptions = ref([]);
  const stockApproverNodes = ref([{ id: 1, userId: null }]);
  let nextStockApproverId = 2;
  const addStockApproverNode = () => {
    stockApproverNodes.value.push({ id: nextStockApproverId++, userId: null });
  };
  const removeStockApproverNode = index => {
    stockApproverNodes.value.splice(index, 1);
  };
  const ledgerQrDialogVisible = ref(false);
  const ledgerQrCompositeUrl = ref("");
@@ -1901,6 +1994,8 @@
      customerName: "", // 客户名称
      customerId: "", // 客户ID(查询下拉)
      salesContractNo: "", // 销售合同编号
      width: undefined, // 产品宽(mm)
      height: undefined, // 产品高(mm)
      entryDate: null, // 录入日期
      entryDateStart: undefined,
      entryDateEnd: undefined,
@@ -2045,6 +2140,37 @@
    return (productData.value || []).some(r => r && r.__editing);
  };
  const buildEmptyInlineProductRow = () => ({
    id: null,
    __tempKey: `__temp_${Date.now()}_${Math.random().toString(16).slice(2)}`,
    __editing: true,
    __isNew: true,
    __productCategoryId: null,
    productCategory: "",
    productModelId: null,
    specificationModel: "",
    thickness: null,
    quantity: null,
    taxInclusiveUnitPrice: null,
    taxRate: "",
    taxInclusiveTotalPrice: null,
    taxExclusiveTotalPrice: null,
    invoiceType: "",
    width: null,
    height: null,
    perimeter: null,
    actualPieceArea: null,
    actualTotalArea: null,
    settlePieceArea: null,
    settleTotalArea: null,
    processRequirement: "",
    remark: "",
    salesProductProcessList: [],
    processFlowConfigId: null,
    floorCode: "",
    heavyBox: "",
  });
  const addProductInline = async () => {
    if (operationType.value === "view") return;
    if (hasEditingProductRow()) {
@@ -2053,40 +2179,70 @@
    }
    await getProductOptions();
    await fetchOtherAmountSelectOptions(true);
    const row = {
      id: null,
      __tempKey: `__temp_${Date.now()}_${Math.random().toString(16).slice(2)}`,
      __editing: true,
      __isNew: true,
      __productCategoryId: null,
      productCategory: "",
      productModelId: null,
      specificationModel: "",
      thickness: null,
      quantity: 0,
      taxInclusiveUnitPrice: 0,
      taxRate: "",
      taxInclusiveTotalPrice: 0,
      taxExclusiveTotalPrice: 0,
      invoiceType: "",
      width: 0,
      height: 0,
      perimeter: 0,
      actualPieceArea: 0,
      actualTotalArea: 0,
      settlePieceArea: 0,
      settleTotalArea: 0,
      processRequirement: "",
      remark: "",
      salesProductProcessList: [],
      processFlowConfigId: null,
      floorCode: "",
      heavyBox: "",
    };
    const row = buildEmptyInlineProductRow();
    productData.value.push(row);
    editingProductRow.value = row;
    // 让现有的计算/其他金额逻辑复用当前行
    productForm.value = row;
  };
  const copyProductInline = async row => {
    if (operationType.value === "view") return;
    if (!row) return;
    if (isProductShipped(row)) {
      proxy.$modal.msgWarning("已发货或审核通过的产品不能复制");
      return;
    }
    if (hasEditingProductRow()) {
      proxy.$modal.msgWarning("请先保存或取消当前编辑行");
      return;
    }
    await getProductOptions();
    await fetchOtherAmountSelectOptions(true);
    const copied = buildEmptyInlineProductRow();
    copied.__productCategoryId =
      row.__productCategoryId ??
      findNodeIdByLabel(productOptions.value, row.productCategory) ??
      null;
    copied.productCategory = row.productCategory ?? "";
    copied.productModelId = row.productModelId ?? null;
    copied.specificationModel = row.specificationModel ?? "";
    copied.thickness =
      row.thickness !== null && row.thickness !== undefined && row.thickness !== ""
        ? Number(row.thickness)
        : null;
    // 复制新建仅带出产品大类与规格型号,其他数字字段全部留空,避免出现 0.00
    copied.quantity = null;
    copied.taxInclusiveUnitPrice = null;
    copied.taxInclusiveTotalPrice = null;
    copied.taxExclusiveTotalPrice = null;
    copied.width = null;
    copied.height = null;
    copied.perimeter = null;
    copied.actualPieceArea = null;
    copied.actualTotalArea = null;
    copied.settlePieceArea = null;
    copied.settleTotalArea = null;
    // 复制时按“产品大类 + 规格型号名称”反查型号 id,确保下拉能正确回显
    try {
      if (copied.__productCategoryId) {
        const models = await modelList({ id: copied.__productCategoryId });
        modelOptions.value = models || [];
        const matchedModel = (modelOptions.value || []).find(
          m => m.model === copied.specificationModel
        );
        copied.productModelId = matchedModel?.id ?? copied.productModelId ?? null;
      }
    } catch (e) {
      console.error("复制时加载产品规格型号失败", e);
    }
    productData.value.push(copied);
    editingProductRow.value = copied;
    productForm.value = copied;
  };
  const editProductInline = async (row, index) => {
@@ -2748,6 +2904,10 @@
      proxy.$modal.msgError("导入失败,请重试");
    },
  });
  const HISTORY_IMPORT_URL_MAP = {
    notShipped: "/sales/ledger/salesHistory/notShippingImport",
    shipped: "/sales/ledger/salesHistory/shippingImport",
  };
  const changeDaterange = value => {
    if (value) {
@@ -2798,14 +2958,44 @@
        delete params.customerName;
      }
    }
    const widthValue =
      params.width != null ? String(params.width).trim() : "";
    if (widthValue) {
      params.width = widthValue;
    } else {
      delete params.width;
    }
    const heightValue =
      params.height != null ? String(params.height).trim() : "";
    if (heightValue) {
      params.height = heightValue;
    } else {
      delete params.height;
    }
    const shouldAutoExpandBySize = Boolean(params.width || params.height);
    delete params.customerId;
    return ledgerListPage(params)
      .then(res => {
      .then(async res => {
        tableLoading.value = false;
        tableData.value = res.records;
        tableData.value.map(item => {
          item.children = [];
        });
        if (shouldAutoExpandBySize && tableData.value.length > 0) {
          const loadChildrenTasks = tableData.value.map(item =>
            productList({ salesLedgerId: item.id, type: 1 })
              .then(productRes => {
                item.children = Array.isArray(productRes?.data)
                  ? productRes.data
                  : [];
              })
              .catch(() => {
                item.children = [];
              })
          );
          await Promise.all(loadChildrenTasks);
          expandedRowKeys.value = tableData.value.map(item => item.id);
        }
        total.value = res.total;
        return res;
      })
@@ -2834,22 +3024,36 @@
    currentStockLedgerId.value = id;
    selectedStockProductIds.value = [];
    stockProductList.value = [];
    stockApproverNodes.value = [{ id: 1, userId: null }];
    nextStockApproverId = 2;
    stockDialogVisible.value = true;
    stockLoading.value = true;
    try {
      const approverRes = await approveUserList({ approveType: 9 });
      stockApproverOptions.value = Array.isArray(approverRes?.data)
        ? approverRes.data.map(item => ({
            userId: item.userId,
            userName: item.userName,
          }))
        : [];
      const res = await productList({ salesLedgerId: id, type: 1 });
      stockProductList.value = [];
      stockProductList.value =
        res.data.filter(item => item.productStockStatus == 0 || item.productStockStatus == 1) || [];
    } catch (e) {
      proxy?.$modal?.msgError?.("获取产品列表失败");
      proxy?.$modal?.msgError?.("获取产品或审批人失败");
    } finally {
      stockLoading.value = false;
    }
  };
  const submitStock = async () => {
    const hasEmptyApprover = stockApproverNodes.value.some(node => !node.userId);
    if (hasEmptyApprover) {
      ElMessage.warning("请为所有审批节点选择审批人");
      return;
    }
    if (selectedStockProductIds.value.length === 0) {
      ElMessage.warning("请选择至少一个产品进行入库");
      return;
@@ -2867,9 +3071,16 @@
    proxy?.$modal?.loading?.("正在入库,请稍候...");
    try {
      const approveUserIds = stockApproverNodes.value.map(node => node.userId).join(",");
      const approveUserName = stockApproverNodes.value
        .map(node => stockApproverOptions.value.find(item => String(item.userId) === String(node.userId))?.userName)
        .filter(Boolean)
        .join(",");
      await salesStock({
        salesLedgerId: currentStockLedgerId.value,
        salesLedgerProducts: selectedStockProductIds.value,
        approveUserIds,
        approveUserName,
      });
      proxy?.$modal?.msgSuccess?.("入库成功");
      stockDialogVisible.value = false;
@@ -2967,7 +3178,63 @@
    });
  };
  const formattedNumber = (row, column, cellValue) => {
    return parseFloat(cellValue).toFixed(2);
    if (cellValue === null || cellValue === undefined || cellValue === "") {
      return "";
    }
    const num = Number(cellValue);
    return Number.isFinite(num) ? num.toFixed(2) : "";
  };
  const scrollElementIntoVisibleArea = target => {
    if (!target || !(target instanceof HTMLElement)) return;
    let parent = target.parentElement;
    while (parent && parent !== document.body) {
      const style = window.getComputedStyle(parent);
      const canScrollX =
        (style.overflowX === "auto" ||
          style.overflowX === "scroll" ||
          style.overflowX === "overlay") &&
        parent.scrollWidth > parent.clientWidth;
      const canScrollY =
        (style.overflowY === "auto" ||
          style.overflowY === "scroll" ||
          style.overflowY === "overlay") &&
        parent.scrollHeight > parent.clientHeight;
      if (canScrollX || canScrollY) {
        const parentRect = parent.getBoundingClientRect();
        const targetRect = target.getBoundingClientRect();
        if (canScrollX) {
          const targetCenterX = targetRect.left + targetRect.width / 2;
          const parentCenterX = parentRect.left + parentRect.width / 2;
          const deltaX = targetCenterX - parentCenterX;
          if (Math.abs(deltaX) > 2) {
            parent.scrollLeft += deltaX;
          }
        }
        if (canScrollY) {
          const targetCenterY = targetRect.top + targetRect.height / 2;
          const parentCenterY = parentRect.top + parentRect.height / 2;
          const deltaY = targetCenterY - parentCenterY;
          if (Math.abs(deltaY) > 2) {
            parent.scrollTop += deltaY;
          }
        }
      }
      parent = parent.parentElement;
    }
  };
  const handleTabScrollFollow = e => {
    if (!e || e.key !== "Tab") return;
    requestAnimationFrame(() => {
      const active = document.activeElement;
      if (active instanceof HTMLElement) {
        scrollElementIntoVisibleArea(active);
      }
    });
  };
  // 获取tree子数据
  const getModels = value => {
@@ -3108,6 +3375,8 @@
  const summarizeMainTable = param => {
    return proxy.summarizeTable(param, [
      "contractAmount",
      "productTotalQuantity",
      "productTotalArea",
      "taxInclusiveTotalPrice",
      "taxExclusiveTotalPrice",
    ]);
@@ -3595,13 +3864,25 @@
    otherAmountAddDialogVisible.value = false;
    otherAmountAddId.value = null;
  };
  // 导入
  const handleImport = () => {
    importUpload.title = "导入销售台账";
  const openImportDialog = (title, url) => {
    importUpload.title = title;
    importUpload.url = import.meta.env.VITE_APP_BASE_API + url;
    importUpload.open = true;
    importUpload.isUploading = false;
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles();
    }
  };
  // 导入
  const handleImport = () => {
    openImportDialog("导入销售台账", "/sales/ledger/import");
  };
  // 历史迁移
  const handleHistoryImportCommand = command => {
    const url = HISTORY_IMPORT_URL_MAP[command];
    if (!url) return;
    const title = command === "shipped" ? "历史迁移-已发货" : "历史迁移-未发货";
    openImportDialog(title, url);
  };
  // 下载导入模板
@@ -3751,7 +4032,7 @@
      try {
        const res = await getSalesInvoices(selectedIds);
        const salesInvoiceData = res?.data ?? {};
        printSalesDeliveryNote(salesInvoiceData, selectedRow);
        await printSalesDeliveryNote(salesInvoiceData, selectedRow, selectedIds);
      } catch (error) {
        console.error("打印销售发货单失败:", error);
        proxy.$modal.msgError("打印失败,请稍后重试");
@@ -4224,6 +4505,40 @@
    return statusStr === "待发货" || statusStr === "审核拒绝";
  };
  const getLedgerDisplayName = ledger =>
    String(ledger?.salesContractNo || "").trim() ||
    String(ledger?.projectName || "").trim() ||
    `ID:${ledger?.id ?? "-"}`;
  const validateLedgersStockedBeforeDelivery = async ledgers => {
    const invalidLedgers = [];
    for (const ledger of ledgers || []) {
      const ledgerId = ledger?.id;
      const ledgerName = getLedgerDisplayName(ledger);
      if (!ledgerId) {
        invalidLedgers.push(`${ledgerName}(缺少台账ID)`);
        continue;
      }
      let products = [];
      try {
        const res = await productList({ salesLedgerId: ledgerId, type: 1 });
        products = Array.isArray(res?.data) ? res.data : [];
      } catch (e) {
        invalidLedgers.push(`${ledgerName}(明细加载失败)`);
        continue;
      }
      const unstockedProducts = products.filter(
        item => Number(item?.productStockStatus) !== 2
      );
      if (unstockedProducts.length > 0) {
        invalidLedgers.push(
          `${ledgerName}(未全部入库${unstockedProducts.length}条)`
        );
      }
    }
    return invalidLedgers;
  };
  const handleBulkDelivery = async () => {
    if (selectedRows.value.length === 0) {
      proxy.$modal.msgWarning("请选择数据");
@@ -4232,7 +4547,7 @@
    // 只允许【未发货/审批失败】进入发货流程
    const statusItem = selectedRows.value[0].deliveryStatus;
    const isTrue = true;
    let isTrue = true;
    selectedRows.value.forEach(row => {
      if (row.deliveryStatus != 1 && row.deliveryStatus != 3) {
        proxy.$modal.msgWarning("仅未发货或审批失败的台账可以发货");
@@ -4246,6 +4561,29 @@
      }
    });
    if (!isTrue) {
      return;
    }
    proxy.$modal.loading("正在校验明细入库状态,请稍候...");
    const invalidLedgers = await validateLedgersStockedBeforeDelivery(
      selectedRows.value
    );
    proxy.$modal.closeLoading();
    if (invalidLedgers.length > 0) {
      try {
        await ElMessageBox.alert(
          `以下销售台账存在未全部入库的明细,暂不可发货:\n${invalidLedgers.join(
            "\n"
          )}`,
          "提示",
          {
            type: "warning",
            confirmButtonText: "知道了",
          }
        );
      } catch {
        /* 关闭弹窗 */
      }
      return;
    }
@@ -4365,11 +4703,30 @@
  };
  // 打开发货弹框(单条)
  const openDeliveryForm = row => {
  const openDeliveryForm = async row => {
    // 只允许【未发货/审批失败】发货;已发货/审批中不允许
    const status = Number(row.deliveryStatus);
    if (status !== 1 && status !== 3) {
      proxy.$modal.msgWarning("只有发货状态为未发货或审批失败的记录才可以发货");
      return;
    }
    proxy.$modal.loading("正在校验明细入库状态,请稍候...");
    const invalidLedgers = await validateLedgersStockedBeforeDelivery([row]);
    proxy.$modal.closeLoading();
    if (invalidLedgers.length > 0) {
      try {
        await ElMessageBox.alert(
          `当前销售台账存在未全部入库的明细,暂不可发货:\n${invalidLedgers[0]}`,
          "提示",
          {
            type: "warning",
            confirmButtonText: "知道了",
          }
        );
      } catch {
        /* 关闭弹窗 */
      }
      return;
    }
@@ -4536,4 +4893,54 @@
  .ledger-qr-save-btn {
    margin-bottom: 12px;
  }
  .approver-nodes-container {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
  }
  .approver-node-item {
    flex: 0 0 calc(33.333% - 12px);
    min-width: 200px;
    padding: 12px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;
  }
  .approver-node-item:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  .approver-node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  .approver-node-label {
    font-size: 13px;
    font-weight: 500;
    color: #606266;
  }
  @media (max-width: 1200px) {
    .approver-node-item {
      flex: 0 0 calc(50% - 8px);
    }
  }
  @media (max-width: 768px) {
    .approver-node-item {
      flex: 0 0 100%;
    }
  }
</style>