feat(external-sales): add complete external sales workbench
This commit is contained in:
parent
f3ed26b9ed
commit
16d062da4e
@ -0,0 +1,21 @@
|
||||
CREATE TABLE "SupplyChainExternalFreightRecord" (
|
||||
"id" TEXT NOT NULL,
|
||||
"orderNo" TEXT NOT NULL,
|
||||
"outboundQty" INTEGER NOT NULL,
|
||||
"incomeAfterTaxRefund" DECIMAL(18, 4),
|
||||
"estimatedFreight" DECIMAL(18, 4) NOT NULL,
|
||||
"remark" TEXT NOT NULL DEFAULT '',
|
||||
"sourceFileName" TEXT NOT NULL DEFAULT '',
|
||||
"importedById" TEXT NOT NULL DEFAULT '',
|
||||
"importedByName" TEXT NOT NULL DEFAULT '',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "SupplyChainExternalFreightRecord_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "SupplyChainExternalFreightRecord_orderNo_key"
|
||||
ON "SupplyChainExternalFreightRecord"("orderNo");
|
||||
|
||||
CREATE INDEX "SCExternalFreight_createdAt_idx"
|
||||
ON "SupplyChainExternalFreightRecord"("createdAt");
|
||||
@ -0,0 +1,5 @@
|
||||
ALTER TABLE "SupplyChainExternalFreightRecord"
|
||||
ADD COLUMN IF NOT EXISTS "statMonth" VARCHAR(7) NOT NULL DEFAULT '';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS "SCExternalFreight_statMonth_idx"
|
||||
ON "SupplyChainExternalFreightRecord"("statMonth");
|
||||
@ -0,0 +1,5 @@
|
||||
ALTER TABLE "SupplyChainExternalFreightRecord"
|
||||
RENAME COLUMN "statMonth" TO "shipMonth";
|
||||
|
||||
ALTER INDEX "SCExternalFreight_statMonth_idx"
|
||||
RENAME TO "SCExternalFreight_shipMonth_idx";
|
||||
@ -6415,6 +6415,25 @@ model SupplyChainExternalOrderCost {
|
||||
@@index([shopStyleCode], map: "SCExternalOrderCost_shopStyleCode_idx")
|
||||
}
|
||||
|
||||
/// 外贸货代费人工导入记录。订单号唯一,重复导入时覆盖更新。
|
||||
model SupplyChainExternalFreightRecord {
|
||||
id String @id @default(cuid())
|
||||
shipMonth String @default("") @db.VarChar(7)
|
||||
orderNo String @unique
|
||||
outboundQty Int
|
||||
incomeAfterTaxRefund Decimal? @db.Decimal(18, 4)
|
||||
estimatedFreight Decimal @db.Decimal(18, 4)
|
||||
remark String @default("") @db.Text
|
||||
sourceFileName String @default("")
|
||||
importedById String @default("")
|
||||
importedByName String @default("")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([shipMonth], map: "SCExternalFreight_shipMonth_idx")
|
||||
@@index([createdAt], map: "SCExternalFreight_createdAt_idx")
|
||||
}
|
||||
|
||||
/// 清货任务流转记录(提交 / 通过 / 驳回 / 调整 / 运营确认移除)
|
||||
model SupplyChainClearanceTaskEvent {
|
||||
id String @id @default(cuid())
|
||||
|
||||
@ -0,0 +1,18 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { externalClearancePriceService } from '@/server/services/external-clearance-price.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'managementBlankPage7',
|
||||
)
|
||||
if (!access.view) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有清货价查看权限', 403, ctx.requestId)
|
||||
}
|
||||
return jsonSuccess({ rows: await externalClearancePriceService.list() }, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainExternalFreightService } from '@/server/services/supply-chain-external-freight.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'managementBlankPage7',
|
||||
)
|
||||
if (!access.edit) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有外贸货代费导入权限', 403, ctx.requestId)
|
||||
}
|
||||
const form = await request.formData()
|
||||
const file = form.get('file')
|
||||
if (!(file instanceof File)) {
|
||||
return jsonError(ErrorCode.VALIDATION_REQUIRED_FIELD, '请选择 Excel 文件', 400, ctx.requestId)
|
||||
}
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return jsonError(ErrorCode.VALIDATION_OUT_OF_RANGE, 'Excel 文件不能超过 10MB', 400, ctx.requestId)
|
||||
}
|
||||
const result = await supplyChainExternalFreightService.importFile({
|
||||
fileName: file.name,
|
||||
buffer: Buffer.from(await file.arrayBuffer()),
|
||||
user: ctx.user,
|
||||
})
|
||||
return jsonSuccess(result, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { supplyChainExternalFreightService } from '@/server/services/supply-chain-external-freight.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'managementBlankPage7',
|
||||
)
|
||||
if (!access.view) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有外贸货代费查看权限', 403, ctx.requestId)
|
||||
}
|
||||
return jsonSuccess({ rows: await supplyChainExternalFreightService.list() }, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError } from '@/server/core/response'
|
||||
import { supplyChainExternalFreightService } from '@/server/services/supply-chain-external-freight.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'managementBlankPage7',
|
||||
)
|
||||
if (!access.view) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有外贸货代费查看权限', 403, ctx.requestId)
|
||||
}
|
||||
const buffer = await supplyChainExternalFreightService.createTemplate()
|
||||
return new NextResponse(buffer as unknown as BodyInit, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent('外贸货代费导入模板.xlsx')}`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { externalProfitService } from '@/server/services/external-profit.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
const querySchema = z.object({
|
||||
basis: z.enum(['cost', 'clearance']).default('cost'),
|
||||
})
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
ctx.user,
|
||||
'managementBlankPage7',
|
||||
)
|
||||
if (!access.view) {
|
||||
return jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有毛利查看权限', 403, ctx.requestId)
|
||||
}
|
||||
const parsed = querySchema.safeParse({
|
||||
basis: request.nextUrl.searchParams.get('basis') ?? undefined,
|
||||
})
|
||||
if (!parsed.success) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '毛利维度不正确', 400, ctx.requestId)
|
||||
}
|
||||
return jsonSuccess(
|
||||
await externalProfitService.getData(parsed.data.basis),
|
||||
200,
|
||||
ctx.requestId,
|
||||
)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
EXTERNAL_SALES_TARGET_SHOPS,
|
||||
externalSalesDateSpan,
|
||||
externalSalesMonthRange,
|
||||
isExternalSalesDate,
|
||||
parseExternalSalesDetailFilters,
|
||||
} from '@/lib/external-sales'
|
||||
import { ErrorCode } from '@/server/core/errors'
|
||||
import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response'
|
||||
import { externalSalesService } from '@/server/services/external-sales.service'
|
||||
import { supplyChainPermissionSettingsService } from '@/server/services/supply-chain-permission-settings.service'
|
||||
|
||||
const querySchema = z.object({
|
||||
view: z.enum(['summary', 'detail', 'afterSale']).default('summary'),
|
||||
dateFrom: z.string().trim().optional(),
|
||||
dateTo: z.string().trim().optional(),
|
||||
month: z.string().trim().optional(),
|
||||
shopName: z.enum(EXTERNAL_SALES_TARGET_SHOPS).or(z.literal('')).optional(),
|
||||
keyword: z.string().trim().max(200).optional(),
|
||||
orderNo: z.string().trim().max(120).optional(),
|
||||
itemCode: z.string().trim().max(120).optional(),
|
||||
filters: z.string().trim().max(5_000).optional(),
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
pageSize: z.coerce.number().int().min(1).max(200).default(50),
|
||||
})
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
return handleRequest(request, async (ctx) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(ctx.user, 'managementBlankPage7')
|
||||
if (!access.view) {
|
||||
return jsonError(
|
||||
ErrorCode.AUTH_PERMISSION_DENIED,
|
||||
'当前账号没有外销销量查看权限',
|
||||
403,
|
||||
ctx.requestId,
|
||||
)
|
||||
}
|
||||
const parsed = querySchema.safeParse(Object.fromEntries(request.nextUrl.searchParams.entries()))
|
||||
if (!parsed.success) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '外销销量查询参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
const monthRange = parsed.data.view === 'summary' && parsed.data.month
|
||||
? externalSalesMonthRange(parsed.data.month)
|
||||
: null
|
||||
const dateFrom = monthRange?.dateFrom ?? parsed.data.dateFrom
|
||||
const dateTo = monthRange?.dateTo ?? parsed.data.dateTo
|
||||
if ((dateFrom && !isExternalSalesDate(dateFrom)) || (dateTo && !isExternalSalesDate(dateTo))) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '统计时间范围不正确', 400, ctx.requestId)
|
||||
}
|
||||
if (dateFrom && dateTo && !externalSalesDateSpan(dateFrom, dateTo)) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '统计时间范围不正确', 400, ctx.requestId)
|
||||
}
|
||||
if (parsed.data.month && !monthRange) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '统计月份不正确', 400, ctx.requestId)
|
||||
}
|
||||
const detailFilters = parsed.data.filters
|
||||
? parseExternalSalesDetailFilters(parsed.data.filters)
|
||||
: {}
|
||||
if (!detailFilters) {
|
||||
return jsonError(ErrorCode.VALIDATION_INVALID_FORMAT, '明细筛选参数不正确', 400, ctx.requestId)
|
||||
}
|
||||
const data = await externalSalesService.getPage({
|
||||
view: parsed.data.view,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
shopName: parsed.data.shopName,
|
||||
keyword: parsed.data.keyword,
|
||||
orderNo: parsed.data.orderNo,
|
||||
itemCode: parsed.data.itemCode,
|
||||
detailFilters,
|
||||
page: parsed.data.page,
|
||||
pageSize: parsed.data.pageSize,
|
||||
})
|
||||
return jsonSuccess(data, 200, ctx.requestId)
|
||||
}, { requireAuth: true })
|
||||
}
|
||||
@ -157,6 +157,11 @@ describe('supply chain menu', () => {
|
||||
module: '经营管理',
|
||||
route: '/supply-chain/management/blank-pages/blank-page-6',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
label: '外销销量',
|
||||
module: '经营管理',
|
||||
route: '/supply-chain/management/blank-pages/blank-page-7',
|
||||
}),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
@ -11,6 +11,7 @@ const BLANK_PAGE_TARGET_KEYS: Record<string, SupplyChainPermissionTargetKey> = {
|
||||
'blank-page-2': 'managementBlankPage2',
|
||||
'blank-page-3': 'productSabc',
|
||||
'blank-page-6': 'productSelection',
|
||||
'blank-page-7': 'managementBlankPage7',
|
||||
}
|
||||
|
||||
export type SupplyChainMenuItem = {
|
||||
|
||||
@ -25,7 +25,7 @@ export default async function SupplyChainRootLayout({ children }: { children: Re
|
||||
authUser,
|
||||
await supplyChainPermissionSettingsService.getVisibleTargetKeys(authUser),
|
||||
)
|
||||
const labelTargets: SupplyChainPermissionTargetKey[] = ['ownerConfig', 'limitManagement', 'managementBlankPage1', 'managementBlankPage2', 'productSabc']
|
||||
const labelTargets: SupplyChainPermissionTargetKey[] = ['ownerConfig', 'limitManagement', 'managementBlankPage1', 'managementBlankPage2', 'managementBlankPage7', 'productSabc']
|
||||
const editableTabRoutes = process.env.NODE_ENV === 'production' ? [] : (await Promise.all(
|
||||
labelTargets.map(async (target) => {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, target)
|
||||
|
||||
@ -0,0 +1,112 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { RefreshCw } from 'lucide-react'
|
||||
import type { ExternalClearancePriceRow } from '@/lib/external-clearance-price'
|
||||
import styles from './external-sales.module.css'
|
||||
|
||||
async function responseJson(response: Response) {
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
success?: boolean
|
||||
data?: { rows?: ExternalClearancePriceRow[] }
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error(payload?.error?.message || '清货价加载失败')
|
||||
}
|
||||
return payload.data?.rows ?? []
|
||||
}
|
||||
|
||||
function amount(value: number) {
|
||||
return `¥${value.toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 4,
|
||||
})}`
|
||||
}
|
||||
|
||||
export function ExternalClearancePricePanel({
|
||||
onRowsChange,
|
||||
}: {
|
||||
onRowsChange: (rows: ExternalClearancePriceRow[]) => void
|
||||
}) {
|
||||
const [rows, setRows] = useState<ExternalClearancePriceRow[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetch('/api/supply-chain/management/external-sales/clearance', {
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(responseJson)
|
||||
.then((nextRows) => {
|
||||
setRows(nextRows)
|
||||
onRowsChange(nextRows)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (cause instanceof DOMException && cause.name === 'AbortError') return
|
||||
setError(cause instanceof Error ? cause.message : '清货价加载失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [onRowsChange, reloadKey])
|
||||
|
||||
return (
|
||||
<section id="external-sales-panel-clearance" role="tabpanel" className={styles.content}>
|
||||
<div className={styles.freightToolbar}>
|
||||
<span>共 {rows.length.toLocaleString('zh-CN')} 个订单商品</span>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.secondaryButton}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setReloadKey((value) => value + 1)
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={14} />刷新
|
||||
</button>
|
||||
</div>
|
||||
{error ? <div className={styles.error}>{error}</div> : null}
|
||||
<div className={styles.tableWrap}>
|
||||
<table className={`${styles.table} ${styles.clearancePriceTable}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>订单号</th>
|
||||
<th>商品编码</th>
|
||||
<th className={styles.number}>成本价</th>
|
||||
<th className={styles.number}>清货价</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={`${row.orderNo}|${row.itemCode}`}>
|
||||
<td className={styles.code}>{row.orderNo}</td>
|
||||
<td className={styles.code}>{row.itemCode}</td>
|
||||
<td className={styles.number}>{amount(row.costPrice)}</td>
|
||||
<td className={`${styles.number} ${styles.clearancePriceCell}`}>
|
||||
{amount(row.clearancePrice)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!loading && rows.length === 0 ? (
|
||||
<tr>
|
||||
<td className={styles.empty} colSpan={4}>
|
||||
暂无清货价数据,请先在“清货 → 外采订单成本”中导入
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{loading ? (
|
||||
<tr><td className={styles.empty} colSpan={4}>正在读取清货价数据…</td></tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,303 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Download, RefreshCw, Upload } from 'lucide-react'
|
||||
import type { ExternalFreightRecordView } from '@/lib/external-freight'
|
||||
import modalStyles from '../clearance/clearance-price-push.module.css'
|
||||
import styles from './external-sales.module.css'
|
||||
|
||||
async function responseJson(response: Response) {
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
success?: boolean
|
||||
data?: unknown
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error(payload?.error?.message || '请求失败')
|
||||
}
|
||||
return payload.data
|
||||
}
|
||||
|
||||
async function downloadResponse(response: Response, fallbackName: string) {
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
throw new Error(payload?.error?.message || '下载失败')
|
||||
}
|
||||
const blob = await response.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
const disposition = response.headers.get('Content-Disposition') ?? ''
|
||||
const encodedName = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
anchor.download = encodedName ? decodeURIComponent(encodedName) : fallbackName
|
||||
document.body.appendChild(anchor)
|
||||
anchor.click()
|
||||
anchor.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
function numberText(value: number) {
|
||||
return value.toLocaleString('zh-CN', { maximumFractionDigits: 0 })
|
||||
}
|
||||
|
||||
function amountText(value: number | null) {
|
||||
return value == null
|
||||
? '-'
|
||||
: `¥${value.toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}`
|
||||
}
|
||||
|
||||
function shipMonthText(value: string) {
|
||||
const match = /^(\d{4})-(\d{2})$/.exec(value)
|
||||
return match ? `${match[1]}年${Number(match[2])}月` : value || '-'
|
||||
}
|
||||
|
||||
export function ExternalFreightPanel({
|
||||
onRowsChange,
|
||||
}: {
|
||||
onRowsChange: (rows: ExternalFreightRecordView[]) => void
|
||||
}) {
|
||||
const [rows, setRows] = useState<ExternalFreightRecordView[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [importDialogOpen, setImportDialogOpen] = useState(false)
|
||||
const [pendingFile, setPendingFile] = useState<File | null>(null)
|
||||
const [dialogError, setDialogError] = useState('')
|
||||
const [downloadingTemplate, setDownloadingTemplate] = useState(false)
|
||||
const [message, setMessage] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetch('/api/supply-chain/management/external-sales/freight', {
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(responseJson)
|
||||
.then((payload) => {
|
||||
const nextRows = (payload as { rows?: ExternalFreightRecordView[] } | null)?.rows ?? []
|
||||
setRows(nextRows)
|
||||
onRowsChange(nextRows)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (cause instanceof DOMException && cause.name === 'AbortError') return
|
||||
setError(cause instanceof Error ? cause.message : '货代费加载失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [onRowsChange, reloadKey])
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
if (downloadingTemplate) return
|
||||
setDownloadingTemplate(true)
|
||||
setDialogError('')
|
||||
setError('')
|
||||
try {
|
||||
await downloadResponse(
|
||||
await fetch('/api/supply-chain/management/external-sales/freight/template', {
|
||||
cache: 'no-store',
|
||||
}),
|
||||
'外贸货代费导入模板.xlsx',
|
||||
)
|
||||
} catch (cause) {
|
||||
const message = cause instanceof Error ? cause.message : '模板下载失败'
|
||||
setDialogError(message)
|
||||
setError(message)
|
||||
} finally {
|
||||
setDownloadingTemplate(false)
|
||||
}
|
||||
}
|
||||
|
||||
const importFile = async (file: File) => {
|
||||
if (importing) return
|
||||
setImporting(true)
|
||||
setError('')
|
||||
setDialogError('')
|
||||
setMessage('')
|
||||
try {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
const payload = await responseJson(await fetch(
|
||||
'/api/supply-chain/management/external-sales/freight/import',
|
||||
{ method: 'POST', body: form },
|
||||
)) as { importedCount?: number }
|
||||
setMessage(`已导入 ${numberText(payload?.importedCount ?? 0)} 个订单的货代费`)
|
||||
setImportDialogOpen(false)
|
||||
setPendingFile(null)
|
||||
setLoading(true)
|
||||
setReloadKey((value) => value + 1)
|
||||
} catch (cause) {
|
||||
setDialogError(cause instanceof Error ? cause.message : '导入失败')
|
||||
} finally {
|
||||
setImporting(false)
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section id="external-sales-panel-freight" role="tabpanel" className={styles.content}>
|
||||
<div className={styles.freightToolbar}>
|
||||
<span>共 {numberText(rows.length)} 个订单</span>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.secondaryButton}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setReloadKey((value) => value + 1)
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={14} />刷新
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.primaryButton}
|
||||
disabled={importing}
|
||||
onClick={() => {
|
||||
setDialogError('')
|
||||
setPendingFile(null)
|
||||
setImportDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Upload size={14} />{importing ? '导入中…' : '人工导入'}
|
||||
</button>
|
||||
</div>
|
||||
{importDialogOpen ? (
|
||||
<div className={modalStyles.importOverlay} role="presentation">
|
||||
<div
|
||||
className={`${modalStyles.importDialog} ${styles.freightImportDialog}`}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="external-freight-import-title"
|
||||
>
|
||||
<header className={modalStyles.importHeader}>
|
||||
<h3 id="external-freight-import-title">导入人工货代费</h3>
|
||||
<button
|
||||
className={modalStyles.importClose}
|
||||
type="button"
|
||||
disabled={importing}
|
||||
aria-label="关闭货代费导入"
|
||||
onClick={() => {
|
||||
setImportDialogOpen(false)
|
||||
setPendingFile(null)
|
||||
setDialogError('')
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className={modalStyles.importRuleBar}>
|
||||
<div className={modalStyles.importRuleText}>
|
||||
<strong>导入说明</strong>
|
||||
<p>请先下载模板,按同款六列填写:发货月份、订单号、出库数量(以实际为准)、收入-减退税(CNY)、预估货运费(货代+海运)、备注。</p>
|
||||
<p>发货月份按月填写,例如 2026年11月;模板第二行为示例,请替换或删除后导入。</p>
|
||||
<p>订单号、出库数量和预估货运费为必填项,收入-减退税和备注为选填项。</p>
|
||||
<p>重复导入同一订单号时,以最后一次导入内容覆盖更新。</p>
|
||||
<p>工作表名称不限,首行表头与模板一致即可;单个文件最多 5000 行、不超过 10MB。</p>
|
||||
</div>
|
||||
<button
|
||||
className={styles.primaryButton}
|
||||
type="button"
|
||||
disabled={downloadingTemplate}
|
||||
onClick={() => void downloadTemplate()}
|
||||
>
|
||||
<Download size={14} />
|
||||
{downloadingTemplate ? '模板下载中…' : '导入模板下载'}
|
||||
</button>
|
||||
</div>
|
||||
{dialogError ? <div className={modalStyles.error} role="alert">{dialogError}</div> : null}
|
||||
<div className={modalStyles.importFileBar}>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".xlsx"
|
||||
hidden
|
||||
aria-label="选择货代费 Excel"
|
||||
onChange={(event) => {
|
||||
setDialogError('')
|
||||
setPendingFile(event.target.files?.[0] ?? null)
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className={styles.secondaryButton}
|
||||
type="button"
|
||||
disabled={importing}
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
浏览...
|
||||
</button>
|
||||
<span className={modalStyles.importFileName}>
|
||||
{pendingFile?.name || '请选择需要上传并导入的 Excel 文件'}
|
||||
</span>
|
||||
<button
|
||||
className={styles.primaryButton}
|
||||
type="button"
|
||||
disabled={!pendingFile || importing}
|
||||
onClick={() => {
|
||||
if (pendingFile) void importFile(pendingFile)
|
||||
}}
|
||||
>
|
||||
{importing ? '导入中…' : '开始导入'}
|
||||
</button>
|
||||
</div>
|
||||
<div className={`${modalStyles.importPreview} ${modalStyles.importPreviewWide}`}>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
{['发货月份', '订单号', '出库数量(以实际为准)', '收入-减退税(CNY)', '预估货运费(货代+海运)', '备注'].map((header) => (
|
||||
<th key={header}>{header}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{message ? <div className={styles.success}>{message}</div> : null}
|
||||
{error ? <div className={styles.error}>{error}</div> : null}
|
||||
<div className={styles.tableWrap}>
|
||||
<table className={`${styles.table} ${styles.freightTable}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>发货月份</th>
|
||||
<th>订单号</th>
|
||||
<th className={styles.number}>出库数量(以实际为准)</th>
|
||||
<th className={styles.number}>收入-减退税(CNY)</th>
|
||||
<th className={styles.number}>预估货运费(货代+海运)</th>
|
||||
<th>备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td className={styles.nowrap}>{shipMonthText(row.shipMonth)}</td>
|
||||
<td className={styles.code}>{row.orderNo}</td>
|
||||
<td className={styles.number}>{numberText(row.outboundQty)}</td>
|
||||
<td className={styles.number}>{amountText(row.incomeAfterTaxRefund)}</td>
|
||||
<td className={styles.number}>{amountText(row.estimatedFreight)}</td>
|
||||
<td>{row.remark || '-'}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!loading && rows.length === 0 ? (
|
||||
<tr><td className={styles.empty} colSpan={6}>暂无货代费数据,请下载模板后人工导入</td></tr>
|
||||
) : null}
|
||||
{loading ? (
|
||||
<tr><td className={styles.empty} colSpan={6}>正在读取货代费数据…</td></tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,190 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { RefreshCw } from 'lucide-react'
|
||||
import type { ExternalProfitBasis, ExternalProfitRow } from '@/lib/external-profit'
|
||||
import styles from './external-sales.module.css'
|
||||
|
||||
async function responseJson(response: Response) {
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
success?: boolean
|
||||
data?: { rows?: ExternalProfitRow[] }
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
if (!response.ok || !payload?.success) {
|
||||
throw new Error(payload?.error?.message || '毛利数据加载失败')
|
||||
}
|
||||
return payload.data?.rows ?? []
|
||||
}
|
||||
|
||||
function amount(value: number) {
|
||||
return `¥${value.toLocaleString('zh-CN', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}`
|
||||
}
|
||||
|
||||
function monthText(value: string) {
|
||||
return /^\d{4}-\d{2}$/.test(value)
|
||||
? `${value.slice(0, 4)}年${Number(value.slice(5, 7))}月`
|
||||
: value
|
||||
}
|
||||
|
||||
export function ExternalProfitPanel({
|
||||
onRowsChange,
|
||||
}: {
|
||||
onRowsChange: (rows: ExternalProfitRow[]) => void
|
||||
}) {
|
||||
const [basis, setBasis] = useState<ExternalProfitBasis>('cost')
|
||||
const [allRows, setAllRows] = useState<ExternalProfitRow[]>([])
|
||||
const [rows, setRows] = useState<ExternalProfitRow[]>([])
|
||||
const [selectedMonth, setSelectedMonth] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetch(`/api/supply-chain/management/external-sales/profit?basis=${basis}`, {
|
||||
cache: 'no-store',
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then(responseJson)
|
||||
.then((nextRows) => {
|
||||
const displayedRows = selectedMonth
|
||||
? nextRows.filter((row) => row.shipMonth === selectedMonth)
|
||||
: nextRows
|
||||
setAllRows(nextRows)
|
||||
setRows(displayedRows)
|
||||
onRowsChange(displayedRows)
|
||||
})
|
||||
.catch((cause) => {
|
||||
if (cause instanceof DOMException && cause.name === 'AbortError') return
|
||||
setError(cause instanceof Error ? cause.message : '毛利数据加载失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [basis, onRowsChange, reloadKey, selectedMonth])
|
||||
|
||||
return (
|
||||
<section id="external-sales-panel-profit" role="tabpanel" className={styles.content}>
|
||||
<div className={styles.profitToolbar}>
|
||||
<div className={styles.profitBasisTabs} role="group" aria-label="毛利成本维度">
|
||||
<button
|
||||
type="button"
|
||||
className={basis === 'cost' ? styles.profitBasisActive : undefined}
|
||||
aria-pressed={basis === 'cost'}
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setBasis('cost')
|
||||
}}
|
||||
>
|
||||
成本价维度
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={basis === 'clearance' ? styles.profitBasisActive : undefined}
|
||||
aria-pressed={basis === 'clearance'}
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setBasis('clearance')
|
||||
}}
|
||||
>
|
||||
清货价维度
|
||||
</button>
|
||||
</div>
|
||||
<label className={styles.profitMonthFilter}>
|
||||
<span>统计月份</span>
|
||||
<select
|
||||
aria-label="毛利统计月份"
|
||||
value={selectedMonth}
|
||||
onChange={(event) => {
|
||||
const nextMonth = event.target.value
|
||||
const displayedRows = nextMonth
|
||||
? allRows.filter((row) => row.shipMonth === nextMonth)
|
||||
: allRows
|
||||
setSelectedMonth(nextMonth)
|
||||
setRows(displayedRows)
|
||||
onRowsChange(displayedRows)
|
||||
}}
|
||||
>
|
||||
<option value="">全部月份</option>
|
||||
{allRows.map((row) => (
|
||||
<option key={row.shipMonth} value={row.shipMonth}>
|
||||
{monthText(row.shipMonth)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<span>成本调整、安装费暂无数据源,暂按 0 计算</span>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.secondaryButton}
|
||||
disabled={loading}
|
||||
onClick={() => {
|
||||
setLoading(true)
|
||||
setError('')
|
||||
setReloadKey((value) => value + 1)
|
||||
}}
|
||||
>
|
||||
<RefreshCw size={14} />刷新
|
||||
</button>
|
||||
</div>
|
||||
{error ? <div className={styles.error}>{error}</div> : null}
|
||||
<div className={styles.tableWrap}>
|
||||
<table className={`${styles.table} ${styles.profitTable}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>发货月份</th>
|
||||
<th>平台</th>
|
||||
<th>利润中心</th>
|
||||
<th className={styles.number}>销售金额</th>
|
||||
<th className={styles.number}>真实业绩</th>
|
||||
<th className={styles.number}>采购成本</th>
|
||||
<th className={styles.number}>成本调整</th>
|
||||
<th className={styles.number}>总成本</th>
|
||||
<th className={styles.number}>运费</th>
|
||||
<th className={styles.number}>其他快递运费</th>
|
||||
<th className={styles.number}>总运费</th>
|
||||
<th className={styles.number}>安装费</th>
|
||||
<th className={styles.number}>毛利额</th>
|
||||
<th className={styles.number}>毛利率</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.shipMonth}>
|
||||
<td className={styles.nowrap}>{monthText(row.shipMonth)}</td>
|
||||
<td>{row.platform}</td>
|
||||
<td>{row.profitCenter}</td>
|
||||
<td className={styles.number}>{amount(row.salesAmount)}</td>
|
||||
<td className={styles.number}>{amount(row.realPerformance)}</td>
|
||||
<td className={styles.number}>{amount(row.purchaseCost)}</td>
|
||||
<td className={styles.number}>{amount(row.costAdjustment)}</td>
|
||||
<td className={styles.number}>{amount(row.totalCost)}</td>
|
||||
<td className={styles.number}>{amount(row.freight)}</td>
|
||||
<td className={styles.number}>{amount(row.otherCourierFreight)}</td>
|
||||
<td className={styles.number}>{amount(row.totalFreight)}</td>
|
||||
<td className={styles.number}>{amount(row.installationFee)}</td>
|
||||
<td className={`${styles.number} ${styles.profitValue}`}>{amount(row.grossProfit)}</td>
|
||||
<td className={`${styles.number} ${styles.profitValue}`}>
|
||||
{(row.grossMargin * 100).toFixed(2)}%
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!loading && rows.length === 0 ? (
|
||||
<tr><td className={styles.empty} colSpan={14}>暂无毛利数据</td></tr>
|
||||
) : null}
|
||||
{loading ? (
|
||||
<tr><td className={styles.empty} colSpan={14}>正在计算毛利数据…</td></tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@ -0,0 +1,539 @@
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { MANAGEMENT_BLANK_PAGES } from '@/lib/supply-chain-management-blank-pages'
|
||||
import type { ExternalSalesDetailRow, ExternalSalesPage } from '@/lib/external-sales'
|
||||
import { ExternalSalesView } from './ExternalSalesView'
|
||||
|
||||
const definition = MANAGEMENT_BLANK_PAGES.find((page) => page.key === 'blank-page-7')!
|
||||
|
||||
const shared = {
|
||||
dateFrom: '2026-11-01',
|
||||
dateTo: '2026-11-13',
|
||||
shopName: '' as const,
|
||||
generatedAt: '2026-11-13T10:00:00.000Z',
|
||||
totals: {
|
||||
orderCount: 1,
|
||||
shipAmount: 10400,
|
||||
shipQty: 260,
|
||||
afterSaleCount: 1,
|
||||
refundQty: 2,
|
||||
refundAmount: 80,
|
||||
goodsValue: 8514,
|
||||
freight: 20,
|
||||
clearanceGoodsValue: 11610,
|
||||
},
|
||||
}
|
||||
|
||||
const summaryData: ExternalSalesPage = {
|
||||
...shared,
|
||||
view: 'summary',
|
||||
rows: [{
|
||||
month: '2026-11',
|
||||
orderNo: 'WM20261106132001PG',
|
||||
shipAmount: 10400,
|
||||
shipQty: 260,
|
||||
afterSaleAmount: 80,
|
||||
afterSaleQty: 2,
|
||||
finalShipAmount: 10320,
|
||||
finalShipQty: 258,
|
||||
}],
|
||||
pageInfo: { page: 1, pageSize: 50, total: 1, totalPages: 1 },
|
||||
}
|
||||
|
||||
const detailData: ExternalSalesPage = {
|
||||
...shared,
|
||||
view: 'detail',
|
||||
detailColumnAvailability: {
|
||||
shopSkuId: true,
|
||||
shopItemId: true,
|
||||
},
|
||||
rows: [{
|
||||
sourceType: 'QMCUST',
|
||||
oId: '10113153',
|
||||
oiId: '20261106001',
|
||||
orderNo: 'WM20261106132001PG',
|
||||
shopName: '阿里巴巴-外贸部欧伯娜导单专用店铺',
|
||||
shippingCourier: '中铁物流',
|
||||
trackingNo: '119033220001',
|
||||
shipmentWeight: 40,
|
||||
shippingUnitWeight: 0.2,
|
||||
shippingWeight: 40,
|
||||
freight: 20,
|
||||
statsDate: '2026-11-06',
|
||||
orderDate: '2026-11-06 11:11:01',
|
||||
sendDate: '2026-11-07 15:23:02',
|
||||
orderStatus: 'Sent',
|
||||
itemStatus: '',
|
||||
ownerName: '张三',
|
||||
localItemId: '6926012',
|
||||
skuId: 'CJ003166N68V01',
|
||||
itemId: 'ITEM-001',
|
||||
shopSkuId: 'SHOP-SKU-001',
|
||||
shopItemId: 'SHOP-ITEM-001',
|
||||
propertiesValue: '荷花白+原木色',
|
||||
itemName: '款式一 100/50/41.2',
|
||||
basePrice: 40,
|
||||
price: 40,
|
||||
qty: 260,
|
||||
amount: 10400,
|
||||
afterSaleAmount: 80,
|
||||
afterSaleQty: 2,
|
||||
finalShipAmount: 10320,
|
||||
finalShipQty: 258,
|
||||
orderPaidAmount: 10400,
|
||||
outerOiId: 'OUTER-10113153',
|
||||
costPrice: 33,
|
||||
goodsValue: 8514,
|
||||
clearancePrice: 45,
|
||||
clearanceGoodsValue: 11610,
|
||||
refundStatus: '',
|
||||
refundQty: 0,
|
||||
statusLabel: '已发货',
|
||||
}],
|
||||
pageInfo: { page: 1, pageSize: 50, total: 1, totalPages: 1 },
|
||||
}
|
||||
|
||||
const afterSaleData: ExternalSalesPage = {
|
||||
...shared,
|
||||
view: 'afterSale',
|
||||
rows: [{
|
||||
asId: '阿里巴巴-外贸部欧伯娜导单专用店铺|2026-11-06|WM20261106132001PG|CJ003166N68V01',
|
||||
outerAsId: 'AS-20261106-001',
|
||||
orderNo: 'WM20261106132001PG',
|
||||
shopName: '阿里巴巴-外贸部欧伯娜导单专用店铺',
|
||||
asDate: '2026-11-06 16:20:00',
|
||||
afterSaleStatus: 'WaitConfirm',
|
||||
afterSaleType: '普通退货',
|
||||
refundPhase: '售后',
|
||||
goodsStatus: '已收到货',
|
||||
creatorName: '张三',
|
||||
questionType: '尺寸不符',
|
||||
buyerApplyRefund: 80,
|
||||
refundAmount: 80,
|
||||
receiveRefund: 80,
|
||||
confirmDate: '',
|
||||
localItemId: '6926012',
|
||||
skuId: 'CJ003166N68V01',
|
||||
itemId: 'CJ003166',
|
||||
shopSkuId: 'SHOP-SKU-001',
|
||||
itemName: '款式一 100/50/41.2',
|
||||
propertiesValue: '荷花白+原木色',
|
||||
qty: 2,
|
||||
returnedQty: 2,
|
||||
amount: 80,
|
||||
remark: '客户申请退货',
|
||||
}],
|
||||
pageInfo: { page: 1, pageSize: 50, total: 1, totalPages: 1 },
|
||||
}
|
||||
|
||||
const freightData = {
|
||||
rows: [{
|
||||
id: 'freight-1',
|
||||
shipMonth: '2026-11',
|
||||
orderNo: 'WM20260917FLD-MANILA-34',
|
||||
outboundQty: 1394,
|
||||
incomeAfterTaxRefund: null,
|
||||
estimatedFreight: 6630,
|
||||
remark: '',
|
||||
sourceFileName: '外贸货代费.xlsx',
|
||||
importedByName: '本地管理员',
|
||||
createdAt: '2026-11-16T02:00:00.000Z',
|
||||
updatedAt: '2026-11-16T02:00:00.000Z',
|
||||
}],
|
||||
}
|
||||
|
||||
const clearanceData = {
|
||||
rows: [{
|
||||
orderNo: 'WM-CLEARANCE-001',
|
||||
itemCode: 'SKU-CLEARANCE-001',
|
||||
costPrice: 18.5,
|
||||
clearancePrice: 18.5,
|
||||
}],
|
||||
}
|
||||
|
||||
function profitData(basis: 'cost' | 'clearance') {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
shipMonth: '2026-11',
|
||||
platform: '外贸',
|
||||
profitCenter: '外贸部',
|
||||
salesAmount: 1000,
|
||||
realPerformance: 1000,
|
||||
purchaseCost: basis === 'cost' ? 500 : 600,
|
||||
costAdjustment: 0,
|
||||
totalCost: basis === 'cost' ? 500 : 600,
|
||||
freight: 50,
|
||||
otherCourierFreight: 100,
|
||||
totalFreight: 150,
|
||||
installationFee: 0,
|
||||
grossProfit: basis === 'cost' ? 350 : 250,
|
||||
grossMargin: (basis === 'cost' ? 350 : 250) / 1000,
|
||||
},
|
||||
{
|
||||
shipMonth: '2026-10',
|
||||
platform: '外贸',
|
||||
profitCenter: '外贸部',
|
||||
salesAmount: 800,
|
||||
realPerformance: 800,
|
||||
purchaseCost: basis === 'cost' ? 400 : 450,
|
||||
costAdjustment: 0,
|
||||
totalCost: basis === 'cost' ? 400 : 450,
|
||||
freight: 30,
|
||||
otherCourierFreight: 20,
|
||||
totalFreight: 50,
|
||||
installationFee: 0,
|
||||
grossProfit: basis === 'cost' ? 350 : 300,
|
||||
grossMargin: (basis === 'cost' ? 350 : 300) / 800,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function response<T>(data: T) {
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ success: true, data }),
|
||||
} as unknown as Response
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
global.fetch = jest.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input)
|
||||
if (url.endsWith('/external-sales/freight')) return response(freightData)
|
||||
if (url.endsWith('/external-sales/clearance')) return response(clearanceData)
|
||||
if (url.includes('/external-sales/profit')) {
|
||||
return response(profitData(url.includes('basis=clearance') ? 'clearance' : 'cost'))
|
||||
}
|
||||
return response(
|
||||
url.includes('view=afterSale')
|
||||
? afterSaleData
|
||||
: url.includes('view=detail')
|
||||
? detailData
|
||||
: summaryData,
|
||||
)
|
||||
}) as unknown as typeof fetch
|
||||
})
|
||||
|
||||
describe('外销销量', () => {
|
||||
it('renders all requested subpages and the summary headers', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
|
||||
expect(screen.getByRole('tab', { name: '汇总' })).toHaveAttribute('aria-selected', 'true')
|
||||
expect(screen.getByRole('tab', { name: '明细' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: '售后明细' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: '货代费' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: '清货价' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: '毛利' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '导出汇总' })).toBeInTheDocument()
|
||||
expect(await screen.findByText('WM20261106132001PG')).toBeInTheDocument()
|
||||
for (const header of [
|
||||
'月份',
|
||||
'订单号',
|
||||
'发货金额',
|
||||
'发货数量',
|
||||
'售后金额',
|
||||
'售后数量',
|
||||
'最终发货金额',
|
||||
'最终发货数量',
|
||||
]) {
|
||||
expect(screen.getByRole('columnheader', { name: header })).toBeInTheDocument()
|
||||
}
|
||||
expect(screen.getByRole('button', { name: '统计月份筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '店铺名称筛选' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: '关键词筛选' })).not.toBeInTheDocument()
|
||||
expect(screen.getAllByText('¥10,400.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('260').length).toBeGreaterThan(0)
|
||||
expect(screen.getByText('合计')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('¥80.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥10,320.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('258').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('offers export on every external-sales tab', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '明细' }))
|
||||
await screen.findByText('CJ003166N68V01')
|
||||
expect(screen.getByRole('button', { name: '导出明细' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('tab', { name: '售后明细' }))
|
||||
await screen.findByText('CJ003166N68V01')
|
||||
expect(screen.getByRole('button', { name: '导出售后明细' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('tab', { name: '货代费' }))
|
||||
await screen.findByText('WM20260917FLD-MANILA-34')
|
||||
expect(screen.getByRole('button', { name: '导出货代费' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('tab', { name: '清货价' }))
|
||||
await screen.findByText('WM-CLEARANCE-001')
|
||||
expect(screen.getByRole('button', { name: '导出清货价' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('tab', { name: '毛利' }))
|
||||
await screen.findAllByText('外贸部')
|
||||
expect(screen.getByRole('button', { name: '导出毛利' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('loads shipped order details from the selected data tab', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '明细' }))
|
||||
|
||||
expect(await screen.findByText('CJ003166N68V01')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '发货时间筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '店铺名称筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByText('款式一 100/50/41.2')).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '发货时间' })).toBeInTheDocument()
|
||||
expect(screen.getByText('2026-11-07 15:23:02')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '外部子订单号' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '基本售价(原价)' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '单价' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '子订单号' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '明细ID' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '内部单号' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '发货快递' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '运单号' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '售后金额' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '售后数量' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '最终发货金额' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '最终发货数量' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '成本' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '货值' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '清货价' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '清货货值' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '运费' })).toBeInTheDocument()
|
||||
expect(screen.getByText('10113153')).toBeInTheDocument()
|
||||
expect(screen.getByText('中铁物流')).toBeInTheDocument()
|
||||
expect(screen.getByText('119033220001')).toBeInTheDocument()
|
||||
expect(screen.getByText('¥33.00')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('¥8,514.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥45.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥11,610.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥80.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥10,320.00').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('258').length).toBeGreaterThan(0)
|
||||
expect(screen.getAllByText('¥20.00').length).toBeGreaterThan(0)
|
||||
const totalRow = screen.getByText('合计').closest('tr')
|
||||
expect(totalRow).not.toBeNull()
|
||||
expect(within(totalRow!).getByText('¥10,320.00')).toBeInTheDocument()
|
||||
expect(within(totalRow!).getByText('258')).toBeInTheDocument()
|
||||
expect(within(totalRow!).getByText('¥8,514.00')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('已发货').length).toBeGreaterThan(0)
|
||||
await waitFor(() => {
|
||||
expect(global.fetch).toHaveBeenLastCalledWith(
|
||||
expect.stringContaining('view=detail'),
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('hides shop code columns when all filtered rows are empty', async () => {
|
||||
const emptyShopCodes: ExternalSalesPage = {
|
||||
...detailData,
|
||||
detailColumnAvailability: {
|
||||
shopSkuId: false,
|
||||
shopItemId: false,
|
||||
},
|
||||
rows: [{
|
||||
...(detailData.rows[0] as ExternalSalesDetailRow),
|
||||
shopSkuId: '',
|
||||
shopItemId: '',
|
||||
}],
|
||||
}
|
||||
global.fetch = jest.fn(async (input: RequestInfo | URL) => (
|
||||
response(String(input).includes('view=detail') ? emptyShopCodes : summaryData)
|
||||
)) as unknown as typeof fetch
|
||||
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
fireEvent.click(screen.getByRole('tab', { name: '明细' }))
|
||||
await screen.findByText('CJ003166N68V01')
|
||||
|
||||
expect(screen.queryByRole('columnheader', { name: '店铺商品编码' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '店铺款式编码' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lets users configure detail filter fields and applies the selected field filters', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '明细' }))
|
||||
await screen.findByText('CJ003166N68V01')
|
||||
|
||||
expect(screen.getByRole('button', { name: '订单号筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '原始商品编码筛选' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: '内部单号筛选' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '明细筛选设置' }))
|
||||
expect(screen.getByRole('dialog', { name: '明细筛选设置' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: '启用内部单号筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '完成' }))
|
||||
expect(screen.getByRole('button', { name: '内部单号筛选' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '订单号筛选' }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: '筛选订单号' }), {
|
||||
target: { value: 'WM20261106132001PG' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用订单号筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '内部单号筛选' }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: '筛选内部单号' }), {
|
||||
target: { value: '10113153' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用内部单号筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '原始商品编码筛选' }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: '筛选原始商品编码' }), {
|
||||
target: { value: 'CJ003166N68V01' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用原始商品编码筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '查询' }))
|
||||
|
||||
await waitFor(() => {
|
||||
const lastCall = String((global.fetch as jest.Mock).mock.calls.at(-1)?.[0])
|
||||
const filters = new URL(lastCall, 'http://localhost').searchParams.get('filters')
|
||||
expect(JSON.parse(filters ?? '{}')).toEqual({
|
||||
orderNo: 'WM20261106132001PG',
|
||||
internalOrderNo: '10113153',
|
||||
skuId: 'CJ003166N68V01',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('filters the monthly summary by a selected month', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '统计月份筛选' }))
|
||||
fireEvent.change(screen.getByLabelText('筛选统计月份'), { target: { value: '2026-10' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用统计月份筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '查询' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(global.fetch).toHaveBeenLastCalledWith(
|
||||
expect.stringContaining('month=2026-10'),
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('loads after-sales only for the external order scope', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '售后明细' }))
|
||||
expect(await screen.findByText('CJ003166N68V01')).toBeInTheDocument()
|
||||
expect(screen.getAllByText('阿里巴巴-外贸部欧伯娜导单专用店铺').length).toBeGreaterThan(0)
|
||||
expect(screen.getByRole('columnheader', { name: '原订单号' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '售后金额' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '售后数量' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '售后日期筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '店铺名称筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '订单号筛选' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '商品编码筛选' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: '统计月份筛选' })).not.toBeInTheDocument()
|
||||
await waitFor(() => {
|
||||
const lastCall = String((global.fetch as jest.Mock).mock.calls.at(-1)?.[0])
|
||||
expect(lastCall).toContain('view=afterSale')
|
||||
expect(lastCall).not.toContain('dateFrom=')
|
||||
expect(lastCall).not.toContain('dateTo=')
|
||||
expect(lastCall).not.toContain('month=')
|
||||
expect(lastCall).not.toContain('shopName=')
|
||||
})
|
||||
})
|
||||
|
||||
it('filters after-sales by date, shop, order number and item code', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
fireEvent.click(screen.getByRole('tab', { name: '售后明细' }))
|
||||
await screen.findByText('CJ003166N68V01')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '售后日期筛选' }))
|
||||
fireEvent.change(screen.getByLabelText('筛选售后日期开始时间'), {
|
||||
target: { value: '2026-11-01' },
|
||||
})
|
||||
fireEvent.change(screen.getByLabelText('筛选售后日期结束时间'), {
|
||||
target: { value: '2026-11-30' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用售后日期筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '店铺名称筛选' }))
|
||||
fireEvent.change(screen.getByLabelText('筛选店铺名称'), {
|
||||
target: { value: '阿里巴巴-外贸部欧伯娜导单专用店铺' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用店铺名称筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '订单号筛选' }))
|
||||
fireEvent.change(screen.getByLabelText('筛选订单号'), {
|
||||
target: { value: 'WM20261106132001PG' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用订单号筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '商品编码筛选' }))
|
||||
fireEvent.change(screen.getByLabelText('筛选商品编码'), {
|
||||
target: { value: 'CJ003166N68V01' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: '应用商品编码筛选' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: '查询' }))
|
||||
|
||||
await waitFor(() => {
|
||||
const lastCall = String((global.fetch as jest.Mock).mock.calls.at(-1)?.[0])
|
||||
expect(lastCall).toContain('dateFrom=2026-11-01')
|
||||
expect(lastCall).toContain('dateTo=2026-11-30')
|
||||
expect(lastCall).toContain('shopName=')
|
||||
expect(lastCall).toContain('orderNo=WM20261106132001PG')
|
||||
expect(lastCall).toContain('itemCode=CJ003166N68V01')
|
||||
})
|
||||
})
|
||||
|
||||
it('loads the freight import workspace and clearance price data', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: '货代费' }))
|
||||
expect(await screen.findByText('WM20260917FLD-MANILA-34')).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '发货月份' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '订单号' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '出库数量(以实际为准)' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '收入-减退税(CNY)' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '预估货运费(货代+海运)' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '备注' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: '下载模板' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '人工导入' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: '人工导入' }))
|
||||
expect(screen.getByRole('dialog', { name: '导入人工货代费' })).toBeInTheDocument()
|
||||
expect(screen.getByText('导入说明')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '导入模板下载' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '浏览...' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '开始导入' })).toBeDisabled()
|
||||
expect(screen.getByText('请选择需要上传并导入的 Excel 文件')).toBeInTheDocument()
|
||||
expect(screen.getByText('2026年11月')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: '关闭货代费导入' }))
|
||||
fireEvent.click(screen.getByRole('tab', { name: '清货价' }))
|
||||
expect(await screen.findByText('WM-CLEARANCE-001')).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '商品编码' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '成本价' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '清货价' })).toBeInTheDocument()
|
||||
expect(screen.getAllByText('¥18.50').length).toBe(2)
|
||||
})
|
||||
|
||||
it('switches between cost-price and clearance-price profit dimensions', async () => {
|
||||
render(<ExternalSalesView definition={definition} />)
|
||||
await screen.findByText('WM20261106132001PG')
|
||||
fireEvent.click(screen.getByRole('tab', { name: '毛利' }))
|
||||
|
||||
expect((await screen.findAllByText('外贸部')).length).toBeGreaterThan(0)
|
||||
expect(screen.getByRole('columnheader', { name: '发货月份' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '销售金额' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('columnheader', { name: '退款金额' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '真实业绩' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '总成本' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '其他快递运费' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('columnheader', { name: '毛利率' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '成本价维度' })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getAllByText('¥500.00').length).toBeGreaterThan(0)
|
||||
|
||||
fireEvent.change(screen.getByLabelText('毛利统计月份'), { target: { value: '2026-10' } })
|
||||
const profitTable = screen.getByRole('table')
|
||||
expect(within(profitTable).getByText('2026年10月')).toBeInTheDocument()
|
||||
expect(within(profitTable).queryByText('2026年11月')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: '清货价维度' }))
|
||||
expect((await screen.findAllByText('¥450.00')).length).toBeGreaterThan(0)
|
||||
expect(screen.getByRole('button', { name: '清货价维度' })).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@ -5,6 +5,7 @@ import { supplyChainPermissionSettingsService } from '@/server/services/supply-c
|
||||
import { ManagementBlankPageView } from '../ManagementBlankPageView'
|
||||
import { ProductSabcView } from '../ProductSabcView'
|
||||
import { ProductSelectionView } from '../ProductSelectionView'
|
||||
import { ExternalSalesView } from '../ExternalSalesView'
|
||||
|
||||
export default async function ManagementBlankPage({ params }: { params: Promise<{ pageKey: string }> }) {
|
||||
const definition = getManagementBlankPage((await params).pageKey)
|
||||
@ -38,6 +39,12 @@ export default async function ManagementBlankPage({ params }: { params: Promise<
|
||||
return <ProductSelectionView definition={definition} canDownload={access.download} />
|
||||
}
|
||||
|
||||
if (definition.key === 'blank-page-7') {
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(authUser, 'managementBlankPage7')
|
||||
if (!access.view) redirect('/supply-chain')
|
||||
return <ExternalSalesView definition={definition} />
|
||||
}
|
||||
|
||||
const access = await supplyChainPermissionSettingsService.getUserAccess(
|
||||
authUser,
|
||||
definition.key === 'blank-page-1' ? 'managementBlankPage1' : 'managementBlankPage2',
|
||||
|
||||
@ -0,0 +1,108 @@
|
||||
.page{display:flex;min-width:0;min-height:0;flex:1;flex-direction:column;overflow:hidden;background:var(--sc-bg);color:var(--sc-ink)}
|
||||
.header{display:flex;flex:none;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--sc-border);background:var(--sc-surface);padding:13px 24px}
|
||||
.header h1{margin:0;font-size:18px;font-weight:700}
|
||||
.header p{margin:5px 0 0;color:var(--sc-muted);font-size:12px}
|
||||
.headerActions{display:flex;flex:none;align-items:center;gap:12px}
|
||||
.headerMeta{display:flex;flex:none;flex-direction:column;align-items:flex-end;gap:3px}
|
||||
.headerMeta span{border-radius:999px;background:#ecfdf5;padding:3px 10px;color:#047857;font-size:12px;font-weight:600}
|
||||
.headerMeta i{color:var(--sc-muted);font-size:11px;font-style:normal}
|
||||
.tabs{display:flex;flex:none;gap:4px;overflow-x:auto;border-bottom:1px solid var(--sc-border);background:var(--sc-surface);padding:10px 24px}
|
||||
.tabs button{display:inline-flex;height:34px;flex:none;align-items:center;gap:6px;border:1px solid transparent;border-radius:6px;background:transparent;padding:0 14px;color:#52525b;font-size:12px;font-family:inherit;cursor:pointer}
|
||||
.tabs .tabActive{border-color:#d4d4d8;background:#fff;color:#18181b;box-shadow:0 1px 2px rgba(0,0,0,.06)}
|
||||
.filters{display:flex;flex:none;flex-wrap:wrap;align-items:flex-end;gap:10px;padding:14px 24px 10px}
|
||||
.filters label{display:flex;min-width:180px;flex:0 1 210px;flex-direction:column;gap:4px;color:var(--sc-muted);font-size:11px}
|
||||
.filters .keyword{min-width:280px;flex:2 1 360px}
|
||||
.filterHint{align-self:center;padding-bottom:8px;color:var(--sc-muted);font-size:11px}
|
||||
.filters label>div{display:flex;height:34px;align-items:center;gap:7px;border:1px solid var(--sc-border);border-radius:5px;background:#fff;padding:0 9px}
|
||||
.filters input,.filters select{box-sizing:border-box;height:34px;border:1px solid var(--sc-border);border-radius:5px;background:#fff;padding:0 9px;outline:0;color:var(--sc-ink);font-size:12px;font-family:inherit}
|
||||
.filters label>div input{height:auto;flex:1;min-width:0;border:0;padding:0}
|
||||
.filters input:focus,.filters select:focus,.filters label>div:focus-within{border-color:#93c5fd;box-shadow:0 0 0 2px #eff6ff}
|
||||
.detailFilterBar{display:flex;min-width:0;flex:1 0 100%;align-items:flex-start;gap:13px;padding-top:2px}
|
||||
.detailFilterLabel{flex:none;padding-top:12px;color:#a1a1aa;font-size:12px}
|
||||
.detailFilterButtons{display:flex;min-width:0;flex:1;flex-wrap:wrap;gap:10px}
|
||||
.detailFilterSelect{position:relative}
|
||||
.detailFilterTrigger{display:flex;height:44px;min-width:82px;max-width:290px;align-items:center;justify-content:space-between;gap:12px;border:1px solid #d4d4d8;border-radius:8px;background:#fff;padding:0 16px;color:#3f3f46;font-size:14px;font-family:inherit;cursor:pointer}
|
||||
.detailFilterTrigger>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.detailFilterTrigger:hover{border-color:#a1a1aa}
|
||||
.detailFilterTriggerActive{border-color:#52525b;background:#f4f4f5;font-weight:600}
|
||||
.detailFilterPopover{position:absolute;top:50px;left:0;z-index:60;width:max(100%,250px);border:1px solid #d4d4d8;border-radius:7px;background:#fff;padding:9px;box-shadow:0 12px 30px rgba(24,24,27,.14)}
|
||||
.detailFilterPopover input{width:100%;height:36px}
|
||||
.detailFilterPopover select{box-sizing:border-box;width:100%;height:36px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 8px;color:#3f3f46;font-size:12px;font-family:inherit}
|
||||
.dateFilterPopover{width:max(100%,390px)}
|
||||
.detailFilterPopover>.dateFilterFields{display:flex;align-items:center;justify-content:flex-start;gap:6px;margin-top:0}
|
||||
.dateFilterFields span{flex:none;color:#a1a1aa;font-size:11px}
|
||||
.dateFilterFields input{width:145px!important}
|
||||
.detailFilterPopover>div{display:flex;justify-content:flex-end;gap:7px;margin-top:8px}
|
||||
.detailFilterPopover>div button{height:29px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 10px;color:#52525b;font-size:11px;font-family:inherit;cursor:pointer}
|
||||
.detailFilterPopover>div button:last-child{border-color:#27272a;background:#27272a;color:#fff}
|
||||
.dateRange{display:flex;min-width:300px;align-items:center;gap:7px;margin:0;border:0;padding:0}
|
||||
.dateRange legend{margin-bottom:4px;color:var(--sc-muted);font-size:11px}
|
||||
.dateRange span{color:var(--sc-muted);font-size:11px}
|
||||
.filterActions{display:flex;flex:1 0 100%;align-items:center;justify-content:flex-end;gap:7px;color:var(--sc-muted);font-size:11px}
|
||||
.filterActions>span{margin-right:5px;white-space:nowrap}
|
||||
.primaryButton,.secondaryButton,.iconButton{display:inline-flex;height:34px;align-items:center;justify-content:center;gap:5px;border-radius:5px;padding:0 11px;font-size:12px;font-family:inherit;cursor:pointer}
|
||||
.primaryButton{border:1px solid #27272a;background:#27272a;color:#fff}
|
||||
.secondaryButton{border:1px solid #d4d4d8;background:#fff;color:#52525b}
|
||||
.iconButton{width:34px;border:1px solid #d4d4d8;background:#fff;padding:0;color:#52525b}
|
||||
.iconButton:hover{border-color:#a1a1aa;background:#fafafa}
|
||||
.primaryButton:disabled,.secondaryButton:disabled{cursor:not-allowed;opacity:.45}
|
||||
.error{margin:0 24px 8px;border:1px solid #fecaca;border-radius:5px;background:#fff7f7;padding:9px 12px;color:#b91c1c;font-size:12px}
|
||||
.success{margin:0 24px 8px;border:1px solid #bbf7d0;border-radius:5px;background:#f0fdf4;padding:9px 12px;color:#15803d;font-size:12px}
|
||||
.freightToolbar{display:flex;flex:none;align-items:center;justify-content:flex-end;gap:8px;padding:14px 24px 10px;color:var(--sc-muted);font-size:11px}
|
||||
.freightToolbar>span{margin-right:auto}
|
||||
.freightImportDialog{width:min(1180px,100%)}
|
||||
.profitToolbar{display:flex;flex:none;align-items:center;gap:12px;padding:14px 24px 10px;color:var(--sc-muted);font-size:11px}
|
||||
.profitToolbar>span{margin-left:auto}
|
||||
.profitBasisTabs{display:inline-flex;gap:3px;padding:3px;border:1px solid #d4d4d8;border-radius:7px;background:#f4f4f5}
|
||||
.profitBasisTabs button{height:30px;border:0;border-radius:5px;background:transparent;padding:0 14px;color:#52525b;font-size:12px;font-family:inherit;cursor:pointer}
|
||||
.profitBasisTabs .profitBasisActive{background:#fff;color:#18181b;font-weight:700;box-shadow:0 1px 2px rgba(0,0,0,.08)}
|
||||
.profitMonthFilter{display:flex;align-items:center;gap:7px;color:#52525b;font-size:12px}
|
||||
.profitMonthFilter select{height:36px;min-width:150px;border:1px solid #d4d4d8;border-radius:7px;background:#fff;padding:0 10px;color:#3f3f46;font-size:12px;font-family:inherit}
|
||||
.content{display:flex;min-height:0;flex:1;flex-direction:column}
|
||||
.tableWrap{min-height:0;flex:1;overflow:auto;padding:0 24px}
|
||||
.table{width:100%;border-collapse:separate;border-spacing:0;background:#fff;font-size:12px}
|
||||
.summaryTable{min-width:980px}
|
||||
.detailTable{min-width:2680px}
|
||||
.afterSaleTable{min-width:980px}
|
||||
.freightTable{min-width:1040px}
|
||||
.clearancePriceTable{min-width:760px}
|
||||
.clearancePriceCell{color:#b45309!important;font-weight:700}
|
||||
.profitTable{min-width:1760px}
|
||||
.profitValue{color:#047857!important;font-weight:700}
|
||||
.table th{position:sticky;top:0;z-index:2;height:40px;border-bottom:1px solid #d4d4d8;background:#eef0ef;padding:0 11px;color:#52525b;font-size:11px;font-weight:600;text-align:left;white-space:nowrap}
|
||||
.table td{height:44px;border-bottom:1px solid #f0f0f1;padding:7px 11px;color:#52525b;vertical-align:middle}
|
||||
.table tbody tr:hover>td{background:#fafafa}
|
||||
.table th.finalHeader{border-right:1px solid #fed7aa;border-left:1px solid #fed7aa;background:#fff1e6;color:#b45309}
|
||||
.table td.finalCell{border-right:1px solid #fed7aa;border-left:1px solid #fed7aa;background:#fff8ed;color:#b45309;font-weight:700}
|
||||
.table tbody tr:hover>td.finalCell{background:#fff2df}
|
||||
.table th.freightHeader{background:#eff6ff;color:#1d4ed8}
|
||||
.table td.freightCell{background:#f8fbff;color:#1d4ed8;font-weight:700}
|
||||
.table tbody tr:hover>td.freightCell{background:#eff6ff}
|
||||
.table th.clearanceHeader{background:#f0fdf4;color:#15803d}
|
||||
.table td.clearanceCell{background:#f8fff9;color:#15803d;font-weight:700}
|
||||
.table tbody tr:hover>td.clearanceCell{background:#f0fdf4}
|
||||
.finalNegative{color:#b91c1c!important}
|
||||
.table .totalRow>td{border-top:1px solid #d4d4d8;background:#f8fafc;color:#18181b;font-weight:700}
|
||||
.table .totalRow>td.finalTotalCell{border-right:1px solid #fed7aa;border-left:1px solid #fed7aa;background:#fff1e6;color:#b45309}
|
||||
.table .totalRow>td.freightCell{background:#eff6ff;color:#1d4ed8}
|
||||
.table .totalRow>td.clearanceCell{background:#f0fdf4;color:#15803d}
|
||||
.number{text-align:right!important;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.code{color:#27272a!important;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;white-space:nowrap}
|
||||
.nowrap{white-space:nowrap}
|
||||
.shopCell{min-width:230px}
|
||||
.nameCell{min-width:260px;max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.propertiesCell{min-width:190px;max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.reasonCell{min-width:180px;max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.status{display:inline-flex;border-radius:999px;background:#ecfdf5;padding:3px 8px;color:#047857;font-size:10px;font-weight:600;white-space:nowrap}
|
||||
.afterSaleType{display:inline-flex;border-radius:999px;background:#fff7ed;padding:3px 8px;color:#c2410c;font-size:10px;font-weight:600;white-space:nowrap}
|
||||
.empty{height:220px!important;color:#a1a1aa!important;text-align:center}
|
||||
.pagination{display:flex;flex:none;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;border-top:1px solid var(--sc-border);background:var(--sc-surface);padding:10px 24px;color:var(--sc-muted);font-size:11px}
|
||||
.pagination>div{display:flex;align-items:center;gap:4px}
|
||||
.pagination button{min-width:30px;height:28px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;padding:0 8px;color:#52525b;font-size:11px;font-family:inherit;cursor:pointer}
|
||||
.pagination button:disabled{cursor:not-allowed;opacity:.4}
|
||||
.pagination .pageActive{border-color:#27272a!important;background:#27272a!important;color:#fff!important}
|
||||
.pendingPanel{display:flex;min-height:320px;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:#a1a1aa}
|
||||
.pendingPanel span{color:#52525b;font-size:13px;font-weight:600}
|
||||
.pendingPanel p{margin:0;font-size:12px}
|
||||
@media(max-width:1100px){.filterActions{justify-content:flex-start;flex-wrap:wrap}.header{align-items:flex-start}.headerMeta{align-items:flex-start}}
|
||||
@media(max-width:760px){.header{flex-direction:column}.tabs,.filters,.tableWrap,.pagination{padding-right:14px;padding-left:14px}.detailFilterBar{flex-direction:column;gap:7px}.detailFilterLabel{padding-top:0}.detailFilterButtons{width:100%}.detailFilterPopover{width:min(280px,calc(100vw - 40px))}.dateFilterPopover{width:min(390px,calc(100vw - 28px))}.filterActions>span{white-space:normal}}
|
||||
50
furniture-3d-system/src/lib/external-clearance-price.test.ts
Normal file
50
furniture-3d-system/src/lib/external-clearance-price.test.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { buildExternalClearancePriceRows } from './external-clearance-price'
|
||||
|
||||
describe('external clearance price', () => {
|
||||
it('deduplicates order and item code and uses the latest cost price', () => {
|
||||
const rows = buildExternalClearancePriceRows([
|
||||
{
|
||||
onlineOrderNo: 'WM-001',
|
||||
internalOrderNo: '',
|
||||
productCode: 'SKU-001',
|
||||
styleCode: '',
|
||||
shopProductCode: '',
|
||||
shopStyleCode: '',
|
||||
costPrice: '18.50',
|
||||
},
|
||||
{
|
||||
onlineOrderNo: 'wm-001',
|
||||
internalOrderNo: '',
|
||||
productCode: 'sku-001',
|
||||
styleCode: '',
|
||||
shopProductCode: '',
|
||||
shopStyleCode: '',
|
||||
costPrice: '99',
|
||||
},
|
||||
{
|
||||
onlineOrderNo: '',
|
||||
internalOrderNo: '10001',
|
||||
productCode: '',
|
||||
styleCode: 'STYLE-001',
|
||||
shopProductCode: '',
|
||||
shopStyleCode: '',
|
||||
costPrice: 8,
|
||||
},
|
||||
])
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
orderNo: '10001',
|
||||
itemCode: 'STYLE-001',
|
||||
costPrice: 8,
|
||||
clearancePrice: 8,
|
||||
},
|
||||
{
|
||||
orderNo: 'WM-001',
|
||||
itemCode: 'SKU-001',
|
||||
costPrice: 18.5,
|
||||
clearancePrice: 18.5,
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
45
furniture-3d-system/src/lib/external-clearance-price.ts
Normal file
45
furniture-3d-system/src/lib/external-clearance-price.ts
Normal file
@ -0,0 +1,45 @@
|
||||
export type ExternalOrderCostSourceRow = {
|
||||
onlineOrderNo: string
|
||||
internalOrderNo: string
|
||||
productCode: string
|
||||
styleCode: string
|
||||
shopProductCode: string
|
||||
shopStyleCode: string
|
||||
costPrice: number | string
|
||||
}
|
||||
|
||||
export type ExternalClearancePriceRow = {
|
||||
orderNo: string
|
||||
itemCode: string
|
||||
costPrice: number
|
||||
clearancePrice: number
|
||||
}
|
||||
|
||||
export function buildExternalClearancePriceRows(
|
||||
rows: readonly ExternalOrderCostSourceRow[],
|
||||
): ExternalClearancePriceRow[] {
|
||||
const result: ExternalClearancePriceRow[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const row of rows) {
|
||||
const orderNo = row.onlineOrderNo.trim() || row.internalOrderNo.trim()
|
||||
const itemCode = row.productCode.trim()
|
||||
|| row.styleCode.trim()
|
||||
|| row.shopProductCode.trim()
|
||||
|| row.shopStyleCode.trim()
|
||||
const costPrice = Number(row.costPrice)
|
||||
if (!orderNo || !itemCode || !Number.isFinite(costPrice)) continue
|
||||
const key = `${orderNo.toUpperCase()}|${itemCode.toUpperCase()}`
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
result.push({
|
||||
orderNo,
|
||||
itemCode,
|
||||
costPrice,
|
||||
clearancePrice: costPrice,
|
||||
})
|
||||
}
|
||||
return result.sort((left, right) => (
|
||||
left.orderNo.localeCompare(right.orderNo, 'zh-CN')
|
||||
|| left.itemCode.localeCompare(right.itemCode, 'zh-CN')
|
||||
))
|
||||
}
|
||||
56
furniture-3d-system/src/lib/external-freight.test.ts
Normal file
56
furniture-3d-system/src/lib/external-freight.test.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
import {
|
||||
createExternalFreightTemplate,
|
||||
EXTERNAL_FREIGHT_HEADERS,
|
||||
parseExternalFreightWorkbook,
|
||||
} from './external-freight'
|
||||
|
||||
async function workbookBuffer(rows: unknown[][]) {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
const sheet = workbook.addWorksheet('货代费')
|
||||
for (const row of rows) sheet.addRow(row)
|
||||
return Buffer.from(await workbook.xlsx.writeBuffer())
|
||||
}
|
||||
|
||||
describe('external freight import', () => {
|
||||
it('parses the screenshot headers and order values', async () => {
|
||||
const rows = await parseExternalFreightWorkbook(await workbookBuffer([
|
||||
EXTERNAL_FREIGHT_HEADERS,
|
||||
['2026年11月', 'WM20260917FLD-MANILA-34', 1394, null, 6630, ''],
|
||||
]))
|
||||
|
||||
expect(rows).toEqual([{
|
||||
rowNumber: 2,
|
||||
shipMonth: '2026-11',
|
||||
orderNo: 'WM20260917FLD-MANILA-34',
|
||||
outboundQty: 1394,
|
||||
incomeAfterTaxRefund: null,
|
||||
estimatedFreight: 6630,
|
||||
remark: '',
|
||||
}])
|
||||
})
|
||||
|
||||
it('creates the downloadable template with the required headers', async () => {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(await createExternalFreightTemplate() as never)
|
||||
const sheet = workbook.getWorksheet('货代费')
|
||||
|
||||
expect(sheet?.getRow(1).values.slice(1)).toEqual([...EXTERNAL_FREIGHT_HEADERS])
|
||||
expect(sheet?.getRow(2).values.slice(1)).toEqual([
|
||||
'2026年11月',
|
||||
'WM20260917FLD-MANILA-34',
|
||||
1394,
|
||||
undefined,
|
||||
6630,
|
||||
'',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects duplicate order numbers in one file', async () => {
|
||||
await expect(parseExternalFreightWorkbook(await workbookBuffer([
|
||||
EXTERNAL_FREIGHT_HEADERS,
|
||||
['2026年11月', 'WM-001', 1, 100, 20, ''],
|
||||
['2026年11月', 'wm-001', 2, 200, 30, ''],
|
||||
]))).rejects.toThrow('订单号重复')
|
||||
})
|
||||
})
|
||||
240
furniture-3d-system/src/lib/external-freight.ts
Normal file
240
furniture-3d-system/src/lib/external-freight.ts
Normal file
@ -0,0 +1,240 @@
|
||||
import ExcelJS from 'exceljs'
|
||||
|
||||
export const EXTERNAL_FREIGHT_HEADERS = [
|
||||
'发货月份',
|
||||
'订单号',
|
||||
'出库数量(以实际为准)',
|
||||
'收入-减退税(CNY)',
|
||||
'预估货运费(货代+海运)',
|
||||
'备注',
|
||||
] as const
|
||||
|
||||
export type ExternalFreightImportRow = {
|
||||
rowNumber: number
|
||||
shipMonth: string
|
||||
orderNo: string
|
||||
outboundQty: number
|
||||
incomeAfterTaxRefund: number | null
|
||||
estimatedFreight: number
|
||||
remark: string
|
||||
}
|
||||
|
||||
export type ExternalFreightRecordView = {
|
||||
id: string
|
||||
shipMonth: string
|
||||
orderNo: string
|
||||
outboundQty: number
|
||||
incomeAfterTaxRefund: number | null
|
||||
estimatedFreight: number
|
||||
remark: string
|
||||
sourceFileName: string
|
||||
importedByName: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
function normalizedHeader(value: string) {
|
||||
return value
|
||||
.trim()
|
||||
.replace(/\s+/g, '')
|
||||
.replaceAll('(', '(')
|
||||
.replaceAll(')', ')')
|
||||
}
|
||||
|
||||
function cellText(value: ExcelJS.CellValue, field: string) {
|
||||
if (value == null) return ''
|
||||
if (value instanceof Date) throw new Error(`${field}格式不正确`)
|
||||
if (typeof value === 'object') {
|
||||
if ('text' in value && typeof value.text === 'string') return value.text.trim()
|
||||
if ('result' in value && value.result != null) return String(value.result).trim()
|
||||
throw new Error(`${field}包含公式,请先粘贴为值`)
|
||||
}
|
||||
return String(value).trim()
|
||||
}
|
||||
|
||||
function requiredNumber(
|
||||
value: ExcelJS.CellValue,
|
||||
field: string,
|
||||
options: { integer?: boolean; min?: number },
|
||||
) {
|
||||
const text = cellText(value, field).replaceAll(',', '')
|
||||
if (!text) throw new Error(`${field}不能为空`)
|
||||
const parsed = Number(text)
|
||||
if (!Number.isFinite(parsed)
|
||||
|| (options.integer && !Number.isInteger(parsed))
|
||||
|| (options.min != null && parsed < options.min)) {
|
||||
throw new Error(`${field}格式不正确`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
function optionalNumber(value: ExcelJS.CellValue, field: string) {
|
||||
const text = cellText(value, field).replaceAll(',', '')
|
||||
if (!text) return null
|
||||
const parsed = Number(text)
|
||||
if (!Number.isFinite(parsed)) throw new Error(`${field}格式不正确`)
|
||||
return parsed
|
||||
}
|
||||
|
||||
function freightShipMonth(value: ExcelJS.CellValue) {
|
||||
if (value instanceof Date) {
|
||||
return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}`
|
||||
}
|
||||
const text = cellText(value, '发货月份').trim()
|
||||
if (!text) throw new Error('发货月份不能为空')
|
||||
const chinese = /^(\d{4})年(0?[1-9]|1[0-2])月$/.exec(text)
|
||||
if (chinese) return `${chinese[1]}-${chinese[2].padStart(2, '0')}`
|
||||
const separated = /^(\d{4})[-/.](\d{1,2})(?:[-/.]\d{1,2})?$/.exec(text)
|
||||
if (separated && Number(separated[2]) >= 1 && Number(separated[2]) <= 12) {
|
||||
return `${separated[1]}-${separated[2].padStart(2, '0')}`
|
||||
}
|
||||
throw new Error('发货月份格式不正确,请填写如 2026年11月 或 2026-11')
|
||||
}
|
||||
|
||||
export async function parseExternalFreightWorkbook(
|
||||
buffer: Buffer,
|
||||
): Promise<ExternalFreightImportRow[]> {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
await workbook.xlsx.load(buffer as never)
|
||||
let worksheet: ExcelJS.Worksheet | null = null
|
||||
let columns = new Map<string, number>()
|
||||
const expected = new Map(EXTERNAL_FREIGHT_HEADERS.map((header) => [normalizedHeader(header), header]))
|
||||
|
||||
for (const candidate of workbook.worksheets) {
|
||||
const found = new Map<string, number>()
|
||||
candidate.getRow(1).eachCell((cell, columnNumber) => {
|
||||
const normalized = normalizedHeader(cellText(cell.value, '抬头'))
|
||||
const header = expected.get(normalized)
|
||||
if (header) found.set(header, columnNumber)
|
||||
})
|
||||
if (EXTERNAL_FREIGHT_HEADERS.every((header) => found.has(header))) {
|
||||
worksheet = candidate
|
||||
columns = found
|
||||
break
|
||||
}
|
||||
}
|
||||
if (!worksheet) {
|
||||
throw new Error(`未找到内容匹配的导入模板,表头必须包含:${EXTERNAL_FREIGHT_HEADERS.join('、')}`)
|
||||
}
|
||||
|
||||
const rows: ExternalFreightImportRow[] = []
|
||||
const seenOrders = new Set<string>()
|
||||
worksheet.eachRow((row, rowNumber) => {
|
||||
if (rowNumber === 1) return
|
||||
const value = (header: typeof EXTERNAL_FREIGHT_HEADERS[number]) => (
|
||||
row.getCell(columns.get(header)!).value
|
||||
)
|
||||
const shipMonthValue = value('发货月份')
|
||||
const orderNo = cellText(value('订单号'), '订单号')
|
||||
const outboundText = cellText(value('出库数量(以实际为准)'), '出库数量')
|
||||
const incomeText = cellText(value('收入-减退税(CNY)'), '收入-减退税')
|
||||
const freightText = cellText(value('预估货运费(货代+海运)'), '预估货运费')
|
||||
const remark = cellText(value('备注'), '备注')
|
||||
if (![
|
||||
cellText(shipMonthValue, '发货月份'),
|
||||
orderNo,
|
||||
outboundText,
|
||||
incomeText,
|
||||
freightText,
|
||||
remark,
|
||||
].some(Boolean)) return
|
||||
if (!orderNo) throw new Error(`第 ${rowNumber} 行订单号不能为空`)
|
||||
const normalizedOrderNo = orderNo.toUpperCase()
|
||||
if (seenOrders.has(normalizedOrderNo)) {
|
||||
throw new Error(`第 ${rowNumber} 行订单号重复:${orderNo}`)
|
||||
}
|
||||
seenOrders.add(normalizedOrderNo)
|
||||
try {
|
||||
rows.push({
|
||||
rowNumber,
|
||||
shipMonth: freightShipMonth(shipMonthValue),
|
||||
orderNo,
|
||||
outboundQty: requiredNumber(value('出库数量(以实际为准)'), '出库数量', {
|
||||
integer: true,
|
||||
min: 0,
|
||||
}),
|
||||
incomeAfterTaxRefund: optionalNumber(value('收入-减退税(CNY)'), '收入-减退税'),
|
||||
estimatedFreight: requiredNumber(value('预估货运费(货代+海运)'), '预估货运费', {
|
||||
min: 0,
|
||||
}),
|
||||
remark,
|
||||
})
|
||||
} catch (error) {
|
||||
throw new Error(`第 ${rowNumber} 行${error instanceof Error ? error.message : '数据格式不正确'}`)
|
||||
}
|
||||
})
|
||||
if (!rows.length) throw new Error('Excel 没有可导入的数据')
|
||||
if (rows.length > 5_000) throw new Error('单个文件最多导入 5000 行')
|
||||
return rows
|
||||
}
|
||||
|
||||
export async function createExternalFreightTemplate() {
|
||||
const workbook = new ExcelJS.Workbook()
|
||||
workbook.creator = '供应链中心 · 外销销量'
|
||||
workbook.created = new Date()
|
||||
const worksheet = workbook.addWorksheet('货代费', {
|
||||
views: [{ state: 'frozen', ySplit: 1 }],
|
||||
})
|
||||
worksheet.columns = [
|
||||
{ header: '发货月份', key: 'shipMonth', width: 18 },
|
||||
{ header: '订单号', key: 'orderNo', width: 32 },
|
||||
{ header: '出库数量(以实际为准)', key: 'outboundQty', width: 24 },
|
||||
{ header: '收入-减退税(CNY)', key: 'incomeAfterTaxRefund', width: 22 },
|
||||
{ header: '预估货运费(货代+海运)', key: 'estimatedFreight', width: 28 },
|
||||
{ header: '备注', key: 'remark', width: 24 },
|
||||
]
|
||||
const exampleRow = worksheet.addRow({
|
||||
shipMonth: '2026年11月',
|
||||
orderNo: 'WM20260917FLD-MANILA-34',
|
||||
outboundQty: 1394,
|
||||
incomeAfterTaxRefund: null,
|
||||
estimatedFreight: 6630,
|
||||
remark: '',
|
||||
})
|
||||
exampleRow.font = { color: { argb: 'FF6B7280' } }
|
||||
exampleRow.getCell(5).fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFE2F0D9' },
|
||||
}
|
||||
const headerRow = worksheet.getRow(1)
|
||||
headerRow.height = 28
|
||||
headerRow.eachCell((cell) => {
|
||||
cell.font = { bold: true }
|
||||
cell.alignment = { vertical: 'middle', horizontal: 'center' }
|
||||
cell.fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFF2F2F2' },
|
||||
}
|
||||
cell.border = {
|
||||
bottom: { style: 'thin', color: { argb: 'FFD9D9D9' } },
|
||||
}
|
||||
})
|
||||
worksheet.getCell('E1').fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFE2F0D9' },
|
||||
}
|
||||
worksheet.getColumn(1).numFmt = '@'
|
||||
worksheet.getColumn(2).numFmt = '@'
|
||||
worksheet.getColumn(3).numFmt = '0'
|
||||
worksheet.getColumn(4).numFmt = '#,##0.00'
|
||||
worksheet.getColumn(5).numFmt = '#,##0.00'
|
||||
|
||||
const instructions = workbook.addWorksheet('填写说明')
|
||||
instructions.columns = [{ width: 100 }]
|
||||
for (const line of [
|
||||
'1、发货月份按月填写,例如 2026年11月;模板第二行为示例,请替换或删除后导入。',
|
||||
'2、订单号、出库数量(以实际为准)、预估货运费(货代+海运)为必填项。',
|
||||
'3、收入-减退税(CNY)和备注为选填项,收入-减退税允许填写负数。',
|
||||
'4、重复导入同一订单号时,以最后一次导入内容覆盖更新。',
|
||||
'5、单个文件最多 5000 行、不超过 10MB。',
|
||||
'6、不要填写公式,请粘贴为值。',
|
||||
]) {
|
||||
const row = instructions.addRow([line])
|
||||
row.alignment = { vertical: 'middle', wrapText: true }
|
||||
row.height = 26
|
||||
}
|
||||
return Buffer.from(await workbook.xlsx.writeBuffer())
|
||||
}
|
||||
51
furniture-3d-system/src/lib/external-profit.test.ts
Normal file
51
furniture-3d-system/src/lib/external-profit.test.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { buildExternalProfitRows } from './external-profit'
|
||||
import type { ExternalSalesDetailRow } from './external-sales'
|
||||
|
||||
const saleRow = {
|
||||
statsDate: '2026-11-10',
|
||||
finalShipAmount: 1000,
|
||||
afterSaleAmount: 100,
|
||||
goodsValue: 500,
|
||||
clearanceGoodsValue: 600,
|
||||
freight: 50,
|
||||
} as ExternalSalesDetailRow
|
||||
|
||||
describe('external profit', () => {
|
||||
it('calculates the cost-price dimension by shipment month', () => {
|
||||
const rows = buildExternalProfitRows({
|
||||
basis: 'cost',
|
||||
salesRows: [saleRow],
|
||||
freightRows: [{ shipMonth: '2026-11', estimatedFreight: 100 }],
|
||||
})
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
shipMonth: '2026-11',
|
||||
platform: '外贸',
|
||||
profitCenter: '外贸部',
|
||||
salesAmount: 1000,
|
||||
realPerformance: 1000,
|
||||
purchaseCost: 500,
|
||||
totalCost: 500,
|
||||
freight: 50,
|
||||
otherCourierFreight: 100,
|
||||
totalFreight: 150,
|
||||
grossProfit: 350,
|
||||
grossMargin: 350 / 1000,
|
||||
})
|
||||
})
|
||||
|
||||
it('uses clearance goods value in the clearance-price dimension', () => {
|
||||
const rows = buildExternalProfitRows({
|
||||
basis: 'clearance',
|
||||
salesRows: [saleRow],
|
||||
freightRows: [{ shipMonth: '2026-11', estimatedFreight: 100 }],
|
||||
})
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
purchaseCost: 600,
|
||||
totalCost: 600,
|
||||
grossProfit: 250,
|
||||
grossMargin: 250 / 1000,
|
||||
})
|
||||
})
|
||||
})
|
||||
96
furniture-3d-system/src/lib/external-profit.ts
Normal file
96
furniture-3d-system/src/lib/external-profit.ts
Normal file
@ -0,0 +1,96 @@
|
||||
import type { ExternalSalesDetailRow } from '@/lib/external-sales'
|
||||
|
||||
export type ExternalProfitBasis = 'cost' | 'clearance'
|
||||
|
||||
export type ExternalProfitFreightInput = {
|
||||
shipMonth: string
|
||||
estimatedFreight: number
|
||||
}
|
||||
|
||||
export type ExternalProfitRow = {
|
||||
shipMonth: string
|
||||
platform: '外贸'
|
||||
profitCenter: '外贸部'
|
||||
salesAmount: number
|
||||
realPerformance: number
|
||||
purchaseCost: number
|
||||
costAdjustment: number
|
||||
totalCost: number
|
||||
freight: number
|
||||
otherCourierFreight: number
|
||||
totalFreight: number
|
||||
installationFee: number
|
||||
grossProfit: number
|
||||
grossMargin: number
|
||||
}
|
||||
|
||||
function money(value: number) {
|
||||
return Math.round(value * 100) / 100
|
||||
}
|
||||
|
||||
export function buildExternalProfitRows(input: {
|
||||
basis: ExternalProfitBasis
|
||||
salesRows: readonly ExternalSalesDetailRow[]
|
||||
freightRows: readonly ExternalProfitFreightInput[]
|
||||
}): ExternalProfitRow[] {
|
||||
const otherFreightByMonth = new Map<string, number>()
|
||||
for (const row of input.freightRows) {
|
||||
otherFreightByMonth.set(
|
||||
row.shipMonth,
|
||||
(otherFreightByMonth.get(row.shipMonth) ?? 0) + row.estimatedFreight,
|
||||
)
|
||||
}
|
||||
|
||||
const grouped = new Map<string, {
|
||||
salesAmount: number
|
||||
purchaseCost: number
|
||||
freight: number
|
||||
}>()
|
||||
for (const row of input.salesRows) {
|
||||
const month = row.statsDate.slice(0, 7)
|
||||
const current = grouped.get(month) ?? {
|
||||
salesAmount: 0,
|
||||
purchaseCost: 0,
|
||||
freight: 0,
|
||||
}
|
||||
current.salesAmount += row.finalShipAmount
|
||||
current.purchaseCost += input.basis === 'clearance'
|
||||
? row.clearanceGoodsValue ?? 0
|
||||
: row.goodsValue ?? 0
|
||||
current.freight += row.freight ?? 0
|
||||
grouped.set(month, current)
|
||||
}
|
||||
|
||||
return [...grouped.entries()]
|
||||
.map(([shipMonth, values]): ExternalProfitRow => {
|
||||
const salesAmount = money(values.salesAmount)
|
||||
const realPerformance = salesAmount
|
||||
const purchaseCost = money(values.purchaseCost)
|
||||
const costAdjustment = 0
|
||||
const totalCost = money(purchaseCost + costAdjustment)
|
||||
const freight = money(values.freight)
|
||||
const otherCourierFreight = money(otherFreightByMonth.get(shipMonth) ?? 0)
|
||||
const totalFreight = money(freight + otherCourierFreight)
|
||||
const installationFee = 0
|
||||
const grossProfit = money(
|
||||
realPerformance - totalCost - totalFreight - installationFee,
|
||||
)
|
||||
return {
|
||||
shipMonth,
|
||||
platform: '外贸',
|
||||
profitCenter: '外贸部',
|
||||
salesAmount,
|
||||
realPerformance,
|
||||
purchaseCost,
|
||||
costAdjustment,
|
||||
totalCost,
|
||||
freight,
|
||||
otherCourierFreight,
|
||||
totalFreight,
|
||||
installationFee,
|
||||
grossProfit,
|
||||
grossMargin: realPerformance === 0 ? 0 : grossProfit / realPerformance,
|
||||
}
|
||||
})
|
||||
.sort((left, right) => right.shipMonth.localeCompare(left.shipMonth))
|
||||
}
|
||||
187
furniture-3d-system/src/lib/external-sales-export.test.ts
Normal file
187
furniture-3d-system/src/lib/external-sales-export.test.ts
Normal file
@ -0,0 +1,187 @@
|
||||
import {
|
||||
buildExternalSalesExportRows,
|
||||
createExternalSalesExportWorkbook,
|
||||
} from './external-sales-export'
|
||||
|
||||
describe('external sales export', () => {
|
||||
it('adds a summary total row', () => {
|
||||
const rows = buildExternalSalesExportRows('summary', [
|
||||
{
|
||||
month: '2026-10',
|
||||
orderNo: 'WM-001',
|
||||
shipAmount: 100,
|
||||
shipQty: 2,
|
||||
afterSaleAmount: 10,
|
||||
afterSaleQty: 1,
|
||||
finalShipAmount: 90,
|
||||
finalShipQty: 1,
|
||||
},
|
||||
{
|
||||
month: '2026-10',
|
||||
orderNo: 'WM-002',
|
||||
shipAmount: 250.5,
|
||||
shipQty: 3,
|
||||
afterSaleAmount: 20,
|
||||
afterSaleQty: 2,
|
||||
finalShipAmount: 230.5,
|
||||
finalShipQty: 1,
|
||||
},
|
||||
])
|
||||
|
||||
expect(rows.at(-1)).toEqual({
|
||||
月份: '合计',
|
||||
订单号: '',
|
||||
发货金额: 350.5,
|
||||
发货数量: 5,
|
||||
售后金额: 30,
|
||||
售后数量: 3,
|
||||
最终发货金额: 320.5,
|
||||
最终发货数量: 2,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the visible detail fields in the exported rows', () => {
|
||||
const rows = buildExternalSalesExportRows('detail', [{
|
||||
sendDate: '2026-10-17 16:56:22',
|
||||
orderNo: 'WM-001',
|
||||
oId: '9807341',
|
||||
shippingCourier: '中铁物流',
|
||||
trackingNo: '119033220001',
|
||||
shopName: '外贸日常店铺',
|
||||
skuId: 'SKU-001',
|
||||
itemId: 'ITEM-001',
|
||||
shopSkuId: 'SHOP-SKU-001',
|
||||
shopItemId: 'SHOP-ITEM-001',
|
||||
itemName: '测试商品',
|
||||
propertiesValue: '原木色',
|
||||
qty: 2,
|
||||
amount: 100,
|
||||
afterSaleAmount: 20,
|
||||
afterSaleQty: 1,
|
||||
finalShipAmount: 80,
|
||||
finalShipQty: 1,
|
||||
costPrice: 30,
|
||||
goodsValue: 30,
|
||||
clearancePrice: 35,
|
||||
clearanceGoodsValue: 35,
|
||||
freight: 12.5,
|
||||
statusLabel: '已发货',
|
||||
orderDate: '2026-10-16 10:00:00',
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
订单号: 'WM-001',
|
||||
内部单号: '9807341',
|
||||
成本: 30,
|
||||
货值: 30,
|
||||
清货价: 35,
|
||||
清货货值: 35,
|
||||
运费: 12.5,
|
||||
'发货金额(已付)': 100,
|
||||
售后金额: 20,
|
||||
售后数量: 1,
|
||||
最终发货金额: 80,
|
||||
最终发货数量: 1,
|
||||
清货货值: 35,
|
||||
运费: 12.5,
|
||||
})
|
||||
expect(rows.at(-1)).toMatchObject({
|
||||
发货时间: '合计',
|
||||
发货数量: 2,
|
||||
售后数量: 1,
|
||||
最终发货数量: 1,
|
||||
货值: 30,
|
||||
})
|
||||
})
|
||||
|
||||
it('omits empty shop code columns from detail exports', () => {
|
||||
const rows = buildExternalSalesExportRows('detail', [{
|
||||
shopSkuId: '',
|
||||
shopItemId: '',
|
||||
}])
|
||||
|
||||
expect(rows[0]).not.toHaveProperty('店铺商品编码')
|
||||
expect(rows[0]).not.toHaveProperty('店铺款式编码')
|
||||
})
|
||||
|
||||
it('exports freight rows with the screenshot headers', () => {
|
||||
const rows = buildExternalSalesExportRows('freight', [{
|
||||
shipMonth: '2026-11',
|
||||
orderNo: 'WM-001',
|
||||
outboundQty: 10,
|
||||
incomeAfterTaxRefund: 100,
|
||||
estimatedFreight: 20,
|
||||
remark: '',
|
||||
}])
|
||||
|
||||
expect(rows[0]).toEqual({
|
||||
发货月份: '2026年11月',
|
||||
订单号: 'WM-001',
|
||||
'出库数量(以实际为准)': 10,
|
||||
'收入-减退税(CNY)': 100,
|
||||
'预估货运费(货代+海运)': 20,
|
||||
备注: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('exports clearance price from external order cost rows', () => {
|
||||
const rows = buildExternalSalesExportRows('clearance', [{
|
||||
orderNo: 'WM-001',
|
||||
itemCode: 'SKU-001',
|
||||
costPrice: 18.5,
|
||||
clearancePrice: 18.5,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toEqual({
|
||||
订单号: 'WM-001',
|
||||
商品编码: 'SKU-001',
|
||||
成本价: 18.5,
|
||||
清货价: 18.5,
|
||||
})
|
||||
})
|
||||
|
||||
it('exports both profit dimensions with all requested headers', () => {
|
||||
const rows = buildExternalSalesExportRows('profit', [{
|
||||
shipMonth: '2026-11',
|
||||
platform: '外贸',
|
||||
profitCenter: '外贸部',
|
||||
salesAmount: 1000,
|
||||
realPerformance: 1000,
|
||||
purchaseCost: 500,
|
||||
costAdjustment: 0,
|
||||
totalCost: 500,
|
||||
freight: 50,
|
||||
otherCourierFreight: 100,
|
||||
totalFreight: 150,
|
||||
installationFee: 0,
|
||||
grossProfit: 350,
|
||||
grossMargin: 350 / 1000,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
发货月份: '2026-11',
|
||||
平台: '外贸',
|
||||
利润中心: '外贸部',
|
||||
销售金额: 1000,
|
||||
真实业绩: 1000,
|
||||
采购成本: 500,
|
||||
总成本: 500,
|
||||
运费: 50,
|
||||
其他快递运费: 100,
|
||||
总运费: 150,
|
||||
毛利额: 350,
|
||||
毛利率: '35.00%',
|
||||
})
|
||||
})
|
||||
|
||||
it('builds an xlsx workbook for an empty pending page', async () => {
|
||||
const result = await createExternalSalesExportWorkbook({
|
||||
view: 'freight',
|
||||
rows: [],
|
||||
now: new Date('2026-11-16T02:03:04.000Z'),
|
||||
})
|
||||
|
||||
expect(result.fileName).toMatch(/^外销销量-货代费-20261116-/)
|
||||
expect(result.bytes.byteLength).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
223
furniture-3d-system/src/lib/external-sales-export.ts
Normal file
223
furniture-3d-system/src/lib/external-sales-export.ts
Normal file
@ -0,0 +1,223 @@
|
||||
import type {
|
||||
ExternalSalesAfterSaleRow,
|
||||
ExternalSalesDetailRow,
|
||||
ExternalSalesSummaryRow,
|
||||
} from '@/lib/external-sales'
|
||||
import type { ExternalFreightRecordView } from '@/lib/external-freight'
|
||||
import type { ExternalClearancePriceRow } from '@/lib/external-clearance-price'
|
||||
import type { ExternalProfitRow } from '@/lib/external-profit'
|
||||
|
||||
export type ExternalSalesExportView =
|
||||
| 'summary'
|
||||
| 'detail'
|
||||
| 'afterSale'
|
||||
| 'freight'
|
||||
| 'clearance'
|
||||
| 'profit'
|
||||
|
||||
type ExportCell = string | number
|
||||
type ExportRow = Record<string, ExportCell>
|
||||
|
||||
const VIEW_LABELS: Record<ExternalSalesExportView, string> = {
|
||||
summary: '汇总',
|
||||
detail: '明细',
|
||||
afterSale: '售后明细',
|
||||
freight: '货代费',
|
||||
clearance: '清货价',
|
||||
profit: '毛利',
|
||||
}
|
||||
|
||||
function roundMoney(value: number) {
|
||||
return Math.round(value * 100) / 100
|
||||
}
|
||||
|
||||
export function buildExternalSalesExportRows(
|
||||
view: ExternalSalesExportView,
|
||||
rows: readonly unknown[],
|
||||
): ExportRow[] {
|
||||
if (view === 'summary') {
|
||||
const summaryRows = rows as ExternalSalesSummaryRow[]
|
||||
const data = summaryRows.map((row) => ({
|
||||
月份: row.month,
|
||||
订单号: row.orderNo,
|
||||
发货金额: row.shipAmount,
|
||||
发货数量: row.shipQty,
|
||||
售后金额: row.afterSaleAmount,
|
||||
售后数量: row.afterSaleQty,
|
||||
最终发货金额: row.finalShipAmount,
|
||||
最终发货数量: row.finalShipQty,
|
||||
}))
|
||||
if (data.length === 0) return []
|
||||
return [...data, {
|
||||
月份: '合计',
|
||||
订单号: '',
|
||||
发货金额: roundMoney(data.reduce((sum, row) => sum + row.发货金额, 0)),
|
||||
发货数量: data.reduce((sum, row) => sum + row.发货数量, 0),
|
||||
售后金额: roundMoney(data.reduce((sum, row) => sum + row.售后金额, 0)),
|
||||
售后数量: data.reduce((sum, row) => sum + row.售后数量, 0),
|
||||
最终发货金额: roundMoney(data.reduce((sum, row) => sum + row.最终发货金额, 0)),
|
||||
最终发货数量: data.reduce((sum, row) => sum + row.最终发货数量, 0),
|
||||
}]
|
||||
}
|
||||
|
||||
if (view === 'detail') {
|
||||
const detailRows = rows as ExternalSalesDetailRow[]
|
||||
const hasShopSkuId = detailRows.some((row) => row.shopSkuId.trim().length > 0)
|
||||
const hasShopItemId = detailRows.some((row) => row.shopItemId.trim().length > 0)
|
||||
const data: ExportRow[] = detailRows.map((row) => ({
|
||||
发货时间: row.sendDate,
|
||||
订单号: row.orderNo,
|
||||
内部单号: row.oId,
|
||||
发货快递: row.shippingCourier,
|
||||
运单号: row.trackingNo,
|
||||
店铺名称: row.shopName,
|
||||
原始商品编码: row.skuId,
|
||||
款式编码: row.itemId,
|
||||
...(hasShopSkuId ? { 店铺商品编码: row.shopSkuId } : {}),
|
||||
...(hasShopItemId ? { 店铺款式编码: row.shopItemId } : {}),
|
||||
商品名称: row.itemName,
|
||||
属性: row.propertiesValue,
|
||||
发货数量: row.qty,
|
||||
'发货金额(已付)': row.amount,
|
||||
售后金额: row.afterSaleAmount,
|
||||
售后数量: row.afterSaleQty,
|
||||
最终发货金额: row.finalShipAmount,
|
||||
最终发货数量: row.finalShipQty,
|
||||
成本: row.costPrice ?? '',
|
||||
货值: row.goodsValue ?? '',
|
||||
清货价: row.clearancePrice ?? '',
|
||||
清货货值: row.clearanceGoodsValue ?? '',
|
||||
运费: row.freight ?? '',
|
||||
明细状态: row.statusLabel,
|
||||
下单时间: row.orderDate,
|
||||
}))
|
||||
if (data.length === 0) return []
|
||||
return [...data, {
|
||||
发货时间: '合计',
|
||||
订单号: '',
|
||||
内部单号: '',
|
||||
发货快递: '',
|
||||
运单号: '',
|
||||
店铺名称: '',
|
||||
原始商品编码: '',
|
||||
款式编码: '',
|
||||
...(hasShopSkuId ? { 店铺商品编码: '' } : {}),
|
||||
...(hasShopItemId ? { 店铺款式编码: '' } : {}),
|
||||
商品名称: '',
|
||||
属性: '',
|
||||
发货数量: detailRows.reduce((sum, row) => sum + row.qty, 0),
|
||||
'发货金额(已付)': roundMoney(detailRows.reduce((sum, row) => sum + row.amount, 0)),
|
||||
售后金额: roundMoney(detailRows.reduce((sum, row) => sum + row.afterSaleAmount, 0)),
|
||||
售后数量: detailRows.reduce((sum, row) => sum + row.afterSaleQty, 0),
|
||||
最终发货金额: roundMoney(detailRows.reduce((sum, row) => sum + row.finalShipAmount, 0)),
|
||||
最终发货数量: detailRows.reduce((sum, row) => sum + row.finalShipQty, 0),
|
||||
成本: '',
|
||||
货值: roundMoney(detailRows.reduce((sum, row) => sum + (row.goodsValue ?? 0), 0)),
|
||||
清货价: '',
|
||||
清货货值: roundMoney(
|
||||
detailRows.reduce((sum, row) => sum + (row.clearanceGoodsValue ?? 0), 0),
|
||||
),
|
||||
运费: roundMoney(detailRows.reduce((sum, row) => sum + (row.freight ?? 0), 0)),
|
||||
明细状态: '',
|
||||
下单时间: '',
|
||||
}]
|
||||
}
|
||||
|
||||
if (view === 'afterSale') {
|
||||
return (rows as ExternalSalesAfterSaleRow[]).map((row) => ({
|
||||
售后日期: row.asDate,
|
||||
店铺名称: row.shopName,
|
||||
原订单号: row.orderNo,
|
||||
商品编码: row.skuId,
|
||||
售后数量: row.qty,
|
||||
售后金额: row.refundAmount,
|
||||
}))
|
||||
}
|
||||
|
||||
if (view === 'freight') {
|
||||
return (rows as ExternalFreightRecordView[]).map((row) => ({
|
||||
发货月份: /^\d{4}-\d{2}$/.test(row.shipMonth)
|
||||
? `${row.shipMonth.slice(0, 4)}年${Number(row.shipMonth.slice(5, 7))}月`
|
||||
: row.shipMonth,
|
||||
订单号: row.orderNo,
|
||||
'出库数量(以实际为准)': row.outboundQty,
|
||||
'收入-减退税(CNY)': row.incomeAfterTaxRefund ?? '',
|
||||
'预估货运费(货代+海运)': row.estimatedFreight,
|
||||
备注: row.remark,
|
||||
}))
|
||||
}
|
||||
|
||||
if (view === 'clearance') {
|
||||
return (rows as ExternalClearancePriceRow[]).map((row) => ({
|
||||
订单号: row.orderNo,
|
||||
商品编码: row.itemCode,
|
||||
成本价: row.costPrice,
|
||||
清货价: row.clearancePrice,
|
||||
}))
|
||||
}
|
||||
|
||||
if (view === 'profit') {
|
||||
return (rows as ExternalProfitRow[]).map((row) => ({
|
||||
发货月份: row.shipMonth,
|
||||
平台: row.platform,
|
||||
利润中心: row.profitCenter,
|
||||
销售金额: row.salesAmount,
|
||||
真实业绩: row.realPerformance,
|
||||
采购成本: row.purchaseCost,
|
||||
成本调整: row.costAdjustment,
|
||||
总成本: row.totalCost,
|
||||
运费: row.freight,
|
||||
其他快递运费: row.otherCourierFreight,
|
||||
总运费: row.totalFreight,
|
||||
安装费: row.installationFee,
|
||||
毛利额: row.grossProfit,
|
||||
毛利率: `${(row.grossMargin * 100).toFixed(2)}%`,
|
||||
}))
|
||||
}
|
||||
|
||||
return [{
|
||||
页面: VIEW_LABELS[view],
|
||||
数据状态: '暂无数据',
|
||||
}]
|
||||
}
|
||||
|
||||
function exportTimestamp(value: Date) {
|
||||
const parts = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).formatToParts(value)
|
||||
const part = (type: Intl.DateTimeFormatPartTypes) => (
|
||||
parts.find((item) => item.type === type)?.value ?? ''
|
||||
)
|
||||
return `${part('year')}${part('month')}${part('day')}-${part('hour')}${part('minute')}${part('second')}`
|
||||
}
|
||||
|
||||
export async function createExternalSalesExportWorkbook(input: {
|
||||
view: ExternalSalesExportView
|
||||
rows: readonly unknown[]
|
||||
now?: Date
|
||||
}) {
|
||||
const XLSX = await import('xlsx')
|
||||
const exportRows = buildExternalSalesExportRows(input.view, input.rows)
|
||||
const sheetRows = exportRows.length > 0
|
||||
? exportRows
|
||||
: [{ 页面: VIEW_LABELS[input.view], 数据状态: '暂无数据' }]
|
||||
const worksheet = XLSX.utils.json_to_sheet(sheetRows)
|
||||
const headers = Object.keys(sheetRows[0] ?? {})
|
||||
worksheet['!cols'] = headers.map((header) => ({
|
||||
wch: Math.min(42, Math.max(12, header.length * 2 + 2)),
|
||||
}))
|
||||
const workbook = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, VIEW_LABELS[input.view])
|
||||
const bytes = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }) as ArrayBuffer
|
||||
return {
|
||||
bytes,
|
||||
fileName: `外销销量-${VIEW_LABELS[input.view]}-${exportTimestamp(input.now ?? new Date())}.xlsx`,
|
||||
}
|
||||
}
|
||||
338
furniture-3d-system/src/lib/external-sales.test.ts
Normal file
338
furniture-3d-system/src/lib/external-sales.test.ts
Normal file
@ -0,0 +1,338 @@
|
||||
import {
|
||||
allocateExternalSalesPaidAmounts,
|
||||
applyExternalSalesAfterSaleMetrics,
|
||||
applyExternalSalesClearancePrices,
|
||||
applyExternalSalesFreight,
|
||||
buildExternalSalesDetailAfterSaleMetricsSql,
|
||||
buildExternalSalesAfterSaleMetricsSql,
|
||||
buildExternalSalesAfterSaleWhereSql,
|
||||
buildExternalSalesSourceSql,
|
||||
buildExternalSalesSummary,
|
||||
buildExternalSalesWaybillFreightSql,
|
||||
enrichExternalSalesItemCosts,
|
||||
externalSalesMonthRange,
|
||||
filterExternalSalesItems,
|
||||
parseExternalSalesDetailFilters,
|
||||
resolveExternalSalesTargetShop,
|
||||
toExternalSalesDetailRows,
|
||||
type ExternalSalesItemRow,
|
||||
} from './external-sales'
|
||||
|
||||
function item(overrides: Partial<ExternalSalesItemRow> = {}): ExternalSalesItemRow {
|
||||
return {
|
||||
sourceType: 'QMCUST',
|
||||
oId: '1',
|
||||
oiId: '11',
|
||||
orderNo: 'WM-001',
|
||||
shopName: '外贸日常店铺',
|
||||
shippingCourier: '',
|
||||
trackingNo: '',
|
||||
shipmentWeight: null,
|
||||
shippingUnitWeight: null,
|
||||
shippingWeight: null,
|
||||
freight: null,
|
||||
statsDate: '2026-11-06',
|
||||
orderDate: '2026-11-06 10:00:00',
|
||||
sendDate: '2026-11-07 11:00:00',
|
||||
orderStatus: 'Sent',
|
||||
itemStatus: '',
|
||||
ownerName: '张三',
|
||||
localItemId: '10',
|
||||
skuId: 'SKU-001',
|
||||
itemId: 'ITEM-001',
|
||||
shopSkuId: 'SHOP-SKU-001',
|
||||
shopItemId: 'SHOP-ITEM-001',
|
||||
propertiesValue: '原木色',
|
||||
itemName: '测试商品',
|
||||
basePrice: 120,
|
||||
price: 100,
|
||||
qty: 2,
|
||||
amount: 200,
|
||||
afterSaleAmount: 0,
|
||||
afterSaleQty: 0,
|
||||
finalShipAmount: 200,
|
||||
finalShipQty: 2,
|
||||
orderPaidAmount: null,
|
||||
outerOiId: 'OUTER-001',
|
||||
costPrice: null,
|
||||
goodsValue: null,
|
||||
clearancePrice: null,
|
||||
clearanceGoodsValue: null,
|
||||
refundStatus: '',
|
||||
refundQty: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('external sales', () => {
|
||||
it('normalizes underscore and hyphen shop-name variants', () => {
|
||||
expect(resolveExternalSalesTargetShop('阿里巴巴_外贸部欧伯娜导单专用店铺'))
|
||||
.toBe('阿里巴巴-外贸部欧伯娜导单专用店铺')
|
||||
expect(resolveExternalSalesTargetShop(' 外贸日常店铺 ')).toBe('外贸日常店铺')
|
||||
expect(resolveExternalSalesTargetShop('其他店铺')).toBeNull()
|
||||
})
|
||||
|
||||
it('groups shipped lines by month and order number', () => {
|
||||
const rows = buildExternalSalesSummary([
|
||||
item(),
|
||||
item({ oiId: '12', qty: 1, amount: 100, skuId: 'SKU-002' }),
|
||||
item({ oiId: '13', orderNo: 'WM-002', ownerName: '' }),
|
||||
], [{
|
||||
orderNo: 'wm-001',
|
||||
afterSaleAmount: 80,
|
||||
afterSaleQty: 2,
|
||||
}])
|
||||
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
month: '2026-11',
|
||||
orderNo: 'WM-001',
|
||||
shipAmount: 300,
|
||||
shipQty: 3,
|
||||
afterSaleAmount: 80,
|
||||
afterSaleQty: 2,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
orderNo: 'WM-002',
|
||||
afterSaleAmount: 0,
|
||||
afterSaleQty: 0,
|
||||
}),
|
||||
])
|
||||
expect(toExternalSalesDetailRows([item()])[0]).toMatchObject({
|
||||
orderNo: 'WM-001',
|
||||
statusLabel: '已发货',
|
||||
})
|
||||
})
|
||||
|
||||
it('applies configurable detail filters to their specific fields', () => {
|
||||
const rows = [
|
||||
item(),
|
||||
item({
|
||||
oId: '2',
|
||||
oiId: '12',
|
||||
orderNo: 'WM-002',
|
||||
skuId: 'SKU-002',
|
||||
itemId: 'ITEM-002',
|
||||
itemName: '另一件商品',
|
||||
propertiesValue: '胡桃色',
|
||||
}),
|
||||
]
|
||||
|
||||
expect(filterExternalSalesItems(rows, '', {
|
||||
skuId: 'SKU-002',
|
||||
})).toEqual([expect.objectContaining({ orderNo: 'WM-002' })])
|
||||
expect(filterExternalSalesItems(rows, '', {
|
||||
itemId: 'ITEM-001',
|
||||
})).toEqual([expect.objectContaining({ orderNo: 'WM-001' })])
|
||||
expect(filterExternalSalesItems(rows, '', {
|
||||
internalOrderNo: '2',
|
||||
})).toEqual([expect.objectContaining({ orderNo: 'WM-002' })])
|
||||
expect(parseExternalSalesDetailFilters(JSON.stringify({
|
||||
orderNo: ' WM-001 ',
|
||||
itemId: ' ITEM-001 ',
|
||||
}))).toEqual({
|
||||
orderNo: 'WM-001',
|
||||
itemId: 'ITEM-001',
|
||||
})
|
||||
expect(parseExternalSalesDetailFilters(JSON.stringify({ unknown: 'x' }))).toBeNull()
|
||||
})
|
||||
|
||||
it('enriches detail rows with archive cost and calculates goods value', () => {
|
||||
const rows = enrichExternalSalesItemCosts([
|
||||
item({ skuId: 'sku-001', qty: 3 }),
|
||||
item({ skuId: 'MISSING', qty: 5 }),
|
||||
], [{
|
||||
barcode: 'SKU-001',
|
||||
costPrice: 12.5,
|
||||
unitWeight: null,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
costPrice: 12.5,
|
||||
goodsValue: 37.5,
|
||||
})
|
||||
expect(rows[1]).toMatchObject({
|
||||
costPrice: null,
|
||||
goodsValue: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('allocates each order paid amount across its detail rows', () => {
|
||||
const rows = allocateExternalSalesPaidAmounts([
|
||||
item({ amount: 100, orderPaidAmount: 260 }),
|
||||
item({ oiId: '12', amount: 300, orderPaidAmount: 260 }),
|
||||
item({ oId: '2', amount: 88, orderPaidAmount: null }),
|
||||
])
|
||||
|
||||
expect(rows.map((row) => row.amount)).toEqual([65, 195, 88])
|
||||
})
|
||||
|
||||
it('matches after-sales by order number and item code and calculates final shipment', () => {
|
||||
const rows = applyExternalSalesAfterSaleMetrics([
|
||||
item({ qty: 3, amount: 300, costPrice: 20 }),
|
||||
item({ oiId: '12', qty: 1, amount: 100, costPrice: 20 }),
|
||||
item({ skuId: 'SKU-OTHER', qty: 2, amount: 50, costPrice: 20 }),
|
||||
], [{
|
||||
orderNo: 'wm-001',
|
||||
skuId: 'sku-001',
|
||||
afterSaleAmount: 80,
|
||||
afterSaleQty: 2,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
afterSaleAmount: 60,
|
||||
afterSaleQty: 2,
|
||||
finalShipAmount: 240,
|
||||
finalShipQty: 1,
|
||||
goodsValue: 20,
|
||||
})
|
||||
expect(rows[1]).toMatchObject({
|
||||
afterSaleAmount: 20,
|
||||
afterSaleQty: 0,
|
||||
finalShipAmount: 80,
|
||||
finalShipQty: 1,
|
||||
goodsValue: 20,
|
||||
})
|
||||
expect(rows[2]).toMatchObject({
|
||||
afterSaleAmount: 0,
|
||||
afterSaleQty: 0,
|
||||
finalShipAmount: 50,
|
||||
finalShipQty: 2,
|
||||
goodsValue: 40,
|
||||
})
|
||||
const sql = buildExternalSalesDetailAfterSaleMetricsSql(['WM-001'])
|
||||
expect(sql).toContain('h.so_id AS order_no, i.sku_id')
|
||||
expect(sql).toContain('GROUP BY h.so_id, i.sku_id')
|
||||
})
|
||||
|
||||
it('allocates waybill freight by detail weight and makes self-pickup free', () => {
|
||||
const rows = applyExternalSalesFreight([
|
||||
item({
|
||||
oId: '1',
|
||||
oiId: '11',
|
||||
shippingCourier: '中铁物流',
|
||||
trackingNo: 'WAYBILL-A',
|
||||
shippingUnitWeight: 1,
|
||||
qty: 2,
|
||||
}),
|
||||
item({
|
||||
oId: '1',
|
||||
oiId: '12',
|
||||
shippingCourier: '中铁物流',
|
||||
trackingNo: 'WAYBILL-A',
|
||||
shippingUnitWeight: 1,
|
||||
qty: 2,
|
||||
}),
|
||||
item({
|
||||
oId: '2',
|
||||
oiId: '21',
|
||||
shippingCourier: '自提自送',
|
||||
trackingNo: 'PICKUP-B',
|
||||
shipmentWeight: 10,
|
||||
qty: 3,
|
||||
}),
|
||||
], [{
|
||||
trackingNo: 'WAYBILL-A',
|
||||
freightCost: 20,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({ shippingWeight: 2, freight: 10 })
|
||||
expect(rows[1]).toMatchObject({ shippingWeight: 2, freight: 10 })
|
||||
expect(rows[2]).toMatchObject({ shippingWeight: 10, freight: 0 })
|
||||
|
||||
const sql = buildExternalSalesWaybillFreightSql(['WAYBILL-A'])
|
||||
expect(sql).toContain('JianSun.dbo.fys_jstFreightCost')
|
||||
expect(sql).toContain('freightCost')
|
||||
expect(sql).toContain("IN (N'WAYBILL-A')")
|
||||
})
|
||||
|
||||
it('uses clearance price by order and code and falls back to cost price', () => {
|
||||
const rows = applyExternalSalesClearancePrices([
|
||||
item({ orderNo: 'WM-001', skuId: 'SKU-001', finalShipQty: 3, costPrice: 10 }),
|
||||
item({ orderNo: 'WM-001', skuId: 'SKU-002', finalShipQty: 2, costPrice: 12 }),
|
||||
], [{
|
||||
orderNo: 'wm-001',
|
||||
itemCode: 'sku-001',
|
||||
costPrice: 20,
|
||||
clearancePrice: 20,
|
||||
}])
|
||||
|
||||
expect(rows[0]).toMatchObject({
|
||||
clearancePrice: 20,
|
||||
clearanceGoodsValue: 60,
|
||||
})
|
||||
expect(rows[1]).toMatchObject({
|
||||
clearancePrice: 12,
|
||||
clearanceGoodsValue: 24,
|
||||
})
|
||||
})
|
||||
|
||||
it('builds the two source queries with shipped-only filtering', () => {
|
||||
const sql = buildExternalSalesSourceSql({
|
||||
dateFrom: '2026-11-01',
|
||||
dateTo: '2026-11-13',
|
||||
})
|
||||
|
||||
expect(sql).toContain('JianSun.dbo.jst_Orders')
|
||||
expect(sql).toContain('JianSun.dbo.jst_orderitem')
|
||||
expect(sql).toContain('JianSun.dbo.jst_qmcust_orderlist')
|
||||
expect(sql).toContain('JianSun.dbo.jst_qmcust_orderlist_item')
|
||||
expect(sql).toContain('阿里巴巴-外贸部欧伯娜导单专用店铺')
|
||||
expect(sql).toContain('外贸日常店铺')
|
||||
expect(sql).toContain("= N'SENT'")
|
||||
expect(sql).toContain("<> N'REPLACED'")
|
||||
expect(sql).toContain('ISNULL(i.qty, 0) > 0')
|
||||
expect(sql).toContain('o.send_date >= CONVERT(datetime2')
|
||||
expect(sql).toContain("CONVERT(varchar(10), o.send_date, 23) AS stats_date")
|
||||
expect(sql).toContain('o.paid_amount')
|
||||
expect(sql).toContain('o.logistics_company')
|
||||
expect(sql).toContain('o.l_id')
|
||||
expect(sql).toContain('o.weight AS shipment_weight')
|
||||
expect(sql.length).toBeLessThan(8000)
|
||||
|
||||
const unfiltered = buildExternalSalesSourceSql({
|
||||
sourceTypes: ['QMCUST'],
|
||||
})
|
||||
expect(unfiltered).not.toContain('AND o.send_date >=')
|
||||
expect(unfiltered).not.toContain('AND o.send_date <')
|
||||
})
|
||||
|
||||
it('builds after-sale filters against Jushuitan external-store data', () => {
|
||||
const whereSql = buildExternalSalesAfterSaleWhereSql({
|
||||
dateFrom: '2026-11-01',
|
||||
dateTo: '2026-11-13',
|
||||
shopName: '外贸日常店铺',
|
||||
orderNo: 'WM20261106132001PG',
|
||||
itemCode: 'CJ003166N68V01',
|
||||
})
|
||||
expect(whereSql).toContain("h.shop_name IN (N'外贸日常店铺')")
|
||||
expect(whereSql).toContain("h.as_date >= CONVERT(datetime2, '2026-11-01', 23)")
|
||||
expect(whereSql).toContain("h.as_date < DATEADD(day, 1, CONVERT(datetime2, '2026-11-13', 23))")
|
||||
expect(whereSql).toContain("h.so_id LIKE N'%WM20261106132001PG%'")
|
||||
expect(whereSql).toContain("i.sku_id LIKE N'%CJ003166N68V01%'")
|
||||
|
||||
const metricsSql = buildExternalSalesAfterSaleMetricsSql([
|
||||
'wm261008LHCV',
|
||||
'wm261009LHCV',
|
||||
])
|
||||
expect(metricsSql).toContain('JianSun.dbo.jst_qmcust_refundlist')
|
||||
expect(metricsSql).toContain('JianSun.dbo.jst_qmcust_refundlist_item')
|
||||
expect(metricsSql).toContain('i.as_id = h.as_id')
|
||||
expect(metricsSql).toContain('阿里巴巴-外贸部欧伯娜导单专用店铺')
|
||||
expect(metricsSql).toContain('外贸日常店铺')
|
||||
expect(metricsSql).toContain("h.so_id IN (N'wm261008LHCV', N'wm261009LHCV')")
|
||||
expect(metricsSql).not.toContain('dwd_jst_refund_data_di')
|
||||
})
|
||||
|
||||
it('converts a selected summary month to an inclusive month range', () => {
|
||||
expect(externalSalesMonthRange('2026-10')).toEqual({
|
||||
dateFrom: '2026-10-01',
|
||||
dateTo: '2026-10-31',
|
||||
})
|
||||
expect(externalSalesMonthRange('2027-01')).toEqual({
|
||||
dateFrom: '2027-01-01',
|
||||
dateTo: '2027-01-31',
|
||||
})
|
||||
expect(externalSalesMonthRange('2026-13')).toBeNull()
|
||||
})
|
||||
})
|
||||
854
furniture-3d-system/src/lib/external-sales.ts
Normal file
854
furniture-3d-system/src/lib/external-sales.ts
Normal file
@ -0,0 +1,854 @@
|
||||
import type { ExternalClearancePriceRow } from '@/lib/external-clearance-price'
|
||||
|
||||
export const EXTERNAL_SALES_TARGET_SHOPS = [
|
||||
'阿里巴巴-外贸部欧伯娜导单专用店铺',
|
||||
'外贸日常店铺',
|
||||
] as const
|
||||
|
||||
export type ExternalSalesTargetShop = (typeof EXTERNAL_SALES_TARGET_SHOPS)[number]
|
||||
export type ExternalSalesView = 'summary' | 'detail' | 'afterSale'
|
||||
|
||||
export const EXTERNAL_SALES_TARGET_SHOP_ALIASES: Record<ExternalSalesTargetShop, readonly string[]> = {
|
||||
'阿里巴巴-外贸部欧伯娜导单专用店铺': [
|
||||
'阿里巴巴-外贸部欧伯娜导单专用店铺',
|
||||
'阿里巴巴_外贸部欧伯娜导单专用店铺',
|
||||
],
|
||||
'外贸日常店铺': ['外贸日常店铺'],
|
||||
}
|
||||
|
||||
function externalSalesShopKey(value: string) {
|
||||
return value.trim().replaceAll(/[_\-\s]/g, '').toUpperCase()
|
||||
}
|
||||
|
||||
export function resolveExternalSalesTargetShop(value: string): ExternalSalesTargetShop | null {
|
||||
const key = externalSalesShopKey(value)
|
||||
return EXTERNAL_SALES_TARGET_SHOPS.find((shop) => (
|
||||
EXTERNAL_SALES_TARGET_SHOP_ALIASES[shop].some((alias) => externalSalesShopKey(alias) === key)
|
||||
)) ?? null
|
||||
}
|
||||
|
||||
export type ExternalSalesItemRow = {
|
||||
sourceType: 'OTHER' | 'QMCUST'
|
||||
oId: string
|
||||
oiId: string
|
||||
orderNo: string
|
||||
shopName: ExternalSalesTargetShop
|
||||
shippingCourier: string
|
||||
trackingNo: string
|
||||
shipmentWeight: number | null
|
||||
shippingUnitWeight: number | null
|
||||
shippingWeight: number | null
|
||||
freight: number | null
|
||||
statsDate: string
|
||||
orderDate: string
|
||||
sendDate: string
|
||||
orderStatus: string
|
||||
itemStatus: string
|
||||
ownerName: string
|
||||
localItemId: string
|
||||
skuId: string
|
||||
itemId: string
|
||||
shopSkuId: string
|
||||
shopItemId: string
|
||||
propertiesValue: string
|
||||
itemName: string
|
||||
basePrice: number
|
||||
price: number
|
||||
qty: number
|
||||
amount: number
|
||||
afterSaleAmount: number
|
||||
afterSaleQty: number
|
||||
finalShipAmount: number
|
||||
finalShipQty: number
|
||||
orderPaidAmount: number | null
|
||||
outerOiId: string
|
||||
costPrice: number | null
|
||||
goodsValue: number | null
|
||||
clearancePrice: number | null
|
||||
clearanceGoodsValue: number | null
|
||||
refundStatus: string
|
||||
refundQty: number
|
||||
}
|
||||
|
||||
export type ExternalSalesSummaryRow = {
|
||||
month: string
|
||||
orderNo: string
|
||||
shipAmount: number
|
||||
shipQty: number
|
||||
afterSaleAmount: number
|
||||
afterSaleQty: number
|
||||
finalShipAmount: number
|
||||
finalShipQty: number
|
||||
}
|
||||
|
||||
export type ExternalSalesDetailRow = ExternalSalesItemRow & {
|
||||
statusLabel: '已发货'
|
||||
}
|
||||
|
||||
export type ExternalSalesAfterSaleRow = {
|
||||
asId: string
|
||||
outerAsId: string
|
||||
orderNo: string
|
||||
shopName: string
|
||||
asDate: string
|
||||
afterSaleStatus: string
|
||||
afterSaleType: string
|
||||
refundPhase: string
|
||||
goodsStatus: string
|
||||
creatorName: string
|
||||
questionType: string
|
||||
buyerApplyRefund: number
|
||||
refundAmount: number
|
||||
receiveRefund: number
|
||||
confirmDate: string
|
||||
localItemId: string
|
||||
skuId: string
|
||||
itemId: string
|
||||
shopSkuId: string
|
||||
itemName: string
|
||||
propertiesValue: string
|
||||
qty: number
|
||||
returnedQty: number
|
||||
amount: number
|
||||
remark: string
|
||||
}
|
||||
|
||||
export type ExternalSalesAfterSaleMetric = {
|
||||
orderNo: string
|
||||
afterSaleAmount: number
|
||||
afterSaleQty: number
|
||||
}
|
||||
|
||||
export type ExternalSalesDetailAfterSaleMetric = {
|
||||
orderNo: string
|
||||
skuId: string
|
||||
afterSaleAmount: number
|
||||
afterSaleQty: number
|
||||
}
|
||||
|
||||
export type ExternalSalesArchiveCost = {
|
||||
barcode: string
|
||||
costPrice: number | null
|
||||
unitWeight: number | null
|
||||
}
|
||||
|
||||
export type ExternalSalesWaybillFreight = {
|
||||
trackingNo: string
|
||||
freightCost: number
|
||||
}
|
||||
|
||||
export const EXTERNAL_SALES_DETAIL_FILTER_KEYS = [
|
||||
'orderNo',
|
||||
'internalOrderNo',
|
||||
'shippingCourier',
|
||||
'trackingNo',
|
||||
'skuId',
|
||||
'itemId',
|
||||
'orderDate',
|
||||
] as const
|
||||
|
||||
export type ExternalSalesDetailFilterKey = (typeof EXTERNAL_SALES_DETAIL_FILTER_KEYS)[number]
|
||||
export type ExternalSalesDetailFilters = Partial<Record<ExternalSalesDetailFilterKey, string>>
|
||||
|
||||
export type ExternalSalesPageInfo = {
|
||||
page: number
|
||||
pageSize: number
|
||||
total: number
|
||||
totalPages: number
|
||||
}
|
||||
|
||||
export type ExternalSalesPage = {
|
||||
view: ExternalSalesView
|
||||
dateFrom: string
|
||||
dateTo: string
|
||||
shopName: ExternalSalesTargetShop | ''
|
||||
generatedAt: string
|
||||
rows: ExternalSalesSummaryRow[] | ExternalSalesDetailRow[] | ExternalSalesAfterSaleRow[]
|
||||
detailColumnAvailability?: {
|
||||
shopSkuId: boolean
|
||||
shopItemId: boolean
|
||||
}
|
||||
pageInfo: ExternalSalesPageInfo
|
||||
totals: {
|
||||
orderCount: number
|
||||
shipAmount: number
|
||||
shipQty: number
|
||||
afterSaleCount: number
|
||||
refundQty: number
|
||||
refundAmount: number
|
||||
goodsValue?: number
|
||||
freight?: number
|
||||
clearanceGoodsValue?: number
|
||||
}
|
||||
}
|
||||
|
||||
const ISO_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/
|
||||
|
||||
export function isExternalSalesDate(value: string) {
|
||||
const match = ISO_DATE_PATTERN.exec(value)
|
||||
if (!match) return false
|
||||
const date = new Date(`${value}T00:00:00.000Z`)
|
||||
return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value
|
||||
}
|
||||
|
||||
export function externalSalesDateSpan(dateFrom: string, dateTo: string) {
|
||||
if (!isExternalSalesDate(dateFrom) || !isExternalSalesDate(dateTo)) return null
|
||||
const start = Date.parse(`${dateFrom}T00:00:00.000Z`)
|
||||
const end = Date.parse(`${dateTo}T00:00:00.000Z`)
|
||||
if (end < start) return null
|
||||
return Math.floor((end - start) / 86_400_000) + 1
|
||||
}
|
||||
|
||||
export function externalSalesMonthRange(month: string) {
|
||||
const match = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(month)
|
||||
if (!match) return null
|
||||
const year = Number(match[1])
|
||||
const monthIndex = Number(match[2]) - 1
|
||||
return {
|
||||
dateFrom: new Date(Date.UTC(year, monthIndex, 1)).toISOString().slice(0, 10),
|
||||
dateTo: new Date(Date.UTC(year, monthIndex + 1, 0)).toISOString().slice(0, 10),
|
||||
}
|
||||
}
|
||||
|
||||
function sqlLiteral(value: string) {
|
||||
return `N'${value.replaceAll("'", "''")}'`
|
||||
}
|
||||
|
||||
function sourceSelect(input: {
|
||||
sourceType: 'OTHER' | 'QMCUST'
|
||||
headerTable: string
|
||||
itemTable: string
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shops: readonly string[]
|
||||
}) {
|
||||
return `
|
||||
SELECT TOP (50000) ${sqlLiteral(input.sourceType)} AS src,
|
||||
o.o_id, i.oi_id, o.so_id, LTRIM(RTRIM(o.shop_name)) AS shop_name,
|
||||
o.logistics_company, o.l_id, o.weight AS shipment_weight,
|
||||
CONVERT(varchar(10), o.send_date, 23) AS stats_date,
|
||||
CONVERT(varchar(19), o.order_date, 120) AS order_date,
|
||||
CONVERT(varchar(19), o.send_date, 120) AS send_date,
|
||||
o.status, i.item_status, o.creator_name, o.referrer_name,
|
||||
i.sku_id, i.i_id, i.shop_sku_id, i.shop_i_id, i.properties_value,
|
||||
i.name, i.base_price, i.price, i.qty, i.amount, o.paid_amount, i.outer_oi_id,
|
||||
o.Id AS header_row_id, i.Id AS item_row_id
|
||||
FROM JianSun.dbo.${input.headerTable} o
|
||||
INNER JOIN JianSun.dbo.${input.itemTable} i ON i.o_id = o.o_id
|
||||
WHERE LTRIM(RTRIM(ISNULL(o.shop_name, ''))) IN (${input.shops.map(sqlLiteral).join(', ')})
|
||||
${input.dateFrom ? `AND o.send_date >= CONVERT(datetime2, '${input.dateFrom}', 23)` : ''}
|
||||
${input.dateTo ? `AND o.send_date < DATEADD(day, 1, CONVERT(datetime2, '${input.dateTo}', 23))` : ''}
|
||||
AND ISNULL(i.qty, 0) > 0
|
||||
AND UPPER(LTRIM(RTRIM(ISNULL(i.item_status, '')))) <> N'REPLACED'
|
||||
AND (
|
||||
UPPER(LTRIM(RTRIM(ISNULL(o.status, '')))) = N'SENT'
|
||||
OR UPPER(LTRIM(RTRIM(ISNULL(i.item_status, '')))) IN (N'SENT', N'已发货')
|
||||
)`
|
||||
}
|
||||
|
||||
export function buildExternalSalesSourceSql(input: {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shopName?: ExternalSalesTargetShop | ''
|
||||
sourceTypes?: readonly ('OTHER' | 'QMCUST')[]
|
||||
}) {
|
||||
if (input.dateFrom && input.dateTo && !externalSalesDateSpan(input.dateFrom, input.dateTo)) {
|
||||
throw new Error('外贸销量统计时间范围不正确')
|
||||
}
|
||||
const shops = input.shopName ? [input.shopName] : EXTERNAL_SALES_TARGET_SHOPS
|
||||
const sourceTypes = input.sourceTypes ?? ['OTHER', 'QMCUST']
|
||||
if (sourceTypes.length === 0) return ''
|
||||
const selects: string[] = []
|
||||
if (sourceTypes.includes('OTHER')) {
|
||||
selects.push(sourceSelect({
|
||||
sourceType: 'OTHER',
|
||||
headerTable: 'jst_Orders',
|
||||
itemTable: 'jst_orderitem',
|
||||
dateFrom: input.dateFrom,
|
||||
dateTo: input.dateTo,
|
||||
shops,
|
||||
}))
|
||||
}
|
||||
if (sourceTypes.includes('QMCUST')) {
|
||||
selects.push(sourceSelect({
|
||||
sourceType: 'QMCUST',
|
||||
headerTable: 'jst_qmcust_orderlist',
|
||||
itemTable: 'jst_qmcust_orderlist_item',
|
||||
dateFrom: input.dateFrom,
|
||||
dateTo: input.dateTo,
|
||||
shops,
|
||||
}))
|
||||
}
|
||||
return `
|
||||
WITH allItems AS (
|
||||
${selects.join('\n UNION ALL\n')}
|
||||
)
|
||||
SELECT * FROM allItems`
|
||||
}
|
||||
|
||||
export function buildExternalSalesAfterSaleWhereSql(input: {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shopName?: ExternalSalesTargetShop | ''
|
||||
keyword?: string
|
||||
orderNo?: string
|
||||
itemCode?: string
|
||||
}) {
|
||||
if (input.dateFrom && input.dateTo && !externalSalesDateSpan(input.dateFrom, input.dateTo)) {
|
||||
throw new Error('外贸售后统计时间范围不正确')
|
||||
}
|
||||
const shops = input.shopName ? [input.shopName] : EXTERNAL_SALES_TARGET_SHOPS
|
||||
const aliases = shops.flatMap((shop) => EXTERNAL_SALES_TARGET_SHOP_ALIASES[shop])
|
||||
const conditions = [
|
||||
`h.shop_name IN (${aliases.map(sqlLiteral).join(', ')})`,
|
||||
]
|
||||
if (input.dateFrom) {
|
||||
conditions.push(`h.as_date >= CONVERT(datetime2, '${input.dateFrom}', 23)`)
|
||||
}
|
||||
if (input.dateTo) {
|
||||
conditions.push(`h.as_date < DATEADD(day, 1, CONVERT(datetime2, '${input.dateTo}', 23))`)
|
||||
}
|
||||
if (input.orderNo?.trim()) {
|
||||
const orderNo = sqlLiteral(`%${input.orderNo.trim()}%`)
|
||||
conditions.push(`(
|
||||
h.so_id LIKE ${orderNo}
|
||||
OR h.raw_so_id LIKE ${orderNo}
|
||||
OR h.as_id LIKE ${orderNo}
|
||||
OR h.outer_as_id LIKE ${orderNo}
|
||||
)`)
|
||||
}
|
||||
if (input.itemCode?.trim()) {
|
||||
const itemCode = sqlLiteral(`%${input.itemCode.trim()}%`)
|
||||
conditions.push(`(i.sku_id LIKE ${itemCode} OR i.i_id LIKE ${itemCode} OR i.shop_sku_id LIKE ${itemCode})`)
|
||||
}
|
||||
if (input.keyword?.trim()) {
|
||||
const keyword = sqlLiteral(`%${input.keyword.trim()}%`)
|
||||
conditions.push(`(
|
||||
h.outer_as_id LIKE ${keyword}
|
||||
OR h.so_id LIKE ${keyword}
|
||||
OR h.raw_so_id LIKE ${keyword}
|
||||
OR h.shop_name LIKE ${keyword}
|
||||
OR h.creator_name LIKE ${keyword}
|
||||
OR i.sku_id LIKE ${keyword}
|
||||
OR i.i_id LIKE ${keyword}
|
||||
OR i.shop_sku_id LIKE ${keyword}
|
||||
OR i.name LIKE ${keyword}
|
||||
OR i.properties_value LIKE ${keyword}
|
||||
)`)
|
||||
}
|
||||
return conditions.join('\n AND ')
|
||||
}
|
||||
|
||||
export function buildExternalSalesAfterSaleMetricsSql(orderNos: readonly string[]) {
|
||||
const uniqueOrderNos = [...new Set(orderNos.map((value) => value.trim()).filter(Boolean))]
|
||||
if (uniqueOrderNos.length === 0) return ''
|
||||
if (uniqueOrderNos.length > 50) throw new Error('外贸售后订单单次最多查询 50 个编号')
|
||||
return `
|
||||
SELECT h.so_id AS order_no,
|
||||
SUM(TRY_CONVERT(decimal(18,4), ISNULL(i.amount, '0'))) AS after_sale_amount,
|
||||
SUM(CAST(ISNULL(i.qty, 0) AS bigint)) AS after_sale_qty
|
||||
FROM JianSun.dbo.jst_qmcust_refundlist h
|
||||
INNER JOIN JianSun.dbo.jst_qmcust_refundlist_item i ON i.as_id = h.as_id
|
||||
WHERE ${buildExternalSalesAfterSaleWhereSql({})}
|
||||
AND h.so_id IN (${uniqueOrderNos.map(sqlLiteral).join(', ')})
|
||||
GROUP BY h.so_id`
|
||||
}
|
||||
|
||||
export function buildExternalSalesDetailAfterSaleMetricsSql(orderNos: readonly string[]) {
|
||||
const uniqueOrderNos = [...new Set(orderNos.map((value) => value.trim()).filter(Boolean))]
|
||||
if (uniqueOrderNos.length === 0) return ''
|
||||
if (uniqueOrderNos.length > 50) throw new Error('外贸售后订单单次最多查询 50 个编号')
|
||||
return `
|
||||
SELECT h.so_id AS order_no, i.sku_id,
|
||||
SUM(TRY_CONVERT(decimal(18,4), ISNULL(i.amount, '0'))) AS after_sale_amount,
|
||||
SUM(CAST(ISNULL(i.qty, 0) AS bigint)) AS after_sale_qty
|
||||
FROM JianSun.dbo.jst_qmcust_refundlist h
|
||||
INNER JOIN JianSun.dbo.jst_qmcust_refundlist_item i ON i.as_id = h.as_id
|
||||
WHERE ${buildExternalSalesAfterSaleWhereSql({})}
|
||||
AND h.so_id IN (${uniqueOrderNos.map(sqlLiteral).join(', ')})
|
||||
GROUP BY h.so_id, i.sku_id`
|
||||
}
|
||||
|
||||
export function buildExternalSalesWaybillFreightSql(trackingNos: readonly string[]) {
|
||||
const uniqueTrackingNos = [...new Set(
|
||||
trackingNos.map((value) => value.trim()).filter(Boolean),
|
||||
)]
|
||||
if (uniqueTrackingNos.length === 0) return ''
|
||||
if (uniqueTrackingNos.length > 50) throw new Error('外贸运单号单次最多查询 50 个')
|
||||
return `
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
LTRIM(RTRIM(CAST(expressNo AS nvarchar(160)))) AS tracking_no,
|
||||
TRY_CONVERT(decimal(18,4), freightCost) AS freight_cost,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY LTRIM(RTRIM(CAST(expressNo AS nvarchar(160))))
|
||||
ORDER BY updateTime DESC, Id DESC
|
||||
) AS row_rank
|
||||
FROM JianSun.dbo.fys_jstFreightCost
|
||||
WHERE LTRIM(RTRIM(CAST(ISNULL(expressNo, '') AS nvarchar(160))))
|
||||
IN (${uniqueTrackingNos.map(sqlLiteral).join(', ')})
|
||||
)
|
||||
SELECT tracking_no, freight_cost
|
||||
FROM ranked
|
||||
WHERE row_rank = 1`
|
||||
}
|
||||
|
||||
export function enrichExternalSalesItemCosts(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
archiveCosts: readonly ExternalSalesArchiveCost[],
|
||||
) {
|
||||
const costs = new Map(archiveCosts.map((item) => [
|
||||
item.barcode.trim().toUpperCase(),
|
||||
item,
|
||||
]))
|
||||
return rows.map((row): ExternalSalesItemRow => {
|
||||
const archiveCost = costs.get(row.skuId.trim().toUpperCase())
|
||||
const costPrice = archiveCost?.costPrice ?? null
|
||||
return {
|
||||
...row,
|
||||
costPrice,
|
||||
shippingUnitWeight: archiveCost?.unitWeight ?? null,
|
||||
goodsValue: costPrice === null
|
||||
? null
|
||||
: Math.round(costPrice * row.qty * 100) / 100,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function allocateExternalSalesPaidAmounts(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
) {
|
||||
const groups = new Map<string, number[]>()
|
||||
for (const [index, row] of rows.entries()) {
|
||||
const key = `${row.sourceType}|${row.oId}`
|
||||
const indexes = groups.get(key) ?? []
|
||||
indexes.push(index)
|
||||
groups.set(key, indexes)
|
||||
}
|
||||
|
||||
const allocated = rows.map((row) => ({ ...row }))
|
||||
for (const indexes of groups.values()) {
|
||||
const orderPaidAmount = rows[indexes[0]]?.orderPaidAmount
|
||||
if (orderPaidAmount === null || orderPaidAmount === undefined) continue
|
||||
const totalAmount = indexes.reduce((sum, index) => sum + rows[index].amount, 0)
|
||||
const totalQty = indexes.reduce((sum, index) => sum + rows[index].qty, 0)
|
||||
let assignedAmount = 0
|
||||
indexes.forEach((index, position) => {
|
||||
const row = rows[index]
|
||||
const ratio = totalAmount !== 0
|
||||
? row.amount / totalAmount
|
||||
: totalQty > 0
|
||||
? row.qty / totalQty
|
||||
: 1 / indexes.length
|
||||
const amount = position === indexes.length - 1
|
||||
? Math.round((orderPaidAmount - assignedAmount) * 100) / 100
|
||||
: Math.round(orderPaidAmount * ratio * 100) / 100
|
||||
allocated[index] = {
|
||||
...allocated[index],
|
||||
amount,
|
||||
}
|
||||
assignedAmount = Math.round((assignedAmount + amount) * 100) / 100
|
||||
})
|
||||
}
|
||||
return allocated
|
||||
}
|
||||
|
||||
function detailAfterSaleKey(orderNo: string, skuId: string) {
|
||||
return `${orderNo.trim().toUpperCase()}|${skuId.trim().toUpperCase()}`
|
||||
}
|
||||
|
||||
export function applyExternalSalesAfterSaleMetrics(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
metrics: readonly ExternalSalesDetailAfterSaleMetric[],
|
||||
) {
|
||||
const metricByKey = new Map<string, ExternalSalesDetailAfterSaleMetric>()
|
||||
for (const metric of metrics) {
|
||||
const key = detailAfterSaleKey(metric.orderNo, metric.skuId)
|
||||
const current = metricByKey.get(key)
|
||||
metricByKey.set(key, {
|
||||
orderNo: metric.orderNo,
|
||||
skuId: metric.skuId,
|
||||
afterSaleAmount: Math.round(((current?.afterSaleAmount ?? 0) + metric.afterSaleAmount) * 100) / 100,
|
||||
afterSaleQty: (current?.afterSaleQty ?? 0) + metric.afterSaleQty,
|
||||
})
|
||||
}
|
||||
|
||||
const groups = new Map<string, number[]>()
|
||||
for (const [index, row] of rows.entries()) {
|
||||
const key = detailAfterSaleKey(row.orderNo, row.skuId)
|
||||
const indexes = groups.get(key) ?? []
|
||||
indexes.push(index)
|
||||
groups.set(key, indexes)
|
||||
}
|
||||
|
||||
const result = rows.map((row) => ({
|
||||
...row,
|
||||
afterSaleAmount: 0,
|
||||
afterSaleQty: 0,
|
||||
finalShipAmount: row.amount,
|
||||
finalShipQty: row.qty,
|
||||
}))
|
||||
|
||||
for (const [key, indexes] of groups) {
|
||||
const metric = metricByKey.get(key)
|
||||
if (!metric) continue
|
||||
const totalQty = indexes.reduce((sum, index) => sum + rows[index].qty, 0)
|
||||
const totalAmount = indexes.reduce((sum, index) => sum + rows[index].amount, 0)
|
||||
const refundQtyShares = indexes.map((index) => (
|
||||
totalQty > 0
|
||||
? metric.afterSaleQty * rows[index].qty / totalQty
|
||||
: metric.afterSaleQty / indexes.length
|
||||
))
|
||||
const roundedQtyShares = refundQtyShares.map((value) => Math.floor(value))
|
||||
let remainingQty = Math.max(
|
||||
0,
|
||||
metric.afterSaleQty - roundedQtyShares.reduce((sum, value) => sum + value, 0),
|
||||
)
|
||||
const remainderOrder = refundQtyShares
|
||||
.map((value, position) => ({ position, remainder: value - Math.floor(value) }))
|
||||
.sort((left, right) => right.remainder - left.remainder || left.position - right.position)
|
||||
for (const item of remainderOrder) {
|
||||
if (remainingQty <= 0) break
|
||||
roundedQtyShares[item.position] += 1
|
||||
remainingQty -= 1
|
||||
}
|
||||
|
||||
let assignedAmount = 0
|
||||
indexes.forEach((index, position) => {
|
||||
const row = rows[index]
|
||||
const amountRatio = totalAmount !== 0
|
||||
? row.amount / totalAmount
|
||||
: totalQty > 0
|
||||
? row.qty / totalQty
|
||||
: 1 / indexes.length
|
||||
const allocatedAmount = position === indexes.length - 1
|
||||
? Math.round((metric.afterSaleAmount - assignedAmount) * 100) / 100
|
||||
: Math.round(metric.afterSaleAmount * amountRatio * 100) / 100
|
||||
assignedAmount = Math.round((assignedAmount + allocatedAmount) * 100) / 100
|
||||
result[index] = {
|
||||
...result[index],
|
||||
afterSaleAmount: allocatedAmount,
|
||||
afterSaleQty: roundedQtyShares[position],
|
||||
finalShipAmount: Math.round((row.amount - allocatedAmount) * 100) / 100,
|
||||
finalShipQty: row.qty - roundedQtyShares[position],
|
||||
}
|
||||
})
|
||||
}
|
||||
return result.map((row) => ({
|
||||
...row,
|
||||
goodsValue: row.costPrice === null
|
||||
? null
|
||||
: Math.round(row.costPrice * row.finalShipQty * 100) / 100,
|
||||
}))
|
||||
}
|
||||
|
||||
function rounded(value: number, digits = 2) {
|
||||
const factor = 10 ** digits
|
||||
return Math.round(value * factor) / factor
|
||||
}
|
||||
|
||||
export function applyExternalSalesFreight(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
waybillFreight: readonly ExternalSalesWaybillFreight[],
|
||||
) {
|
||||
const freightByTrackingNo = new Map(waybillFreight.map((row) => [
|
||||
row.trackingNo.trim().toUpperCase(),
|
||||
row.freightCost,
|
||||
]))
|
||||
const result = rows.map((row) => ({
|
||||
...row,
|
||||
shippingWeight: null as number | null,
|
||||
freight: null as number | null,
|
||||
}))
|
||||
|
||||
const orderGroups = new Map<string, number[]>()
|
||||
for (const [index, row] of rows.entries()) {
|
||||
const key = `${row.sourceType}|${row.oId}`
|
||||
const indexes = orderGroups.get(key) ?? []
|
||||
indexes.push(index)
|
||||
orderGroups.set(key, indexes)
|
||||
}
|
||||
for (const indexes of orderGroups.values()) {
|
||||
const totalQty = indexes.reduce((sum, index) => sum + rows[index].qty, 0)
|
||||
const shipmentWeight = rows[indexes[0]]?.shipmentWeight
|
||||
indexes.forEach((index, position) => {
|
||||
const row = rows[index]
|
||||
const shippingWeight = row.shippingUnitWeight !== null && row.shippingUnitWeight > 0
|
||||
? row.shippingUnitWeight * row.qty
|
||||
: shipmentWeight !== null && shipmentWeight > 0 && totalQty > 0
|
||||
? position === indexes.length - 1
|
||||
? shipmentWeight - indexes.slice(0, -1).reduce((sum, itemIndex) => (
|
||||
sum + (result[itemIndex].shippingWeight ?? 0)
|
||||
), 0)
|
||||
: shipmentWeight * row.qty / totalQty
|
||||
: null
|
||||
result[index] = {
|
||||
...result[index],
|
||||
shippingWeight: shippingWeight === null ? null : rounded(shippingWeight, 4),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const selfPickupIndexes: number[] = []
|
||||
const waybillGroups = new Map<string, number[]>()
|
||||
for (const [index, row] of rows.entries()) {
|
||||
if (row.shippingCourier.includes('自提')) {
|
||||
selfPickupIndexes.push(index)
|
||||
continue
|
||||
}
|
||||
const trackingNo = row.trackingNo.trim().toUpperCase()
|
||||
if (!trackingNo) continue
|
||||
const indexes = waybillGroups.get(trackingNo) ?? []
|
||||
indexes.push(index)
|
||||
waybillGroups.set(trackingNo, indexes)
|
||||
}
|
||||
for (const index of selfPickupIndexes) {
|
||||
result[index] = { ...result[index], freight: 0 }
|
||||
}
|
||||
|
||||
for (const [trackingNo, indexes] of waybillGroups) {
|
||||
const totalFreight = freightByTrackingNo.get(trackingNo)
|
||||
if (totalFreight === undefined) continue
|
||||
const allWeightsAvailable = indexes.every((index) => (
|
||||
(result[index].shippingWeight ?? 0) > 0
|
||||
))
|
||||
const weights = indexes.map((index) => (
|
||||
allWeightsAvailable
|
||||
? result[index].shippingWeight ?? 0
|
||||
: Math.max(0, rows[index].qty)
|
||||
))
|
||||
const totalWeight = weights.reduce((sum, value) => sum + value, 0)
|
||||
let assigned = 0
|
||||
indexes.forEach((index, position) => {
|
||||
const weight = totalWeight > 0 ? weights[position] : 1
|
||||
const denominator = totalWeight > 0 ? totalWeight : indexes.length
|
||||
const freight = position === indexes.length - 1
|
||||
? rounded(totalFreight - assigned)
|
||||
: rounded(totalFreight * weight / denominator)
|
||||
result[index] = { ...result[index], freight }
|
||||
assigned = rounded(assigned + freight)
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function applyExternalSalesClearancePrices(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
clearanceRows: readonly ExternalClearancePriceRow[],
|
||||
) {
|
||||
const clearanceByKey = new Map(clearanceRows.map((row) => [
|
||||
`${row.orderNo.trim().toUpperCase()}|${row.itemCode.trim().toUpperCase()}`,
|
||||
row.clearancePrice,
|
||||
]))
|
||||
return rows.map((row): ExternalSalesItemRow => {
|
||||
const orderKey = row.orderNo.trim().toUpperCase()
|
||||
const matchedPrice = [row.skuId, row.itemId, row.shopSkuId, row.shopItemId]
|
||||
.map((code) => code.trim().toUpperCase())
|
||||
.filter(Boolean)
|
||||
.map((code) => clearanceByKey.get(`${orderKey}|${code}`))
|
||||
.find((value) => value !== undefined)
|
||||
const clearancePrice = matchedPrice ?? row.costPrice
|
||||
return {
|
||||
...row,
|
||||
clearancePrice,
|
||||
clearanceGoodsValue: clearancePrice === null
|
||||
? null
|
||||
: Math.round(clearancePrice * row.finalShipQty * 100) / 100,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function parseExternalSalesDetailFilters(value: string): ExternalSalesDetailFilters | null {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
|
||||
const allowed = new Set<string>(EXTERNAL_SALES_DETAIL_FILTER_KEYS)
|
||||
const filters: ExternalSalesDetailFilters = {}
|
||||
for (const [key, rawValue] of Object.entries(parsed)) {
|
||||
if (!allowed.has(key) || typeof rawValue !== 'string' || rawValue.length > 200) return null
|
||||
const normalized = rawValue.trim()
|
||||
if (normalized) filters[key as ExternalSalesDetailFilterKey] = normalized
|
||||
}
|
||||
return filters
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function externalSalesDetailFieldValues(
|
||||
row: ExternalSalesItemRow,
|
||||
key: ExternalSalesDetailFilterKey,
|
||||
) {
|
||||
switch (key) {
|
||||
case 'orderNo': return [row.orderNo]
|
||||
case 'internalOrderNo': return [row.oId]
|
||||
case 'shippingCourier': return [row.shippingCourier]
|
||||
case 'trackingNo': return [row.trackingNo]
|
||||
case 'skuId': return [row.skuId]
|
||||
case 'itemId': return [row.itemId]
|
||||
case 'orderDate': return [row.orderDate]
|
||||
}
|
||||
}
|
||||
|
||||
export function filterExternalSalesItems(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
keyword: string,
|
||||
fieldFilters: ExternalSalesDetailFilters = {},
|
||||
) {
|
||||
const needle = keyword.trim().toLocaleLowerCase('zh-CN')
|
||||
const activeFieldFilters = Object.entries(fieldFilters).flatMap(([key, value]) => {
|
||||
const normalized = value?.trim().toLocaleLowerCase('zh-CN')
|
||||
return normalized
|
||||
? [[key as ExternalSalesDetailFilterKey, normalized] as const]
|
||||
: []
|
||||
})
|
||||
if (!needle && activeFieldFilters.length === 0) return [...rows]
|
||||
return rows.filter((row) => {
|
||||
if (needle && ![
|
||||
row.orderNo,
|
||||
row.oiId,
|
||||
row.shopName,
|
||||
row.skuId,
|
||||
row.itemId,
|
||||
row.shopSkuId,
|
||||
row.shopItemId,
|
||||
row.itemName,
|
||||
row.propertiesValue,
|
||||
].some((value) => value.toLocaleLowerCase('zh-CN').includes(needle))) {
|
||||
return false
|
||||
}
|
||||
return activeFieldFilters.every(([key, value]) => (
|
||||
externalSalesDetailFieldValues(row, key)
|
||||
.some((candidate) => candidate.toLocaleLowerCase('zh-CN').includes(value))
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
export function filterExternalSalesAfterSaleRows(
|
||||
rows: readonly ExternalSalesAfterSaleRow[],
|
||||
keyword: string,
|
||||
) {
|
||||
const needle = keyword.trim().toLocaleLowerCase('zh-CN')
|
||||
return rows
|
||||
.filter((row) => !needle || [
|
||||
row.asId,
|
||||
row.outerAsId,
|
||||
row.orderNo,
|
||||
row.shopName,
|
||||
row.creatorName,
|
||||
row.skuId,
|
||||
row.shopSkuId,
|
||||
row.itemName,
|
||||
row.propertiesValue,
|
||||
row.questionType,
|
||||
].some((value) => value.toLocaleLowerCase('zh-CN').includes(needle)))
|
||||
.sort((left, right) => (
|
||||
right.asDate.localeCompare(left.asDate)
|
||||
|| right.asId.localeCompare(left.asId, 'zh-CN')
|
||||
))
|
||||
}
|
||||
|
||||
export function externalSalesAfterSaleStatusLabel(value: string) {
|
||||
const normalized = value.trim()
|
||||
const labels: Record<string, string> = {
|
||||
WaitConfirm: '待确认',
|
||||
Confirmed: '已确认',
|
||||
Cancelled: '已取消',
|
||||
Rejected: '已拒绝',
|
||||
Closed: '已关闭',
|
||||
}
|
||||
return labels[normalized] ?? (normalized || '-')
|
||||
}
|
||||
|
||||
export function buildExternalSalesSummary(
|
||||
rows: readonly ExternalSalesItemRow[],
|
||||
afterSaleMetrics: readonly ExternalSalesAfterSaleMetric[] = [],
|
||||
): ExternalSalesSummaryRow[] {
|
||||
const grouped = new Map<string, {
|
||||
month: string
|
||||
orderNo: string
|
||||
shipAmount: number
|
||||
shipQty: number
|
||||
}>()
|
||||
const afterSaleMetricsByOrder = new Map<string, {
|
||||
afterSaleAmount: number
|
||||
afterSaleQty: number
|
||||
}>()
|
||||
for (const row of afterSaleMetrics) {
|
||||
const key = row.orderNo.trim().toUpperCase()
|
||||
const metric = afterSaleMetricsByOrder.get(key) ?? { afterSaleAmount: 0, afterSaleQty: 0 }
|
||||
metric.afterSaleAmount += row.afterSaleAmount
|
||||
metric.afterSaleQty += row.afterSaleQty
|
||||
afterSaleMetricsByOrder.set(key, metric)
|
||||
}
|
||||
for (const row of rows) {
|
||||
const month = row.statsDate.slice(0, 7)
|
||||
const key = `${month}|${row.orderNo}`
|
||||
const current = grouped.get(key) ?? {
|
||||
month,
|
||||
orderNo: row.orderNo,
|
||||
shipAmount: 0,
|
||||
shipQty: 0,
|
||||
}
|
||||
current.shipAmount += row.amount
|
||||
current.shipQty += row.qty
|
||||
grouped.set(key, current)
|
||||
}
|
||||
const latestMonthByOrder = new Map<string, string>()
|
||||
for (const row of grouped.values()) {
|
||||
const orderKey = row.orderNo.trim().toUpperCase()
|
||||
const current = latestMonthByOrder.get(orderKey)
|
||||
if (!current || row.month > current) latestMonthByOrder.set(orderKey, row.month)
|
||||
}
|
||||
return [...grouped.values()]
|
||||
.map((row) => {
|
||||
const orderKey = row.orderNo.trim().toUpperCase()
|
||||
const metric = latestMonthByOrder.get(orderKey) === row.month
|
||||
? afterSaleMetricsByOrder.get(orderKey)
|
||||
: undefined
|
||||
const afterSaleAmount = Math.round((metric?.afterSaleAmount ?? 0) * 100) / 100
|
||||
const afterSaleQty = metric?.afterSaleQty ?? 0
|
||||
const shipAmount = Math.round(row.shipAmount * 100) / 100
|
||||
return {
|
||||
month: row.month,
|
||||
orderNo: row.orderNo,
|
||||
shipAmount,
|
||||
shipQty: row.shipQty,
|
||||
afterSaleAmount,
|
||||
afterSaleQty,
|
||||
finalShipAmount: Math.round((shipAmount - afterSaleAmount) * 100) / 100,
|
||||
finalShipQty: row.shipQty - afterSaleQty,
|
||||
}
|
||||
})
|
||||
.sort((left, right) => (
|
||||
right.month.localeCompare(left.month)
|
||||
|| left.orderNo.localeCompare(right.orderNo, 'zh-CN')
|
||||
))
|
||||
}
|
||||
|
||||
export function toExternalSalesDetailRows(rows: readonly ExternalSalesItemRow[]): ExternalSalesDetailRow[] {
|
||||
return rows
|
||||
.map((row) => ({
|
||||
...row,
|
||||
statusLabel: '已发货' as const,
|
||||
}))
|
||||
.sort((left, right) => (
|
||||
right.orderDate.localeCompare(left.orderDate)
|
||||
|| right.oiId.localeCompare(left.oiId, 'zh-CN')
|
||||
))
|
||||
}
|
||||
|
||||
export function paginateExternalSales<T>(
|
||||
rows: readonly T[],
|
||||
page: number,
|
||||
pageSize: number,
|
||||
): { rows: T[]; pageInfo: ExternalSalesPageInfo } {
|
||||
const total = rows.length
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize))
|
||||
const current = Math.min(Math.max(1, Math.trunc(page)), totalPages)
|
||||
const offset = (current - 1) * pageSize
|
||||
return {
|
||||
rows: rows.slice(offset, offset + pageSize),
|
||||
pageInfo: { page: current, pageSize, total, totalPages },
|
||||
}
|
||||
}
|
||||
@ -10,11 +10,14 @@ describe('经营管理空白页注册表', () => {
|
||||
'特殊备货&特殊入库流程监控',
|
||||
'商品SABC打标',
|
||||
'选品明细',
|
||||
'外销销量',
|
||||
])
|
||||
expect(getManagementBlankPage('blank-page-2')?.route)
|
||||
.toBe('/supply-chain/management/blank-pages/blank-page-2')
|
||||
expect(getManagementBlankPage('blank-page-6')?.route)
|
||||
.toBe('/supply-chain/management/blank-pages/blank-page-6')
|
||||
expect(getManagementBlankPage('blank-page-7')?.route)
|
||||
.toBe('/supply-chain/management/blank-pages/blank-page-7')
|
||||
})
|
||||
|
||||
it('让未来新增的空白页路径自动继承同一权限范围', () => {
|
||||
|
||||
@ -20,6 +20,11 @@ export const MANAGEMENT_BLANK_PAGES: readonly ManagementBlankPageDefinition[] =
|
||||
label: '选品明细',
|
||||
route: '/supply-chain/management/blank-pages/blank-page-6',
|
||||
},
|
||||
{
|
||||
key: 'blank-page-7',
|
||||
label: '外销销量',
|
||||
route: '/supply-chain/management/blank-pages/blank-page-7',
|
||||
},
|
||||
]
|
||||
|
||||
export const MANAGEMENT_BLANK_PAGE_ROUTE_PREFIX = '/supply-chain/management/blank-pages/'
|
||||
|
||||
@ -14,8 +14,8 @@ describe('independent supply-chain page permissions', () => {
|
||||
])
|
||||
|
||||
it('gives every menu page its own target, route mapping and permission row', () => {
|
||||
// 菜单页数量随功能迭代增长(新增「商品盘停管理」后为 33)
|
||||
expect(pages).toHaveLength(33)
|
||||
// 菜单页数量随功能迭代增长(新增「外销销量」后为 34)
|
||||
expect(pages).toHaveLength(34)
|
||||
expect(new Set(pages.map((page) => page.targetKey)).size).toBe(pages.length)
|
||||
const matrixRows = PERMISSION_MATRIX_SECTIONS.find((section) => section.id === 'supply')!.groups.flatMap((group) => group.rows)
|
||||
for (const page of pages) {
|
||||
@ -36,7 +36,7 @@ describe('independent supply-chain page permissions', () => {
|
||||
|
||||
it('does not reuse old management or sample grants for the new nodes', () => {
|
||||
const overrides = { 'businessManagement:purchase:edit': true, 'newProductSampleProgress:purchase:edit': true }
|
||||
for (const target of ['ownerConfig', 'limitManagement', 'productionStopDemands', 'logisticsArrivalSigningDuration', 'managementBlankPage1', 'managementBlankPage2', 'finishedProductProgress'] as const) {
|
||||
for (const target of ['ownerConfig', 'limitManagement', 'productionStopDemands', 'logisticsArrivalSigningDuration', 'managementBlankPage1', 'managementBlankPage2', 'managementBlankPage7', 'finishedProductProgress'] as const) {
|
||||
expect(resolveSupplyChainPermissionAccess(overrides, target, ['purchase'])).toEqual({ view: false, download: false, edit: false })
|
||||
}
|
||||
})
|
||||
|
||||
@ -27,6 +27,7 @@ export function getSupplyChainPermissionTargetForPath(pathname: string): SupplyC
|
||||
}
|
||||
if (pathname === '/supply-chain/management/blank-pages/blank-page-1') return 'managementBlankPage1' as const
|
||||
if (pathname === '/supply-chain/management/blank-pages/blank-page-2') return 'managementBlankPage2' as const
|
||||
if (pathname === '/supply-chain/management/blank-pages/blank-page-7') return 'managementBlankPage7' as const
|
||||
if (pathname === '/supply-chain/management/employee-hours') return 'employeeHours' as const
|
||||
if (pathname === '/supply-chain/management/logistics-arrival-signing-duration') return 'logisticsArrivalSigningDuration' as const
|
||||
if (pathname === '/supply-chain/management/order-not-dispatched') return 'orderNotDispatched' as const
|
||||
@ -131,6 +132,17 @@ export function getSupplyChainApiPermissionRequirement(pathname: string, method:
|
||||
if (pathname.startsWith('/api/supply-chain/management/employee-hours')) {
|
||||
return { targetKey: 'employeeHours' as const, action: 'view' as const }
|
||||
}
|
||||
if (pathname === '/api/supply-chain/management/external-sales/freight/import') {
|
||||
return { targetKey: 'managementBlankPage7' as const, action: 'edit' as const }
|
||||
}
|
||||
if (
|
||||
pathname === '/api/supply-chain/management/external-sales'
|
||||
|| pathname.startsWith('/api/supply-chain/management/external-sales/freight')
|
||||
|| pathname.startsWith('/api/supply-chain/management/external-sales/clearance')
|
||||
|| pathname.startsWith('/api/supply-chain/management/external-sales/profit')
|
||||
) {
|
||||
return { targetKey: 'managementBlankPage7' as const, action: 'view' as const }
|
||||
}
|
||||
if (pathname.startsWith('/api/supply-chain/management/freight-config')) {
|
||||
return { targetKey: 'managementBlankPage1' as const, action: 'view' as const }
|
||||
}
|
||||
|
||||
@ -126,6 +126,7 @@ export type SupplyChainPermissionTargetKey =
|
||||
| 'orderNotDispatched'
|
||||
| 'managementBlankPage1'
|
||||
| 'managementBlankPage2'
|
||||
| 'managementBlankPage7'
|
||||
| 'finishedProductProgress'
|
||||
| 'employeeHours'
|
||||
| 'productArchive'
|
||||
@ -258,6 +259,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGETS: SupplyChainPermissionTarget[] = [
|
||||
{ key: 'orderNotDispatched', label: '应发未发', description: '查看应发未发订单、超时原因、处理人与原始订单明细' },
|
||||
{ key: 'managementBlankPage1', label: '空白页 1', description: '经营管理空白页 1' },
|
||||
{ key: 'managementBlankPage2', label: '空白页 2', description: '经营管理空白页 2' },
|
||||
{ key: 'managementBlankPage7', label: '外销销量', description: '外销销量查看、下载与维护' },
|
||||
{ key: 'finishedProductProgress', label: '成品进度明细', description: '成品进度查看、导出与维护' },
|
||||
{ key: 'employeeHours', label: '员工工时统计', description: '员工本人、部门或全公司数据范围单独设置' },
|
||||
{ key: 'productArchive', label: '产品全量档案', description: '商品、供应链和运营档案' },
|
||||
@ -386,6 +388,7 @@ export const SUPPLY_CHAIN_PERMISSION_TARGET_ROUTES: Partial<
|
||||
orderNotDispatched: '/supply-chain/management/order-not-dispatched',
|
||||
managementBlankPage1: '/supply-chain/management/blank-pages/blank-page-1',
|
||||
managementBlankPage2: '/supply-chain/management/blank-pages/blank-page-2',
|
||||
managementBlankPage7: '/supply-chain/management/blank-pages/blank-page-7',
|
||||
finishedProductProgress: '/supply-chain/purchase/finished-product-progress',
|
||||
employeeHours: '/supply-chain/management/employee-hours',
|
||||
productArchive: '/supply-chain/database/product-archive',
|
||||
|
||||
@ -0,0 +1,16 @@
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
export async function listExternalClearancePriceSourceRows() {
|
||||
return prisma.supplyChainExternalOrderCost.findMany({
|
||||
select: {
|
||||
onlineOrderNo: true,
|
||||
internalOrderNo: true,
|
||||
productCode: true,
|
||||
styleCode: true,
|
||||
shopProductCode: true,
|
||||
shopStyleCode: true,
|
||||
costPrice: true,
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,56 @@
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { ExternalSalesArchiveCost } from '@/lib/external-sales'
|
||||
|
||||
type ProductArchiveCostRow = {
|
||||
barcode: string
|
||||
costPrice: string | null
|
||||
unitWeight: string | null
|
||||
}
|
||||
|
||||
function normalizedBarcodes(barcodes: readonly string[]) {
|
||||
return Array.from(new Set(
|
||||
barcodes.map((barcode) => barcode.trim().toUpperCase()).filter(Boolean),
|
||||
))
|
||||
}
|
||||
|
||||
export async function listExternalSalesArchiveCosts(
|
||||
barcodes: readonly string[],
|
||||
): Promise<ExternalSalesArchiveCost[]> {
|
||||
const normalized = normalizedBarcodes(barcodes)
|
||||
const costs: ExternalSalesArchiveCost[] = []
|
||||
for (let offset = 0; offset < normalized.length; offset += 500) {
|
||||
const chunk = normalized.slice(offset, offset + 500)
|
||||
const rows = await prisma.$queryRaw<ProductArchiveCostRow[]>(Prisma.sql`
|
||||
SELECT
|
||||
UPPER(BTRIM("barcode")) AS "barcode",
|
||||
"costPrice" AS "costPrice",
|
||||
"weight" AS "unitWeight"
|
||||
FROM "SupplyChainProductArchive"
|
||||
WHERE UPPER(BTRIM("barcode")) IN (${Prisma.join(chunk)})
|
||||
`)
|
||||
for (const row of rows) {
|
||||
const rawCostPrice = String(row.costPrice ?? '').replaceAll(',', '').trim()
|
||||
const parsedCostPrice = rawCostPrice ? Number(rawCostPrice) : null
|
||||
const costPrice = parsedCostPrice !== null
|
||||
&& Number.isFinite(parsedCostPrice)
|
||||
&& parsedCostPrice >= 0
|
||||
? parsedCostPrice
|
||||
: null
|
||||
const rawUnitWeight = String(row.unitWeight ?? '').replaceAll(',', '').trim()
|
||||
const parsedUnitWeight = rawUnitWeight ? Number(rawUnitWeight) : null
|
||||
const unitWeight = parsedUnitWeight !== null
|
||||
&& Number.isFinite(parsedUnitWeight)
|
||||
&& parsedUnitWeight >= 0
|
||||
? parsedUnitWeight
|
||||
: null
|
||||
if (costPrice === null && unitWeight === null) continue
|
||||
costs.push({
|
||||
barcode: row.barcode.trim().toUpperCase(),
|
||||
costPrice,
|
||||
unitWeight,
|
||||
})
|
||||
}
|
||||
}
|
||||
return costs
|
||||
}
|
||||
@ -0,0 +1,327 @@
|
||||
import sql from 'mssql'
|
||||
import {
|
||||
allocateExternalSalesPaidAmounts,
|
||||
buildExternalSalesDetailAfterSaleMetricsSql,
|
||||
buildExternalSalesWaybillFreightSql,
|
||||
buildExternalSalesAfterSaleMetricsSql,
|
||||
buildExternalSalesAfterSaleWhereSql,
|
||||
buildExternalSalesSourceSql,
|
||||
resolveExternalSalesTargetShop,
|
||||
type ExternalSalesAfterSaleRow,
|
||||
type ExternalSalesAfterSaleMetric,
|
||||
type ExternalSalesDetailAfterSaleMetric,
|
||||
type ExternalSalesWaybillFreight,
|
||||
type ExternalSalesItemRow,
|
||||
type ExternalSalesTargetShop,
|
||||
} from '@/lib/external-sales'
|
||||
|
||||
type ExternalSalesSourcePoolGlobal = typeof globalThis & {
|
||||
externalSalesSourcePool?: sql.ConnectionPool
|
||||
}
|
||||
|
||||
function requiredEnv(name: string) {
|
||||
const value = process.env[name]?.trim()
|
||||
if (!value) throw new Error(`Missing required environment variable: ${name}`)
|
||||
return value
|
||||
}
|
||||
|
||||
function booleanEnv(name: string, fallback: boolean) {
|
||||
const value = process.env[name]?.trim().toLowerCase()
|
||||
return value ? value === 'true' || value === '1' : fallback
|
||||
}
|
||||
|
||||
function sourcePool() {
|
||||
const globalForPool = globalThis as ExternalSalesSourcePoolGlobal
|
||||
if (globalForPool.externalSalesSourcePool) return globalForPool.externalSalesSourcePool
|
||||
const pool = new sql.ConnectionPool({
|
||||
server: requiredEnv('JST_REPORT_DB_HOST'),
|
||||
port: Number(process.env.JST_REPORT_DB_PORT?.trim() || '1433'),
|
||||
database: requiredEnv('JST_REPORT_DB_NAME'),
|
||||
user: requiredEnv('JST_REPORT_DB_USER'),
|
||||
password: requiredEnv('JST_REPORT_DB_PASSWORD'),
|
||||
options: {
|
||||
encrypt: booleanEnv('JST_REPORT_DB_ENCRYPT', true),
|
||||
trustServerCertificate: booleanEnv('JST_REPORT_DB_TRUST_SERVER_CERTIFICATE', true),
|
||||
readOnlyIntent: true,
|
||||
appName: 'furniture-external-sales-readonly',
|
||||
},
|
||||
pool: { min: 0, max: 2, idleTimeoutMillis: 60_000 },
|
||||
connectionTimeout: 20_000,
|
||||
requestTimeout: 120_000,
|
||||
})
|
||||
globalForPool.externalSalesSourcePool = pool
|
||||
return pool
|
||||
}
|
||||
|
||||
function text(value: unknown) {
|
||||
return String(value ?? '').trim()
|
||||
}
|
||||
|
||||
function dateTimeText(value: unknown) {
|
||||
if (value instanceof Date) return value.toISOString().replace('T', ' ').slice(0, 19)
|
||||
return text(value).replace('T', ' ').slice(0, 19)
|
||||
}
|
||||
|
||||
function numberValue(value: unknown) {
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function nullableNumberValue(value: unknown) {
|
||||
if (value === null || value === undefined || String(value).trim() === '') return null
|
||||
const parsed = Number(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
|
||||
function targetShop(value: unknown): ExternalSalesTargetShop | null {
|
||||
return resolveExternalSalesTargetShop(text(value))
|
||||
}
|
||||
|
||||
export async function listExternalSalesItems(input: {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shopName?: ExternalSalesTargetShop | ''
|
||||
}) {
|
||||
const sourceSql = buildExternalSalesSourceSql({
|
||||
...input,
|
||||
sourceTypes: ['QMCUST'],
|
||||
})
|
||||
const outerSql = `SELECT * FROM OPENQUERY([JianSun_Old], N'${sourceSql.replaceAll("'", "''")}')`
|
||||
const pool = await sourcePool().connect()
|
||||
const result = await pool.request().query<Record<string, unknown>>(outerSql)
|
||||
const latest = new Map<string, Record<string, unknown>>()
|
||||
for (const row of result.recordset) {
|
||||
const key = `${text(row.src)}|${text(row.o_id)}|${text(row.oi_id)}`
|
||||
const current = latest.get(key)
|
||||
const rank = (candidate: Record<string, unknown>) => [
|
||||
numberValue(candidate.header_row_id),
|
||||
numberValue(candidate.item_row_id),
|
||||
] as const
|
||||
const [headerRowId, itemRowId] = rank(row)
|
||||
const [currentHeaderRowId, currentItemRowId] = current ? rank(current) : [-1, -1]
|
||||
if (!current
|
||||
|| headerRowId > currentHeaderRowId
|
||||
|| (headerRowId === currentHeaderRowId && itemRowId > currentItemRowId)) {
|
||||
latest.set(key, row)
|
||||
}
|
||||
}
|
||||
const rows = [...latest.values()].flatMap((row): ExternalSalesItemRow[] => {
|
||||
const shopName = targetShop(row.shop_name)
|
||||
if (!shopName) return []
|
||||
return [{
|
||||
sourceType: text(row.src).toUpperCase() === 'QMCUST' ? 'QMCUST' : 'OTHER',
|
||||
oId: text(row.o_id),
|
||||
oiId: text(row.oi_id),
|
||||
orderNo: text(row.so_id),
|
||||
shopName,
|
||||
shippingCourier: text(row.logistics_company),
|
||||
trackingNo: text(row.l_id),
|
||||
shipmentWeight: nullableNumberValue(row.shipment_weight),
|
||||
shippingUnitWeight: null,
|
||||
shippingWeight: null,
|
||||
freight: null,
|
||||
statsDate: text(row.stats_date),
|
||||
orderDate: text(row.order_date),
|
||||
sendDate: text(row.send_date),
|
||||
orderStatus: text(row.status),
|
||||
itemStatus: text(row.item_status),
|
||||
ownerName: text(row.creator_name) || text(row.referrer_name),
|
||||
localItemId: text(row.item_row_id),
|
||||
skuId: text(row.sku_id),
|
||||
itemId: text(row.i_id),
|
||||
shopSkuId: text(row.shop_sku_id),
|
||||
shopItemId: text(row.shop_i_id),
|
||||
propertiesValue: text(row.properties_value),
|
||||
itemName: text(row.name),
|
||||
basePrice: numberValue(row.base_price),
|
||||
price: numberValue(row.price),
|
||||
qty: Math.max(0, Math.trunc(numberValue(row.qty))),
|
||||
amount: numberValue(row.amount),
|
||||
afterSaleAmount: 0,
|
||||
afterSaleQty: 0,
|
||||
finalShipAmount: numberValue(row.amount),
|
||||
finalShipQty: Math.max(0, Math.trunc(numberValue(row.qty))),
|
||||
orderPaidAmount: nullableNumberValue(row.paid_amount),
|
||||
outerOiId: text(row.outer_oi_id),
|
||||
costPrice: null,
|
||||
goodsValue: null,
|
||||
clearancePrice: null,
|
||||
clearanceGoodsValue: null,
|
||||
refundStatus: '',
|
||||
refundQty: 0,
|
||||
}]
|
||||
})
|
||||
return allocateExternalSalesPaidAmounts(rows)
|
||||
}
|
||||
|
||||
function mapAfterSaleRow(row: Record<string, unknown>): ExternalSalesAfterSaleRow[] {
|
||||
const shopName = targetShop(row.shop_name)
|
||||
const orderNo = text(row.so_id) || text(row.raw_so_id)
|
||||
const asDate = dateTimeText(row.as_date)
|
||||
if (!shopName || !orderNo || !asDate) return []
|
||||
const refundAmount = numberValue(row.item_amount)
|
||||
const refundQty = Math.max(0, Math.trunc(numberValue(row.qty)))
|
||||
return [{
|
||||
asId: `${text(row.as_id)}|${text(row.item_row_id)}`,
|
||||
outerAsId: text(row.outer_as_id),
|
||||
orderNo,
|
||||
shopName,
|
||||
asDate,
|
||||
afterSaleStatus: text(row.status),
|
||||
afterSaleType: text(row.type),
|
||||
refundPhase: text(row.refund_phase),
|
||||
goodsStatus: text(row.goods_status),
|
||||
creatorName: text(row.creator_name),
|
||||
questionType: text(row.question_type),
|
||||
buyerApplyRefund: numberValue(row.buyer_apply_refund),
|
||||
refundAmount,
|
||||
receiveRefund: numberValue(row.buyer_receive_refund),
|
||||
confirmDate: dateTimeText(row.confirm_date),
|
||||
localItemId: text(row.item_row_id),
|
||||
skuId: text(row.sku_id),
|
||||
itemId: text(row.i_id),
|
||||
shopSkuId: text(row.shop_sku_id),
|
||||
itemName: text(row.item_name),
|
||||
propertiesValue: text(row.properties_value),
|
||||
qty: refundQty,
|
||||
returnedQty: Math.max(0, Math.trunc(numberValue(row.returned_qty))),
|
||||
amount: numberValue(row.item_amount),
|
||||
remark: text(row.item_remark) || text(row.remark),
|
||||
}]
|
||||
}
|
||||
|
||||
export async function getExternalSalesAfterSalePage(input: {
|
||||
page: number
|
||||
pageSize: number
|
||||
keyword?: string
|
||||
shopName?: ExternalSalesTargetShop | ''
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
orderNo?: string
|
||||
itemCode?: string
|
||||
}) {
|
||||
const where = buildExternalSalesAfterSaleWhereSql(input)
|
||||
const offset = (input.page - 1) * input.pageSize
|
||||
const pool = await sourcePool().connect()
|
||||
const aggregateSql = `
|
||||
SELECT COUNT_BIG(*) AS row_count,
|
||||
SUM(TRY_CONVERT(decimal(18,4), ISNULL(i.amount, '0'))) AS refund_amount,
|
||||
SUM(CAST(ISNULL(i.qty, 0) AS bigint)) AS refund_qty
|
||||
FROM JianSun.dbo.jst_qmcust_refundlist h
|
||||
INNER JOIN JianSun.dbo.jst_qmcust_refundlist_item i ON i.as_id = h.as_id
|
||||
WHERE ${where}`
|
||||
const pageSql = `
|
||||
SELECT h.as_id, h.outer_as_id, h.so_id, h.raw_so_id, h.as_date,
|
||||
h.status, h.type, h.shop_name, h.creator_name, h.question_type,
|
||||
h.buyer_apply_refund, h.buyer_receive_refund, h.confirm_date, h.remark,
|
||||
h.refund_phase, h.good_status,
|
||||
i.asi_id AS item_row_id, i.sku_id, i.i_id, i.shop_sku_id,
|
||||
i.name AS item_name, i.properties_value, i.qty, i.r_qty AS returned_qty,
|
||||
TRY_CONVERT(decimal(18,4), ISNULL(i.amount, '0')) AS item_amount,
|
||||
i.remark AS item_remark
|
||||
FROM JianSun.dbo.jst_qmcust_refundlist h
|
||||
INNER JOIN JianSun.dbo.jst_qmcust_refundlist_item i ON i.as_id = h.as_id
|
||||
WHERE ${where}
|
||||
ORDER BY h.as_date DESC, h.as_id DESC, i.asi_id DESC
|
||||
OFFSET ${offset} ROWS FETCH NEXT ${input.pageSize} ROWS ONLY`
|
||||
const [aggregate, page] = await Promise.all([
|
||||
pool.request().query<Record<string, unknown>>(
|
||||
`SELECT * FROM OPENQUERY([JianSun_Old], N'${aggregateSql.replaceAll("'", "''")}')`,
|
||||
),
|
||||
pool.request().query<Record<string, unknown>>(
|
||||
`SELECT * FROM OPENQUERY([JianSun_Old], N'${pageSql.replaceAll("'", "''")}')`,
|
||||
),
|
||||
])
|
||||
const total = numberValue(aggregate.recordset[0]?.row_count)
|
||||
const totalPages = Math.max(1, Math.ceil(total / input.pageSize))
|
||||
return {
|
||||
rows: page.recordset.flatMap(mapAfterSaleRow),
|
||||
pageInfo: {
|
||||
page: Math.min(Math.max(1, input.page), totalPages),
|
||||
pageSize: input.pageSize,
|
||||
total,
|
||||
totalPages,
|
||||
},
|
||||
totals: {
|
||||
afterSaleCount: total,
|
||||
refundAmount: numberValue(aggregate.recordset[0]?.refund_amount),
|
||||
refundQty: numberValue(aggregate.recordset[0]?.refund_qty),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function listExternalSalesAfterSaleMetrics(orderNos: readonly string[]) {
|
||||
const uniqueOrderNos = [...new Set(orderNos.map((value) => value.trim()).filter(Boolean))]
|
||||
if (uniqueOrderNos.length === 0) return [] as ExternalSalesAfterSaleMetric[]
|
||||
const pool = await sourcePool().connect()
|
||||
const chunks: string[][] = []
|
||||
for (let offset = 0; offset < uniqueOrderNos.length; offset += 50) {
|
||||
chunks.push(uniqueOrderNos.slice(offset, offset + 50))
|
||||
}
|
||||
const results = await Promise.all(chunks.map((chunk) => {
|
||||
const sourceSql = buildExternalSalesAfterSaleMetricsSql(chunk)
|
||||
return pool.request().query<Record<string, unknown>>(
|
||||
`SELECT * FROM OPENQUERY([JianSun_Old], N'${sourceSql.replaceAll("'", "''")}')`,
|
||||
)
|
||||
}))
|
||||
return results.flatMap((result) => result.recordset.flatMap((row): ExternalSalesAfterSaleMetric[] => {
|
||||
const orderNo = text(row.order_no)
|
||||
if (!orderNo) return []
|
||||
return [{
|
||||
orderNo,
|
||||
afterSaleAmount: numberValue(row.after_sale_amount),
|
||||
afterSaleQty: Math.max(0, Math.trunc(numberValue(row.after_sale_qty))),
|
||||
}]
|
||||
}))
|
||||
}
|
||||
|
||||
export async function listExternalSalesDetailAfterSaleMetrics(orderNos: readonly string[]) {
|
||||
const uniqueOrderNos = [...new Set(orderNos.map((value) => value.trim()).filter(Boolean))]
|
||||
if (uniqueOrderNos.length === 0) return [] as ExternalSalesDetailAfterSaleMetric[]
|
||||
const pool = await sourcePool().connect()
|
||||
const chunks: string[][] = []
|
||||
for (let offset = 0; offset < uniqueOrderNos.length; offset += 50) {
|
||||
chunks.push(uniqueOrderNos.slice(offset, offset + 50))
|
||||
}
|
||||
const results = await Promise.all(chunks.map((chunk) => {
|
||||
const sourceSql = buildExternalSalesDetailAfterSaleMetricsSql(chunk)
|
||||
return pool.request().query<Record<string, unknown>>(
|
||||
`SELECT * FROM OPENQUERY([JianSun_Old], N'${sourceSql.replaceAll("'", "''")}')`,
|
||||
)
|
||||
}))
|
||||
return results.flatMap((result) => result.recordset.flatMap((row): ExternalSalesDetailAfterSaleMetric[] => {
|
||||
const orderNo = text(row.order_no)
|
||||
const skuId = text(row.sku_id)
|
||||
if (!orderNo || !skuId) return []
|
||||
return [{
|
||||
orderNo,
|
||||
skuId,
|
||||
afterSaleAmount: numberValue(row.after_sale_amount),
|
||||
afterSaleQty: Math.max(0, Math.trunc(numberValue(row.after_sale_qty))),
|
||||
}]
|
||||
}))
|
||||
}
|
||||
|
||||
export async function listExternalSalesWaybillFreight(trackingNos: readonly string[]) {
|
||||
const uniqueTrackingNos = [...new Set(
|
||||
trackingNos.map((value) => value.trim()).filter(Boolean),
|
||||
)]
|
||||
if (uniqueTrackingNos.length === 0) return [] as ExternalSalesWaybillFreight[]
|
||||
const pool = await sourcePool().connect()
|
||||
const chunks: string[][] = []
|
||||
for (let offset = 0; offset < uniqueTrackingNos.length; offset += 50) {
|
||||
chunks.push(uniqueTrackingNos.slice(offset, offset + 50))
|
||||
}
|
||||
const results = await Promise.all(chunks.map((chunk) => {
|
||||
const sourceSql = buildExternalSalesWaybillFreightSql(chunk)
|
||||
return pool.request().query<Record<string, unknown>>(
|
||||
`SELECT * FROM OPENQUERY([JianSun_Old], N'${sourceSql.replaceAll("'", "''")}')`,
|
||||
)
|
||||
}))
|
||||
return results.flatMap((result) => result.recordset.flatMap((row): ExternalSalesWaybillFreight[] => {
|
||||
const trackingNo = text(row.tracking_no)
|
||||
if (!trackingNo || row.freight_cost === null || row.freight_cost === undefined) return []
|
||||
const freightCost = numberValue(row.freight_cost)
|
||||
return freightCost >= 0 ? [{ trackingNo, freightCost }] : []
|
||||
}))
|
||||
}
|
||||
@ -0,0 +1,96 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import type { ExternalFreightImportRow } from '@/lib/external-freight'
|
||||
|
||||
export type ExternalFreightRecordInput = ExternalFreightImportRow & {
|
||||
sourceFileName: string
|
||||
importedById: string
|
||||
importedByName: string
|
||||
}
|
||||
|
||||
type ExternalFreightDatabaseRow = {
|
||||
id: string
|
||||
shipMonth: string
|
||||
orderNo: string
|
||||
outboundQty: number
|
||||
incomeAfterTaxRefund: Prisma.Decimal | null
|
||||
estimatedFreight: Prisma.Decimal
|
||||
remark: string
|
||||
sourceFileName: string
|
||||
importedByName: string
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
class SupplyChainExternalFreightRepository {
|
||||
async listAll() {
|
||||
return prisma.$queryRaw<ExternalFreightDatabaseRow[]>(Prisma.sql`
|
||||
SELECT
|
||||
"id",
|
||||
"shipMonth",
|
||||
"orderNo",
|
||||
"outboundQty",
|
||||
"incomeAfterTaxRefund",
|
||||
"estimatedFreight",
|
||||
"remark",
|
||||
"sourceFileName",
|
||||
"importedByName",
|
||||
"createdAt",
|
||||
"updatedAt"
|
||||
FROM "SupplyChainExternalFreightRecord"
|
||||
ORDER BY "updatedAt" DESC, "orderNo" ASC
|
||||
`)
|
||||
}
|
||||
|
||||
async upsertMany(rows: readonly ExternalFreightRecordInput[]) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
for (const row of rows) {
|
||||
await tx.$executeRaw(Prisma.sql`
|
||||
INSERT INTO "SupplyChainExternalFreightRecord" (
|
||||
"id",
|
||||
"shipMonth",
|
||||
"orderNo",
|
||||
"outboundQty",
|
||||
"incomeAfterTaxRefund",
|
||||
"estimatedFreight",
|
||||
"remark",
|
||||
"sourceFileName",
|
||||
"importedById",
|
||||
"importedByName",
|
||||
"createdAt",
|
||||
"updatedAt"
|
||||
)
|
||||
VALUES (
|
||||
${randomUUID()},
|
||||
${row.shipMonth},
|
||||
${row.orderNo},
|
||||
${row.outboundQty},
|
||||
${row.incomeAfterTaxRefund},
|
||||
${row.estimatedFreight},
|
||||
${row.remark},
|
||||
${row.sourceFileName},
|
||||
${row.importedById},
|
||||
${row.importedByName},
|
||||
CURRENT_TIMESTAMP,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT ("orderNo") DO UPDATE SET
|
||||
"shipMonth" = EXCLUDED."shipMonth",
|
||||
"outboundQty" = EXCLUDED."outboundQty",
|
||||
"incomeAfterTaxRefund" = EXCLUDED."incomeAfterTaxRefund",
|
||||
"estimatedFreight" = EXCLUDED."estimatedFreight",
|
||||
"remark" = EXCLUDED."remark",
|
||||
"sourceFileName" = EXCLUDED."sourceFileName",
|
||||
"importedById" = EXCLUDED."importedById",
|
||||
"importedByName" = EXCLUDED."importedByName",
|
||||
"updatedAt" = CURRENT_TIMESTAMP
|
||||
`)
|
||||
}
|
||||
}, { maxWait: 10_000, timeout: 120_000 })
|
||||
return rows.length
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainExternalFreightRepository =
|
||||
new SupplyChainExternalFreightRepository()
|
||||
@ -0,0 +1,26 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import { buildExternalClearancePriceRows } from '@/lib/external-clearance-price'
|
||||
import { listExternalClearancePriceSourceRows } from '@/server/repositories/external-clearance-price.repository'
|
||||
|
||||
export const externalClearancePriceService = {
|
||||
async list() {
|
||||
try {
|
||||
const rows = await listExternalClearancePriceSourceRows()
|
||||
return buildExternalClearancePriceRows(rows.map((row) => ({
|
||||
onlineOrderNo: row.onlineOrderNo,
|
||||
internalOrderNo: row.internalOrderNo,
|
||||
productCode: row.productCode,
|
||||
styleCode: row.styleCode,
|
||||
shopProductCode: row.shopProductCode,
|
||||
shopStyleCode: row.shopStyleCode,
|
||||
costPrice: row.costPrice.toString(),
|
||||
})))
|
||||
} catch (error) {
|
||||
console.error('[external-clearance-price] list failed', error)
|
||||
throw new AppError(
|
||||
ErrorCode.SYSTEM_DATABASE,
|
||||
'清货价数据读取失败,请稍后刷新重试',
|
||||
)
|
||||
}
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
import {
|
||||
buildExternalProfitRows,
|
||||
type ExternalProfitBasis,
|
||||
} from '@/lib/external-profit'
|
||||
import type { ExternalSalesDetailRow } from '@/lib/external-sales'
|
||||
import { externalSalesService } from '@/server/services/external-sales.service'
|
||||
import { supplyChainExternalFreightService } from '@/server/services/supply-chain-external-freight.service'
|
||||
|
||||
export const externalProfitService = {
|
||||
async getData(basis: ExternalProfitBasis) {
|
||||
const [salesPage, freightRows] = await Promise.all([
|
||||
externalSalesService.getPage({
|
||||
view: 'detail',
|
||||
page: 1,
|
||||
pageSize: 100_000,
|
||||
}),
|
||||
supplyChainExternalFreightService.list(),
|
||||
])
|
||||
return {
|
||||
basis,
|
||||
generatedAt: new Date().toISOString(),
|
||||
rows: buildExternalProfitRows({
|
||||
basis,
|
||||
salesRows: salesPage.rows as ExternalSalesDetailRow[],
|
||||
freightRows: freightRows.map((row) => ({
|
||||
shipMonth: row.shipMonth,
|
||||
estimatedFreight: row.estimatedFreight,
|
||||
})),
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,198 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import {
|
||||
EXTERNAL_SALES_TARGET_SHOPS,
|
||||
applyExternalSalesAfterSaleMetrics,
|
||||
applyExternalSalesClearancePrices,
|
||||
applyExternalSalesFreight,
|
||||
buildExternalSalesSummary,
|
||||
enrichExternalSalesItemCosts,
|
||||
externalSalesDateSpan,
|
||||
filterExternalSalesItems,
|
||||
paginateExternalSales,
|
||||
toExternalSalesDetailRows,
|
||||
type ExternalSalesItemRow,
|
||||
type ExternalSalesPage,
|
||||
type ExternalSalesDetailFilters,
|
||||
type ExternalSalesTargetShop,
|
||||
type ExternalSalesView,
|
||||
} from '@/lib/external-sales'
|
||||
import {
|
||||
getExternalSalesAfterSalePage,
|
||||
listExternalSalesAfterSaleMetrics,
|
||||
listExternalSalesDetailAfterSaleMetrics,
|
||||
listExternalSalesItems,
|
||||
listExternalSalesWaybillFreight,
|
||||
} from '@/server/repositories/external-sales.repository'
|
||||
import { externalClearancePriceService } from '@/server/services/external-clearance-price.service'
|
||||
import { listExternalSalesArchiveCosts } from '@/server/repositories/external-sales-cost.repository'
|
||||
|
||||
const CACHE_TTL_MS = 5 * 60_000
|
||||
const cache = new Map<string, {
|
||||
fetchedAt: number
|
||||
generatedAt: string
|
||||
rows: ExternalSalesItemRow[]
|
||||
}>()
|
||||
|
||||
async function loadItems(input: {
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shopName: ExternalSalesTargetShop | ''
|
||||
}) {
|
||||
if (input.dateFrom && input.dateTo && !externalSalesDateSpan(input.dateFrom, input.dateTo)) {
|
||||
throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, '统计时间范围不正确')
|
||||
}
|
||||
const key = `${input.dateFrom || '*'}|${input.dateTo || '*'}|${input.shopName}`
|
||||
const cached = cache.get(key)
|
||||
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) return cached
|
||||
const rows = await listExternalSalesItems(input)
|
||||
const result = {
|
||||
fetchedAt: Date.now(),
|
||||
generatedAt: new Date().toISOString(),
|
||||
rows,
|
||||
}
|
||||
cache.set(key, result)
|
||||
return result
|
||||
}
|
||||
|
||||
export const externalSalesService = {
|
||||
async getPage(input: {
|
||||
view: ExternalSalesView
|
||||
dateFrom?: string
|
||||
dateTo?: string
|
||||
shopName?: ExternalSalesTargetShop | ''
|
||||
keyword?: string
|
||||
orderNo?: string
|
||||
itemCode?: string
|
||||
detailFilters?: ExternalSalesDetailFilters
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}): Promise<ExternalSalesPage> {
|
||||
const shopName = input.shopName && EXTERNAL_SALES_TARGET_SHOPS.includes(input.shopName)
|
||||
? input.shopName
|
||||
: ''
|
||||
if (input.view === 'afterSale') {
|
||||
const source = await getExternalSalesAfterSalePage({
|
||||
page: input.page ?? 1,
|
||||
pageSize: input.pageSize ?? 50,
|
||||
keyword: input.keyword,
|
||||
shopName,
|
||||
dateFrom: input.dateFrom,
|
||||
dateTo: input.dateTo,
|
||||
orderNo: input.orderNo,
|
||||
itemCode: input.itemCode,
|
||||
})
|
||||
return {
|
||||
view: input.view,
|
||||
dateFrom: input.dateFrom || '',
|
||||
dateTo: input.dateTo || '',
|
||||
shopName,
|
||||
generatedAt: new Date().toISOString(),
|
||||
rows: source.rows,
|
||||
pageInfo: source.pageInfo,
|
||||
totals: {
|
||||
orderCount: 0,
|
||||
shipAmount: 0,
|
||||
shipQty: 0,
|
||||
afterSaleCount: source.totals.afterSaleCount,
|
||||
refundQty: source.totals.refundQty,
|
||||
refundAmount: source.totals.refundAmount,
|
||||
},
|
||||
}
|
||||
}
|
||||
const source = await loadItems({
|
||||
dateFrom: input.dateFrom || '',
|
||||
dateTo: input.dateTo || '',
|
||||
shopName,
|
||||
})
|
||||
const filtered = filterExternalSalesItems(
|
||||
source.rows,
|
||||
input.keyword ?? '',
|
||||
input.view === 'detail' ? input.detailFilters : {},
|
||||
)
|
||||
const detailSource = input.view === 'detail' && filtered.length > 0
|
||||
? await Promise.all([
|
||||
listExternalSalesArchiveCosts(filtered.map((row) => row.skuId)),
|
||||
listExternalSalesDetailAfterSaleMetrics([
|
||||
...new Set(filtered.map((row) => row.orderNo)),
|
||||
]),
|
||||
listExternalSalesWaybillFreight([
|
||||
...new Set(filtered.map((row) => row.trackingNo)),
|
||||
]),
|
||||
externalClearancePriceService.list(),
|
||||
]).then(([archiveCosts, afterSaleMetrics, waybillFreight, clearancePrices]) => (
|
||||
applyExternalSalesClearancePrices(
|
||||
applyExternalSalesFreight(
|
||||
applyExternalSalesAfterSaleMetrics(
|
||||
enrichExternalSalesItemCosts(filtered, archiveCosts),
|
||||
afterSaleMetrics,
|
||||
),
|
||||
waybillFreight,
|
||||
),
|
||||
clearancePrices,
|
||||
)
|
||||
))
|
||||
: filtered
|
||||
const afterSaleMetrics = input.view === 'summary'
|
||||
? await listExternalSalesAfterSaleMetrics([...new Set(filtered.map((row) => row.orderNo))])
|
||||
: []
|
||||
const summaryRows = buildExternalSalesSummary(filtered, afterSaleMetrics)
|
||||
const detailRows = toExternalSalesDetailRows(detailSource)
|
||||
const detailTotals = input.view === 'detail'
|
||||
? {
|
||||
shipAmount: Math.round(detailSource.reduce((sum, row) => sum + row.amount, 0) * 100) / 100,
|
||||
shipQty: detailSource.reduce((sum, row) => sum + row.qty, 0),
|
||||
afterSaleCount: detailSource.filter(
|
||||
(row) => row.afterSaleAmount > 0 || row.afterSaleQty > 0,
|
||||
).length,
|
||||
refundQty: detailSource.reduce((sum, row) => sum + row.afterSaleQty, 0),
|
||||
refundAmount: Math.round(
|
||||
detailSource.reduce((sum, row) => sum + row.afterSaleAmount, 0) * 100,
|
||||
) / 100,
|
||||
goodsValue: Math.round(
|
||||
detailSource.reduce((sum, row) => sum + (row.goodsValue ?? 0), 0) * 100,
|
||||
) / 100,
|
||||
freight: Math.round(
|
||||
detailSource.reduce((sum, row) => sum + (row.freight ?? 0), 0) * 100,
|
||||
) / 100,
|
||||
clearanceGoodsValue: Math.round(
|
||||
detailSource.reduce((sum, row) => sum + (row.clearanceGoodsValue ?? 0), 0) * 100,
|
||||
) / 100,
|
||||
}
|
||||
: null
|
||||
const pageSize = input.pageSize ?? 50
|
||||
const paged = input.view === 'summary'
|
||||
? paginateExternalSales(summaryRows, input.page ?? 1, pageSize)
|
||||
: paginateExternalSales(detailRows, input.page ?? 1, pageSize)
|
||||
return {
|
||||
view: input.view,
|
||||
dateFrom: input.dateFrom || '',
|
||||
dateTo: input.dateTo || '',
|
||||
shopName,
|
||||
generatedAt: source.generatedAt,
|
||||
rows: paged.rows,
|
||||
detailColumnAvailability: input.view === 'detail'
|
||||
? {
|
||||
shopSkuId: filtered.some((row) => row.shopSkuId.trim().length > 0),
|
||||
shopItemId: filtered.some((row) => row.shopItemId.trim().length > 0),
|
||||
}
|
||||
: undefined,
|
||||
pageInfo: paged.pageInfo,
|
||||
totals: {
|
||||
orderCount: summaryRows.length,
|
||||
shipAmount: detailTotals?.shipAmount ??
|
||||
Math.round(summaryRows.reduce((total, row) => total + row.shipAmount, 0) * 100) / 100,
|
||||
shipQty: detailTotals?.shipQty ??
|
||||
summaryRows.reduce((total, row) => total + row.shipQty, 0),
|
||||
afterSaleCount: detailTotals?.afterSaleCount ??
|
||||
summaryRows.filter((row) => row.afterSaleQty > 0).length,
|
||||
refundQty: detailTotals?.refundQty ??
|
||||
summaryRows.reduce((total, row) => total + row.afterSaleQty, 0),
|
||||
refundAmount: detailTotals?.refundAmount ??
|
||||
Math.round(summaryRows.reduce((total, row) => total + row.afterSaleAmount, 0) * 100) / 100,
|
||||
goodsValue: detailTotals?.goodsValue,
|
||||
freight: detailTotals?.freight,
|
||||
clearanceGoodsValue: detailTotals?.clearanceGoodsValue,
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
@ -0,0 +1,90 @@
|
||||
import { AppError, ErrorCode } from '@/server/core/errors'
|
||||
import type { AuthUser } from '@/server/core/types'
|
||||
import {
|
||||
createExternalFreightTemplate,
|
||||
parseExternalFreightWorkbook,
|
||||
type ExternalFreightRecordView,
|
||||
} from '@/lib/external-freight'
|
||||
import {
|
||||
supplyChainExternalFreightRepository,
|
||||
type ExternalFreightRecordInput,
|
||||
} from '@/server/repositories/supply-chain-external-freight.repository'
|
||||
|
||||
type Repository = Pick<typeof supplyChainExternalFreightRepository, 'listAll' | 'upsertMany'>
|
||||
|
||||
function number(value: unknown) {
|
||||
return value == null ? null : Number(value)
|
||||
}
|
||||
|
||||
export class SupplyChainExternalFreightService {
|
||||
constructor(
|
||||
private readonly repository: Repository = supplyChainExternalFreightRepository,
|
||||
) {}
|
||||
|
||||
async list(): Promise<ExternalFreightRecordView[]> {
|
||||
let rows
|
||||
try {
|
||||
rows = await this.repository.listAll()
|
||||
} catch (error) {
|
||||
console.error('[external-freight] list failed', error)
|
||||
throw new AppError(
|
||||
ErrorCode.SYSTEM_DATABASE,
|
||||
'货代费数据读取失败,请稍后刷新重试',
|
||||
)
|
||||
}
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
shipMonth: row.shipMonth,
|
||||
orderNo: row.orderNo,
|
||||
outboundQty: row.outboundQty,
|
||||
incomeAfterTaxRefund: number(row.incomeAfterTaxRefund),
|
||||
estimatedFreight: number(row.estimatedFreight) ?? 0,
|
||||
remark: row.remark,
|
||||
sourceFileName: row.sourceFileName,
|
||||
importedByName: row.importedByName,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
}))
|
||||
}
|
||||
|
||||
async importFile(input: {
|
||||
fileName: string
|
||||
buffer: Buffer
|
||||
user: AuthUser
|
||||
}) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = await parseExternalFreightWorkbook(input.buffer)
|
||||
} catch (error) {
|
||||
throw new AppError(
|
||||
ErrorCode.VALIDATION_INVALID_FORMAT,
|
||||
`${input.fileName}:${error instanceof Error ? error.message : '文件格式不正确'}`,
|
||||
)
|
||||
}
|
||||
const rows: ExternalFreightRecordInput[] = parsed.map((row) => ({
|
||||
...row,
|
||||
orderNo: row.orderNo.trim().toUpperCase(),
|
||||
sourceFileName: input.fileName,
|
||||
importedById: input.user.id,
|
||||
importedByName: input.user.name,
|
||||
}))
|
||||
let importedCount
|
||||
try {
|
||||
importedCount = await this.repository.upsertMany(rows)
|
||||
} catch (error) {
|
||||
console.error('[external-freight] import failed', error)
|
||||
throw new AppError(
|
||||
ErrorCode.SYSTEM_DATABASE,
|
||||
'货代费导入失败,请检查模板或稍后重试',
|
||||
)
|
||||
}
|
||||
return { importedCount, fileName: input.fileName }
|
||||
}
|
||||
|
||||
createTemplate() {
|
||||
return createExternalFreightTemplate()
|
||||
}
|
||||
}
|
||||
|
||||
export const supplyChainExternalFreightService =
|
||||
new SupplyChainExternalFreightService()
|
||||
Loading…
x
Reference in New Issue
Block a user