From d38e6c506651d5a3f7901cbbbfa89f7428395bea Mon Sep 17 00:00:00 2001 From: qiuxiang Date: Fri, 6 Nov 2026 15:43:58 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E5=B0=8F=E7=BA=A2?= =?UTF-8?q?=E4=B9=A6=E8=B4=A6=E6=88=B7=E8=B4=A6=E5=8D=95=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E4=B8=8E=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ImportXiaohongshuSettlementBills.php | 73 +++ config/business_navigation.php | 1 + deploy/finance-batch-imports.json | 1 + .../EcommerceFinance/AccountBillColumns.php | 20 + .../Http/Controllers/AccountBills.php | 11 +- .../Services/AccountLedgerRemarkMap.php | 4 + .../XiaohongshuSettlementBillImporter.php | 510 ++++++++++++++++++ .../js/components/business/AccountBills.vue | 6 +- resources/assets/js/views/business/pages.js | 6 +- .../XiaohongshuReceivingBillsTest.php | 128 +++++ .../XiaohongshuSettlementBillImporterTest.php | 214 ++++++++ tests/Unit/View/AccountBillsTableTest.php | 10 +- 12 files changed, 970 insertions(+), 14 deletions(-) create mode 100644 app/Console/Commands/ImportXiaohongshuSettlementBills.php create mode 100644 modules/EcommerceFinance/Services/XiaohongshuSettlementBillImporter.php create mode 100644 tests/Feature/Business/XiaohongshuReceivingBillsTest.php create mode 100644 tests/Feature/Console/XiaohongshuSettlementBillImporterTest.php diff --git a/app/Console/Commands/ImportXiaohongshuSettlementBills.php b/app/Console/Commands/ImportXiaohongshuSettlementBills.php new file mode 100644 index 00000000..e29c7f89 --- /dev/null +++ b/app/Console/Commands/ImportXiaohongshuSettlementBills.php @@ -0,0 +1,73 @@ +option($option)) === '') { + $this->error("缺少 --{$option},导入必须提供账期和三项权威控制数。"); + + return self::FAILURE; + } + } + + try { + $result = $importer->import( + (string) $this->argument('path'), + (int) $this->option('company-id'), + (string) $this->option('from'), + (string) $this->option('to'), + (int) $this->option('expected-count'), + (string) $this->option('expected-income'), + (string) $this->option('expected-expense'), + (int) $this->option('batch'), + ); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + report($exception); + $this->error('小红书订单结算明细导入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->table(['状态', '账单行数', '店铺数', '账单项目数', '收入', '支出', '收支净额', '账期'], [[ + $result['status'], + $result['row_count'], + $result['store_count'], + $result['bill_item_count'], + $result['income_total'], + $result['expense_total'], + $result['net_total'], + $result['period_start'] . ' 至 ' . $result['period_end'], + ]]); + $this->line('交易类型:' . collect($result['transaction_type_counts']) + ->map(fn (int $count, string $type): string => "{$type} {$count}") + ->implode(';')); + $this->line('SHA-256: ' . $result['source_sha256']); + + return self::SUCCESS; + } +} diff --git a/config/business_navigation.php b/config/business_navigation.php index f0b78353..db8b9dac 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -554,6 +554,7 @@ $navigation = [ ['slug' => 'dewu', 'title' => '得物账户'], ['slug' => 'vipshop', 'title' => '唯品会MP账户'], ['slug' => 'vipshop-jx', 'title' => '唯品会JX账户'], + ['slug' => 'xiaohongshu', 'title' => '小红书账户'], ], ], [ diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index ca2b4441..a2ade4ee 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -35,5 +35,6 @@ "business:import-taobao-alipay-bills", "taobao-alipay-bills:import-authoritative", "taobao-wechat-bills:import-authoritative", + "xiaohongshu-bills:import", "business-mirror:import-third-party-warehouse-anchor" ] diff --git a/modules/EcommerceFinance/AccountBillColumns.php b/modules/EcommerceFinance/AccountBillColumns.php index a220fae8..d719fa97 100644 --- a/modules/EcommerceFinance/AccountBillColumns.php +++ b/modules/EcommerceFinance/AccountBillColumns.php @@ -115,6 +115,26 @@ class AccountBillColumns ['合计金额', 'amount', 'money'], ], ], + 'xiaohongshu' => [ + 'title' => '小红书账户', + 'columns' => [ + ['记录编码', 'record_code', 'num'], + ['店铺', 'store_name', 'text'], + ['账单项目', 'bill_item', 'tag'], + ['线上单号', 'payload.online_order_no', 'num'], + ['交易类型', 'payload.transaction_type', 'text'], + ['订单号', 'order_no', 'num'], + ['售后单号', 'payload.after_sale_no', 'num'], + ['下单时间', 'payload.ordered_at', 'date'], + ['结算时间', 'occurred_at', 'date'], + ['收入金额', 'income', 'money_in'], + ['支出金额', 'expense', 'money_out'], + ['账单备注', 'payload.bill_remark', 'text'], + ['创建时间', 'payload.source_created_at', 'date'], + ['修改时间', 'payload.source_updated_at', 'date'], + ['修改人', 'modifier', 'text'], + ], + ], 'taobao-wechat' => [ 'title' => '淘系微信账户', 'groups' => [ diff --git a/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index 03a6cf88..31707bbc 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -105,8 +105,8 @@ class AccountBills extends Controller 'income' => $income, 'expense' => $expense, 'count' => (int) ($summaryRow->count ?? 0), - // 唯品会JX账单没有账户余额列,该页签以收支净额作为汇总口径。 - 'balance' => $billType === 'vipshop-jx' + // 唯品会JX、小红书账单没有账户余额列,以收支净额作为汇总口径。 + 'balance' => in_array($billType, ['vipshop-jx', 'xiaohongshu'], true) ? round($income - $expense, 2) : ($latestBalance !== null ? (float) $latestBalance : 0), ]; @@ -287,7 +287,7 @@ class AccountBills extends Controller $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab($bill_type); - if (in_array($bill_type, ['vipshop', 'vipshop-jx'], true)) { + if (in_array($bill_type, ['vipshop', 'vipshop-jx', 'xiaohongshu'], true)) { $query = AccountBill::query() ->where('company_id', company_id()) ->where('bill_type', $bill_type); @@ -354,6 +354,10 @@ class AccountBills extends Controller private function exportQuery(Request $request, $query, string $billType) { + $exportToken = $this->exportProgressToken($request); + $exportTotal = max(0, (int) $request->get('total', 0)); + $this->putExportProgress($exportToken, 0, $exportTotal); + $definition = AccountBillColumns::for($billType); $available = collect($definition['columns'] ?? [])->keyBy('field'); $requested = $request->input('columns', []); @@ -792,6 +796,7 @@ class AccountBills extends Controller 'taobao-wechat' => '淘系微信账户', 'vipshop' => '唯品会MP账户', 'vipshop-jx' => '唯品会JX账户', + 'xiaohongshu' => '小红书账户', 'douyin' => '抖音账户', default => $billType, }; diff --git a/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php b/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php index 883b2440..4a585d68 100644 --- a/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php +++ b/modules/EcommerceFinance/Services/AccountLedgerRemarkMap.php @@ -32,6 +32,7 @@ class AccountLedgerRemarkMap 'dewu' => '得物', 'vipshop' => '唯品会MP', 'vipshop-jx' => '唯品会jx', + 'xiaohongshu' => '小红书', ]; /** @@ -51,6 +52,7 @@ class AccountLedgerRemarkMap 'dewu' => ['得物'], 'vipshop' => ['唯品会MP'], 'vipshop-jx' => ['唯品会jx'], + 'xiaohongshu' => ['小红书'], ]; /** 页签账单表里可作「业务备注关键词」匹配的列(折算筛选 SQL 用;列不存在时自动跳过)。 */ @@ -65,6 +67,7 @@ class AccountLedgerRemarkMap 'douyin' => [], 'vipshop' => [], 'vipshop-jx' => [], + 'xiaohongshu' => [], ]; /** 页签账单表里可作「商品名称关键词」匹配的列。 */ @@ -77,6 +80,7 @@ class AccountLedgerRemarkMap private const STORE_PREFIX_PLATFORMS = [ '唯品会JX' => '唯品会jx', '唯品会MP' => '唯品会MP', + '小红书' => '小红书', '阿里巴巴' => '阿里巴巴', // 1688 系店铺:新佰广1688 / 1688xxx 等店铺名不带「阿里巴巴」前缀, // 按平台口径归到阿里巴巴,账单项目与阿里巴巴一致(阿里-xxx 仍走上面的前缀)。 diff --git a/modules/EcommerceFinance/Services/XiaohongshuSettlementBillImporter.php b/modules/EcommerceFinance/Services/XiaohongshuSettlementBillImporter.php new file mode 100644 index 00000000..50883545 --- /dev/null +++ b/modules/EcommerceFinance/Services/XiaohongshuSettlementBillImporter.php @@ -0,0 +1,510 @@ + '记录编码', + 'store_name' => '店铺', + 'bill_item' => '账单项目', + 'online_order_no' => '线上单号', + 'transaction_type' => '交易类型', + 'order_no' => '订单号', + 'after_sale_no' => '售后单号', + 'ordered_at' => '下单时间', + 'occurred_at' => '结算时间', + 'income' => '收入金额', + 'expense' => '支出金额', + 'bill_remark' => '账单备注', + 'source_created_at' => '创建时间', + 'source_updated_at' => '修改时间', + 'modifier' => '修改人', + ]; + + /** + * @return array{status:string,row_count:int,store_count:int,bill_item_count:int,transaction_type_counts:array,income_total:string,expense_total:string,net_total:string,period_start:string,period_end:string,source_sha256:string} + */ + public function import( + string $path, + int $companyId, + string $fromDate, + string $toDate, + int $expectedCount, + string $expectedIncome, + string $expectedExpense, + int $batchSize = 500, + ): array { + $path = $this->validatedPath($path); + [$from, $to] = $this->period($fromDate, $toDate); + if ($companyId <= 0) { + throw new RuntimeException('公司 ID 必须大于零。'); + } + if ($expectedCount <= 0) { + throw new RuntimeException('权威笔数控制数必须大于零。'); + } + $expectedIncome = $this->controlAmount($expectedIncome, '收入'); + $expectedExpense = $this->controlAmount($expectedExpense, '支出'); + $batchSize = min(max($batchSize, 100), 2000); + + if (! Schema::hasTable(self::TABLE)) { + throw new RuntimeException('通用账户账单表尚未完成迁移:' . self::TABLE); + } + + $hash = hash_file('sha256', $path); + if (! is_string($hash)) { + throw new RuntimeException('无法计算小红书订单结算明细文件摘要。'); + } + + $temporary = tempnam(sys_get_temp_dir(), 'xiaohongshu-settlement-'); + if ($temporary === false) { + throw new RuntimeException('无法创建小红书账单导入缓冲文件。'); + } + $handle = fopen($temporary, 'wb'); + if ($handle === false) { + @unlink($temporary); + throw new RuntimeException('无法写入小红书账单导入缓冲文件。'); + } + + try { + $stats = $this->stageToJsonLines($path, $handle, $from, $to); + fclose($handle); + $handle = null; + + $this->assertControls($stats, $expectedCount, $expectedIncome, $expectedExpense); + $this->replacePeriod($temporary, $companyId, $from, $to, $batchSize); + } finally { + if (is_resource($handle)) { + fclose($handle); + } + @unlink($temporary); + } + + return [ + 'status' => 'succeeded', + 'row_count' => $stats['row_count'], + 'store_count' => $stats['store_count'], + 'bill_item_count' => $stats['bill_item_count'], + 'transaction_type_counts' => $stats['transaction_type_counts'], + 'income_total' => $stats['income_total'], + 'expense_total' => $stats['expense_total'], + 'net_total' => $stats['net_total'], + 'period_start' => $from->format('Y-m-d'), + 'period_end' => $to->format('Y-m-d'), + 'source_sha256' => $hash, + ]; + } + + private function validatedPath(string $path): string + { + $realPath = realpath($path); + if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) { + throw new RuntimeException('小红书订单结算明细文件不存在或不可读。'); + } + if (strtolower((string) pathinfo($realPath, PATHINFO_EXTENSION)) !== 'xlsx') { + throw new RuntimeException('小红书订单结算明细导入只支持 XLSX 文件。'); + } + + return $realPath; + } + + /** @return array{0:DateTimeImmutable,1:DateTimeImmutable} */ + private function period(string $fromDate, string $toDate): array + { + $from = DateTimeImmutable::createFromFormat('!Y-m-d', $fromDate); + $to = DateTimeImmutable::createFromFormat('!Y-m-d', $toDate); + if ($from === false || $to === false + || $from->format('Y-m-d') !== $fromDate + || $to->format('Y-m-d') !== $toDate + || $from > $to) { + throw new RuntimeException('小红书账单导入账期无效。'); + } + + return [$from, $to]; + } + + /** + * @param resource $handle + * @return array{row_count:int,store_count:int,bill_item_count:int,transaction_type_counts:array,income_total:string,expense_total:string,net_total:string} + */ + private function stageToJsonLines( + string $path, + $handle, + DateTimeImmutable $from, + DateTimeImmutable $to, + ): array { + $archive = new ZipArchive(); + if ($archive->open($path) !== true) { + throw new RuntimeException('无法打开小红书订单结算明细 XLSX 文件。'); + } + + try { + $worksheet = $this->firstWorksheet($archive); + $sharedStrings = $this->sharedStrings($path, $archive); + } finally { + $archive->close(); + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, $worksheet), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取小红书订单结算明细工作表。'); + } + + $headerMap = null; + $rowCount = 0; + $incomeTotal = '0.00'; + $expenseTotal = '0.00'; + $stores = []; + $billItems = []; + $transactionTypes = []; + + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'row') { + continue; + } + + $rowNumber = (int) ($reader->getAttribute('r') ?: 0); + $cells = $this->rowCells($reader->readOuterXml(), $sharedStrings); + if ($headerMap === null) { + $headerMap = $this->headerMap($cells); + continue; + } + + $values = []; + foreach ($headerMap as $header => $column) { + $values[$header] = trim((string) ($cells[$column] ?? '')); + } + if (implode('', $values) === '') { + continue; + } + + $recordCode = $this->required($values, 'record_code', $rowNumber, '记录编码'); + $storeName = $this->required($values, 'store_name', $rowNumber, '店铺'); + $billItem = $this->required($values, 'bill_item', $rowNumber, '账单项目'); + $onlineOrderNo = $this->required($values, 'online_order_no', $rowNumber, '线上单号'); + $transactionType = $this->required($values, 'transaction_type', $rowNumber, '交易类型'); + $orderNo = $this->required($values, 'order_no', $rowNumber, '订单号'); + $modifier = $this->required($values, 'modifier', $rowNumber, '修改人'); + $orderedAt = $this->dateTime($values['ordered_at'], $rowNumber, '下单时间'); + $occurredAt = $this->dateTime($values['occurred_at'], $rowNumber, '结算时间'); + $sourceCreatedAt = $this->dateTime($values['source_created_at'], $rowNumber, '创建时间'); + $sourceUpdatedAt = $this->dateTime($values['source_updated_at'], $rowNumber, '修改时间'); + if ($occurredAt < $from->format('Y-m-d') . ' 00:00:00' + || $occurredAt >= $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') { + throw new RuntimeException("第 {$rowNumber} 行结算时间超出指定账期。"); + } + + $income = $this->money($values['income'], $rowNumber, '收入金额', false); + $expense = $this->money($values['expense'], $rowNumber, '支出金额', true); + $payload = [ + 'online_order_no' => mb_substr($onlineOrderNo, 0, 191), + 'transaction_type' => mb_substr($transactionType, 0, 255), + 'after_sale_no' => $this->nullable($values['after_sale_no'], 191), + 'ordered_at' => $orderedAt, + 'bill_remark' => $this->nullable($values['bill_remark'], 1000), + 'source_created_at' => $sourceCreatedAt, + 'source_updated_at' => $sourceUpdatedAt, + ]; + $normalized = [ + 'record_code' => mb_substr($recordCode, 0, 64), + 'store_name' => mb_substr($storeName, 0, 255), + 'order_no' => mb_substr($orderNo, 0, 64), + 'amount' => bcsub($income, $expense, 2), + 'bill_item' => mb_substr($billItem, 0, 64), + 'occurred_at' => $occurredAt, + 'income' => $income, + 'expense' => $expense, + 'remark' => $this->nullable($values['bill_remark'], 512), + 'modifier' => mb_substr($modifier, 0, 64), + 'payload' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + ]; + $line = json_encode($normalized, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"; + if (fwrite($handle, $line) !== strlen($line)) { + throw new RuntimeException('写入小红书账单导入缓冲文件失败。'); + } + + $rowCount++; + $stores[$storeName] = true; + $billItems[$billItem] = true; + $transactionTypes[$transactionType] = ($transactionTypes[$transactionType] ?? 0) + 1; + $incomeTotal = bcadd($incomeTotal, $income, 2); + $expenseTotal = bcadd($expenseTotal, $expense, 2); + } + } finally { + $reader->close(); + } + + if ($headerMap === null) { + throw new RuntimeException('未找到聚水潭小红书订单结算明细标准表头。'); + } + if ($rowCount === 0) { + throw new RuntimeException('文件中没有小红书订单结算明细数据。'); + } + + return [ + 'row_count' => $rowCount, + 'store_count' => count($stores), + 'bill_item_count' => count($billItems), + 'transaction_type_counts' => $transactionTypes, + 'income_total' => $incomeTotal, + 'expense_total' => $expenseTotal, + 'net_total' => bcsub($incomeTotal, $expenseTotal, 2), + ]; + } + + private function replacePeriod( + string $normalizedPath, + int $companyId, + DateTimeImmutable $from, + DateTimeImmutable $to, + int $batchSize, + ): void { + $handle = fopen($normalizedPath, 'rb'); + if ($handle === false) { + throw new RuntimeException('无法读取小红书账单导入缓冲文件。'); + } + + $now = now(); + try { + DB::transaction(function () use ($handle, $companyId, $from, $to, $batchSize, $now): void { + DB::table(self::TABLE) + ->where('company_id', $companyId) + ->where('bill_type', self::BILL_TYPE) + ->where('occurred_at', '>=', $from->format('Y-m-d') . ' 00:00:00') + ->where('occurred_at', '<', $to->modify('+1 day')->format('Y-m-d') . ' 00:00:00') + ->delete(); + + $batch = []; + while (($line = fgets($handle)) !== false) { + $row = json_decode($line, true, 512, JSON_THROW_ON_ERROR); + if (! is_array($row)) { + throw new RuntimeException('小红书账单导入缓冲文件内容无效。'); + } + $batch[] = $row + [ + 'company_id' => $companyId, + 'bill_type' => self::BILL_TYPE, + 'finance_remark' => null, + 'custom_remark' => null, + 'balance' => '0.00', + 'created_by' => null, + 'created_from' => self::CREATED_FROM, + 'created_at' => $now, + 'updated_at' => $now, + 'deleted_at' => null, + ]; + + if (count($batch) >= $batchSize) { + DB::table(self::TABLE)->insert($batch); + $batch = []; + } + } + if ($batch !== []) { + DB::table(self::TABLE)->insert($batch); + } + }); + } finally { + fclose($handle); + } + } + + private function assertControls(array $stats, int $count, string $income, string $expense): void + { + if ($stats['row_count'] !== $count + || bccomp($stats['income_total'], $income, 2) !== 0 + || bccomp($stats['expense_total'], $expense, 2) !== 0) { + throw new RuntimeException(sprintf( + '权威控制数不一致:实际 %d 笔,收入 %s,支出 %s;期望 %d 笔,收入 %s,支出 %s。', + $stats['row_count'], + $stats['income_total'], + $stats['expense_total'], + $count, + $income, + $expense, + )); + } + } + + /** @return array */ + private function rowCells(string $xml, array $sharedStrings): array + { + $row = simplexml_load_string($xml); + if (! $row instanceof SimpleXMLElement) { + return []; + } + + $cells = []; + foreach ($row->xpath('./*[local-name()="c"]') ?: [] as $cell) { + $reference = (string) ($cell['r'] ?? ''); + if (preg_match('/^([A-Z]+)\d+$/i', $reference, $matches) !== 1) { + continue; + } + $type = (string) ($cell['t'] ?? ''); + if ($type === 'inlineStr') { + $nodes = $cell->xpath('.//*[local-name()="t"]') ?: []; + $value = implode('', array_map(static fn (SimpleXMLElement $node): string => (string) $node, $nodes)); + } else { + $nodes = $cell->xpath('./*[local-name()="v"]') ?: []; + $raw = isset($nodes[0]) ? (string) $nodes[0] : ''; + $value = $type === 's' ? (string) ($sharedStrings[(int) $raw] ?? '') : $raw; + } + $cells[$this->columnIndex($matches[1])] = $value; + } + + return $cells; + } + + /** @param array $cells @return array|null */ + private function headerMap(array $cells): ?array + { + $lookup = []; + foreach ($cells as $column => $value) { + $lookup[trim($value)] = $column; + } + + $mapping = []; + foreach (self::HEADER_ALIASES as $field => $label) { + if (! array_key_exists($label, $lookup)) { + return null; + } + $mapping[$field] = $lookup[$label]; + } + + return $mapping; + } + + private function required(array $values, string $key, int $row, string $label): string + { + $value = trim((string) ($values[$key] ?? '')); + if ($value === '') { + throw new RuntimeException("第 {$row} 行缺少{$label}。"); + } + + return $value; + } + + private function money(string $value, int $row, string $field, bool $absolute = false): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + $value = $value === '' ? '0' : $value; + if (! is_numeric($value) || (! $absolute && bccomp($value, '0', 6) < 0)) { + throw new RuntimeException("第 {$row} 行{$field}不是有效金额。"); + } + if ($absolute && bccomp($value, '0', 6) < 0) { + $value = bcmul($value, '-1', 6); + } + + return bcadd($value, '0', 2); + } + + private function controlAmount(string $value, string $label): string + { + $value = str_replace([',', ',', '¥', '¥'], '', trim($value)); + if (! is_numeric($value) || bccomp($value, '0', 6) < 0) { + throw new RuntimeException("权威{$label}控制数无效。"); + } + + return bcadd($value, '0', 2); + } + + private function dateTime(string $value, int $row, string $field): string + { + $value = trim($value); + try { + if (is_numeric($value)) { + $seconds = (int) round((((float) $value) - 25569) * 86400); + + return Carbon::createFromTimestampUTC($seconds)->format('Y-m-d H:i:s'); + } + + return Carbon::parse($value)->format('Y-m-d H:i:s'); + } catch (Throwable) { + throw new RuntimeException("第 {$row} 行{$field}不是有效日期时间。"); + } + } + + private function nullable(string $value, int $max): ?string + { + $value = trim($value); + + return $value === '' ? null : mb_substr($value, 0, $max); + } + + private function columnIndex(string $letters): int + { + $index = 0; + foreach (str_split(strtoupper($letters)) as $letter) { + $index = ($index * 26) + ord($letter) - 64; + } + + return $index - 1; + } + + /** @return list */ + private function sharedStrings(string $path, ZipArchive $archive): array + { + if ($archive->locateName('xl/sharedStrings.xml') === false) { + return []; + } + + $reader = new XMLReader(); + if (! $reader->open($this->zipUri($path, 'xl/sharedStrings.xml'), null, LIBXML_NONET | LIBXML_COMPACT)) { + throw new RuntimeException('无法读取小红书账单 XLSX 共享文本。'); + } + + $strings = []; + try { + while ($reader->read()) { + if ($reader->nodeType !== XMLReader::ELEMENT || $reader->localName !== 'si') { + continue; + } + $item = simplexml_load_string($reader->readOuterXml()); + $nodes = $item instanceof SimpleXMLElement ? ($item->xpath('.//*[local-name()="t"]') ?: []) : []; + $strings[] = implode('', array_map( + static fn (SimpleXMLElement $node): string => (string) $node, + $nodes, + )); + } + } finally { + $reader->close(); + } + + return $strings; + } + + private function firstWorksheet(ZipArchive $archive): string + { + $worksheets = []; + for ($index = 0; $index < $archive->numFiles; $index++) { + $name = $archive->getNameIndex($index); + if (is_string($name) && preg_match('#^xl/worksheets/sheet\d+\.xml$#', $name) === 1) { + $worksheets[] = $name; + } + } + sort($worksheets, SORT_NATURAL); + if ($worksheets === []) { + throw new RuntimeException('XLSX 文件中没有工作表。'); + } + + return $worksheets[0]; + } + + private function zipUri(string $path, string $entry): string + { + return 'zip://' . str_replace('\\', '/', $path) . '#' . $entry; + } +} diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index ffc2e428..29f55874 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -268,7 +268,7 @@ const SORTABLE = ['occurred_at','income','expense','balance','record_code']; const JD_BILL_TABS = ['jd-transactions','jingxi']; // 时间筛选标签与该页签的时间列名保持一致(其余页签沿用「发生时间」)。 // 唯品会两个页签的筛选项按「账单期间」筛(后端也只按 payload.settle_period 过滤)。 -const DATE_FILTER_LABELS = {'jd-transactions':'费用结算时间','jingxi':'费用结算时间','jd-wallet':'费用结算时间','douyin':'结算时间','vipshop':'账单期间','vipshop-jx':'账单期间','promotion-marketing':'交易时间'}; +const DATE_FILTER_LABELS = {'jd-transactions':'费用结算时间','jingxi':'费用结算时间','jd-wallet':'费用结算时间','douyin':'结算时间','vipshop':'账单期间','vipshop-jx':'账单期间','xiaohongshu':'结算时间','promotion-marketing':'交易时间'}; const dateConfig = {dateFormat:'Y-m-d',locale:Mandarin,disableMobile:true,allowInput:false,onReady:(_,value,picker)=>picker.calendarContainer.classList.add('account-bill-calendar')}; // 默认账期=本月:不填日期时查全表(几百万行)会很慢,默认落到当月既快又符合日常用法。 const currentMonthRange = () => { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const pad = value => String(value).padStart(2, '0'); const lastDay = new Date(year, month, 0).getDate(); return { start: `${year}-${pad(month)}-01`, end: `${year}-${pad(month)}-${pad(lastDay)}` }; }; @@ -291,7 +291,7 @@ export default { // Every account-bill tab uses the same explicit picker path. Keeping one // control avoids browser-native date inputs appearing on older tabs. usesStableDateControl(){return true;}, - usesMirrorOptions(){return ['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','promotion-marketing'].indexOf(this.billType)!==-1;}, + usesMirrorOptions(){return ['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','xiaohongshu','promotion-marketing'].indexOf(this.billType)!==-1;}, canUseStoreSelect(){return !this.filterOptionsError&&(this.filterOptionsLoading||this.filterOptions.shops.length>0);}, invalidDateRange(){return Boolean(this.filters.start&&this.filters.end&&this.filters.start>this.filters.end);}, startDateConfig(){return {...dateConfig,maxDate:this.filters.end||null};}, @@ -358,7 +358,7 @@ export default { {label:'交易笔数',value:this.summary.count,note:'当前筛选结果',className:''}, ]; } - const netLabel=JD_BILL_TABS.concat(['vipshop-jx']).indexOf(this.billType)!==-1; + const netLabel=JD_BILL_TABS.concat(['vipshop-jx','xiaohongshu']).indexOf(this.billType)!==-1; const items=[ {label:'收入合计',value:this.moneyWan(this.summary.income),note:`${this.summary.count} 笔交易`,className:'is-income'}, {label:'支出合计',value:this.moneyWan(this.summary.expense),note:'按当前筛选',className:'is-expense'}, diff --git a/resources/assets/js/views/business/pages.js b/resources/assets/js/views/business/pages.js index 6fb90b1b..f2bcfb7f 100644 --- a/resources/assets/js/views/business/pages.js +++ b/resources/assets/js/views/business/pages.js @@ -5,7 +5,7 @@ * * 店铺收款账户账单(store-receiving-bills)下各 tab: * - taobao-alipay → 独立实现 TaobaoAlipayBills(经营分析副本共享镜像) - * - taobao-wechat / pinduoduo / jd-wallet / jd-transactions / jingxi / dewu / vipshop / vipshop-jx / promotion-marketing + * - taobao-wechat / pinduoduo / jd-wallet / jd-transactions / jingxi / dewu / vipshop / vipshop-jx / xiaohongshu / promotion-marketing * → 通用实现 AccountBills(表 ec_account_bills,按 bill_type 区分) * - douyin → AccountBills 展示共享原始账单镜像中的头条放心购渠道 * 店铺营销账户账单(marketing-account-bills)的推广费页签复用 AccountBills; @@ -18,8 +18,8 @@ import Vue from 'vue'; import TaobaoAlipayBills from './../../components/business/TaobaoAlipayBills.vue'; import AccountBills from './../../components/business/AccountBills.vue'; -const GENERIC_TABS = ['taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'promotion-marketing']; -const STORE_RECEIVING_TABS = ['taobao-alipay', 'taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx']; +const GENERIC_TABS = ['taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'xiaohongshu', 'promotion-marketing']; +const STORE_RECEIVING_TABS = ['taobao-alipay', 'taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'xiaohongshu']; function pageContext(pathname = window.location.pathname) { const parts = (pathname || '').split('/').filter(Boolean); diff --git a/tests/Feature/Business/XiaohongshuReceivingBillsTest.php b/tests/Feature/Business/XiaohongshuReceivingBillsTest.php new file mode 100644 index 00000000..01c5690f --- /dev/null +++ b/tests/Feature/Business/XiaohongshuReceivingBillsTest.php @@ -0,0 +1,128 @@ +allowPage(); + $tabs = collect(config('business_navigation')) + ->firstWhere('slug', 'billing-transactions')['pages']; + $receivingTabs = collect($tabs)->firstWhere('slug', 'store-receiving-bills')['tabs']; + $slugs = array_column($receivingTabs, 'slug'); + $this->assertSame('vipshop-jx', $slugs[array_search('xiaohongshu', $slugs, true) - 1]); + + $this->bill('2000000001351148890', '佣金', '结算入账', '2026-10-29 07:55:02', 0, 33.15); + $this->bill('2000000001351148888', '商品实付', '结算入账', '2026-10-29 07:55:02', 642.92, 0); + $this->bill('vipshop-jx', '销售', '结算入账', '2026-10-29 07:55:02', 999, 0); + + $response = $this->loginAs() + ->getJson(route('ecommerce-finance.account-bills.index', [ + 'bill_type' => 'xiaohongshu', + 'start' => '2026-10-01', + 'end' => '2026-10-31', + 'limit' => 20, + ])) + ->assertOk() + ->assertJsonPath('columns.title', '小红书账户') + ->assertJsonPath('total', 2) + ->assertJsonPath('summary.count', 2) + ->assertJsonPath('summary.income', 642.92) + ->assertJsonPath('summary.expense', 33.15) + ->assertJsonPath('summary.balance', 609.77) + ->assertJsonPath('data.0.occurred_at', '2026-10-29 07:55:02'); + + $this->assertSame( + [ + '记录编码', '店铺', '账单项目', '线上单号', '交易类型', '订单号', '售后单号', + '下单时间', '结算时间', '收入金额', '支出金额', '账单备注', '创建时间', '修改时间', '修改人', + ], + array_column($response->json('columns.columns'), 'label'), + ); + } + + public function test_xiaohongshu_filter_options_and_export_stay_inside_the_account(): void + { + $this->allowPage(); + $this->bill('2000000001351148890', '佣金', '结算入账', '2026-10-29 07:55:02', 0, 33.15); + $this->bill('2000000001351148888', '商品实付', '退款', '2026-10-29 07:55:02', 642.92, 0); + $this->bill('vipshop-jx', '销售', '结算入账', '2026-10-29 07:55:02', 999, 0); + + $options = $this->loginAs() + ->getJson(route('ecommerce-finance.account-bills.filter-options', ['bill_type' => 'xiaohongshu'])) + ->assertOk() + ->json(); + $this->assertSame(['小红书-索菲亚生活家具'], $options['shops']); + $this->assertSame(['佣金', '商品实付'], $options['bill_items']); + $this->assertSame([], $options['ledger_remarks']); + + $export = $this->loginAs()->get(route('ecommerce-finance.account-bills.export', [ + 'bill_type' => 'xiaohongshu', + 'bill_item' => '佣金', + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ])); + + $export->assertOk()->assertDownload('xiaohongshu_account_bills.csv'); + + $filtered = $this->loginAs() + ->getJson(route('ecommerce-finance.account-bills.index', [ + 'bill_type' => 'xiaohongshu', + 'bill_item' => '佣金', + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ])) + ->assertOk(); + $this->assertSame(1, $filtered->json('total')); + $this->assertSame('2000000001351148890', $filtered->json('data.0.record_code')); + } + + private function bill( + string $recordCode, + string $billItem, + string $transactionType, + string $occurredAt, + float $income, + float $expense, + ): void { + AccountBill::create([ + 'company_id' => $this->company->id, + 'bill_type' => $recordCode === 'vipshop-jx' ? 'vipshop-jx' : 'xiaohongshu', + 'record_code' => $recordCode, + 'store_name' => $recordCode === 'vipshop-jx' ? '唯品会JITX_测试店' : '小红书-索菲亚生活家具', + 'order_no' => $recordCode === 'vipshop-jx' ? 'SO-1' : 'P807944039495145531', + 'amount' => $income - $expense, + 'bill_item' => $billItem, + 'occurred_at' => $occurredAt, + 'income' => $income, + 'expense' => $expense, + 'payload' => $recordCode === 'vipshop-jx' + ? ['second_remark' => '销售', 'settle_period' => '2026-10'] + : [ + 'online_order_no' => 'P807944039495145531', + 'transaction_type' => $transactionType, + 'after_sale_no' => '-', + 'ordered_at' => '2026-10-19 14:40:39', + 'bill_remark' => $billItem, + 'source_created_at' => '2026-10-31 06:00:44', + 'source_updated_at' => '2026-11-05 14:39:13', + ], + 'modifier' => 'api', + ]); + } + + private function allowPage(): void + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + } +} diff --git a/tests/Feature/Console/XiaohongshuSettlementBillImporterTest.php b/tests/Feature/Console/XiaohongshuSettlementBillImporterTest.php new file mode 100644 index 00000000..20af055b --- /dev/null +++ b/tests/Feature/Console/XiaohongshuSettlementBillImporterTest.php @@ -0,0 +1,214 @@ + */ + private array $files = []; + + protected function tearDown(): void + { + foreach ($this->files as $file) { + @unlink($file); + } + + parent::tearDown(); + } + + public function test_it_validates_and_replaces_only_the_xiaohongshu_period(): void + { + $companyId = (int) DB::table('companies')->value('id'); + $this->existingBill($companyId, 'OLD-IN-PERIOD', 'xiaohongshu', '2026-10-15 00:00:00'); + $this->existingBill($companyId, 'KEEP-OUTSIDE-PERIOD', 'xiaohongshu', '2026-09-30 23:59:59'); + $this->existingBill($companyId, 'KEEP-OTHER-TYPE', 'vipshop-jx', '2026-10-15 00:00:00'); + $path = $this->xlsx([ + $this->row('REC-INCOME', '结算入账', '100.00', '0.00'), + $this->row('REC-EXPENSE', '退款', '0.00', '30.00'), + ]); + + $result = app(XiaohongshuSettlementBillImporter::class)->import( + $path, + $companyId, + '2026-10-01', + '2026-10-31', + 2, + '100.00', + '30.00', + 100, + ); + + $this->assertSame('succeeded', $result['status']); + $this->assertSame(2, $result['row_count']); + $this->assertSame('100.00', $result['income_total']); + $this->assertSame('30.00', $result['expense_total']); + $this->assertSame('70.00', $result['net_total']); + $this->assertSame(['结算入账' => 1, '退款' => 1], $result['transaction_type_counts']); + + $this->assertDatabaseMissing('ec_account_bills', ['record_code' => 'OLD-IN-PERIOD']); + $this->assertDatabaseHas('ec_account_bills', ['record_code' => 'KEEP-OUTSIDE-PERIOD']); + $this->assertDatabaseHas('ec_account_bills', ['record_code' => 'KEEP-OTHER-TYPE']); + $this->assertDatabaseHas('ec_account_bills', [ + 'company_id' => $companyId, + 'bill_type' => 'xiaohongshu', + 'record_code' => 'REC-INCOME', + 'store_name' => '小红书-索菲亚生活家具', + 'bill_item' => '佣金', + 'order_no' => 'P-REC-INCOME', + 'income' => 100, + 'expense' => 0, + 'amount' => 100, + 'modifier' => 'api', + 'created_from' => 'jushuitan-xiaohongshu-import', + ]); + + $row = AccountBill::query() + ->where('record_code', 'REC-INCOME') + ->where('bill_type', 'xiaohongshu') + ->firstOrFail(); + $this->assertSame('P-REC-INCOME', $row->payload['online_order_no']); + $this->assertSame('结算入账', $row->payload['transaction_type']); + $this->assertSame('-', $row->payload['after_sale_no']); + $this->assertSame('2026-10-19 14:40:39', $row->payload['ordered_at']); + $this->assertSame('2026-10-31 06:00:44', $row->payload['source_created_at']); + $this->assertSame('2026-11-05 14:39:13', $row->payload['source_updated_at']); + + $again = app(XiaohongshuSettlementBillImporter::class)->import( + $path, + $companyId, + '2026-10-01', + '2026-10-31', + 2, + '100.00', + '30.00', + 100, + ); + $this->assertSame('succeeded', $again['status']); + $this->assertSame( + 3, + DB::table('ec_account_bills') + ->where('company_id', $companyId) + ->whereIn('record_code', ['REC-INCOME', 'REC-EXPENSE', 'KEEP-OUTSIDE-PERIOD']) + ->count(), + ); + } + + public function test_control_or_period_mismatch_does_not_replace_the_active_period(): void + { + $companyId = (int) DB::table('companies')->value('id'); + $this->existingBill($companyId, 'ACTIVE-ROW', 'xiaohongshu', '2026-10-15 00:00:00'); + $importer = app(XiaohongshuSettlementBillImporter::class); + + try { + $importer->import( + $this->xlsx([$this->row('NEW-ROW', '结算入账', '10.00', '0.00')]), + $companyId, + '2026-10-01', + '2026-10-31', + 2, + '10.00', + '0.00', + 100, + ); + $this->fail('控制数不一致时必须拒绝导入。'); + } catch (RuntimeException $exception) { + $this->assertStringContainsString('权威控制数不一致', $exception->getMessage()); + } + + $this->assertDatabaseHas('ec_account_bills', ['record_code' => 'ACTIVE-ROW']); + $this->assertDatabaseMissing('ec_account_bills', ['record_code' => 'NEW-ROW']); + + try { + $importer->import( + $this->xlsx([$this->row('OUTSIDE', '结算入账', '10.00', '0.00', '2026-11-01 00:00:00')]), + $companyId, + '2026-10-01', + '2026-10-31', + 1, + '10.00', + '0.00', + 100, + ); + $this->fail('结算时间超出账期时必须拒绝导入。'); + } catch (RuntimeException $exception) { + $this->assertStringContainsString('结算时间超出指定账期', $exception->getMessage()); + } + + $this->assertDatabaseHas('ec_account_bills', ['record_code' => 'ACTIVE-ROW']); + $this->assertDatabaseMissing('ec_account_bills', ['record_code' => 'OUTSIDE']); + } + + private function existingBill(int $companyId, string $recordCode, string $billType, string $occurredAt): void + { + DB::table('ec_account_bills')->insert([ + 'company_id' => $companyId, + 'bill_type' => $billType, + 'record_code' => $recordCode, + 'store_name' => '原有店铺', + 'order_no' => 'OLD', + 'bill_item' => '原项目', + 'occurred_at' => $occurredAt, + 'income' => 1, + 'expense' => 0, + 'balance' => 0, + 'payload' => json_encode([], JSON_THROW_ON_ERROR), + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + /** + * @return list + */ + private function row( + string $recordCode, + string $transactionType, + string $income, + string $expense, + string $occurredAt = '2026-10-29 07:55:02', + ): array { + return [ + $recordCode, + '小红书-索菲亚生活家具', + '佣金', + 'P-' . $recordCode, + $transactionType, + 'P-' . $recordCode, + '-', + '2026-10-19 14:40:39', + $occurredAt, + $income, + $expense, + '佣金', + '2026-10-31 06:00:44', + '2026-11-05 14:39:13', + 'api', + ]; + } + + /** @param list> $rows */ + private function xlsx(array $rows): string + { + $temporary = tempnam(sys_get_temp_dir(), 'xiaohongshu-authoritative-'); + $path = $temporary . '.xlsx'; + rename($temporary, $path); + $spreadsheet = new Spreadsheet(); + $spreadsheet->getActiveSheet()->fromArray(array_merge([[ + '记录编码', '店铺', '账单项目', '线上单号', '交易类型', '订单号', '售后单号', + '下单时间', '结算时间', '收入金额', '支出金额', '账单备注', '创建时间', '修改时间', '修改人', + ]], $rows)); + (new Xlsx($spreadsheet))->save($path); + $spreadsheet->disconnectWorksheets(); + $this->files[] = $path; + + return $path; + } +} diff --git a/tests/Unit/View/AccountBillsTableTest.php b/tests/Unit/View/AccountBillsTableTest.php index b5833824..6de52f42 100644 --- a/tests/Unit/View/AccountBillsTableTest.php +++ b/tests/Unit/View/AccountBillsTableTest.php @@ -14,7 +14,7 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("usesStableDateControl(){return true;}", $source); $this->assertStringContainsString("{ 'is-stable-date': usesStableDateControl }", $source); $this->assertStringContainsString('.tw-date.is-stable-date .tw-date-control', $source); - $this->assertStringContainsString("['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','promotion-marketing'].indexOf(this.billType)!==-1", $source); + $this->assertStringContainsString("['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','xiaohongshu','promotion-marketing'].indexOf(this.billType)!==-1", $source); $this->assertStringContainsString('v-if="usesMirrorOptions && !filterOptionsError"', $source); $this->assertStringContainsString(':page-key="pageKey"', $source); $this->assertStringContainsString(':tab-key="billType"', $source); @@ -30,11 +30,11 @@ class AccountBillsTableTest extends TestCase $source = file_get_contents(__DIR__ . '/../../../resources/assets/js/views/business/pages.js'); $this->assertStringContainsString( - "const GENERIC_TABS = ['taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'promotion-marketing'];", + "const GENERIC_TABS = ['taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'xiaohongshu', 'promotion-marketing'];", $source, ); $this->assertStringContainsString( - "const STORE_RECEIVING_TABS = ['taobao-alipay', 'taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx'];", + "const STORE_RECEIVING_TABS = ['taobao-alipay', 'taobao-wechat', 'pinduoduo', 'jd-wallet', 'jd-transactions', 'jingxi', 'douyin', 'dewu', 'vipshop', 'vipshop-jx', 'xiaohongshu'];", $source, ); $this->assertStringContainsString( @@ -76,10 +76,10 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("const JD_BILL_TABS = ['jd-transactions','jingxi'];", $source); $this->assertStringContainsString("isJdBillTab(){return JD_BILL_TABS.indexOf(this.billType)!==-1;}", $source); // 唯品会两个页签的筛选标签是「账单期间」(后端也只按 payload.settle_period 过滤)。 - $this->assertStringContainsString("const DATE_FILTER_LABELS = {'jd-transactions':'费用结算时间','jingxi':'费用结算时间','jd-wallet':'费用结算时间','douyin':'结算时间','vipshop':'账单期间','vipshop-jx':'账单期间','promotion-marketing':'交易时间'};", $source); + $this->assertStringContainsString("const DATE_FILTER_LABELS = {'jd-transactions':'费用结算时间','jingxi':'费用结算时间','jd-wallet':'费用结算时间','douyin':'结算时间','vipshop':'账单期间','vipshop-jx':'账单期间','xiaohongshu':'结算时间','promotion-marketing':'交易时间'};", $source); $this->assertStringContainsString('{{ dateFilterLabel }}', $source); $this->assertStringContainsString('v-if="isJdBillTab && sync"', $source); - $this->assertStringContainsString("netLabel=JD_BILL_TABS.concat(['vipshop-jx']).indexOf(this.billType)!==-1", $source); + $this->assertStringContainsString("netLabel=JD_BILL_TABS.concat(['vipshop-jx','xiaohongshu']).indexOf(this.billType)!==-1", $source); } public function test_taobao_wechat_places_alipay_balances_before_income(): void