import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http' import { listSuppliers, type SupplierCategory } from '@/modules/suppliers' export type ContainerFeeDirection = 'RECEIVABLE' | 'PAYABLE' export type ContainerFeeReviewStatus = 'PENDING' | 'APPROVED' | 'REJECTED' export type ContainerFeeSettlementMode = 'ON_ACCOUNT' | 'DIRECT_PAID' export type ContainerFeePaymentMethod = 'ONLINE' | 'BANK_TRANSFER' | 'CASH' | 'OTHER' export interface ContainerFeeResource { id: string loadingPlanId: string customerId?: string allocationGroupId?: string | null allocationOrderId?: string | null allocationOrderNo?: string | null allocationInboundId?: string | null allocationInboundCode?: string | null allocationGroupAmount?: number | null containerBookingId: string | null containerNo: string | null feeItemId: string feeItemName: string direction: ContainerFeeDirection supplierId: string | null supplierName: string | null supplierCategory: SupplierCategory | null settlementMode?: ContainerFeeSettlementMode | null paidAt?: string | null paymentMethod?: ContainerFeePaymentMethod | null paymentReferenceNo?: string | null paymentVoucherFileIds?: string[] | null businessDate: string amount: number currency: 'CNY' reviewStatus: ContainerFeeReviewStatus sourceStatus: 'ACTIVE' | 'VOIDED' sourceVersion: number remark: string | null reviewerName: string | null reviewedAt: string | null reviewReason: string | null } export interface ContainerFeeSaveRequest { feeItemId: string direction: ContainerFeeDirection supplierId: string | null settlementMode: ContainerFeeSettlementMode | null paidAt: string | null paymentMethod: ContainerFeePaymentMethod | null paymentReferenceNo: string | null paymentVoucherFileIds: string[] | null businessDate: string amount: number currency: 'CNY' remark: string | null } export interface ContainerFeeAdjustRequest { expectedSourceVersion: number businessDate: string amount: number } export interface ContainerFeeAllocation { customerId: string orderId: string orderNo: string inboundId: string | null inboundCode: string | null amount: number } export interface ContainerFeeAllocationGroupRequest { fee: ContainerFeeSaveRequest allocations: ContainerFeeAllocation[] } export interface ContainerFeeAllocationGroupAdjustRequest { expectedSourceVersion: number businessDate: string totalAmount: number allocations: Array<{ feeId: string; amount: number }> } export interface ApplicableFeeItem { id: string name: string feeCode: string supplierCategory: SupplierCategory | null warehouseReceivable: boolean warehousePayable: boolean pickupReceivable: boolean pickupPayable: boolean } export interface ContainerFeeSupplierOption { id: string supplierName: string category: SupplierCategory } export interface ContainerCostAllocation { id: string orderId: string inboundId: string | null volumeCbm: number totalVolumeCbm: number allocationRate: number allocatedAmount: number roundingAdjustment: boolean } export interface ContainerCostDetail { id: string costNo: string costType: string costOrigin: string sourceFeeId: string | null sourceFeeVersion: number containerBookingId: string | null supplierName: string | null feeItemName: string amount: number currency: string status: string allocations: ContainerCostAllocation[] } export interface ContainerSettlementDetails { customerId: string containerBookingId: string settledSourceFeeIds: string[] costs: ContainerCostDetail[] } const id = (value: unknown) => value == null ? '' : String(value) const numberValue = (value: unknown) => Number.isFinite(Number(value)) ? Number(value) : 0 const supplierCategories: SupplierCategory[] = ['BOOKING', 'CUSTOMS', 'TRUCKING', 'CERTIFICATE'] function supplierCategory(value: unknown): SupplierCategory | null { if (value == null || value === '') return null if (supplierCategories.includes(value as SupplierCategory)) return value as SupplierCategory throw new TypeError(`Unsupported supplierCategory: ${String(value)}`) } const base = (planId: string) => `/platform/v1/loading-plans/${encodeURIComponent(planId)}/fee-details` const params = (accountId: string) => ({ accountId }) function normalizeFee(raw: Record): ContainerFeeResource { return { id: id(raw.id), loadingPlanId: id(raw.loadingPlanId), customerId: id(raw.tenantId), allocationGroupId: raw.allocationGroupId == null ? null : id(raw.allocationGroupId), allocationOrderId: raw.allocationOrderId == null ? null : id(raw.allocationOrderId), allocationOrderNo: raw.allocationOrderNo == null ? null : String(raw.allocationOrderNo), allocationInboundId: raw.allocationInboundId == null ? null : id(raw.allocationInboundId), allocationInboundCode: raw.allocationInboundCode == null ? null : String(raw.allocationInboundCode), allocationGroupAmount: raw.allocationGroupAmount == null ? null : numberValue(raw.allocationGroupAmount), containerBookingId: raw.containerBookingId == null ? null : id(raw.containerBookingId), containerNo: raw.containerNo == null ? null : String(raw.containerNo), feeItemId: id(raw.feeItemId), feeItemName: String(raw.feeItemNameSnapshot || ''), direction: raw.direction as ContainerFeeDirection, supplierId: raw.supplierId == null ? null : id(raw.supplierId), supplierName: raw.supplierName == null ? null : String(raw.supplierName), supplierCategory: supplierCategory(raw.supplierCategory), settlementMode: raw.settlementMode == null ? null : raw.settlementMode as ContainerFeeSettlementMode, paidAt: raw.paidAt == null ? null : String(raw.paidAt), paymentMethod: raw.paymentMethod == null ? null : raw.paymentMethod as ContainerFeePaymentMethod, paymentReferenceNo: raw.paymentReferenceNo == null ? null : String(raw.paymentReferenceNo), paymentVoucherFileIds: Array.isArray(raw.paymentVoucherFileIds) ? raw.paymentVoucherFileIds.map(id) : null, businessDate: String(raw.businessDate || ''), amount: numberValue(raw.amount), currency: 'CNY', reviewStatus: raw.reviewStatus as ContainerFeeReviewStatus, sourceStatus: raw.sourceStatus as ContainerFeeResource['sourceStatus'], sourceVersion: numberValue(raw.sourceVersion), remark: raw.remark == null ? null : String(raw.remark), reviewerName: raw.reviewerName == null ? null : String(raw.reviewerName), reviewedAt: raw.reviewedAt == null ? null : String(raw.reviewedAt), reviewReason: raw.reviewReason == null ? null : String(raw.reviewReason), } } export async function listContainerFees(planId: string, accountId: string) { const response = await http.get[]>, ApiEnvelope[]>>(base(planId), { params: params(accountId) }) return unwrapApiResponse(response).map(normalizeFee) } export async function createContainerFee(planId: string, accountId: string, payload: ContainerFeeSaveRequest) { const response = await http.post>, ApiEnvelope>>(base(planId), payload, { params: params(accountId) }) return normalizeFee(unwrapApiResponse(response)) } export async function createContainerFeeAllocationGroup(planId: string, payload: ContainerFeeAllocationGroupRequest) { const response = await http.post[]>, ApiEnvelope[]>>(`${base(planId)}/allocation-groups`, payload) return unwrapApiResponse(response).map(normalizeFee) } export async function approveContainerFeeAllocationGroup(planId: string, groupId: string) { const response = await http.post[]>, ApiEnvelope[]>>(`${base(planId)}/allocation-groups/${encodeURIComponent(groupId)}/approve`) return unwrapApiResponse(response).map(normalizeFee) } export async function rejectContainerFeeAllocationGroup(planId: string, groupId: string, reason: string) { const response = await http.post[]>, ApiEnvelope[]>>(`${base(planId)}/allocation-groups/${encodeURIComponent(groupId)}/reject`, { reason }) return unwrapApiResponse(response).map(normalizeFee) } export async function adjustContainerFeeAllocationGroup(planId: string, groupId: string, payload: ContainerFeeAllocationGroupAdjustRequest) { const response = await http.post[]>, ApiEnvelope[]>>(`${base(planId)}/allocation-groups/${encodeURIComponent(groupId)}/adjust`, payload) return unwrapApiResponse(response).map(normalizeFee) } export async function voidContainerFeeAllocationGroup(planId: string, groupId: string, expectedSourceVersion: number) { await http.post(`${base(planId)}/allocation-groups/${encodeURIComponent(groupId)}/void`, { expectedSourceVersion }) } export async function approveContainerFee(planId: string, accountId: string, feeId: string) { await http.post(`${base(planId)}/${encodeURIComponent(feeId)}/approve`, undefined, { params: params(accountId) }) } export async function rejectContainerFee(planId: string, accountId: string, feeId: string, reason: string) { await http.post(`${base(planId)}/${encodeURIComponent(feeId)}/reject`, { reason }, { params: params(accountId) }) } export async function adjustContainerFee(planId: string, accountId: string, feeId: string, payload: ContainerFeeAdjustRequest) { const response = await http.post>, ApiEnvelope>>(`${base(planId)}/${encodeURIComponent(feeId)}/adjust`, payload, { params: params(accountId) }) return normalizeFee(unwrapApiResponse(response)) } export async function voidContainerFee(planId: string, accountId: string, feeId: string, expectedSourceVersion: number) { await http.post(`${base(planId)}/${encodeURIComponent(feeId)}/void`, { expectedSourceVersion }, { params: params(accountId) }) } export async function listApplicableFeeItems() { const response = await http.get[] }>, ApiEnvelope<{ records: Record[] }>>('/platform/v1/fee-items', { params: { status: 'ACTIVE', page: 1, size: 200 } }) return (unwrapApiResponse(response).records || []).map((raw) => ({ id: id(raw.id), name: String(raw.feeTypeName || ''), feeCode: String(raw.feeCode || ''), supplierCategory: supplierCategory(raw.supplierCategory), warehouseReceivable: Boolean(raw.warehouseReceivable), warehousePayable: Boolean(raw.warehousePayable), pickupReceivable: Boolean(raw.pickupReceivable), pickupPayable: Boolean(raw.pickupPayable) })) } export async function listContainerFeeSupplierOptions(category: SupplierCategory | null): Promise { const page = await listSuppliers({ status: 'ACTIVE', category: category ?? undefined, page: 1, size: 200 }) return page.records.filter((supplier) => supplier.status === 'ACTIVE' && (!category || supplier.category === category)).map((supplier) => ({ id: supplier.id, supplierName: supplier.name, category: supplier.category })) } export async function uploadContainerFeePaymentVoucher(customerId: string, file: File): Promise<{ fileId: string; fileName: string }> { const body = new FormData(); body.append('file', file) const raw = unwrapApiResponse(await http.post>, ApiEnvelope>>('/platform/finance/v1/vouchers', body, { params: { customerId }, headers: { 'Content-Type': 'multipart/form-data' }, })) const fileId = raw.fileId == null ? '' : id(raw.fileId) const echoedCustomerId = raw.tenantId == null ? id(raw.customerId ?? customerId) : id(raw.tenantId) if (!fileId || echoedCustomerId !== customerId) throw new Error('付款凭证与当前客户不匹配') return { fileId, fileName: String(raw.fileName || raw.file_name || file.name) } } export async function getContainerSettlementDetails(customerId: string, containerBookingId: string): Promise { const response = await http.get>, ApiEnvelope>>('/platform/finance/v1/container-settlement-details', { params: { customerId, containerBookingId } }) const raw = unwrapApiResponse(response) if (id(raw.customerId) !== customerId || id(raw.containerBookingId) !== containerBookingId) throw new Error('Finance 聚合结果与柜次或客户上下文不一致') const costs = (Array.isArray(raw.costs) ? raw.costs : []).map((value) => { const cost = value as Record if (id(cost.containerBookingId) !== containerBookingId) throw new Error('Finance 聚合成本与柜次上下文不一致') return { id: id(cost.costId), costNo: String(cost.costNo || ''), costType: String(cost.costType || ''), costOrigin: String(cost.costOrigin || ''), sourceFeeId: cost.sourceFeeId == null ? null : id(cost.sourceFeeId), sourceFeeVersion: numberValue(cost.sourceFeeVersion), containerBookingId: cost.containerBookingId == null ? null : id(cost.containerBookingId), supplierName: cost.supplierName == null ? null : String(cost.supplierName), feeItemName: String(cost.feeItemName || ''), amount: numberValue(cost.amount), currency: String(cost.currency || ''), status: String(cost.status || ''), allocations: (Array.isArray(cost.allocations) ? cost.allocations : []).map((value) => { const allocation = value as Record return { id: id(allocation.allocationId), orderId: id(allocation.orderId), inboundId: allocation.inboundId == null ? null : id(allocation.inboundId), volumeCbm: numberValue(allocation.volumeCbm), totalVolumeCbm: numberValue(allocation.totalVolumeCbm), allocationRate: numberValue(allocation.allocationRate), allocatedAmount: numberValue(allocation.allocatedAmount), roundingAdjustment: Boolean(allocation.roundingAdjustment) } }), } }) return { customerId, containerBookingId, settledSourceFeeIds: (Array.isArray(raw.settledSourceFeeIds) ? raw.settledSourceFeeIds : []).map(id), costs } }