Merge remote-tracking branch 'origin/main' into feature/shanshi-ledger-dual-calendar-range
This commit is contained in:
commit
00bdda64da
51
app/Console/Commands/ImportPinduoduoPlatformBalances.php
Normal file
51
app/Console/Commands/ImportPinduoduoPlatformBalances.php
Normal file
@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Services\PinduoduoPlatformBalanceImporter;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class ImportPinduoduoPlatformBalances extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:import-pdd-platform-balances
|
||||
{path : 拼多多平台实际期末余额 XLSX/XLS/CSV}
|
||||
{--period-end= : 余额截止日期,必须是月末 YYYY-MM-DD}';
|
||||
|
||||
protected $description = '导入拼多多平台实际期末余额,作为后续月份期初余额的滚动基准';
|
||||
|
||||
public function handle(PinduoduoPlatformBalanceImporter $importer): int
|
||||
{
|
||||
$periodEnd = trim((string) $this->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;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TABLE = 'pdd_platform_balance_snapshots';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->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');
|
||||
}
|
||||
};
|
||||
18
docs/拼多多余额接入.md
Normal file
18
docs/拼多多余额接入.md
Normal file
@ -0,0 +1,18 @@
|
||||
# 拼多多账户余额
|
||||
|
||||
财务系统「店铺收款账户账单 › 拼多多账户」的期初余额以拼多多平台实际期末余额为锚点,按月滚动:
|
||||
|
||||
- 2026 年 7 月期初余额取 `2026-06-30` 的平台实际期末余额。
|
||||
- 后续月份期初余额取上一账期的期末余额。
|
||||
- 期末余额统一按“期初余额 + 收入合计 - 支出合计”计算。
|
||||
- 切换月份、店铺或账单项目筛选时,期初余额仍按所选月份的上一账期截止日展示。
|
||||
|
||||
平台余额基准存放在共享业务镜像 `pdd_platform_balance_snapshots`。导入命令:
|
||||
|
||||
```bash
|
||||
php artisan business-mirror:import-pdd-platform-balances <XLSX/XLS/CSV路径> --period-end=2026-06-30
|
||||
```
|
||||
|
||||
余额截止日期必须是月末。导入按店铺名称规范化后去重,同一账期原子替换;实际财务数据、原始文件和导出记录只放被 Git 忽略的 `runtime/private/`,不进入仓库。
|
||||
|
||||
店铺匹配使用去掉“拼多多-”平台前缀并统一空白后的名称。平台余额表存在、财务账单不存在,以及财务账单存在、平台余额表不存在的店铺都需要单独核对,不自动合并相似名称。
|
||||
@ -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);
|
||||
}
|
||||
|
||||
@ -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<string,mixed> */
|
||||
private function mapAccountBillRow(object $row): array
|
||||
{
|
||||
|
||||
@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use RuntimeException;
|
||||
|
||||
class PinduoduoPlatformBalanceImporter
|
||||
{
|
||||
public const TABLE = 'pdd_platform_balance_snapshots';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->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<array{store_name:string,normalized_store_name:string,account_name:?string,balance:string}> */
|
||||
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<list<mixed>> */
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@ -40,7 +40,15 @@ class PinduoduoReceivingBillsTest extends FeatureTestCase
|
||||
'type' => '拼多多货款账户',
|
||||
],
|
||||
]],
|
||||
'summary' => ['income' => 91.64, 'expense' => 0.0, 'balance' => 91.64, 'count' => 41],
|
||||
'summary' => [
|
||||
'income' => 91.64,
|
||||
'expense' => 0.0,
|
||||
'opening_balance' => 500.0,
|
||||
'opening_balance_date' => '2026-07-31',
|
||||
'opening_balance_source' => 'previous_period',
|
||||
'balance' => 591.64,
|
||||
'count' => 41,
|
||||
],
|
||||
]);
|
||||
$this->app->instance(PinduoduoSettlementBillRepository::class, $repository);
|
||||
|
||||
@ -55,6 +63,9 @@ class PinduoduoReceivingBillsTest extends FeatureTestCase
|
||||
->assertOk()
|
||||
->assertJsonPath('data.0.payload.type', '拼多多货款账户')
|
||||
->assertJsonPath('columns.title', '拼多多账户')
|
||||
->assertJsonPath('summary.opening_balance', 500)
|
||||
->assertJsonPath('summary.opening_balance_date', '2026-07-31')
|
||||
->assertJsonPath('summary.balance', 591.64)
|
||||
->assertJsonPath('summary.count', 41);
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\PinduoduoPlatformBalanceImporter;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PinduoduoPlatformBalanceImporterTest extends TestCase
|
||||
{
|
||||
private ?string $file = null;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'database.connections.business_mirror' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
'prefix' => '',
|
||||
],
|
||||
'upstream_mirrors.connection' => 'business_mirror',
|
||||
]);
|
||||
DB::purge('business_mirror');
|
||||
Schema::connection('business_mirror')->create(PinduoduoPlatformBalanceImporter::TABLE, function (Blueprint $table): void {
|
||||
$table->bigIncrements('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');
|
||||
$table->timestamps();
|
||||
$table->unique(['period_end', 'normalized_store_name']);
|
||||
});
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if ($this->file !== null && is_file($this->file)) {
|
||||
unlink($this->file);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_it_imports_platform_actual_balances_as_the_month_end_anchor(): void
|
||||
{
|
||||
$this->file = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'pdd-balance-' . bin2hex(random_bytes(6)) . '.csv';
|
||||
$handle = fopen($this->file, 'wb');
|
||||
fputcsv($handle, ['平台', '来源', '店铺', '平台实际期末余额']);
|
||||
fputcsv($handle, ['拼多多', '拼多多货款账户', '拼多多-测试一店', '100.25']);
|
||||
fputcsv($handle, ['拼多多', '拼多多货款账户', '拼多多-测试二店', '23.20']);
|
||||
fputcsv($handle, ['京东', '京东钱包', '京东-不导入', '999.00']);
|
||||
fclose($handle);
|
||||
|
||||
$result = app(PinduoduoPlatformBalanceImporter::class)->import($this->file, '2026-06-30');
|
||||
|
||||
$this->assertSame('2026-06-30', $result['period_end']);
|
||||
$this->assertSame(2, $result['total']);
|
||||
$this->assertSame('123.45', $result['balance_total']);
|
||||
$this->assertSame(2, DB::connection('business_mirror')->table(PinduoduoPlatformBalanceImporter::TABLE)->count());
|
||||
$this->assertEquals(
|
||||
'100.25',
|
||||
DB::connection('business_mirror')->table(PinduoduoPlatformBalanceImporter::TABLE)
|
||||
->where('store_name', '拼多多-测试一店')->value('balance'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_period_end_must_be_the_last_day_of_the_month(): void
|
||||
{
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('有效月末');
|
||||
|
||||
app(PinduoduoPlatformBalanceImporter::class)->periodEnd('2026-06-29');
|
||||
}
|
||||
}
|
||||
@ -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\JushuitanShopBalanceRepository;
|
||||
use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
@ -43,6 +44,7 @@ class PinduoduoSettlementAccountBillsRepositoryTest extends TestCase
|
||||
$this->assertSame(2, $result['total']);
|
||||
$this->assertSame(100.0, $result['summary']['income']);
|
||||
$this->assertSame(20.0, $result['summary']['expense']);
|
||||
$this->assertSame(0.0, $result['summary']['opening_balance']);
|
||||
$this->assertSame(80.0, $result['summary']['balance']);
|
||||
$this->assertSame('REC-EXPENSE', $result['data'][0]['record_code']);
|
||||
$this->assertSame('M-200', $result['data'][0]['order_no']);
|
||||
@ -70,6 +72,49 @@ class PinduoduoSettlementAccountBillsRepositoryTest extends TestCase
|
||||
$this->assertSame('REC-EXPENSE', $export[0]['record_code']);
|
||||
}
|
||||
|
||||
public function test_platform_balance_rolls_forward_from_june_into_later_months(): void
|
||||
{
|
||||
$this->insertSucceededImport();
|
||||
$this->insertBalanceSnapshot('拼多多-一店', '100.00');
|
||||
$this->insertBalanceSnapshot('拼多多-二店', '50.00');
|
||||
$this->insertBalanceSnapshot('拼多多-平台独有店', '20.00');
|
||||
|
||||
$this->insertRow('JUL-A-IN', '拼多多-一店', '交易收款', '2026-07-10 10:00:00', '30.00', '0.00', '30.00', 'M-1', 'O-1');
|
||||
$this->insertRow('JUL-A-OUT', '拼多多-一店', '退款', '2026-07-11 10:00:00', '0.00', '5.00', '-5.00', 'M-2', 'O-2');
|
||||
$this->insertRow('JUL-B-IN', '拼多多-二店', '交易收款', '2026-07-12 10:00:00', '8.00', '0.00', '8.00', 'M-3', 'O-3');
|
||||
$this->insertRow('AUG-A-IN', '拼多多-一店', '交易收款', '2026-08-10 10:00:00', '10.00', '0.00', '10.00', 'M-4', 'O-4');
|
||||
|
||||
$repository = app(PinduoduoSettlementBillRepository::class);
|
||||
$july = $repository->paginateAccountBills([
|
||||
'start' => '2026-07-01',
|
||||
'end' => '2026-07-31',
|
||||
], 'occurred_at', 'desc', 1, 10);
|
||||
$august = $repository->paginateAccountBills([
|
||||
'start' => '2026-08-01',
|
||||
'end' => '2026-08-31',
|
||||
], 'occurred_at', 'desc', 1, 10);
|
||||
|
||||
$this->assertSame(170.0, $july['summary']['opening_balance']);
|
||||
$this->assertSame('2026-06-30', $july['summary']['opening_balance_date']);
|
||||
$this->assertSame('platform_snapshot', $july['summary']['opening_balance_source']);
|
||||
$this->assertSame(38.0, $july['summary']['income']);
|
||||
$this->assertSame(5.0, $july['summary']['expense']);
|
||||
$this->assertSame(203.0, $july['summary']['balance']);
|
||||
|
||||
$this->assertSame($july['summary']['balance'], $august['summary']['opening_balance']);
|
||||
$this->assertSame('2026-07-31', $august['summary']['opening_balance_date']);
|
||||
$this->assertSame('previous_period', $august['summary']['opening_balance_source']);
|
||||
$this->assertSame(213.0, $august['summary']['balance']);
|
||||
|
||||
$oneStore = $repository->paginateAccountBills([
|
||||
'store_name' => '拼多多-一店',
|
||||
'start' => '2026-08-01',
|
||||
'end' => '2026-08-31',
|
||||
], 'occurred_at', 'desc', 1, 10);
|
||||
$this->assertSame(125.0, $oneStore['summary']['opening_balance']);
|
||||
$this->assertSame(135.0, $oneStore['summary']['balance']);
|
||||
}
|
||||
|
||||
public function test_account_bill_page_fails_closed_until_a_successful_import_exists(): void
|
||||
{
|
||||
$this->expectException(RuntimeException::class);
|
||||
@ -90,6 +135,7 @@ class PinduoduoSettlementAccountBillsRepositoryTest extends TestCase
|
||||
$schema->create('pdd_settlement_bill_imports', function (Blueprint $table): void {
|
||||
$table->uuid('generation')->primary();
|
||||
$table->string('status', 32);
|
||||
$table->timestamp('updated_at')->nullable();
|
||||
});
|
||||
$schema->create('pdd_settlement_bill_rows', function (Blueprint $table): void {
|
||||
$table->string('record_code', 191)->primary();
|
||||
@ -109,6 +155,17 @@ class PinduoduoSettlementAccountBillsRepositoryTest extends TestCase
|
||||
$table->dateTime('source_updated_at')->nullable();
|
||||
$table->string('source_modified_by')->nullable();
|
||||
});
|
||||
$schema->create('pdd_platform_balance_snapshots', function (Blueprint $table): void {
|
||||
$table->bigIncrements('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');
|
||||
});
|
||||
}
|
||||
|
||||
private function insertSucceededImport(): void
|
||||
@ -119,6 +176,20 @@ class PinduoduoSettlementAccountBillsRepositoryTest extends TestCase
|
||||
]);
|
||||
}
|
||||
|
||||
private function insertBalanceSnapshot(string $storeName, string $balance): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('pdd_platform_balance_snapshots')->insert([
|
||||
'period_end' => '2026-06-30',
|
||||
'store_name' => $storeName,
|
||||
'normalized_store_name' => JushuitanShopBalanceRepository::normalizeStoreName($storeName),
|
||||
'account_name' => '拼多多货款账户',
|
||||
'balance' => $balance,
|
||||
'source_filename' => '拼多多6月平台期末余额.xlsx',
|
||||
'source_sha256' => str_repeat('a', 64),
|
||||
'imported_at' => '2026-11-06 10:00:00',
|
||||
]);
|
||||
}
|
||||
|
||||
private function insertRow(
|
||||
string $recordCode,
|
||||
string $storeName,
|
||||
|
||||
@ -115,6 +115,22 @@ class AccountBillsTableTest extends TestCase
|
||||
$this->assertStringContainsString('.tw-stats--jd-wallet{grid-template-columns:repeat(5,minmax(0,1fr))}', $source);
|
||||
}
|
||||
|
||||
public function test_pinduoduo_places_rolled_opening_balance_before_income(): void
|
||||
{
|
||||
$source = file_get_contents(__DIR__ . '/../../../resources/assets/js/components/business/AccountBills.vue');
|
||||
|
||||
$this->assertStringContainsString("'tw-stats--pinduoduo': billType === 'pinduoduo'", $source);
|
||||
$this->assertStringContainsString("if(this.billType==='pinduoduo')", $source);
|
||||
$this->assertStringContainsString('平台实际期末余额', $source);
|
||||
$this->assertStringContainsString('上一账期期末', $source);
|
||||
$this->assertStringContainsString("note:'期初余额 + 收入合计 - 支出合计'", $source);
|
||||
$this->assertLessThan(
|
||||
strpos($source, "label:'收入合计'"),
|
||||
strpos($source, "label:'期初余额'"),
|
||||
);
|
||||
$this->assertStringContainsString('.tw-stats--pinduoduo{grid-template-columns:repeat(5,minmax(0,1fr))}', $source);
|
||||
}
|
||||
|
||||
public function test_promotion_marketing_card_opens_the_store_detail_modal(): void
|
||||
{
|
||||
$source = file_get_contents(__DIR__ . '/../../../resources/assets/js/components/business/AccountBills.vue');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user