5 Commits

Author SHA1 Message Date
8cf94c6c4d V3.56 2026-07-15 09:18:26 +08:00
31903bdb39 feat: 基础信息弹窗新增"发起采购申请"按钮, 跳转采购管理自动预填物料+默认审批人
- material/list.vue: 弹窗头部新增"发起采购申请"按钮, 携带物料信息跳转/purchase
- purchase/index.vue: onMounted读取URL参数自动弹窗并预填物料
- purchase/index.vue: fetchDefaultApprover取当前用户上一次采购申请的审批人作为默认值
- 商家链接placeholder去掉"选填"字样
2026-07-14 17:13:31 +08:00
68fd93b457 fix: BOM跳转恢复 + 采购单导入优化 + 基础信息表单禁用守卫
- BOM: 移除父件/子件跳转按钮的 isReadOnlyMode 限制, 任何模式均可跳转
- BOM: 补全缺失的5个权限码(sys_element + sys_role_permission)
- 采购单导入: supplier_link→detail_link, 新增采购人/邮箱自动填充
- 采购单导入: 实时搜索(300ms防抖)+模糊匹配, 保留搜索按钮
- 采购单导入: 移除原始/详情链接的历史 autocomplete
- 基础信息: el-form 增加 formDisabled, 无 material_list:operation 时全局禁用
- /approved-unstocked API 增加 permission_required(inbound_buy)
- PurchaseRequest.to_dict() 增加 requester_email
2026-07-14 17:02:07 +08:00
538b6cb818 feat: 采购单导入自动填充采购人/邮箱/详情链接 + 实时搜索
- PurchaseRequest.to_dict() 新增 requester_email
- 导入时自动填入: 采购人(requester_name) + 邮箱(requester_email) + 详情链接(supplier_link)
- 移除原始链接/详情链接的历史 autocomplete, 改为纯输入框+权限守卫
- 采购单导入搜索改为实时输入搜索(300ms防抖), 保留搜索按钮
2026-07-14 16:29:19 +08:00
8f468a0a39 fix: 修复全局字段权限导致数据显示为空的问题
根因: /permissions/role/<role_code> 接口要求 system_permission,
非管理员角色无法获取自身权限 → 权限数组为空 → 前后端字段全被过滤

修复:
- permission.py: 查自己角色不再需要 system_permission, 解除权限死锁
- 5个 inbound API: 恢复完整 field_to_perm 映射, 每个字段均可独立权限管控
- 补齐遗漏字段(qty_inbound/qty_stock/qty_available/request_id/request_no)
- buy.vue: 入库表单价格字段加入 hasFormFieldPermission 守卫
2026-07-14 16:09:41 +08:00
15 changed files with 279 additions and 116 deletions

View File

@ -53,13 +53,9 @@ def get_current_user_permissions():
def filter_item_by_permissions(item_dict, user_permissions):
"""
根据用户权限过滤 item 字典,无权限的字段值置为 None
"""
# 如果用户拥有通配符权限,则不过滤
"""根据用户权限过滤字段,无权限的字段值置为 None"""
if 'material_list:*' in user_permissions:
return item_dict
# 字段名到权限码的映射(与前端 permissionMap 保持一致)
field_to_perm = {
'id': 'material_list:id',
'companyName': 'material_list:companyName',
@ -74,7 +70,11 @@ def filter_item_by_permissions(item_dict, user_permissions):
'generalManual': 'material_list:files',
'generalImage': 'material_list:files',
'referencePrice': 'material_list:referencePrice',
'isEnabled': 'material_list:isEnabled'
'isEnabled': 'material_list:isEnabled',
'isInspectionRequired': 'material_list:isInspectionRequired',
'visibilityLevel': 'material_list:visibilityLevel',
'manualLinkRemark': 'material_list:manualLinkRemark',
'productImageRemark': 'material_list:productImageRemark',
}
for field, perm_code in field_to_perm.items():
if field in item_dict and perm_code not in user_permissions:

View File

@ -34,44 +34,69 @@ def get_current_user_permissions():
def filter_item_by_permissions(item_dict, user_permissions):
"""
根据用户权限过滤 item 字典,无权限的字段值置为 None
根据用户权限过滤字段,无权限的字段值置为 None。
所有字段均可通过权限码独立控制。
"""
# 字段名到权限码的映射(与前端 permissionMap 保持一致)
# 字段名 → 权限码(与前端 permissionMap、数据库 sys_element/sys_menu 保持一致)
field_to_perm = {
# 基础身份
'id': 'inbound_buy:id',
'base_id': 'inbound_buy:base_id',
'global_print_id': 'inbound_buy:global_print_id',
'sku': 'inbound_buy:sku',
'barcode': 'inbound_buy:barcode',
'in_date': 'inbound_buy:in_date',
'serial_number': 'inbound_buy:sn_bn',
'batch_number': 'inbound_buy:sn_bn',
'status': 'inbound_buy:status',
'in_quantity': 'inbound_buy:in_quantity',
'stock_quantity': 'inbound_buy:stock_quantity',
'available_quantity': 'inbound_buy:available_quantity',
'inspection_status': 'inbound_buy:inspection_status',
'warehouse_location': 'inbound_buy:warehouse_location',
'unit_price': 'inbound_buy:unit_price',
'post_tax_unit_price': 'inbound_buy:post_tax_unit_price',
'tax_rate': 'inbound_buy:tax_rate',
'total_price': 'inbound_buy:total_price',
'currency': 'inbound_buy:currency',
'exchange_rate': 'inbound_buy:exchange_rate',
'supplier_name': 'inbound_buy:supplier_name',
'buyer_name': 'inbound_buy:buyer_name',
'buyer_email': 'inbound_buy:buyer_email',
'original_link': 'inbound_buy:original_link',
'detail_link': 'inbound_buy:detail_link',
'arrival_photo': 'inbound_buy:arrival_photo',
'inspection_report': 'inbound_buy:inspection_report',
'global_print_id_str': 'inbound_buy:global_print_id',
'company_name': 'inbound_buy:company_name',
'material_name': 'inbound_buy:material_name',
'spec_model': 'inbound_buy:spec_model',
'category': 'inbound_buy:category',
'unit': 'inbound_buy:unit',
'material_type': 'inbound_buy:material_type',
'company_name': 'inbound_buy:company_name',
'isInspectionRequired': 'inbound_buy:isInspectionRequired',
# 入库身份
'sku': 'inbound_buy:sku',
'inbound_date': 'inbound_buy:inbound_date',
'barcode': 'inbound_buy:barcode',
'serial_number': 'inbound_buy:sn_bn',
'batch_number': 'inbound_buy:sn_bn',
'warehouse_loc': 'inbound_buy:warehouse_loc',
'warehouse_location': 'inbound_buy:warehouse_loc',
# 状态
'status': 'inbound_buy:status',
'inspection_status': 'inbound_buy:inspection_status',
# 数量(三组命名,覆盖 model to_dict 中所有 key)
'in_quantity': 'inbound_buy:in_quantity',
'qty_inbound': 'inbound_buy:in_quantity',
'stock_quantity': 'inbound_buy:stock_quantity',
'qty_stock': 'inbound_buy:stock_quantity',
'available_quantity': 'inbound_buy:available_quantity',
'qty_available': 'inbound_buy:available_quantity',
# 价格
'unit_price': 'inbound_buy:unit_price',
'post_tax_unit_price': 'inbound_buy:post_tax_unit_price',
'total_price': 'inbound_buy:total_price',
'tax_rate': 'inbound_buy:tax_rate',
'currency': 'inbound_buy:currency',
'exchange_rate': 'inbound_buy:exchange_rate',
# 商务
'supplier_name': 'inbound_buy:supplier_name',
'purchaser': 'inbound_buy:purchaser',
'purchaser_email': 'inbound_buy:purchaser_email',
'source_link': 'inbound_buy:source_link',
'detail_link': 'inbound_buy:detail_link',
# 图片/附件
'arrival_photo': 'inbound_buy:arrival_photo',
'inspection_report': 'inbound_buy:inspection_report',
# 采购单关联
'request_id': 'inbound_buy:request_id',
'request_no': 'inbound_buy:request_no',
}
# 通配符(SUPER_ADMIN)不过滤
if 'inbound_buy:*' in user_permissions:
return item_dict
for field, perm_code in field_to_perm.items():
base_perm_code = perm_code.split(':')[-1] if ':' in perm_code else perm_code
if field in item_dict and perm_code not in user_permissions and base_perm_code not in user_permissions:
item_dict[field] = None
return item_dict
# 如果用户是超级管理员且有 'inbound_buy:*',则不过滤
if 'inbound_buy:*' in user_permissions:
return item_dict

View File

@ -19,6 +19,7 @@ def get_current_user_permissions():
return perm_dict.get('menus', []) + perm_dict.get('elements', [])
def filter_item_by_permissions(item_dict, user_permissions):
"""根据用户权限过滤字段,无权限的字段值置为 None"""
field_to_perm = {
'id': 'inbound_product:id', 'base_id': 'inbound_product:base_id', 'company_name': 'inbound_product:company_name',
'material_name': 'inbound_product:material_name', 'category': 'inbound_product:category',

View File

@ -19,6 +19,7 @@ def get_current_user_permissions():
return perm_dict.get('menus', []) + perm_dict.get('elements', [])
def filter_item_by_permissions(item_dict, user_permissions):
"""根据用户权限过滤字段,无权限的字段值置为 None"""
field_to_perm = {
'id': 'inbound_semi:id', 'base_id': 'inbound_semi:base_id', 'company_name': 'inbound_semi:company_name',
'material_name': 'inbound_semi:material_name', 'category': 'inbound_semi:category',

View File

@ -32,10 +32,7 @@ def get_current_user_permissions():
def filter_item_by_permissions(item_dict, user_permissions):
"""
根据用户权限过滤 item 字典,无权限的字段值置为 None
"""
# 字段名到权限码的映射(与前端 permissionMap 保持一致)
"""根据用户权限过滤字段,无权限的字段值置为 None"""
field_to_perm = {
'id': 'inbound_service:id',
'base_id': 'inbound_service:base_id',

View File

@ -13,6 +13,17 @@ def _get_operator_company():
role = claims.get('role', '')
if role and role.upper() == 'SUPER_ADMIN':
return None # 超管不限制公司
def _has_system_permission(role_code):
"""检查角色是否有 system_permission"""
try:
from app.services.auth_service import AuthService
perm_dict = AuthService.get_user_permissions(role_code)
all_perms = perm_dict.get('menus', []) + perm_dict.get('elements', [])
return 'system_permission' in all_perms
except Exception:
return False
return claims.get('company_name', '')
@ -31,10 +42,20 @@ def get_tree():
@permission_bp.route('/role/<string:role_code>', methods=['GET'])
@jwt_required()
@permission_required('system_permission')
def get_role_perms(role_code):
"""获取某个角色的权限列表(已选中的)"""
"""获取某个角色的权限列表。
- 查自己角色:不需要额外权限
- 查其他角色:需要 system_permission
"""
try:
claims = get_jwt()
current_role = (claims.get('role') or '').upper()
# 非管理员查其他角色 → 拒绝
if current_role != role_code.upper() and current_role != 'SUPER_ADMIN':
if not _has_system_permission(current_role):
return jsonify({'code': 403, 'msg': '无权查看其他角色的权限'}), 403
company_name = _get_operator_company()
data = PermissionService.get_role_permissions(role_code, company_name=company_name)
return jsonify({'code': 200, 'msg': '获取成功', 'data': data}), 200

View File

@ -213,6 +213,7 @@ def auto_fill_purchase():
# --------------------------------------------------------
@purchase_bp.route('/approved-unstocked', methods=['GET'])
@jwt_required()
@permission_required('inbound_buy')
def get_approved_unstocked_requests():
"""获取已审批通过且未入库的采购申请列表"""
try:

View File

@ -64,6 +64,16 @@ class PurchaseRequest(db.Model):
except Exception:
return f"用户({user_id})"
def _get_user_email(self, user_id):
if not user_id:
return ""
from app.models.system import SysUser
try:
user = db.session.get(SysUser, user_id)
return user.email or "" if user else ""
except Exception:
return ""
def to_dict(self):
return {
'id': self.id,
@ -82,6 +92,7 @@ class PurchaseRequest(db.Model):
'status_text': ['待审批', '已通过', '已驳回', '已完成'][self.status] if self.status in [0, 1, 2, 3] else '未知',
'requester_id': self.requester_id,
'requester_name': self._get_user_name(self.requester_id),
'requester_email': self._get_user_email(self.requester_id),
'approver_id': self.approver_id,
'approver_name': self._get_user_name(self.approver_id) if self.approver_id else None,
'approved_at': self.approved_at.strftime('%Y-%m-%d %H:%M:%S') if self.approved_at else None,

View File

@ -0,0 +1,44 @@
"""补全 BOM 模块缺失的权限码"""
import subprocess, sys
CODES = [
('bom_manage:parent_spec', '父件规格'),
('bom_manage:child_id', '子件ID'),
('bom_manage:dosage', '用量'),
('bom_manage:remark', '备注'),
]
SQLS = []
# 1. sys_element
for code, name in CODES:
SQLS.append(f"""INSERT INTO sys_element (menu_code, name, code, element_type)
SELECT 'bom_manage', '{name}', '{code}', 'column'
WHERE NOT EXISTS (SELECT 1 FROM sys_element WHERE code = '{code}');""")
# 2. sys_role_permission — 给已有 BOM 权限的角色补全
SQLS.append("""
INSERT INTO sys_role_permission (role_code, target_code, type, company_name)
SELECT rp.role_code, elem.code, 'element', rp.company_name
FROM (SELECT DISTINCT role_code, company_name FROM sys_role_permission WHERE target_code LIKE 'bom_manage:%') rp
CROSS JOIN (SELECT unnest(ARRAY['bom_manage:parent_spec','bom_manage:child_id','bom_manage:dosage','bom_manage:remark']) AS code) elem
WHERE NOT EXISTS (
SELECT 1 FROM sys_role_permission rp2
WHERE rp2.role_code = rp.role_code
AND rp2.target_code = elem.code
AND COALESCE(rp2.company_name, '') = COALESCE(rp.company_name, '')
);
""")
# 3. 验证
SQLS.append("""SELECT target_code, string_agg(role_code, ', ' ORDER BY role_code) AS roles
FROM sys_role_permission WHERE target_code LIKE 'bom_manage:%'
GROUP BY target_code ORDER BY target_code;""")
full_sql = '\n'.join(SQLS)
result = subprocess.run(
['docker', 'exec', '-i', 'inventory_db', 'psql', '-U', 'test', '-d', 'inventory_system'],
input=full_sql, capture_output=True, text=True, timeout=10
)
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)

View File

@ -239,7 +239,7 @@ const handleLogout = () => {
<footer v-if="!isLoginPage" class="app-footer">
<span class="version-tag">
<el-icon style="vertical-align: middle; margin-right: 4px"><InfoFilled /></el-icon>
当前版本:V3.56
当前版本:V3.57
</span>
</footer>

View File

@ -17,6 +17,7 @@ export interface PurchaseItem {
status_text?: string
requester_id?: number
requester_name?: string
requester_email?: string
approver_id?: number
approver_name?: string
approved_at?: string

View File

@ -93,7 +93,7 @@
</template>
</el-autocomplete>
<el-link
v-if="form.parent_id && !isReadOnlyMode"
v-if="form.parent_id"
type="primary"
:underline="false"
style="margin-left: 12px; font-size: 13px;"
@ -183,7 +183,7 @@
</div>
</template>
</el-autocomplete>
<el-tooltip content="前往修改基础信息" placement="top" v-if="row.child_id && !isReadOnlyMode">
<el-tooltip content="前往修改基础信息" placement="top" v-if="row.child_id">
<el-button
type="primary"
link

View File

@ -405,10 +405,19 @@
>
<el-icon style="margin-right: 4px"><Plus /></el-icon>加入或查看BOM
</el-link>
<el-link
v-if="form.id"
type="warning"
:underline="false"
style="font-size: 14px;"
@click="createPurchaseForMaterial"
>
<el-icon style="margin-right: 4px"><ShoppingCart /></el-icon>发起采购申请
</el-link>
</div>
</div>
</template>
<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
<el-form ref="formRef" :model="form" :rules="rules" label-width="110px" :disabled="formDisabled">
<el-row>
<el-col :span="12">
@ -604,7 +613,7 @@
<template #footer>
<div class="dialog-footer">
<el-button @click="cancel" :disabled="isUploading">取 消</el-button>
<el-button type="primary" @click="submitForm" :loading="submitLoading || isUploading">确 定</el-button>
<el-button type="primary" @click="submitForm" :loading="submitLoading || isUploading" :disabled="formDisabled">确 定</el-button>
</div>
</template>
</el-dialog>
@ -696,7 +705,7 @@
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue';
import { Plus, Document, DocumentCopy, Refresh, Setting, Rank, Camera, Download, Bell, CircleCheck, Files, ZoomIn, Delete, Picture } from '@element-plus/icons-vue';
import { Plus, Document, DocumentCopy, Refresh, Setting, Rank, Camera, Download, Bell, CircleCheck, Files, ZoomIn, Delete, Picture, ShoppingCart } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '@/stores/user';
@ -1048,6 +1057,12 @@ const hasFieldPermission = (field: string) => {
return userStore.hasPermission(code);
};
// 表单全局禁用:没有 material_list:operation 权限时,所有表单字段不可编辑
const formDisabled = computed(() => {
if (userStore.role === 'SUPER_ADMIN' || userStore.username === 'IRIS') return false;
return !userStore.hasPermission('material_list:operation');
});
const companyOptions = ref<string[]>([]);
const categoryOptions = ref<string[]>([]);
const typeOptions = ref<string[]>([]);
@ -1555,6 +1570,22 @@ const createBomForMaterial = () => {
window.open(routeUrl.href, '_blank');
};
const createPurchaseForMaterial = () => {
if (!form.value.id) {
return ElMessage.warning('请先保存物料基础信息后再操作');
}
const routeUrl = router.resolve({
path: '/purchase',
query: {
material_id: String(form.value.id),
name: form.value.name,
spec: form.value.spec,
unit: form.value.unit
}
});
window.open(routeUrl.href, '_blank');
};
const resetForm = () => {
form.value = JSON.parse(JSON.stringify(initForm));
fileListImage.value = [];

View File

@ -138,7 +138,7 @@
</el-col>
<el-col :span="24">
<el-form-item label="商家链接">
<el-input v-model="form.supplier_link" placeholder="商家地址链接(选填)" clearable />
<el-input v-model="form.supplier_link" placeholder="商家地址链接" clearable />
</el-form-item>
</el-col>
<el-col :span="24">
@ -235,6 +235,7 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
@ -372,21 +373,55 @@ const handlePageChange = (p: number) => { page.value = p; fetchData() }
const handleSizeChange = (s: number) => { pageSize.value = s; page.value = 1; fetchData() }
// --- 新建 ---
const openCreateDialog = () => {
const openCreateDialog = (prefill?: { materialId?: number; name?: string; spec?: string; unit?: string }) => {
dialogTitle.value = '新建采购申请'
form.value = {
name: '', spec_model: '', quantity: 1,
name: prefill?.name || '',
spec_model: prefill?.spec || '',
quantity: 1,
purchase_date: new Date().toISOString().split('T')[0],
supplier_link: '', remark: '',
unit_price: undefined, total_price: undefined,
approver_id: undefined, images: []
}
materialBaseId.value = null
materialOptions.value = []
autoFillHint.value = ''
if (prefill?.materialId) {
materialBaseId.value = prefill.materialId
// 预填物料选项以便显示选中状态
materialOptions.value = [{
id: prefill.materialId,
name: prefill.name || '',
spec_model: prefill.spec || ''
}]
if (prefill.spec) {
form.value.spec_model = prefill.spec
}
autoFillHint.value = `已从基础信息【${prefill.name || ''}】带入,请补充采购信息`
} else {
materialBaseId.value = null
materialOptions.value = []
autoFillHint.value = ''
}
fileList.value = []
totalPriceManuallyEdited.value = false
formDialogVisible.value = true
// 异步加载默认审批人(取当前用户上一次采购申请的审批人)
fetchDefaultApprover()
}
// 获取当前用户上一次采购申请的审批人作为默认值
const fetchDefaultApprover = async () => {
try {
const res: any = await getPurchaseList({ page: 1, limit: 1, status: undefined })
const items = res?.data?.items || []
if (items.length > 0 && items[0].approver_id) {
form.value.approver_id = items[0].approver_id
}
} catch (e) {
// 静默失败,用户可手动选择
}
}
// --- 物料搜索(分页) ---
@ -602,9 +637,22 @@ const confirmReject = async () => {
}
// --- 初始化 ---
const route = useRoute()
onMounted(() => {
fetchData()
fetchApprovers()
// 从基础信息跳转过来的参数
const query = route.query
if (query.material_id) {
openCreateDialog({
materialId: Number(query.material_id),
name: (query.name as string) || '',
spec: (query.spec as string) || '',
unit: (query.unit as string) || ''
})
}
})
</script>

View File

@ -513,19 +513,19 @@
<el-row :gutter="20">
<el-col :span="8">
<el-form-item label="币种">
<el-form-item v-if="hasFormFieldPermission('currency')" label="币种">
<el-autocomplete v-model="form.currency" :fetch-suggestions="querySearchCurrency" placeholder="币种" style="width: 100%" :trigger-on-focus="true">
<template #default="{ item }"><span>{{ item.value }}</span><span style="float:right; color:#999; font-size:12px">{{ item.desc }}</span></template>
</el-autocomplete>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="汇率">
<el-form-item v-if="hasFormFieldPermission('exchange_rate')" label="汇率">
<el-input-number v-model="form.exchange_rate" :precision="2" controls-position="right" style="width:100%"/>
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="税率">
<el-form-item v-if="hasFormFieldPermission('tax_rate')" label="税率">
<el-select v-model="form.tax_rate" style="width:100%" @change="updatePrices('tax')">
<el-option label="0%" :value="0" />
<el-option label="1%" :value="1" />
@ -537,7 +537,7 @@
<el-row :gutter="20" style="margin-top: 15px;">
<el-col :span="8">
<el-form-item label="不含税单价" prop="unit_price">
<el-form-item v-if="hasFormFieldPermission('unit_price')" label="不含税单价" prop="unit_price">
<el-input-number
v-model="form.unit_price"
:precision="2"
@ -549,7 +549,7 @@
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="含税单价">
<el-form-item v-if="hasFormFieldPermission('unit_price')" label="含税单价">
<el-input-number
v-model="form.post_tax_unit_price"
:precision="2"
@ -561,7 +561,7 @@
</el-form-item>
</el-col>
<el-col :span="8">
<el-form-item label="不含税总价">
<el-form-item v-if="hasFormFieldPermission('total_price')" label="不含税总价">
<el-input-number
v-model="form.total_price"
:precision="2"
@ -621,31 +621,13 @@
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="原始链接">
<el-autocomplete
v-model="form.source_link"
:fetch-suggestions="(qs, cb) => querySearchLinks(qs, cb, 'original')"
placeholder="http://"
style="width: 100%"
clearable
:trigger-on-focus="true"
>
<template #default="{ item }"><div style="font-size: 12px; line-height: 1.2; padding: 4px 0;">{{ item.value }}</div></template>
</el-autocomplete>
<el-form-item v-if="hasFormFieldPermission('source_link')" label="原始链接">
<el-input v-model="form.source_link" placeholder="http://" style="width: 100%" clearable />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="详情链接">
<el-autocomplete
v-model="form.detail_link"
:fetch-suggestions="(qs, cb) => querySearchLinks(qs, cb, 'detail')"
placeholder="http://"
style="width: 100%"
clearable
:trigger-on-focus="true"
>
<template #default="{ item }"><div style="font-size: 12px; line-height: 1.2; padding: 4px 0;">{{ item.value }}</div></template>
</el-autocomplete>
<el-form-item v-if="hasFormFieldPermission('detail_link')" label="详情链接">
<el-input v-model="form.detail_link" placeholder="http://" style="width: 100%" clearable />
</el-form-item>
</el-col>
</el-row>
@ -678,18 +660,18 @@
destroy-on-close
:close-on-click-modal="false"
>
<div style="margin-bottom: 15px;">
<div style="margin-bottom: 15px; display: flex; gap: 10px;">
<el-input
v-model="purchaseImportKeyword"
placeholder="搜索采购单号 / 名称 / 规格..."
placeholder="输入关键字实时搜索..."
clearable
style="width: 300px;"
@keyup.enter="fetchPurchaseImportList"
style="flex: 1;"
@input="debouncedPurchaseImportSearch"
@clear="fetchPurchaseImportList"
>
<template #prefix><el-icon><Search /></el-icon></template>
</el-input>
<el-button type="primary" style="margin-left: 10px;" @click="fetchPurchaseImportList">搜索</el-button>
<el-button type="primary" @click="fetchPurchaseImportList">搜索</el-button>
</div>
<el-table
@ -710,7 +692,7 @@
</template>
</el-table-column>
<el-table-column prop="quantity" label="申请数量" width="85" align="right" />
<el-table-column prop="unit_price" label="单价" width="100" align="right">
<el-table-column v-if="hasFormFieldPermission('unit_price')" prop="unit_price" label="单价" width="100" align="right">
<template #default="scope">
{{ scope.row.unit_price ? '¥' + Number(scope.row.unit_price).toFixed(2) : '-' }}
</template>
@ -798,7 +780,6 @@ import {
deleteFile,
getSupplierSuggestions,
getUserSuggestions,
getLinkSuggestions,
getLocationSuggestions,
getFilterOptions
} from '@/api/inbound/buy'
@ -1206,19 +1187,6 @@ const fetchUserSuggestions = async (query: string, cb: any) => {
const querySearchPurchaser = (qs: string, cb: any) => fetchUserSuggestions(qs, cb)
const handlePurchaserSelect = (item: any) => { form.purchaser = item.value; if (item.email) form.purchaser_email = item.email }
const fetchLinkSuggestions = async (query: string, cb: any, type: 'original' | 'detail') => {
if (!form.base_id) { cb([]); return }
try {
const res: any = await getLinkSuggestions({ base_id: form.base_id, type })
if (res.code === 200) {
const links = res.data.map((link: string) => ({ value: link }))
const filtered = query ? links.filter((item:any) => item.value.toLowerCase().includes(query.toLowerCase())) : links
cb(filtered)
} else { cb([]) }
} catch(e) { cb([]) }
}
const querySearchLinks = (qs: string, cb: any, type: 'original' | 'detail') => fetchLinkSuggestions(qs, cb, type)
const fetchLocationSuggestions = async (query: string, cb: any) => {
if (!form.base_id) { cb([]); return }
try {
@ -1805,6 +1773,13 @@ const fetchPurchaseImportList = async () => {
}
}
// 防抖实时搜索(输入即搜,无需点按钮)
const debouncedPurchaseImportSearch = debounce(() => {
purchaseImportPage.value = 1
purchaseImportSelected.value = null
fetchPurchaseImportList()
}, 300)
// 表格选中行变化(点击已选中行可取消)
const onPurchaseImportSelect = (row: any) => {
if (purchaseImportSelected.value?.id === row.id) {
@ -1861,29 +1836,36 @@ const confirmPurchaseImport = () => {
return
}
// 2. 填充采购商务信息(单价/总价互相推算,缺哪个补哪个)
// 2. 填充采购商务信息
const qty = Number(po.quantity) || 1
form.in_quantity = qty
const hasUnitPrice = po.unit_price !== null && po.unit_price !== undefined && Number(po.unit_price) > 0
const hasTotalPrice = po.total_price !== null && po.total_price !== undefined && Number(po.total_price) > 0
// 价格字段:仅具有单价查看权限的用户才自动填充
if (hasFormFieldPermission('unit_price')) {
const hasUnitPrice = po.unit_price !== null && po.unit_price !== undefined && Number(po.unit_price) > 0
const hasTotalPrice = po.total_price !== null && po.total_price !== undefined && Number(po.total_price) > 0
if (hasUnitPrice && hasTotalPrice) {
// 两者都有,直接使用
form.unit_price = Number(po.unit_price)
form.total_price = Number(po.total_price)
} else if (hasUnitPrice) {
// 只有单价 → 用数量推算总价
form.unit_price = Number(po.unit_price)
form.total_price = Number((qty * form.unit_price).toFixed(2))
} else if (hasTotalPrice) {
// 只有总价 → 用数量反推单价
form.total_price = Number(po.total_price)
form.unit_price = Number((form.total_price / qty).toFixed(4))
if (hasUnitPrice && hasTotalPrice) {
form.unit_price = Number(po.unit_price)
form.total_price = Number(po.total_price)
} else if (hasUnitPrice) {
form.unit_price = Number(po.unit_price)
form.total_price = Number((qty * form.unit_price).toFixed(2))
} else if (hasTotalPrice) {
form.total_price = Number(po.total_price)
form.unit_price = Number((form.total_price / qty).toFixed(4))
}
}
// 都没有就都不填
if (po.supplier_link) {
form.source_link = po.supplier_link
form.detail_link = po.supplier_link
}
// 从采购申请人自动填充采购人信息
if (po.requester_name) {
form.purchaser = po.requester_name
}
if (po.requester_email) {
form.purchaser_email = po.requester_email
}
// 3. 关联采购单号