From 9b320095cee1f2e65088b0fc25134777a448d880 Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Tue, 10 Nov 2026 14:17:13 +0800 Subject: [PATCH 01/12] =?UTF-8?q?revert:=20=E6=81=A2=E5=A4=8D=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=8C=96=E5=BE=85=E5=8A=9E=E8=87=B3=202026-11-09=20?= =?UTF-8?q?=E7=8A=B6=E6=80=81=20(#1040)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Models/Business/SystemizationTodo.php | 1 - tests/Feature/Business/SystemizationTodosTest.php | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/app/Models/Business/SystemizationTodo.php b/app/Models/Business/SystemizationTodo.php index d521b3df..c53a1ce8 100644 --- a/app/Models/Business/SystemizationTodo.php +++ b/app/Models/Business/SystemizationTodo.php @@ -142,7 +142,6 @@ class SystemizationTodo extends Model if ($this->isCompleted()) { return ['label' => '—', 'tone' => 'muted']; } - // Freeze the first scheduled date so later completion-date option changes do not move overdue status. $reminderDate = $this->reminder_date ?: $this->due_date; if ($reminderDate === null) { return ['label' => '时间待定', 'tone' => 'muted']; diff --git a/tests/Feature/Business/SystemizationTodosTest.php b/tests/Feature/Business/SystemizationTodosTest.php index ba35e861..987887c3 100644 --- a/tests/Feature/Business/SystemizationTodosTest.php +++ b/tests/Feature/Business/SystemizationTodosTest.php @@ -1519,7 +1519,7 @@ class SystemizationTodosTest extends FeatureTestCase } } - public function test_reminder_remains_on_first_saved_completion_date_when_option_changes(): void + public function test_reminder_keeps_the_first_saved_completion_date(): void { Carbon::setTestNow('2026-10-26 12:00:00'); try { From 906b9ea1978f91644ad0de39ed3454b98ff2b547 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 14:17:34 +0800 Subject: [PATCH 02/12] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=9C=9F?= =?UTF-8?q?=E6=9C=AB=E4=BD=99=E9=A2=9D=E5=BA=97=E9=93=BA=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E6=98=8E=E7=BB=86=20(#1041)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StoreReceivingBalanceOverview.php | 15 + .../DouyinAuthoritativeBillRepository.php | 103 +++ .../StoreReceivingBalanceOverviewService.php | 710 +++++++++++++++++- .../StoreReceivingBalanceOverview.vue | 92 ++- routes/admin.php | 2 + ...reReceivingBalanceOverviewEndpointTest.php | 43 ++ ...oreReceivingBalanceOverviewServiceTest.php | 79 ++ .../StoreReceivingBalanceOverviewTest.php | 5 + 8 files changed, 1037 insertions(+), 12 deletions(-) diff --git a/modules/EcommerceFinance/Http/Controllers/StoreReceivingBalanceOverview.php b/modules/EcommerceFinance/Http/Controllers/StoreReceivingBalanceOverview.php index 621b76af..915c95f3 100644 --- a/modules/EcommerceFinance/Http/Controllers/StoreReceivingBalanceOverview.php +++ b/modules/EcommerceFinance/Http/Controllers/StoreReceivingBalanceOverview.php @@ -85,6 +85,21 @@ class StoreReceivingBalanceOverview extends Controller } } + public function balanceStoreDetail(Request $request, StoreReceivingBalanceOverviewService $service) + { + $this->authorizeStoreReceivingBills(); + + try { + return response()->json($service->balanceStoreDetail(...$this->requestedPeriod($request))); + } catch (Throwable $exception) { + report($exception); + + return response()->json([ + 'message' => '店铺期末余额明细暂时无法读取,请稍后重试。', + ], 503); + } + } + /** @return array{0:string,1?:string} */ private function requestedPeriod(Request $request): array { diff --git a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php index f41d8ddf..3c90a402 100644 --- a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php +++ b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php @@ -98,6 +98,109 @@ class DouyinAuthoritativeBillRepository ]; } + /** + * @return array + */ + public function storeBalances(array $filters): array + { + $start = $this->monthStart($filters['start'] ?? null); + if ($start === null) { + return []; + } + + $activity = []; + $displayNames = []; + foreach ($this->query($filters, true) + ->select('store_name') + ->selectRaw( + 'COALESCE(SUM(income), 0) AS income_total, ' + . 'COALESCE(SUM(expense), 0) AS expense_total', + ) + ->groupBy('store_name') + ->get() as $row) { + $storeName = trim((string) $row->store_name); + $storeName = $storeName !== '' ? $storeName : '未标注店铺'; + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + $displayNames[$normalized] = $storeName; + $activity[$normalized] = [ + 'income' => round((float) ($activity[$normalized]['income'] ?? 0) + (float) $row->income_total, 2), + 'expense' => round((float) ($activity[$normalized]['expense'] ?? 0) + (float) $row->expense_total, 2), + ]; + } + + $base = []; + $db = $this->db(); + if ($db->getSchemaBuilder()->hasTable(DouyinOpeningBalanceImporter::TABLE)) { + foreach ($db->table(DouyinOpeningBalanceImporter::TABLE) + ->where('period_end', '2026-06-30') + ->select(['store_name', 'normalized_store_name']) + ->selectRaw('COALESCE(SUM(balance), 0) AS balance') + ->groupBy('store_name', 'normalized_store_name') + ->get() as $row) { + $base[(string) $row->normalized_store_name] = [ + 'store_name' => trim((string) $row->store_name), + 'balance' => round((float) $row->balance, 2), + ]; + } + } + foreach (self::MERCHANT_BACKOFFICE_JUNE_ENDING_BALANCES as $storeName => $opening) { + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + $base[$normalized] ??= [ + 'store_name' => $storeName, + 'balance' => round((float) $opening['balance'], 2), + ]; + } + + $movement = []; + $baselineMonth = CarbonImmutable::create(2026, 7, 1)->startOfDay(); + if ($start->gt($baselineMonth)) { + foreach ($this->query([ + 'start' => $baselineMonth->format('Y-m-d'), + 'end' => $start->subDay()->format('Y-m-d'), + ], true) + ->select('store_name') + ->selectRaw( + 'COALESCE(SUM(income), 0) AS income_total, ' + . 'COALESCE(SUM(expense), 0) AS expense_total', + ) + ->groupBy('store_name') + ->get() as $row) { + $normalized = JushuitanShopBalanceRepository::normalizeStoreName((string) $row->store_name); + $movement[$normalized] = [ + 'income' => (float) $row->income_total, + 'expense' => (float) $row->expense_total, + ]; + } + } + + $normalizedStores = array_values(array_unique(array_merge( + array_keys($base), + array_keys($movement), + array_keys($activity), + ))); + $rows = []; + foreach ($normalizedStores as $normalized) { + $storeName = $displayNames[$normalized] + ?? ($base[$normalized]['store_name'] ?? '未标注店铺'); + $opening = array_key_exists($normalized, $base) + ? round( + (float) $base[$normalized]['balance'] + + (float) ($movement[$normalized]['income'] ?? 0) + - (float) ($movement[$normalized]['expense'] ?? 0), + 2, + ) + : null; + $rows[] = [ + 'store_name' => $storeName, + 'opening_balance' => $opening, + 'income' => round((float) ($activity[$normalized]['income'] ?? 0), 2), + 'expense' => round((float) ($activity[$normalized]['expense'] ?? 0), 2), + ]; + } + + return $rows; + } + private function query(array $filters, bool $withOptions = false): Builder { $dataset = $this->datasets->get(StoreReceivingAlipayBillMirrorRepository::DATASET); diff --git a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php index 9897e0a2..65c3ac6a 100644 --- a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php +++ b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php @@ -3,6 +3,10 @@ namespace Modules\EcommerceFinance\Services; use Carbon\CarbonImmutable; +use Illuminate\Database\ConnectionInterface; +use Illuminate\Database\DatabaseManager; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; +use Illuminate\Database\Query\Builder; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Modules\EcommerceFinance\Http\Controllers\AccountBills; @@ -10,17 +14,38 @@ use Modules\EcommerceFinance\Http\Controllers\AlipayBills; use Modules\EcommerceFinance\Http\Controllers\PinduoduoAccountBills; use Modules\EcommerceFinance\Http\Controllers\TaobaoWechatAccountBills; use Modules\EcommerceFinance\Models\AccountBill; +use Modules\EcommerceFinance\Repositories\DouyinAuthoritativeBillRepository; +use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository; use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository; use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository; use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository; +use Modules\EcommerceFinance\Repositories\VipshopJxOpeningBalanceRepository; use RuntimeException; use Throwable; class StoreReceivingBalanceOverviewService { + private const TAOBAO_ALIPAY_ROW_TABLE = 'taobao_alipay_bill_rows'; + + private const TAOBAO_WECHAT_ROW_TABLE = 'taobao_wechat_bill_rows'; + + private const TAOBAO_WECHAT_OPENING_TABLE = 'taobao_wechat_opening_balances'; + + private const PINDUODUO_ROW_TABLE = 'pdd_settlement_bill_rows'; + + private const PINDUODUO_SNAPSHOT_TABLE = 'pdd_platform_balance_snapshots'; + + private const JD_WALLET_PERIOD_TABLE = 'jd_wallet_bill_periods'; + + private const JD_WALLET_ROW_TABLE = 'jd_wallet_bill_rows'; + + private const VIPSHOP_MP_SNAPSHOT_TABLE = 'vipshop_mp_opening_balance_snapshots'; + + private const XIAOHONGSHU_BALANCE_START = '2026-10-01'; + /** @var array */ public const PLATFORMS = [ ['slug' => 'taobao-alipay', 'name' => '淘系支付宝账户'], @@ -301,7 +326,6 @@ class StoreReceivingBalanceOverviewService 'amount' => round((float) $platform['balance'], 2), ]; } - return [ 'month' => $overview['month'], 'period' => $overview['period'], @@ -315,6 +339,111 @@ class StoreReceivingBalanceOverviewService ]; } + /** + * 期末余额的店铺明细。 + * + * 每个店铺统一按「期初余额 + 收入 - 支出」计算;某一店铺缺少期初时 + * 返回 null,由页面显示为“—”,不把未知期初静默当成 0。 + * + * @return array + */ + public function balanceStoreDetail(string $periodStart, ?string $periodEnd = null): array + { + [$periodStart, $periodEnd, $periodMonth] = $this->periodForRange($periodStart, $periodEnd); + $details = []; + $platformCount = 0; + $storeCount = 0; + $readyStoreCount = 0; + $balance = 0.0; + + foreach (self::PLATFORMS as $index => $definition) { + try { + $rows = $this->fetchPlatformStoreBalances( + $definition['slug'], + $periodStart, + $periodEnd, + ); + if ($rows === []) { + continue; + } + $platformCount++; + } catch (Throwable $exception) { + throw new RuntimeException('店铺期末余额明细暂时无法读取,请稍后重试。', 0, $exception); + } + + $platformRows = []; + foreach ($rows as $row) { + $storeName = trim((string) ($row['store_name'] ?? '')); + $storeName = $storeName !== '' ? $storeName : '未标注店铺'; + $opening = is_numeric($row['opening_balance'] ?? null) + ? round((float) $row['opening_balance'], 2) + : null; + $income = round((float) ($row['income'] ?? 0), 2); + $expense = round((float) ($row['expense'] ?? 0), 2); + $amount = $opening === null + ? null + : round($opening + $income - $expense, 2); + + $storeCount++; + if ($amount !== null) { + $readyStoreCount++; + $balance += $amount; + } + $platformRows[] = [ + 'platform_slug' => $definition['slug'], + 'platform' => $definition['name'], + 'store_name' => $storeName, + 'bill_item' => '', + 'opening_balance' => $opening, + 'income' => $income, + 'expense' => $expense, + 'amount' => $amount, + 'available' => $amount !== null, + '_platform_order' => $index, + ]; + } + + usort($platformRows, static function (array $left, array $right): int { + return [ + $left['amount'] === null ? 1 : 0, + $left['amount'] === null ? 0 : -$left['amount'], + $left['store_name'], + ] <=> [ + $right['amount'] === null ? 1 : 0, + $right['amount'] === null ? 0 : -$right['amount'], + $right['store_name'], + ]; + }); + array_push($details, ...$platformRows); + } + + foreach ($details as &$detail) { + unset($detail['_platform_order']); + } + unset($detail); + + $complete = $platformCount === count(self::PLATFORMS) + && $storeCount > 0 + && $readyStoreCount === $storeCount; + + return [ + 'month' => $periodMonth, + 'period' => [ + 'start' => $periodStart, + 'end' => $periodEnd, + ], + 'summary' => [ + 'balance' => $complete ? round($balance, 2) : null, + 'platform_count' => count(self::PLATFORMS), + 'available_platform_count' => $platformCount, + 'store_count' => $storeCount, + 'ready_store_count' => $readyStoreCount, + 'complete' => $complete, + ], + 'details' => $details, + ]; + } + /** @return array */ private function flowDetail(string $periodStart, ?string $periodEnd, string $flow): array { @@ -465,6 +594,585 @@ class StoreReceivingBalanceOverviewService return $this->fetchPlatformRows($platform, $start, $end, 'expense'); } + /** + * @return array + */ + protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array + { + return match ($platform) { + 'taobao-alipay' => $this->taobaoAlipayStoreBalances($start, $end), + 'taobao-wechat' => $this->taobaoWechatStoreBalances($start, $end), + 'pinduoduo' => $this->pinduoduoStoreBalances($start, $end), + 'jd-wallet' => $this->jdWalletStoreBalances($start, $end), + 'douyin' => $this->douyinStoreBalances($start, $end), + 'vipshop' => $this->vipshopStoreBalances($start, $end), + 'vipshop-jx' => $this->vipshopJxStoreBalances($start, $end), + 'xiaohongshu' => $this->xiaohongshuStoreBalances($start, $end), + default => throw new RuntimeException('unsupported_balance_overview_platform'), + }; + } + + /** + * @return array + */ + private function taobaoAlipayStoreBalances(string $start, string $end): array + { + $connection = $this->mirrorConnection(); + $activity = $this->groupedActivity( + $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE) + ->where('occurred_at', '>=', $start . ' 00:00:00') + ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'), + ); + $cutoff = $start . ' 00:00:00'; + $periodEnd = $this->dayAfter($end) . ' 00:00:00'; + $ranked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE) + ->where('occurred_at', '<', $cutoff) + ->whereNotNull('alipay_account') + ->where('alipay_account', '<>', '') + ->select([ + 'store_name', + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY alipay_account ' . + 'ORDER BY occurred_at DESC, source_row_number DESC' . + ') AS row_rank', + ); + $latestRows = $connection->query() + ->fromSub($ranked, 'latest_store_balances') + ->where('row_rank', 1) + ->get(); + $opening = []; + + if ($latestRows->isNotEmpty()) { + foreach ($latestRows as $row) { + $storeName = $this->storeName($row->store_name); + $opening[$storeName] = round( + (float) ($opening[$storeName] ?? 0) + (float) $row->balance_amount, + 2, + ); + } + } else { + $firstRanked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE) + ->where('occurred_at', '>=', $cutoff) + ->where('occurred_at', '<', $periodEnd) + ->whereNotNull('alipay_account') + ->where('alipay_account', '<>', '') + ->select([ + 'store_name', + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY alipay_account ' . + 'ORDER BY occurred_at ASC, source_row_number ASC' . + ') AS row_rank', + ); + $firstRows = $connection->query() + ->fromSub($firstRanked, 'first_store_balances') + ->where('row_rank', 1) + ->get(); + foreach ($firstRows as $row) { + $storeName = $this->storeName($row->store_name); + $opening[$storeName] = round( + (float) ($opening[$storeName] ?? 0) + + (float) $row->balance_amount + - (float) $row->income_amount + + (float) $row->expense_amount, + 2, + ); + } + } + + return $this->mergeStoreBalances($opening, $activity); + } + + /** + * @return array + */ + private function taobaoWechatStoreBalances(string $start, string $end): array + { + $connection = $this->mirrorConnection(); + $activity = $this->groupedActivity( + $connection->table(self::TAOBAO_WECHAT_ROW_TABLE) + ->where('occurred_at', '>=', $start . ' 00:00:00') + ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'), + ); + $opening = []; + if ($connection->getSchemaBuilder()->hasTable(self::TAOBAO_WECHAT_OPENING_TABLE)) { + $baseline = $connection->table(self::TAOBAO_WECHAT_OPENING_TABLE) + ->where('balance_date', TaobaoWechatOpeningBalanceRepository::BASELINE_DATE) + ->select('store_name') + ->selectRaw('COALESCE(SUM(balance), 0) AS balance') + ->groupBy('store_name') + ->get(); + foreach ($baseline as $row) { + $opening[$this->storeName($row->store_name)] = round((float) $row->balance, 2); + } + + if (CarbonImmutable::parse($start)->gt(CarbonImmutable::parse('2026-07-01'))) { + $movement = $this->groupedActivity( + $connection->table(self::TAOBAO_WECHAT_ROW_TABLE) + ->where('occurred_at', '>=', '2026-07-01 00:00:00') + ->where('occurred_at', '<', $start . ' 00:00:00'), + ); + foreach ($opening as $storeName => $balance) { + $row = $movement[$storeName] ?? ['income' => 0.0, 'expense' => 0.0]; + $opening[$storeName] = round( + $balance + (float) $row['income'] - (float) $row['expense'], + 2, + ); + } + } + } + + return $this->mergeStoreBalances($opening, $activity); + } + + /** + * @return array + */ + private function pinduoduoStoreBalances(string $start, string $end): array + { + $connection = $this->mirrorConnection(); + $activity = $this->groupedActivity( + $connection->table(self::PINDUODUO_ROW_TABLE) + ->where('occurred_at', '>=', $start . ' 00:00:00') + ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'), + ); + if (! $connection->getSchemaBuilder()->hasTable(self::PINDUODUO_SNAPSHOT_TABLE)) { + return $this->mergeNormalizedStoreBalances([], [], $activity); + } + + $monthStart = CarbonImmutable::parse($start)->startOfMonth()->format('Y-m-d'); + $balanceDate = $connection->table(self::PINDUODUO_SNAPSHOT_TABLE) + ->where('period_end', '<', $monthStart) + ->orderBy('period_end') + ->value('period_end'); + if ($balanceDate === null) { + return $this->mergeNormalizedStoreBalances([], [], $activity); + } + + $base = []; + foreach ($connection->table(self::PINDUODUO_SNAPSHOT_TABLE) + ->where('period_end', $balanceDate) + ->select(['store_name', 'normalized_store_name']) + ->selectRaw('COALESCE(SUM(balance), 0) AS balance') + ->groupBy('store_name', 'normalized_store_name') + ->get() as $row) { + $normalized = (string) $row->normalized_store_name; + $base[$normalized] = [ + 'store_name' => $this->storeName($row->store_name), + 'balance' => round((float) $row->balance, 2), + ]; + } + + $movement = []; + foreach ($connection->table(self::PINDUODUO_ROW_TABLE) + ->where('occurred_at', '>=', $balanceDate . ' 00:00:00') + ->where('occurred_at', '<', $monthStart . ' 00:00:00') + ->select('store_name') + ->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense', + ) + ->groupBy('store_name') + ->get() as $row) { + $normalized = JushuitanShopBalanceRepository::normalizeStoreName((string) $row->store_name); + $movement[$normalized] = [ + 'income' => (float) $row->income, + 'expense' => (float) $row->expense, + ]; + } + + return $this->mergeNormalizedStoreBalances($base, $movement, $activity); + } + + /** + * @return array + */ + private function jdWalletStoreBalances(string $start, string $end): array + { + $connection = $this->mirrorConnection(); + $generations = $connection->table(self::JD_WALLET_PERIOD_TABLE) + ->pluck('active_generation') + ->filter() + ->map(static fn (mixed $value): string => (string) $value) + ->values() + ->all(); + if ($generations === []) { + throw new RuntimeException('jd_wallet_bill_mirror_not_ready'); + } + + $activity = $this->groupedActivity( + $connection->table(self::JD_WALLET_ROW_TABLE) + ->whereIn('generation', $generations) + ->where('occurred_at', '>=', $start . ' 00:00:00') + ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'), + 'income', + 'expense', + ); + $cutoff = $start . ' 00:00:00'; + $periodEnd = $this->dayAfter($end) . ' 00:00:00'; + $ranked = $connection->table(self::JD_WALLET_ROW_TABLE) + ->whereIn('generation', $generations) + ->whereNotNull('balance') + ->where('occurred_at', '<', $cutoff) + ->select([ + 'store_name', + 'account_name', + 'occurred_at', + 'income', + 'expense', + 'balance', + 'record_code', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY store_name, account_name ' . + 'ORDER BY occurred_at DESC, LENGTH(record_code) DESC, record_code DESC' . + ') AS row_rank', + ); + $latestRows = $connection->query() + ->fromSub($ranked, 'latest_jd_balances') + ->where('row_rank', 1) + ->get(); + $opening = []; + if ($latestRows->isNotEmpty()) { + foreach ($latestRows as $row) { + $storeName = $this->storeName($row->store_name); + $opening[$storeName] = round( + (float) ($opening[$storeName] ?? 0) + (float) $row->balance, + 2, + ); + } + } else { + $firstRanked = $connection->table(self::JD_WALLET_ROW_TABLE) + ->whereIn('generation', $generations) + ->whereNotNull('balance') + ->where('occurred_at', '>=', $cutoff) + ->where('occurred_at', '<', $periodEnd) + ->select([ + 'store_name', + 'account_name', + 'occurred_at', + 'income', + 'expense', + 'balance', + 'record_code', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY store_name, account_name ' . + 'ORDER BY occurred_at ASC, LENGTH(record_code) ASC, record_code ASC' . + ') AS row_rank', + ); + $firstRows = $connection->query() + ->fromSub($firstRanked, 'first_jd_balances') + ->where('row_rank', 1) + ->get(); + foreach ($firstRows as $row) { + $storeName = $this->storeName($row->store_name); + $opening[$storeName] = round( + (float) ($opening[$storeName] ?? 0) + + (float) $row->balance + - (float) $row->income + + (float) $row->expense, + 2, + ); + } + } + + return $this->mergeStoreBalances($opening, $activity); + } + + /** + * @return array + */ + private function douyinStoreBalances(string $start, string $end): array + { + $repository = app(DouyinAuthoritativeBillRepository::class); + if (! $repository->available()) { + throw new RuntimeException('douyin_authoritative_bills_not_ready'); + } + + return $repository->storeBalances([ + 'start' => $start, + 'end' => $end, + ]); + } + + /** + * @return array + */ + private function vipshopStoreBalances(string $start, string $end): array + { + $activity = $this->accountBillActivity('vipshop', $start, $end, true); + $connection = $this->mirrorConnection(); + $opening = []; + if ($connection->getSchemaBuilder()->hasTable(self::VIPSHOP_MP_SNAPSHOT_TABLE)) { + foreach ($connection->table(self::VIPSHOP_MP_SNAPSHOT_TABLE) + ->where('period_end', '2026-06-30') + ->select('store_name') + ->selectRaw('COALESCE(SUM(balance), 0) AS balance') + ->groupBy('store_name') + ->get() as $row) { + $opening[$this->storeName($row->store_name)] = round((float) $row->balance, 2); + } + } + + $monthStart = CarbonImmutable::parse($start)->startOfMonth(); + if ($opening !== [] && $monthStart->gt(CarbonImmutable::parse('2026-07-01'))) { + $movement = $this->accountBillActivity( + 'vipshop', + '2026-07-01', + $monthStart->subDay()->format('Y-m-d'), + true, + ); + foreach ($opening as $storeName => $balance) { + $row = $movement[$storeName] ?? ['income' => 0.0, 'expense' => 0.0]; + $opening[$storeName] = round( + $balance + (float) $row['income'] - (float) $row['expense'], + 2, + ); + } + } + + return $this->mergeStoreBalances($opening, $activity); + } + + /** + * @return array + */ + private function vipshopJxStoreBalances(string $start, string $end): array + { + $activity = $this->accountBillActivity('vipshop-jx', $start, $end, true); + $openingData = app(VipshopJxOpeningBalanceRepository::class)->openingBalance($start, $end); + $opening = $openingData['source'] === 'none' + ? null + : round((float) $openingData['balance'], 2); + $storeNames = array_keys($activity); + if ($storeNames === []) { + $storeNames = AccountBill::query() + ->where('company_id', company_id()) + ->where('bill_type', 'vipshop-jx') + ->whereNull('deleted_at') + ->whereNotNull('store_name') + ->where('store_name', '<>', '') + ->distinct() + ->orderBy('store_name') + ->pluck('store_name') + ->map(fn (mixed $value): string => $this->storeName($value)) + ->all(); + } + $openingMap = count($storeNames) === 1 && $opening !== null + ? [reset($storeNames) => $opening] + : []; + + return $this->mergeStoreBalances($openingMap, $activity); + } + + /** + * @return array + */ + private function xiaohongshuStoreBalances(string $start, string $end): array + { + $activity = $this->accountBillActivity('xiaohongshu', $start, $end, false); + $opening = []; + $monthStart = CarbonImmutable::parse($start)->startOfMonth(); + if ($monthStart->lte(CarbonImmutable::parse(self::XIAOHONGSHU_BALANCE_START))) { + foreach (array_keys($activity) as $storeName) { + $opening[$storeName] = 0.0; + } + } elseif ($monthStart->gt(CarbonImmutable::parse(self::XIAOHONGSHU_BALANCE_START))) { + $movement = $this->accountBillActivity( + 'xiaohongshu', + self::XIAOHONGSHU_BALANCE_START, + $monthStart->subDay()->format('Y-m-d'), + false, + ); + foreach ($movement as $storeName => $row) { + $opening[$storeName] = round( + (float) $row['income'] - (float) $row['expense'], + 2, + ); + } + } + + if ($opening === []) { + $storeNames = AccountBill::query() + ->where('company_id', company_id()) + ->where('bill_type', 'xiaohongshu') + ->whereNull('deleted_at') + ->whereNotNull('store_name') + ->where('store_name', '<>', '') + ->distinct() + ->pluck('store_name') + ->map(fn (mixed $value): string => $this->storeName($value)) + ->all(); + foreach ($storeNames as $storeName) { + $opening[$storeName] = 0.0; + } + } + + return $this->mergeStoreBalances($opening, $activity); + } + + /** + * @return array + */ + private function groupedActivity( + Builder|EloquentBuilder $query, + string $incomeColumn = 'income_amount', + string $expenseColumn = 'expense_amount', + ): array { + $activity = []; + foreach ($query + ->select('store_name') + ->selectRaw( + 'COALESCE(SUM(' . $incomeColumn . '), 0) AS income_total, ' + . 'COALESCE(SUM(' . $expenseColumn . '), 0) AS expense_total', + ) + ->groupBy('store_name') + ->get() as $row) { + $storeName = $this->storeName($row->store_name); + $activity[$storeName] = [ + 'income' => round((float) ($activity[$storeName]['income'] ?? 0) + (float) $row->income_total, 2), + 'expense' => round((float) ($activity[$storeName]['expense'] ?? 0) + (float) $row->expense_total, 2), + ]; + } + + return $activity; + } + + /** + * @param array $opening + * @param array $activity + * @return array + */ + private function mergeStoreBalances(array $opening, array $activity): array + { + $storeNames = array_values(array_unique(array_merge(array_keys($opening), array_keys($activity)))); + $rows = []; + foreach ($storeNames as $storeName) { + $rows[] = [ + 'store_name' => $storeName, + 'opening_balance' => array_key_exists($storeName, $opening) + ? round((float) $opening[$storeName], 2) + : null, + 'income' => round((float) ($activity[$storeName]['income'] ?? 0), 2), + 'expense' => round((float) ($activity[$storeName]['expense'] ?? 0), 2), + ]; + } + + return $rows; + } + + /** + * @param array $base + * @param array $movement + * @param array $activity + * @return array + */ + private function mergeNormalizedStoreBalances(array $base, array $movement, array $activity): array + { + $normalizedActivity = []; + $displayNames = []; + foreach ($activity as $storeName => $row) { + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + $displayNames[$normalized] = $storeName; + $normalizedActivity[$normalized]['income'] = round( + (float) ($normalizedActivity[$normalized]['income'] ?? 0) + (float) $row['income'], + 2, + ); + $normalizedActivity[$normalized]['expense'] = round( + (float) ($normalizedActivity[$normalized]['expense'] ?? 0) + (float) $row['expense'], + 2, + ); + } + + $storeNames = array_values(array_unique(array_merge( + array_keys($base), + array_keys($movement), + array_keys($normalizedActivity), + ))); + $rows = []; + foreach ($storeNames as $normalized) { + $storeName = $displayNames[$normalized] + ?? ($base[$normalized]['store_name'] ?? '未标注店铺'); + $opening = array_key_exists($normalized, $base) + ? round( + (float) $base[$normalized]['balance'] + + (float) ($movement[$normalized]['income'] ?? 0) + - (float) ($movement[$normalized]['expense'] ?? 0), + 2, + ) + : null; + $rows[] = [ + 'store_name' => $storeName, + 'opening_balance' => $opening, + 'income' => round((float) ($normalizedActivity[$normalized]['income'] ?? 0), 2), + 'expense' => round((float) ($normalizedActivity[$normalized]['expense'] ?? 0), 2), + ]; + } + + return $rows; + } + + /** + * @return array + */ + private function accountBillActivity( + string $billType, + string $start, + string $end, + bool $bySettlePeriod, + ): array { + $query = AccountBill::query() + ->where('company_id', company_id()) + ->where('bill_type', $billType) + ->whereNull('deleted_at'); + if ($bySettlePeriod) { + $query->where('payload->settle_period', '>=', substr($start, 0, 7)) + ->where('payload->settle_period', '<=', substr($end, 0, 7)); + } else { + $query->where('occurred_at', '>=', $start . ' 00:00:00') + ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'); + } + + return $this->groupedActivity($query, 'income', 'expense'); + } + + private function mirrorConnection(): ConnectionInterface + { + return app(DatabaseManager::class)->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + private function storeName(mixed $value): string + { + $storeName = trim((string) $value); + + return $storeName !== '' ? $storeName : '未标注店铺'; + } + + private function dayAfter(string $date): string + { + return CarbonImmutable::parse($date, 'Asia/Shanghai')->addDay()->format('Y-m-d'); + } + /** @return iterable> */ private function fetchPlatformRows( string $platform, diff --git a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue index a973515d..951e5d55 100644 --- a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue +++ b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue @@ -240,13 +240,13 @@ role="tab" :aria-selected="detailTab === tab.key ? 'true' : 'false'" :class="{ 'is-active': detailTab === tab.key }" - @click="detailTab = tab.key" + @click="selectDetailTab(tab.key)" >{{ tab.label }}
正在汇总各平台{{ detailFlowLabel }}明细…
@@ -264,13 +264,17 @@ - + + + + + - + @@ -360,6 +364,8 @@ export default { detailLoading: false, detailError: '', detailDetails: [], + detailStoreDetails: [], + detailStoreLoaded: false, detailRequestSerial: 0, detailTab: 'platform', detailPlatform: '', @@ -460,12 +466,15 @@ export default { }, detailDescription() { return this.detailFlow === 'balance' - ? '按平台汇总期末余额' + ? '按平台和店铺汇总期末余额' : '按平台、店铺和账单项目汇总'; }, detailTabs() { if (this.detailFlow === 'balance') { - return [{ key: 'platform', label: '平台' }]; + return [ + { key: 'platform', label: '平台' }, + { key: 'store', label: '店铺名称' }, + ]; } return [ @@ -501,7 +510,11 @@ export default { )].sort((left, right) => left.localeCompare(right, 'zh-CN')); }, detailFilteredDetails() { - return this.detailDetails.filter((row) => ( + const details = this.detailFlow === 'balance' && this.detailTab === 'store' + ? this.detailStoreDetails + : this.detailDetails; + + return details.filter((row) => ( (!this.detailPlatform || row.platform_slug === this.detailPlatform) && (!this.detailStore || row.store_name === this.detailStore) && (!this.detailBillItem || row.bill_item === this.detailBillItem) @@ -509,6 +522,9 @@ export default { }, detailFilteredTotal() { if (this.detailLoading || this.detailError) return null; + if (this.detailFilteredDetails.some(row => row.amount === null || row.amount === undefined)) { + return null; + } return this.detailFilteredDetails.reduce( (total, row) => total + Number(row.amount || 0), @@ -547,14 +563,21 @@ export default { platform: row.platform, store_name: row.store_name, bill_item: row.bill_item, - amount: 0, + amount: row.amount === null ? null : 0, }; - current.amount += Number(row.amount || 0); + if (current.amount === null || row.amount === null || row.amount === undefined) { + current.amount = null; + } else { + current.amount += Number(row.amount || 0); + } grouped.set(key, current); }); return Array.from(grouped.values()) - .map(row => ({ ...row, amount: Math.round(row.amount * 100) / 100 })) + .map(row => ({ + ...row, + amount: row.amount === null ? null : Math.round(row.amount * 100) / 100, + })) .sort((left, right) => { if (this.detailTab === 'platform') { return (platformOrder.get(left.platform_slug) ?? 99) @@ -562,7 +585,9 @@ export default { } return ( - right.amount - left.amount + (left.amount === null ? 1 : 0) - (right.amount === null ? 1 : 0) + || (left.amount === null ? 0 : right.amount) + - (left.amount === null ? 0 : left.amount) || (platformOrder.get(left.platform_slug) ?? 99) - (platformOrder.get(right.platform_slug) ?? 99) || String(left.store_name).localeCompare(String(right.store_name), 'zh-CN') @@ -671,6 +696,8 @@ export default { this.detailStore = ''; this.detailBillItem = ''; this.detailDetails = []; + this.detailStoreDetails = []; + this.detailStoreLoaded = false; this.detailError = ''; this.lockDetailScroll(); this.$nextTick(() => { @@ -704,12 +731,55 @@ export default { } catch (error) { if (requestId !== this.detailRequestSerial || !this.detailOpen) return; this.detailDetails = []; + this.detailStoreDetails = []; this.detailError = (error.response && error.response.data && error.response.data.message) || `${this.detailFlowLabel}明细暂时无法读取,请稍后重试。`; } finally { if (requestId === this.detailRequestSerial) this.detailLoading = false; } }, + async selectDetailTab(tab) { + if (this.detailTab === tab) return; + this.detailTab = tab; + this.detailError = ''; + if (this.detailFlow === 'balance' && tab === 'store' && !this.detailStoreLoaded) { + await this.fetchStoreBalanceDetails(); + } + }, + async fetchStoreBalanceDetails() { + const requestId = ++this.detailRequestSerial; + this.detailLoading = true; + this.detailError = ''; + + try { + const response = await window.axios.get(`${this.apiBase}/balance-store-detail`, { + params: { + start: this.queryRange.start, + end: this.queryRange.end, + }, + }); + if (requestId !== this.detailRequestSerial || !this.detailOpen) return; + const body = response.data || {}; + this.detailStoreDetails = Array.isArray(body.details) ? body.details : []; + this.detailStoreLoaded = true; + } catch (error) { + if (requestId !== this.detailRequestSerial || !this.detailOpen) return; + this.detailStoreDetails = []; + this.detailStoreLoaded = false; + this.detailError = (error.response && error.response.data && error.response.data.message) + || '店铺期末余额明细暂时无法读取,请稍后重试。'; + } finally { + if (requestId === this.detailRequestSerial) this.detailLoading = false; + } + }, + retryDetails() { + if (this.detailFlow === 'balance' && this.detailTab === 'store') { + this.fetchStoreBalanceDetails(); + return; + } + + this.fetchDetails(); + }, normalizeDetailFilters() { if (this.detailPlatform && !this.detailPlatformOptions.some(item => item.slug === this.detailPlatform)) { diff --git a/routes/admin.php b/routes/admin.php index c7a0b844..1843ad5b 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -47,6 +47,8 @@ Route::get('ecommerce-finance/account-bills/overview/expense-detail', [StoreRece ->name('ecommerce-finance.account-bills.overview.expense-detail'); Route::get('ecommerce-finance/account-bills/overview/balance-detail', [StoreReceivingBalanceOverview::class, 'balanceDetail']) ->name('ecommerce-finance.account-bills.overview.balance-detail'); +Route::get('ecommerce-finance/account-bills/overview/balance-store-detail', [StoreReceivingBalanceOverview::class, 'balanceStoreDetail']) + ->name('ecommerce-finance.account-bills.overview.balance-store-detail'); Route::get('ecommerce-finance/alipay-bills', [AlipayBills::class, 'index']) ->name('ecommerce-finance.alipay-bills.index'); Route::get('ecommerce-finance/alipay-bills/export', [AlipayBills::class, 'export']) diff --git a/tests/Feature/Business/StoreReceivingBalanceOverviewEndpointTest.php b/tests/Feature/Business/StoreReceivingBalanceOverviewEndpointTest.php index fc87b3ed..6240f5dc 100644 --- a/tests/Feature/Business/StoreReceivingBalanceOverviewEndpointTest.php +++ b/tests/Feature/Business/StoreReceivingBalanceOverviewEndpointTest.php @@ -245,4 +245,47 @@ class StoreReceivingBalanceOverviewEndpointTest extends FeatureTestCase ->assertJsonPath('details.0.platform_slug', 'taobao-alipay') ->assertJsonPath('details.0.amount', 218.88); } + + public function test_balance_store_detail_endpoint_returns_store_closing_balances(): void + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + + $payload = [ + 'month' => '2026-10', + 'period' => ['start' => '2026-10-01', 'end' => '2026-10-31'], + 'summary' => [ + 'balance' => 1049.07, + 'platform_count' => 8, + 'available_platform_count' => 8, + 'store_count' => 1, + 'ready_store_count' => 1, + 'complete' => true, + ], + 'details' => [[ + 'platform_slug' => 'taobao-alipay', + 'platform' => '淘系支付宝账户', + 'store_name' => '测试店铺', + 'bill_item' => '', + 'opening_balance' => 100.0, + 'income' => 130.0, + 'expense' => 10.0, + 'amount' => 220.0, + 'available' => true, + ]], + ]; + $service = Mockery::mock(StoreReceivingBalanceOverviewService::class); + $service->shouldReceive('balanceStoreDetail')->once()->with('2026-10')->andReturn($payload); + $this->app->instance(StoreReceivingBalanceOverviewService::class, $service); + + $this->loginAs() + ->getJson(route('ecommerce-finance.account-bills.overview.balance-store-detail', [ + 'month' => '2026-10', + ])) + ->assertOk() + ->assertJsonPath('summary.complete', true) + ->assertJsonPath('details.0.store_name', '测试店铺') + ->assertJsonPath('details.0.amount', 220); + } } diff --git a/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php b/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php index 48cd6c74..db7f23ea 100644 --- a/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php +++ b/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php @@ -210,6 +210,80 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase $this->assertSame(8, $result['summary']['available_platform_count']); } + public function test_balance_store_detail_calculates_each_store_closing_balance(): void + { + $service = new class extends StoreReceivingBalanceOverviewService { + public function __construct() + { + } + + protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array + { + $index = array_search($platform, array_column(StoreReceivingBalanceOverviewService::PLATFORMS, 'slug'), true) + 1; + + return [[ + 'store_name' => '店铺-' . $index, + 'opening_balance' => 100.10 * $index, + 'income' => 10.20 * $index, + 'expense' => 1.25 * $index, + ]]; + } + }; + + $result = $service->balanceStoreDetail('2026-10'); + + $this->assertSame('2026-10', $result['month']); + $this->assertSame(['start' => '2026-10-01', 'end' => '2026-10-31'], $result['period']); + $this->assertCount(8, $result['details']); + $this->assertSame([ + 'platform_slug' => 'taobao-alipay', + 'platform' => '淘系支付宝账户', + 'store_name' => '店铺-1', + 'bill_item' => '', + 'opening_balance' => 100.10, + 'income' => 10.20, + 'expense' => 1.25, + 'amount' => 109.05, + 'available' => true, + ], $result['details'][0]); + $this->assertSame(3925.80, $result['summary']['balance']); + $this->assertSame(8, $result['summary']['store_count']); + $this->assertSame(8, $result['summary']['ready_store_count']); + $this->assertTrue($result['summary']['complete']); + } + + public function test_balance_store_detail_marks_missing_opening_instead_of_using_zero(): void + { + $service = new class extends StoreReceivingBalanceOverviewService { + public function __construct() + { + } + + protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array + { + return [[ + 'store_name' => '待补期初店铺', + 'opening_balance' => $platform === 'vipshop-jx' ? null : 25.0, + 'income' => 5.0, + 'expense' => 2.0, + ]]; + } + }; + + $result = $service->balanceStoreDetail('2026-10'); + + $this->assertFalse($result['summary']['complete']); + $this->assertNull($result['summary']['balance']); + $this->assertSame(7, $result['summary']['ready_store_count']); + $unavailable = array_values(array_filter( + $result['details'], + static fn (array $row): bool => $row['platform_slug'] === 'vipshop-jx', + ))[0]; + $this->assertNull($unavailable['opening_balance']); + $this->assertNull($unavailable['amount']); + $this->assertFalse($unavailable['available']); + } + public function test_monthly_closing_returns_july_to_october_for_all_platforms(): void { $monthOrdinal = ['2026-07' => 1, '2026-08' => 2, '2026-09' => 3, '2026-10' => 4]; @@ -256,6 +330,11 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase { return ($this->summaryCallback)($platform, $start, $end); } + + protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array + { + return []; + } }; } } diff --git a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php index 96199a7a..79564334 100644 --- a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php +++ b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php @@ -42,11 +42,16 @@ class StoreReceivingBalanceOverviewTest extends TestCase $this->assertStringContainsString("{ key: 'platform', label: '平台' }", $source); $this->assertStringContainsString("{ key: 'store', label: '店铺' }", $source); $this->assertStringContainsString("{ key: 'bill_item', label: '账单项目' }", $source); + $this->assertStringContainsString("{ key: 'store', label: '店铺名称' }", $source); $this->assertStringContainsString('income-detail', $source); $this->assertStringContainsString('expense-detail', $source); $this->assertStringContainsString('balance-detail', $source); + $this->assertStringContainsString('balance-store-detail', $source); $this->assertStringContainsString("detailFlow === 'balance'", $source); $this->assertStringContainsString('期末余额(万元)', $source); + $this->assertStringContainsString("detailFlow === 'balance' ? '店铺名称' : '店铺'", $source); + $this->assertStringContainsString('fetchStoreBalanceDetails', $source); + $this->assertStringContainsString('该店铺缺少期初余额', $source); $this->assertStringContainsString('当前筛选合计(万元)', $source); } From 4ee396151dc3ef987c19f7a0976041970e2b2617 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 14:34:55 +0800 Subject: [PATCH 03/12] =?UTF-8?q?perf:=20=E5=A4=8D=E7=94=A8=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E5=AE=9D=E5=BA=97=E9=93=BA=E6=9C=9F=E5=88=9D=E7=BC=93?= =?UTF-8?q?=E5=AD=98=20(#1042)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TaobaoAlipaySettlementBillRepository.php | 66 +++++++++++++++-- .../StoreReceivingBalanceOverviewService.php | 74 +------------------ ...obaoAlipaySettlementBillRepositoryTest.php | 10 +++ 3 files changed, 74 insertions(+), 76 deletions(-) diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php index ffd3d67e..b02654ea 100644 --- a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -98,6 +98,33 @@ class TaobaoAlipaySettlementBillRepository return $this->summaryForQuery($query, $filters); } + /** + * 复用总览期初查询已经缓存的店铺余额,避免店铺明细再次扫描全历史。 + * + * @return array + */ + public function storeOpeningBalances(?string $periodStart): array + { + $start = $this->date($periodStart); + if ($start === null) { + return []; + } + + $monthStart = $start->modify('first day of this month'); + $cutoff = $monthStart->format('Y-m-d') . ' 00:00:00'; + $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) + ->where('status', 'succeeded') + ->max('completed_at') ?? ''); + $cacheKey = $this->openingBalanceCacheKey($cutoff, '', $importVersion); + $opening = Cache::get($cacheKey); + if (! is_array($opening) || ! is_array($opening['stores'] ?? null)) { + $this->openingBalance(['start' => $periodStart]); + $opening = Cache::get($cacheKey); + } + + return is_array($opening['stores'] ?? null) ? $opening['stores'] : []; + } + /** * @return array{income:float,expense:float,opening_balance:float,opening_balance_date:?string,opening_balance_source:string,balance:float,count:int} */ @@ -223,11 +250,7 @@ class TaobaoAlipaySettlementBillRepository $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) ->where('status', 'succeeded') ->max('completed_at') ?? ''); - $cacheKey = 'taobao-alipay-opening-balance:v1:' . hash('sha256', implode('|', [ - $cutoff, - $store, - $importVersion, - ])); + $cacheKey = $this->openingBalanceCacheKey($cutoff, $store, $importVersion); $opening = Cache::remember( $cacheKey, @@ -259,9 +282,20 @@ class TaobaoAlipaySettlementBillRepository ->get(); if ($latestRows->isNotEmpty()) { + $stores = []; + foreach ($latestRows as $row) { + $storeName = trim((string) ($row->store_name ?? '')); + $storeName = $storeName !== '' ? $storeName : '未标注店铺'; + $stores[$storeName] = round( + (float) ($stores[$storeName] ?? 0) + (float) $row->balance_amount, + 2, + ); + } + return [ 'balance' => round((float) $latestRows->sum('balance_amount'), 2), 'source' => 'previous_period', + 'stores' => $stores, ]; } @@ -291,6 +325,18 @@ class TaobaoAlipaySettlementBillRepository ->fromSub($firstRows, 'first_balances') ->where('row_rank', 1) ->get(); + $stores = []; + foreach ($first as $row) { + $storeName = trim((string) ($row->store_name ?? '')); + $storeName = $storeName !== '' ? $storeName : '未标注店铺'; + $stores[$storeName] = round( + (float) ($stores[$storeName] ?? 0) + + (float) $row->balance_amount + - (float) $row->income_amount + + (float) $row->expense_amount, + 2, + ); + } return [ 'balance' => round((float) $first->sum( @@ -299,6 +345,7 @@ class TaobaoAlipaySettlementBillRepository + (float) $row->expense_amount, ), 2), 'source' => 'first_row_estimate', + 'stores' => $stores, ]; }, ); @@ -356,4 +403,13 @@ class TaobaoAlipaySettlementBillRepository { return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value); } + + private function openingBalanceCacheKey(string $cutoff, string $store, string $importVersion): string + { + return 'taobao-alipay-opening-balance:v2:' . hash('sha256', implode('|', [ + $cutoff, + $store, + $importVersion, + ])); + } } diff --git a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php index 65c3ac6a..8672a0ba 100644 --- a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php +++ b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php @@ -20,6 +20,7 @@ use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository; +use Modules\EcommerceFinance\Repositories\TaobaoAlipaySettlementBillRepository; use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository; use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository; use Modules\EcommerceFinance\Repositories\VipshopJxOpeningBalanceRepository; @@ -623,77 +624,8 @@ class StoreReceivingBalanceOverviewService ->where('occurred_at', '>=', $start . ' 00:00:00') ->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'), ); - $cutoff = $start . ' 00:00:00'; - $periodEnd = $this->dayAfter($end) . ' 00:00:00'; - $ranked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE) - ->where('occurred_at', '<', $cutoff) - ->whereNotNull('alipay_account') - ->where('alipay_account', '<>', '') - ->select([ - 'store_name', - 'alipay_account', - 'occurred_at', - 'source_row_number', - 'income_amount', - 'expense_amount', - 'balance_amount', - ]) - ->selectRaw( - 'ROW_NUMBER() OVER (' . - 'PARTITION BY alipay_account ' . - 'ORDER BY occurred_at DESC, source_row_number DESC' . - ') AS row_rank', - ); - $latestRows = $connection->query() - ->fromSub($ranked, 'latest_store_balances') - ->where('row_rank', 1) - ->get(); - $opening = []; - - if ($latestRows->isNotEmpty()) { - foreach ($latestRows as $row) { - $storeName = $this->storeName($row->store_name); - $opening[$storeName] = round( - (float) ($opening[$storeName] ?? 0) + (float) $row->balance_amount, - 2, - ); - } - } else { - $firstRanked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE) - ->where('occurred_at', '>=', $cutoff) - ->where('occurred_at', '<', $periodEnd) - ->whereNotNull('alipay_account') - ->where('alipay_account', '<>', '') - ->select([ - 'store_name', - 'alipay_account', - 'occurred_at', - 'source_row_number', - 'income_amount', - 'expense_amount', - 'balance_amount', - ]) - ->selectRaw( - 'ROW_NUMBER() OVER (' . - 'PARTITION BY alipay_account ' . - 'ORDER BY occurred_at ASC, source_row_number ASC' . - ') AS row_rank', - ); - $firstRows = $connection->query() - ->fromSub($firstRanked, 'first_store_balances') - ->where('row_rank', 1) - ->get(); - foreach ($firstRows as $row) { - $storeName = $this->storeName($row->store_name); - $opening[$storeName] = round( - (float) ($opening[$storeName] ?? 0) - + (float) $row->balance_amount - - (float) $row->income_amount - + (float) $row->expense_amount, - 2, - ); - } - } + $opening = app(TaobaoAlipaySettlementBillRepository::class) + ->storeOpeningBalances($start); return $this->mergeStoreBalances($opening, $activity); } diff --git a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php index d0d68f34..5a42c430 100644 --- a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php @@ -65,6 +65,11 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase 'end' => '2026-10-31', ]), ); + $this->assertSame( + ['天猫-A店' => 180.0, '淘宝-B店' => 50.0], + app(TaobaoAlipaySettlementBillRepository::class) + ->storeOpeningBalances('2026-10-01'), + ); } public function test_month_balance_respects_store_filter(): void @@ -116,6 +121,11 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase $this->assertSame(35.0, $result['summary']['income']); $this->assertSame(15.0, $result['summary']['expense']); $this->assertSame(320.0, $result['summary']['balance']); + $this->assertSame( + ['天猫-A店' => 200.0, '淘宝-B店' => 100.0], + app(TaobaoAlipaySettlementBillRepository::class) + ->storeOpeningBalances('2026-07-01'), + ); } private function createTables(): void From d0c4ac800b8dd95b4ced4bcd800ec6eb216b409e Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 14:51:11 +0800 Subject: [PATCH 04/12] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E5=AE=9D=E5=BA=97=E9=93=BA=E6=9C=9F=E5=88=9D=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=E5=B9=B6=E5=90=88=E5=B9=B6=E9=87=8D=E5=A4=8D=E5=BA=97?= =?UTF-8?q?=E9=93=BA=20(#1043)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TaobaoAlipaySettlementBillRepository.php | 2 ++ .../StoreReceivingBalanceOverviewService.php | 34 ++++++++++++++---- ...oreReceivingBalanceOverviewServiceTest.php | 36 +++++++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php index b02654ea..b05f87a5 100644 --- a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -262,6 +262,7 @@ class TaobaoAlipaySettlementBillRepository ->where('alipay_account', '<>', '') ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) ->select([ + 'store_name', 'alipay_account', 'occurred_at', 'source_row_number', @@ -308,6 +309,7 @@ class TaobaoAlipaySettlementBillRepository ->where('alipay_account', '<>', '') ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) ->select([ + 'store_name', 'alipay_account', 'occurred_at', 'source_row_number', diff --git a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php index 8672a0ba..beef5537 100644 --- a/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php +++ b/modules/EcommerceFinance/Services/StoreReceivingBalanceOverviewService.php @@ -372,15 +372,37 @@ class StoreReceivingBalanceOverviewService throw new RuntimeException('店铺期末余额明细暂时无法读取,请稍后重试。', 0, $exception); } - $platformRows = []; + $rowsByStore = []; foreach ($rows as $row) { $storeName = trim((string) ($row['store_name'] ?? '')); $storeName = $storeName !== '' ? $storeName : '未标注店铺'; - $opening = is_numeric($row['opening_balance'] ?? null) - ? round((float) $row['opening_balance'], 2) - : null; - $income = round((float) ($row['income'] ?? 0), 2); - $expense = round((float) ($row['expense'] ?? 0), 2); + $rowsByStore[$storeName] ??= [ + 'opening_balance' => null, + 'income' => 0.0, + 'expense' => 0.0, + ]; + if (is_numeric($row['opening_balance'] ?? null)) { + $rowsByStore[$storeName]['opening_balance'] = round( + (float) ($rowsByStore[$storeName]['opening_balance'] ?? 0) + + (float) $row['opening_balance'], + 2, + ); + } + $rowsByStore[$storeName]['income'] = round( + (float) $rowsByStore[$storeName]['income'] + (float) ($row['income'] ?? 0), + 2, + ); + $rowsByStore[$storeName]['expense'] = round( + (float) $rowsByStore[$storeName]['expense'] + (float) ($row['expense'] ?? 0), + 2, + ); + } + + $platformRows = []; + foreach ($rowsByStore as $storeName => $row) { + $opening = $row['opening_balance']; + $income = $row['income']; + $expense = $row['expense']; $amount = $opening === null ? null : round($opening + $income - $expense, 2); diff --git a/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php b/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php index db7f23ea..1d55ae6c 100644 --- a/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php +++ b/tests/Unit/EcommerceFinance/StoreReceivingBalanceOverviewServiceTest.php @@ -284,6 +284,42 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase $this->assertFalse($unavailable['available']); } + public function test_balance_store_detail_merges_duplicate_store_rows_without_creating_zero_opening(): void + { + $service = new class extends StoreReceivingBalanceOverviewService { + public function __construct() + { + } + + protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array + { + return [[ + 'store_name' => '重复店铺', + 'opening_balance' => null, + 'income' => 5.0, + 'expense' => 0.0, + ], [ + 'store_name' => '重复店铺', + 'opening_balance' => null, + 'income' => 0.0, + 'expense' => 2.0, + ]]; + } + }; + + $result = $service->balanceStoreDetail('2026-10'); + $rows = array_values(array_filter( + $result['details'], + static fn (array $row): bool => $row['store_name'] === '重复店铺', + )); + + $this->assertCount(1, $rows); + $this->assertNull($rows[0]['opening_balance']); + $this->assertSame(5.0, $rows[0]['income']); + $this->assertSame(2.0, $rows[0]['expense']); + $this->assertNull($rows[0]['amount']); + } + public function test_monthly_closing_returns_july_to_october_for_all_platforms(): void { $monthOrdinal = ['2026-07' => 1, '2026-08' => 2, '2026-09' => 3, '2026-10' => 4]; From 73bd32b1e78bc1b6266ecf070c0d7cf311311e08 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 15:30:10 +0800 Subject: [PATCH 05/12] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=9C=88?= =?UTF-8?q?=E5=BA=A6=E6=9C=9F=E6=9C=AB=E4=BD=99=E9=A2=9D=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E6=B1=87=E6=80=BB=20(#1044)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StoreReceivingBalanceOverview.vue | 284 +++++++++++++++++- .../StoreReceivingBalanceOverviewTest.php | 11 +- 2 files changed, 288 insertions(+), 7 deletions(-) diff --git a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue index 951e5d55..f2af513c 100644 --- a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue +++ b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue @@ -132,11 +132,30 @@

月度期末余额汇总

新增 -

2026 年 7-10 月各平台期末余额 · 金额单位:万元

+

+ 2026 年 7-10 月{{ monthlyClosingView === 'store' ? '店铺' : '各平台' }}期末余额 + · 金额单位:万元 +

+ +
+ {{ monthlyClosingCountText }} +
+ + +
- - {{ monthlyClosing.summary.available_platform_count }} / {{ monthlyClosing.summary.platform_count }} 个平台 -
@@ -147,7 +166,15 @@ {{ monthlyClosingError }}
-
+
+ +

正在汇总 7-10 月店铺期末余额…

+
+ +
平台店铺{{ detailFlowLabel }}金额(万元)
平台{{ detailFlow === 'balance' ? '店铺名称' : '店铺' }}{{ detailFlow === 'balance' ? '期末余额(万元)' : `${detailFlowLabel}金额(万元)` }}
{{ row.platform }} {{ row.store_name }}{{ moneyWan(row.amount) }}{{ moneyWan(row.amount) }}
当前筛选范围内暂无{{ detailFlowLabel }}明细
@@ -179,9 +206,46 @@
+
+ + + + + + + + + + + + + + + + + +
平台账户店铺名称 + {{ month.label }} + 环比
{{ row.platform }}{{ row.store_name }} + {{ monthlyBalanceWan(row, month.key) }} + + {{ signedMoneyWan(row.change.amount) }} + + {{ signedPercent(row.change.rate) }} + +
+
环比口径:2026年10月期末余额 − 2026年9月期末余额,金额单位为万元,百分比以上月余额为基数。 - 8 个平台沿用各自账单页的期末余额口径。 + + {{ monthlyClosingView === 'store' + ? '店铺期末余额 = 期初余额 + 收入 - 支出;缺少期初时显示“—”。' + : '8 个平台沿用各自账单页的期末余额口径。' }} +
@@ -342,6 +406,19 @@ const dateConfig = { onReady: (_, value, picker) => picker.calendarContainer.classList.add('overview-calendar'), }; +const closingChange = (balances, currentMonth, previousMonth) => { + const current = balances[currentMonth]; + const previous = balances[previousMonth]; + const amount = Number.isFinite(current) && Number.isFinite(previous) + ? Math.round((current - previous) * 100) / 100 + : null; + const rate = amount !== null && Math.abs(previous) >= 0.005 + ? Math.round((amount / Math.abs(previous)) * 10000) / 100 + : (amount === 0 ? 0 : null); + + return { amount, rate }; +}; + export default { name: 'StoreReceivingBalanceOverview', components: { flatPicker }, @@ -375,6 +452,12 @@ export default { monthlyClosingLoading: true, monthlyClosingError: '', monthlyClosingRequestSerial: 0, + monthlyClosingView: 'platform', + monthlyClosingStoreLoading: false, + monthlyClosingStoreError: '', + monthlyClosingStoreLoaded: false, + monthlyClosingStoreRequestSerial: 0, + monthlyStoreMonthDetails: [], monthlyClosing: { months: [], summary: { @@ -605,6 +688,81 @@ export default { ...(Array.isArray(this.monthlyClosing.platforms) ? this.monthlyClosing.platforms : []), ]; }, + monthlyClosingCountText() { + if (this.monthlyClosingView === 'platform') { + return `${this.monthlyClosing.summary.available_platform_count} / ${this.monthlyClosing.summary.platform_count} 个平台`; + } + if (this.monthlyClosingStoreLoading) return '正在读取店铺…'; + if (this.monthlyClosingStoreError) return '店铺数据暂不可用'; + + const total = this.monthlyStoreRows.filter(row => !row.isTotal).length; + const incomplete = this.monthlyStoreRows.filter(row => !row.isTotal && !row.available).length; + + return incomplete > 0 + ? `${total} 个店铺 · ${incomplete} 个期初待补` + : `${total} 个店铺`; + }, + monthlyStoreRows() { + const months = Array.isArray(this.monthlyClosing.months) + ? this.monthlyClosing.months.map(month => month.key) + : []; + const platformOrder = new Map( + this.monthlyClosing.platforms.map((platform, index) => [platform.slug, index]), + ); + const grouped = new Map(); + + this.monthlyStoreMonthDetails.forEach((result) => { + (Array.isArray(result.details) ? result.details : []).forEach((detail) => { + const key = [detail.platform_slug, detail.store_name].join('|'); + const row = grouped.get(key) || { + key, + platform_slug: detail.platform_slug, + platform: detail.platform, + store_name: detail.store_name, + balances: Object.fromEntries(months.map(month => [month, null])), + }; + row.balances[result.month] = detail.amount === null || detail.amount === undefined + ? null + : (Number.isFinite(Number(detail.amount)) + ? Math.round(Number(detail.amount) * 100) / 100 + : null); + grouped.set(key, row); + }); + }); + + const currentMonth = this.monthlyClosing.comparison.current; + const previousMonth = this.monthlyClosing.comparison.previous; + const rows = Array.from(grouped.values()).map(row => ({ + ...row, + available: months.some(month => row.balances[month] !== null), + change: closingChange(row.balances, currentMonth, previousMonth), + })); + const latestMonth = months[months.length - 1]; + rows.sort((left, right) => { + const leftBalance = left.balances[latestMonth]; + const rightBalance = right.balances[latestMonth]; + + return ( + (leftBalance === null ? 1 : 0) - (rightBalance === null ? 1 : 0) + || (leftBalance === null ? 0 : rightBalance) + - (leftBalance === null ? 0 : leftBalance) + || (platformOrder.get(left.platform_slug) ?? 99) + - (platformOrder.get(right.platform_slug) ?? 99) + || left.store_name.localeCompare(right.store_name, 'zh-CN') + ); + }); + + if (!this.monthlyClosing.total) return rows; + + return [{ + ...this.monthlyClosing.total, + key: 'monthly-store-total', + platform: '合计', + store_name: `合计 · ${rows.length} 个店铺`, + isTotal: true, + available: true, + }, ...rows]; + }, }, mounted() { this.fetchOverview(); @@ -652,6 +810,9 @@ export default { const requestId = ++this.monthlyClosingRequestSerial; this.monthlyClosingLoading = true; this.monthlyClosingError = ''; + ++this.monthlyClosingStoreRequestSerial; + this.monthlyClosingStoreLoaded = false; + this.monthlyStoreMonthDetails = []; try { const response = await window.axios.get(`${this.apiBase}/monthly-closing`); @@ -668,6 +829,9 @@ export default { total: body.total || null, platforms: Array.isArray(body.platforms) ? body.platforms : [], }; + if (this.monthlyClosingView === 'store') { + this.fetchMonthlyClosingStores(); + } } catch (error) { if (requestId !== this.monthlyClosingRequestSerial) return; this.monthlyClosingError = (error.response && error.response.data && error.response.data.message) @@ -678,6 +842,54 @@ export default { } } }, + selectMonthlyClosingView(view) { + if (!['platform', 'store'].includes(view) || this.monthlyClosingView === view) return; + this.monthlyClosingView = view; + if (view === 'store' && !this.monthlyClosingStoreLoaded && !this.monthlyClosingStoreLoading) { + this.fetchMonthlyClosingStores(); + } + }, + async fetchMonthlyClosingStores() { + const months = Array.isArray(this.monthlyClosing.months) ? this.monthlyClosing.months : []; + if (!months.length) return; + + const requestId = ++this.monthlyClosingStoreRequestSerial; + this.monthlyClosingStoreLoading = true; + this.monthlyClosingStoreError = ''; + + try { + const responses = await Promise.all(months.map((month) => { + const [year, monthNumber] = month.key.split('-').map(Number); + const lastDay = new Date(year, monthNumber, 0).getDate(); + + return window.axios.get(`${this.apiBase}/balance-store-detail`, { + params: { + start: `${month.key}-01`, + end: `${month.key}-${pad(lastDay)}`, + }, + }); + })); + if (requestId !== this.monthlyClosingStoreRequestSerial) return; + + this.monthlyStoreMonthDetails = responses.map((response, index) => ({ + month: months[index].key, + details: Array.isArray(response.data && response.data.details) + ? response.data.details + : [], + })); + this.monthlyClosingStoreLoaded = true; + } catch (error) { + if (requestId !== this.monthlyClosingStoreRequestSerial) return; + this.monthlyStoreMonthDetails = []; + this.monthlyClosingStoreLoaded = false; + this.monthlyClosingStoreError = (error.response && error.response.data && error.response.data.message) + || '店铺月度期末余额暂时无法读取,请稍后重试。'; + } finally { + if (requestId === this.monthlyClosingStoreRequestSerial) { + this.monthlyClosingStoreLoading = false; + } + } + }, changeDate(field, value) { const date = value || ''; if (this.dateRange[field] === date) return; @@ -1255,10 +1467,55 @@ export default { font-size: .6875rem; font-weight: 600; } +.monthly-closing-head-actions { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: .75rem; +} +.monthly-closing-view-switch { + display: inline-flex; + padding: 2px; + border: 1px solid #d8cdbc; + border-radius: .5rem; + background: #f7f1e5; +} +.monthly-closing-view-switch button { + height: 1.9rem; + padding: 0 .75rem; + border: 0; + border-radius: .38rem; + background: transparent; + color: var(--overview-muted); + font: 600 .6875rem/1.2 inherit; + white-space: nowrap; + cursor: pointer; +} +.monthly-closing-view-switch button:hover { + color: var(--overview-gold); +} +.monthly-closing-view-switch button.is-active { + background: #fffdf8; + color: var(--overview-gold); + box-shadow: 0 1px 2px rgba(63, 50, 29, .10); +} +.monthly-closing-view-switch button:focus-visible { + box-shadow: 0 0 0 3px rgba(138, 104, 47, .18); + outline: none; +} .monthly-closing-scroll { overflow-x: auto; overscroll-behavior-inline: contain; } +.monthly-closing-scroll.is-store { + max-height: 30rem; + overflow: auto; +} +.monthly-closing-scroll.is-store .monthly-closing-table thead th { + position: sticky; + z-index: 2; + top: 0; +} .monthly-closing-table { width: 100%; min-width: 44rem; @@ -1267,6 +1524,9 @@ export default { font-size: .75rem; font-variant-numeric: tabular-nums; } +.monthly-closing-store-table { + min-width: 60rem; +} .monthly-closing-table th, .monthly-closing-table td { padding: .65rem .8rem; @@ -1316,6 +1576,9 @@ export default { .monthly-closing-table tbody tr.is-unavailable td { color: #937b57; } +.monthly-closing-store-table .monthly-store-name { + min-width: 15rem; +} .monthly-closing-compare span, .monthly-closing-compare small { display: block; @@ -1345,6 +1608,10 @@ export default { font-size: .625rem; } .monthly-closing-loading, +.monthly-closing-error { + min-height: 6rem; +} +.monthly-closing-loading, .monthly-closing-error { padding: 1rem; } @@ -1678,6 +1945,11 @@ export default { align-items: flex-start; flex-direction: column; } + .monthly-closing-head-actions { + width: 100%; + flex-wrap: wrap; + justify-content: space-between; + } .monthly-closing-foot { align-items: flex-start; flex-direction: column; diff --git a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php index 79564334..101d82c9 100644 --- a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php +++ b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php @@ -74,7 +74,8 @@ class StoreReceivingBalanceOverviewTest extends TestCase $this->assertStringContainsString('月度期末余额汇总', $source); $this->assertStringContainsString('平台账户', $source); $this->assertStringContainsString('monthly-closing-table', $source); - $this->assertStringContainsString('2026 年 7-10 月各平台期末余额', $source); + $this->assertStringContainsString('2026 年 7-10 月', $source); + $this->assertStringContainsString("'各平台'", $source); $this->assertStringContainsString('金额单位:万元', $source); $this->assertStringContainsString('monthlyBalanceWan', $source); $this->assertStringContainsString('signedMoneyWan', $source); @@ -83,5 +84,13 @@ class StoreReceivingBalanceOverviewTest extends TestCase $this->assertStringContainsString('环比口径:2026年10月期末余额 − 2026年9月期末余额', $source); $this->assertStringContainsString('monthlyClosingRows', $source); $this->assertStringContainsString('fetchMonthlyClosing', $source); + $this->assertStringContainsString('店铺汇总', $source); + $this->assertStringContainsString('monthly-closing-view-switch', $source); + $this->assertStringContainsString('selectMonthlyClosingView', $source); + $this->assertStringContainsString('fetchMonthlyClosingStores', $source); + $this->assertStringContainsString('monthlyStoreRows', $source); + $this->assertStringContainsString('monthly-closing-store-table', $source); + $this->assertStringContainsString('店铺期末余额 = 期初余额 + 收入 - 支出', $source); + $this->assertStringContainsString('缺少期初时显示“—”', $source); } } From 0b3e05af8fa6c4fab2583f623d23c0facb4d8154 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 15:46:32 +0800 Subject: [PATCH 06/12] =?UTF-8?q?perf:=20=E5=BA=97=E9=93=BA=E6=9C=88?= =?UTF-8?q?=E5=BA=A6=E6=B1=87=E6=80=BB=E6=8C=89=E5=BA=8F=E6=B8=90=E8=BF=9B?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=20(#1045)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../StoreReceivingBalanceOverview.vue | 139 ++++++++++++------ 1 file changed, 93 insertions(+), 46 deletions(-) diff --git a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue index f2af513c..9e7341a7 100644 --- a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue +++ b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue @@ -166,11 +166,19 @@ {{ monthlyClosingError }} -
+

正在汇总 7-10 月店铺期末余额…

- -
- - - - - - - - - - - - - - - - - -
平台账户店铺名称 - {{ month.label }} - 环比
{{ row.platform }}{{ row.store_name }} - {{ monthlyBalanceWan(row, month.key) }} - - {{ signedMoneyWan(row.change.amount) }} - - {{ signedPercent(row.change.rate) }} - -
-
+
环比口径:2026年10月期末余额 − 2026年9月期末余额,金额单位为万元,百分比以上月余额为基数。 @@ -856,31 +878,32 @@ export default { const requestId = ++this.monthlyClosingStoreRequestSerial; this.monthlyClosingStoreLoading = true; this.monthlyClosingStoreError = ''; + this.monthlyStoreMonthDetails = []; try { - const responses = await Promise.all(months.map((month) => { + for (const month of months) { const [year, monthNumber] = month.key.split('-').map(Number); const lastDay = new Date(year, monthNumber, 0).getDate(); - - return window.axios.get(`${this.apiBase}/balance-store-detail`, { + const response = await window.axios.get(`${this.apiBase}/balance-store-detail`, { params: { start: `${month.key}-01`, end: `${month.key}-${pad(lastDay)}`, }, }); - })); + if (requestId !== this.monthlyClosingStoreRequestSerial) return; + + this.monthlyStoreMonthDetails = [...this.monthlyStoreMonthDetails, { + month: month.key, + details: Array.isArray(response.data && response.data.details) + ? response.data.details + : [], + }]; + } if (requestId !== this.monthlyClosingStoreRequestSerial) return; - this.monthlyStoreMonthDetails = responses.map((response, index) => ({ - month: months[index].key, - details: Array.isArray(response.data && response.data.details) - ? response.data.details - : [], - })); this.monthlyClosingStoreLoaded = true; } catch (error) { if (requestId !== this.monthlyClosingStoreRequestSerial) return; - this.monthlyStoreMonthDetails = []; this.monthlyClosingStoreLoaded = false; this.monthlyClosingStoreError = (error.response && error.response.data && error.response.data.message) || '店铺月度期末余额暂时无法读取,请稍后重试。'; @@ -1516,6 +1539,30 @@ export default { z-index: 2; top: 0; } +.monthly-store-progress { + display: flex; + align-items: center; + justify-content: space-between; + gap: .75rem; + padding: .5rem .8rem; + border-bottom: 1px solid #eee7da; + background: #fbf7ef; + color: var(--overview-muted); + font-size: .6875rem; +} +.monthly-store-progress.is-error { + background: #fff6f3; + color: #9b3c2d; +} +.monthly-store-progress button { + padding: .2rem .55rem; + border: 1px solid currentColor; + border-radius: .35rem; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} .monthly-closing-table { width: 100%; min-width: 44rem; From 190f9b0a724836dca7cf9cdfbf0d8da140e876ee Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 16:00:50 +0800 Subject: [PATCH 07/12] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90=E5=BA=97?= =?UTF-8?q?=E9=93=BA=E6=9C=88=E5=BA=A6=E7=8E=AF=E6=AF=94=E6=AF=94=E8=BE=83?= =?UTF-8?q?=E6=9C=88=E4=BB=BD=20(#1046)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../business/StoreReceivingBalanceOverview.vue | 9 +++++++++ tests/Unit/View/StoreReceivingBalanceOverviewTest.php | 1 + 2 files changed, 10 insertions(+) diff --git a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue index 9e7341a7..813f380d 100644 --- a/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue +++ b/resources/assets/js/components/business/StoreReceivingBalanceOverview.vue @@ -487,6 +487,10 @@ export default { available_platform_count: 0, complete: false, }, + comparison: { + current: '2026-10', + previous: '2026-09', + }, total: null, platforms: [], }, @@ -848,6 +852,11 @@ export default { complete: false, ...(body.summary || {}), }, + comparison: { + current: '2026-10', + previous: '2026-09', + ...(body.comparison || {}), + }, total: body.total || null, platforms: Array.isArray(body.platforms) ? body.platforms : [], }; diff --git a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php index 101d82c9..caa29f24 100644 --- a/tests/Unit/View/StoreReceivingBalanceOverviewTest.php +++ b/tests/Unit/View/StoreReceivingBalanceOverviewTest.php @@ -90,6 +90,7 @@ class StoreReceivingBalanceOverviewTest extends TestCase $this->assertStringContainsString('fetchMonthlyClosingStores', $source); $this->assertStringContainsString('monthlyStoreRows', $source); $this->assertStringContainsString('monthly-closing-store-table', $source); + $this->assertStringContainsString('...(body.comparison || {})', $source); $this->assertStringContainsString('店铺期末余额 = 期初余额 + 收入 - 支出', $source); $this->assertStringContainsString('缺少期初时显示“—”', $source); } From 1c7a93b0a8ebc1584178115619ede117e6305091 Mon Sep 17 00:00:00 2001 From: chenxi Date: Tue, 10 Nov 2026 16:28:11 +0800 Subject: [PATCH 08/12] =?UTF-8?q?feat:=20=E9=A1=BE=E5=AE=B6=E8=BF=87?= =?UTF-8?q?=E8=B4=A6=E6=96=B0=E5=A2=9E=E5=9F=BA=E7=A1=80=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E8=8F=9C=E5=8D=95=20(#1047)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/business_navigation.php | 9 ++++++++- tests/Feature/Settings/NavigationTest.php | 9 +++++++++ .../SystemSettings/UserPermissionsTest.php | 15 +++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/config/business_navigation.php b/config/business_navigation.php index bd874e2c..56df8b6a 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -720,7 +720,14 @@ $navigation = [ 'title' => '过账数据', 'icon' => 'post_add', 'pages' => [ - ['slug' => 'kuka-posting', 'title' => '顾家过账'], + [ + 'slug' => 'kuka-posting', + 'title' => '顾家过账', + 'children_inherit_parent_access' => true, + 'children' => [ + ['slug' => 'kuka-basic-data', 'title' => '基础数据'], + ], + ], ['slug' => 'suofeiya-posting', 'title' => '索菲亚过账'], ], ], diff --git a/tests/Feature/Settings/NavigationTest.php b/tests/Feature/Settings/NavigationTest.php index 4f92a668..ac203e01 100644 --- a/tests/Feature/Settings/NavigationTest.php +++ b/tests/Feature/Settings/NavigationTest.php @@ -621,6 +621,15 @@ class NavigationTest extends FeatureTestCase ['顾家过账', '索菲亚过账'], array_column($navigation[$postingIndex]['pages'], 'title') ); + $this->assertTrue($navigation[$postingIndex]['pages'][0]['children_inherit_parent_access']); + $this->assertSame( + ['kuka-basic-data'], + array_column($navigation[$postingIndex]['pages'][0]['children'], 'slug') + ); + $this->assertSame( + ['基础数据'], + array_column($navigation[$postingIndex]['pages'][0]['children'], 'title') + ); $this->assertSame( ['after-sales-expenses', 'promotion-expenses'], array_column($orderData['pages'][0]['tabs'], 'slug') diff --git a/tests/Feature/SystemSettings/UserPermissionsTest.php b/tests/Feature/SystemSettings/UserPermissionsTest.php index a1a180f6..038a2223 100644 --- a/tests/Feature/SystemSettings/UserPermissionsTest.php +++ b/tests/Feature/SystemSettings/UserPermissionsTest.php @@ -159,7 +159,22 @@ class UserPermissionsTest extends FeatureTestCase ['顾家过账', '索菲亚过账'], array_column($navigation[1]['pages'], 'title') ); + $this->assertSame( + ['kuka-basic-data'], + array_column($navigation[1]['pages'][0]['children'], 'slug') + ); } + + setting()->set('system.sidebar_permissions', [ + 'configured' => [$subject], + 'subjects' => [$subject => ['posting-data/kuka-posting']], + ]); + + $navigation = SidebarPermissions::navigationFor($regular); + $this->assertSame( + ['kuka-basic-data'], + array_column($navigation[0]['pages'][0]['children'], 'slug') + ); } public function test_refund_export_requires_a_separate_operation_grant_when_page_access_is_limited(): void From d132cd1c4dd5138d757544a45ba77e62b2c1f052 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 17:04:48 +0800 Subject: [PATCH 09/12] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90=E6=8A=96?= =?UTF-8?q?=E9=9F=B3=E4=BA=BF=E5=AE=B6=E8=BE=BE=E4=B9=90=E7=AE=80=E4=B8=83?= =?UTF-8?q?=E6=9C=88=E6=9C=9F=E5=88=9D=20(#1048)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DouyinAuthoritativeBillRepository.php | 4 ++ .../DouyinAuthoritativeBillTest.php | 54 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php index 3c90a402..1de0c582 100644 --- a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php +++ b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php @@ -26,6 +26,10 @@ class DouyinAuthoritativeBillRepository 'balance' => 287706.90, 'source' => 'merchant_backoffice_june_ending', ], + '亿家达乐简家具专卖店' => [ + 'balance' => 0.0, + 'source' => 'merchant_backoffice_zero', + ], ]; public function __construct( diff --git a/tests/Unit/EcommerceFinance/DouyinAuthoritativeBillTest.php b/tests/Unit/EcommerceFinance/DouyinAuthoritativeBillTest.php index 56eb44ae..33920ef7 100644 --- a/tests/Unit/EcommerceFinance/DouyinAuthoritativeBillTest.php +++ b/tests/Unit/EcommerceFinance/DouyinAuthoritativeBillTest.php @@ -5,6 +5,7 @@ namespace Tests\Unit\EcommerceFinance; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Modules\EcommerceFinance\Repositories\DouyinAuthoritativeBillRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository; use Modules\EcommerceFinance\Services\DouyinAuthoritativeBillImporter; @@ -298,6 +299,59 @@ class DouyinAuthoritativeBillTest extends TestCase $this->assertSame(22870.22, $august['summary']['balance']); } + public function test_lejian_uses_confirmed_zero_backoffice_opening_and_preserves_store_name(): void + { + $store = '抖音-亿家达乐简家具专卖店'; + $septemberIncome = array_replace($this->row('2000000000000000501', '288.00'), [ + '店铺' => $store, + '结算时间' => '2026-09-02 09:06:52', + ]); + $septemberExpense = array_replace($this->row('2000000000000000502', '0.00', '288.00'), [ + '店铺' => $store, + '账单项目' => '平台服务费', + '结算时间' => '2026-09-02 09:06:52', + ]); + $this->import([$septemberIncome, $septemberExpense], 2, '288.00', '288.00', null, '2026-09'); + + $repo = app(StoreReceivingDouyinBillMirrorRepository::class); + $july = $repo->paginate([ + 'store_name' => $store, + 'start' => '2026-07-01', + 'end' => '2026-07-31', + ], 'occurred_at', 'asc', 1, 10); + $september = $repo->paginate([ + 'store_name' => $store, + 'start' => '2026-09-01', + 'end' => '2026-09-30', + ], 'occurred_at', 'asc', 1, 10); + $october = $repo->paginate([ + 'store_name' => $store, + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ], 'occurred_at', 'asc', 1, 10); + $storeBalances = app(DouyinAuthoritativeBillRepository::class)->storeBalances([ + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ]); + $lejian = array_values(array_filter( + $storeBalances, + static fn (array $row): bool => $row['store_name'] === $store, + )); + + $this->assertSame(0.0, $july['summary']['opening_balance']); + $this->assertSame('2026-06-30', $july['summary']['opening_balance_date']); + $this->assertSame('merchant_backoffice_zero', $july['summary']['opening_balance_source']); + $this->assertSame(0.0, $september['summary']['opening_balance']); + $this->assertSame(288.0, $september['summary']['income']); + $this->assertSame(288.0, $september['summary']['expense']); + $this->assertSame(0.0, $september['summary']['balance']); + $this->assertSame(0.0, $october['summary']['opening_balance']); + $this->assertSame(0.0, $october['summary']['balance']); + $this->assertCount(1, $lejian); + $this->assertSame(0.0, $lejian[0]['opening_balance']); + $this->assertNotContains('未标注店铺', array_column($storeBalances, 'store_name')); + } + private function import( array $rows, int $count, From bde661a11953538b987aee26d45e7b5e633887a5 Mon Sep 17 00:00:00 2001 From: chenxi Date: Tue, 10 Nov 2026 17:08:41 +0800 Subject: [PATCH 10/12] =?UTF-8?q?feat:=20=E6=8E=A5=E5=85=A5=E9=A1=BE?= =?UTF-8?q?=E5=AE=B6=E8=BF=87=E8=B4=A6=E5=9F=BA=E7=A1=80=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=20(#1049)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat: 接入顾家过账基础数据 (#1049) --- .../KukaPostingBaseImporter.php | 276 ++++++++++++++ .../KukaPostingBasePageData.php | 131 +++++++ .../KukaPostingBaseRepository.php | 137 +++++++ app/Business/XlsxSheetReader.php | 48 ++- .../Commands/ImportKukaPostingBase.php | 62 ++++ app/Http/Controllers/Business/Pages.php | 11 + config/kuka_posting.php | 62 ++++ ...170000_create_kuka_posting_base_tables.php | 94 +++++ deploy/finance-batch-imports.json | 1 + docs/上游业务镜像清单.md | 1 + .../posting-data/kuka-basic-data.blade.php | 347 ++++++++++++++++++ .../Business/KukaPostingBasePageTest.php | 205 +++++++++++ tests/Unit/Business/XlsxSheetReaderTest.php | 63 ++++ 13 files changed, 1430 insertions(+), 8 deletions(-) create mode 100644 app/Business/KukaPostingBase/KukaPostingBaseImporter.php create mode 100644 app/Business/KukaPostingBase/KukaPostingBasePageData.php create mode 100644 app/Business/KukaPostingBase/KukaPostingBaseRepository.php create mode 100644 app/Console/Commands/ImportKukaPostingBase.php create mode 100644 config/kuka_posting.php create mode 100644 database/migrations/2026_11_10_170000_create_kuka_posting_base_tables.php create mode 100644 resources/views/business/pages/posting-data/kuka-basic-data.blade.php create mode 100644 tests/Feature/Business/KukaPostingBasePageTest.php diff --git a/app/Business/KukaPostingBase/KukaPostingBaseImporter.php b/app/Business/KukaPostingBase/KukaPostingBaseImporter.php new file mode 100644 index 00000000..3d155605 --- /dev/null +++ b/app/Business/KukaPostingBase/KukaPostingBaseImporter.php @@ -0,0 +1,276 @@ +, + * store_count: int, + * order_count: int, + * skipped_store_rows: int, + * file_sha256: string + * } + */ + public function import( + string $path, + string $period, + ?string $sheetName = null, + int $companyId = 1, + bool $dryRun = false, + ): array { + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) { + throw new InvalidArgumentException('账期格式必须为 YYYY-MM。'); + } + if (! is_file($path) || ! is_readable($path)) { + throw new InvalidArgumentException('聚水潭导出文件不存在或不可读。'); + } + + $connection = $this->connection(); + if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_imports') + || ! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) { + throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。'); + } + + $fields = (array) config('kuka_posting.fields', []); + $allowedStores = array_values((array) config('kuka_posting.stores', [])); + if ($fields === [] || $allowedStores === []) { + throw new RuntimeException('顾家过账基础数据字段或店铺范围未配置。'); + } + + $sourceColumns = array_values(array_filter(array_map( + static fn (array $field): string => trim((string) ($field['source'] ?? '')), + $fields, + ))); + if (count($sourceColumns) !== count($fields)) { + throw new RuntimeException('顾家过账基础数据字段配置不完整。'); + } + + $sheetName = trim((string) ($sheetName ?: config('kuka_posting.source_sheet', '发货明细表'))); + $fileHash = hash_file('sha256', $path); + if (! is_string($fileHash)) { + throw new RuntimeException('无法计算聚水潭导出文件摘要。'); + } + + $storeCounts = array_fill_keys($allowedStores, 0); + $orders = []; + $rowCount = 0; + $skippedStoreRows = 0; + $sourceRowNumber = 1; + $now = now(); + + $write = function () use ( + $connection, + $path, + $period, + $sheetName, + $companyId, + $fields, + $sourceColumns, + $allowedStores, + &$storeCounts, + &$orders, + &$rowCount, + &$skippedStoreRows, + &$sourceRowNumber, + $fileHash, + $now, + $dryRun, + ): void { + if (! $dryRun) { + $connection->table('kuka_posting_base_rows') + ->where('company_id', $companyId) + ->where('period', $period) + ->delete(); + } + + $batch = []; + $flush = static function () use (&$batch, $connection): void { + if ($batch === []) { + return; + } + $connection->table('kuka_posting_base_rows')->insert($batch); + $batch = []; + }; + + foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) { + $sourceRowNumber++; + $storeName = trim((string) ($sourceValues['店铺'] ?? '')); + if ($storeName === '' || ! in_array($storeName, $allowedStores, true)) { + $skippedStoreRows++; + + continue; + } + + $payload = []; + foreach ($fields as $field) { + $source = (string) $field['source']; + $value = trim((string) ($sourceValues[$source] ?? '')); + if (($field['kind'] ?? null) === 'date') { + $value = $this->normalizeDate($value); + } + $payload[$source] = $value; + } + + $rowCount++; + $storeCounts[$storeName]++; + $internalOrderNo = trim((string) ($payload['内部订单号'] ?? '')); + if ($internalOrderNo !== '') { + $orders[$internalOrderNo] = true; + } + + if ($dryRun) { + continue; + } + + $batch[] = [ + 'company_id' => $companyId, + 'period' => $period, + 'store_name' => $storeName, + 'internal_order_no' => $this->limit($internalOrderNo, 191), + 'online_order_no' => $this->limit((string) ($payload['线上订单号'] ?? ''), 191), + 'product_code' => $this->limit((string) ($payload['商品编码'] ?? ''), 191), + 'order_status' => $this->limit((string) ($payload['订单状态'] ?? ''), 64), + 'order_date' => $this->nullableValue($payload['订单日期'] ?? ''), + 'send_date' => $this->nullableValue($payload['发货日期'] ?? ''), + 'pay_date' => $this->nullableValue($payload['付款日期'] ?? ''), + 'confirm_date' => $this->nullableValue($payload['确认收货日期'] ?? ''), + 'row_hash' => hash('sha256', json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)), + 'source_values' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), + 'source_row_number' => $sourceRowNumber, + 'imported_at' => $now, + ]; + + if (count($batch) >= self::INSERT_CHUNK) { + $flush(); + } + } + + $flush(); + + if ($rowCount === 0) { + throw new RuntimeException('导出文件中没有指定店铺的数据,已保留原有基础数据。'); + } + + $missingStores = array_keys(array_filter( + $storeCounts, + static fn (int $count): bool => $count === 0, + )); + if ($missingStores !== []) { + throw new RuntimeException('导出文件缺少指定店铺:' . implode('、', $missingStores)); + } + + if ($dryRun) { + return; + } + + $import = [ + 'company_id' => $companyId, + 'period' => $period, + 'row_count' => $rowCount, + 'store_count' => count(array_filter($storeCounts)), + 'order_count' => count($orders), + 'store_counts' => json_encode($storeCounts, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'file_name' => basename($path), + 'file_sha256' => $fileHash, + 'source_sheet' => $sheetName, + 'completed_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]; + + $connection->table('kuka_posting_base_imports')->upsert( + [$import], + ['company_id', 'period'], + [ + 'row_count', + 'store_count', + 'order_count', + 'store_counts', + 'file_name', + 'file_sha256', + 'source_sheet', + 'completed_at', + 'updated_at', + ], + ); + }; + + if ($dryRun) { + $write(); + } else { + $connection->transaction($write); + } + + return [ + 'period' => $period, + 'dry_run' => $dryRun, + 'rows' => $rowCount, + 'stores' => $storeCounts, + 'store_count' => count(array_filter($storeCounts)), + 'order_count' => count($orders), + 'skipped_store_rows' => $skippedStoreRows, + 'file_sha256' => strtolower($fileHash), + ]; + } + + private function connection(): ConnectionInterface + { + return $this->databases->connection($this->connectionName()); + } + + private function connectionName(): string + { + return (string) config('upstream_mirrors.connection', 'business_mirror'); + } + + private function normalizeDate(string $value): string + { + if ($value === '') { + return ''; + } + + if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) { + return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400)); + } + + try { + return CarbonImmutable::parse($value, 'Asia/Shanghai')->format('Y-m-d H:i:s'); + } catch (Throwable) { + throw new InvalidArgumentException('聚水潭日期格式无法识别:' . $value); + } + } + + private function nullableValue(string $value): ?string + { + return $value === '' ? null : $value; + } + + private function limit(string $value, int $length): ?string + { + $value = trim($value); + + return $value === '' ? null : mb_substr($value, 0, $length); + } +} diff --git a/app/Business/KukaPostingBase/KukaPostingBasePageData.php b/app/Business/KukaPostingBase/KukaPostingBasePageData.php new file mode 100644 index 00000000..e8979c78 --- /dev/null +++ b/app/Business/KukaPostingBase/KukaPostingBasePageData.php @@ -0,0 +1,131 @@ +, + * rows: mixed, + * filters: array, + * periods: list, + * statuses: list, + * stores: list, + * import: ?array, + * summary: array, + * error: ?string + * } + */ + public function build(Request $request, int $companyId): array + { + $stores = array_values((array) config('kuka_posting.stores', [])); + $fields = array_values((array) config('kuka_posting.fields', [])); + $available = $this->repository->available(); + $periods = $available ? $this->repository->periods($companyId) : []; + $latest = $available ? $this->repository->latestImport($companyId) : null; + + $period = trim((string) $request->query('period', '')); + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) { + $period = (string) ($latest->period ?? ($periods[0] ?? now()->format('Y-m'))); + } + + $storeName = trim((string) $request->query('store_name', '')); + if ($storeName !== '' && ! in_array($storeName, $stores, true)) { + $storeName = ''; + } + + $status = mb_substr(trim((string) $request->query('status', '')), 0, 64); + $keyword = mb_substr(trim((string) $request->query('keyword', '')), 0, 120); + $perPage = (int) $request->integer('per_page', 50); + if (! in_array($perPage, [50, 100, 200], true)) { + $perPage = 50; + } + $page = max(1, (int) $request->integer('page', 1)); + + $filters = [ + 'period' => $period, + 'store_name' => $storeName, + 'status' => $status, + 'keyword' => $keyword, + 'per_page' => $perPage, + ]; + + $error = $available ? null : '顾家过账基础数据镜像尚未建立,请先执行数据库迁移。'; + try { + $rows = $available + ? $this->repository->paginate($companyId, $period, $filters, $page, $perPage) + : new LengthAwarePaginator([], 0, $perPage, $page, [ + 'path' => $request->url(), + 'query' => $request->query(), + ]); + $rows->setCollection($rows->getCollection()->map(function (object $row): object { + $values = json_decode((string) $row->source_values, true); + if (! is_array($values)) { + $values = []; + } + $values['_row_id'] = $row->id; + + return (object) $values; + })); + $statuses = $available ? $this->repository->statuses($companyId, $period) : []; + } catch (Throwable $exception) { + report($exception); + $statuses = []; + $error = '顾家过账基础数据暂时无法读取,请稍后重试;这不代表业务数据为 0。'; + $rows = new LengthAwarePaginator([], 0, $perPage, $page, [ + 'path' => $request->url(), + 'query' => $request->query(), + ]); + } + + $import = $available ? $this->repository->importFor($companyId, $period) : null; + $importData = null; + if ($import !== null) { + $storeCounts = json_decode((string) ($import->store_counts ?? ''), true); + $importData = [ + 'period' => (string) $import->period, + 'row_count' => (int) $import->row_count, + 'store_count' => (int) $import->store_count, + 'order_count' => (int) $import->order_count, + 'store_counts' => is_array($storeCounts) ? $storeCounts : [], + 'file_name' => (string) $import->file_name, + 'file_sha256' => (string) $import->file_sha256, + 'source_sheet' => (string) $import->source_sheet, + 'completed_at' => (string) $import->completed_at, + ]; + } + + return [ + 'directory' => [ + 'icon' => 'dataset', + 'status' => $importData === null ? '尚未导入' : '聚水潭原始明细', + 'description' => '聚水潭“销售主题分析(新版)· 商品利润 · 明细(订单商品)”原始导出。仅保留指定 12 家店铺的 ' . $period . ' 数据。', + 'empty' => '该账期还没有导入顾家过账基础数据。', + 'fields' => $fields, + ], + 'rows' => $rows, + 'filters' => $filters, + 'periods' => $periods, + 'statuses' => $statuses, + 'stores' => $stores, + 'import' => $importData, + 'summary' => [ + 'filtered_rows' => $rows->total(), + 'rows' => (int) ($importData['row_count'] ?? 0), + 'stores' => (int) ($importData['store_count'] ?? 0), + 'orders' => (int) ($importData['order_count'] ?? 0), + 'completed_at' => $importData['completed_at'] ?? null, + ], + 'error' => $error, + ]; + } +} diff --git a/app/Business/KukaPostingBase/KukaPostingBaseRepository.php b/app/Business/KukaPostingBase/KukaPostingBaseRepository.php new file mode 100644 index 00000000..bfb86e6c --- /dev/null +++ b/app/Business/KukaPostingBase/KukaPostingBaseRepository.php @@ -0,0 +1,137 @@ +connectionName()); + + return $schema->hasTable('kuka_posting_base_imports') + && $schema->hasTable('kuka_posting_base_rows'); + } + + public function latestImport(int $companyId): ?object + { + if (! $this->available()) { + return null; + } + + return $this->connection() + ->table('kuka_posting_base_imports') + ->where('company_id', $companyId) + ->orderByDesc('period') + ->first(); + } + + public function importFor(int $companyId, string $period): ?object + { + if (! $this->available()) { + return null; + } + + return $this->connection() + ->table('kuka_posting_base_imports') + ->where('company_id', $companyId) + ->where('period', $period) + ->first(); + } + + /** + * @return list + */ + public function periods(int $companyId): array + { + if (! $this->available()) { + return []; + } + + return $this->connection() + ->table('kuka_posting_base_imports') + ->where('company_id', $companyId) + ->orderByDesc('period') + ->pluck('period') + ->map(static fn (mixed $period): string => (string) $period) + ->all(); + } + + /** + * @return list + */ + public function statuses(int $companyId, string $period): array + { + if (! $this->available()) { + return []; + } + + return $this->connection() + ->table('kuka_posting_base_rows') + ->where('company_id', $companyId) + ->where('period', $period) + ->whereNotNull('order_status') + ->where('order_status', '!=', '') + ->distinct() + ->orderBy('order_status') + ->pluck('order_status') + ->map(static fn (mixed $status): string => (string) $status) + ->all(); + } + + public function paginate( + int $companyId, + string $period, + array $filters, + int $page, + int $perPage, + ): LengthAwarePaginator { + $query = $this->connection() + ->table('kuka_posting_base_rows') + ->where('company_id', $companyId) + ->where('period', $period); + + $storeName = trim((string) ($filters['store_name'] ?? '')); + if ($storeName !== '') { + $query->where('store_name', $storeName); + } + + $status = trim((string) ($filters['status'] ?? '')); + if ($status !== '') { + $query->where('order_status', $status); + } + + $keyword = trim((string) ($filters['keyword'] ?? '')); + if ($keyword !== '') { + $like = '%' . addcslashes($keyword, '\\%_') . '%'; + $query->where(static function ($nested) use ($like): void { + $nested->where('internal_order_no', 'like', $like) + ->orWhere('online_order_no', 'like', $like) + ->orWhere('product_code', 'like', $like); + }); + } + + return $query + ->orderBy('source_row_number') + ->paginate($perPage, ['*'], 'page', $page) + ->withQueryString(); + } + + private function connection(): ConnectionInterface + { + return $this->databases->connection($this->connectionName()); + } + + private function connectionName(): string + { + return (string) config('upstream_mirrors.connection', 'business_mirror'); + } +} diff --git a/app/Business/XlsxSheetReader.php b/app/Business/XlsxSheetReader.php index af66ab16..c535f39f 100644 --- a/app/Business/XlsxSheetReader.php +++ b/app/Business/XlsxSheetReader.php @@ -30,7 +30,12 @@ class XlsxSheetReader * @param list> $optionalColumns 可选列:文件里有就取,没有就跳过(不报错)。 * @return Generator> */ - public function rows(string $path, array $columns, array $optionalColumns = []): Generator + public function rows( + string $path, + array $columns, + array $optionalColumns = [], + ?string $sheetName = null, + ): Generator { if (! is_file($path)) { throw new RuntimeException('订单导出文件不存在:' . $path); @@ -41,7 +46,7 @@ class XlsxSheetReader throw new RuntimeException('无法打开订单导出文件(不是有效的 xlsx):' . $path); } - $stream = $zip->getStream($this->worksheetPath($zip)); + $stream = $zip->getStream($this->worksheetPath($zip, $sheetName)); if ($stream === false) { $zip->close(); @@ -252,16 +257,43 @@ class XlsxSheetReader return $index - 1; } - private function worksheetPath(ZipArchive $zip): string + private function worksheetPath(ZipArchive $zip, ?string $sheetName = null): string { $workbook = $zip->getFromName('xl/workbook.xml'); $relationships = $zip->getFromName('xl/_rels/workbook.xml.rels'); - if (is_string($workbook) && is_string($relationships) - && preg_match('/]*r:id="([^"]+)"/', $workbook, $sheet) === 1 - && preg_match('/Id="' . preg_quote($sheet[1], '/') . '"[^>]*Target="([^"]+)"/', $relationships, $target) === 1) { - $path = ltrim($target[1], '/'); + if (is_string($workbook) && is_string($relationships)) { + $relationshipId = null; + preg_match_all('/<(?:[A-Za-z0-9_]+:)?sheet\b([^>]*)\/?>/', $workbook, $sheets); - return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path; + foreach ($sheets[1] ?? [] as $attributes) { + if (preg_match('/\bname=(["\'])(.*?)\1/s', $attributes, $name) !== 1 + || preg_match('/\br:id=(["\'])(.*?)\1/s', $attributes, $id) !== 1) { + continue; + } + + $candidateName = html_entity_decode($name[2], ENT_QUOTES | ENT_XML1, 'UTF-8'); + if ($sheetName !== null && $candidateName !== $sheetName) { + continue; + } + + $relationshipId = $id[2]; + break; + } + + if ($relationshipId !== null + && preg_match( + '/<(?:[A-Za-z0-9_]+:)?Relationship\b[^>]*\bId=(["\'])' . preg_quote($relationshipId, '/') . '\1[^>]*\bTarget=(["\'])(.*?)\2[^>]*\/?>/s', + $relationships, + $target, + ) === 1) { + $path = ltrim($target[3], '/'); + + return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path; + } + + if ($sheetName !== null) { + throw new RuntimeException('导出文件缺少工作表:' . $sheetName); + } } for ($i = 0; $i < $zip->numFiles; $i++) { diff --git a/app/Console/Commands/ImportKukaPostingBase.php b/app/Console/Commands/ImportKukaPostingBase.php new file mode 100644 index 00000000..788c1f3a --- /dev/null +++ b/app/Console/Commands/ImportKukaPostingBase.php @@ -0,0 +1,62 @@ +option('month')); + if ($period === '') { + $this->error('必须指定 --month=YYYY-MM。'); + + return self::FAILURE; + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + $period, + $this->option('sheet') ?: null, + max(1, (int) $this->option('company')), + (bool) $this->option('dry-run'), + ); + } catch (Throwable $exception) { + $this->error('顾家过账基础数据未导入,原有数据未改变。' . $exception->getMessage()); + + return self::FAILURE; + } + + $storeRows = []; + foreach ($result['stores'] as $store => $count) { + $storeRows[] = [$store, number_format($count)]; + } + + $this->table(['项目', '值'], [ + ['模式', $result['dry_run'] ? '仅校验' : '正式导入'], + ['账期', $result['period']], + ['数据行数', number_format($result['rows'])], + ['店铺数', number_format($result['store_count'])], + ['订单数', number_format($result['order_count'])], + ['非指定店铺跳过', number_format($result['skipped_store_rows'])], + ['文件 SHA-256', $result['file_sha256']], + ]); + $this->table(['店铺', '行数'], $storeRows); + $this->info($result['dry_run'] ? '顾家过账基础数据校验完成。' : '顾家过账基础数据已导入共享镜像。'); + + return self::SUCCESS; + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 33b7e360..7bd193c4 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -8,6 +8,7 @@ use App\Business\InventoryInboundDetailImporter; use App\Business\InventoryWarehouseMappingAlerts; use App\Business\InventoryWarehouseNameMappingWorkbookImporter; use App\Business\InventoryWarehouseShortNames; +use App\Business\KukaPostingBase\KukaPostingBasePageData; use App\Business\LaborExpenseWorkbookImporter; use App\Business\LaborExpenseDataStore; use App\Business\CourierPayableSummaryFilter; @@ -3956,6 +3957,14 @@ class Pages extends Controller $agreementCourierAccounts = $this->agreementCourierAccounts($page['slug'] ?? null, $agreementCourierNames); $agreementCourierContractParties = $this->agreementCourierContractParties($page['slug'] ?? null, $agreementCourierNames); $agreementSupplierOptions = $this->agreementSupplierOptions($page['slug'] ?? null); + $kukaPostingBase = null; + if (($section['slug'] ?? null) === 'posting-data' + && ($page['slug'] ?? null) === 'kuka-basic-data') { + $kukaPostingBase = app(KukaPostingBasePageData::class)->build( + request(), + (int) (company_id() ?: 1), + ); + } $staticSummaryKey = (string) ($section['slug'] ?? '') . '/' . (string) ($page['slug'] ?? ''); if (in_array($staticSummaryKey, [ @@ -4065,6 +4074,7 @@ class Pages extends Controller 'inventoryUnmappedWarehouseError' => $inventoryUnmappedWarehouseError, 'inventoryWarehouseMappingView' => $inventoryWarehouseMappingView, 'receiptStats' => $receiptStats, + 'kukaPostingBase' => $kukaPostingBase, ]; } @@ -4131,6 +4141,7 @@ class Pages extends Controller 'inventoryWarehouseMappingView' => $inventoryWarehouseMappingView, 'receiptStats' => $receiptStats, 'payablesFinal' => $this->payablesFinalData($section, $page), + 'kukaPostingBase' => $kukaPostingBase, ]; } diff --git a/config/kuka_posting.php b/config/kuka_posting.php new file mode 100644 index 00000000..8c634112 --- /dev/null +++ b/config/kuka_posting.php @@ -0,0 +1,62 @@ + '聚水潭销售主题分析(新版)/ 商品利润 / 明细(订单商品)', + 'source_sheet' => '发货明细表', + 'stores' => [ + '天猫-HX旗舰店101', + '京东-HX旗舰店101', + '京东-HX旗舰店102', + '京东-HX旗舰店103', + '京东-HX旗舰店104', + '拼多多-HX旗舰店101', + '拼多多-HX旗舰店102', + '拼多多-HX旗舰店103', + '拼多多-HX旗舰店105', + '拼多多-HX旗舰店106', + '拼多多-HX旗舰店107', + '抖音-HX旗舰店101', + ], + 'fields' => [ + ['name' => 'internal_order_no', 'source' => '内部订单号', 'label' => '内部订单号'], + ['name' => 'marked_labels', 'source' => '标记多标签', 'label' => '标记多标签'], + ['name' => 'after_sales_order_no', 'source' => '售后单号', 'label' => '售后单号'], + ['name' => 'order_type', 'source' => '订单类型', 'label' => '订单类型'], + ['name' => 'online_order_no', 'source' => '线上订单号', 'label' => '线上订单号'], + ['name' => 'order_status', 'source' => '订单状态', 'label' => '订单状态', 'kind' => 'badge'], + ['name' => 'shipping_warehouse', 'source' => '发货仓', 'label' => '发货仓'], + ['name' => 'operations_cloud_warehouse', 'source' => '运营云仓', 'label' => '运营云仓'], + ['name' => 'distributor', 'source' => '分销商', 'label' => '分销商'], + ['name' => 'owner_distribution', 'source' => '货主分销', 'label' => '货主分销'], + ['name' => 'store_name', 'source' => '店铺', 'label' => '店铺'], + ['name' => 'buyer_account', 'source' => '买家账号', 'label' => '买家账号'], + ['name' => 'seller_remark', 'source' => '卖家备注', 'label' => '卖家备注'], + ['name' => 'order_date', 'source' => '订单日期', 'label' => '订单日期', 'kind' => 'date'], + ['name' => 'shipping_date', 'source' => '发货日期', 'label' => '发货日期', 'kind' => 'date'], + ['name' => 'payment_date', 'source' => '付款日期', 'label' => '付款日期', 'kind' => 'date'], + ['name' => 'receipt_confirm_date', 'source' => '确认收货日期', 'label' => '确认收货日期', 'kind' => 'date'], + ['name' => 'province', 'source' => '省', 'label' => '省'], + ['name' => 'city', 'source' => '市', 'label' => '市'], + ['name' => 'district', 'source' => '区县', 'label' => '区县'], + ['name' => 'shipping_company', 'source' => '订单快递公司', 'label' => '订单快递公司'], + ['name' => 'shipping_tracking_no', 'source' => '订单快递单号', 'label' => '订单快递单号'], + ['name' => 'after_sales_company', 'source' => '售后快递公司', 'label' => '售后快递公司'], + ['name' => 'after_sales_tracking_no', 'source' => '售后快递单号', 'label' => '售后快递单号'], + ['name' => 'receiver_name', 'source' => '收货人', 'label' => '收货人'], + ['name' => 'after_sales_registered_at', 'source' => '售后登记日期', 'label' => '售后登记日期', 'kind' => 'date'], + ['name' => 'after_sales_confirmed_at', 'source' => '售后确认日期', 'label' => '售后确认日期', 'kind' => 'date'], + ['name' => 'receiving_warehouse', 'source' => '收货仓', 'label' => '收货仓'], + ['name' => 'after_sales_category', 'source' => '售后分类', 'label' => '售后分类'], + ['name' => 'problem_type', 'source' => '问题类型', 'label' => '问题类型'], + ['name' => 'product_code', 'source' => '商品编码', 'label' => '商品编码'], + ['name' => 'original_online_order_no', 'source' => '原始线上订单号', 'label' => '原始线上订单号'], + ['name' => 'style_code', 'source' => '款式编码', 'label' => '款式编码'], + ['name' => 'item_number', 'source' => '货号', 'label' => '货号'], + ['name' => 'material_number', 'source' => '物料编号', 'label' => '物料编号'], + ['name' => 'model', 'source' => '型号', 'label' => '型号'], + ['name' => 'cost', 'source' => '成本', 'label' => '成本', 'kind' => 'number'], + ['name' => 'product_material', 'source' => '产品材质', 'label' => '产品材质'], + ['name' => 'shipped_quantity', 'source' => '实发数量', 'label' => '实发数量', 'kind' => 'number'], + ['name' => 'shipping_amount', 'source' => '发货金额', 'label' => '发货金额', 'kind' => 'number'], + ], +]; diff --git a/database/migrations/2026_11_10_170000_create_kuka_posting_base_tables.php b/database/migrations/2026_11_10_170000_create_kuka_posting_base_tables.php new file mode 100644 index 00000000..95b28ee8 --- /dev/null +++ b/database/migrations/2026_11_10_170000_create_kuka_posting_base_tables.php @@ -0,0 +1,94 @@ +connection()); + + if (! $schema->hasTable('kuka_posting_base_imports')) { + $schema->create('kuka_posting_base_imports', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedBigInteger('company_id')->default(1); + $table->char('period', 7); + $table->unsignedInteger('row_count')->default(0); + $table->unsignedInteger('store_count')->default(0); + $table->unsignedInteger('order_count')->default(0); + $table->longText('store_counts')->nullable(); + $table->string('file_name', 255); + $table->char('file_sha256', 64); + $table->string('source_sheet', 191); + $table->timestamp('completed_at'); + $table->timestamps(); + + $table->unique(['company_id', 'period'], 'kuka_posting_import_company_period_unique'); + }); + } + + if (! $schema->hasTable('kuka_posting_base_rows')) { + $schema->create('kuka_posting_base_rows', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->unsignedBigInteger('company_id')->default(1); + $table->char('period', 7); + $table->string('store_name', 191); + $table->string('internal_order_no', 191)->nullable(); + $table->string('online_order_no', 191)->nullable(); + $table->string('product_code', 191)->nullable(); + $table->string('order_status', 64)->nullable(); + $table->dateTime('order_date')->nullable(); + $table->dateTime('send_date')->nullable(); + $table->dateTime('pay_date')->nullable(); + $table->dateTime('confirm_date')->nullable(); + $table->char('row_hash', 64); + $table->longText('source_values'); + $table->unsignedInteger('source_row_number'); + $table->timestamp('imported_at'); + + $table->unique( + ['company_id', 'period', 'source_row_number'], + 'kuka_posting_base_company_period_row_unique' + ); + $table->index( + ['company_id', 'period', 'store_name', 'source_row_number'], + 'kuka_posting_base_company_period_store' + ); + $table->index( + ['company_id', 'period', 'order_status', 'store_name'], + 'kuka_posting_base_company_period_status' + ); + $table->index( + ['company_id', 'period', 'pay_date'], + 'kuka_posting_base_company_period_pay' + ); + $table->index( + ['company_id', 'period', 'internal_order_no'], + 'kuka_posting_base_company_period_order' + ); + $table->index( + ['company_id', 'period', 'online_order_no'], + 'kuka_posting_base_company_period_online' + ); + $table->index( + ['company_id', 'period', 'product_code'], + 'kuka_posting_base_company_period_product' + ); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('kuka_posting_base_rows'); + $schema->dropIfExists('kuka_posting_base_imports'); + } +}; diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 9ad4888c..2c1fa30c 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -11,6 +11,7 @@ "dewu-bills:import-authoritative", "business-mirror:import-douyin-authoritative", "business-mirror:import-douyin-opening-balances", + "business-mirror:import-kuka-posting-base", "finance-ledger:import-company-alipay", "finance-ledger:import-wangshang-bank", "finance-ledger:import-base", diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index efda47f5..c834dd35 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -16,6 +16,7 @@ | 状态 | 说明 | | --- | --- | +| 本次接入 | 顾家过账基础数据读取聚水潭“销售主题分析(新版)→ 商品利润 → 明细(订单商品)”10 月导出,仅保留天猫、京东、拼多多和抖音的 12 家 HX 旗舰店,写入 `kuka_posting_base_rows`;导入摘要写入 `kuka_posting_base_imports`。只保存前 40 个聚水潭原始字段,后续成本映射、报价和过账分类不混入基础数据。XLSX 通过 `business-mirror:import-kuka-posting-base` 流式读取,校验 12 家店铺均有数据后,在单一事务内整月替换;文件缺失、字段错误或中断时保留上一版。当前 2026 年 10 月导出为 13,949 行。 | | 本次接入 | 钉钉考勤 `attendance/list` 按财务中心在职成员同步到 `ding_attendance_records`,保留打卡记录 ID、用户、工作日期、上下班类型、打卡结果、审批标识、审批实例和打卡时间;每 15 分钟回看 35 天,按 7 天窗口和 50 人上限分页。钉钉排班通过 `getScheduleByRange` 同步到 `ding_attendance_schedule_records`,保留逐日排班 ID、用户、考勤组、班次、是否休息、变更状态和完整源数据;本机脚本为 `scripts/sync-ding-attendance-schedules.py`,导入命令为 `business-mirror:import-ding-attendance-schedules`,默认覆盖最近 95 天,查询不完整时拒绝覆盖旧镜像。日志漏写扣分只统计钉钉排班明确为工作日的日期,并继续排除没有日志但有“请假 / 休息 / 调休”等审批标记的日期;排班或考勤镜像未完成时扣分暂不计算,周五、周末或法定班次调整均以公司真实排班为准。依赖权限 `qyapi_attendance_isv_query_result`、`qyapi_get_attendance_data`。 | | 已完成 | `operations_replica/rpt.Bulk_Price_Limit` 已进入类型化表 `product_price_mirror_rows`,商品价格页面已读取镜像并支持完整分页。 | | 已完成 | `operations_replica/rpt.jst_sku` 已进入 `ops_jst_sku`,普通商品资料页面固定读取 `sku_type = normal` 的共享镜像,并支持稳定分页和业务筛选。 | diff --git a/resources/views/business/pages/posting-data/kuka-basic-data.blade.php b/resources/views/business/pages/posting-data/kuka-basic-data.blade.php new file mode 100644 index 00000000..186dbacb --- /dev/null +++ b/resources/views/business/pages/posting-data/kuka-basic-data.blade.php @@ -0,0 +1,347 @@ +@php + $base = $kukaPostingBase ?? []; + $directory = $base['directory'] ?? ['fields' => [], 'empty' => '基础数据尚未导入。']; + $baseRows = $base['rows'] ?? collect(); + $filters = $base['filters'] ?? []; + $periods = $base['periods'] ?? []; + $statuses = $base['statuses'] ?? []; + $stores = $base['stores'] ?? []; + $import = $base['import'] ?? null; + $summary = $base['summary'] ?? []; + $error = $base['error'] ?? null; + $resetUrl = route('business.pages.show', ['section' => 'posting-data', 'page' => 'kuka-basic-data']); +@endphp + + + +
+
+
+ +
+ 顾家过账 · 基础数据 +

从聚水潭销售主题分析(新版)的“商品利润 → 明细(订单商品)”导入原始明细。这里只展示指定 12 家店铺的原始字段,不执行成本映射、报价或过账分类。

+
+
+ 聚水潭共享镜像 +
+ + @if ($error) + + @endif + +
+
+ 账期 + {{ $filters['period'] ?? '—' }} + 当前筛选账期 +
+
+ 原始数据行 + {{ number_format((int) ($summary['rows'] ?? 0)) }} + 当前筛选 {{ number_format((int) ($summary['filtered_rows'] ?? 0)) }} 行 +
+
+ 店铺 / 订单 + {{ number_format((int) ($summary['stores'] ?? 0)) }} / {{ number_format((int) ($summary['orders'] ?? 0)) }} + 仅包含指定店铺 +
+
+ 最近导入 + {{ $summary['completed_at'] ? \Illuminate\Support\Carbon::parse($summary['completed_at'])->format('Y-m-d H:i') : '尚未导入' }} + {{ $import['source_sheet'] ?? '等待首次导入' }} +
+
+ +
+ + + + + +
+ + 重置 +
+
+ + @if ($import) +
+ 来源文件:{{ $import['file_name'] }} + 工作表:{{ $import['source_sheet'] }} + SHA-256:{{ substr($import['file_sha256'], 0, 12) }}… +
+ @endif + + @include('business.pages.partials.directory-table', [ + 'directory' => $directory, + 'rows' => $baseRows, + 'section' => $section, + 'page' => $page, + 'upstreamError' => $error, + ]) +
diff --git a/tests/Feature/Business/KukaPostingBasePageTest.php b/tests/Feature/Business/KukaPostingBasePageTest.php new file mode 100644 index 00000000..e1f642ff --- /dev/null +++ b/tests/Feature/Business/KukaPostingBasePageTest.php @@ -0,0 +1,205 @@ +workbook(); + + $this->artisan('business-mirror:import-kuka-posting-base', [ + 'path' => $file, + '--month' => '2026-10', + '--company' => (string) $this->company->id, + ])->assertExitCode(0); + + $connection = DB::connection('business_mirror'); + $this->assertSame(12, $connection->table('kuka_posting_base_rows')->count()); + $this->assertDatabaseHas('kuka_posting_base_imports', [ + 'company_id' => $this->company->id, + 'period' => '2026-10', + 'row_count' => 12, + 'store_count' => 12, + ], 'business_mirror'); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'posting-data', + 'page' => 'kuka-basic-data', + 'store_name' => '天猫-HX旗舰店101', + ])) + ->assertOk() + ->assertSeeText('顾家过账 · 基础数据') + ->assertSeeText('内部订单号') + ->assertSeeText('发货金额') + ->assertSeeText('聚水潭共享镜像') + ->assertSeeText('KUKA-00') + ->assertSeeText('SKU-00') + ->assertDontSeeText('KUKA-01') + ->assertDontSeeText('SKU-01'); + + @unlink($file); + } + + public function test_incomplete_store_export_keeps_the_previous_period_data(): void + { + $complete = $this->workbook(); + $this->artisan('business-mirror:import-kuka-posting-base', [ + 'path' => $complete, + '--month' => '2026-10', + '--company' => (string) $this->company->id, + ])->assertExitCode(0); + + $incomplete = $this->workbook(skipFirstStore: true); + $this->artisan('business-mirror:import-kuka-posting-base', [ + 'path' => $incomplete, + '--month' => '2026-10', + '--company' => (string) $this->company->id, + ])->assertExitCode(1); + + $this->assertSame( + 12, + DB::connection('business_mirror')->table('kuka_posting_base_rows') + ->where('period', '2026-10') + ->count(), + ); + + @unlink($complete); + @unlink($incomplete); + } + + private function workbook(bool $skipFirstStore = false): string + { + $fields = config('kuka_posting.fields'); + $headers = array_column($fields, 'source'); + $stores = array_values(config('kuka_posting.stores')); + $rows = []; + + foreach ($stores as $index => $store) { + if ($skipFirstStore && $index === 0) { + continue; + } + + $rows[] = [ + '内部订单号' => sprintf('KUKA-%02d', $index), + '标记多标签' => '测试标签', + '售后单号' => '', + '订单类型' => '普通订单', + '线上订单号' => sprintf('ONLINE-%02d', $index), + '订单状态' => '已发货', + '发货仓' => '测试仓', + '运营云仓' => '测试云仓', + '分销商' => '', + '货主分销' => '', + '店铺' => $store, + '买家账号' => 'buyer' . $index, + '卖家备注' => '测试备注', + '订单日期' => '2026-10-01 10:00:00', + '发货日期' => '2026-10-02 11:00:00', + '付款日期' => '2026-10-01 09:30:00', + '确认收货日期' => '2026-10-05 12:00:00', + '省' => '江苏省', + '市' => '常州市', + '区县' => '新北区', + '订单快递公司' => '测试快递', + '订单快递单号' => 'EXP-' . $index, + '售后快递公司' => '', + '售后快递单号' => '', + '收货人' => '测试收货人', + '售后登记日期' => '', + '售后确认日期' => '', + '收货仓' => '', + '售后分类' => '', + '问题类型' => '', + '商品编码' => sprintf('SKU-%02d', $index), + '原始线上订单号' => sprintf('ONLINE-%02d', $index), + '款式编码' => sprintf('STYLE-%02d', $index), + '货号' => sprintf('ITEM-%02d', $index), + '物料编号' => sprintf('MAT-%02d', $index), + '型号' => '测试型号', + '成本' => '100.00', + '产品材质' => '板材', + '实发数量' => '1', + '发货金额' => '199.00', + ]; + } + + $path = tempnam(sys_get_temp_dir(), 'kuka-posting-base-') . '.xlsx'; + $zip = new ZipArchive(); + $zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE); + $zip->addFromString('xl/workbook.xml', <<<'XML' + + + + + + + +XML); + $zip->addFromString('xl/_rels/workbook.xml.rels', <<<'XML' + + + + + +XML); + $zip->addFromString('xl/worksheets/sheet1.xml', $this->worksheetXml([['汇总']])); + $zip->addFromString('xl/worksheets/sheet2.xml', $this->worksheetXml(array_merge([$headers], $rows))); + $zip->close(); + + return $path; + } + + /** + * @param list|array> $rows + */ + private function worksheetXml(array $rows): string + { + $xmlRows = []; + foreach ($rows as $rowIndex => $row) { + $cells = []; + $values = array_is_list($row) ? $row : $this->rowValues($row); + foreach ($values as $columnIndex => $value) { + $reference = $this->columnName($columnIndex + 1) . ($rowIndex + 1); + $cells[] = '' + . htmlspecialchars((string) $value, ENT_XML1 | ENT_QUOTES, 'UTF-8') + . ''; + } + $xmlRows[] = '' . implode('', $cells) . ''; + } + + return '' + . '' + . '' . implode('', $xmlRows) . ''; + } + + /** + * @param array $row + * @return list + */ + private function rowValues(array $row): array + { + return array_map( + static fn (array $field): string => (string) ($row[$field['source']] ?? ''), + config('kuka_posting.fields'), + ); + } + + private function columnName(int $index): string + { + $name = ''; + while ($index > 0) { + $index--; + $name = chr(65 + ($index % 26)) . $name; + $index = intdiv($index, 26); + } + + return $name; + } +} diff --git a/tests/Unit/Business/XlsxSheetReaderTest.php b/tests/Unit/Business/XlsxSheetReaderTest.php index cc581407..92456bf1 100644 --- a/tests/Unit/Business/XlsxSheetReaderTest.php +++ b/tests/Unit/Business/XlsxSheetReaderTest.php @@ -36,4 +36,67 @@ XML); @unlink($path); } + + public function test_it_can_select_a_named_worksheet(): void + { + $path = tempnam(sys_get_temp_dir(), 'xlsx-named-sheet') . '.xlsx'; + $zip = new ZipArchive(); + $zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE); + $zip->addFromString('xl/workbook.xml', <<<'XML' + + + + + + + +XML); + $zip->addFromString('xl/_rels/workbook.xml.rels', <<<'XML' + + + + + +XML); + $zip->addFromString('xl/worksheets/sheet1.xml', <<<'XML' + + + + 汇总 + 不是明细 + + +XML); + $zip->addFromString('xl/worksheets/sheet2.xml', <<<'XML' + + + + + 店铺 + 商品编码 + + + 天猫-HX旗舰店101 + SKU-NAMED + + + +XML); + $zip->close(); + + $rows = iterator_to_array((new XlsxSheetReader())->rows( + $path, + ['店铺', '商品编码'], + [], + '发货明细表', + )); + + $this->assertSame( + [['店铺' => '天猫-HX旗舰店101', '商品编码' => 'SKU-NAMED']], + $rows, + ); + + @unlink($path); + } } From d2439b3be8ab80a7a16ee98119edbc6b3c438e27 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Tue, 10 Nov 2026 17:12:10 +0800 Subject: [PATCH 11/12] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E6=8A=96?= =?UTF-8?q?=E9=9F=B3=E4=B9=90=E7=AE=80=E5=BA=97=E9=93=BA=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=20(#1050)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Repositories/DouyinAuthoritativeBillRepository.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php index 1de0c582..be3f4692 100644 --- a/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php +++ b/modules/EcommerceFinance/Repositories/DouyinAuthoritativeBillRepository.php @@ -26,7 +26,7 @@ class DouyinAuthoritativeBillRepository 'balance' => 287706.90, 'source' => 'merchant_backoffice_june_ending', ], - '亿家达乐简家具专卖店' => [ + '抖音-亿家达乐简家具专卖店' => [ 'balance' => 0.0, 'source' => 'merchant_backoffice_zero', ], From c9f84ccea970cac9946c288829754ae2866eabe3 Mon Sep 17 00:00:00 2001 From: chenxi Date: Tue, 10 Nov 2026 17:18:23 +0800 Subject: [PATCH 12/12] =?UTF-8?q?fix:=20=E7=B3=BB=E7=BB=9F=E5=8C=96?= =?UTF-8?q?=E5=BE=85=E5=8A=9E=E5=88=9B=E5=BB=BA=E6=97=B6=E9=97=B4=E6=8C=89?= =?UTF-8?q?=E4=B8=8A=E6=B5=B7=E6=97=B6=E5=8C=BA=E6=98=BE=E7=A4=BA=20(#1052?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Models/Business/SystemizationTodo.php | 14 +++++++ .../pages/systemization-todos.blade.php | 2 +- .../Business/SystemizationTodosTest.php | 39 ++++++++++++++++++- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/app/Models/Business/SystemizationTodo.php b/app/Models/Business/SystemizationTodo.php index c53a1ce8..92ef4109 100644 --- a/app/Models/Business/SystemizationTodo.php +++ b/app/Models/Business/SystemizationTodo.php @@ -93,6 +93,20 @@ class SystemizationTodo extends Model return $this->belongsTo(User::class, 'created_by')->withTrashed(); } + public function creationTimeLabel(): string + { + if ($this->created_at === null) { + return ''; + } + + $timezone = (string) config('app.platform_timezone', config('app.timezone', 'Asia/Shanghai')); + if ($timezone === '') { + $timezone = 'Asia/Shanghai'; + } + + return $this->created_at->copy()->setTimezone($timezone)->format('Y-m-d H:i'); + } + public function attachments(): HasMany { return $this->hasMany(SystemizationTodoAttachment::class, 'systemization_todo_id') diff --git a/resources/views/business/pages/systemization-todos.blade.php b/resources/views/business/pages/systemization-todos.blade.php index 9679939a..d4aa5a88 100644 --- a/resources/views/business/pages/systemization-todos.blade.php +++ b/resources/views/business/pages/systemization-todos.blade.php @@ -767,7 +767,7 @@
{{ $item->creator?->name ?: '—' }} - {{ $item->created_at?->format('Y-m-d H:i') ?: '—' }} + {{ $item->creationTimeLabel() ?: '—' }} @php($ownerNames = $personNames($item->owner_display ?? null)) created_by; $createdAt = $todo->created_at->format('Y-m-d H:i:s'); - $displayedCreatedAt = $todo->created_at->format('Y-m-d H:i'); + $displayedCreatedAt = $todo->creationTimeLabel(); $this->get(route('business.pages.show', [ 'section' => 'other', @@ -1402,6 +1402,43 @@ class SystemizationTodosTest extends FeatureTestCase } } + public function test_creation_time_is_displayed_in_the_platform_timezone(): void + { + $originalTimezone = config('app.timezone'); + $originalPlatformTimezone = config('app.platform_timezone'); + + try { + config([ + 'app.timezone' => 'Europe/London', + 'app.platform_timezone' => 'Asia/Shanghai', + ]); + date_default_timezone_set('Europe/London'); + Carbon::setTestNow('2026-11-10 08:21:30'); + + $this->loginAs(); + $todo = $this->createTodo('收入', '创建时间测试', '创建时间按上海展示', '2026-11-12', 1); + $todo->refresh(); + + $this->assertSame('2026-11-10 08:21', $todo->created_at->format('Y-m-d H:i')); + $this->assertSame('2026-11-10 16:21', $todo->creationTimeLabel()); + + $this->get(route('business.pages.show', [ + 'section' => 'other', + 'page' => 'systemization-todos', + ]))->assertOk()->assertSee( + 'data-sys-todo-immutable="created_at">2026-11-10 16:21', + false, + ); + } finally { + Carbon::setTestNow(); + config([ + 'app.timezone' => $originalTimezone, + 'app.platform_timezone' => $originalPlatformTimezone, + ]); + date_default_timezone_set((string) $originalTimezone); + } + } + public function test_edit_redirect_keeps_current_filters_and_highlight(): void { $this->loginAs();