From 55f3e7d10f9889531f3ca36d0f1d6aa70575de11 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Fri, 6 Nov 2026 11:37:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8B=BC=E5=A4=9A=E5=A4=9A=E8=B4=A6?= =?UTF-8?q?=E6=88=B7=E6=8C=89=E5=B9=B3=E5=8F=B0=E4=BD=99=E9=A2=9D=E6=BB=9A?= =?UTF-8?q?=E5=8A=A8=E8=AE=A1=E7=AE=97=E6=9C=9F=E5=88=9D=E6=9C=9F=E6=9C=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 以6月平台实际期末余额为基准,按财务系统每月收支滚动计算期初余额;期末余额=期初余额+收入合计-支出合计。 --- .../ImportPinduoduoPlatformBalances.php | 51 +++++ ..._create_pdd_platform_balance_snapshots.php | 49 +++++ docs/拼多多余额接入.md | 18 ++ .../Controllers/PinduoduoAccountBills.php | 10 +- .../PinduoduoSettlementBillRepository.php | 117 ++++++++-- .../PinduoduoPlatformBalanceImporter.php | 200 ++++++++++++++++++ .../js/components/business/AccountBills.vue | 19 +- .../Business/PinduoduoReceivingBillsTest.php | 13 +- .../PinduoduoPlatformBalanceImporterTest.php | 82 +++++++ ...uoSettlementAccountBillsRepositoryTest.php | 71 +++++++ tests/Unit/View/AccountBillsTableTest.php | 16 ++ 11 files changed, 630 insertions(+), 16 deletions(-) create mode 100644 app/Console/Commands/ImportPinduoduoPlatformBalances.php create mode 100644 database/migrations/2026_11_06_110000_create_pdd_platform_balance_snapshots.php create mode 100644 docs/拼多多余额接入.md create mode 100644 modules/EcommerceFinance/Services/PinduoduoPlatformBalanceImporter.php create mode 100644 tests/Unit/EcommerceFinance/PinduoduoPlatformBalanceImporterTest.php diff --git a/app/Console/Commands/ImportPinduoduoPlatformBalances.php b/app/Console/Commands/ImportPinduoduoPlatformBalances.php new file mode 100644 index 00000000..f4fb54d5 --- /dev/null +++ b/app/Console/Commands/ImportPinduoduoPlatformBalances.php @@ -0,0 +1,51 @@ +option('period-end')); + if ($periodEnd === '') { + $this->error('缺少 --period-end。'); + + return self::FAILURE; + } + + try { + $result = $importer->import((string) $this->argument('path'), $periodEnd); + } catch (InvalidArgumentException|RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('拼多多平台期末余额导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['截止日期', '店铺数', '余额合计', '替换旧行数', '来源文件'], [[ + $result['period_end'], + $result['total'], + $result['balance_total'], + $result['replaced'], + $result['source_filename'], + ]]); + + return self::SUCCESS; + } +} diff --git a/database/migrations/2026_11_06_110000_create_pdd_platform_balance_snapshots.php b/database/migrations/2026_11_06_110000_create_pdd_platform_balance_snapshots.php new file mode 100644 index 00000000..7b4d196f --- /dev/null +++ b/database/migrations/2026_11_06_110000_create_pdd_platform_balance_snapshots.php @@ -0,0 +1,49 @@ +connection()); + if ($schema->hasTable(self::TABLE)) { + return; + } + + $schema->create(self::TABLE, function (Blueprint $table): void { + $table->id(); + $table->date('period_end'); + $table->string('store_name'); + $table->string('normalized_store_name'); + $table->string('account_name')->nullable(); + $table->decimal('balance', 20, 6); + $table->string('source_filename'); + $table->char('source_sha256', 64); + $table->dateTime('imported_at', 6); + $table->timestamps(6); + + $table->unique( + ['period_end', 'normalized_store_name'], + 'pdd_platform_balance_period_store_uq', + ); + }); + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + if ($schema->hasTable(self::TABLE)) { + $schema->dropIfExists(self::TABLE); + } + } + + private function connection(): string + { + return (string) config('upstream_mirrors.connection', 'business_mirror'); + } +}; diff --git a/docs/拼多多余额接入.md b/docs/拼多多余额接入.md new file mode 100644 index 00000000..39571888 --- /dev/null +++ b/docs/拼多多余额接入.md @@ -0,0 +1,18 @@ +# 拼多多账户余额 + +财务系统「店铺收款账户账单 › 拼多多账户」的期初余额以拼多多平台实际期末余额为锚点,按月滚动: + +- 2026 年 7 月期初余额取 `2026-06-30` 的平台实际期末余额。 +- 后续月份期初余额取上一账期的期末余额。 +- 期末余额统一按“期初余额 + 收入合计 - 支出合计”计算。 +- 切换月份、店铺或账单项目筛选时,期初余额仍按所选月份的上一账期截止日展示。 + +平台余额基准存放在共享业务镜像 `pdd_platform_balance_snapshots`。导入命令: + +```bash +php artisan business-mirror:import-pdd-platform-balances --period-end=2026-06-30 +``` + +余额截止日期必须是月末。导入按店铺名称规范化后去重,同一账期原子替换;实际财务数据、原始文件和导出记录只放被 Git 忽略的 `runtime/private/`,不进入仓库。 + +店铺匹配使用去掉“拼多多-”平台前缀并统一空白后的名称。平台余额表存在、财务账单不存在,以及财务账单存在、平台余额表不存在的店铺都需要单独核对,不自动合并相似名称。 diff --git a/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php b/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php index 55a326a0..5c0c520f 100644 --- a/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/PinduoduoAccountBills.php @@ -50,7 +50,15 @@ class PinduoduoAccountBills extends Controller 'current_page' => 1, 'last_page' => 1, 'per_page' => (int) ($validated['limit'] ?? 10), - 'summary' => ['income' => 0, 'expense' => 0, 'balance' => 0, 'count' => 0], + 'summary' => [ + 'income' => 0, + 'expense' => 0, + 'opening_balance' => null, + 'opening_balance_date' => null, + 'opening_balance_source' => null, + 'balance' => null, + 'count' => 0, + ], 'columns' => AccountBillColumns::for('pinduoduo'), ], 503); } diff --git a/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php b/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php index 55ad3aa5..7bf58773 100644 --- a/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/PinduoduoSettlementBillRepository.php @@ -6,6 +6,7 @@ use DateTimeImmutable; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\LedgerRemarkFilter; use RuntimeException; @@ -14,6 +15,8 @@ class PinduoduoSettlementBillRepository { private const IMPORT_TABLE = 'pdd_settlement_bill_imports'; private const ROW_TABLE = 'pdd_settlement_bill_rows'; + private const BALANCE_SNAPSHOT_TABLE = 'pdd_platform_balance_snapshots'; + private const OPENING_BALANCE_CACHE_SECONDS = 300; private readonly ConnectionInterface $connection; @@ -128,13 +131,8 @@ class PinduoduoSettlementBillRepository $query = $this->query(); $this->applyAccountBillFilters($query, $filters); - $summary = (clone $query)->selectRaw( - 'COALESCE(SUM(income_amount), 0) AS income_total, ' - . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' - )->first(); - $total = (int) ($summary->row_count ?? 0); - $income = (float) ($summary->income_total ?? 0); - $expense = (float) ($summary->expense_total ?? 0); + $summary = $this->summaryForQuery($query, $filters); + $total = $summary['count']; $sortColumn = $this->accountBillSortColumn($sort); $direction = $direction === 'asc' ? 'asc' : 'desc'; @@ -155,12 +153,34 @@ class PinduoduoSettlementBillRepository 'per_page' => $perPage, 'from' => $total === 0 ? null : (($page - 1) * $perPage) + 1, 'to' => $total === 0 ? null : min($page * $perPage, $total), - 'summary' => [ - 'income' => $income, - 'expense' => $expense, - 'balance' => round($income - $expense, 2), - 'count' => $total, - ], + 'summary' => $summary, + ]; + } + + /** + * @return array{ + * income:float,expense:float,opening_balance:float,opening_balance_date:?string, + * opening_balance_source:string,balance:float,count:int + * } + */ + private function summaryForQuery(Builder $query, array $filters): array + { + $row = (clone $query)->selectRaw( + 'COALESCE(SUM(income_amount), 0) AS income_total, ' + . 'COALESCE(SUM(expense_amount), 0) AS expense_total, COUNT(*) AS row_count' + )->first(); + $income = round((float) ($row->income_total ?? 0), 2); + $expense = round((float) ($row->expense_total ?? 0), 2); + $opening = $this->openingBalance($filters); + + return [ + 'income' => $income, + 'expense' => $expense, + 'opening_balance' => $opening['balance'], + 'opening_balance_date' => $opening['date'], + 'opening_balance_source' => $opening['source'], + 'balance' => round($opening['balance'] + $income - $expense, 2), + 'count' => (int) ($row->row_count ?? 0), ]; } @@ -281,6 +301,77 @@ class PinduoduoSettlementBillRepository ][$sort] ?? 'occurred_at'; } + /** + * 以最近一次平台实际期末余额为锚点,滚动计算所选账期的期初余额。 + * + * @return array{balance:float,date:?string,source:string} + */ + private function openingBalance(array $filters): array + { + $start = $this->date(isset($filters['start']) ? (string) $filters['start'] : null) + ?? $this->date(isset($filters['end']) ? (string) $filters['end'] : null); + if ($start === null) { + return ['balance' => 0.0, 'date' => null, 'source' => 'none']; + } + + $monthStart = $start->modify('first day of this month')->setTime(0, 0); + $balanceDate = $this->connection->table(self::BALANCE_SNAPSHOT_TABLE) + ->where('period_end', '<', $monthStart->format('Y-m-d')) + ->orderBy('period_end') + ->value('period_end'); + if ($balanceDate === null) { + return ['balance' => 0.0, 'date' => null, 'source' => 'none']; + } + + $store = trim((string) ($filters['store_name'] ?? '')); + $snapshotVersion = (string) ($this->connection->table(self::BALANCE_SNAPSHOT_TABLE) + ->max('imported_at') ?? ''); + $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) + ->where('status', 'succeeded') + ->max('updated_at') ?? ''); + $cacheKey = 'pdd-opening-balance:v1:' . hash('sha256', implode('|', [ + $monthStart->format('Y-m-d'), + $balanceDate, + $store, + $snapshotVersion, + $importVersion, + ])); + + $balance = Cache::remember( + $cacheKey, + self::OPENING_BALANCE_CACHE_SECONDS, + function () use ($monthStart, $balanceDate, $store): float { + $baseline = $this->connection->table(self::BALANCE_SNAPSHOT_TABLE) + ->where('period_end', $balanceDate) + ->when( + $store !== '', + fn (Builder $query) => $query->where( + 'normalized_store_name', + JushuitanShopBalanceRepository::normalizeStoreName($store), + ), + ) + ->sum('balance'); + + $movement = $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $balanceDate . ' 00:00:00') + ->where('occurred_at', '<', $monthStart->format('Y-m-d') . ' 00:00:00') + ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) + ->selectRaw('COALESCE(SUM(income_amount - expense_amount), 0) AS net_total') + ->first(); + + return round((float) $baseline + (float) ($movement->net_total ?? 0), 2); + }, + ); + + $date = $monthStart->modify('-1 day')->format('Y-m-d'); + + return [ + 'balance' => (float) $balance, + 'date' => $date, + 'source' => $date === $balanceDate ? 'platform_snapshot' : 'previous_period', + ]; + } + /** @return array */ private function mapAccountBillRow(object $row): array { diff --git a/modules/EcommerceFinance/Services/PinduoduoPlatformBalanceImporter.php b/modules/EcommerceFinance/Services/PinduoduoPlatformBalanceImporter.php new file mode 100644 index 00000000..6ee3b9fe --- /dev/null +++ b/modules/EcommerceFinance/Services/PinduoduoPlatformBalanceImporter.php @@ -0,0 +1,200 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{period_end:string,total:int,balance_total:string,replaced:int,source_filename:string} + */ + public function import(string $path, string $periodEnd): array + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new InvalidArgumentException('拼多多平台余额文件不存在或不可读取。'); + } + + $period = $this->periodEnd($periodEnd); + if (! Schema::connection($this->connection->getName())->hasTable(self::TABLE)) { + throw new RuntimeException('拼多多平台余额表尚未完成迁移。'); + } + + $rows = $this->normalizeRows($this->matrix($realPath)); + if ($rows === []) { + throw new InvalidArgumentException('拼多多平台余额文件中没有可导入的店铺数据。'); + } + + $sourceName = mb_substr(basename($realPath), 0, 255); + $sourceSha = hash_file('sha256', $realPath); + $now = now(); + $replaced = $this->connection->table(self::TABLE) + ->where('period_end', $period) + ->count(); + + $this->connection->transaction(function () use ($rows, $period, $sourceName, $sourceSha, $now): void { + $this->connection->table(self::TABLE)->where('period_end', $period)->delete(); + foreach (array_chunk($rows, 500) as $chunk) { + $this->connection->table(self::TABLE)->insert(array_map( + static fn (array $row): array => $row + [ + 'period_end' => $period, + 'source_filename' => $sourceName, + 'source_sha256' => $sourceSha, + 'imported_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + $chunk, + )); + } + }); + + $balanceTotal = '0.00'; + foreach ($rows as $row) { + $balanceTotal = bcadd($balanceTotal, $row['balance'], 2); + } + + return [ + 'period_end' => $period, + 'total' => count($rows), + 'balance_total' => $balanceTotal, + 'replaced' => $replaced, + 'source_filename' => $sourceName, + ]; + } + + public function periodEnd(string $value): string + { + $date = DateTimeImmutable::createFromFormat('!Y-m-d', trim($value)); + if ($date === false || $date->format('Y-m-d') !== $value || $date->format('Y-m-t') !== $value) { + throw new InvalidArgumentException('平台余额截止日期必须是有效月末,格式 YYYY-MM-DD。'); + } + + return $value; + } + + /** @return list */ + private function normalizeRows(array $matrix): array + { + $header = null; + foreach (array_slice($matrix, 0, 20, true) as $rowNumber => $row) { + $labels = array_map(static fn (mixed $value): string => trim((string) $value), $row); + if (in_array('店铺', $labels, true) + && in_array('平台实际期末余额', $labels, true)) { + $header = ['row' => $rowNumber, 'labels' => $labels]; + break; + } + } + if ($header === null) { + throw new InvalidArgumentException('文件中未找到“店铺”和“平台实际期末余额”表头。'); + } + + $indexes = array_flip($header['labels']); + $storeIndex = $indexes['店铺']; + $balanceIndex = $indexes['平台实际期末余额']; + $platformIndex = $indexes['平台'] ?? null; + $accountIndex = $indexes['来源'] ?? null; + $rows = []; + + foreach ($matrix as $rowNumber => $row) { + if ($rowNumber <= $header['row']) { + continue; + } + $storeName = trim((string) ($row[$storeIndex] ?? '')); + if ($storeName === '') { + continue; + } + if ($platformIndex !== null && trim((string) ($row[$platformIndex] ?? '')) !== '拼多多') { + continue; + } + + $balance = $this->amount($row[$balanceIndex] ?? null, $storeName); + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + if ($normalized === '') { + throw new InvalidArgumentException('存在无法识别的拼多多店铺名称。'); + } + if (isset($rows[$normalized]) && bccomp($rows[$normalized]['balance'], $balance, 2) !== 0) { + throw new InvalidArgumentException("店铺 {$storeName} 存在冲突的平台期末余额。"); + } + $rows[$normalized] = [ + 'store_name' => mb_substr($storeName, 0, 255), + 'normalized_store_name' => mb_substr($normalized, 0, 255), + 'account_name' => $accountIndex === null + ? null + : mb_substr(trim((string) ($row[$accountIndex] ?? '')), 0, 255), + 'balance' => $balance, + ]; + } + + return array_values($rows); + } + + private function amount(mixed $value, string $storeName): string + { + $raw = trim(str_replace([',', ',', '¥', '¥'], '', (string) $value)); + if ($raw === '' || ! is_numeric($raw)) { + throw new InvalidArgumentException("店铺 {$storeName} 的平台实际期末余额无效。"); + } + + return number_format((float) $raw, 2, '.', ''); + } + + /** @return list> */ + private function matrix(string $path): array + { + $extension = strtolower((string) pathinfo($path, PATHINFO_EXTENSION)); + if ($extension === 'csv') { + $handle = fopen($path, 'rb'); + if ($handle === false) { + throw new InvalidArgumentException('无法读取拼多多平台余额 CSV。'); + } + $rows = []; + try { + $first = fgets($handle); + if ($first !== false && str_starts_with($first, "\xEF\xBB\xBF")) { + rewind($handle); + fread($handle, 3); + } else { + rewind($handle); + } + while (($row = fgetcsv($handle)) !== false) { + $rows[] = $row; + } + } finally { + fclose($handle); + } + + return $rows; + } + + if (! in_array($extension, ['xlsx', 'xls'], true)) { + throw new InvalidArgumentException('拼多多平台余额仅支持 XLSX、XLS 或 CSV 文件。'); + } + + $spreadsheet = IOFactory::load($path); + try { + return $spreadsheet->getActiveSheet()->toArray(null, true, true, false); + } finally { + $spreadsheet->disconnectWorksheets(); + } + } +} diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index 5988a304..ffc2e428 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -7,6 +7,7 @@ 'tw-stats--promotion-compact': compact, 'tw-stats--taobao-wechat': billType === 'taobao-wechat', 'tw-stats--jd-wallet': billType === 'jd-wallet', + 'tw-stats--pinduoduo': billType === 'pinduoduo', }" >