接入聚水潭采购入库明细、固定剔除规则和工作平台最新变价后采购价。 Co-authored-by: 苏木 <594326199@qq.com> Co-committed-by: 苏木 <594326199@qq.com>
275 lines
10 KiB
PHP
275 lines
10 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\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 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 DEFAULT_FROM = '2026-10-01';
|
|
|
|
private readonly ConnectionInterface $connection;
|
|
|
|
private readonly string $connectionName;
|
|
|
|
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>
|
|
* }
|
|
*/
|
|
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' => [],
|
|
];
|
|
}
|
|
}
|
|
|
|
$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,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @param array{date_from:string,date_to:string,keyword:string} $filters
|
|
* @return array{
|
|
* total:int,
|
|
* quantity: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->filteredGoodsQuery($filters);
|
|
$total = (clone $query)->count();
|
|
$aggregate = (clone $query)
|
|
->selectRaw('COALESCE(SUM(qty), 0) AS quantity, COUNT(DISTINCT supplier_name) AS supplier_count')
|
|
->first();
|
|
|
|
$perPage = min(max($perPage, 1), 100);
|
|
$page = max($page, 1);
|
|
$sourceRows = (clone $query)
|
|
->orderByDesc('h.io_date')
|
|
->orderByDesc('h.Id')
|
|
->orderByDesc('i.Id')
|
|
->forPage($page, $perPage)
|
|
->get([
|
|
'h.Id as receiving_id',
|
|
'h.io_id',
|
|
'h.po_id',
|
|
'h.io_date',
|
|
'h.remark as head_remark',
|
|
'h.warehouse',
|
|
'h.logistics_company',
|
|
'h.status',
|
|
'i.Id as item_id',
|
|
'i.sku_id',
|
|
'i.i_id',
|
|
'i.name',
|
|
'i.qty',
|
|
'i.cost_price',
|
|
'i.cost_amount',
|
|
'i.remark as item_remark',
|
|
]);
|
|
|
|
$priceMap = $this->latestChangePrices(
|
|
$sourceRows->pluck('sku_id')->filter()->map(static fn (mixed $value): string => trim((string) $value))->unique()->values()->all()
|
|
);
|
|
|
|
$rows = $sourceRows->map(
|
|
fn (object $row): array => $this->formatGoodsRow($row, $priceMap->get($this->normalizeSku($row->sku_id)))
|
|
)->values()->all();
|
|
|
|
return [
|
|
'total' => $total,
|
|
'quantity' => (float) ($aggregate->quantity ?? 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 filteredGoodsQuery(array $filters): \Illuminate\Database\Query\Builder
|
|
{
|
|
$from = Carbon::parse($filters['date_from'] ?: self::DEFAULT_FROM)->startOfDay();
|
|
$to = trim((string) ($filters['date_to'] ?? ''));
|
|
$keyword = trim((string) ($filters['keyword'] ?? ''));
|
|
|
|
$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->format('Y-m-d H:i:s'))
|
|
->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 !== '') {
|
|
$query->where('h.io_date', '<', Carbon::parse($to)->addDay()->startOfDay()->format('Y-m-d H:i:s'));
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/** @param list<string> $skuIds */
|
|
private function latestChangePrices(array $skuIds): Collection
|
|
{
|
|
if ($skuIds === []) {
|
|
return collect();
|
|
}
|
|
|
|
return $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))
|
|
->keyBy(fn (object $price): string => $this->normalizeSku($price->skucode));
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
private function formatGoodsRow(object $row, ?object $price): array
|
|
{
|
|
$occurredAt = Carbon::parse((string) $row->io_date);
|
|
$quantity = (float) ($row->qty ?? 0);
|
|
$afterPrice = $price?->afterPrice;
|
|
$unitPrice = $afterPrice === null ? 0.0 : (float) $afterPrice;
|
|
$amount = round($quantity * $unitPrice, 2);
|
|
$costPrice = $row->cost_price === null ? null : (float) $row->cost_price;
|
|
$costAmount = $row->cost_amount === null
|
|
? ($costPrice === null ? null : round($quantity * $costPrice, 2))
|
|
: (float) $row->cost_amount;
|
|
$remark = trim(implode(' ', array_filter([
|
|
trim((string) ($row->head_remark ?? '')),
|
|
trim((string) ($row->item_remark ?? '')),
|
|
])));
|
|
|
|
return [
|
|
'receivingId' => (int) $row->receiving_id,
|
|
'itemId' => (int) $row->item_id,
|
|
'month' => $occurredAt->format('Y-m'),
|
|
'stockNo' => (string) ($row->io_id ?? ''),
|
|
'purchaseNo' => (string) ($row->po_id ?? ''),
|
|
'date' => $occurredAt->format('Y-m-d'),
|
|
'supplier' => (string) ($row->supplier_name ?? ''),
|
|
'skuCode' => (string) ($row->i_id ?? ''),
|
|
'productCode' => (string) ($row->sku_id ?? ''),
|
|
'skuName' => (string) ($row->name ?? ''),
|
|
'qty' => $quantity,
|
|
'unitPrice' => $unitPrice,
|
|
'amount' => $amount,
|
|
'guessUnitPrice' => $costPrice,
|
|
'guessAmount' => $costAmount,
|
|
'supplierGoodsCode' => '',
|
|
'remark' => $remark,
|
|
'warehouse' => (string) ($row->warehouse ?? ''),
|
|
'expressName' => (string) ($row->logistics_company ?? ''),
|
|
'expressNo' => '',
|
|
'unsent' => '',
|
|
'reconciler' => '',
|
|
'priceMatched' => $afterPrice !== null,
|
|
'priceEffectTime' => $price?->effectStartTime,
|
|
'sourceStatus' => $row->status,
|
|
];
|
|
}
|
|
|
|
private function normalizeSku(mixed $value): string
|
|
{
|
|
return mb_strtolower(trim((string) $value), 'UTF-8');
|
|
}
|
|
}
|