feat(bx): 报销可代选申请人,并放宽主数据选项的数据权限过滤
支持具备 changeApplicant 权限时代填申请人及发票/余额联动;系统/CRM/BX/PL 主数据与下拉选项改为仅租户隔离,避免「仅本人」导致空选项。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6c2121d7fc
commit
31b0db6840
36 files changed
+36351
-37915
No files matched your search
@@ -75,11 +75,14 @@ def list_users_for_select(
|
||||
user: dict = Depends(require_admin_or_super_admin),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""返回用户下拉选项(label=昵称,value=用户ID,附带 nickName/userNo),供审批人选择等场景使用。"""
|
||||
"""返回用户下拉选项(label=昵称,value=用户ID,附带 nickName/userNo)。
|
||||
|
||||
供申请人/审批人等选择场景使用,返回本租户全部有效用户,
|
||||
不做业务数据范围过滤(否则「仅本人」角色会按 create_by 滤空,连自己都选不到)。
|
||||
"""
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
q = db.query(SysUser).filter(SysUser.del_flag == 0, SysUser.status == "1")
|
||||
q = q.filter(SysUser.tenant_no == tenant_no)
|
||||
q = apply_data_scope(q, SysUser, user, db, tenant_no)
|
||||
rows = q.order_by(SysUser.create_time.desc()).all()
|
||||
out = [
|
||||
{
|
||||
@@ -99,11 +102,12 @@ def list_roles_for_designer(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""返回角色下拉选项(label=角色名,value=角色ID UUID),供流程设计器审批人选择使用。
|
||||
与 /roles 不同,此端点返回角色 UUID 作为 value(引擎解析审批人需要 UUID)。"""
|
||||
与 /roles 不同,此端点返回角色 UUID 作为 value(引擎解析审批人需要 UUID)。
|
||||
角色为租户级主数据选项,不做 create_by 数据范围过滤。
|
||||
"""
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
q = db.query(SysRole).filter(SysRole.del_flag == 0, SysRole.status == "1")
|
||||
q = q.filter(SysRole.tenant_no == tenant_no)
|
||||
q = apply_data_scope(q, SysRole, user, db, tenant_no)
|
||||
rows = q.order_by(SysRole.create_time.desc()).all()
|
||||
out = [{"label": (r.role_name or "").strip(), "value": r.id} for r in rows if (r.role_name or "").strip()]
|
||||
return success_response(out)
|
||||
@@ -630,8 +634,9 @@ def dict_data_options(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
tenant_no = _get_tenant_no(db, user)
|
||||
# 字典选项为租户主数据,表单共用;不做数据范围过滤
|
||||
items = dict_data_svc.list_dict_data_options(
|
||||
db, dict_type_code=dictType, tenant_no=tenant_no, user_info=user
|
||||
db, dict_type_code=dictType, tenant_no=tenant_no, user_info=None
|
||||
)
|
||||
return success_response(items)
|
||||
|
||||
@@ -645,7 +650,6 @@ def dict_data_all(
|
||||
q = db.query(SysDictData).filter(
|
||||
and_(SysDictData.tenant_no == tenant_no, SysDictData.del_flag == 0)
|
||||
)
|
||||
q = apply_data_scope(q, SysDictData, user, db, tenant_no)
|
||||
rows = q.order_by(SysDictData.order_num.asc()).all()
|
||||
grouped = {}
|
||||
for r in rows:
|
||||
|
||||
@@ -259,7 +259,7 @@ def create_advance(
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
eid = data.get("expense_item_id")
|
||||
if eid:
|
||||
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user):
|
||||
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user, skip_scope=True):
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"费用项目 {eid} 不存在")
|
||||
data["applicant_id"] = user.id
|
||||
data["applicant_name"] = user.name
|
||||
@@ -293,7 +293,7 @@ def update_advance(
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("expense_item_id"):
|
||||
eid = data["expense_item_id"]
|
||||
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user):
|
||||
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user, skip_scope=True):
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"费用项目 {eid} 不存在")
|
||||
advance = AdvanceService.update(db, advance_id, data, user=user)
|
||||
if not advance:
|
||||
|
||||
@@ -16,10 +16,11 @@ router = APIRouter(tags=["发票夹"])
|
||||
|
||||
@router.get("/invoice-wallets/mine/summary", response_model=ApiResponse[WalletSummaryOut])
|
||||
def get_mine_wallet_summary(
|
||||
userId: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: BxUserContext = Depends(get_bx_current_user),
|
||||
):
|
||||
data = InvoiceService.get_mine_summary(db, user=user)
|
||||
data = InvoiceService.get_mine_summary(db, user=user, owner_user_id=userId)
|
||||
return ApiResponse(data=WalletSummaryOut.model_validate(data))
|
||||
|
||||
|
||||
|
||||
@@ -31,10 +31,18 @@ def _tenant(db: Session, user: BxUserContext) -> str:
|
||||
return get_tenant_no(db, user.to_tenant_user_dict())
|
||||
|
||||
|
||||
def _build_details_data(db: Session, tenant_no: str, body_details) -> List[dict]:
|
||||
def _build_details_data(
|
||||
db: Session,
|
||||
tenant_no: str,
|
||||
body_details,
|
||||
*,
|
||||
user: BxUserContext,
|
||||
) -> List[dict]:
|
||||
details_data: List[dict] = []
|
||||
for d in body_details:
|
||||
item = ExpenseItemService.get_by_id(db, d.expense_item_id, tenant_no, user=user)
|
||||
item = ExpenseItemService.get_by_id(
|
||||
db, d.expense_item_id, tenant_no, user=user, skip_scope=True
|
||||
)
|
||||
if not item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -55,12 +63,16 @@ def _build_details_data(db: Session, tenant_no: str, body_details) -> List[dict]
|
||||
def get_generated_title(
|
||||
reimburseDate: Optional[str] = None,
|
||||
excludeApplyId: Optional[str] = None,
|
||||
applicantId: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: BxUserContext = Depends(get_bx_current_user),
|
||||
):
|
||||
tenant_no = _tenant(db, user)
|
||||
exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
|
||||
title = generate_title(db, user.name, tenant_no, reimburseDate, exclude_id)
|
||||
_, applicant_name = ReimburseService.resolve_applicant(
|
||||
db, user, applicantId, tenant_no=tenant_no
|
||||
)
|
||||
title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id)
|
||||
return ApiResponse(data=title)
|
||||
|
||||
|
||||
@@ -295,7 +307,7 @@ def create_reimburse(
|
||||
user: BxUserContext = Depends(get_bx_current_user),
|
||||
):
|
||||
tenant_no = _tenant(db, user)
|
||||
details_data = _build_details_data(db, tenant_no, body.details)
|
||||
details_data = _build_details_data(db, tenant_no, body.details, user=user)
|
||||
data = {
|
||||
"apply_code": generate_apply_code(db, "BX", tenant_no),
|
||||
"status": "draft",
|
||||
@@ -315,7 +327,17 @@ def create_reimburse(
|
||||
)
|
||||
if wf:
|
||||
data["wf_id"] = wf.id
|
||||
reimburse = ReimburseService.create_with_details(db, data, details_data, user=user)
|
||||
applicant_id, applicant_name = ReimburseService.resolve_applicant(
|
||||
db, user, body.applicant_id, tenant_no=tenant_no
|
||||
)
|
||||
reimburse = ReimburseService.create_with_details(
|
||||
db,
|
||||
data,
|
||||
details_data,
|
||||
user=user,
|
||||
applicant_id=applicant_id,
|
||||
applicant_name=applicant_name,
|
||||
)
|
||||
if body.invoice_ids is not None:
|
||||
ReimburseService.sync_reimburse_invoices(
|
||||
db,
|
||||
@@ -323,7 +345,7 @@ def create_reimburse(
|
||||
body.invoice_ids,
|
||||
tenant_no,
|
||||
user,
|
||||
applicant_id=user.id,
|
||||
applicant_id=applicant_id,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(reimburse)
|
||||
@@ -341,7 +363,7 @@ def update_reimburse(
|
||||
tenant_no = _tenant(db, user)
|
||||
details_data = None
|
||||
if body.details is not None:
|
||||
details_data = _build_details_data(db, tenant_no, body.details)
|
||||
details_data = _build_details_data(db, tenant_no, body.details, user=user)
|
||||
main_data = {}
|
||||
if body.remark is not None:
|
||||
main_data["remark"] = body.remark
|
||||
@@ -349,6 +371,12 @@ def update_reimburse(
|
||||
main_data["reimburse_date"] = body.reimburse_date
|
||||
if body.title is not None:
|
||||
main_data["title"] = body.title
|
||||
if body.applicant_id is not None:
|
||||
applicant_id, applicant_name = ReimburseService.resolve_applicant(
|
||||
db, user, body.applicant_id, tenant_no=tenant_no
|
||||
)
|
||||
main_data["applicant_id"] = applicant_id
|
||||
main_data["applicant_name"] = applicant_name
|
||||
reimburse = ReimburseService.update_with_details(
|
||||
db, reimburse_id, main_data, details_data, user=user
|
||||
)
|
||||
|
||||
@@ -9,7 +9,6 @@ from sqlalchemy.orm import Session
|
||||
from app.core.database import get_db
|
||||
from app.core.db_auth import DbUserContext, get_db_current_user
|
||||
from app.core.delete_guard import assert_row_deletable_by_creator, user_info_from_context
|
||||
from app.services.pl_data_scope import apply_pl_scope, assert_pl_row_in_scope
|
||||
from app.core.tenant_context import get_tenant_no
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.pl_models import (
|
||||
@@ -101,8 +100,7 @@ def list_carriers(
|
||||
)
|
||||
)
|
||||
|
||||
query = apply_pl_scope(query, PlCarrier, user, db, tenant_no)
|
||||
|
||||
# 承运商为物流主数据,列表不做 create_by 数据范围过滤
|
||||
query = query.order_by(
|
||||
case((PlCarrier.order_num.is_(None), 1), else_=0).asc(),
|
||||
PlCarrier.create_time.desc(),
|
||||
@@ -231,7 +229,6 @@ def _get_carrier(db: Session, tenant_no: str, carrier_id: str, user: DbUserConte
|
||||
)
|
||||
if not carrier:
|
||||
raise HTTPException(status_code=404, detail="承运商不存在")
|
||||
assert_pl_row_in_scope(db, carrier, PlCarrier, user, tenant_no)
|
||||
return carrier
|
||||
|
||||
|
||||
@@ -308,8 +305,7 @@ def list_vehicles(
|
||||
if q:
|
||||
query = query.filter(PlVehicle.license_plate.contains(q))
|
||||
|
||||
query = apply_pl_scope(query, PlVehicle, user, db, tenant_no)
|
||||
|
||||
# 车辆为主数据,列表不做 create_by 数据范围过滤
|
||||
query = query.order_by(
|
||||
case((PlVehicle.order_num.is_(None), 1), else_=0).asc(),
|
||||
PlVehicle.create_time.desc(),
|
||||
@@ -567,7 +563,6 @@ def _get_vehicle(db: Session, tenant_no: str, vehicle_id: str, user: DbUserConte
|
||||
)
|
||||
if not vehicle:
|
||||
raise HTTPException(status_code=404, detail="车辆不存在")
|
||||
assert_pl_row_in_scope(db, vehicle, PlVehicle, user, tenant_no)
|
||||
return vehicle
|
||||
|
||||
|
||||
@@ -636,8 +631,7 @@ def list_personnel(
|
||||
)
|
||||
)
|
||||
|
||||
query = apply_pl_scope(query, PlPersonnel, user, db, tenant_no)
|
||||
|
||||
# 人员为主数据,列表不做 create_by 数据范围过滤
|
||||
query = query.order_by(
|
||||
case((PlPersonnel.order_num.is_(None), 1), else_=0).asc(),
|
||||
PlPersonnel.create_time.desc(),
|
||||
@@ -805,7 +799,6 @@ def _get_personnel(db: Session, tenant_no: str, personnel_id: str, user: DbUserC
|
||||
)
|
||||
if not personnel:
|
||||
raise HTTPException(status_code=404, detail="人员不存在")
|
||||
assert_pl_row_in_scope(db, personnel, PlPersonnel, user, tenant_no)
|
||||
return personnel
|
||||
|
||||
|
||||
@@ -854,8 +847,7 @@ def list_drivers(
|
||||
)
|
||||
)
|
||||
|
||||
query = apply_pl_scope(query, PlPersonnel, user, db, tenant_no)
|
||||
|
||||
# 司机列表为主数据选项,不做 create_by 数据范围过滤
|
||||
query = query.order_by(
|
||||
case((PlPersonnel.order_num.is_(None), 1), else_=0).asc(),
|
||||
PlPersonnel.create_time.desc(),
|
||||
@@ -1008,10 +1000,6 @@ def unbind_vehicle_driver(
|
||||
.first()
|
||||
)
|
||||
if vd:
|
||||
if isinstance(vd, PlVehiclePersonnel):
|
||||
assert_pl_row_in_scope(db, vd, PlVehiclePersonnel, user, tenant_no)
|
||||
else:
|
||||
assert_pl_row_in_scope(db, vd, PlVehicleDriver, user, tenant_no)
|
||||
assert_row_deletable_by_creator(vd, user_info_from_context(user))
|
||||
vd.del_flag = 1
|
||||
db.commit()
|
||||
|
||||
@@ -17,7 +17,6 @@ from app.schemas.pl.transport_address import (
|
||||
TransportAddressRead,
|
||||
TransportAddressUpdate,
|
||||
)
|
||||
from app.services.pl_data_scope import apply_pl_scope, assert_pl_row_in_scope
|
||||
|
||||
router = APIRouter(tags=["运输地址库"])
|
||||
|
||||
@@ -40,16 +39,16 @@ def _get_address(
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail="地址不存在")
|
||||
assert_pl_row_in_scope(db, row, PlTransportAddress, user, tenant_no)
|
||||
return row
|
||||
|
||||
|
||||
def _build_address_query(db: Session, tenant_no: str, user: DbUserContext):
|
||||
# 运输地址为主数据选项,不做 create_by 数据范围过滤
|
||||
_ = user
|
||||
query = db.query(PlTransportAddress).filter(
|
||||
PlTransportAddress.tenant_no == tenant_no,
|
||||
PlTransportAddress.del_flag == 0,
|
||||
)
|
||||
query = apply_pl_scope(query, PlTransportAddress, user, db, tenant_no)
|
||||
return query
|
||||
|
||||
|
||||
|
||||
@@ -173,6 +173,13 @@ def apply_data_scope(
|
||||
):
|
||||
"""根据用户角色的数据权限过滤查询。
|
||||
|
||||
适用于业务单据列表/详情(报销单、客户、运单等)。
|
||||
|
||||
以下场景 SHALL NOT 调用本函数(仅租户隔离即可):
|
||||
- 下拉/选项接口(/options)
|
||||
- 租户级主数据树与码表(部门、字典、费用项目、产品分类、民族等)
|
||||
- 已有专用归属过滤的接口(如发票夹按 owner_user_id、待办按审批人)
|
||||
|
||||
Args:
|
||||
query: SQLAlchemy query 对象
|
||||
model: 查询的主模型类(需要有 create_dept_id / create_by 字段)
|
||||
|
||||
@@ -60,8 +60,8 @@ def list_categories(
|
||||
CrmProductCategory.tenant_no == tenant_no,
|
||||
CrmProductCategory.del_flag == 0,
|
||||
)
|
||||
if user_info:
|
||||
q = apply_crm_create_by_scope(q, CrmProductCategory, user_info, db, tenant_no)
|
||||
# 产品分类为租户主数据(树选择/管理共用),不做 create_by 过滤
|
||||
_ = user_info
|
||||
name_kw = (category_name or "").strip()
|
||||
if name_kw:
|
||||
q = q.filter(CrmProductCategory.category_name.like(f"%{name_kw}%"))
|
||||
@@ -634,8 +634,8 @@ def list_product_options(
|
||||
CrmProduct.del_flag == 0,
|
||||
CrmProduct.status == "on",
|
||||
)
|
||||
if user_info:
|
||||
q = apply_crm_create_by_scope(q, CrmProduct, user_info, db, tenant_no)
|
||||
# 下拉选项供合同/报价等选用,不做 create_by 过滤(产品管理分页列表仍保留数据权限)
|
||||
_ = user_info
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
q = q.filter(or_(CrmProduct.product_name.like(like), CrmProduct.product_no.like(like)))
|
||||
|
||||
@@ -67,9 +67,8 @@ def list_depts(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q = q.filter(SysDept.dept_name.like(like))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, SysDept, user_info, db, tenant_no)
|
||||
# 部门为组织主数据(选人/选部门/数据权限配置均需完整树),不做 create_by 过滤
|
||||
_ = user_info
|
||||
rows = q.order_by(SysDept.create_time.desc()).all()
|
||||
return [_row_to_dict(x) for x in rows]
|
||||
|
||||
|
||||
@@ -49,9 +49,7 @@ def list_dict_data(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q0 = q0.filter(SysDictData.dict_label.like(like))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q0 = apply_data_scope(q0, SysDictData, user_info, db, tenant_no)
|
||||
# 字典数据为租户主数据;管理列表也不按 create_by 过滤,避免普通管理员看不到字典项
|
||||
return q0
|
||||
|
||||
total = _filtered().order_by(None).with_entities(func.count(SysDictData.id)).scalar() or 0
|
||||
@@ -159,15 +157,13 @@ def list_dict_data_options(
|
||||
tenant_no: Optional[str] = None,
|
||||
user_info=None,
|
||||
) -> List[Dict[str, str]]:
|
||||
"""字典下拉选项:租户主数据,忽略数据范围(user_info 保留兼容调用方,不参与过滤)。"""
|
||||
_ = user_info
|
||||
q = db.query(SysDictData).filter(
|
||||
and_(SysDictData.dict_type == dict_type_code, SysDictData.del_flag == 0)
|
||||
)
|
||||
if tenant_no:
|
||||
q = q.filter(SysDictData.tenant_no == tenant_no)
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
|
||||
q = apply_data_scope(q, SysDictData, user_info, db, tenant_no)
|
||||
rows = q.order_by(SysDictData.create_time.desc()).all()
|
||||
return [{"label": r.dict_label, "value": r.dict_value, "tagType": r.tag_type or ""} for r in rows]
|
||||
|
||||
|
||||
@@ -44,9 +44,7 @@ def list_dict_types(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q0 = q0.filter(or_(SysDictType.dict_name.like(like), SysDictType.dict_type.like(like)))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q0 = apply_data_scope(q0, SysDictType, user_info, db, tenant_no)
|
||||
# 字典类型为租户主数据,不做 create_by 数据范围过滤
|
||||
return q0
|
||||
|
||||
total = _filtered().order_by(None).with_entities(func.count(SysDictType.id)).scalar() or 0
|
||||
|
||||
@@ -27,8 +27,7 @@ def list_ethnics(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q = q.filter(SysEthnic.ethnic_name.like(like))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q = apply_data_scope(q, SysEthnic, user_info, db)
|
||||
# 民族码表为全局主数据,不做数据范围过滤
|
||||
_ = user_info
|
||||
rows = q.order_by(SysEthnic.order_num.asc(), SysEthnic.ethnic_code.asc()).limit(max(1, min(limit, 500))).all()
|
||||
return [_row_to_dict(x) for x in rows]
|
||||
@@ -45,9 +45,7 @@ def list_posts(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q0 = q0.filter(or_(SysPost.post_name.like(like), SysPost.post_code.like(like)))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q0 = apply_data_scope(q0, SysPost, user_info, db, tenant_no)
|
||||
# 职位为租户主数据,不做 create_by 数据范围过滤
|
||||
return q0
|
||||
|
||||
total = _filtered().order_by(None).with_entities(func.count(SysPost.id)).scalar() or 0
|
||||
|
||||
@@ -50,9 +50,7 @@ def list_sites(
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
q0 = q0.filter(or_(SysSite.site_name.like(like), SysSite.site_code.like(like)))
|
||||
if user_info:
|
||||
from app.core.data_scope import apply_data_scope
|
||||
q0 = apply_data_scope(q0, SysSite, user_info, db, tenant_no)
|
||||
# 站点为租户主数据,不做 create_by 数据范围过滤
|
||||
return q0
|
||||
|
||||
total = _filtered().order_by(None).with_entities(func.count(SysSite.id)).scalar() or 0
|
||||
|
||||
@@ -54,6 +54,7 @@ class ReimburseApplyCreate(BaseModel):
|
||||
details: List[ReimburseDetailCreate] = Field(..., min_length=1)
|
||||
remark: Optional[str] = None
|
||||
invoice_ids: Optional[List[str]] = None
|
||||
applicant_id: Optional[str] = None
|
||||
|
||||
@field_validator("details")
|
||||
@classmethod
|
||||
@@ -62,6 +63,11 @@ class ReimburseApplyCreate(BaseModel):
|
||||
raise ValueError("至少需要一条报销明细")
|
||||
return value
|
||||
|
||||
@field_validator("applicant_id", mode="before")
|
||||
@classmethod
|
||||
def coerce_applicant_id(cls, value):
|
||||
return _coerce_id(value) or None
|
||||
|
||||
|
||||
class ReimburseApplyUpdate(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True, alias_generator=to_camel)
|
||||
@@ -71,6 +77,12 @@ class ReimburseApplyUpdate(BaseModel):
|
||||
reimburse_date: Optional[str] = None
|
||||
remark: Optional[str] = None
|
||||
invoice_ids: Optional[List[str]] = None
|
||||
applicant_id: Optional[str] = None
|
||||
|
||||
@field_validator("applicant_id", mode="before")
|
||||
@classmethod
|
||||
def coerce_applicant_id(cls, value):
|
||||
return _coerce_id(value) or None
|
||||
|
||||
|
||||
class ReimburseSubmitBody(BaseModel):
|
||||
|
||||
@@ -44,13 +44,14 @@ class BxCrudService:
|
||||
filters: Optional[List[Any]] = None,
|
||||
*,
|
||||
user: Optional["BxUserContext"] = None,
|
||||
skip_scope: bool = False,
|
||||
) -> Tuple[Sequence[M], int]:
|
||||
query = db.query(model).filter(model.tenant_no == tenant_no)
|
||||
if hasattr(model, "del_flag"):
|
||||
query = query.filter(model.del_flag == 0)
|
||||
if filters:
|
||||
query = query.filter(*filters)
|
||||
if user:
|
||||
if user and not skip_scope:
|
||||
query = apply_bx_scope(query, model, user, db, tenant_no)
|
||||
total = query.count()
|
||||
if hasattr(model, "sort_order"):
|
||||
|
||||
@@ -8,7 +8,6 @@ from app.core.bx_auth import BxUserContext
|
||||
from app.core.tenant_context import get_tenant_no
|
||||
from app.models.bx_models import BxExpenseItem
|
||||
from app.services.bx.base import BxCrudService
|
||||
from app.services.bx_data_scope import apply_bx_scope
|
||||
|
||||
|
||||
class ExpenseItemService:
|
||||
@@ -23,8 +22,9 @@ class ExpenseItemService:
|
||||
tenant_no: str,
|
||||
*,
|
||||
user: Optional[BxUserContext] = None,
|
||||
skip_scope: bool = False,
|
||||
skip_scope: bool = True,
|
||||
) -> Optional[BxExpenseItem]:
|
||||
# 费用项目为主数据:默认跳过 create_by 数据范围
|
||||
return BxCrudService.get_by_id(
|
||||
BxExpenseItem, db, item_id, tenant_no, user=user, skip_scope=skip_scope
|
||||
)
|
||||
@@ -84,21 +84,30 @@ class ExpenseItemService:
|
||||
data,
|
||||
user_id=user.id,
|
||||
user=user,
|
||||
skip_scope=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def soft_delete(db: Session, item_id: str, *, user: BxUserContext) -> bool:
|
||||
tenant_no = ExpenseItemService._tenant_no(db, user)
|
||||
return BxCrudService.soft_delete(
|
||||
BxExpenseItem, db, item_id, tenant_no, user_id=user.id, user=user
|
||||
BxExpenseItem,
|
||||
db,
|
||||
item_id,
|
||||
tenant_no,
|
||||
user_id=user.id,
|
||||
user=user,
|
||||
skip_scope=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_item_tree(db: Session, tenant_no: str, *, user: BxUserContext) -> List[BxExpenseItem]:
|
||||
# 费用项目是租户级主数据,供报销/备用金选择;不做 create_by 数据范围过滤,
|
||||
# 否则「仅本人」角色看不到管理员维护的费用项目。
|
||||
_ = user
|
||||
query = db.query(BxExpenseItem).filter(
|
||||
BxExpenseItem.del_flag == 0, BxExpenseItem.tenant_no == tenant_no
|
||||
)
|
||||
query = apply_bx_scope(query, BxExpenseItem, user, db, tenant_no)
|
||||
items = query.order_by(
|
||||
BxExpenseItem.sort_order.asc(), BxExpenseItem.create_time.desc()
|
||||
).all()
|
||||
|
||||
@@ -24,6 +24,7 @@ from app.services.bx.storage import upload_bx_file
|
||||
from app.services.web_auth_roles import iter_user_menu_perm_codes
|
||||
|
||||
INVOICE_WALLET_ADMIN_PERM = "bx:invoiceWallet:admin"
|
||||
REIMBURSE_CHANGE_APPLICANT_PERM = "bx:reimburseApply:changeApplicant"
|
||||
|
||||
|
||||
class InvoiceService:
|
||||
@@ -38,6 +39,14 @@ class InvoiceService:
|
||||
codes = iter_user_menu_perm_codes(db, user.id, user.tenant_no)
|
||||
return INVOICE_WALLET_ADMIN_PERM in codes
|
||||
|
||||
@staticmethod
|
||||
def can_query_others_wallet(db: Session, user: BxUserContext) -> bool:
|
||||
"""发票夹管理 或 报销改选申请人 权限可查询他人发票/余额。"""
|
||||
if InvoiceService.is_wallet_admin(db, user):
|
||||
return True
|
||||
codes = iter_user_menu_perm_codes(db, user.id, user.tenant_no)
|
||||
return REIMBURSE_CHANGE_APPLICANT_PERM in set(codes)
|
||||
|
||||
@staticmethod
|
||||
def _require_wallet_admin(db: Session, user: BxUserContext) -> None:
|
||||
if not InvoiceService.is_wallet_admin(db, user):
|
||||
@@ -73,8 +82,11 @@ class InvoiceService:
|
||||
user_id: Optional[str],
|
||||
) -> str:
|
||||
owner_id = (user_id or "").strip() or user.id
|
||||
if owner_id != user.id:
|
||||
InvoiceService._require_wallet_admin(db, user)
|
||||
if owner_id != user.id and not InvoiceService.can_query_others_wallet(db, user):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="无权查看他人发票夹",
|
||||
)
|
||||
return owner_id
|
||||
|
||||
@staticmethod
|
||||
@@ -90,28 +102,39 @@ class InvoiceService:
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_mine_summary(db: Session, *, user: BxUserContext) -> dict:
|
||||
def get_mine_summary(
|
||||
db: Session,
|
||||
*,
|
||||
user: BxUserContext,
|
||||
owner_user_id: Optional[str] = None,
|
||||
) -> dict:
|
||||
tenant_no = InvoiceService._tenant_no(db, user)
|
||||
owner_id = InvoiceService._resolve_owner_for_query(db, user, owner_user_id)
|
||||
owner_name = (
|
||||
user.name
|
||||
if owner_id == user.id
|
||||
else InvoiceService._lookup_user_name(db, owner_id)
|
||||
)
|
||||
row = (
|
||||
db.query(BxInvoiceWalletSummary)
|
||||
.filter(
|
||||
BxInvoiceWalletSummary.tenant_no == tenant_no,
|
||||
BxInvoiceWalletSummary.owner_user_id == user.id,
|
||||
BxInvoiceWalletSummary.owner_user_id == owner_id,
|
||||
BxInvoiceWalletSummary.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row:
|
||||
return InvoiceService._summary_to_dict(row)
|
||||
totals = InvoiceLedgerService.calc_summary(db, tenant_no, user.id)
|
||||
totals = InvoiceLedgerService.calc_summary(db, tenant_no, owner_id)
|
||||
return {
|
||||
"id": "",
|
||||
"owner_user_id": user.id,
|
||||
"owner_user_name": user.name,
|
||||
"owner_user_id": owner_id,
|
||||
"owner_user_name": owner_name,
|
||||
"total_amount": totals["total_amount"],
|
||||
"used_amount": totals["used_amount"],
|
||||
"balance": totals["balance"],
|
||||
"invoice_count": InvoiceService._count_invoices(db, tenant_no, user.id),
|
||||
"invoice_count": InvoiceService._count_invoices(db, tenant_no, owner_id),
|
||||
"version": 0,
|
||||
"create_time": None,
|
||||
"update_time": None,
|
||||
|
||||
@@ -10,6 +10,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.bx_auth import BxUserContext
|
||||
from app.core.menu_guard import SUPER_ADMIN_ROLE
|
||||
from app.core.tenant_context import get_tenant_no
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.bx_models import (
|
||||
@@ -23,12 +24,14 @@ from app.models.bx_models import (
|
||||
BxWorkflowDef,
|
||||
BxWorkflowNode,
|
||||
)
|
||||
from app.models.models import SysUser
|
||||
from app.schemas.bx.reimburse import ReimburseApplyOut, ReimburseDetailOut, ReimburseInvoiceBriefOut
|
||||
from app.services.bx.approval_cycle import filter_current_cycle_approvals
|
||||
from app.services.bx.attachment import AttachmentService
|
||||
from app.services.bx.base import BxCrudService
|
||||
from app.services.bx.invoice_ledger import ENTRY_DEBIT_REIMBURSE, InvoiceLedgerService
|
||||
from app.services.bx_data_scope import apply_bx_scope
|
||||
from app.services.web_auth_roles import iter_user_menu_perm_codes
|
||||
from app.utils.bx_codegen import (
|
||||
allocate_reimburse_title_seq,
|
||||
generate_apply_code,
|
||||
@@ -39,6 +42,8 @@ from app.utils.bx_codegen import (
|
||||
)
|
||||
from app.utils.bx_date_range import current_month_bounds, resolve_create_time_bounds
|
||||
|
||||
REIMBURSE_CHANGE_APPLICANT_PERM = "bx:reimburseApply:changeApplicant"
|
||||
|
||||
_REIMBURSE_MY_STATS_PASSED_STATUSES = ("approved", "processed", "paid", "offset")
|
||||
|
||||
|
||||
@@ -47,6 +52,53 @@ class ReimburseService:
|
||||
def _tenant_no(db: Session, user: BxUserContext) -> str:
|
||||
return get_tenant_no(db, user.to_tenant_user_dict())
|
||||
|
||||
@staticmethod
|
||||
def can_change_applicant(db: Session, user: BxUserContext) -> bool:
|
||||
"""是否可选择他人作为报销申请人(超管或具备按钮权限)。"""
|
||||
if user.role == SUPER_ADMIN_ROLE:
|
||||
return True
|
||||
return REIMBURSE_CHANGE_APPLICANT_PERM in set(
|
||||
iter_user_menu_perm_codes(db, user.id, user.tenant_no)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def resolve_applicant(
|
||||
db: Session,
|
||||
user: BxUserContext,
|
||||
applicant_id: Optional[str],
|
||||
*,
|
||||
tenant_no: str,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
解析报销申请人。
|
||||
无 changeApplicant 权限时忽略客户端指定,强制本人;
|
||||
有权限时可指定同租户有效用户。
|
||||
返回 (applicant_id, applicant_name)。
|
||||
"""
|
||||
requested = (applicant_id or "").strip() or None
|
||||
if not requested or requested == user.id:
|
||||
return user.id, (user.name or user.id)
|
||||
|
||||
if not ReimburseService.can_change_applicant(db, user):
|
||||
return user.id, (user.name or user.id)
|
||||
|
||||
target = (
|
||||
db.query(SysUser)
|
||||
.filter(
|
||||
SysUser.id == requested,
|
||||
SysUser.tenant_no == tenant_no,
|
||||
SysUser.del_flag == 0,
|
||||
SysUser.status == "1",
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not target:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="申请人不存在或已停用",
|
||||
)
|
||||
return target.id, (target.nick_name or target.user_no or target.id)
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(
|
||||
db: Session,
|
||||
@@ -615,6 +667,8 @@ class ReimburseService:
|
||||
details: List[dict],
|
||||
*,
|
||||
user: BxUserContext,
|
||||
applicant_id: Optional[str] = None,
|
||||
applicant_name: Optional[str] = None,
|
||||
) -> BxReimburseApply:
|
||||
tenant_no = ReimburseService._tenant_no(db, user)
|
||||
data = dict(obj_in)
|
||||
@@ -622,11 +676,13 @@ class ReimburseService:
|
||||
reimburse_date = parse_reimburse_date(data.pop("reimburse_date", None))
|
||||
requested_title = data.pop("title", None)
|
||||
first_detail = details[0] if details else {}
|
||||
resolved_id = applicant_id or user.id
|
||||
resolved_name = applicant_name or user.name
|
||||
|
||||
apply_obj: BxReimburseApply | None = None
|
||||
for attempt in range(5):
|
||||
title, title_seq = resolve_reimburse_title(
|
||||
db, user.name, tenant_no, reimburse_date, requested_title
|
||||
db, resolved_name, tenant_no, reimburse_date, requested_title
|
||||
)
|
||||
apply_obj = BxReimburseApply(
|
||||
id=generate_uuid(),
|
||||
@@ -636,8 +692,8 @@ class ReimburseService:
|
||||
amount=total_amount,
|
||||
expense_id=str(first_detail.get("expense_id") or ""),
|
||||
expense_name=first_detail.get("expense_name") or "",
|
||||
applicant_id=user.id,
|
||||
applicant_name=user.name,
|
||||
applicant_id=resolved_id,
|
||||
applicant_name=resolved_name,
|
||||
tenant_no=tenant_no,
|
||||
create_by=user.id,
|
||||
create_dept_id=user.dept_id or "",
|
||||
@@ -693,6 +749,7 @@ class ReimburseService:
|
||||
date_changed = reimburse_date != apply_obj.reimburse_date
|
||||
|
||||
requested_title = obj_in.pop("title", None)
|
||||
prev_applicant_id = apply_obj.applicant_id
|
||||
|
||||
for key, value in obj_in.items():
|
||||
setattr(apply_obj, key, value)
|
||||
@@ -703,7 +760,10 @@ class ReimburseService:
|
||||
if requested_title is not None:
|
||||
apply_obj.title = str(requested_title).strip()
|
||||
|
||||
should_regen_title = date_changed and is_auto_reimburse_title(apply_obj.title)
|
||||
applicant_changed = apply_obj.applicant_id != prev_applicant_id
|
||||
should_regen_title = (date_changed or applicant_changed) and is_auto_reimburse_title(
|
||||
apply_obj.title
|
||||
)
|
||||
if should_regen_title:
|
||||
seq = allocate_reimburse_title_seq(
|
||||
db, tenant_no, apply_obj.reimburse_date, exclude_apply_id=apply_id
|
||||
|
||||
@@ -50,8 +50,9 @@ class WorkflowService:
|
||||
*,
|
||||
user: Optional[BxUserContext] = None,
|
||||
) -> Tuple[Sequence[BxWorkflowDef], int]:
|
||||
# 流程定义为租户配置主数据,列表不做 create_by 数据范围过滤
|
||||
return BxCrudService.get_paged(
|
||||
BxWorkflowDef, db, tenant_no, page, page_size, user=user
|
||||
BxWorkflowDef, db, tenant_no, page, page_size, user=user, skip_scope=True
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -88,13 +89,14 @@ class WorkflowService:
|
||||
obj_in,
|
||||
user_id=user.id,
|
||||
user=user,
|
||||
skip_scope=True,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def soft_delete(db: Session, workflow_id: str, *, user: BxUserContext) -> bool:
|
||||
tenant_no = WorkflowService._tenant_no(db, user)
|
||||
deleted = BxCrudService.soft_delete(
|
||||
BxWorkflowDef, db, workflow_id, tenant_no, user_id=user.id, user=user
|
||||
BxWorkflowDef, db, workflow_id, tenant_no, user_id=user.id, user=user, skip_scope=True
|
||||
)
|
||||
if deleted:
|
||||
db.query(BxWorkflowNode).filter(
|
||||
@@ -156,7 +158,7 @@ class WorkflowService:
|
||||
user: BxUserContext,
|
||||
) -> List[BxWorkflowNode]:
|
||||
tenant_no = WorkflowService._tenant_no(db, user)
|
||||
workflow = WorkflowService.get_by_id(db, wf_id, tenant_no, user=user)
|
||||
workflow = WorkflowService.get_by_id(db, wf_id, tenant_no, user=user, skip_scope=True)
|
||||
if not workflow:
|
||||
raise ValueError("工作流不存在")
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
/Users/zlwu/work/00code/shanxia2.0/.worktrees/bx-invoice-wallet/backend
|
||||
/Users/zlwu/work/00code/shanxia2.0/backend
|
||||
File diff suppressed because it is too large.
Load diff
+7637
-7242
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,16 @@
|
||||
-- 报销申请:改选申请人按钮权限
|
||||
-- 幂等:按 id 不存在时插入
|
||||
|
||||
INSERT INTO `sys_menu` (
|
||||
`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`,
|
||||
`is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`,
|
||||
`create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`
|
||||
)
|
||||
SELECT
|
||||
'BX10000000000000000000000000009', '改选申请人', 'BX00000000000000000000000000011', 'F',
|
||||
'', NULL, 'bx:reimburseApply:changeApplicant',
|
||||
1, '1', '1', 'shanxia2.0', 2, '报销申请新增/编辑时可改选申请人并代选其发票',
|
||||
NULL, '', NOW(), NULL, NOW(), 0
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `sys_menu` WHERE `id` = 'BX10000000000000000000000000009'
|
||||
);
|
||||
@@ -131,6 +131,7 @@ INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `co
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('BX10000000000000000000000000005', '备用金审批通过', 'BX00000000000000000000000000008', 'F', '', NULL, 'bx:advanceApprove:approve', 1, '1', '1', 'shanxia2.0', 1, NULL, NULL, '', '2026-06-06 21:22:32', NULL, '2026-06-06 21:22:32', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('BX10000000000000000000000000006', '备用金发放', 'BX00000000000000000000000000009', 'F', '', NULL, 'bx:advanceIssue:issue', 1, '1', '1', 'shanxia2.0', 1, NULL, NULL, '', '2026-06-06 21:22:32', NULL, '2026-06-06 21:22:32', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('BX10000000000000000000000000007', '报销提交', 'BX00000000000000000000000000011', 'F', '', NULL, 'bx:reimburseApply:submit', 1, '1', '1', 'shanxia2.0', 1, NULL, NULL, '', '2026-06-06 21:22:32', NULL, '2026-06-06 21:22:32', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('BX10000000000000000000000000009', '改选申请人', 'BX00000000000000000000000000011', 'F', '', NULL, 'bx:reimburseApply:changeApplicant', 1, '1', '1', 'shanxia2.0', 2, '报销申请新增/编辑时可改选申请人并代选其发票', NULL, '', '2026-07-25 22:00:00', NULL, '2026-07-25 22:00:00', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('BX10000000000000000000000000008', '报销支付', 'BX00000000000000000000000000013', 'F', '', NULL, 'bx:payment:pay', 1, '1', '1', 'shanxia2.0', 1, NULL, NULL, '', '2026-06-06 21:22:32', NULL, '2026-06-06 21:22:32', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('PL_FREIGHT_APPROVAL_Q', '查询', 'PL_FREIGHT_APPROVAL', 'F', '', '', 'pl:freight-approval:query', 1, '1', '1', 'shanxia2.0', 1, NULL, 'system', '', '2026-06-28 16:41:25', NULL, '2026-06-28 16:41:25', 0);
|
||||
INSERT INTO `sys_menu` (`id`, `menu_name`, `parent_id`, `menu_type`, `path`, `component`, `perms`, `is_frame`, `visible`, `status`, `tenant_no`, `order_num`, `remark`, `create_by`, `create_dept_id`, `create_time`, `update_by`, `update_time`, `del_flag`) VALUES ('PL_FREIGHT_DISBURSE_Q', '查询', 'PL_FREIGHT_DISBURSE_MENU', 'F', '', '', 'pl:freight-disburse:query', 1, '1', '1', 'shanxia2.0', 1, NULL, 'system', '', '2026-06-28 16:41:25', NULL, '2026-06-28 16:41:25', 0);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# 报销申请「申请人」可改选设计
|
||||
|
||||
**日期:** 2026-07-25
|
||||
**方案:** A(独立按钮权限)
|
||||
|
||||
## 目标
|
||||
|
||||
- 新增/编辑弹窗展示「申请人」,默认当前登录用户。
|
||||
- 有权限或 `super_admin` 可改选他人;无权限只读展示本人。
|
||||
- 关联发票与额度按所选申请人的发票夹校验。
|
||||
|
||||
## 权限
|
||||
|
||||
- 权限码:`bx:reimburseApply:changeApplicant`(按钮级,挂在「报销申请」下)。
|
||||
- `super_admin` 始终可改选。
|
||||
- 无权限:前端只读;后端忽略客户端 `applicantId`,强制本人。
|
||||
|
||||
## 前后端要点
|
||||
|
||||
- Create/Update 支持可选 `applicantId`;写入 `applicant_id/name`;自动标题用申请人姓名。
|
||||
- 发票列表/余额:持有改申请人权限或发票夹管理权限时可按 `userId` 查他人。
|
||||
- 切换申请人时清空已选发票并刷新余额。
|
||||
+966
-3758
File diff suppressed because it is too large.
Load diff
@@ -1 +1 @@
|
||||
/Users/zlwu/work/00code/shanxia2.0/.worktrees/bx-invoice-wallet/web-admin
|
||||
/Users/zlwu/work/00code/shanxia2.0/web-admin
|
||||
+1357
-1602
File diff suppressed because it is too large.
Load diff
+24526
-24409
File diff suppressed because it is too large.
Load diff
@@ -118,10 +118,11 @@ export const advanceApi = {
|
||||
}
|
||||
|
||||
export const reimburseApi = {
|
||||
generateTitle(reimburseDate?: string, excludeApplyId?: BxId) {
|
||||
generateTitle(reimburseDate?: string, excludeApplyId?: BxId, applicantId?: BxId) {
|
||||
const params: Record<string, string> = {}
|
||||
if (reimburseDate) params.reimburseDate = reimburseDate
|
||||
if (excludeApplyId) params.excludeApplyId = String(excludeApplyId)
|
||||
if (applicantId) params.applicantId = String(applicantId)
|
||||
return bxRequest.get('/reimburses/generate-title', { params })
|
||||
},
|
||||
list(params: {
|
||||
@@ -283,8 +284,8 @@ export const paymentApi = {
|
||||
}
|
||||
|
||||
export const invoiceWalletApi = {
|
||||
mineSummary() {
|
||||
return bxRequest.get('/invoice-wallets/mine/summary')
|
||||
mineSummary(params?: { userId?: BxId }) {
|
||||
return bxRequest.get('/invoice-wallets/mine/summary', { params })
|
||||
},
|
||||
list(params: { page: number; pageSize: number; keyword?: string }) {
|
||||
return bxRequest.get('/invoice-wallets', { params })
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
<template>
|
||||
<div class="attachment-upload">
|
||||
<div
|
||||
ref="rootRef"
|
||||
class="attachment-upload"
|
||||
:class="{ 'attachment-upload--drag-over': isDragOver && !disabled }"
|
||||
:tabindex="disabled ? undefined : 0"
|
||||
@mouseenter="handlePointerEnter"
|
||||
@mouseleave="handlePointerLeave"
|
||||
@focusin="handlePointerEnter"
|
||||
@focusout="handleFocusOut"
|
||||
@dragenter="handleDragEnter"
|
||||
@dragleave="handleDragLeave"
|
||||
@dragover="handleDragOver"
|
||||
@drop="handleDrop"
|
||||
>
|
||||
<div class="attachment-list">
|
||||
<el-upload
|
||||
ref="uploadRef"
|
||||
@@ -12,7 +25,7 @@
|
||||
>
|
||||
<div class="upload-card">
|
||||
<el-icon :size="28" color="#1ca851"><Plus /></el-icon>
|
||||
<span class="upload-card-text">上传附件</span>
|
||||
<span class="upload-card-text">{{ isDragOver ? '松开上传' : '上传附件' }}</span>
|
||||
</div>
|
||||
</el-upload>
|
||||
<div
|
||||
@@ -87,147 +100,273 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue'
|
||||
import {
|
||||
Plus,
|
||||
Loading,
|
||||
VideoPlay,
|
||||
Document,
|
||||
Download,
|
||||
Delete
|
||||
} from '@element-plus/icons-vue'
|
||||
import type { UploadFile, UploadInstance } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { attachmentApi, type BxId } from '@/api/bx'
|
||||
import {
|
||||
type BxAttachmentItem,
|
||||
isBxImageFile,
|
||||
isBxVideoFile,
|
||||
canBxPreview,
|
||||
downloadBxAttachment,
|
||||
previewBxAttachment
|
||||
} from '@/utils/bx/attachment'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import {
|
||||
Plus,
|
||||
Loading,
|
||||
VideoPlay,
|
||||
Document,
|
||||
Download,
|
||||
Delete
|
||||
} from '@element-plus/icons-vue'
|
||||
import type { UploadFile, UploadInstance } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { attachmentApi, type BxId } from '@/api/bx'
|
||||
import {
|
||||
type BxAttachmentItem,
|
||||
isBxImageFile,
|
||||
isBxVideoFile,
|
||||
canBxPreview,
|
||||
downloadBxAttachment,
|
||||
previewBxAttachment
|
||||
} from '@/utils/bx/attachment'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: BxAttachmentItem[]
|
||||
bizType: string
|
||||
bizId?: BxId
|
||||
hint?: string
|
||||
showHint?: boolean
|
||||
disabled?: boolean
|
||||
}>(),
|
||||
{
|
||||
bizId: 0,
|
||||
hint: '支持图片、视频、PDF、Word、Excel等文件',
|
||||
showHint: true,
|
||||
disabled: false
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: BxAttachmentItem[]]
|
||||
}>()
|
||||
|
||||
const uploadRef = ref<UploadInstance>()
|
||||
const globalUploading = ref(false)
|
||||
const previewVisible = ref(false)
|
||||
const previewUrl = ref('')
|
||||
const previewFileName = ref('')
|
||||
const previewMode = ref<'image' | 'video'>('image')
|
||||
|
||||
const files = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value)
|
||||
})
|
||||
|
||||
function syncFiles(next: BxAttachmentItem[]) {
|
||||
emit('update:modelValue', next)
|
||||
}
|
||||
|
||||
async function handleAttachmentChange(uploadFile: UploadFile) {
|
||||
const rawFile = uploadFile.raw
|
||||
if (!rawFile) return
|
||||
|
||||
const item: BxAttachmentItem = {
|
||||
id: `upload-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
fileName: rawFile.name,
|
||||
fileType: rawFile.type,
|
||||
fileSize: rawFile.size,
|
||||
previewUrl: '',
|
||||
_uploading: true
|
||||
}
|
||||
syncFiles([...files.value, item])
|
||||
globalUploading.value = true
|
||||
|
||||
try {
|
||||
const res: any = await attachmentApi.upload(rawFile, props.bizType, props.bizId ?? 0)
|
||||
item.id = res.data.id
|
||||
item.fileName = res.data.fileName || item.fileName
|
||||
item.fileType = res.data.fileType || item.fileType
|
||||
item.fileSize = res.data.fileSize ?? item.fileSize
|
||||
item._uploading = false
|
||||
if (isBxImageFile(item)) {
|
||||
try {
|
||||
const previewRes: any = await attachmentApi.preview(item.id)
|
||||
item.previewUrl = previewRes.data?.url || ''
|
||||
} catch {
|
||||
/* preview optional */
|
||||
}
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: BxAttachmentItem[]
|
||||
bizType: string
|
||||
bizId?: BxId
|
||||
hint?: string
|
||||
showHint?: boolean
|
||||
disabled?: boolean
|
||||
}>(),
|
||||
{
|
||||
bizId: 0,
|
||||
hint: '支持图片、视频、PDF、Word、Excel等文件;可拖拽或在此区域粘贴上传',
|
||||
showHint: true,
|
||||
disabled: false
|
||||
}
|
||||
syncFiles([...files.value])
|
||||
} catch (error: any) {
|
||||
syncFiles(files.value.filter((entry) => entry.id !== item.id))
|
||||
ElMessage.error(error?.message || '上传失败')
|
||||
} finally {
|
||||
globalUploading.value = files.value.some((entry) => entry._uploading)
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: BxAttachmentItem[]]
|
||||
}>()
|
||||
|
||||
const rootRef = ref<HTMLElement>()
|
||||
const uploadRef = ref<UploadInstance>()
|
||||
const globalUploading = ref(false)
|
||||
const previewVisible = ref(false)
|
||||
const previewUrl = ref('')
|
||||
const previewFileName = ref('')
|
||||
const previewMode = ref<'image' | 'video'>('image')
|
||||
const isPointerInside = ref(false)
|
||||
const isDragOver = ref(false)
|
||||
let dragEnterDepth = 0
|
||||
|
||||
const files = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value)
|
||||
})
|
||||
|
||||
function syncFiles(next: BxAttachmentItem[]) {
|
||||
emit('update:modelValue', next)
|
||||
}
|
||||
|
||||
function normalizeIncomingFile(file: File, index = 0) {
|
||||
if (file.name && file.name.trim()) return file
|
||||
const ext = (file.type || '').split('/')[1] || 'bin'
|
||||
return new File([file], `paste-${Date.now()}-${index}.${ext}`, {
|
||||
type: file.type || 'application/octet-stream'
|
||||
})
|
||||
}
|
||||
|
||||
function collectClipboardFiles(event: ClipboardEvent) {
|
||||
const out: File[] = []
|
||||
const items = event.clipboardData?.items
|
||||
if (items?.length) {
|
||||
Array.from(items).forEach((item, index) => {
|
||||
if (item.kind !== 'file') return
|
||||
const file = item.getAsFile()
|
||||
if (file) out.push(normalizeIncomingFile(file, index))
|
||||
})
|
||||
}
|
||||
if (!out.length && event.clipboardData?.files?.length) {
|
||||
Array.from(event.clipboardData.files).forEach((file, index) => {
|
||||
out.push(normalizeIncomingFile(file, index))
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function uploadRawFile(rawFile: File) {
|
||||
if (props.disabled) return
|
||||
const item: BxAttachmentItem = {
|
||||
id: `upload-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
||||
fileName: rawFile.name,
|
||||
fileType: rawFile.type,
|
||||
fileSize: rawFile.size,
|
||||
previewUrl: '',
|
||||
_uploading: true
|
||||
}
|
||||
syncFiles([...files.value, item])
|
||||
globalUploading.value = true
|
||||
|
||||
try {
|
||||
const res: any = await attachmentApi.upload(rawFile, props.bizType, props.bizId ?? 0)
|
||||
item.id = res.data.id
|
||||
item.fileName = res.data.fileName || item.fileName
|
||||
item.fileType = res.data.fileType || item.fileType
|
||||
item.fileSize = res.data.fileSize ?? item.fileSize
|
||||
item._uploading = false
|
||||
if (isBxImageFile(item)) {
|
||||
try {
|
||||
const previewRes: any = await attachmentApi.preview(item.id)
|
||||
item.previewUrl = previewRes.data?.url || ''
|
||||
} catch {
|
||||
/* preview optional */
|
||||
}
|
||||
}
|
||||
syncFiles([...files.value])
|
||||
} catch (error: any) {
|
||||
syncFiles(files.value.filter((entry) => entry.id !== item.id))
|
||||
ElMessage.error(error?.message || '上传失败')
|
||||
} finally {
|
||||
globalUploading.value = files.value.some((entry) => entry._uploading)
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadFiles(list: File[]) {
|
||||
for (const file of list) {
|
||||
await uploadRawFile(file)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAttachmentChange(uploadFile: UploadFile) {
|
||||
const rawFile = uploadFile.raw
|
||||
if (!rawFile) return
|
||||
await uploadRawFile(rawFile)
|
||||
await nextTick()
|
||||
uploadRef.value?.clearFiles()
|
||||
}
|
||||
}
|
||||
|
||||
async function removeAttachment(index: number) {
|
||||
const file = files.value[index]
|
||||
if (!file || file._uploading) return
|
||||
try {
|
||||
await ElMessageBox.confirm('确定删除该附件?', '提示', { type: 'warning' })
|
||||
if (typeof file.id === 'number' || /^\d+$/.test(String(file.id))) {
|
||||
await attachmentApi.delete(file.id)
|
||||
}
|
||||
const next = [...files.value]
|
||||
next.splice(index, 1)
|
||||
syncFiles(next)
|
||||
ElMessage.success('已删除')
|
||||
} catch {
|
||||
/* cancelled */
|
||||
function handlePointerEnter() {
|
||||
if (props.disabled) return
|
||||
isPointerInside.value = true
|
||||
}
|
||||
}
|
||||
|
||||
function handleDownload(file: BxAttachmentItem) {
|
||||
if (file._uploading) return
|
||||
downloadBxAttachment(file)
|
||||
}
|
||||
function handlePointerLeave() {
|
||||
isPointerInside.value = false
|
||||
}
|
||||
|
||||
async function handlePreview(file: BxAttachmentItem) {
|
||||
const result = await previewBxAttachment(file)
|
||||
if (!result) return
|
||||
previewMode.value = result.type
|
||||
previewUrl.value = result.url
|
||||
previewFileName.value = result.fileName
|
||||
previewVisible.value = true
|
||||
}
|
||||
function handleFocusOut(event: FocusEvent) {
|
||||
const next = event.relatedTarget as Node | null
|
||||
if (next && rootRef.value?.contains(next)) return
|
||||
isPointerInside.value = false
|
||||
}
|
||||
|
||||
function hasUploading() {
|
||||
return files.value.some((item) => item._uploading)
|
||||
}
|
||||
function handleDragEnter(event: DragEvent) {
|
||||
if (props.disabled) return
|
||||
event.preventDefault()
|
||||
dragEnterDepth += 1
|
||||
isDragOver.value = true
|
||||
isPointerInside.value = true
|
||||
}
|
||||
|
||||
function getFileIds() {
|
||||
return files.value.filter((item) => !item._uploading).map((item) => item.id)
|
||||
}
|
||||
function handleDragLeave(event: DragEvent) {
|
||||
if (props.disabled) return
|
||||
event.preventDefault()
|
||||
dragEnterDepth = Math.max(0, dragEnterDepth - 1)
|
||||
if (dragEnterDepth === 0) isDragOver.value = false
|
||||
}
|
||||
|
||||
defineExpose({ hasUploading, getFileIds })
|
||||
function handleDragOver(event: DragEvent) {
|
||||
if (props.disabled) return
|
||||
event.preventDefault()
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy'
|
||||
}
|
||||
|
||||
async function handleDrop(event: DragEvent) {
|
||||
if (props.disabled) return
|
||||
event.preventDefault()
|
||||
dragEnterDepth = 0
|
||||
isDragOver.value = false
|
||||
await uploadFiles(Array.from(event.dataTransfer?.files || []))
|
||||
}
|
||||
|
||||
async function handleDocumentPaste(event: ClipboardEvent) {
|
||||
if (props.disabled || !isPointerInside.value) return
|
||||
const clipboardFiles = collectClipboardFiles(event)
|
||||
if (!clipboardFiles.length) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
await uploadFiles(clipboardFiles)
|
||||
}
|
||||
|
||||
async function removeAttachment(index: number) {
|
||||
const file = files.value[index]
|
||||
if (!file || file._uploading) return
|
||||
try {
|
||||
await ElMessageBox.confirm('确定删除该附件?', '提示', { type: 'warning' })
|
||||
if (typeof file.id === 'number' || /^\d+$/.test(String(file.id))) {
|
||||
await attachmentApi.delete(file.id)
|
||||
}
|
||||
const next = [...files.value]
|
||||
next.splice(index, 1)
|
||||
syncFiles(next)
|
||||
ElMessage.success('已删除')
|
||||
} catch {
|
||||
/* cancelled */
|
||||
}
|
||||
}
|
||||
|
||||
function handleDownload(file: BxAttachmentItem) {
|
||||
if (file._uploading) return
|
||||
downloadBxAttachment(file)
|
||||
}
|
||||
|
||||
async function handlePreview(file: BxAttachmentItem) {
|
||||
const result = await previewBxAttachment(file)
|
||||
if (!result) return
|
||||
previewMode.value = result.type
|
||||
previewUrl.value = result.url
|
||||
previewFileName.value = result.fileName
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
function hasUploading() {
|
||||
return files.value.some((item) => item._uploading)
|
||||
}
|
||||
|
||||
function getFileIds() {
|
||||
return files.value.filter((item) => !item._uploading).map((item) => item.id)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('paste', handleDocumentPaste, true)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('paste', handleDocumentPaste, true)
|
||||
})
|
||||
|
||||
defineExpose({ hasUploading, getFileIds })
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use '@/styles/bx/attachment.scss';
|
||||
@use '@/styles/bx/attachment.scss';
|
||||
|
||||
.attachment-upload {
|
||||
outline: none;
|
||||
border-radius: 8px;
|
||||
|
||||
&:focus-visible {
|
||||
box-shadow: 0 0 0 2px rgba(28, 168, 81, 0.25);
|
||||
}
|
||||
|
||||
&--drag-over {
|
||||
.attachment-list {
|
||||
padding: 4px;
|
||||
border-radius: 8px;
|
||||
outline: 2px dashed #1ca851;
|
||||
outline-offset: 4px;
|
||||
background: rgba(16, 185, 129, 0.06);
|
||||
}
|
||||
|
||||
.upload-card {
|
||||
border-color: #1ca851;
|
||||
border-style: solid;
|
||||
background: #e6f8ed;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,35 +2,68 @@
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="从发票夹选择"
|
||||
width="720px"
|
||||
class="dialog-form-layout"
|
||||
width="1040px"
|
||||
class="dialog-form-layout bx-invoice-select-dialog"
|
||||
align-center
|
||||
destroy-on-close
|
||||
append-to-body
|
||||
@open="loadList"
|
||||
>
|
||||
<el-table
|
||||
ref="tableRef"
|
||||
v-loading="loading"
|
||||
class="list-table"
|
||||
:data="rows"
|
||||
stripe
|
||||
row-key="id"
|
||||
max-height="420"
|
||||
@selection-change="onSelectionChange"
|
||||
>
|
||||
<el-table-column type="selection" min-width="48" />
|
||||
<el-table-column prop="amount" label="金额(元)" min-width="120" align="right">
|
||||
<template #default="{ row }">{{ formatMoneyYuan(row.amount) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="fileName" label="附件" min-width="180" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ attachmentLabel(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="remark" label="备注" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.remark || '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="createTime" label="上传时间" min-width="160" />
|
||||
</el-table>
|
||||
<div v-loading="loading" class="invoice-attach-panel">
|
||||
<div v-if="!loading && !monthGroups.length" class="invoice-attach-empty">暂无发票附件</div>
|
||||
<div v-else class="invoice-attach-months">
|
||||
<section v-for="group in monthGroups" :key="group.monthKey" class="invoice-attach-month">
|
||||
<h4 class="invoice-attach-month__title">{{ group.monthLabel }}</h4>
|
||||
<div class="invoice-attach-grid">
|
||||
<button
|
||||
v-for="item in group.items"
|
||||
:key="item.key"
|
||||
type="button"
|
||||
class="invoice-attach-card"
|
||||
:class="{ 'is-selected': selectedKeys.has(item.key) }"
|
||||
@click="toggleOne(item.key)"
|
||||
>
|
||||
<span class="invoice-attach-card__index">{{ item.serial }}</span>
|
||||
<div class="invoice-attach-card__preview">
|
||||
<template v-if="isBxImageFile(item.file) && item.file.previewUrl">
|
||||
<img :src="item.file.previewUrl" :alt="item.file.fileName" />
|
||||
</template>
|
||||
<template v-else-if="isBxVideoFile(item.file)">
|
||||
<div class="attachment-preview__icon attachment-preview__icon--video">
|
||||
<el-icon :size="28"><VideoPlay /></el-icon>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="attachment-preview__icon attachment-preview__icon--doc">
|
||||
<el-icon :size="28"><Document /></el-icon>
|
||||
</div>
|
||||
</template>
|
||||
<span v-if="selectedKeys.has(item.key)" class="invoice-attach-check">
|
||||
<el-icon :size="14"><Check /></el-icon>
|
||||
</span>
|
||||
</div>
|
||||
<div class="invoice-attach-card__meta">
|
||||
<span class="invoice-attach-card__name" :title="item.file.fileName">
|
||||
{{ item.file.fileName }}
|
||||
</span>
|
||||
<div class="invoice-attach-card__footer">
|
||||
<span class="invoice-attach-card__amount">
|
||||
{{ formatMoneyYuan(item.amount) }} 元
|
||||
</span>
|
||||
<el-icon
|
||||
class="invoice-attach-card__download"
|
||||
title="下载"
|
||||
@click.stop="handleDownload(item.file)"
|
||||
>
|
||||
<Download />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button class="btn-ghost" @click="visible = false">
|
||||
@@ -44,28 +77,75 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
import { Close, Check } from '@element-plus/icons-vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Close, Check, VideoPlay, Document, Download } from '@element-plus/icons-vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { invoiceApi } from '@/api/bx'
|
||||
import { formatMoneyYuan } from '@/utils/bx/format'
|
||||
import { pickBxPageResult } from '@/utils/http/bx'
|
||||
import {
|
||||
type BxAttachmentItem,
|
||||
fillBxAttachmentPreviews,
|
||||
downloadBxAttachment,
|
||||
isBxImageFile,
|
||||
isBxVideoFile
|
||||
} from '@/utils/bx/attachment'
|
||||
|
||||
export type InvoiceAttachPick = {
|
||||
key: string
|
||||
invoiceId: string | number
|
||||
attachmentId: string | number
|
||||
amount: number | string
|
||||
createTime: string
|
||||
invoice: any
|
||||
file: BxAttachmentItem
|
||||
}
|
||||
|
||||
type MonthGroup = {
|
||||
monthKey: string
|
||||
monthLabel: string
|
||||
items: Array<InvoiceAttachPick & { serial: number }>
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
selectedIds?: string[]
|
||||
/** 已选附件 key:`${invoiceId}:${attachmentId}` */
|
||||
selectedKeys?: string[]
|
||||
/** 代申请时查询指定申请人的发票夹 */
|
||||
ownerUserId?: string | number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update:modelValue', v: boolean): void
|
||||
(e: 'confirm', rows: any[]): void
|
||||
(e: 'confirm', picks: InvoiceAttachPick[]): void
|
||||
}>()
|
||||
|
||||
const visible = ref(false)
|
||||
const loading = ref(false)
|
||||
const rows = ref<any[]>([])
|
||||
const selected = ref<any[]>([])
|
||||
const tableRef = ref<any>(null)
|
||||
const attachItems = ref<InvoiceAttachPick[]>([])
|
||||
const selectedKeys = ref<Set<string>>(new Set())
|
||||
|
||||
const monthGroups = computed<MonthGroup[]>(() => {
|
||||
const map = new Map<string, InvoiceAttachPick[]>()
|
||||
attachItems.value.forEach((item) => {
|
||||
const monthKey = toMonthKey(item.createTime)
|
||||
const list = map.get(monthKey) || []
|
||||
list.push(item)
|
||||
map.set(monthKey, list)
|
||||
})
|
||||
return Array.from(map.entries())
|
||||
.sort((a, b) => b[0].localeCompare(a[0]))
|
||||
.map(([monthKey, items]) => {
|
||||
const sorted = items
|
||||
.slice()
|
||||
.sort((a, b) => String(b.createTime).localeCompare(String(a.createTime)))
|
||||
return {
|
||||
monthKey,
|
||||
monthLabel: toMonthLabel(monthKey),
|
||||
items: sorted.map((item, idx) => ({ ...item, serial: idx + 1 }))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
@@ -79,44 +159,262 @@
|
||||
emit('update:modelValue', v)
|
||||
})
|
||||
|
||||
function toMonthKey(raw: string) {
|
||||
const text = String(raw || '').trim()
|
||||
if (!text) return 'unknown'
|
||||
const m = text.match(/^(\d{4})[-/]?(\d{2})/)
|
||||
if (m) return `${m[1]}-${m[2]}`
|
||||
const d = new Date(text)
|
||||
if (!Number.isNaN(d.getTime())) {
|
||||
const y = d.getFullYear()
|
||||
const mo = String(d.getMonth() + 1).padStart(2, '0')
|
||||
return `${y}-${mo}`
|
||||
}
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function toMonthLabel(monthKey: string) {
|
||||
if (monthKey === 'unknown') return '未知月份'
|
||||
const [y, m] = monthKey.split('-')
|
||||
return `${y}年${Number(m)}月`
|
||||
}
|
||||
|
||||
function invoiceAttachments(row: any): BxAttachmentItem[] {
|
||||
const list = Array.isArray(row?.attachments) ? row.attachments : []
|
||||
if (list.length) {
|
||||
return list.map((a: any) => ({
|
||||
id: a.id || a.attachmentId,
|
||||
fileName: a.fileName || a.file_name || '发票附件',
|
||||
fileType: a.fileType || a.file_type || '',
|
||||
previewUrl: a.previewUrl || '',
|
||||
_existing: true
|
||||
}))
|
||||
}
|
||||
if (row?.attachmentId) {
|
||||
return [
|
||||
{
|
||||
id: row.attachmentId,
|
||||
fileName: row.fileName || '发票附件',
|
||||
fileType: row.fileType || '',
|
||||
previewUrl: '',
|
||||
_existing: true
|
||||
}
|
||||
]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function buildAttachItems(rows: any[]): InvoiceAttachPick[] {
|
||||
const items: InvoiceAttachPick[] = []
|
||||
rows.forEach((row) => {
|
||||
invoiceAttachments(row).forEach((file) => {
|
||||
const attachmentId = file.id
|
||||
items.push({
|
||||
key: `${row.id}:${attachmentId}`,
|
||||
invoiceId: row.id,
|
||||
attachmentId,
|
||||
amount: row.amount,
|
||||
createTime: row.createTime || row.create_time || '',
|
||||
invoice: row,
|
||||
file
|
||||
})
|
||||
})
|
||||
})
|
||||
return items
|
||||
}
|
||||
|
||||
async function loadList() {
|
||||
loading.value = true
|
||||
try {
|
||||
const res: any = await invoiceApi.list({ page: 1, pageSize: 200 })
|
||||
const page = pickBxPageResult<any>(res)
|
||||
rows.value = page.list
|
||||
await nextTick()
|
||||
const idSet = new Set((props.selectedIds || []).map(String))
|
||||
selected.value = []
|
||||
rows.value.forEach((row) => {
|
||||
if (idSet.has(String(row.id))) {
|
||||
tableRef.value?.toggleRowSelection?.(row, true)
|
||||
}
|
||||
const res: any = await invoiceApi.list({
|
||||
page: 1,
|
||||
pageSize: 200,
|
||||
userId: props.ownerUserId || undefined
|
||||
})
|
||||
const page = pickBxPageResult<any>(res)
|
||||
const items = buildAttachItems(page.list)
|
||||
await fillBxAttachmentPreviews(items.map((item) => item.file))
|
||||
attachItems.value = items
|
||||
const preferred = new Set((props.selectedKeys || []).map(String))
|
||||
selectedKeys.value = new Set(items.filter((i) => preferred.has(i.key)).map((i) => i.key))
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e?.message || '加载发票失败')
|
||||
attachItems.value = []
|
||||
selectedKeys.value = new Set()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onSelectionChange(list: any[]) {
|
||||
selected.value = list
|
||||
/** 多选:同一批附件可逐个勾选,互不影响 */
|
||||
function toggleOne(key: string) {
|
||||
const next = new Set(selectedKeys.value)
|
||||
if (next.has(key)) next.delete(key)
|
||||
else next.add(key)
|
||||
selectedKeys.value = next
|
||||
}
|
||||
|
||||
function attachmentLabel(row: any) {
|
||||
const list = Array.isArray(row?.attachments) ? row.attachments : []
|
||||
if (list.length) {
|
||||
return list
|
||||
.map((a: any) => a.fileName || a.file_name)
|
||||
.filter(Boolean)
|
||||
.join('、') || `${list.length} 个附件`
|
||||
}
|
||||
return row?.fileName || '-'
|
||||
function handleDownload(file: BxAttachmentItem) {
|
||||
downloadBxAttachment(file)
|
||||
}
|
||||
|
||||
function confirm() {
|
||||
emit('confirm', selected.value.slice())
|
||||
emit(
|
||||
'confirm',
|
||||
attachItems.value.filter((item) => selectedKeys.value.has(item.key))
|
||||
)
|
||||
visible.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
@use '@/styles/bx/attachment.scss';
|
||||
|
||||
.invoice-attach-panel {
|
||||
min-height: calc(100vh - 280px);
|
||||
}
|
||||
|
||||
.invoice-attach-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 240px;
|
||||
font-size: 13px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
}
|
||||
|
||||
.invoice-attach-months {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.invoice-attach-month__title {
|
||||
margin: 0 0 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text, #1e293b);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.invoice-attach-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-content: flex-start;
|
||||
}
|
||||
|
||||
.invoice-attach-card {
|
||||
position: relative;
|
||||
width: 140px;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border, #d9e8e2);
|
||||
border-radius: 8px;
|
||||
background: var(--surface, #fff);
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition:
|
||||
border-color 0.15s ease,
|
||||
box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary, #10b981);
|
||||
box-shadow: 0 2px 8px rgba(16, 185, 129, 0.12);
|
||||
}
|
||||
|
||||
&.is-selected {
|
||||
border-color: var(--primary, #10b981);
|
||||
box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
.invoice-attach-card__index {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 6px;
|
||||
left: 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
color: var(--primary, #10b981);
|
||||
background: none;
|
||||
}
|
||||
|
||||
.invoice-attach-card__preview {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 96px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--table-head, #f8fafc);
|
||||
overflow: hidden;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.invoice-attach-check {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
background: var(--primary, #10b981);
|
||||
color: #fff;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.invoice-attach-card__meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.invoice-attach-card__name {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
color: var(--text, #1e293b);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.invoice-attach-card__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.invoice-attach-card__amount {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--primary-dark, #059669);
|
||||
}
|
||||
|
||||
.invoice-attach-card__download {
|
||||
flex-shrink: 0;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 4px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary, #10b981);
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -3,7 +3,7 @@
|
||||
<header class="portal-header">
|
||||
<div class="portal-header-start">
|
||||
<div class="portal-header-brand" @click="toHome">
|
||||
<ArtLogo class="portal-header-logo" src="/logo-sx.svg" :size="38" />
|
||||
<ArtLogo class="portal-header-logo" src="/logo-sx.svg" :size="28" />
|
||||
<p class="portal-header-title">{{ AppConfig.systemInfo.name }}</p>
|
||||
</div>
|
||||
|
||||
@@ -110,7 +110,7 @@
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 12px;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
/* +1px:与侧栏 #app-sidebar 外边框(内容宽 + 1px border)纵向对齐 */
|
||||
width: calc(var(--app-sidebar-open-width, 270px) + 1px);
|
||||
@@ -134,7 +134,7 @@
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
color: #fff;
|
||||
white-space: nowrap;
|
||||
|
||||
@@ -93,6 +93,15 @@ bxAxios.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
|
||||
if (config.url) {
|
||||
config.url = normalizeBxUrl(config.url)
|
||||
}
|
||||
if (config.data instanceof FormData) {
|
||||
// 让浏览器自动带 multipart boundary;覆盖实例默认 application/json
|
||||
if (typeof config.headers.set === 'function') {
|
||||
config.headers.set('Content-Type', false as unknown as string)
|
||||
} else {
|
||||
delete (config.headers as any)['Content-Type']
|
||||
delete (config.headers as any)['content-type']
|
||||
}
|
||||
}
|
||||
const store = useUserStore()
|
||||
let token = store.accessToken as unknown as string
|
||||
if (!token) {
|
||||
|
||||
@@ -234,14 +234,31 @@
|
||||
<el-dialog
|
||||
v-model="dialogs.add"
|
||||
:title="editingId ? '编辑报销申请' : '新增报销申请'"
|
||||
width="780px"
|
||||
width="1040px"
|
||||
class="dialog-form-layout"
|
||||
align-center
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<el-form label-position="top" class="bx-dialog-form">
|
||||
<div class="form-grid-2">
|
||||
<div class="form-grid-3">
|
||||
<el-form-item label="申请人">
|
||||
<el-select
|
||||
v-model="addForm.applicantId"
|
||||
placeholder="请选择申请人"
|
||||
filterable
|
||||
:disabled="!canChangeApplicant"
|
||||
style="width: 100%"
|
||||
@change="onApplicantChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in applicantOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="报销日期">
|
||||
<el-date-picker
|
||||
v-model="addForm.reimburseDate"
|
||||
@@ -340,21 +357,55 @@
|
||||
<el-button class="btn-ghost" @click="invoiceSelectVisible = true">
|
||||
<el-icon><FolderOpened /></el-icon>从发票夹选择
|
||||
</el-button>
|
||||
<span class="invoice-select-hint">发票请先在「我的发票夹」上传;此处仅做可选关联。</span>
|
||||
</div>
|
||||
<div v-if="selectedInvoices.length" class="invoice-selected-list">
|
||||
<el-tag
|
||||
v-for="inv in selectedInvoices"
|
||||
:key="inv.id"
|
||||
class="invoice-selected-tag"
|
||||
closable
|
||||
@close="removeSelectedInvoice(inv.id)"
|
||||
<div v-if="selectedInvoicePicks.length" class="invoice-selected-thumbs">
|
||||
<div
|
||||
v-for="pick in selectedInvoicePicks"
|
||||
:key="pick.key"
|
||||
class="invoice-selected-card"
|
||||
>
|
||||
{{ formatMoneyYuan(inv.amount) }} 元
|
||||
<template v-if="invoicePickLabel(inv)"> · {{ invoicePickLabel(inv) }}</template>
|
||||
</el-tag>
|
||||
<button
|
||||
type="button"
|
||||
class="invoice-selected-card__remove"
|
||||
title="移除"
|
||||
@click="removeSelectedInvoice(pick.key)"
|
||||
>
|
||||
<el-icon :size="12"><Close /></el-icon>
|
||||
</button>
|
||||
<div class="invoice-selected-card__preview">
|
||||
<template v-if="isBxImageFile(pick) && pick.previewUrl">
|
||||
<img :src="pick.previewUrl" :alt="pick.fileName" />
|
||||
</template>
|
||||
<template v-else-if="isBxVideoFile(pick)">
|
||||
<div class="invoice-selected-card__icon invoice-selected-card__icon--video">
|
||||
<el-icon :size="20"><VideoPlay /></el-icon>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="invoice-selected-card__icon invoice-selected-card__icon--doc">
|
||||
<el-icon :size="20"><Document /></el-icon>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<div class="invoice-selected-card__meta">
|
||||
<span class="invoice-selected-card__name" :title="pick.fileName">
|
||||
{{ pick.fileName || '发票附件' }}
|
||||
</span>
|
||||
<div class="invoice-selected-card__footer">
|
||||
<span class="invoice-selected-card__amount">
|
||||
{{ formatMoneyYuan(pick.amount) }} 元
|
||||
</span>
|
||||
<el-icon
|
||||
class="invoice-selected-card__download"
|
||||
title="下载"
|
||||
@click="downloadSelectedInvoice(pick)"
|
||||
>
|
||||
<Download />
|
||||
</el-icon>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="invoice-selected-empty">未关联发票(可选)</div>
|
||||
</div>
|
||||
|
||||
<el-form label-position="top" class="bx-dialog-form">
|
||||
@@ -375,7 +426,8 @@
|
||||
|
||||
<BxInvoiceSelectDialog
|
||||
v-model="invoiceSelectVisible"
|
||||
:selected-ids="selectedInvoices.map((i) => String(i.id))"
|
||||
:selected-keys="selectedInvoicePicks.map((p) => p.key)"
|
||||
:owner-user-id="addForm.applicantId || undefined"
|
||||
@confirm="onInvoicesPicked"
|
||||
/>
|
||||
|
||||
@@ -541,12 +593,18 @@ import {
|
||||
Check,
|
||||
Search,
|
||||
RefreshLeft,
|
||||
FolderOpened
|
||||
FolderOpened,
|
||||
VideoPlay,
|
||||
Document,
|
||||
Download
|
||||
} from '@element-plus/icons-vue'
|
||||
import { reimburseApi, invoiceWalletApi } from '@/api/bx'
|
||||
import { fetchGetMenuCodes } from '@/api/auth'
|
||||
import { buildApplyDateRangeQuery, type ApplyDateRange } from '@/utils/bx/apply-date-filter'
|
||||
import { canDeleteByCreator, allRowsDeletableByCreator, CREATOR_DELETE_TIP } from '@/utils/creator-delete'
|
||||
import { useExpenseItemTree, type ExpenseItem } from '@/hooks/bx/useExpenseItemTree'
|
||||
import { useApplicantOptions } from '@/hooks/bx/useApplicantOptions'
|
||||
import { useUserStore } from '@/store/modules/user'
|
||||
import {
|
||||
statusLabel,
|
||||
statusTagType,
|
||||
@@ -567,7 +625,13 @@ import BxInvoiceSelectDialog from '@/components/bx/base/BxInvoiceSelectDialog.vu
|
||||
import type { ViewField } from '@/components/business/system-view-dialog/types'
|
||||
import { bxViewKv, bxViewKvLong, bxViewKvMoney } from '@/utils/bx/view-kv'
|
||||
import { buildPageSummaryMethod, sumField } from '@/utils/bx/table-summary'
|
||||
import { type BxAttachmentItem, loadBxAttachments } from '@/utils/bx/attachment'
|
||||
import {
|
||||
type BxAttachmentItem,
|
||||
loadBxAttachments,
|
||||
downloadBxAttachment,
|
||||
isBxImageFile,
|
||||
isBxVideoFile
|
||||
} from '@/utils/bx/attachment'
|
||||
import { pickBxData } from '@/utils/http/bx'
|
||||
|
||||
type DialogKey = 'add' | 'view' | 'viewFlow'
|
||||
@@ -593,6 +657,38 @@ const { rows, total, currentPage, pageSize, rangeText, loading, refresh, search,
|
||||
)
|
||||
|
||||
const { expenseTree } = useExpenseItemTree()
|
||||
const { applicantOptions, loadApplicantOptions } = useApplicantOptions()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const CHANGE_APPLICANT_PERM = 'bx:reimburseApply:changeApplicant'
|
||||
const canChangeApplicant = ref(false)
|
||||
|
||||
function isSuperAdminUser() {
|
||||
const roles = userStore.info?.roles || []
|
||||
return userStore.info?.role === 'super_admin' || roles.includes('super_admin')
|
||||
}
|
||||
|
||||
function currentUserId() {
|
||||
return String(userStore.info?.userId || userStore.info?.id || '')
|
||||
}
|
||||
|
||||
async function loadChangeApplicantPerm() {
|
||||
if (isSuperAdminUser()) {
|
||||
canChangeApplicant.value = true
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await fetchGetMenuCodes()
|
||||
if (res?.all || res?.isSuperAdmin) {
|
||||
canChangeApplicant.value = true
|
||||
return
|
||||
}
|
||||
const codes = new Set(res?.menuCodes || [])
|
||||
canChangeApplicant.value = codes.has(CHANGE_APPLICANT_PERM)
|
||||
} catch {
|
||||
canChangeApplicant.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function markDisabledExpenseNodes(tree: ExpenseItem[]): ExpenseItem[] {
|
||||
return tree.map((node) => ({
|
||||
@@ -639,6 +735,7 @@ function todayYmd() {
|
||||
}
|
||||
|
||||
const addForm = reactive({
|
||||
applicantId: '' as string,
|
||||
reimburseDate: todayYmd(),
|
||||
title: '',
|
||||
remark: '',
|
||||
@@ -687,7 +784,17 @@ const viewAttachments = ref<BxAttachmentItem[]>([])
|
||||
const viewPayAttachments = ref<BxAttachmentItem[]>([])
|
||||
const viewOffsetAttachments = ref<BxAttachmentItem[]>([])
|
||||
const viewLinkedInvoices = ref<any[]>([])
|
||||
const selectedInvoices = ref<any[]>([])
|
||||
type SelectedInvoicePick = {
|
||||
key: string
|
||||
invoiceId: string | number
|
||||
attachmentId: string | number
|
||||
amount: number | string
|
||||
fileName: string
|
||||
fileType?: string
|
||||
previewUrl?: string
|
||||
}
|
||||
|
||||
const selectedInvoicePicks = ref<SelectedInvoicePick[]>([])
|
||||
const invoiceSelectVisible = ref(false)
|
||||
const walletBalance = ref(0)
|
||||
const editingId = ref<number | null>(null)
|
||||
@@ -706,7 +813,8 @@ async function refreshGeneratedTitle() {
|
||||
try {
|
||||
const res: any = await reimburseApi.generateTitle(
|
||||
addForm.reimburseDate,
|
||||
editingId.value ?? undefined
|
||||
editingId.value ?? undefined,
|
||||
addForm.applicantId || undefined
|
||||
)
|
||||
addForm.title = res.data || ''
|
||||
titleAutoLinked.value = true
|
||||
@@ -725,9 +833,16 @@ async function onReimburseDateChange() {
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshWalletBalance() {
|
||||
async function onApplicantChange() {
|
||||
selectedInvoicePicks.value = []
|
||||
await Promise.all([refreshWalletBalance(), refreshGeneratedTitle()])
|
||||
}
|
||||
|
||||
async function refreshWalletBalance(ownerUserId?: string) {
|
||||
try {
|
||||
const res: any = await invoiceWalletApi.mineSummary()
|
||||
const res: any = await invoiceWalletApi.mineSummary({
|
||||
userId: ownerUserId || addForm.applicantId || undefined
|
||||
})
|
||||
const data: any = pickBxData(res) || {}
|
||||
walletBalance.value = Number(data.balance ?? 0)
|
||||
} catch {
|
||||
@@ -735,35 +850,84 @@ async function refreshWalletBalance() {
|
||||
}
|
||||
}
|
||||
|
||||
function onInvoicesPicked(rows: any[]) {
|
||||
selectedInvoices.value = rows
|
||||
function onInvoicesPicked(picks: any[]) {
|
||||
selectedInvoicePicks.value = (picks || []).map((pick) => ({
|
||||
key: String(pick.key),
|
||||
invoiceId: pick.invoiceId,
|
||||
attachmentId: pick.attachmentId,
|
||||
amount: pick.amount,
|
||||
fileName: pick.file?.fileName || '',
|
||||
fileType: pick.file?.fileType || '',
|
||||
previewUrl: pick.file?.previewUrl || ''
|
||||
}))
|
||||
}
|
||||
|
||||
function invoicePickLabel(inv: any) {
|
||||
const list = Array.isArray(inv?.attachments) ? inv.attachments : []
|
||||
if (list.length) {
|
||||
return list
|
||||
.map((a: any) => a.fileName || a.file_name)
|
||||
.filter(Boolean)
|
||||
.join('、')
|
||||
}
|
||||
return inv?.fileName || ''
|
||||
function removeSelectedInvoice(key: string) {
|
||||
selectedInvoicePicks.value = selectedInvoicePicks.value.filter((p) => p.key !== key)
|
||||
}
|
||||
|
||||
function removeSelectedInvoice(id: string | number) {
|
||||
selectedInvoices.value = selectedInvoices.value.filter((i) => String(i.id) !== String(id))
|
||||
function downloadSelectedInvoice(pick: SelectedInvoicePick) {
|
||||
if (!pick.attachmentId) return
|
||||
downloadBxAttachment({
|
||||
id: pick.attachmentId,
|
||||
fileName: pick.fileName || '发票附件'
|
||||
})
|
||||
}
|
||||
|
||||
async function loadSelectedPicksFromInvoices(invoices: any[]) {
|
||||
const picks: SelectedInvoicePick[] = []
|
||||
await Promise.all(
|
||||
(invoices || []).map(async (inv) => {
|
||||
try {
|
||||
const files = await loadBxAttachments('invoice', inv.id)
|
||||
const file = files[0]
|
||||
if (file) {
|
||||
picks.push({
|
||||
key: `${inv.id}:${file.id}`,
|
||||
invoiceId: inv.id,
|
||||
attachmentId: file.id,
|
||||
amount: inv.amount,
|
||||
fileName: file.fileName || '',
|
||||
fileType: file.fileType || '',
|
||||
previewUrl: file.previewUrl || ''
|
||||
})
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* fallback below */
|
||||
}
|
||||
picks.push({
|
||||
key: String(inv.id),
|
||||
invoiceId: inv.id,
|
||||
attachmentId: inv.id,
|
||||
amount: inv.amount,
|
||||
fileName: '',
|
||||
fileType: '',
|
||||
previewUrl: ''
|
||||
})
|
||||
})
|
||||
)
|
||||
const order = new Map((invoices || []).map((inv: any, idx: number) => [String(inv.id), idx]))
|
||||
picks.sort((a, b) => (order.get(String(a.invoiceId)) ?? 0) - (order.get(String(b.invoiceId)) ?? 0))
|
||||
selectedInvoicePicks.value = picks
|
||||
}
|
||||
|
||||
async function openAddDialog() {
|
||||
addForm.applicantId = currentUserId()
|
||||
addForm.reimburseDate = todayYmd()
|
||||
addForm.title = ''
|
||||
addForm.remark = ''
|
||||
addForm.details = [{ expenseItemId: '', amount: '', remark: '' }]
|
||||
selectedInvoices.value = []
|
||||
selectedInvoicePicks.value = []
|
||||
editingId.value = null
|
||||
titleAutoLinked.value = true
|
||||
dialogs.add = true
|
||||
await Promise.all([refreshGeneratedTitle(), refreshWalletBalance()])
|
||||
await Promise.all([
|
||||
loadApplicantOptions(),
|
||||
loadChangeApplicantPerm(),
|
||||
refreshGeneratedTitle(),
|
||||
refreshWalletBalance()
|
||||
])
|
||||
}
|
||||
|
||||
function isDraftEditable(row?: any) {
|
||||
@@ -832,6 +996,7 @@ async function openEditDialog(row: any) {
|
||||
try {
|
||||
const res: any = await reimburseApi.getById(row.id)
|
||||
const data = res.data || res
|
||||
addForm.applicantId = String(data.applicantId || currentUserId())
|
||||
addForm.title = data.title || ''
|
||||
addForm.reimburseDate = data.reimburseDate || todayYmd()
|
||||
titleAutoLinked.value = isAutoReimburseTitle(addForm.title)
|
||||
@@ -845,9 +1010,14 @@ async function openEditDialog(row: any) {
|
||||
addForm.details = [{ expenseItemId: '', amount: '', remark: '' }]
|
||||
}
|
||||
editingId.value = row.id
|
||||
selectedInvoices.value = Array.isArray(data.invoices) ? data.invoices : []
|
||||
const invoices = Array.isArray(data.invoices) ? data.invoices : []
|
||||
dialogs.add = true
|
||||
await refreshWalletBalance()
|
||||
await Promise.all([
|
||||
loadApplicantOptions(),
|
||||
loadChangeApplicantPerm(),
|
||||
refreshWalletBalance(),
|
||||
loadSelectedPicksFromInvoices(invoices)
|
||||
])
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || '加载失败')
|
||||
}
|
||||
@@ -922,13 +1092,20 @@ async function handleToolbarSubmit() {
|
||||
ElMessage.warning('仅草稿或已驳回的报销单可提交')
|
||||
return
|
||||
}
|
||||
await refreshWalletBalance()
|
||||
const totalNeed = selectedRows.value.reduce((s, r) => s + Number(r.amount || 0), 0)
|
||||
if (Number(walletBalance.value) < totalNeed) {
|
||||
ElMessage.warning(
|
||||
`发票额度不足(余额 ${formatMoneyYuan(walletBalance.value)},本次 ${formatMoneyYuan(totalNeed)})`
|
||||
)
|
||||
return
|
||||
// 按申请人分别校验发票余额(代申请时用申请人额度)
|
||||
const needByApplicant = new Map<string, number>()
|
||||
for (const row of selectedRows.value) {
|
||||
const aid = String(row.applicantId || currentUserId())
|
||||
needByApplicant.set(aid, (needByApplicant.get(aid) || 0) + Number(row.amount || 0))
|
||||
}
|
||||
for (const [aid, need] of needByApplicant) {
|
||||
await refreshWalletBalance(aid)
|
||||
if (Number(walletBalance.value) < need) {
|
||||
ElMessage.warning(
|
||||
`发票额度不足(余额 ${formatMoneyYuan(walletBalance.value)},本次 ${formatMoneyYuan(need)})`
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
loadingMap.submit = true
|
||||
try {
|
||||
@@ -955,8 +1132,11 @@ async function submitAdd() {
|
||||
ElMessage.warning('请为每条报销明细填写报销事由')
|
||||
return
|
||||
}
|
||||
const invoiceIds = selectedInvoices.value.map((i) => String(i.id))
|
||||
const invoiceIds = Array.from(
|
||||
new Set(selectedInvoicePicks.value.map((p) => String(p.invoiceId)))
|
||||
)
|
||||
const payload = {
|
||||
applicantId: addForm.applicantId || undefined,
|
||||
reimburseDate: addForm.reimburseDate,
|
||||
title: addForm.title || undefined,
|
||||
remark: addForm.remark,
|
||||
@@ -977,11 +1157,12 @@ async function submitAdd() {
|
||||
ElMessage.success('新增成功')
|
||||
}
|
||||
dialogs.add = false
|
||||
addForm.applicantId = currentUserId()
|
||||
addForm.reimburseDate = todayYmd()
|
||||
addForm.title = ''
|
||||
addForm.remark = ''
|
||||
addForm.details = [{ expenseItemId: '', amount: '', remark: '' }]
|
||||
selectedInvoices.value = []
|
||||
selectedInvoicePicks.value = []
|
||||
editingId.value = null
|
||||
await refreshList()
|
||||
} catch (e: any) {
|
||||
@@ -1068,7 +1249,7 @@ async function openFlowDialog(row?: any) {
|
||||
}
|
||||
|
||||
async function handleSubmit(row: any) {
|
||||
await refreshWalletBalance()
|
||||
await refreshWalletBalance(String(row.applicantId || currentUserId()))
|
||||
if (Number(walletBalance.value) < Number(row.amount || 0)) {
|
||||
ElMessage.warning(
|
||||
`发票额度不足(余额 ${formatMoneyYuan(walletBalance.value)},本次 ${formatMoneyYuan(row.amount)})`
|
||||
@@ -1154,23 +1335,121 @@ function viewDetailSummary({ columns, data }: { columns: any[]; data: any[] }) {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.invoice-select-hint {
|
||||
font-size: 12px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
}
|
||||
|
||||
.invoice-selected-list {
|
||||
.invoice-selected-thumbs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.invoice-selected-tag {
|
||||
max-width: 100%;
|
||||
.invoice-selected-card {
|
||||
position: relative;
|
||||
width: 96px;
|
||||
border: 1px solid var(--border, #d9e8e2);
|
||||
border-radius: 6px;
|
||||
background: var(--surface, #fff);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.invoice-selected-empty {
|
||||
font-size: 13px;
|
||||
.invoice-selected-card__remove {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: rgba(15, 23, 42, 0.55);
|
||||
color: #fff;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--el-color-danger);
|
||||
}
|
||||
}
|
||||
|
||||
.invoice-selected-card__preview {
|
||||
width: 100%;
|
||||
height: 64px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--table-head, #f8fafc);
|
||||
overflow: hidden;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.invoice-selected-card__icon {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&--video {
|
||||
background: #ede9fe;
|
||||
color: #7c3aed;
|
||||
}
|
||||
|
||||
&--doc {
|
||||
background: #e0f2fe;
|
||||
color: #0284c7;
|
||||
}
|
||||
}
|
||||
|
||||
.invoice-selected-card__meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
|
||||
.invoice-selected-card__name {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 1;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
font-size: 10px;
|
||||
line-height: 1.3;
|
||||
color: var(--text, #1e293b);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.invoice-selected-card__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.invoice-selected-card__amount {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--primary-dark, #059669);
|
||||
}
|
||||
|
||||
.invoice-selected-card__download {
|
||||
flex-shrink: 0;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 4px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--primary, #10b981);
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user