feat(线上代发价格): 识别改版明细表格 + 新增报销成本核查(多报销) (#841)

1) 钉钉「线上代发业务报销」有 23 张已通过审批单的商品明细表格不叫“收款费用明细”(新版模板表格名为空、旧单叫“费用明细”),
   同步时整单只剩一行空明细。按名称找不到时改取行内含“商品ID”列的明细表格;料号兼容新版“商品编码”。上线后对该数据集全量重同步。
2) 新增报销成本核查:按聚水潭订单由本行商品编码拆出的子商品,取普通商品资料成本价×发货数量求和为系统成本,
   与代发订单金额比较,高出 0.01 元以上判“多报销”,另有“成本缺失”“无发货明细”;页面新增筛选、计数、多报销金额汇总及四列,导出同步。

涉及:金额核查展示(只读)、镜像全量重同步;不涉及迁移、权限和上游写入。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VANWYsNUbu2piMtCKymoyd
This commit is contained in:
limeng 2026-11-03 17:13:56 +08:00
parent 78115f38d2
commit 43390be327
8 changed files with 496 additions and 14 deletions

View File

@ -6930,7 +6930,7 @@ class Pages extends Controller
fputcsv($csv, [
'审批编号', '标题', '状态', '申请人', '收款人全称', '标签', '商品ID', '商品名称(匹配)', '店铺名称',
'代发交易单号', '店铺交易单号', '发货数量', '订单实付金额', '代发订单金额', '差价',
'供应商名称', '商品编码', '实际发货商品编码', '聚水潭标记|多标签', '创建时间',
'供应商名称', '商品编码', '实际发货商品编码', '系统成本', '报销−成本', '成本核查', '成本明细', '聚水潭标记|多标签', '创建时间',
]);
foreach ($this->onlineDaifaPrices->exportRows($filters) as $row) {
@ -6964,6 +6964,10 @@ class Pages extends Controller
$this->csvText($row['supplier_name'] ?? ''),
$this->csvIdentifier($row['material_no'] ?? ''),
$this->csvText($row['ship_skus'] ?? ''),
$row['system_cost'] ?? null,
$row['cost_diff'] ?? null,
$this->csvText($row['audit_result'] ?? ''),
$this->csvText(str_replace("\n", ';', (string) ($row['audit_detail'] ?? ''))),
$this->csvText($row['jst_labels'] ?? ''),
$this->csvText($row['workflow_created_at'] ?? ''),
]);
@ -6994,6 +6998,7 @@ class Pages extends Controller
'supplier_name' => $clean($request->query('supplier_name', ''), 120),
'material_no' => $clean($request->query('material_no', ''), 120),
'status' => preg_match('/^[A-Z_]+$/', $status) === 1 ? $status : '',
'audit' => in_array($audit = trim((string) $request->query('audit', '')), DingOnlineDaifaPriceMirrorRepository::AUDIT_RESULTS, true) ? $audit : '',
'created_from' => $date($request->query('created_from', '')),
'created_to' => $date($request->query('created_to', '')),
];

View File

@ -167,7 +167,8 @@ return [
'shop_trade_no' => '店铺交易单号',
'shop_name' => '店铺名称',
'supplier_name' => '供应商名称',
'material_no' => '料号',
// 新版模板用“商品编码”替代了“料号”,两个都认。
'material_no' => ['料号', '商品编码'],
'ship_qty' => '订单发货数量',
'paid_amount' => '订单实付金额',
'daifa_amount' => '代发订单金额',
@ -183,6 +184,9 @@ return [
// 若审批模板把“一个商品一行”放在明细表格里,填写该表格的字段名,
// 同步器会按明细行展开为多条镜像记录;留空则整张表单视为单行。
'detail_table' => env('DING_ONLINE_DAIFA_PRICE_DETAIL_TABLE', ''),
// 按名称找不到明细表格时(模板改版后表格名为空、或旧版叫“费用明细”),
// 改用行内含有该列的明细表格,避免整单只剩一行空明细。
'detail_table_match_label' => '商品ID',
// 收款人过滤(可选):默认不过滤,以便页面按收款人展示“刘萧代发”或
// “1688代发”标签。需要限定公司时可通过环境变量按全称精确匹配。
'row_filters' => [

View File

@ -5,6 +5,7 @@ namespace Modules\EcommerceFinance\Repositories;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Services\DingPayableWorkflowStatus;
@ -37,6 +38,22 @@ class DingOnlineDaifaPriceMirrorRepository
private const EXPORT_HYDRATE_BATCH = 200;
/** 报销成本核查结果:代发订单金额 vs Σ(实际发货子商品成本价 × 数量)。 */
public const AUDIT_OVER = '多报销';
public const AUDIT_OK = '正常';
public const AUDIT_COST_MISSING = '成本缺失';
public const AUDIT_NO_SHIPMENT = '无发货明细';
public const AUDIT_RESULTS = [self::AUDIT_OVER, self::AUDIT_OK, self::AUDIT_COST_MISSING, self::AUDIT_NO_SHIPMENT];
/** 报销金额比系统成本高出超过此值即判为多报销(元)。 */
private const AUDIT_TOLERANCE = 0.01;
private const AUDIT_CACHE_SECONDS = 600;
private readonly ConnectionInterface $connection;
/** @var array<string,array<string,mixed>>|null */
@ -102,12 +119,23 @@ class DingOnlineDaifaPriceMirrorRepository
'price_diff' => round((float) ($aggregate->price_diff ?? 0), 2),
];
$pageRows = $this->filteredQuery($filters)
->orderByDesc('workflow_created_at')
->orderByDesc('process_instance_id')
->orderByDesc('detail_index')
->forPage($page, $perPage)
->get();
if (($filters['audit'] ?? '') === '') {
$pageRows = $this->filteredQuery($filters)
->orderByDesc('workflow_created_at')
->orderByDesc('process_instance_id')
->orderByDesc('detail_index')
->forPage($page, $perPage)
->get();
}
}
$audit = $total > 0 ? $this->auditIndex($filters) : ['keys' => [], 'counts' => [], 'over_amount' => 0.0];
$summary['audit_counts'] = $audit['counts'];
$summary['over_amount'] = $audit['over_amount'];
if (($filters['audit'] ?? '') !== '') {
$keys = $audit['keys'][$filters['audit']] ?? [];
$total = count($keys);
$pageRows = $this->rowsForKeys(array_slice($keys, ($page - 1) * $perPage, $perPage), $filters);
}
$data = [];
@ -115,6 +143,7 @@ class DingOnlineDaifaPriceMirrorRepository
$data[] = $this->presentRow($row);
}
$this->attachJstOrderDetails($data);
$this->attachCostAudit($data);
$sources = $this->sourceStatuses();
$readySources = array_filter($sources, static fn (array $source): bool => (bool) ($source['ready'] ?? false));
@ -139,6 +168,21 @@ class DingOnlineDaifaPriceMirrorRepository
throw new RuntimeException('business_mirror_dataset_not_ready');
}
if (($filters['audit'] ?? '') !== '') {
$keys = $this->auditIndex($filters)['keys'][$filters['audit']] ?? [];
foreach (array_chunk($keys, self::EXPORT_HYDRATE_BATCH) as $chunk) {
$buffer = [];
foreach ($this->rowsForKeys($chunk, $filters) as $row) {
$buffer[] = $this->presentRow($row);
}
$this->attachJstOrderDetails($buffer);
$this->attachCostAudit($buffer);
yield from $buffer;
}
return;
}
$rows = $this->filteredQuery($filters)
->orderByDesc('workflow_created_at')
->orderByDesc('process_instance_id')
@ -150,12 +194,14 @@ class DingOnlineDaifaPriceMirrorRepository
$buffer[] = $this->presentRow($row);
if (count($buffer) >= self::EXPORT_HYDRATE_BATCH) {
$this->attachJstOrderDetails($buffer);
$this->attachCostAudit($buffer);
yield from $buffer;
$buffer = [];
}
}
if ($buffer !== []) {
$this->attachJstOrderDetails($buffer);
$this->attachCostAudit($buffer);
yield from $buffer;
}
}
@ -608,6 +654,200 @@ class DingOnlineDaifaPriceMirrorRepository
];
}
/**
* 报销成本核查:只针对钉钉行。系统成本 = Σ(实际发货子商品在普通商品资料的成本价 × 发货数量),
* 组合装按聚水潭订单里由本行商品编码拆出的子商品计算;代发订单金额 − 系统成本 > 0.01 即判为多报销。
*
* @param list<array<string,mixed>> $rows
*/
private function attachCostAudit(array &$rows): void
{
$skus = [];
foreach ($rows as &$row) {
$row['system_cost'] = null;
$row['cost_diff'] = null;
$row['audit_result'] = '';
$row['audit_detail'] = '';
if (($row['source_type'] ?? 'ding') !== 'ding') {
continue;
}
foreach ((array) ($row['ship_sku_items'] ?? []) as $item) {
$skus[(string) $item['sku_id']] = true;
}
}
unset($row);
$costs = $this->normalCostPrices(array_keys($skus));
foreach ($rows as &$row) {
if (($row['source_type'] ?? 'ding') !== 'ding') {
continue;
}
$items = (array) ($row['ship_sku_items'] ?? []);
if ($items === []) {
$row['audit_result'] = self::AUDIT_NO_SHIPMENT;
continue;
}
$cents = 0;
$missing = [];
$parts = [];
foreach ($items as $item) {
$sku = (string) $item['sku_id'];
$qty = (float) $item['qty'];
if (! isset($costs[$sku])) {
$missing[] = $sku;
$parts[] = $sku . '×' . $this->formatQty($qty) . ' 成本价缺失';
continue;
}
$line = (int) round($costs[$sku] * 100 * $qty);
$cents += $line;
$parts[] = sprintf('%s×%s×%s=%s', $sku, $this->formatQty($qty), rtrim(rtrim(number_format($costs[$sku], 4, '.', ''), '0'), '.'), number_format($line / 100, 2, '.', ''));
}
$row['system_cost'] = round($cents / 100, 2);
$row['audit_detail'] = implode("\n", $parts);
if ($missing !== []) {
$row['audit_result'] = self::AUDIT_COST_MISSING;
continue;
}
if ($row['daifa_amount'] === null) {
continue;
}
$row['cost_diff'] = round((float) $row['daifa_amount'] - $row['system_cost'], 2);
$row['audit_result'] = $row['cost_diff'] > self::AUDIT_TOLERANCE ? self::AUDIT_OVER : self::AUDIT_OK;
}
unset($row);
}
/**
* 普通商品资料成本价(ops_jst_sku,sku_type=normal,同编码取最新一条;空或 0 视为缺失)。
*
* @param list<string> $skus
* @return array<string,float>
*/
private function normalCostPrices(array $skus): array
{
$skus = array_values(array_filter($skus, static fn (string $sku): bool => $sku !== ''));
if ($skus === [] || ! Schema::connection($this->connection->getName())->hasTable('ops_jst_sku')) {
return [];
}
$costs = [];
foreach (array_chunk($skus, self::JST_LOOKUP_CHUNK) as $chunk) {
$records = $this->connection->table('ops_jst_sku')
->whereIn('sku_id', $chunk)
->where('sku_type', 'normal')
->orderByDesc('autoid')
->get(['sku_id', 'cost_price']);
foreach ($records as $record) {
$sku = (string) $record->sku_id;
if (! isset($costs[$sku]) && is_numeric($record->cost_price) && (float) $record->cost_price > 0) {
$costs[$sku] = (float) $record->cost_price;
}
}
}
return $costs;
}
/**
* 当前筛选条件下全部钉钉行的核查结果索引(按页面顺序的行键),供“核查结果”筛选、汇总和导出使用。
* 按筛选条件 + 镜像同步时间缓存 10 分钟。
*
* @return array{keys:array<string,list<string>>,counts:array<string,int>,over_amount:float}
*/
private function auditIndex(array $filters): array
{
$base = $filters;
unset($base['audit']);
$synced = (string) ($this->sourceStatuses()['ding']['last_synced_at'] ?? '');
$key = 'online-daifa:audit-index:v1:' . sha1(json_encode($base) . '|' . $synced);
$cached = Cache::get($key);
if (is_array($cached)) {
return $cached;
}
$index = ['keys' => array_fill_keys(self::AUDIT_RESULTS, []), 'counts' => array_fill_keys(self::AUDIT_RESULTS, 0), 'over_amount' => 0.0];
$buffer = [];
$flush = function () use (&$buffer, &$index): void {
if ($buffer === []) {
return;
}
$this->attachJstOrderDetails($buffer);
$this->attachCostAudit($buffer);
foreach ($buffer as $row) {
$result = (string) $row['audit_result'];
if ($result === '') {
continue;
}
$index['keys'][$result][] = $row['process_instance_id'] . '|' . $row['detail_index'];
$index['counts'][$result]++;
if ($result === self::AUDIT_OVER) {
$index['over_amount'] += (float) $row['cost_diff'];
}
}
$buffer = [];
};
$rows = $this->filteredQuery($base)
->where('source_type', 'ding')
->orderByDesc('workflow_created_at')
->orderByDesc('process_instance_id')
->orderByDesc('detail_index')
->get(['source_type', 'process_instance_id', 'detail_index', 'shop_trade_no', 'material_no', 'daifa_amount']);
foreach ($rows as $row) {
$buffer[] = [
'source_type' => 'ding',
'process_instance_id' => (string) $row->process_instance_id,
'detail_index' => (int) $row->detail_index,
'shop_trade_no' => (string) ($row->shop_trade_no ?? ''),
'material_no' => (string) ($row->material_no ?? ''),
'daifa_amount' => $row->daifa_amount === null ? null : (float) $row->daifa_amount,
];
if (count($buffer) >= self::EXPORT_HYDRATE_BATCH) {
$flush();
}
}
$flush();
$index['over_amount'] = round($index['over_amount'], 2);
try {
Cache::put($key, $index, self::AUDIT_CACHE_SECONDS);
} catch (\Throwable $exception) {
report($exception);
}
return $index;
}
/**
* 按“流程ID|明细序号”取回行,保持传入顺序。
*
* @param list<string> $keys
* @return list<object>
*/
private function rowsForKeys(array $keys, array $filters): array
{
if ($keys === []) {
return [];
}
$base = $filters;
unset($base['audit']);
$pairs = array_map(static fn (string $key): array => explode('|', $key, 2), $keys);
$rows = $this->filteredQuery($base)
->where('source_type', 'ding')
->where(function ($query) use ($pairs): void {
foreach ($pairs as [$id, $index]) {
$query->orWhere(function ($pair) use ($id, $index): void {
$pair->where('process_instance_id', $id)->where('detail_index', (int) $index);
});
}
})
->get();
$byKey = [];
foreach ($rows as $row) {
$byKey[$row->process_instance_id . '|' . $row->detail_index] = $row;
}
return array_values(array_filter(array_map(static fn (string $key) => $byKey[$key] ?? null, $keys)));
}
/** @return array<string,mixed> */
private function presentRow(object $row): array
{

View File

@ -113,6 +113,7 @@ class DingPayableWorkflowMirrorSynchronizer
$columnMap = $extendColumns ? (array) ($config['column_map'] ?? []) : [];
$columnTypes = $extendColumns ? (array) ($config['column_types'] ?? []) : [];
$detailTable = $extendColumns ? trim((string) ($config['detail_table'] ?? '')) : '';
$detailTableMatchLabel = $extendColumns ? trim((string) ($config['detail_table_match_label'] ?? '')) : '';
$resolveProductName = $extendColumns && ! empty($config['resolve_product_name']);
$rowFilters = $extendColumns ? (array) ($config['row_filters'] ?? []) : [];
$onlyStatus = strtoupper(trim((string) ($config['only_status'] ?? '')));
@ -135,7 +136,7 @@ class DingPayableWorkflowMirrorSynchronizer
$workflow['originatorUserName'] = $originatorName;
}
$schemeRows = $schemeById[$id] ?? [];
$detailFieldsList = $this->buildDetailRowFields($schemeRows, $detailTable);
$detailFieldsList = $this->buildDetailRowFields($schemeRows, $detailTable, $detailTableMatchLabel);
$detailIndex = 0;
foreach ($detailFieldsList as $fields) {
$payload = [
@ -148,8 +149,17 @@ class DingPayableWorkflowMirrorSynchronizer
'synced_at' => $now,
];
if ($extendColumns) {
foreach ($columnMap as $column => $label) {
$payload[$column] = $this->castColumn($fields[$label] ?? null, (string) ($columnTypes[$column] ?? 'string'));
foreach ($columnMap as $column => $labels) {
// 同一列允许多个候选字段名(审批模板改版后字段改名),取第一个有值的。
$value = null;
foreach ((array) $labels as $label) {
$candidate = $fields[(string) $label] ?? null;
if ($candidate !== null && $candidate !== '') {
$value = $candidate;
break;
}
}
$payload[$column] = $this->castColumn($value, (string) ($columnTypes[$column] ?? 'string'));
}
// 行级过滤(如“收款人全称”限定):不匹配的明细行直接跳过,
// 不写入镜像,也不占用 detail_index,保证保留行编号连续。
@ -550,7 +560,7 @@ class DingPayableWorkflowMirrorSynchronizer
* @param array<int,array<string,mixed>> $schemeRows
* @return list<array<string,mixed>>
*/
private function buildDetailRowFields(array $schemeRows, string $detailTable): array
private function buildDetailRowFields(array $schemeRows, string $detailTable, string $matchLabel = ''): array
{
$topLevel = $this->formFieldLookup($schemeRows);
if ($detailTable === '') {
@ -574,6 +584,25 @@ class DingPayableWorkflowMirrorSynchronizer
}
}
// 审批模板改版后明细表格可能改名或名称为空:按名称找不到时,取行里含有指定列(如“商品ID”)的明细表格。
if ($grid === null && $matchLabel !== '') {
foreach ($schemeRows as $row) {
$value = is_array($row) ? ($row['value'] ?? null) : null;
$decoded = is_string($value) ? json_decode($value, true) : $value;
if (! is_array($decoded)) {
continue;
}
foreach ($decoded as $gridRow) {
foreach ((array) ($gridRow['rowValue'] ?? []) as $cell) {
if (is_array($cell) && (string) ($cell['label'] ?? '') === $matchLabel) {
$grid = $decoded;
break 3;
}
}
}
}
}
if ($grid === null) {
return [$topLevel];
}

View File

@ -18,6 +18,13 @@
? (string) ($row['matched_product']['name'] ?? '-')
: '(未匹配)');
$payeeScope = trim((string) config('upstream_mirrors.ding_online_daifa_price.row_filters.payee_name', ''));
$auditResults = \Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository::AUDIT_RESULTS;
$auditCounts = (array) ($summary['audit_counts'] ?? []);
$auditClass = static fn (string $result): string => match ($result) {
'多报销' => 'audit-over',
'成本缺失', '无发货明细' => 'unmatched',
default => '',
};
@endphp
<div class="online-daifa-page">
@ -41,6 +48,9 @@
.online-daifa-summary .item { display:flex; flex-direction:column; gap:.15rem; }
.online-daifa-summary .item span { color:var(--vip-content-muted,#595959); font-size:.7rem; }
.online-daifa-summary .item b { font-size:.95rem; font-variant-numeric:tabular-nums; }
.online-daifa-page .audit-over { color:var(--vip-danger,#B80000); font-weight:600; }
.online-daifa-page .audit-detail { white-space:pre-line; min-width:14rem; }
.online-daifa-audit-note { margin:-.5rem 0 1rem; color:var(--vip-content-muted,#595959); font-size:.75rem; line-height:1.6; }
.online-daifa-table-wrap { overflow:auto; border:1px solid var(--vip-border,#D8D2C7); border-radius:.5rem; background:#fff; }
.online-daifa-table { width:100%; min-width:120rem; border-collapse:separate; border-spacing:0; font-size:.75rem; }
.online-daifa-table th,.online-daifa-table td { padding:.55rem .65rem; border-right:1px solid var(--vip-border,#D8D2C7); border-bottom:1px solid var(--vip-border,#D8D2C7); white-space:nowrap; vertical-align:top; }
@ -83,6 +93,15 @@
@endforeach
</select>
</div>
<div class="online-daifa-field">
<label for="daifa-audit">成本核查</label>
<select id="daifa-audit" name="audit">
<option value="">全部</option>
@foreach ($auditResults as $auditResult)
<option value="{{ $auditResult }}" @selected(($filters['audit'] ?? '') === $auditResult)>{{ $auditResult }}({{ (int) ($auditCounts[$auditResult] ?? 0) }})</option>
@endforeach
</select>
</div>
<div class="online-daifa-field">
<label for="daifa-created-from">创建时间</label>
<div class="online-daifa-date-range">
@ -119,7 +138,10 @@
<div class="item"><span>差价合计</span><b>{{ $money($summary['price_diff'] ?? null) }}</b></div>
<div class="item"><span>采购单管理</span><b>{{ (int) ($summary['purchase_count'] ?? 0) }}</b></div>
<div class="item"><span>已匹配商品目录</span><b>{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['matchable_count'] ?? $summary['count'] ?? 0) }}</b></div>
<div class="item"><span>多报销(代发金额高于系统成本)</span><b class="audit-over">{{ (int) ($auditCounts['多报销'] ?? 0) }} 条 · {{ $money($summary['over_amount'] ?? 0) }}</b></div>
<div class="item"><span>成本缺失 / 无发货明细</span><b>{{ (int) ($auditCounts['成本缺失'] ?? 0) }} / {{ (int) ($auditCounts['无发货明细'] ?? 0) }}</b></div>
</div>
<p class="online-daifa-audit-note">成本核查:系统成本 = Σ(实际发货子商品在普通商品资料的成本价 × 发货数量),组合装按聚水潭订单中由本行商品编码拆出的子商品计算;代发订单金额比系统成本高出 0.01 元以上判为“多报销”。成本价为空或 0 的标“成本缺失”,聚水潭订单找不到发货商品的标“无发货明细”。仅核查钉钉报销行,采购单行不参与。</p>
<div class="online-daifa-table-wrap">
<table class="online-daifa-table">
@ -128,7 +150,7 @@
<th>商品ID</th><th>商品名称(匹配)</th><th>店铺名称</th>
<th>代发交易单号</th><th>店铺交易单号</th>
<th class="num">发货数量</th><th class="num">订单实付金额</th><th class="num">代发订单金额</th><th class="num">差价</th>
<th>供应商名称</th><th>商品编码</th><th>实际发货商品编码</th><th>聚水潭标记|多标签</th><th>创建时间</th>
<th>供应商名称</th><th>商品编码</th><th>实际发货商品编码</th><th class="num">系统成本</th><th class="num">报销−成本</th><th>成本核查</th><th>成本明细(编码×数量×成本价)</th><th>聚水潭标记|多标签</th><th>创建时间</th>
</tr></thead>
<tbody>
@forelse ($rows ?? [] as $row)
@ -154,11 +176,15 @@
<td>{{ $num($row['supplier_name']) }}</td>
<td>{{ $num($row['material_no']) }}</td>
<td class="wrap">{{ ($row['ship_skus'] ?? '') !== '' ? $row['ship_skus'] : '-' }}</td>
<td class="num">{{ $money($row['system_cost'] ?? null) }}</td>
<td class="num {{ ($row['audit_result'] ?? '') === '多报销' ? 'audit-over' : '' }}">{{ $money($row['cost_diff'] ?? null) }}</td>
<td class="{{ $auditClass((string) ($row['audit_result'] ?? '')) }}">{{ ($row['audit_result'] ?? '') !== '' ? $row['audit_result'] : '-' }}</td>
<td class="wrap audit-detail">{{ ($row['audit_detail'] ?? '') !== '' ? $row['audit_detail'] : '-' }}</td>
<td class="wrap">{{ ($row['jst_labels'] ?? '') !== '' ? $row['jst_labels'] : '-' }}</td>
<td>{{ $row['workflow_created_at'] ?? '-' }}</td>
</tr>
@empty
<tr><td colspan="20"><div class="online-daifa-empty">{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}</div></td></tr>
<tr><td colspan="24"><div class="online-daifa-empty">{{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }}</div></td></tr>
@endforelse
</tbody>
</table>

View File

@ -157,6 +157,7 @@ class OnlineDaifaPricePageTest extends FeatureTestCase
'supplier_name' => '新北供应商',
'material_no' => 'MAT-001',
'status' => '',
'audit' => '',
'created_from' => '2026-09-01',
'created_to' => '2026-09-07',
],
@ -202,6 +203,7 @@ class OnlineDaifaPricePageTest extends FeatureTestCase
'supplier_name' => '新北供应商',
'material_no' => 'MAT-001',
'status' => 'COMPLETED',
'audit' => '',
'created_from' => '2026-09-01',
'created_to' => '2026-09-07',
];

View File

@ -178,6 +178,40 @@ class DingPayableWorkflowMirrorSynchronizerTest extends TestCase
$this->assertSame(0, $table->count());
}
public function test_daifa_detail_table_falls_back_to_grid_with_product_id_column(): void
{
config(['upstream_mirrors.ding_online_daifa_price' => [
'dataset_key' => 'operations_replica.rpt.ding_online_daifa_price',
'target_table' => 'ding_online_daifa_price_mirror',
'source_key' => 'operations_replica', 'process_code' => 'PROC-TEST',
'extend_columns' => true, 'only_status' => 'COMPLETED',
'detail_table' => '收款费用明细', 'detail_table_match_label' => '商品ID',
'column_map' => ['product_id' => '商品ID', 'shop_trade_no' => '店铺交易单号', 'material_no' => ['料号', '商品编码'], 'payee_name' => '收款人全称'],
]]);
$cell = static fn (string $label, string $value): array => ['label' => $label, 'value' => $value];
$this->query->schemeRows = [
['processInstanceId' => 'blank-name', 'name' => '收款人全称', 'componentType' => 'TextField', 'value' => '宁波顾家望业家居有限公司'],
// 付款明细不含“商品ID”,不能被当成商品明细。
['processInstanceId' => 'blank-name', 'name' => '付款明细', 'componentType' => 'TableField', 'value' => json_encode([
['rowValue' => [$cell('付款金额', '1384')]],
], JSON_UNESCAPED_UNICODE)],
// 新版模板:商品明细表格名称为空,料号改叫商品编码。
['processInstanceId' => 'blank-name', 'name' => '', 'componentType' => 'TableField', 'value' => json_encode([
['rowValue' => [$cell('商品ID', '10035514372245'), $cell('店铺交易单号', '3630463003975610'), $cell('商品编码', 'DNZ-01')]],
['rowValue' => [$cell('商品ID', '10035514372246'), $cell('店铺交易单号', '3630463003975611'), $cell('商品编码', 'DNZ-02')]],
], JSON_UNESCAPED_UNICODE)],
];
$this->query->workflowBatches = [[$this->workflow('blank-name', now()->subHour()->format('Y-m-d H:i:s.u'))]];
$this->synchronizer->forConfigKey('ding_online_daifa_price')->sync(true, 10, 0);
$rows = DB::connection('business_mirror')->table('ding_online_daifa_price_mirror')->orderBy('detail_index')->get();
$this->assertCount(2, $rows);
$this->assertSame('10035514372245', $rows[0]->product_id);
$this->assertSame('3630463003975611', $rows[1]->shop_trade_no);
$this->assertSame('DNZ-01', $rows[0]->material_no);
$this->assertSame('宁波顾家望业家居有限公司', $rows[1]->payee_name);
}
public function test_daifa_repository_includes_end_date_and_counts_only_resolved_products(): void
{
config(['upstream_mirrors.ding_online_daifa_price' => [
@ -300,6 +334,9 @@ class FakeDingPayableWorkflowQuery extends UpstreamReadOnlyQuery
/** @var list<list<array<string,mixed>>> */
public array $workflowBatches = [];
/** @var list<array<string,mixed>> */
public array $schemeRows = [];
/** @var list<array{sql:string,bindings:array}> */
public array $calls = [];
@ -315,6 +352,9 @@ class FakeDingPayableWorkflowQuery extends UpstreamReadOnlyQuery
if (str_contains($sql, 'FROM [rpt].[ding_Workflow]')) {
return array_shift($this->workflowBatches) ?? [];
}
if (str_contains($sql, 'FROM [rpt].[ding_WorkflowScheme]')) {
return $this->schemeRows;
}
return [];
}

View File

@ -0,0 +1,136 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Repositories\DingOnlineDaifaPriceMirrorRepository as Repository;
use Tests\TestCase;
class OnlineDaifaCostAuditTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config([
'database.connections.business_mirror' => ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => ''],
'upstream_mirrors.connection' => 'business_mirror',
]);
Cache::setDefaultDriver('array');
Cache::flush();
DB::purge('business_mirror');
$schema = Schema::connection('business_mirror');
$schema->create('business_mirror_table_states', function (Blueprint $table): void {
$table->string('dataset_key')->primary();
$table->string('status');
$table->dateTime('initial_completed_at')->nullable();
$table->dateTime('last_succeeded_at')->nullable();
});
$schema->create(Repository::TARGET_TABLE, function (Blueprint $table): void {
$table->string('process_instance_id');
$table->unsignedInteger('detail_index');
foreach (['product_id', 'product_name', 'daifa_trade_no', 'shop_trade_no', 'shop_name', 'payee_name', 'supplier_name', 'material_no'] as $column) {
$table->string($column)->nullable();
}
$table->integer('ship_qty')->nullable();
$table->decimal('paid_amount', 20, 2)->nullable();
$table->decimal('daifa_amount', 20, 2)->nullable();
$table->decimal('price_diff', 20, 2)->nullable();
$table->text('workflow_payload')->nullable();
$table->text('scheme_payload')->nullable();
$table->text('task_payload')->nullable();
$table->dateTime('workflow_created_at')->nullable();
});
$schema->create('ops_jst_orders', function (Blueprint $table): void {
$table->unsignedBigInteger('Id')->primary();
$table->unsignedBigInteger('o_id')->index();
$table->string('so_id')->nullable()->index();
$table->string('shop_name')->nullable();
$table->string('status')->nullable();
$table->text('labels')->nullable();
});
$schema->create('ops_jst_order_item', function (Blueprint $table): void {
$table->unsignedBigInteger('Id')->primary();
$table->unsignedBigInteger('o_id')->index();
$table->string('sku_id')->nullable();
$table->decimal('qty', 20, 4)->nullable();
$table->string('src_combine_sku_id')->nullable();
});
$schema->create('ops_jst_sku', function (Blueprint $table): void {
$table->unsignedBigInteger('autoid');
$table->string('sku_id');
$table->string('sku_type');
$table->decimal('cost_price', 18, 4)->nullable();
});
$db = DB::connection('business_mirror');
$db->table('business_mirror_table_states')->insert([
'dataset_key' => Repository::DATASET_KEY, 'status' => 'succeeded',
'initial_completed_at' => '2026-10-01 00:00:00', 'last_succeeded_at' => '2026-11-03 05:00:00',
]);
$ding = static fn (string $id, string $soId, string $material, ?float $amount): array => [
'process_instance_id' => $id, 'detail_index' => 0, 'shop_trade_no' => $soId, 'shop_name' => '京东-测试店',
'material_no' => $material, 'ship_qty' => 1, 'daifa_amount' => $amount,
'workflow_payload' => '{"status":"COMPLETED","result":"agree","businessId":"' . $id . '"}', 'scheme_payload' => '[]', 'task_payload' => '[]',
'workflow_created_at' => '2026-10-10 10:00:00',
];
$db->table(Repository::TARGET_TABLE)->insert([
$ding('OVER', '1001', 'ZH-CHAIR-2', 250.00), // 组合装:2 把椅子,成本 2×100=200,报 250 → 多报销 50
$ding('OK', '1002', 'DESK-B', 80.00), // 普通商品成本 80,报 80 → 正常
$ding('MISS', '1003', 'NOCOST', 30.00), // 成本价为 0 → 成本缺失
$ding('NONE', '9999', 'ANY', 10.00), // 聚水潭找不到订单 → 无发货明细
]);
$db->table('ops_jst_orders')->insert([
['Id' => 1, 'o_id' => 1, 'so_id' => '1001', 'shop_name' => 'x', 'status' => 'Sent', 'labels' => null],
['Id' => 2, 'o_id' => 2, 'so_id' => '1002', 'shop_name' => 'x', 'status' => 'Sent', 'labels' => null],
['Id' => 3, 'o_id' => 3, 'so_id' => '1003', 'shop_name' => 'x', 'status' => 'Sent', 'labels' => null],
]);
$db->table('ops_jst_order_item')->insert([
['Id' => 1, 'o_id' => 1, 'sku_id' => 'CHAIR-A', 'qty' => 2, 'src_combine_sku_id' => 'ZH-CHAIR-2'],
['Id' => 2, 'o_id' => 2, 'sku_id' => 'DESK-B', 'qty' => 1, 'src_combine_sku_id' => null],
['Id' => 3, 'o_id' => 3, 'sku_id' => 'NOCOST', 'qty' => 1, 'src_combine_sku_id' => null],
]);
$db->table('ops_jst_sku')->insert([
['autoid' => 1, 'sku_id' => 'CHAIR-A', 'sku_type' => 'normal', 'cost_price' => 90],
['autoid' => 2, 'sku_id' => 'CHAIR-A', 'sku_type' => 'normal', 'cost_price' => 100],
['autoid' => 3, 'sku_id' => 'DESK-B', 'sku_type' => 'normal', 'cost_price' => 80],
['autoid' => 4, 'sku_id' => 'NOCOST', 'sku_type' => 'normal', 'cost_price' => 0],
]);
}
public function test_cost_audit_splits_combo_and_flags_over_reimbursement(): void
{
$result = app(Repository::class)->paginate([], 1, 100);
$rows = collect($result['data'])->keyBy('process_instance_id');
$this->assertSame(Repository::AUDIT_OVER, $rows['OVER']['audit_result']);
$this->assertSame(200.0, $rows['OVER']['system_cost']);
$this->assertSame(50.0, $rows['OVER']['cost_diff']);
$this->assertSame('CHAIR-A×2×100=200.00', $rows['OVER']['audit_detail']);
$this->assertSame(Repository::AUDIT_OK, $rows['OK']['audit_result']);
$this->assertSame(0.0, $rows['OK']['cost_diff']);
$this->assertSame(Repository::AUDIT_COST_MISSING, $rows['MISS']['audit_result']);
$this->assertNull($rows['MISS']['cost_diff']);
$this->assertSame(Repository::AUDIT_NO_SHIPMENT, $rows['NONE']['audit_result']);
$this->assertSame(1, $result['summary']['audit_counts'][Repository::AUDIT_OVER]);
$this->assertSame(50.0, $result['summary']['over_amount']);
}
public function test_audit_filter_pages_and_exports_only_matching_rows(): void
{
$repository = app(Repository::class);
$result = $repository->paginate(['audit' => Repository::AUDIT_OVER], 1, 100);
$this->assertSame(1, $result['total']);
$this->assertSame(['OVER'], array_column($result['data'], 'process_instance_id'));
$export = iterator_to_array($repository->exportRows(['audit' => Repository::AUDIT_COST_MISSING]), false);
$this->assertSame(['MISS'], array_column($export, 'process_instance_id'));
$this->assertSame(Repository::AUDIT_COST_MISSING, $export[0]['audit_result']);
}
}