商品成本合计增加仓库透视明细 (#568)

商品成本合计增加仓库透视明细 (#568)
This commit is contained in:
chenxi 2026-10-25 23:06:23 +08:00
parent e75946ae88
commit 3c7757d848
5 changed files with 616 additions and 4 deletions

View File

@ -2811,6 +2811,75 @@ class Pages extends Controller
];
}
/**
* 商品成本合计明细:与页面成本合计使用同一有效单价口径,
* 按发货仓库透视商品数量与商品成本。
*/
public function productCostSummaryDetails(Request $request): \Illuminate\Http\JsonResponse
{
$month = trim((string) $request->query('month', ''));
if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
return response()->json(['message' => '请选择有效月份。'], 422);
}
$filterValues = [
'platform' => trim((string) $request->query('platform', '')),
'store_name' => trim((string) $request->query('store_name', '')),
'online_order_no' => trim((string) $request->query('online_order_no', '')),
'product_code' => trim((string) $request->query('product_code', '')),
'warehouse_short_name' => trim((string) $request->query('warehouse_short_name', '')),
];
$connection = (string) config('upstream_mirrors.connection', 'business_mirror');
$query = DB::connection($connection)
->table(self::PRODUCT_COST_TABLE)
->where('report_month', $month . '-01')
->whereNotNull('unit_price');
if ($filterValues['platform'] !== '') {
$query->where('platform', $filterValues['platform']);
}
foreach (['store_name', 'online_order_no', 'product_code'] as $column) {
if ($filterValues[$column] !== '') {
$query->where(
$column,
'like',
'%' . addcslashes($filterValues[$column], '%_\\') . '%'
);
}
}
if ($filterValues['warehouse_short_name'] !== '') {
$query->where('warehouse_short_name', $filterValues['warehouse_short_name']);
}
$warehouseExpression = "COALESCE(NULLIF(warehouse, ''), '未填写发货仓库')";
$rows = $query
->selectRaw($warehouseExpression . ' as warehouse')
->selectRaw('SUM(product_quantity) as product_quantity')
->selectRaw('SUM(product_cost) as product_cost')
->groupByRaw($warehouseExpression)
->orderByDesc('product_cost')
->orderBy('warehouse')
->get()
->map(static fn ($row): array => [
'warehouse' => (string) ($row->warehouse ?? '未填写发货仓库'),
'quantity' => round((float) ($row->product_quantity ?? 0), 4),
'cost' => round((float) ($row->product_cost ?? 0), 2),
])
->values();
return response()->json([
'summary' => [
'warehouse_count' => $rows->count(),
'quantity_total' => round((float) $rows->sum('quantity'), 4),
'cost_total' => round((float) $rows->sum('cost'), 2),
],
'rows' => $rows,
], 200, [
'Cache-Control' => 'private, no-store, max-age=0',
]);
}
/**
* 商品成本待核验明细:当前单价为空或仓库简称未匹配的行。
* 每次打开或刷新弹框都重新查询共享镜像,已修复的行会自然从结果中消失。

View File

@ -22,13 +22,18 @@
: $formatted;
};
$metricCards = [
['label' => '商品成本合计', 'value' => number_format((float) ($summary['cost_total'] ?? 0) / 10000, 2), 'unit' => '万'],
[
'label' => '商品成本合计',
'value' => number_format((float) ($summary['cost_total'] ?? 0) / 10000, 2),
'unit' => '万',
'dialog' => 'cost_summary',
],
[
'label' => '待核验成本',
'value' => number_format((int) ($summary['pending_rows'] ?? 0)),
'unit' => '行',
'tone' => 'warn',
'dialog' => true,
'dialog' => 'pending',
],
];
$tableColumns = [
@ -49,6 +54,23 @@
);
$pendingDetailsUrl = route('business.financial-operations.product-costs.pending-details', $pendingQuery);
$pendingExportUrl = route('business.financial-operations.product-costs.pending-details.export', $pendingQuery);
$costSummaryQuery = array_merge(
['company_id' => company_id()],
request()->except([
'page',
'per_page',
'pending_page',
'pending_type',
'warehouse_keyword',
'sort_by',
'sort_direction',
]),
['month' => $filters['month'] ?? '']
);
$costSummaryDetailsUrl = route(
'business.financial-operations.product-costs.summary-details',
$costSummaryQuery
);
@endphp
<div class="product-cost-page">
@ -876,6 +898,135 @@
gap: .45rem;
}
.product-cost-cost-summary-dialog {
width: min(56rem, calc(100vw - 2rem));
}
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table {
width: 100%;
min-width: 100%;
table-layout: fixed;
}
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table th:first-child,
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table td:first-child {
width: 50%;
}
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table th:nth-child(2),
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table td:nth-child(2) {
width: 20%;
}
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table th:nth-child(3),
.product-cost-cost-summary-dialog .product-cost-pending-dialog__table td:nth-child(3) {
width: 30%;
}
.product-cost-cost-summary-filter {
display: flex;
align-items: end;
gap: .5rem;
padding-bottom: .8rem;
}
.product-cost-cost-summary-filter__field {
display: grid;
flex: 1 1 auto;
gap: .3rem;
min-width: 0;
}
.product-cost-cost-summary-filter__field label {
color: var(--vip-content-muted, #595959);
font-size: .7rem;
font-weight: 500;
}
.product-cost-cost-summary-filter__field input {
width: 100%;
height: 2rem;
min-width: 0;
padding: 0 .6rem;
border: 1px solid var(--vip-border, #d8d2c7);
border-radius: .5rem;
background: #fff;
color: var(--vip-content-ink, #171717);
font: inherit;
font-size: .72rem;
}
.product-cost-cost-summary-filter__field input:focus {
border-color: var(--vip-content-accent-dark, #856632);
outline: none;
box-shadow: 0 0 0 3px rgba(133, 102, 50, .2);
}
.product-cost-cost-summary-filter button {
display: inline-flex;
box-sizing: border-box;
height: 2rem;
align-items: center;
justify-content: center;
padding: 0 .75rem;
border: 1px solid var(--vip-border, #d8d2c7);
border-radius: .5rem;
background: #fff;
color: var(--vip-content-ink, #171717);
font: inherit;
font-size: .72rem;
cursor: pointer;
}
.product-cost-cost-summary-filter button:hover {
border-color: var(--vip-content-accent-dark, #856632);
color: var(--vip-content-accent-dark, #856632);
}
.product-cost-cost-summary-sort {
display: inline-flex;
align-items: center;
gap: .25rem;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font: inherit;
font-weight: inherit;
cursor: pointer;
}
.product-cost-cost-summary-sort:hover,
.product-cost-cost-summary-sort:focus-visible {
color: var(--vip-content-accent-dark, #856632);
}
.product-cost-cost-summary-sort:focus-visible {
outline: 2px solid var(--vip-content-accent-dark, #856632);
outline-offset: 2px;
}
.product-cost-cost-summary-sort__indicator {
min-width: .7rem;
color: var(--vip-content-muted, #595959);
font-size: .65rem;
}
.product-cost-cost-summary-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding-top: .75rem;
color: var(--vip-content-muted, #595959);
font-size: .72rem;
}
.product-cost-cost-summary-footer strong {
color: var(--vip-content-ink, #171717);
font-variant-numeric: tabular-nums;
}
@media (max-width: 1100px) {
.product-cost-filter-form {
grid-template-columns: repeat(2, minmax(10rem, 1fr));
@ -946,6 +1097,16 @@
.product-cost-pending-dialog__body {
max-height: calc(100vh - 4rem);
}
.product-cost-cost-summary-filter,
.product-cost-cost-summary-footer {
align-items: stretch;
flex-direction: column;
}
.product-cost-cost-summary-dialog .product-cost-pending-dialog__title {
flex: 0 0 auto;
}
}
</style>
@ -1028,8 +1189,8 @@
</div>
<div class="product-cost-metrics-grid">
@foreach ($metricCards as $card)
@php($opensDialog = ($card['dialog'] ?? false) === true)
@if ($opensDialog)
@php($dialog = $card['dialog'] ?? null)
@if ($dialog === 'pending')
<div
class="product-cost-metric is-warn is-summary"
aria-label="待核验成本汇总"
@ -1044,6 +1205,21 @@
data-product-cost-pending-url="{{ $pendingDetailsUrl }}"
>查看明细 →</button>
</div>
@elseif ($dialog === 'cost_summary')
<div
class="product-cost-metric is-summary"
aria-label="商品成本合计明细"
data-product-cost-metric-card="cost-summary"
>
<span class="product-cost-metric__label">{{ $card['label'] }}</span>
<strong class="product-cost-metric__value">{{ $card['value'] }}<small>{{ $card['unit'] }}</small></strong>
<button
type="button"
class="product-cost-metric__action product-cost-metric__action--button"
data-product-cost-summary-open
data-product-cost-summary-url="{{ $costSummaryDetailsUrl }}"
>查看明细 →</button>
</div>
@else
<a
class="product-cost-metric"
@ -1209,6 +1385,89 @@
</div>
</section>
<dialog
class="product-cost-pending-dialog product-cost-cost-summary-dialog"
id="product-cost-cost-summary-dialog"
aria-labelledby="product-cost-cost-summary-dialog-title"
data-product-cost-summary-dialog
>
<header class="product-cost-pending-dialog__head">
<div class="product-cost-pending-dialog__title">
<h2 id="product-cost-cost-summary-dialog-title">商品成本合计明细</h2>
<span>按当前页面筛选条件统计,并按发货仓库透视商品数量与商品成本。</span>
</div>
<div class="product-cost-pending-dialog__actions">
<button type="button" data-product-cost-summary-refresh>刷新</button>
<button
type="button"
class="product-cost-pending-dialog__close"
aria-label="关闭商品成本合计明细"
data-product-cost-summary-close
>×</button>
</div>
</header>
<div class="product-cost-pending-dialog__body">
<div class="product-cost-cost-summary-filter">
<label class="product-cost-cost-summary-filter__field" for="product-cost-summary-warehouse">
<span>发货仓库筛选</span>
<input
id="product-cost-summary-warehouse"
type="search"
placeholder="输入发货仓库名称"
autocomplete="off"
data-product-cost-summary-search
>
</label>
<button type="button" data-product-cost-summary-filter-reset>清除筛选</button>
</div>
<div
class="product-cost-pending-dialog__status"
role="status"
data-product-cost-summary-status
>正在加载商品成本汇总…</div>
<div class="product-cost-pending-dialog__table-wrap" data-product-cost-summary-table hidden>
<table class="product-cost-pending-dialog__table">
<thead>
<tr>
<th scope="col">发货仓库</th>
<th scope="col" class="num" data-product-cost-summary-sort-column="quantity" aria-sort="none">
<button
type="button"
class="product-cost-cost-summary-sort"
data-product-cost-summary-sort="quantity"
>
商品数量
<span class="product-cost-cost-summary-sort__indicator" aria-hidden="true">↕</span>
</button>
</th>
<th scope="col" class="num" data-product-cost-summary-sort-column="cost" aria-sort="descending">
<button
type="button"
class="product-cost-cost-summary-sort"
data-product-cost-summary-sort="cost"
>
商品成本
<span class="product-cost-cost-summary-sort__indicator" aria-hidden="true">↓</span>
</button>
</th>
</tr>
</thead>
<tbody data-product-cost-summary-rows></tbody>
</table>
</div>
<div class="product-cost-pending-dialog__empty" data-product-cost-summary-empty hidden>
当前筛选条件下没有可汇总的商品成本明细。
</div>
<div class="product-cost-cost-summary-footer" data-product-cost-summary-footer hidden>
<span data-product-cost-summary-count></span>
<span>
商品数量合计 <strong data-product-cost-summary-quantity>0</strong>
· 商品成本合计 <strong data-product-cost-summary-cost>0.00</strong>
</span>
</div>
</div>
</dialog>
<dialog
class="product-cost-pending-dialog"
id="product-cost-pending-dialog"
@ -1392,6 +1651,197 @@
}
})();
</script>
<script>
(function () {
var trigger = document.querySelector('[data-product-cost-summary-open]');
var dialog = document.querySelector('[data-product-cost-summary-dialog]');
if (!trigger || !dialog) { return; }
var rowsBody = dialog.querySelector('[data-product-cost-summary-rows]');
var table = dialog.querySelector('[data-product-cost-summary-table]');
var status = dialog.querySelector('[data-product-cost-summary-status]');
var empty = dialog.querySelector('[data-product-cost-summary-empty]');
var footer = dialog.querySelector('[data-product-cost-summary-footer]');
var count = dialog.querySelector('[data-product-cost-summary-count]');
var quantityTotal = dialog.querySelector('[data-product-cost-summary-quantity]');
var costTotal = dialog.querySelector('[data-product-cost-summary-cost]');
var search = dialog.querySelector('[data-product-cost-summary-search]');
var filterReset = dialog.querySelector('[data-product-cost-summary-filter-reset]');
var refresh = dialog.querySelector('[data-product-cost-summary-refresh]');
var close = dialog.querySelector('[data-product-cost-summary-close]');
var sortButtons = Array.prototype.slice.call(
dialog.querySelectorAll('[data-product-cost-summary-sort]')
);
var allRows = [];
var sortKey = 'cost';
var sortDirection = 'desc';
function quantity(value) {
return Number(value || 0).toLocaleString('zh-CN', {
maximumFractionDigits: 4
});
}
function money(value) {
return Number(value || 0).toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
function currentRows() {
var keyword = search.value.trim().toLowerCase();
return allRows.filter(function (row) {
return keyword === ''
|| String(row.warehouse || '').toLowerCase().indexOf(keyword) !== -1;
}).sort(function (left, right) {
var leftValue = Number(left[sortKey] || 0);
var rightValue = Number(right[sortKey] || 0);
if (leftValue === rightValue) {
return String(left.warehouse || '').localeCompare(
String(right.warehouse || ''),
'zh-CN'
);
}
return sortDirection === 'asc'
? leftValue - rightValue
: rightValue - leftValue;
});
}
function updateSortHeaders() {
sortButtons.forEach(function (button) {
var key = button.dataset.productCostSummarySort;
var header = button.closest('[data-product-cost-summary-sort-column]');
var indicator = button.querySelector('.product-cost-cost-summary-sort__indicator');
var active = key === sortKey;
if (header) {
header.setAttribute(
'aria-sort',
active ? (sortDirection === 'asc' ? 'ascending' : 'descending') : 'none'
);
}
if (indicator) {
indicator.textContent = active
? (sortDirection === 'asc' ? '↑' : '↓')
: '↕';
}
});
}
function render() {
var rows = currentRows();
rowsBody.replaceChildren();
rows.forEach(function (row) {
var tr = document.createElement('tr');
var warehouse = document.createElement('td');
var rowQuantity = document.createElement('td');
var rowCost = document.createElement('td');
warehouse.textContent = row.warehouse || '未填写发货仓库';
rowQuantity.className = 'num';
rowQuantity.textContent = quantity(row.quantity);
rowCost.className = 'num';
rowCost.textContent = money(row.cost);
tr.append(warehouse, rowQuantity, rowCost);
rowsBody.append(tr);
});
var sumQuantity = rows.reduce(function (sum, row) {
return sum + Number(row.quantity || 0);
}, 0);
var sumCost = rows.reduce(function (sum, row) {
return sum + Number(row.cost || 0);
}, 0);
count.textContent = '共 ' + rows.length.toLocaleString('zh-CN') + ' 个发货仓库';
quantityTotal.textContent = quantity(sumQuantity);
costTotal.textContent = money(sumCost);
var hasRows = rows.length > 0;
table.hidden = !hasRows;
empty.hidden = hasRows;
footer.hidden = !hasRows;
updateSortHeaders();
}
function setLoading(loading) {
refresh.disabled = loading;
search.disabled = loading;
filterReset.disabled = loading;
if (loading) {
status.hidden = false;
status.classList.remove('is-error');
status.textContent = '正在加载商品成本汇总…';
table.hidden = true;
empty.hidden = true;
footer.hidden = true;
}
}
async function load() {
setLoading(true);
try {
var url = new URL(trigger.dataset.productCostSummaryUrl, window.location.href);
var response = await fetch(url.toString(), {
credentials: 'same-origin',
cache: 'no-store',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
});
var payload = await response.json().catch(function () { return {}; });
if (!response.ok) {
throw new Error(payload.message || '商品成本汇总加载失败,请稍后重试。');
}
allRows = Array.isArray(payload.rows) ? payload.rows : [];
status.hidden = true;
render();
} catch (error) {
table.hidden = true;
empty.hidden = true;
footer.hidden = true;
status.hidden = false;
status.classList.add('is-error');
status.textContent = error && error.message
? error.message
: '商品成本汇总加载失败,请稍后重试。';
} finally {
refresh.disabled = false;
search.disabled = false;
filterReset.disabled = false;
}
}
trigger.addEventListener('click', function () {
if (!dialog.open) { dialog.showModal(); }
load();
});
sortButtons.forEach(function (button) {
button.addEventListener('click', function () {
var key = button.dataset.productCostSummarySort;
if (sortKey === key) {
sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
} else {
sortKey = key;
sortDirection = 'desc';
}
render();
});
});
search.addEventListener('input', render);
filterReset.addEventListener('click', function () {
search.value = '';
search.focus();
render();
});
refresh.addEventListener('click', load);
close.addEventListener('click', function () { dialog.close(); });
dialog.addEventListener('click', function (event) {
if (event.target === dialog) { dialog.close(); }
});
})();
</script>
<script>
(function () {
var trigger = document.querySelector('[data-product-cost-pending-open]');

View File

@ -272,6 +272,10 @@ Route::get('workspace/product-inventory/monthly-weighted-average-price/export',
->middleware('business.page:financial-operations,product-costs')
->name('business.financial-operations.product-costs.export');
Route::get('workspace/financial-operations/product-costs/summary-details', 'Business\Pages@productCostSummaryDetails')
->middleware('business.page:financial-operations,product-costs')
->name('business.financial-operations.product-costs.summary-details');
Route::get('workspace/financial-operations/product-costs/pending-details', 'Business\Pages@productCostPendingDetails')
->middleware('business.page:financial-operations,product-costs')
->name('business.financial-operations.product-costs.pending-details');

View File

@ -57,6 +57,13 @@ class ProductCostPageLayoutTest extends TestCase
$this->assertStringContainsString('口径说明', $html);
$this->assertStringContainsString('商品成本合计', $html);
$this->assertStringContainsString('待核验成本', $html);
$this->assertStringContainsString('data-product-cost-metric-card="cost-summary"', $html);
$this->assertStringContainsString('data-product-cost-summary-open', $html);
$this->assertStringContainsString('data-product-cost-summary-dialog', $html);
$this->assertStringContainsString('按发货仓库透视商品数量与商品成本', $html);
$this->assertStringContainsString('data-product-cost-summary-search', $html);
$this->assertStringContainsString('data-product-cost-summary-sort="quantity"', $html);
$this->assertStringContainsString('data-product-cost-summary-sort="cost"', $html);
$this->assertStringContainsString('data-product-cost-metric-card="pending-summary"', $html);
$this->assertStringContainsString('data-product-cost-summary="pending_rows">7</span>', $html);
$this->assertStringContainsString('data-product-cost-pending-open', $html);

View File

@ -0,0 +1,82 @@
<?php
namespace Tests\Feature\Business;
use Illuminate\Support\Facades\DB;
use Tests\Feature\FeatureTestCase;
class ProductCostSummaryDetailsTest extends FeatureTestCase
{
public function test_summary_details_pivot_by_warehouse_using_cost_total_scope(): void
{
DB::connection('business_mirror')->table('store_receipt_product_cost_rows')->insert([
$this->row('cuiqiao-1', '崔桥工厂仓', 10, 2, 20, '天猫'),
$this->row('cuiqiao-2', '崔桥工厂仓', 10, 3, 30, '天猫'),
$this->row('accessory', '配件单仓', 5, 1, 5, '京东'),
$this->row('missing-price', '崔桥工厂仓', null, 99, null, '天猫'),
$this->row('missing-warehouse', null, 10, 4, 40, '天猫'),
$this->row('other-month', '崔桥工厂仓', 10, 8, 80, '天猫', '2026-08-01'),
]);
$response = $this->loginAs()->getJson(route(
'business.financial-operations.product-costs.summary-details',
[
'month' => '2026-09',
'platform' => '天猫',
],
));
$response
->assertOk()
->assertJsonPath('summary.warehouse_count', 2)
->assertJsonPath('summary.quantity_total', 9)
->assertJsonPath('summary.cost_total', 90)
->assertJsonPath('rows.0.warehouse', '崔桥工厂仓')
->assertJsonPath('rows.0.quantity', 5)
->assertJsonPath('rows.0.cost', 50)
->assertJsonPath('rows.1.warehouse', '未填写发货仓库')
->assertJsonPath('rows.1.quantity', 4)
->assertJsonPath('rows.1.cost', 40);
$cacheControl = (string) $response->headers->get('Cache-Control');
$this->assertStringContainsString('private', $cacheControl);
$this->assertStringContainsString('no-store', $cacheControl);
}
public function test_summary_details_rejects_invalid_month(): void
{
$this->loginAs()
->getJson(route('business.financial-operations.product-costs.summary-details', [
'month' => 'invalid',
]))
->assertUnprocessable()
->assertJsonPath('message', '请选择有效月份。');
}
private function row(
string $rowKey,
?string $warehouse,
int|float|null $unitPrice,
int|float $quantity,
int|float|null $cost,
string $platform,
string $reportMonth = '2026-09-01'
): array {
return [
'report_month' => $reportMonth,
'row_key' => $rowKey,
'platform' => $platform,
'occurred_date' => $reportMonth,
'store_name' => 'HX旗舰店',
'online_order_no' => 'ORDER-' . $rowKey,
'warehouse' => $warehouse,
'warehouse_short_name' => $warehouse,
'product_code' => 'SKU-' . $rowKey,
'product_quantity' => $quantity,
'unit_price' => $unitPrice,
'product_cost' => $cost,
'remark' => null,
'imported_at' => now(),
];
}
}