831 lines
32 KiB
PHP
831 lines
32 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Repositories;
|
|
|
|
use Illuminate\Database\ConnectionInterface;
|
|
use Illuminate\Database\DatabaseManager;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
class SupplierPayableForecastRepository
|
|
{
|
|
public const HEAD_DATASET = 'jiansun.dbo.jst_purchaseReceiving';
|
|
|
|
public const ITEM_DATASET = 'jiansun.dbo.jst_purchaseReceivingItem';
|
|
|
|
public const PRICE_DATASET = 'jiansun.dbo.pm_priceAdjustment_log';
|
|
|
|
public const CURRENT_PRICE_DATASET = 'jiansun.dbo.pm_priceAdjustment';
|
|
|
|
public const PRODUCT_DATASET = 'operations_replica.rpt.jst_sku';
|
|
|
|
public const HEAD_TABLE = 'js_jst_purchase_receiving';
|
|
|
|
public const ITEM_TABLE = 'js_jst_purchase_receiving_item';
|
|
|
|
public const PRICE_TABLE = 'js_pm_price_adjustment_log';
|
|
|
|
public const CURRENT_PRICE_TABLE = 'js_pm_price_adjustment';
|
|
|
|
public const PRODUCT_TABLE = 'ops_jst_sku';
|
|
|
|
public const SHIPPING_TABLE = 'jst_oms_shipping';
|
|
|
|
public const DEFAULT_FROM = '2026-10-01';
|
|
|
|
public const DEFAULT_FROM_TIME = self::DEFAULT_FROM . ' 00:00:00';
|
|
|
|
private readonly ConnectionInterface $connection;
|
|
|
|
private readonly string $connectionName;
|
|
|
|
private ?bool $shippingTableAvailable = null;
|
|
|
|
private ?bool $currentPriceTableAvailable = null;
|
|
|
|
private ?bool $productTableAvailable = null;
|
|
|
|
public function __construct(DatabaseManager $database)
|
|
{
|
|
$this->connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
|
|
$this->connection = $database->connection($this->connectionName);
|
|
}
|
|
|
|
/**
|
|
* @return array{
|
|
* ready:bool,
|
|
* code:string,
|
|
* initialized_at:?string,
|
|
* last_succeeded_at:?string,
|
|
* states:array<string,string>,
|
|
* shipping_available:bool,
|
|
* current_price_available:bool,
|
|
* product_catalog_available:bool
|
|
* }
|
|
*/
|
|
public function syncStatus(): array
|
|
{
|
|
$schema = Schema::connection($this->connectionName);
|
|
foreach ([self::HEAD_TABLE, self::ITEM_TABLE, self::PRICE_TABLE, 'business_mirror_table_states'] as $table) {
|
|
if (! $schema->hasTable($table)) {
|
|
return [
|
|
'ready' => false,
|
|
'code' => 'unavailable',
|
|
'initialized_at' => null,
|
|
'last_succeeded_at' => null,
|
|
'states' => [],
|
|
'shipping_available' => $schema->hasTable(self::SHIPPING_TABLE),
|
|
'current_price_available' => $schema->hasTable(self::CURRENT_PRICE_TABLE),
|
|
'product_catalog_available' => $schema->hasTable(self::PRODUCT_TABLE),
|
|
];
|
|
}
|
|
}
|
|
|
|
$keys = [self::HEAD_DATASET, self::ITEM_DATASET, self::PRICE_DATASET];
|
|
$rows = $this->connection->table('business_mirror_table_states')
|
|
->whereIn('dataset_key', $keys)
|
|
->get(['dataset_key', 'status', 'initial_completed_at', 'last_succeeded_at'])
|
|
->keyBy('dataset_key');
|
|
|
|
$states = [];
|
|
$ready = $rows->count() === count($keys);
|
|
$initializedAt = null;
|
|
$lastSucceededAt = null;
|
|
|
|
foreach ($keys as $key) {
|
|
$row = $rows->get($key);
|
|
$initialized = $row !== null && ($row->initial_completed_at ?? null) !== null;
|
|
$ready = $ready && $initialized;
|
|
$states[$key] = $initialized ? (string) ($row->status ?? 'ready') : (string) ($row->status ?? 'pending');
|
|
if ($initialized) {
|
|
$completedAt = (string) $row->initial_completed_at;
|
|
if ($initializedAt === null || $completedAt > $initializedAt) {
|
|
$initializedAt = $completedAt;
|
|
}
|
|
}
|
|
if (($row->last_succeeded_at ?? null) !== null) {
|
|
$succeededAt = (string) $row->last_succeeded_at;
|
|
if ($lastSucceededAt === null || $succeededAt > $lastSucceededAt) {
|
|
$lastSucceededAt = $succeededAt;
|
|
}
|
|
}
|
|
}
|
|
|
|
return [
|
|
'ready' => $ready,
|
|
'code' => $ready ? 'ready' : ($rows->contains(static fn (object $row): bool => $row->status === 'running')
|
|
? 'initializing'
|
|
: 'pending'),
|
|
'initialized_at' => $initializedAt,
|
|
'last_succeeded_at' => $lastSucceededAt,
|
|
'states' => $states,
|
|
'shipping_available' => $this->shippingTableAvailable(),
|
|
'current_price_available' => $this->currentPriceTableAvailable(),
|
|
'product_catalog_available' => $this->productTableAvailable(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
* @return array{
|
|
* total:int,
|
|
* quantity:float,
|
|
* amount:float,
|
|
* estimated_amount_after_discount:float,
|
|
* supplier_count:int,
|
|
* rows:list<array<string,mixed>>,
|
|
* page:int,
|
|
* per_page:int
|
|
* }
|
|
*/
|
|
public function goodsDetails(array $filters, int $page, int $perPage = 20): array
|
|
{
|
|
$query = $this->goodsSourceRows($filters);
|
|
$aggregate = $this->goodsSummary($filters);
|
|
|
|
$perPage = min(max($perPage, 1), 100);
|
|
$page = max($page, 1);
|
|
$sourceRows = $this->pageSourceRows($filters, $page, $perPage);
|
|
|
|
$priceMap = $this->latestEffectivePrices(
|
|
$sourceRows->pluck('product_code')->filter()->map(static fn (mixed $value): string => trim((string) $value))->unique()->values()->all()
|
|
);
|
|
$catalogCostMap = $this->catalogCostsForRows($sourceRows, $priceMap);
|
|
|
|
$rows = $sourceRows->map(
|
|
fn (object $row): array => $this->formatGoodsRow(
|
|
$row,
|
|
$priceMap->get($this->normalizeSku($row->product_code)),
|
|
$catalogCostMap->get($this->normalizeSku($row->product_code)),
|
|
)
|
|
)->values()->all();
|
|
|
|
return [
|
|
'total' => (int) ($aggregate->row_count ?? 0),
|
|
'quantity' => (float) ($aggregate->quantity ?? 0),
|
|
'amount' => (float) ($aggregate->amount ?? 0),
|
|
'estimated_amount_after_discount' => (float) ($aggregate->estimated_amount_after_discount ?? 0),
|
|
'supplier_count' => (int) ($aggregate->supplier_count ?? 0),
|
|
'rows' => $rows,
|
|
'page' => $page,
|
|
'per_page' => $perPage,
|
|
];
|
|
}
|
|
|
|
/** @param array{date_from:string,date_to:string,keyword:string} $filters */
|
|
private function goodsSummary(array $filters): object
|
|
{
|
|
$query = $this->goodsSummarySourceRows($filters);
|
|
$groups = (clone $query)
|
|
->select('product_code')
|
|
->selectRaw(
|
|
'COUNT(*) AS row_count,'
|
|
. ' COALESCE(SUM(qty), 0) AS quantity,'
|
|
. ' COALESCE(SUM(CASE'
|
|
. ' WHEN cost_amount > 0 THEN ROUND(cost_amount * 0.8, 2)'
|
|
. ' WHEN cost_price > 0 THEN ROUND(qty * cost_price * 0.8, 2)'
|
|
. ' ELSE 0 END), 0) AS estimated_amount_after_discount,'
|
|
. ' COALESCE(SUM(CASE'
|
|
. ' WHEN (cost_amount IS NULL OR cost_amount <= 0)'
|
|
. ' AND (cost_price IS NULL OR cost_price <= 0) THEN qty'
|
|
. ' ELSE 0 END), 0) AS fallback_quantity',
|
|
)
|
|
->groupBy('product_code')
|
|
->get();
|
|
|
|
if ($groups->isEmpty()) {
|
|
return (object) [
|
|
'row_count' => 0,
|
|
'supplier_count' => 0,
|
|
'quantity' => 0,
|
|
'amount' => 0,
|
|
'estimated_amount_after_discount' => 0,
|
|
];
|
|
}
|
|
|
|
$priceMap = $this->latestEffectivePrices(
|
|
$groups->pluck('product_code')
|
|
->map(static fn (mixed $value): string => trim((string) $value))
|
|
->filter()
|
|
->unique()
|
|
->values()
|
|
->all(),
|
|
);
|
|
$amount = $groups->sum(function (object $group) use ($priceMap): float {
|
|
$price = $priceMap->get($this->normalizeSku($group->product_code));
|
|
if ($price === null) {
|
|
return 0.0;
|
|
}
|
|
|
|
return round((float) $group->quantity * (float) $price->price, 2);
|
|
});
|
|
$catalogCostMap = $this->latestCatalogCosts(
|
|
$groups
|
|
->filter(fn (object $group): bool => ! $priceMap->has($this->normalizeSku($group->product_code))
|
|
&& (float) $group->fallback_quantity > 0)
|
|
->pluck('product_code')
|
|
->map(static fn (mixed $value): string => trim((string) $value))
|
|
->filter()
|
|
->unique()
|
|
->values()
|
|
->all(),
|
|
);
|
|
$catalogEstimate = $groups->sum(function (object $group) use ($priceMap, $catalogCostMap): float {
|
|
if ($priceMap->has($this->normalizeSku($group->product_code))) {
|
|
return 0.0;
|
|
}
|
|
$catalogCost = $catalogCostMap->get($this->normalizeSku($group->product_code));
|
|
if ($catalogCost === null) {
|
|
return 0.0;
|
|
}
|
|
|
|
return round((float) $group->fallback_quantity * (float) $catalogCost->price * 0.8, 2);
|
|
});
|
|
$unpricedReceiptEstimate = $groups->sum(function (object $group) use ($priceMap): float {
|
|
if ($priceMap->has($this->normalizeSku($group->product_code))) {
|
|
return 0.0;
|
|
}
|
|
|
|
return (float) $group->estimated_amount_after_discount;
|
|
});
|
|
|
|
return (object) [
|
|
'row_count' => (int) $groups->sum('row_count'),
|
|
'supplier_count' => (int) (clone $query)->distinct()->count('supplier_name'),
|
|
'quantity' => (float) $groups->sum('quantity'),
|
|
'amount' => round($amount, 2),
|
|
'estimated_amount_after_discount' => round(
|
|
$unpricedReceiptEstimate + $catalogEstimate,
|
|
2,
|
|
),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 流式读取当前筛选全集,按小批次匹配变价,避免导出把整表装入内存。
|
|
*
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
* @return \Generator<int,array<string,mixed>>
|
|
*/
|
|
public function goodsRowsForExport(array $filters, int $batchSize = 500): \Generator
|
|
{
|
|
$batchSize = min(max($batchSize, 1), 1000);
|
|
$last = null;
|
|
|
|
while (true) {
|
|
$query = $this->goodsSourceRows($filters);
|
|
if ($last !== null) {
|
|
$this->applyExportCursor($query, $last);
|
|
}
|
|
$sourceRows = $query
|
|
->orderByDesc('occurred_at')
|
|
->orderByDesc('source_rank')
|
|
->orderByDesc('source_id')
|
|
->orderByDesc('source_item_id')
|
|
->limit($batchSize)
|
|
->get();
|
|
if ($sourceRows->isEmpty()) {
|
|
return;
|
|
}
|
|
|
|
$priceMap = $this->latestEffectivePrices(
|
|
$sourceRows->pluck('product_code')
|
|
->filter()
|
|
->map(static fn (mixed $value): string => trim((string) $value))
|
|
->unique()
|
|
->values()
|
|
->all()
|
|
);
|
|
$catalogCostMap = $this->catalogCostsForRows($sourceRows, $priceMap);
|
|
|
|
foreach ($sourceRows as $row) {
|
|
yield $this->formatGoodsRow(
|
|
$row,
|
|
$priceMap->get($this->normalizeSku($row->product_code)),
|
|
$catalogCostMap->get($this->normalizeSku($row->product_code)),
|
|
);
|
|
}
|
|
|
|
$lastRow = $sourceRows->last();
|
|
$last = [
|
|
'occurred_at' => (string) $lastRow->occurred_at,
|
|
'source_rank' => (int) $lastRow->source_rank,
|
|
'source_id' => (int) $lastRow->source_id,
|
|
'source_item_id' => (int) $lastRow->source_item_id,
|
|
];
|
|
if ($sourceRows->count() < $batchSize) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param array{occurred_at:string,source_rank:int,source_id:int,source_item_id:int} $last
|
|
*/
|
|
private function applyExportCursor(\Illuminate\Database\Query\Builder $query, array $last): void
|
|
{
|
|
$query->where(static function (\Illuminate\Database\Query\Builder $nested) use ($last): void {
|
|
$nested->where('occurred_at', '<', $last['occurred_at'])
|
|
->orWhere(static function (\Illuminate\Database\Query\Builder $sameTime) use ($last): void {
|
|
$sameTime->where('occurred_at', '=', $last['occurred_at'])
|
|
->where(static function (\Illuminate\Database\Query\Builder $sameRank) use ($last): void {
|
|
$sameRank->where('source_rank', '<', $last['source_rank'])
|
|
->orWhere(static function (\Illuminate\Database\Query\Builder $sameSource) use ($last): void {
|
|
$sameSource->where('source_rank', '=', $last['source_rank'])
|
|
->where(static function (\Illuminate\Database\Query\Builder $sameId) use ($last): void {
|
|
$sameId->where('source_id', '<', $last['source_id'])
|
|
->orWhere(static function (\Illuminate\Database\Query\Builder $sameItem) use ($last): void {
|
|
$sameItem->where('source_id', '=', $last['source_id'])
|
|
->where('source_item_id', '<', $last['source_item_id']);
|
|
});
|
|
});
|
|
});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 采购入库与代发仓发货明细合并为同一列集合,表格与导出共用。
|
|
*
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function goodsSourceRows(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
return $this->connection
|
|
->query()
|
|
->fromSub($this->goodsUnionQuery($filters), 'forecast_rows');
|
|
}
|
|
|
|
/**
|
|
* 汇总只需要供应商、商品编码、数量和成本,避免为计算合计而物化完整表格列。
|
|
*
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
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 = $purchase;
|
|
if ($this->shippingTableAvailable()) {
|
|
$shipping = $this->filteredShippingQuery($filters)->select([
|
|
's.supplier_name AS supplier_name',
|
|
DB::raw('TRIM(barcode) AS product_code'),
|
|
's.qty AS qty',
|
|
DB::raw('NULL AS cost_price'),
|
|
DB::raw('NULL AS cost_amount'),
|
|
]);
|
|
$sources = $purchase->unionAll($shipping);
|
|
}
|
|
|
|
return $this->connection
|
|
->query()
|
|
->fromSub($sources, 'forecast_summary_rows');
|
|
}
|
|
|
|
/**
|
|
* 页面分页分别读取两条索引有序数据,再在内存中合并;避免每页都对全部联合结果排序。
|
|
*
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
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();
|
|
|
|
if ($this->shippingTableAvailable()) {
|
|
$rows = $rows->concat(
|
|
$this->shippingSourceQuery($filters)
|
|
->orderByDesc('s.ship_time')
|
|
->orderByDesc('s.id')
|
|
->orderByDesc('s.sku_source_id')
|
|
->limit($limit)
|
|
->get(),
|
|
);
|
|
}
|
|
|
|
return $rows
|
|
->sort(static function (object $left, object $right): int {
|
|
$time = strcmp((string) $right->occurred_at, (string) $left->occurred_at);
|
|
if ($time !== 0) {
|
|
return $time;
|
|
}
|
|
|
|
$rank = (int) $right->source_rank <=> (int) $left->source_rank;
|
|
if ($rank !== 0) {
|
|
return $rank;
|
|
}
|
|
|
|
$source = (int) $right->source_id <=> (int) $left->source_id;
|
|
|
|
return $source !== 0
|
|
? $source
|
|
: (int) $right->source_item_id <=> (int) $left->source_item_id;
|
|
})
|
|
->slice(($page - 1) * $perPage, $perPage)
|
|
->values();
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function goodsUnionQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
$purchase = $this->procurementSourceQuery($filters);
|
|
|
|
if (! $this->shippingTableAvailable()) {
|
|
return $purchase;
|
|
}
|
|
|
|
return $purchase->unionAll($this->shippingSourceQuery($filters));
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function procurementSourceQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
return $this->filteredProcurementQuery($filters)->select([
|
|
DB::raw("'purchase' AS source_type"),
|
|
DB::raw('1 AS source_rank'),
|
|
'h.Id AS source_id',
|
|
'i.Id AS source_item_id',
|
|
'h.io_date AS occurred_at',
|
|
'h.io_id AS stock_no',
|
|
'h.po_id AS purchase_no',
|
|
'h.supplier_name AS supplier_name',
|
|
'i.i_id AS sku_code',
|
|
DB::raw('TRIM(sku_id) AS product_code'),
|
|
'i.name AS sku_name',
|
|
'i.qty AS qty',
|
|
'i.cost_price AS cost_price',
|
|
'i.cost_amount AS cost_amount',
|
|
'h.remark AS head_remark',
|
|
'i.remark AS item_remark',
|
|
'h.warehouse AS warehouse_name',
|
|
'h.logistics_company AS express_name',
|
|
DB::raw("'' AS express_no"),
|
|
'h.status AS source_status',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function shippingSourceQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
return $this->filteredShippingQuery($filters)->select([
|
|
DB::raw("'shipping' AS source_type"),
|
|
DB::raw('2 AS source_rank'),
|
|
's.id AS source_id',
|
|
DB::raw('COALESCE(sku_source_id, 0) AS source_item_id'),
|
|
's.ship_time AS occurred_at',
|
|
DB::raw("'' AS stock_no"),
|
|
DB::raw("'' AS purchase_no"),
|
|
's.supplier_name AS supplier_name',
|
|
's.product_code AS sku_code',
|
|
DB::raw('TRIM(barcode) AS product_code'),
|
|
's.product_name AS sku_name',
|
|
's.qty AS qty',
|
|
DB::raw('NULL AS cost_price'),
|
|
DB::raw('NULL AS cost_amount'),
|
|
's.seller_memo AS head_remark',
|
|
DB::raw("'' AS item_remark"),
|
|
's.warehouse_name AS warehouse_name',
|
|
DB::raw("COALESCE(NULLIF(express_name1, ''), express_name2) AS express_name"),
|
|
's.express_no AS express_no',
|
|
DB::raw('NULL AS source_status'),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function filteredProcurementQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
[$from, $to, $keyword] = $this->sourceFilterValues($filters);
|
|
|
|
$query = $this->connection->table(self::HEAD_TABLE . ' as h')
|
|
->join(self::ITEM_TABLE . ' as i', 'i.io_id', '=', 'h.io_id')
|
|
->where('h.io_date', '>=', $from)
|
|
->whereRaw("TRIM(COALESCE(warehouse, '')) <> ?", ['配件单仓'])
|
|
->whereRaw("NULLIF(TRIM(CAST(po_id AS CHAR)), '') IS NOT NULL")
|
|
->whereRaw("TRIM(COALESCE(supplier_name, '')) NOT IN (?, ?)", ['虚拟', '简尚送货'])
|
|
->whereRaw("TRIM(COALESCE(sku_id, '')) NOT LIKE ?", ['DF-%']);
|
|
|
|
if ($to !== null) {
|
|
$query->where('h.io_date', '<=', $to);
|
|
}
|
|
|
|
if ($keyword !== '') {
|
|
$like = '%' . $keyword . '%';
|
|
$query->where(static function ($nested) use ($like): void {
|
|
foreach ([
|
|
'h.io_id',
|
|
'h.po_id',
|
|
'h.supplier_name',
|
|
'h.warehouse',
|
|
'i.sku_id',
|
|
'i.i_id',
|
|
'i.name',
|
|
] as $column) {
|
|
$nested->orWhere($column, 'like', $like);
|
|
}
|
|
});
|
|
}
|
|
|
|
return $query;
|
|
}
|
|
|
|
/**
|
|
* 只取仓库名称含“代发仓”的发货明细,并剔除条形码以 DF- 开头的记录。
|
|
*
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
*/
|
|
private function filteredShippingQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
[$from, $to, $keyword] = $this->sourceFilterValues($filters);
|
|
$query = $this->connection->table(self::SHIPPING_TABLE . ' as s')
|
|
->where('s.ship_time', '>=', $from)
|
|
->where('s.warehouse_name', 'like', '%代发仓%')
|
|
->whereRaw("TRIM(COALESCE(barcode, '')) NOT LIKE ?", ['DF-%']);
|
|
|
|
if ($to !== null) {
|
|
$query->where('s.ship_time', '<=', $to);
|
|
}
|
|
|
|
if ($keyword !== '') {
|
|
$like = '%' . $keyword . '%';
|
|
$query->where(static function ($nested) use ($like): void {
|
|
foreach ([
|
|
's.supplier_name',
|
|
's.warehouse_name',
|
|
's.barcode',
|
|
's.product_code',
|
|
's.product_name',
|
|
's.express_no',
|
|
's.express_name1',
|
|
's.trade_no',
|
|
's.package_no',
|
|
's.seller_memo',
|
|
] as $column) {
|
|
$nested->orWhere($column, 'like', $like);
|
|
}
|
|
});
|
|
}
|
|
|
|
return $query;
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
* @return array{0:string,1:?string,2:string}
|
|
*/
|
|
private function sourceFilterValues(array $filters): array
|
|
{
|
|
$from = Carbon::parse($filters['date_from'] ?: self::DEFAULT_FROM_TIME);
|
|
$to = trim((string) ($filters['date_to'] ?? ''));
|
|
$keyword = trim((string) ($filters['keyword'] ?? ''));
|
|
|
|
if ($to !== '') {
|
|
$toDate = Carbon::parse($to);
|
|
if (preg_match('/^\d{4}-\d{2}-\d{2}$/D', $to) === 1) {
|
|
$toDate->endOfDay();
|
|
}
|
|
$to = $toDate->format('Y-m-d H:i:s');
|
|
}
|
|
|
|
return [$from->format('Y-m-d H:i:s'), $to !== '' ? $to : null, $keyword];
|
|
}
|
|
|
|
/**
|
|
* 变价历史优先;从未变价的条码回退当前已生效定价。
|
|
*
|
|
* @param list<string> $skuIds
|
|
*/
|
|
private function latestEffectivePrices(array $skuIds): Collection
|
|
{
|
|
if ($skuIds === []) {
|
|
return collect();
|
|
}
|
|
|
|
$changes = $this->connection->table(self::PRICE_TABLE)
|
|
->whereIn('skucode', $skuIds)
|
|
->whereRaw("TRIM(COALESCE(priceType, '')) = ?", ['1'])
|
|
->whereNotNull('afterPrice')
|
|
->orderByDesc('effectStartTime')
|
|
->orderByDesc('Id')
|
|
->get(['skucode', 'afterPrice', 'effectStartTime', 'Id'])
|
|
->unique(fn (object $price): string => $this->normalizeSku($price->skucode))
|
|
->map(static function (object $price): object {
|
|
$price->price = (float) $price->afterPrice;
|
|
$price->priceSource = 'change';
|
|
|
|
return $price;
|
|
})
|
|
->keyBy(fn (object $price): string => $this->normalizeSku($price->skucode));
|
|
|
|
$missingSkuIds = array_values(array_filter(
|
|
array_map(fn (mixed $skuId): string => trim((string) $skuId), $skuIds),
|
|
fn (string $skuId): bool => $skuId !== '' && ! $changes->has($this->normalizeSku($skuId)),
|
|
));
|
|
|
|
return $changes->union($this->latestCurrentPrices($missingSkuIds));
|
|
}
|
|
|
|
/** @param list<string> $skuIds */
|
|
private function latestCurrentPrices(array $skuIds): Collection
|
|
{
|
|
if ($skuIds === [] || ! $this->currentPriceTableAvailable()) {
|
|
return collect();
|
|
}
|
|
|
|
$now = now();
|
|
|
|
return $this->connection->table(self::CURRENT_PRICE_TABLE)
|
|
->whereIn('skuCode', $skuIds)
|
|
->whereNotNull('purchasePrice')
|
|
->where(static function ($query) use ($now): void {
|
|
$query->whereNull('effectTime')->orWhere('effectTime', '<=', $now);
|
|
})
|
|
->orderBy('skuCode')
|
|
->orderByDesc('effectTime')
|
|
->orderByDesc('Id')
|
|
->get(['Id', 'skuCode', 'purchasePrice', 'effectTime'])
|
|
->unique(fn (object $price): string => $this->normalizeSku($price->skuCode))
|
|
->map(static fn (object $price): object => (object) [
|
|
'skucode' => $price->skuCode,
|
|
'price' => (float) $price->purchasePrice,
|
|
'effectStartTime' => $price->effectTime,
|
|
'priceSource' => 'pricing',
|
|
])
|
|
->keyBy(fn (object $price): string => $this->normalizeSku($price->skucode));
|
|
}
|
|
|
|
/**
|
|
* 聚水潭普通商品资料成本价:同编码取最新一条,空或 0 视为缺失。
|
|
*
|
|
* @param list<string> $skuIds
|
|
*/
|
|
private function latestCatalogCosts(array $skuIds): Collection
|
|
{
|
|
if ($skuIds === [] || ! $this->productTableAvailable()) {
|
|
return collect();
|
|
}
|
|
|
|
return $this->connection->table(self::PRODUCT_TABLE)
|
|
->whereIn('sku_id', $skuIds)
|
|
->where('sku_type', 'normal')
|
|
->where('cost_price', '>', 0)
|
|
->orderByDesc('autoid')
|
|
->get(['sku_id', 'cost_price', 'autoid'])
|
|
->unique(fn (object $product): string => $this->normalizeSku($product->sku_id))
|
|
->map(static fn (object $product): object => (object) [
|
|
'skucode' => $product->sku_id,
|
|
'price' => (float) $product->cost_price,
|
|
'effectStartTime' => null,
|
|
'priceSource' => 'catalog',
|
|
])
|
|
->keyBy(fn (object $price): string => $this->normalizeSku($price->skucode));
|
|
}
|
|
|
|
private function catalogCostsForRows(Collection $rows, Collection $priceMap): Collection
|
|
{
|
|
$skuIds = $rows
|
|
->filter(function (object $row) use ($priceMap): bool {
|
|
$productCode = trim((string) ($row->product_code ?? ''));
|
|
if ($productCode === '' || $priceMap->has($this->normalizeSku($productCode))) {
|
|
return false;
|
|
}
|
|
|
|
$costPrice = $row->cost_price ?? null;
|
|
$costAmount = $row->cost_amount ?? null;
|
|
|
|
return ($costPrice === null || (float) $costPrice <= 0)
|
|
&& ($costAmount === null || (float) $costAmount <= 0);
|
|
})
|
|
->pluck('product_code')
|
|
->map(static fn (mixed $value): string => trim((string) $value))
|
|
->filter()
|
|
->unique()
|
|
->values()
|
|
->all();
|
|
|
|
return $this->latestCatalogCosts($skuIds);
|
|
}
|
|
|
|
private function currentPriceTableAvailable(): bool
|
|
{
|
|
if ($this->currentPriceTableAvailable === null) {
|
|
$this->currentPriceTableAvailable = Schema::connection($this->connectionName)
|
|
->hasTable(self::CURRENT_PRICE_TABLE);
|
|
}
|
|
|
|
return $this->currentPriceTableAvailable;
|
|
}
|
|
|
|
private function productTableAvailable(): bool
|
|
{
|
|
if ($this->productTableAvailable === null) {
|
|
$this->productTableAvailable = Schema::connection($this->connectionName)
|
|
->hasTable(self::PRODUCT_TABLE);
|
|
}
|
|
|
|
return $this->productTableAvailable;
|
|
}
|
|
|
|
private function shippingTableAvailable(): bool
|
|
{
|
|
if ($this->shippingTableAvailable === null) {
|
|
$this->shippingTableAvailable = Schema::connection($this->connectionName)->hasTable(self::SHIPPING_TABLE);
|
|
}
|
|
|
|
return $this->shippingTableAvailable;
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function formatGoodsRow(object $row, ?object $price, ?object $catalogCost): array
|
|
{
|
|
$occurredAt = Carbon::parse((string) $row->occurred_at);
|
|
$month = $occurredAt->format('Y-m');
|
|
$quantity = (float) ($row->qty ?? 0);
|
|
$effectivePrice = $price?->price;
|
|
$unitPrice = $effectivePrice === null ? 0.0 : (float) $effectivePrice;
|
|
$amount = round($quantity * $unitPrice, 2);
|
|
$supplier = trim((string) ($row->supplier_name ?? ''));
|
|
$productCode = trim((string) ($row->product_code ?? ''));
|
|
$costPrice = null;
|
|
$costAmount = null;
|
|
$estimatePriceSource = null;
|
|
if ($price === null) {
|
|
$costPrice = $row->cost_price === null || (float) $row->cost_price <= 0
|
|
? null
|
|
: (float) $row->cost_price;
|
|
$costAmount = $row->cost_amount === null || (float) $row->cost_amount <= 0
|
|
? ($costPrice === null ? null : round($quantity * $costPrice, 2))
|
|
: (float) $row->cost_amount;
|
|
$estimatePriceSource = $costPrice === null && $costAmount === null ? null : 'receipt';
|
|
if ($costPrice === null && $costAmount === null && $catalogCost !== null) {
|
|
$costPrice = (float) $catalogCost->price;
|
|
$costAmount = round($quantity * $costPrice, 2);
|
|
$estimatePriceSource = 'catalog';
|
|
}
|
|
}
|
|
$remark = trim(implode(' ', array_filter([
|
|
trim((string) ($row->head_remark ?? '')),
|
|
trim((string) ($row->item_remark ?? '')),
|
|
])));
|
|
|
|
return [
|
|
'sourceType' => (string) $row->source_type,
|
|
'receivingId' => $row->source_type === 'purchase' ? (int) $row->source_id : null,
|
|
'itemId' => $row->source_type === 'purchase' ? (int) $row->source_item_id : null,
|
|
'shippingId' => $row->source_type === 'shipping' ? (int) $row->source_id : null,
|
|
'summary_month' => $month,
|
|
'month' => $month,
|
|
'stockNo' => trim((string) ($row->stock_no ?? '')),
|
|
'purchaseNo' => trim((string) ($row->purchase_no ?? '')),
|
|
'date' => $occurredAt->format('Y-m-d H:i:s'),
|
|
'supplier' => $supplier,
|
|
'skuCode' => trim((string) ($row->sku_code ?? '')),
|
|
'productCode' => $productCode,
|
|
'skuName' => trim((string) ($row->sku_name ?? '')),
|
|
'qty' => $quantity,
|
|
'unitPrice' => $unitPrice,
|
|
'amount' => $amount,
|
|
'guessUnitPrice' => $costPrice,
|
|
'guessAmount' => $costAmount,
|
|
'estimatePriceSource' => $estimatePriceSource,
|
|
'supplierGoodsCode' => $supplier.$productCode,
|
|
'remark' => $remark,
|
|
'warehouse' => trim((string) ($row->warehouse_name ?? '')),
|
|
'expressName' => trim((string) ($row->express_name ?? '')),
|
|
'expressNo' => trim((string) ($row->express_no ?? '')),
|
|
'unsent' => '',
|
|
'reconciler' => '',
|
|
'priceMatched' => $effectivePrice !== null,
|
|
'priceSource' => $price?->priceSource,
|
|
'priceEffectTime' => $price?->effectStartTime,
|
|
'sourceStatus' => $row->source_status,
|
|
];
|
|
}
|
|
|
|
private function normalizeSku(mixed $value): string
|
|
{
|
|
return mb_strtolower(trim((string) $value), 'UTF-8');
|
|
}
|
|
}
|