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, * shipping_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), ]; } } $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(), ]; } /** * @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>, * page:int, * per_page:int * } */ public function goodsDetails(array $filters, int $page, int $perPage = 20): array { $query = $this->goodsSourceRows($filters); $aggregate = $this->goodsSummary($query); $perPage = min(max($perPage, 1), 100); $page = max($page, 1); $sourceRows = (clone $query) ->orderByDesc('occurred_at') ->orderByDesc('source_rank') ->orderByDesc('source_id') ->orderByDesc('source_item_id') ->forPage($page, $perPage) ->get(); $priceMap = $this->latestChangePrices( $sourceRows->pluck('product_code')->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->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, ]; } private function goodsSummary(\Illuminate\Database\Query\Builder $query): ?object { $summaryLines = (clone $query) ->leftJoinSub( $this->latestPriceRows(), 'latest_price', static fn ($join) => $join->on('latest_price.skucode', '=', 'forecast_rows.product_code'), ) ->select([ 'forecast_rows.supplier_name as supplier_name', 'forecast_rows.qty as qty', 'forecast_rows.cost_price as cost_price', 'forecast_rows.cost_amount as cost_amount', 'forecast_rows.source_type as source_type', ]) ->addSelect('latest_price.afterPrice as latest_price'); return $this->connection ->query() ->fromSub($summaryLines, 'summary_lines') ->selectRaw( 'COUNT(*) AS row_count,' . ' COUNT(DISTINCT supplier_name) AS supplier_count,' . ' COALESCE(SUM(qty), 0) AS quantity,' . ' COALESCE(SUM(CASE WHEN latest_price IS NULL THEN 0' . ' ELSE ROUND(qty * latest_price, 2) END), 0) AS amount,' . ' COALESCE(SUM(CASE' . ' WHEN cost_amount IS NOT NULL THEN ROUND(cost_amount * 0.8, 2)' . ' WHEN cost_price IS NOT NULL THEN ROUND(qty * cost_price * 0.8, 2)' . ' ELSE 0 END), 0) AS estimated_amount_after_discount', ) ->first(); } /** * 流式读取当前筛选全集,按小批次匹配变价,避免导出把整表装入内存。 * * @param array{date_from:string,date_to:string,keyword:string} $filters * @return \Generator> */ 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->latestChangePrices( $sourceRows->pluck('product_code') ->filter() ->map(static fn (mixed $value): string => trim((string) $value)) ->unique() ->values() ->all() ); foreach ($sourceRows as $row) { yield $this->formatGoodsRow( $row, $priceMap->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 goodsUnionQuery(array $filters): \Illuminate\Database\Query\Builder { $purchase = $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', ]); if (! $this->shippingTableAvailable()) { return $purchase; } $shipping = $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'), ]); return $purchase->unionAll($shipping); } /** * @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 $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)); } private function latestPriceRows(): \Illuminate\Database\Query\Builder { $rankedPrices = $this->connection->table(self::PRICE_TABLE) ->whereRaw("TRIM(COALESCE(priceType, '')) = ?", ['1']) ->whereNotNull('afterPrice') ->selectRaw( 'TRIM(skucode) AS skucode, afterPrice,' . ' ROW_NUMBER() OVER (' . 'PARTITION BY TRIM(skucode) ORDER BY effectStartTime DESC, Id DESC' . ') AS price_rank', ); return $this->connection ->query() ->fromSub($rankedPrices, 'ranked_prices') ->select(['skucode', 'afterPrice']) ->where('price_rank', 1); } private function shippingTableAvailable(): bool { if ($this->shippingTableAvailable === null) { $this->shippingTableAvailable = Schema::connection($this->connectionName)->hasTable(self::SHIPPING_TABLE); } return $this->shippingTableAvailable; } /** @return array */ private function formatGoodsRow(object $row, ?object $price): array { $occurredAt = Carbon::parse((string) $row->occurred_at); $month = $occurredAt->format('Y-m'); $quantity = (float) ($row->qty ?? 0); $afterPrice = $price?->afterPrice; $unitPrice = $afterPrice === null ? 0.0 : (float) $afterPrice; $amount = round($quantity * $unitPrice, 2); $supplier = trim((string) ($row->supplier_name ?? '')); $productCode = trim((string) ($row->product_code ?? '')); $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 [ '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, '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' => $afterPrice !== null, 'priceEffectTime' => $price?->effectStartTime, 'sourceStatus' => $row->source_status, ]; } private function normalizeSku(mixed $value): string { return mb_strtolower(trim((string) $value), 'UTF-8'); } }