511 lines
20 KiB
PHP
511 lines
20 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use DateTimeImmutable;
|
||
use Illuminate\Support\Carbon;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use RuntimeException;
|
||
use SimpleXMLElement;
|
||
use Throwable;
|
||
use XMLReader;
|
||
use ZipArchive;
|
||
|
||
class XiaohongshuSettlementBillImporter
|
||
{
|
||
private const TABLE = 'ec_account_bills';
|
||
private const BILL_TYPE = 'xiaohongshu';
|
||
private const CREATED_FROM = 'jushuitan-xiaohongshu-import';
|
||
|
||
private const HEADER_ALIASES = [
|
||
'record_code' => '记录编码',
|
||
'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<string,int>,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<string,int>,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<int,string> */
|
||
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<int,string> $cells @return array<string,int>|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<string> */
|
||
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;
|
||
}
|
||
}
|