fix(供应商对账): 合入线上热修复并发布货款预估汇总 (#1562)

Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
This commit is contained in:
苏木 2026-11-30 14:10:29 +08:00 committed by sumu
parent a125a8f135
commit cae8f769c9
15 changed files with 592 additions and 53 deletions

View File

@ -0,0 +1,53 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Repositories\SupplierPayableForecastRepository;
use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer;
use Throwable;
class SyncSupplierPayableForecastMirror extends Command
{
protected $signature = 'business-mirror:sync-supplier-payable-forecast
{--batch= : 每批最多读取行数}
{--incremental : 只执行增量同步;默认完整校正采购入库头表和明细}';
protected $description = '完整校正供应商货款预估使用的聚水潭采购入库镜像';
public function handle(BusinessMirrorSynchronizer $synchronizer): int
{
$datasets = [
SupplierPayableForecastRepository::HEAD_DATASET => '采购入库头表',
SupplierPayableForecastRepository::ITEM_DATASET => '采购入库明细',
];
$full = ! (bool) $this->option('incremental');
$batchSize = $this->option('batch') === null ? null : (int) $this->option('batch');
foreach ($datasets as $dataset => $label) {
try {
$result = $synchronizer->sync($dataset, $full, $batchSize, 0);
} catch (Throwable) {
$this->error($label . ':同步失败,已保留上一版镜像数据。');
return self::FAILURE;
}
if ($result['status'] !== 'succeeded') {
$this->error($label . ':未完成同步。');
return self::FAILURE;
}
$this->info(sprintf(
'%s:%s,本轮 %d 批,累计处理 %d 行。',
$label,
$full ? '完整校正完成' : '增量同步完成',
$result['batches'],
$result['rows'],
));
}
return self::SUCCESS;
}
}

View File

@ -21,9 +21,12 @@ class EnsureLimitedDingTalkPageAccess
if ($route?->named('logout', 'business.supplier-portal.home')) {
return $next($request);
}
if ($route?->named('dashboard') && $route->hasParameter('company_id')) {
$dashboardCompanyId = $route?->named('dashboard')
? ($route->parameter('company_id') ?: company_id())
: null;
if ($dashboardCompanyId !== null && $dashboardCompanyId !== '') {
return redirect()->route('business.supplier-portal.home', [
'company_id' => $route->parameter('company_id'),
'company_id' => $dashboardCompanyId,
]);
}
if ($route?->named('business.pages.show')

View File

@ -0,0 +1,63 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private const TABLE = 'supplier_payable_overrides';
private const INDEX = 'supplier_payable_override_supplier';
public function up(): void
{
$schema = Schema::connection(config('database.supplier_payable_maintenance_connection'));
if ($schema->getConnection()->getDriverName() !== 'mysql' || ! $schema->hasTable(self::TABLE)) {
return;
}
$connection = $schema->getConnection();
if (! $schema->hasColumn(self::TABLE, 'supplier_name_key')) {
$connection->statement(
'ALTER TABLE `' . self::TABLE . '`
ADD COLUMN `supplier_name_key` VARCHAR(191)
GENERATED ALWAYS AS (TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, \'$.supplier\')))) STORED'
);
}
$indexes = collect($connection->select('SHOW INDEX FROM `' . self::TABLE . '`'))
->pluck('Key_name')
->map(static fn (mixed $name): string => (string) $name);
if (! $indexes->contains(self::INDEX)) {
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->index(
['company_id', 'dataset', 'supplier_name_key', 'id'],
self::INDEX,
);
});
}
}
public function down(): void
{
$schema = Schema::connection(config('database.supplier_payable_maintenance_connection'));
if ($schema->getConnection()->getDriverName() !== 'mysql' || ! $schema->hasTable(self::TABLE)) {
return;
}
$indexes = collect($schema->getConnection()->select('SHOW INDEX FROM `' . self::TABLE . '`'))
->pluck('Key_name')
->map(static fn (mixed $name): string => (string) $name);
if ($indexes->contains(self::INDEX)) {
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->dropIndex(self::INDEX);
});
}
if ($schema->hasColumn(self::TABLE, 'supplier_name_key')) {
$schema->table(self::TABLE, function (Blueprint $table): void {
$table->dropColumn('supplier_name_key');
});
}
}
};

View File

@ -218,6 +218,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 供应商货款预估:每天完整校正采购入库头表和明细,补回增量更新时间窗口漏掉的记录。
40 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
@ -270,6 +272,9 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# 本次发布立即校正一次供应商采购入库数据,避免等待次日定时任务。
/usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1 || true
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。

View File

@ -222,6 +222,8 @@ CRON_TZ=Asia/Shanghai
# 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。
3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1
0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1
# 供应商货款预估:每天完整校正采购入库头表和明细,补回增量更新时间窗口漏掉的记录。
40 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1
# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。
10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1
# 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。
@ -274,6 +276,9 @@ CRON_TZ=Asia/Shanghai
EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# 本次发布立即校正一次供应商采购入库数据,避免等待次日定时任务。
/usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1 || true
# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票;
# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。

View File

@ -11,6 +11,12 @@ use Illuminate\Support\Facades\Schema;
class SupplierPayableForecastRepository
{
public const SOURCE_ALL = 'all';
public const SOURCE_PURCHASE = 'purchase';
public const SOURCE_SHIPPING = 'shipping';
public const HEAD_DATASET = 'jiansun.dbo.jst_purchaseReceiving';
public const ITEM_DATASET = 'jiansun.dbo.jst_purchaseReceivingItem';
@ -215,6 +221,7 @@ class SupplierPayableForecastRepository
* amount:float,
* estimated_amount_after_discount:float,
* supplier_count:int,
* sources:array<string,array{row_count:int,quantity:float,latest_at:?string}>,
* rows:list<array<string,mixed>>,
* page:int,
* per_page:int
@ -248,6 +255,7 @@ class SupplierPayableForecastRepository
'amount' => (float) ($aggregate->amount ?? 0),
'estimated_amount_after_discount' => (float) ($aggregate->estimated_amount_after_discount ?? 0),
'supplier_count' => (int) ($aggregate->supplier_count ?? 0),
'sources' => $this->goodsSourceBreakdown($filters),
'rows' => $rows,
'page' => $page,
'per_page' => $perPage,
@ -885,16 +893,18 @@ class SupplierPayableForecastRepository
*/
private function goodsSummarySourceRows(array $filters): \Illuminate\Database\Query\Builder
{
$purchase = $this->filteredProcurementQuery($filters)->select([
'h.supplier_name AS supplier_name',
DB::raw('TRIM(sku_id) AS product_code'),
'i.qty AS qty',
'i.cost_price AS cost_price',
'i.cost_amount AS cost_amount',
]);
$sources = null;
if ($this->includesPurchaseSource($filters)) {
$sources = $this->filteredProcurementQuery($filters)->select([
'h.supplier_name AS supplier_name',
DB::raw('TRIM(sku_id) AS product_code'),
'i.qty AS qty',
'i.cost_price AS cost_price',
'i.cost_amount AS cost_amount',
]);
}
$sources = $purchase;
if ($this->shippingTableAvailable()) {
if ($this->includesShippingSource($filters) && $this->shippingTableAvailable()) {
$shipping = $this->filteredShippingQuery($filters)->select([
's.supplier_name AS supplier_name',
DB::raw('TRIM(barcode) AS product_code'),
@ -902,7 +912,7 @@ class SupplierPayableForecastRepository
DB::raw('NULL AS cost_price'),
DB::raw('NULL AS cost_amount'),
]);
$sources = $purchase->unionAll($shipping);
$sources = $sources === null ? $shipping : $sources->unionAll($shipping);
}
return $this->connection
@ -918,14 +928,19 @@ class SupplierPayableForecastRepository
private function pageSourceRows(array $filters, int $page, int $perPage): Collection
{
$limit = $page * $perPage;
$rows = $this->procurementSourceQuery($filters)
->orderByDesc('h.io_date')
->orderByDesc('h.Id')
->orderByDesc('i.Id')
->limit($limit)
->get();
$rows = collect();
if ($this->includesPurchaseSource($filters)) {
$rows = $rows->concat(
$this->procurementSourceQuery($filters)
->orderByDesc('h.io_date')
->orderByDesc('h.Id')
->orderByDesc('i.Id')
->limit($limit)
->get(),
);
}
if ($this->shippingTableAvailable()) {
if ($this->includesShippingSource($filters) && $this->shippingTableAvailable()) {
$rows = $rows->concat(
$this->shippingSourceQuery($filters)
->orderByDesc('s.ship_time')
@ -963,13 +978,90 @@ class SupplierPayableForecastRepository
*/
private function goodsUnionQuery(array $filters): \Illuminate\Database\Query\Builder
{
$purchase = $this->procurementSourceQuery($filters);
$purchase = $this->includesPurchaseSource($filters)
? $this->procurementSourceQuery($filters)
: null;
$shipping = $this->includesShippingSource($filters) && $this->shippingTableAvailable()
? $this->shippingSourceQuery($filters)
: null;
if (! $this->shippingTableAvailable()) {
return $purchase;
if ($purchase !== null && $shipping !== null) {
return $purchase->unionAll($shipping);
}
return $purchase->unionAll($this->shippingSourceQuery($filters));
// The source filter is normalized to "all" when a caller asks for a
// table that is not present, so at least one branch is guaranteed.
return $shipping ?? $purchase;
}
/**
* 页面汇总固定同时展示两类来源,帮助用户区分采购入库与代发发货;
* 当前筛选项只决定明细行与顶部合计,不影响这里的来源拆分。
*
* @param array{date_from:string,date_to:string,keyword:string,source?:string} $filters
* @return array{purchase:array{row_count:int,quantity:float,latest_at:?string},shipping:array{row_count:int,quantity:float,latest_at:?string}}
*/
private function goodsSourceBreakdown(array $filters): array
{
$scope = $filters;
$scope['source'] = self::SOURCE_ALL;
$purchase = $this->filteredProcurementQuery($scope)
->selectRaw(
'COUNT(*) AS row_count,'
. ' COALESCE(SUM(qty), 0) AS quantity,'
. ' MAX(io_date) AS latest_at',
)
->first();
$shipping = null;
if ($this->shippingTableAvailable()) {
$shipping = $this->filteredShippingQuery($scope)
->selectRaw(
'COUNT(*) AS row_count,'
. ' COALESCE(SUM(qty), 0) AS quantity,'
. ' MAX(ship_time) AS latest_at',
)
->first();
}
return [
self::SOURCE_PURCHASE => [
'row_count' => (int) ($purchase->row_count ?? 0),
'quantity' => (float) ($purchase->quantity ?? 0),
'latest_at' => $purchase->latest_at !== null ? (string) $purchase->latest_at : null,
],
self::SOURCE_SHIPPING => [
'row_count' => (int) ($shipping->row_count ?? 0),
'quantity' => (float) ($shipping->quantity ?? 0),
'latest_at' => $shipping?->latest_at !== null ? (string) $shipping->latest_at : null,
],
];
}
/** @param array{source?:string} $filters */
private function normalizedSource(array $filters): string
{
$source = strtolower(trim((string) ($filters['source'] ?? '')));
if ($source === self::SOURCE_SHIPPING && $this->shippingTableAvailable()) {
return self::SOURCE_SHIPPING;
}
return $source === self::SOURCE_PURCHASE
? self::SOURCE_PURCHASE
: self::SOURCE_ALL;
}
/** @param array{source?:string} $filters */
private function includesPurchaseSource(array $filters): bool
{
return $this->normalizedSource($filters) !== self::SOURCE_SHIPPING;
}
/** @param array{source?:string} $filters */
private function includesShippingSource(array $filters): bool
{
return $this->normalizedSource($filters) !== self::SOURCE_PURCHASE;
}
/**

View File

@ -5,9 +5,12 @@ namespace Modules\EcommerceFinance\Services;
use Closure;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class SupplierPayableOverrideStore
{
private ?bool $supplierNameIndexAvailable = null;
public function key(string $dataset, array $row): string
{
if (isset($row['sourceId']) && $row['sourceId'] !== '') {
@ -321,6 +324,62 @@ class SupplierPayableOverrideStore
->all();
}
/**
* 只读取指定供应商的数据,避免厂家页面把整个共享数据集解码到 PHP。
*
* @return array<int,array<string,mixed>>
*/
public function listRowsForSupplier(string $dataset, string $supplier, int $companyId): array
{
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
$this->whereSupplier($query, $supplier);
return $query
->orderBy('id')
->get()
->map(static function (object $record): array {
$values = json_decode((string) $record->values, true) ?: [];
$values['_action_key'] = (string) $record->record_key;
return $values;
})
->all();
}
/** @return list<string> */
public function distinctSuppliersInDataset(string $dataset, int $companyId): array
{
$query = $this->connection()->table('supplier_payable_overrides')
->where('company_id', $companyId)
->where('dataset', $dataset);
if ($this->supportsSupplierNameIndex()) {
$values = $query
->whereNotNull('supplier_name_key')
->where('supplier_name_key', '<>', '')
->distinct()
->pluck('supplier_name_key');
} else {
$expression = $this->connection()->getDriverName() === 'mysql'
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.supplier')))"
: "TRIM(json_extract(\"values\", '$.supplier'))";
$values = $query
->selectRaw("DISTINCT {$expression} AS supplier_name")
->pluck('supplier_name');
}
$suppliers = $values
->map(static fn (mixed $value): string => trim((string) $value))
->filter(static fn (string $value): bool => $value !== '')
->unique()
->values()
->all();
sort($suppliers, SORT_NATURAL | SORT_FLAG_CASE);
return $suppliers;
}
/**
* 按数据库分页读取终版明细,避免宽表在历史数据较多时整表解码。
*
@ -346,6 +405,7 @@ class SupplierPayableOverrideStore
}
$total = (int) (clone $query)->count();
$page = min($page, max((int) ceil($total / $perPage), 1));
if ($latestFirst && $this->connection()->getDriverName() === 'sqlite') {
$query->orderByRaw(
"(json_extract(`values`, '$.summary_month') IS NULL"
@ -441,4 +501,31 @@ class SupplierPayableOverrideStore
{
return DB::connection(config('database.supplier_payable_maintenance_connection'));
}
private function whereSupplier(\Illuminate\Database\Query\Builder $query, string $supplier): void
{
if ($this->supportsSupplierNameIndex()) {
$query->where('supplier_name_key', $supplier);
return;
}
$expression = $this->connection()->getDriverName() === 'mysql'
? "TRIM(JSON_UNQUOTE(JSON_EXTRACT(`values`, '$.supplier')))"
: "TRIM(json_extract(\"values\", '$.supplier'))";
$query->whereRaw("{$expression} = ?", [$supplier]);
}
private function supportsSupplierNameIndex(): bool
{
if ($this->supplierNameIndexAvailable !== null) {
return $this->supplierNameIndexAvailable;
}
$schema = Schema::connection($this->connection()->getName());
$this->supplierNameIndexAvailable = $schema->hasTable('supplier_payable_overrides')
&& $schema->hasColumn('supplier_payable_overrides', 'supplier_name_key');
return $this->supplierNameIndexAvailable;
}
}

View File

@ -41,6 +41,17 @@ class SupplierStatementStore
return $this->store->listRows(self::PREFIX . $supplier, $companyId);
}
/** @return array{rows:list<array<string,mixed>>,total:int} */
public function paginate(string $supplier, int $companyId, int $perPage, int $page): array
{
return $this->store->paginateRows(
self::PREFIX . $supplier,
$companyId,
$perPage,
$page,
);
}
/** @return list<array<string,mixed>> 最近的上传记录(新到旧) */
public function uploads(string $supplier, int $companyId, int $limit = 10): array
{

View File

@ -36,6 +36,18 @@ class SupplierPayableForecastPageData
'amount' => 0.0,
'estimated_amount_after_discount' => 0.0,
'supplier_count' => 0,
'sources' => [
SupplierPayableForecastRepository::SOURCE_PURCHASE => [
'row_count' => 0,
'quantity' => 0.0,
'latest_at' => null,
],
SupplierPayableForecastRepository::SOURCE_SHIPPING => [
'row_count' => 0,
'quantity' => 0.0,
'latest_at' => null,
],
],
'rows' => [],
'page' => max((int) $request->query('goods_page', 1), 1),
'per_page' => 20,
@ -91,6 +103,9 @@ class SupplierPayableForecastPageData
: $filters['date_from'],
'goods_date_to' => $filters['date_to'] !== '' ? $filters['date_to'] : null,
'goods_keyword' => $filters['keyword'] !== '' ? $filters['keyword'] : null,
'goods_source' => $filters['source'] !== SupplierPayableForecastRepository::SOURCE_ALL
? $filters['source']
: null,
], static fn (mixed $value): bool => $value !== null && $value !== '');
$rows = new LengthAwarePaginator(
@ -152,6 +167,7 @@ class SupplierPayableForecastPageData
'amount' => $result['amount'],
'estimated_amount_after_discount' => $result['estimated_amount_after_discount'],
'supplier_count' => $result['supplier_count'],
'sources' => $result['sources'],
'matched_price_rows' => collect($result['rows'])->where('priceMatched', true)->count(),
'missing_price_rows' => collect($result['rows'])->where('priceMatched', false)->count(),
],
@ -177,7 +193,7 @@ class SupplierPayableForecastPageData
];
}
/** @return array{date_from:string,date_to:string,keyword:string} */
/** @return array{date_from:string,date_to:string,keyword:string,source:string} */
public function goodsFilters(Request $request): array
{
$minimum = Carbon::createFromFormat('!Y-m-d H:i:s', SupplierPayableForecastRepository::DEFAULT_FROM_TIME);
@ -195,10 +211,20 @@ class SupplierPayableForecastPageData
$to = $from->copy();
}
$source = (string) $request->query('goods_source', SupplierPayableForecastRepository::SOURCE_ALL);
if (! in_array($source, [
SupplierPayableForecastRepository::SOURCE_ALL,
SupplierPayableForecastRepository::SOURCE_PURCHASE,
SupplierPayableForecastRepository::SOURCE_SHIPPING,
], true)) {
$source = SupplierPayableForecastRepository::SOURCE_ALL;
}
return [
'date_from' => $from->format('Y-m-d H:i:s'),
'date_to' => $to?->format('Y-m-d H:i:s') ?? '',
'keyword' => mb_substr(trim((string) $request->query('goods_keyword', '')), 0, 120),
'source' => $source,
];
}

View File

@ -315,28 +315,21 @@ class SupplierReconciliationPageData
);
$supplierQuery = $selected;
} else {
$mine = $this->store->listRows(
$suppliers = [];
foreach ($this->store->distinctSuppliersInDataset(
PayablesFinalActions::DATASET_PREFIX . 'supplier:payment-reconciliation',
$companyId,
);
$suppliers = [];
foreach ($mine as $row) {
$name = trim((string) ($row['supplier'] ?? ''));
if ($name !== '') {
$suppliers[$name] = true;
}
) as $name) {
$suppliers[$name] = true;
}
foreach ($this->statements->uploadedSuppliers($companyId) as $name) {
$suppliers[$name] = true;
}
foreach ($this->store->listRows(
foreach ($this->store->distinctSuppliersInDataset(
PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation',
$companyId,
) as $row) {
$name = trim((string) ($row['supplier'] ?? ''));
if ($name !== '') {
$suppliers[$name] = true;
}
) as $name) {
$suppliers[$name] = true;
}
$supplierNames = array_keys($suppliers);
sort($supplierNames);
@ -350,7 +343,9 @@ class SupplierReconciliationPageData
}
$page = max((int) request()->query('rows_page', 1), 1);
$statementRows = $selected !== '' ? $this->statements->rows($selected, $companyId) : [];
$statementPage = $selected !== ''
? $this->statements->paginate($selected, $companyId, self::PER_PAGE, $page)
: ['rows' => [], 'total' => 0];
$returnData = $selected !== ''
? $this->returnPanelData($selected, $companyId, request()->query())
: ['returnPanel' => null, 'returnWarehouses' => []];
@ -365,8 +360,8 @@ class SupplierReconciliationPageData
'supplierBindings' => $supplierBindings,
'supplierCount' => $supplierCount,
'uploads' => $selected !== '' ? $this->statements->uploads($selected, $companyId) : [],
'statementRows' => array_slice($statementRows, ($page - 1) * self::PER_PAGE, self::PER_PAGE),
'statementTotal' => count($statementRows),
'statementRows' => $statementPage['rows'],
'statementTotal' => $statementPage['total'],
'returnPanel' => $returnData['returnPanel'],
'returnWarehouses' => $returnData['returnWarehouses'],
'rowsPage' => $page,
@ -387,12 +382,12 @@ class SupplierReconciliationPageData
public function portalData(string $supplier, int $companyId): array
{
$page = max((int) request()->query('rows_page', 1), 1);
$statementRows = $this->statements->rows($supplier, $companyId);
$statementPage = $this->statements->paginate($supplier, $companyId, self::PER_PAGE, $page);
$returnData = $this->returnPanelData($supplier, $companyId, request()->query());
return [
'statementRows' => array_slice($statementRows, ($page - 1) * self::PER_PAGE, self::PER_PAGE),
'statementTotal' => count($statementRows),
'statementRows' => $statementPage['rows'],
'statementTotal' => $statementPage['total'],
'uploads' => $this->statements->uploads($supplier, $companyId),
'returnPanel' => $returnData['returnPanel'],
'returnWarehouses' => $returnData['returnWarehouses'],
@ -1035,15 +1030,11 @@ class SupplierReconciliationPageData
/** @return list<array<string,mixed>> 该厂家的退货明细(我方数据,展示给厂家确认扣减) */
public function returnRows(string $supplier, int $companyId): array
{
$rows = $this->store->listRows(
return $this->store->listRowsForSupplier(
PayablesFinalActions::DATASET_PREFIX . 'supplier:return-reconciliation',
$supplier,
$companyId,
);
return array_values(array_filter(
$rows,
static fn (array $row): bool => trim((string) ($row['supplier'] ?? '')) === $supplier,
));
}
/**

View File

@ -244,7 +244,7 @@
.supplier-payable-forecast .npf-filter {
display: grid;
grid-template-columns: minmax(220px, .9fr) minmax(220px, .9fr) minmax(240px, 1.8fr) auto;
grid-template-columns: minmax(210px, .9fr) minmax(210px, .9fr) minmax(220px, 1.4fr) minmax(150px, .65fr) auto;
align-items: end;
gap: 10px;
padding: 12px;
@ -259,7 +259,8 @@
.supplier-payable-forecast .npf-field { display: grid; gap: 4px; min-width: 0; }
.supplier-payable-forecast .npf-field span { color: var(--npf-muted); font-size: 11px; font-weight: 600; }
.supplier-payable-forecast .npf-field input {
.supplier-payable-forecast .npf-field input,
.supplier-payable-forecast .npf-field select {
width: 100%;
min-width: 0;
height: 34px;
@ -271,7 +272,13 @@
font-size: 12px;
}
.supplier-payable-forecast .npf-field input:focus {
.supplier-payable-forecast .npf-field select {
padding-right: 28px;
cursor: pointer;
}
.supplier-payable-forecast .npf-field input:focus,
.supplier-payable-forecast .npf-field select:focus {
border-color: var(--npf-gold);
outline: 0;
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.20);
@ -380,6 +387,30 @@
}
.supplier-payable-forecast .npf-price-note { display: block; margin-top: 2px; color: var(--npf-warning); font-size: 10px; }
.supplier-payable-forecast .npf-data-note { color: var(--npf-muted); font-size: 11px; line-height: 1.7; }
.supplier-payable-forecast .npf-source-breakdown {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin-top: 8px;
}
.supplier-payable-forecast .npf-source-item {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px 12px;
padding: 9px 11px;
border: 1px solid #EEE8DC;
border-radius: 8px;
background: #FCFBF8;
color: var(--npf-muted);
font-size: 11px;
}
.supplier-payable-forecast .npf-source-item strong {
color: var(--npf-ink);
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.supplier-payable-forecast .npf-source-item small { margin-left: auto; }
.supplier-payable-forecast .npf-pagination { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; color: var(--npf-muted); font-size: 11px; }
.supplier-payable-forecast .npf-pagination-links { display: flex; gap: 7px; }
@ -396,6 +427,7 @@
.supplier-payable-forecast .npf-panel-head { display: grid; }
.supplier-payable-forecast .npf-scope { grid-template-columns: minmax(0, 1fr); }
.supplier-payable-forecast .npf-data-overview { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.supplier-payable-forecast .npf-source-breakdown { grid-template-columns: minmax(0, 1fr); }
.supplier-payable-forecast .npf-filter { grid-template-columns: minmax(0, 1fr); }
.supplier-payable-forecast .npf-summary-filter { grid-template-columns: minmax(0, 1fr); }
.supplier-payable-forecast .npf-filter-actions { grid-column: 1; justify-content: flex-start; }
@ -532,6 +564,25 @@
</div>
</div>
@php
$purchaseSource = $goodsForecastSummary['sources']['purchase'] ?? [];
$shippingSource = $goodsForecastSummary['sources']['shipping'] ?? [];
@endphp
<div class="npf-source-breakdown" aria-label="筛选范围数据来源拆分">
<div class="npf-source-item">
<span>采购入库</span>
<strong>{{ number_format((int) ($purchaseSource['row_count'] ?? 0)) }} 行</strong>
<span>数量 {{ number_format((float) ($purchaseSource['quantity'] ?? 0), 2) }}</span>
<small>最近入库 {{ $purchaseSource['latest_at'] ?? '—' }}</small>
</div>
<div class="npf-source-item">
<span>代发发货</span>
<strong>{{ number_format((int) ($shippingSource['row_count'] ?? 0)) }} 行</strong>
<span>数量 {{ number_format((float) ($shippingSource['quantity'] ?? 0), 2) }}</span>
<small>最近发货 {{ $shippingSource['latest_at'] ?? '—' }}</small>
</div>
</div>
<form method="GET" action="{{ request()->url() }}" class="npf-filter" aria-label="查询货款明细">
<input type="hidden" name="forecast_view" value="goods">
<div class="npf-field">
@ -564,6 +615,14 @@
<span>关键字</span>
<input type="search" name="goods_keyword" maxlength="120" value="{{ $goodsForecastFilters['keyword'] }}" placeholder="单号 / 供应商 / 货号 / 条形码 / 仓库 / 快递单号">
</label>
<label class="npf-field">
<span>数据来源</span>
<select name="goods_source" aria-label="数据来源">
<option value="all" @selected($goodsForecastFilters['source'] === 'all')>全部数据</option>
<option value="purchase" @selected($goodsForecastFilters['source'] === 'purchase')>采购入库</option>
<option value="shipping" @selected($goodsForecastFilters['source'] === 'shipping') @disabled(! $goodsForecastSyncStatus['shipping_available'])>代发发货</option>
</select>
</label>
<div class="npf-filter-actions">
<button type="submit" class="npf-button is-primary">查询</button>
<button
@ -648,6 +707,7 @@
</div>
<div class="npf-data-note">
顶部筛选结果是当前所选数据来源的合计;上方来源拆分始终分别显示采购入库与代发发货,核对手工采购入库数据时请将“数据来源”切换为“采购入库”。
采购入库固定剔除:仓库“配件单仓”、采购单号为空、供应商“虚拟/简尚送货”、商品编码以“DF-”开头。
发货明细只保留仓库名称含“代发仓”的记录,并剔除条形码以“DF-”开头的记录;日期取发货时间。
单价优先取工作平台 <code>pm_priceAdjustment_log</code> 中该商品最新一条 <code>priceType=1</code> 的变价后价格;

View File

@ -666,6 +666,9 @@ class NegativeAlertPagesTest extends FeatureTestCase
])
->assertSeeText('24.00')
->assertSeeText('60.00')
->assertSeeText('数据来源')
->assertSeeText('最近入库')
->assertSeeText('最近发货')
->assertSeeText('上月重跑')
->assertSeeText('+2 行')
->assertSeeText('+3.00 件')
@ -685,6 +688,9 @@ class NegativeAlertPagesTest extends FeatureTestCase
$this->assertStringContainsString("timeField('second', '秒', 59", $html);
$this->assertStringContainsString('业务日期起', $html);
$this->assertStringContainsString('2026-10-01 00:00:00', $html);
$this->assertStringContainsString('name="goods_source"', $html);
$this->assertStringContainsString('<option value="purchase"', $html);
$this->assertStringContainsString('<option value="shipping"', $html);
$this->assertStringContainsString(route('business.supplier-payable-forecast.goods.export'), $html);
$this->assertStringContainsString('导出当前筛选', $html);
$this->assertStringContainsString('CaiWuDatePicker.setup(filterForm)', $html);
@ -746,6 +752,24 @@ class NegativeAlertPagesTest extends FeatureTestCase
'goods_date_to' => '2026-10-01',
]))->assertOk()
->assertSeeText('IN-20261001');
$this->loginAs()->get(route('business.pages.show', [
'section' => 'negative-alerts',
'page' => 'supplier-negative-alert',
'tab' => 'payable-forecast',
'goods_source' => 'purchase',
]))->assertOk()
->assertSeeText('STYLE-20261001')
->assertDontSeeText('代发测试供应商');
$this->loginAs()->get(route('business.pages.show', [
'section' => 'negative-alerts',
'page' => 'supplier-negative-alert',
'tab' => 'payable-forecast',
'goods_source' => 'shipping',
]))->assertOk()
->assertSeeText('STYLE-DAIFA')
->assertDontSeeText('测试供应商SKU-20261001');
}
public function test_supplier_payable_forecast_export_streams_all_rows_matching_second_precision(): void

View File

@ -1186,6 +1186,78 @@ class SupplierReconciliationTest extends FeatureTestCase
->assertDontSeeText('鸣飞家具 · 厂家对账');
}
public function test_supplier_page_filters_and_paginates_with_two_hundred_suppliers(): void
{
$store = app(SupplierPayableOverrideStore::class);
$companyId = (int) $this->company->id;
$returnRows = [];
for ($index = 1; $index <= 200; $index++) {
$supplier = $index === 200 ? '建林木业' : sprintf('厂家%03d', $index);
$returnRows['bulk:' . $index] = [
'summary_month' => '2026-10',
'send_time' => '2026-10-20 10:00:00',
'supplier' => $supplier,
'barcode' => sprintf('退货-RET-%03d', $index),
'sku_name' => '分页测试商品',
'qty' => '1',
'unit_price' => '10',
'amount' => '10',
];
}
$store->saveBatch(
'final:supplier:return-reconciliation',
$returnRows,
$companyId,
null,
'test',
);
$statementRows = [];
for ($index = 1; $index <= 31; $index++) {
$statementRows[] = array_merge(
$this->statementRow(sprintf('对账-%02d', $index), '10.00', '1', '10.00'),
['supplier' => '建林木业'],
);
}
$this->seedStatement('建林木业', $statementRows);
$this->assertSame(
['退货-RET-200'],
array_column(
$store->listRowsForSupplier(
'final:supplier:return-reconciliation',
'建林木业',
$companyId,
),
'barcode',
),
);
$this->assertCount(
200,
$store->distinctSuppliersInDataset(
'final:supplier:return-reconciliation',
$companyId,
),
);
$this->loginAs()->get(route('business.pages.show', [
'company_id' => $companyId,
'section' => 'supplier-reconciliation',
'page' => 'supplier-data',
'supplier' => '建林木业',
'rows_page' => 2,
]))
->assertOk()
->assertSeeText('建林木业 · 厂家对账')
->assertSeeText('第 2 / 3 页')
->assertSeeText('对账-16')
->assertSeeText('对账-30')
->assertDontSeeText('对账-15')
->assertDontSeeText('对账-31')
->assertSeeText('退货-RET-200')
->assertDontSeeText('退货-RET-199');
}
public function test_supplier_portal_is_locked_to_its_own_page_and_blocks_core_routes(): void
{
$this->seedStatement('晨丰', [

View File

@ -232,6 +232,32 @@ class BusinessMirrorScheduleTest extends TestCase
$this->assertStringNotContainsString('supplier-statement:send-reminders', $kernel);
}
public function test_release_scripts_fully_reconcile_supplier_payable_receipts_daily(): void
{
foreach (['activate-release.sh', 'activate-incremental-release.sh'] as $script) {
$contents = file_get_contents(dirname(__DIR__, 3) . '/deploy/' . $script);
$this->assertIsString($contents);
$this->assertStringContainsString(
'40 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock '
. '/usr/bin/docker exec -u www-data caiwu_app php artisan '
. 'business-mirror:sync-supplier-payable-forecast --quiet >/dev/null 2>&1',
$contents,
$script,
);
$this->assertSame(
2,
substr_count($contents, 'business-mirror:sync-supplier-payable-forecast --quiet'),
$script,
);
$this->assertStringContainsString(
'# 本次发布立即校正一次供应商采购入库数据,避免等待次日定时任务。',
$contents,
$script,
);
}
}
public function test_laravel_scheduler_runs_worklog_sync_every_fifteen_minutes(): void
{
$contents = file_get_contents(dirname(__DIR__, 3) . '/app/Console/Kernel.php');

View File

@ -355,12 +355,33 @@ class SupplierPayableForecastRepositoryTest extends TestCase
$second = $repository->goodsDetails($filters, 2, 2);
$this->assertSame(4, $first['total']);
$this->assertSame(2, $first['sources']['purchase']['row_count']);
$this->assertSame(3.0, $first['sources']['purchase']['quantity']);
$this->assertSame('2026-10-03 09:00:00', $first['sources']['purchase']['latest_at']);
$this->assertSame(2, $first['sources']['shipping']['row_count']);
$this->assertSame(3.0, $first['sources']['shipping']['quantity']);
$this->assertSame('2026-10-04 09:00:00', $first['sources']['shipping']['latest_at']);
$this->assertSame(['2026-10-04 09:00:00', '2026-10-03 09:00:00'], array_column($first['rows'], 'date'));
$this->assertSame(['2026-10-02 09:00:00', '2026-10-01 09:00:00'], array_column($second['rows'], 'date'));
$purchaseOnly = $repository->goodsDetails($filters + ['source' => 'purchase'], 1, 10);
$shippingOnly = $repository->goodsDetails($filters + ['source' => 'shipping'], 1, 10);
$this->assertSame(2, $purchaseOnly['total']);
$this->assertSame(3.0, $purchaseOnly['quantity']);
$this->assertSame(['purchase'], array_values(array_unique(array_column($purchaseOnly['rows'], 'sourceType'))));
$this->assertSame(2, $shippingOnly['total']);
$this->assertSame(3.0, $shippingOnly['quantity']);
$this->assertSame(['shipping'], array_values(array_unique(array_column($shippingOnly['rows'], 'sourceType'))));
$this->assertSame(
['2026-10-04 09:00:00', '2026-10-03 09:00:00', '2026-10-02 09:00:00', '2026-10-01 09:00:00'],
array_column(iterator_to_array($repository->goodsRowsForExport($filters, 1)), 'date'),
);
$purchaseExport = iterator_to_array(
$repository->goodsRowsForExport($filters + ['source' => 'purchase'], 1),
);
$this->assertCount(2, $purchaseExport);
$this->assertSame(['purchase'], array_values(array_unique(array_column($purchaseExport, 'sourceType'))));
}
public function test_purchase_return_details_match_return_reconciliation_and_goods_pricing_rules(): void