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 * } */ 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, * 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->filteredGoodsQuery($filters); $aggregate = $this->goodsSummary($query); $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(self::GOODS_SOURCE_COLUMNS); $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' => (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 { $tablePrefix = $this->connection->getTablePrefix(); $priceTable = $tablePrefix . self::PRICE_TABLE; $itemAlias = $tablePrefix . 'i'; $summaryLines = (clone $query) ->select([ 'h.supplier_name as supplier_name', 'i.qty as qty', 'i.cost_price as cost_price', 'i.cost_amount as cost_amount', ]) ->selectRaw( '(SELECT latest_price.afterPrice' . ' FROM ' . $priceTable . ' AS latest_price' . ' WHERE latest_price.skucode = ' . $itemAlias . '.sku_id' . " AND TRIM(COALESCE(latest_price.priceType, '')) = ?" . ' AND latest_price.afterPrice IS NOT NULL' . ' ORDER BY latest_price.effectStartTime DESC, latest_price.Id DESC' . ' LIMIT 1) AS latest_price', ['1'], ); 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); $query = $this->filteredGoodsQuery($filters); $page = 1; do { $sourceRows = (clone $query) ->orderByDesc('h.io_date') ->orderByDesc('h.Id') ->orderByDesc('i.Id') ->forPage($page, $batchSize) ->get(self::GOODS_SOURCE_COLUMNS); $priceMap = $this->latestChangePrices( $sourceRows->pluck('sku_id') ->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->sku_id)), ); } $page++; } while ($sourceRows->count() === $batchSize); } /** * @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_TIME); $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 !== '') { $toDate = Carbon::parse($to); if (preg_match('/^\d{4}-\d{2}-\d{2}$/D', $to) === 1) { $toDate->endOfDay(); } $query->where('h.io_date', '<=', $toDate->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 $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 */ 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 H:i:s'), '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'); } }