Merge remote-tracking branch 'origin/main' into feature/wuyongjie-invoice-basic-sync

This commit is contained in:
WuYongJie 2026-11-10 17:19:32 +08:00
commit 88e75c1138
30 changed files with 3019 additions and 37 deletions

View File

@ -0,0 +1,276 @@
<?php
namespace App\Business\KukaPostingBase;
use App\Business\XlsxSheetReader;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
class KukaPostingBaseImporter
{
private const INSERT_CHUNK = 500;
public function __construct(
private readonly DatabaseManager $databases,
private readonly XlsxSheetReader $reader,
) {
}
/**
* @return array{
* period: string,
* dry_run: bool,
* rows: int,
* stores: array<string, int>,
* store_count: int,
* order_count: int,
* skipped_store_rows: int,
* file_sha256: string
* }
*/
public function import(
string $path,
string $period,
?string $sheetName = null,
int $companyId = 1,
bool $dryRun = false,
): array {
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
throw new InvalidArgumentException('账期格式必须为 YYYY-MM。');
}
if (! is_file($path) || ! is_readable($path)) {
throw new InvalidArgumentException('聚水潭导出文件不存在或不可读。');
}
$connection = $this->connection();
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_imports')
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) {
throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。');
}
$fields = (array) config('kuka_posting.fields', []);
$allowedStores = array_values((array) config('kuka_posting.stores', []));
if ($fields === [] || $allowedStores === []) {
throw new RuntimeException('顾家过账基础数据字段或店铺范围未配置。');
}
$sourceColumns = array_values(array_filter(array_map(
static fn (array $field): string => trim((string) ($field['source'] ?? '')),
$fields,
)));
if (count($sourceColumns) !== count($fields)) {
throw new RuntimeException('顾家过账基础数据字段配置不完整。');
}
$sheetName = trim((string) ($sheetName ?: config('kuka_posting.source_sheet', '发货明细表')));
$fileHash = hash_file('sha256', $path);
if (! is_string($fileHash)) {
throw new RuntimeException('无法计算聚水潭导出文件摘要。');
}
$storeCounts = array_fill_keys($allowedStores, 0);
$orders = [];
$rowCount = 0;
$skippedStoreRows = 0;
$sourceRowNumber = 1;
$now = now();
$write = function () use (
$connection,
$path,
$period,
$sheetName,
$companyId,
$fields,
$sourceColumns,
$allowedStores,
&$storeCounts,
&$orders,
&$rowCount,
&$skippedStoreRows,
&$sourceRowNumber,
$fileHash,
$now,
$dryRun,
): void {
if (! $dryRun) {
$connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->delete();
}
$batch = [];
$flush = static function () use (&$batch, $connection): void {
if ($batch === []) {
return;
}
$connection->table('kuka_posting_base_rows')->insert($batch);
$batch = [];
};
foreach ($this->reader->rows($path, $sourceColumns, [], $sheetName) as $sourceValues) {
$sourceRowNumber++;
$storeName = trim((string) ($sourceValues['店铺'] ?? ''));
if ($storeName === '' || ! in_array($storeName, $allowedStores, true)) {
$skippedStoreRows++;
continue;
}
$payload = [];
foreach ($fields as $field) {
$source = (string) $field['source'];
$value = trim((string) ($sourceValues[$source] ?? ''));
if (($field['kind'] ?? null) === 'date') {
$value = $this->normalizeDate($value);
}
$payload[$source] = $value;
}
$rowCount++;
$storeCounts[$storeName]++;
$internalOrderNo = trim((string) ($payload['内部订单号'] ?? ''));
if ($internalOrderNo !== '') {
$orders[$internalOrderNo] = true;
}
if ($dryRun) {
continue;
}
$batch[] = [
'company_id' => $companyId,
'period' => $period,
'store_name' => $storeName,
'internal_order_no' => $this->limit($internalOrderNo, 191),
'online_order_no' => $this->limit((string) ($payload['线上订单号'] ?? ''), 191),
'product_code' => $this->limit((string) ($payload['商品编码'] ?? ''), 191),
'order_status' => $this->limit((string) ($payload['订单状态'] ?? ''), 64),
'order_date' => $this->nullableValue($payload['订单日期'] ?? ''),
'send_date' => $this->nullableValue($payload['发货日期'] ?? ''),
'pay_date' => $this->nullableValue($payload['付款日期'] ?? ''),
'confirm_date' => $this->nullableValue($payload['确认收货日期'] ?? ''),
'row_hash' => hash('sha256', json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)),
'source_values' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
'source_row_number' => $sourceRowNumber,
'imported_at' => $now,
];
if (count($batch) >= self::INSERT_CHUNK) {
$flush();
}
}
$flush();
if ($rowCount === 0) {
throw new RuntimeException('导出文件中没有指定店铺的数据,已保留原有基础数据。');
}
$missingStores = array_keys(array_filter(
$storeCounts,
static fn (int $count): bool => $count === 0,
));
if ($missingStores !== []) {
throw new RuntimeException('导出文件缺少指定店铺:' . implode('、', $missingStores));
}
if ($dryRun) {
return;
}
$import = [
'company_id' => $companyId,
'period' => $period,
'row_count' => $rowCount,
'store_count' => count(array_filter($storeCounts)),
'order_count' => count($orders),
'store_counts' => json_encode($storeCounts, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'file_name' => basename($path),
'file_sha256' => $fileHash,
'source_sheet' => $sheetName,
'completed_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
$connection->table('kuka_posting_base_imports')->upsert(
[$import],
['company_id', 'period'],
[
'row_count',
'store_count',
'order_count',
'store_counts',
'file_name',
'file_sha256',
'source_sheet',
'completed_at',
'updated_at',
],
);
};
if ($dryRun) {
$write();
} else {
$connection->transaction($write);
}
return [
'period' => $period,
'dry_run' => $dryRun,
'rows' => $rowCount,
'stores' => $storeCounts,
'store_count' => count(array_filter($storeCounts)),
'order_count' => count($orders),
'skipped_store_rows' => $skippedStoreRows,
'file_sha256' => strtolower($fileHash),
];
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
private function normalizeDate(string $value): string
{
if ($value === '') {
return '';
}
if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) {
return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400));
}
try {
return CarbonImmutable::parse($value, 'Asia/Shanghai')->format('Y-m-d H:i:s');
} catch (Throwable) {
throw new InvalidArgumentException('聚水潭日期格式无法识别:' . $value);
}
}
private function nullableValue(string $value): ?string
{
return $value === '' ? null : $value;
}
private function limit(string $value, int $length): ?string
{
$value = trim($value);
return $value === '' ? null : mb_substr($value, 0, $length);
}
}

View File

@ -0,0 +1,131 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use Throwable;
class KukaPostingBasePageData
{
public function __construct(private readonly KukaPostingBaseRepository $repository)
{
}
/**
* @return array{
* directory: array<string, mixed>,
* rows: mixed,
* filters: array<string, mixed>,
* periods: list<string>,
* statuses: list<string>,
* stores: list<string>,
* import: ?array<string, mixed>,
* summary: array<string, mixed>,
* error: ?string
* }
*/
public function build(Request $request, int $companyId): array
{
$stores = array_values((array) config('kuka_posting.stores', []));
$fields = array_values((array) config('kuka_posting.fields', []));
$available = $this->repository->available();
$periods = $available ? $this->repository->periods($companyId) : [];
$latest = $available ? $this->repository->latestImport($companyId) : null;
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$period = (string) ($latest->period ?? ($periods[0] ?? now()->format('Y-m')));
}
$storeName = trim((string) $request->query('store_name', ''));
if ($storeName !== '' && ! in_array($storeName, $stores, true)) {
$storeName = '';
}
$status = mb_substr(trim((string) $request->query('status', '')), 0, 64);
$keyword = mb_substr(trim((string) $request->query('keyword', '')), 0, 120);
$perPage = (int) $request->integer('per_page', 50);
if (! in_array($perPage, [50, 100, 200], true)) {
$perPage = 50;
}
$page = max(1, (int) $request->integer('page', 1));
$filters = [
'period' => $period,
'store_name' => $storeName,
'status' => $status,
'keyword' => $keyword,
'per_page' => $perPage,
];
$error = $available ? null : '顾家过账基础数据镜像尚未建立,请先执行数据库迁移。';
try {
$rows = $available
? $this->repository->paginate($companyId, $period, $filters, $page, $perPage)
: new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
$rows->setCollection($rows->getCollection()->map(function (object $row): object {
$values = json_decode((string) $row->source_values, true);
if (! is_array($values)) {
$values = [];
}
$values['_row_id'] = $row->id;
return (object) $values;
}));
$statuses = $available ? $this->repository->statuses($companyId, $period) : [];
} catch (Throwable $exception) {
report($exception);
$statuses = [];
$error = '顾家过账基础数据暂时无法读取,请稍后重试;这不代表业务数据为 0。';
$rows = new LengthAwarePaginator([], 0, $perPage, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
}
$import = $available ? $this->repository->importFor($companyId, $period) : null;
$importData = null;
if ($import !== null) {
$storeCounts = json_decode((string) ($import->store_counts ?? ''), true);
$importData = [
'period' => (string) $import->period,
'row_count' => (int) $import->row_count,
'store_count' => (int) $import->store_count,
'order_count' => (int) $import->order_count,
'store_counts' => is_array($storeCounts) ? $storeCounts : [],
'file_name' => (string) $import->file_name,
'file_sha256' => (string) $import->file_sha256,
'source_sheet' => (string) $import->source_sheet,
'completed_at' => (string) $import->completed_at,
];
}
return [
'directory' => [
'icon' => 'dataset',
'status' => $importData === null ? '尚未导入' : '聚水潭原始明细',
'description' => '聚水潭“销售主题分析(新版)· 商品利润 · 明细(订单商品)”原始导出。仅保留指定 12 家店铺的 ' . $period . ' 数据。',
'empty' => '该账期还没有导入顾家过账基础数据。',
'fields' => $fields,
],
'rows' => $rows,
'filters' => $filters,
'periods' => $periods,
'statuses' => $statuses,
'stores' => $stores,
'import' => $importData,
'summary' => [
'filtered_rows' => $rows->total(),
'rows' => (int) ($importData['row_count'] ?? 0),
'stores' => (int) ($importData['store_count'] ?? 0),
'orders' => (int) ($importData['order_count'] ?? 0),
'completed_at' => $importData['completed_at'] ?? null,
],
'error' => $error,
];
}
}

View File

@ -0,0 +1,137 @@
<?php
namespace App\Business\KukaPostingBase;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
class KukaPostingBaseRepository
{
public function __construct(private readonly DatabaseManager $databases)
{
}
public function available(): bool
{
$schema = Schema::connection($this->connectionName());
return $schema->hasTable('kuka_posting_base_imports')
&& $schema->hasTable('kuka_posting_base_rows');
}
public function latestImport(int $companyId): ?object
{
if (! $this->available()) {
return null;
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->orderByDesc('period')
->first();
}
public function importFor(int $companyId, string $period): ?object
{
if (! $this->available()) {
return null;
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->where('period', $period)
->first();
}
/**
* @return list<string>
*/
public function periods(int $companyId): array
{
if (! $this->available()) {
return [];
}
return $this->connection()
->table('kuka_posting_base_imports')
->where('company_id', $companyId)
->orderByDesc('period')
->pluck('period')
->map(static fn (mixed $period): string => (string) $period)
->all();
}
/**
* @return list<string>
*/
public function statuses(int $companyId, string $period): array
{
if (! $this->available()) {
return [];
}
return $this->connection()
->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->whereNotNull('order_status')
->where('order_status', '!=', '')
->distinct()
->orderBy('order_status')
->pluck('order_status')
->map(static fn (mixed $status): string => (string) $status)
->all();
}
public function paginate(
int $companyId,
string $period,
array $filters,
int $page,
int $perPage,
): LengthAwarePaginator {
$query = $this->connection()
->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period);
$storeName = trim((string) ($filters['store_name'] ?? ''));
if ($storeName !== '') {
$query->where('store_name', $storeName);
}
$status = trim((string) ($filters['status'] ?? ''));
if ($status !== '') {
$query->where('order_status', $status);
}
$keyword = trim((string) ($filters['keyword'] ?? ''));
if ($keyword !== '') {
$like = '%' . addcslashes($keyword, '\\%_') . '%';
$query->where(static function ($nested) use ($like): void {
$nested->where('internal_order_no', 'like', $like)
->orWhere('online_order_no', 'like', $like)
->orWhere('product_code', 'like', $like);
});
}
return $query
->orderBy('source_row_number')
->paginate($perPage, ['*'], 'page', $page)
->withQueryString();
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
}

View File

@ -30,7 +30,12 @@ class XlsxSheetReader
* @param list<string|list<string>> $optionalColumns 可选列:文件里有就取,没有就跳过(不报错)。
* @return Generator<int, array<string, string>>
*/
public function rows(string $path, array $columns, array $optionalColumns = []): Generator
public function rows(
string $path,
array $columns,
array $optionalColumns = [],
?string $sheetName = null,
): Generator
{
if (! is_file($path)) {
throw new RuntimeException('订单导出文件不存在:' . $path);
@ -41,7 +46,7 @@ class XlsxSheetReader
throw new RuntimeException('无法打开订单导出文件(不是有效的 xlsx):' . $path);
}
$stream = $zip->getStream($this->worksheetPath($zip));
$stream = $zip->getStream($this->worksheetPath($zip, $sheetName));
if ($stream === false) {
$zip->close();
@ -252,16 +257,43 @@ class XlsxSheetReader
return $index - 1;
}
private function worksheetPath(ZipArchive $zip): string
private function worksheetPath(ZipArchive $zip, ?string $sheetName = null): string
{
$workbook = $zip->getFromName('xl/workbook.xml');
$relationships = $zip->getFromName('xl/_rels/workbook.xml.rels');
if (is_string($workbook) && is_string($relationships)
&& preg_match('/<sheet[^>]*r:id="([^"]+)"/', $workbook, $sheet) === 1
&& preg_match('/Id="' . preg_quote($sheet[1], '/') . '"[^>]*Target="([^"]+)"/', $relationships, $target) === 1) {
$path = ltrim($target[1], '/');
if (is_string($workbook) && is_string($relationships)) {
$relationshipId = null;
preg_match_all('/<(?:[A-Za-z0-9_]+:)?sheet\b([^>]*)\/?>/', $workbook, $sheets);
return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
foreach ($sheets[1] ?? [] as $attributes) {
if (preg_match('/\bname=(["\'])(.*?)\1/s', $attributes, $name) !== 1
|| preg_match('/\br:id=(["\'])(.*?)\1/s', $attributes, $id) !== 1) {
continue;
}
$candidateName = html_entity_decode($name[2], ENT_QUOTES | ENT_XML1, 'UTF-8');
if ($sheetName !== null && $candidateName !== $sheetName) {
continue;
}
$relationshipId = $id[2];
break;
}
if ($relationshipId !== null
&& preg_match(
'/<(?:[A-Za-z0-9_]+:)?Relationship\b[^>]*\bId=(["\'])' . preg_quote($relationshipId, '/') . '\1[^>]*\bTarget=(["\'])(.*?)\2[^>]*\/?>/s',
$relationships,
$target,
) === 1) {
$path = ltrim($target[3], '/');
return str_starts_with($path, 'xl/') ? $path : 'xl/' . $path;
}
if ($sheetName !== null) {
throw new RuntimeException('导出文件缺少工作表:' . $sheetName);
}
}
for ($i = 0; $i < $zip->numFiles; $i++) {

View File

@ -0,0 +1,62 @@
<?php
namespace App\Console\Commands;
use App\Business\KukaPostingBase\KukaPostingBaseImporter;
use Illuminate\Console\Command;
use Throwable;
class ImportKukaPostingBase extends Command
{
protected $signature = 'business-mirror:import-kuka-posting-base
{path : 聚水潭销售主题分析(新版)明细导出 XLSX 文件}
{--month= : 账期 YYYY-MM}
{--sheet= : 工作表名称,默认按配置读取“发货明细表”}
{--company=1 : 公司 ID}
{--dry-run : 只校验文件、店铺和行数,不写入共享镜像}';
protected $description = '导入顾家过账基础数据(仅指定 12 家店铺)';
public function handle(KukaPostingBaseImporter $importer): int
{
$period = trim((string) $this->option('month'));
if ($period === '') {
$this->error('必须指定 --month=YYYY-MM。');
return self::FAILURE;
}
try {
$result = $importer->import(
(string) $this->argument('path'),
$period,
$this->option('sheet') ?: null,
max(1, (int) $this->option('company')),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error('顾家过账基础数据未导入,原有数据未改变。' . $exception->getMessage());
return self::FAILURE;
}
$storeRows = [];
foreach ($result['stores'] as $store => $count) {
$storeRows[] = [$store, number_format($count)];
}
$this->table(['项目', '值'], [
['模式', $result['dry_run'] ? '仅校验' : '正式导入'],
['账期', $result['period']],
['数据行数', number_format($result['rows'])],
['店铺数', number_format($result['store_count'])],
['订单数', number_format($result['order_count'])],
['非指定店铺跳过', number_format($result['skipped_store_rows'])],
['文件 SHA-256', $result['file_sha256']],
]);
$this->table(['店铺', '行数'], $storeRows);
$this->info($result['dry_run'] ? '顾家过账基础数据校验完成。' : '顾家过账基础数据已导入共享镜像。');
return self::SUCCESS;
}
}

View File

@ -8,6 +8,7 @@ use App\Business\InventoryInboundDetailImporter;
use App\Business\InventoryWarehouseMappingAlerts;
use App\Business\InventoryWarehouseNameMappingWorkbookImporter;
use App\Business\InventoryWarehouseShortNames;
use App\Business\KukaPostingBase\KukaPostingBasePageData;
use App\Business\LaborExpenseWorkbookImporter;
use App\Business\LaborExpenseDataStore;
use App\Business\CourierPayableSummaryFilter;
@ -3965,6 +3966,14 @@ class Pages extends Controller
$agreementCourierAccounts = $this->agreementCourierAccounts($page['slug'] ?? null, $agreementCourierNames);
$agreementCourierContractParties = $this->agreementCourierContractParties($page['slug'] ?? null, $agreementCourierNames);
$agreementSupplierOptions = $this->agreementSupplierOptions($page['slug'] ?? null);
$kukaPostingBase = null;
if (($section['slug'] ?? null) === 'posting-data'
&& ($page['slug'] ?? null) === 'kuka-basic-data') {
$kukaPostingBase = app(KukaPostingBasePageData::class)->build(
request(),
(int) (company_id() ?: 1),
);
}
$staticSummaryKey = (string) ($section['slug'] ?? '') . '/' . (string) ($page['slug'] ?? '');
if (in_array($staticSummaryKey, [
@ -4074,6 +4083,7 @@ class Pages extends Controller
'inventoryUnmappedWarehouseError' => $inventoryUnmappedWarehouseError,
'inventoryWarehouseMappingView' => $inventoryWarehouseMappingView,
'receiptStats' => $receiptStats,
'kukaPostingBase' => $kukaPostingBase,
];
}
@ -4234,6 +4244,7 @@ class Pages extends Controller
'invoiceBasicPageTotals' => $invoiceBasicPageTotals,
'invoiceBasicAllTotals' => $invoiceBasicAllTotals,
'payablesFinal' => $this->payablesFinalData($section, $page),
'kukaPostingBase' => $kukaPostingBase,
];
}

View File

@ -93,6 +93,20 @@ class SystemizationTodo extends Model
return $this->belongsTo(User::class, 'created_by')->withTrashed();
}
public function creationTimeLabel(): string
{
if ($this->created_at === null) {
return '';
}
$timezone = (string) config('app.platform_timezone', config('app.timezone', 'Asia/Shanghai'));
if ($timezone === '') {
$timezone = 'Asia/Shanghai';
}
return $this->created_at->copy()->setTimezone($timezone)->format('Y-m-d H:i');
}
public function attachments(): HasMany
{
return $this->hasMany(SystemizationTodoAttachment::class, 'systemization_todo_id')
@ -142,7 +156,6 @@ class SystemizationTodo extends Model
if ($this->isCompleted()) {
return ['label' => '—', 'tone' => 'muted'];
}
// Freeze the first scheduled date so later completion-date option changes do not move overdue status.
$reminderDate = $this->reminder_date ?: $this->due_date;
if ($reminderDate === null) {
return ['label' => '时间待定', 'tone' => 'muted'];

View File

@ -721,7 +721,14 @@ $navigation = [
'title' => '过账数据',
'icon' => 'post_add',
'pages' => [
['slug' => 'kuka-posting', 'title' => '顾家过账'],
[
'slug' => 'kuka-posting',
'title' => '顾家过账',
'children_inherit_parent_access' => true,
'children' => [
['slug' => 'kuka-basic-data', 'title' => '基础数据'],
],
],
['slug' => 'suofeiya-posting', 'title' => '索菲亚过账'],
],
],

62
config/kuka_posting.php Normal file
View File

@ -0,0 +1,62 @@
<?php
return [
'source_name' => '聚水潭销售主题分析(新版)/ 商品利润 / 明细(订单商品)',
'source_sheet' => '发货明细表',
'stores' => [
'天猫-HX旗舰店101',
'京东-HX旗舰店101',
'京东-HX旗舰店102',
'京东-HX旗舰店103',
'京东-HX旗舰店104',
'拼多多-HX旗舰店101',
'拼多多-HX旗舰店102',
'拼多多-HX旗舰店103',
'拼多多-HX旗舰店105',
'拼多多-HX旗舰店106',
'拼多多-HX旗舰店107',
'抖音-HX旗舰店101',
],
'fields' => [
['name' => 'internal_order_no', 'source' => '内部订单号', 'label' => '内部订单号'],
['name' => 'marked_labels', 'source' => '标记多标签', 'label' => '标记多标签'],
['name' => 'after_sales_order_no', 'source' => '售后单号', 'label' => '售后单号'],
['name' => 'order_type', 'source' => '订单类型', 'label' => '订单类型'],
['name' => 'online_order_no', 'source' => '线上订单号', 'label' => '线上订单号'],
['name' => 'order_status', 'source' => '订单状态', 'label' => '订单状态', 'kind' => 'badge'],
['name' => 'shipping_warehouse', 'source' => '发货仓', 'label' => '发货仓'],
['name' => 'operations_cloud_warehouse', 'source' => '运营云仓', 'label' => '运营云仓'],
['name' => 'distributor', 'source' => '分销商', 'label' => '分销商'],
['name' => 'owner_distribution', 'source' => '货主分销', 'label' => '货主分销'],
['name' => 'store_name', 'source' => '店铺', 'label' => '店铺'],
['name' => 'buyer_account', 'source' => '买家账号', 'label' => '买家账号'],
['name' => 'seller_remark', 'source' => '卖家备注', 'label' => '卖家备注'],
['name' => 'order_date', 'source' => '订单日期', 'label' => '订单日期', 'kind' => 'date'],
['name' => 'shipping_date', 'source' => '发货日期', 'label' => '发货日期', 'kind' => 'date'],
['name' => 'payment_date', 'source' => '付款日期', 'label' => '付款日期', 'kind' => 'date'],
['name' => 'receipt_confirm_date', 'source' => '确认收货日期', 'label' => '确认收货日期', 'kind' => 'date'],
['name' => 'province', 'source' => '省', 'label' => '省'],
['name' => 'city', 'source' => '市', 'label' => '市'],
['name' => 'district', 'source' => '区县', 'label' => '区县'],
['name' => 'shipping_company', 'source' => '订单快递公司', 'label' => '订单快递公司'],
['name' => 'shipping_tracking_no', 'source' => '订单快递单号', 'label' => '订单快递单号'],
['name' => 'after_sales_company', 'source' => '售后快递公司', 'label' => '售后快递公司'],
['name' => 'after_sales_tracking_no', 'source' => '售后快递单号', 'label' => '售后快递单号'],
['name' => 'receiver_name', 'source' => '收货人', 'label' => '收货人'],
['name' => 'after_sales_registered_at', 'source' => '售后登记日期', 'label' => '售后登记日期', 'kind' => 'date'],
['name' => 'after_sales_confirmed_at', 'source' => '售后确认日期', 'label' => '售后确认日期', 'kind' => 'date'],
['name' => 'receiving_warehouse', 'source' => '收货仓', 'label' => '收货仓'],
['name' => 'after_sales_category', 'source' => '售后分类', 'label' => '售后分类'],
['name' => 'problem_type', 'source' => '问题类型', 'label' => '问题类型'],
['name' => 'product_code', 'source' => '商品编码', 'label' => '商品编码'],
['name' => 'original_online_order_no', 'source' => '原始线上订单号', 'label' => '原始线上订单号'],
['name' => 'style_code', 'source' => '款式编码', 'label' => '款式编码'],
['name' => 'item_number', 'source' => '货号', 'label' => '货号'],
['name' => 'material_number', 'source' => '物料编号', 'label' => '物料编号'],
['name' => 'model', 'source' => '型号', 'label' => '型号'],
['name' => 'cost', 'source' => '成本', 'label' => '成本', 'kind' => 'number'],
['name' => 'product_material', 'source' => '产品材质', 'label' => '产品材质'],
['name' => 'shipped_quantity', 'source' => '实发数量', 'label' => '实发数量', 'kind' => 'number'],
['name' => 'shipping_amount', 'source' => '发货金额', 'label' => '发货金额', 'kind' => 'number'],
],
];

View File

@ -0,0 +1,94 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('kuka_posting_base_imports')) {
$schema->create('kuka_posting_base_imports', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id')->default(1);
$table->char('period', 7);
$table->unsignedInteger('row_count')->default(0);
$table->unsignedInteger('store_count')->default(0);
$table->unsignedInteger('order_count')->default(0);
$table->longText('store_counts')->nullable();
$table->string('file_name', 255);
$table->char('file_sha256', 64);
$table->string('source_sheet', 191);
$table->timestamp('completed_at');
$table->timestamps();
$table->unique(['company_id', 'period'], 'kuka_posting_import_company_period_unique');
});
}
if (! $schema->hasTable('kuka_posting_base_rows')) {
$schema->create('kuka_posting_base_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id')->default(1);
$table->char('period', 7);
$table->string('store_name', 191);
$table->string('internal_order_no', 191)->nullable();
$table->string('online_order_no', 191)->nullable();
$table->string('product_code', 191)->nullable();
$table->string('order_status', 64)->nullable();
$table->dateTime('order_date')->nullable();
$table->dateTime('send_date')->nullable();
$table->dateTime('pay_date')->nullable();
$table->dateTime('confirm_date')->nullable();
$table->char('row_hash', 64);
$table->longText('source_values');
$table->unsignedInteger('source_row_number');
$table->timestamp('imported_at');
$table->unique(
['company_id', 'period', 'source_row_number'],
'kuka_posting_base_company_period_row_unique'
);
$table->index(
['company_id', 'period', 'store_name', 'source_row_number'],
'kuka_posting_base_company_period_store'
);
$table->index(
['company_id', 'period', 'order_status', 'store_name'],
'kuka_posting_base_company_period_status'
);
$table->index(
['company_id', 'period', 'pay_date'],
'kuka_posting_base_company_period_pay'
);
$table->index(
['company_id', 'period', 'internal_order_no'],
'kuka_posting_base_company_period_order'
);
$table->index(
['company_id', 'period', 'online_order_no'],
'kuka_posting_base_company_period_online'
);
$table->index(
['company_id', 'period', 'product_code'],
'kuka_posting_base_company_period_product'
);
});
}
}
public function down(): void
{
$schema = Schema::connection($this->connection());
$schema->dropIfExists('kuka_posting_base_rows');
$schema->dropIfExists('kuka_posting_base_imports');
}
};

View File

@ -11,6 +11,7 @@
"dewu-bills:import-authoritative",
"business-mirror:import-douyin-authoritative",
"business-mirror:import-douyin-opening-balances",
"business-mirror:import-kuka-posting-base",
"finance-ledger:import-company-alipay",
"finance-ledger:import-wangshang-bank",
"finance-ledger:import-base",

View File

@ -16,6 +16,7 @@
| 状态 | 说明 |
| --- | --- |
| 本次接入 | 顾家过账基础数据读取聚水潭“销售主题分析(新版)→ 商品利润 → 明细(订单商品)”10 月导出,仅保留天猫、京东、拼多多和抖音的 12 家 HX 旗舰店,写入 `kuka_posting_base_rows`;导入摘要写入 `kuka_posting_base_imports`。只保存前 40 个聚水潭原始字段,后续成本映射、报价和过账分类不混入基础数据。XLSX 通过 `business-mirror:import-kuka-posting-base` 流式读取,校验 12 家店铺均有数据后,在单一事务内整月替换;文件缺失、字段错误或中断时保留上一版。当前 2026 年 10 月导出为 13,949 行。 |
| 本次接入 | 钉钉考勤 `attendance/list` 按财务中心在职成员同步到 `ding_attendance_records`,保留打卡记录 ID、用户、工作日期、上下班类型、打卡结果、审批标识、审批实例和打卡时间;每 15 分钟回看 35 天,按 7 天窗口和 50 人上限分页。钉钉排班通过 `getScheduleByRange` 同步到 `ding_attendance_schedule_records`,保留逐日排班 ID、用户、考勤组、班次、是否休息、变更状态和完整源数据;本机脚本为 `scripts/sync-ding-attendance-schedules.py`,导入命令为 `business-mirror:import-ding-attendance-schedules`,默认覆盖最近 95 天,查询不完整时拒绝覆盖旧镜像。日志漏写扣分只统计钉钉排班明确为工作日的日期,并继续排除没有日志但有“请假 / 休息 / 调休”等审批标记的日期;排班或考勤镜像未完成时扣分暂不计算,周五、周末或法定班次调整均以公司真实排班为准。依赖权限 `qyapi_attendance_isv_query_result`、`qyapi_get_attendance_data`。 |
| 已完成 | `operations_replica/rpt.Bulk_Price_Limit` 已进入类型化表 `product_price_mirror_rows`,商品价格页面已读取镜像并支持完整分页。 |
| 已完成 | `operations_replica/rpt.jst_sku` 已进入 `ops_jst_sku`,普通商品资料页面固定读取 `sku_type = normal` 的共享镜像,并支持稳定分页和业务筛选。 |

View File

@ -85,6 +85,21 @@ class StoreReceivingBalanceOverview extends Controller
}
}
public function balanceStoreDetail(Request $request, StoreReceivingBalanceOverviewService $service)
{
$this->authorizeStoreReceivingBills();
try {
return response()->json($service->balanceStoreDetail(...$this->requestedPeriod($request)));
} catch (Throwable $exception) {
report($exception);
return response()->json([
'message' => '店铺期末余额明细暂时无法读取,请稍后重试。',
], 503);
}
}
/** @return array{0:string,1?:string} */
private function requestedPeriod(Request $request): array
{

View File

@ -26,6 +26,10 @@ class DouyinAuthoritativeBillRepository
'balance' => 287706.90,
'source' => 'merchant_backoffice_june_ending',
],
'抖音-亿家达乐简家具专卖店' => [
'balance' => 0.0,
'source' => 'merchant_backoffice_zero',
],
];
public function __construct(
@ -98,6 +102,109 @@ class DouyinAuthoritativeBillRepository
];
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
public function storeBalances(array $filters): array
{
$start = $this->monthStart($filters['start'] ?? null);
if ($start === null) {
return [];
}
$activity = [];
$displayNames = [];
foreach ($this->query($filters, true)
->select('store_name')
->selectRaw(
'COALESCE(SUM(income), 0) AS income_total, '
. 'COALESCE(SUM(expense), 0) AS expense_total',
)
->groupBy('store_name')
->get() as $row) {
$storeName = trim((string) $row->store_name);
$storeName = $storeName !== '' ? $storeName : '未标注店铺';
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName);
$displayNames[$normalized] = $storeName;
$activity[$normalized] = [
'income' => round((float) ($activity[$normalized]['income'] ?? 0) + (float) $row->income_total, 2),
'expense' => round((float) ($activity[$normalized]['expense'] ?? 0) + (float) $row->expense_total, 2),
];
}
$base = [];
$db = $this->db();
if ($db->getSchemaBuilder()->hasTable(DouyinOpeningBalanceImporter::TABLE)) {
foreach ($db->table(DouyinOpeningBalanceImporter::TABLE)
->where('period_end', '2026-06-30')
->select(['store_name', 'normalized_store_name'])
->selectRaw('COALESCE(SUM(balance), 0) AS balance')
->groupBy('store_name', 'normalized_store_name')
->get() as $row) {
$base[(string) $row->normalized_store_name] = [
'store_name' => trim((string) $row->store_name),
'balance' => round((float) $row->balance, 2),
];
}
}
foreach (self::MERCHANT_BACKOFFICE_JUNE_ENDING_BALANCES as $storeName => $opening) {
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName);
$base[$normalized] ??= [
'store_name' => $storeName,
'balance' => round((float) $opening['balance'], 2),
];
}
$movement = [];
$baselineMonth = CarbonImmutable::create(2026, 7, 1)->startOfDay();
if ($start->gt($baselineMonth)) {
foreach ($this->query([
'start' => $baselineMonth->format('Y-m-d'),
'end' => $start->subDay()->format('Y-m-d'),
], true)
->select('store_name')
->selectRaw(
'COALESCE(SUM(income), 0) AS income_total, '
. 'COALESCE(SUM(expense), 0) AS expense_total',
)
->groupBy('store_name')
->get() as $row) {
$normalized = JushuitanShopBalanceRepository::normalizeStoreName((string) $row->store_name);
$movement[$normalized] = [
'income' => (float) $row->income_total,
'expense' => (float) $row->expense_total,
];
}
}
$normalizedStores = array_values(array_unique(array_merge(
array_keys($base),
array_keys($movement),
array_keys($activity),
)));
$rows = [];
foreach ($normalizedStores as $normalized) {
$storeName = $displayNames[$normalized]
?? ($base[$normalized]['store_name'] ?? '未标注店铺');
$opening = array_key_exists($normalized, $base)
? round(
(float) $base[$normalized]['balance']
+ (float) ($movement[$normalized]['income'] ?? 0)
- (float) ($movement[$normalized]['expense'] ?? 0),
2,
)
: null;
$rows[] = [
'store_name' => $storeName,
'opening_balance' => $opening,
'income' => round((float) ($activity[$normalized]['income'] ?? 0), 2),
'expense' => round((float) ($activity[$normalized]['expense'] ?? 0), 2),
];
}
return $rows;
}
private function query(array $filters, bool $withOptions = false): Builder
{
$dataset = $this->datasets->get(StoreReceivingAlipayBillMirrorRepository::DATASET);

View File

@ -98,6 +98,33 @@ class TaobaoAlipaySettlementBillRepository
return $this->summaryForQuery($query, $filters);
}
/**
* 复用总览期初查询已经缓存的店铺余额,避免店铺明细再次扫描全历史。
*
* @return array<string,float>
*/
public function storeOpeningBalances(?string $periodStart): array
{
$start = $this->date($periodStart);
if ($start === null) {
return [];
}
$monthStart = $start->modify('first day of this month');
$cutoff = $monthStart->format('Y-m-d') . ' 00:00:00';
$importVersion = (string) ($this->connection->table(self::IMPORT_TABLE)
->where('status', 'succeeded')
->max('completed_at') ?? '');
$cacheKey = $this->openingBalanceCacheKey($cutoff, '', $importVersion);
$opening = Cache::get($cacheKey);
if (! is_array($opening) || ! is_array($opening['stores'] ?? null)) {
$this->openingBalance(['start' => $periodStart]);
$opening = Cache::get($cacheKey);
}
return is_array($opening['stores'] ?? null) ? $opening['stores'] : [];
}
/**
* @return array{income:float,expense:float,opening_balance:float,opening_balance_date:?string,opening_balance_source:string,balance:float,count:int}
*/
@ -223,11 +250,7 @@ class TaobaoAlipaySettlementBillRepository
$importVersion = (string) ($this->connection->table(self::IMPORT_TABLE)
->where('status', 'succeeded')
->max('completed_at') ?? '');
$cacheKey = 'taobao-alipay-opening-balance:v1:' . hash('sha256', implode('|', [
$cutoff,
$store,
$importVersion,
]));
$cacheKey = $this->openingBalanceCacheKey($cutoff, $store, $importVersion);
$opening = Cache::remember(
$cacheKey,
@ -239,6 +262,7 @@ class TaobaoAlipaySettlementBillRepository
->where('alipay_account', '<>', '')
->when($store !== '', fn (Builder $query) => $query->where('store_name', $store))
->select([
'store_name',
'alipay_account',
'occurred_at',
'source_row_number',
@ -259,9 +283,20 @@ class TaobaoAlipaySettlementBillRepository
->get();
if ($latestRows->isNotEmpty()) {
$stores = [];
foreach ($latestRows as $row) {
$storeName = trim((string) ($row->store_name ?? ''));
$storeName = $storeName !== '' ? $storeName : '未标注店铺';
$stores[$storeName] = round(
(float) ($stores[$storeName] ?? 0) + (float) $row->balance_amount,
2,
);
}
return [
'balance' => round((float) $latestRows->sum('balance_amount'), 2),
'source' => 'previous_period',
'stores' => $stores,
];
}
@ -274,6 +309,7 @@ class TaobaoAlipaySettlementBillRepository
->where('alipay_account', '<>', '')
->when($store !== '', fn (Builder $query) => $query->where('store_name', $store))
->select([
'store_name',
'alipay_account',
'occurred_at',
'source_row_number',
@ -291,6 +327,18 @@ class TaobaoAlipaySettlementBillRepository
->fromSub($firstRows, 'first_balances')
->where('row_rank', 1)
->get();
$stores = [];
foreach ($first as $row) {
$storeName = trim((string) ($row->store_name ?? ''));
$storeName = $storeName !== '' ? $storeName : '未标注店铺';
$stores[$storeName] = round(
(float) ($stores[$storeName] ?? 0)
+ (float) $row->balance_amount
- (float) $row->income_amount
+ (float) $row->expense_amount,
2,
);
}
return [
'balance' => round((float) $first->sum(
@ -299,6 +347,7 @@ class TaobaoAlipaySettlementBillRepository
+ (float) $row->expense_amount,
), 2),
'source' => 'first_row_estimate',
'stores' => $stores,
];
},
);
@ -356,4 +405,13 @@ class TaobaoAlipaySettlementBillRepository
{
return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $value);
}
private function openingBalanceCacheKey(string $cutoff, string $store, string $importVersion): string
{
return 'taobao-alipay-opening-balance:v2:' . hash('sha256', implode('|', [
$cutoff,
$store,
$importVersion,
]));
}
}

View File

@ -3,6 +3,10 @@
namespace Modules\EcommerceFinance\Services;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\EcommerceFinance\Http\Controllers\AccountBills;
@ -10,17 +14,39 @@ use Modules\EcommerceFinance\Http\Controllers\AlipayBills;
use Modules\EcommerceFinance\Http\Controllers\PinduoduoAccountBills;
use Modules\EcommerceFinance\Http\Controllers\TaobaoWechatAccountBills;
use Modules\EcommerceFinance\Models\AccountBill;
use Modules\EcommerceFinance\Repositories\DouyinAuthoritativeBillRepository;
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
use Modules\EcommerceFinance\Repositories\PinduoduoSettlementBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository;
use Modules\EcommerceFinance\Repositories\TaobaoAlipaySettlementBillRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use Modules\EcommerceFinance\Repositories\VipshopJxOpeningBalanceRepository;
use RuntimeException;
use Throwable;
class StoreReceivingBalanceOverviewService
{
private const TAOBAO_ALIPAY_ROW_TABLE = 'taobao_alipay_bill_rows';
private const TAOBAO_WECHAT_ROW_TABLE = 'taobao_wechat_bill_rows';
private const TAOBAO_WECHAT_OPENING_TABLE = 'taobao_wechat_opening_balances';
private const PINDUODUO_ROW_TABLE = 'pdd_settlement_bill_rows';
private const PINDUODUO_SNAPSHOT_TABLE = 'pdd_platform_balance_snapshots';
private const JD_WALLET_PERIOD_TABLE = 'jd_wallet_bill_periods';
private const JD_WALLET_ROW_TABLE = 'jd_wallet_bill_rows';
private const VIPSHOP_MP_SNAPSHOT_TABLE = 'vipshop_mp_opening_balance_snapshots';
private const XIAOHONGSHU_BALANCE_START = '2026-10-01';
/** @var array<int,array{slug:string,name:string}> */
public const PLATFORMS = [
['slug' => 'taobao-alipay', 'name' => '淘系支付宝账户'],
@ -301,7 +327,6 @@ class StoreReceivingBalanceOverviewService
'amount' => round((float) $platform['balance'], 2),
];
}
return [
'month' => $overview['month'],
'period' => $overview['period'],
@ -315,6 +340,133 @@ class StoreReceivingBalanceOverviewService
];
}
/**
* 期末余额的店铺明细。
*
* 每个店铺统一按「期初余额 + 收入 - 支出」计算;某一店铺缺少期初时
* 返回 null,由页面显示为“—”,不把未知期初静默当成 0。
*
* @return array<string,mixed>
*/
public function balanceStoreDetail(string $periodStart, ?string $periodEnd = null): array
{
[$periodStart, $periodEnd, $periodMonth] = $this->periodForRange($periodStart, $periodEnd);
$details = [];
$platformCount = 0;
$storeCount = 0;
$readyStoreCount = 0;
$balance = 0.0;
foreach (self::PLATFORMS as $index => $definition) {
try {
$rows = $this->fetchPlatformStoreBalances(
$definition['slug'],
$periodStart,
$periodEnd,
);
if ($rows === []) {
continue;
}
$platformCount++;
} catch (Throwable $exception) {
throw new RuntimeException('店铺期末余额明细暂时无法读取,请稍后重试。', 0, $exception);
}
$rowsByStore = [];
foreach ($rows as $row) {
$storeName = trim((string) ($row['store_name'] ?? ''));
$storeName = $storeName !== '' ? $storeName : '未标注店铺';
$rowsByStore[$storeName] ??= [
'opening_balance' => null,
'income' => 0.0,
'expense' => 0.0,
];
if (is_numeric($row['opening_balance'] ?? null)) {
$rowsByStore[$storeName]['opening_balance'] = round(
(float) ($rowsByStore[$storeName]['opening_balance'] ?? 0)
+ (float) $row['opening_balance'],
2,
);
}
$rowsByStore[$storeName]['income'] = round(
(float) $rowsByStore[$storeName]['income'] + (float) ($row['income'] ?? 0),
2,
);
$rowsByStore[$storeName]['expense'] = round(
(float) $rowsByStore[$storeName]['expense'] + (float) ($row['expense'] ?? 0),
2,
);
}
$platformRows = [];
foreach ($rowsByStore as $storeName => $row) {
$opening = $row['opening_balance'];
$income = $row['income'];
$expense = $row['expense'];
$amount = $opening === null
? null
: round($opening + $income - $expense, 2);
$storeCount++;
if ($amount !== null) {
$readyStoreCount++;
$balance += $amount;
}
$platformRows[] = [
'platform_slug' => $definition['slug'],
'platform' => $definition['name'],
'store_name' => $storeName,
'bill_item' => '',
'opening_balance' => $opening,
'income' => $income,
'expense' => $expense,
'amount' => $amount,
'available' => $amount !== null,
'_platform_order' => $index,
];
}
usort($platformRows, static function (array $left, array $right): int {
return [
$left['amount'] === null ? 1 : 0,
$left['amount'] === null ? 0 : -$left['amount'],
$left['store_name'],
] <=> [
$right['amount'] === null ? 1 : 0,
$right['amount'] === null ? 0 : -$right['amount'],
$right['store_name'],
];
});
array_push($details, ...$platformRows);
}
foreach ($details as &$detail) {
unset($detail['_platform_order']);
}
unset($detail);
$complete = $platformCount === count(self::PLATFORMS)
&& $storeCount > 0
&& $readyStoreCount === $storeCount;
return [
'month' => $periodMonth,
'period' => [
'start' => $periodStart,
'end' => $periodEnd,
],
'summary' => [
'balance' => $complete ? round($balance, 2) : null,
'platform_count' => count(self::PLATFORMS),
'available_platform_count' => $platformCount,
'store_count' => $storeCount,
'ready_store_count' => $readyStoreCount,
'complete' => $complete,
],
'details' => $details,
];
}
/** @return array<string,mixed> */
private function flowDetail(string $periodStart, ?string $periodEnd, string $flow): array
{
@ -465,6 +617,516 @@ class StoreReceivingBalanceOverviewService
return $this->fetchPlatformRows($platform, $start, $end, 'expense');
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
{
return match ($platform) {
'taobao-alipay' => $this->taobaoAlipayStoreBalances($start, $end),
'taobao-wechat' => $this->taobaoWechatStoreBalances($start, $end),
'pinduoduo' => $this->pinduoduoStoreBalances($start, $end),
'jd-wallet' => $this->jdWalletStoreBalances($start, $end),
'douyin' => $this->douyinStoreBalances($start, $end),
'vipshop' => $this->vipshopStoreBalances($start, $end),
'vipshop-jx' => $this->vipshopJxStoreBalances($start, $end),
'xiaohongshu' => $this->xiaohongshuStoreBalances($start, $end),
default => throw new RuntimeException('unsupported_balance_overview_platform'),
};
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function taobaoAlipayStoreBalances(string $start, string $end): array
{
$connection = $this->mirrorConnection();
$activity = $this->groupedActivity(
$connection->table(self::TAOBAO_ALIPAY_ROW_TABLE)
->where('occurred_at', '>=', $start . ' 00:00:00')
->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'),
);
$opening = app(TaobaoAlipaySettlementBillRepository::class)
->storeOpeningBalances($start);
return $this->mergeStoreBalances($opening, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function taobaoWechatStoreBalances(string $start, string $end): array
{
$connection = $this->mirrorConnection();
$activity = $this->groupedActivity(
$connection->table(self::TAOBAO_WECHAT_ROW_TABLE)
->where('occurred_at', '>=', $start . ' 00:00:00')
->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'),
);
$opening = [];
if ($connection->getSchemaBuilder()->hasTable(self::TAOBAO_WECHAT_OPENING_TABLE)) {
$baseline = $connection->table(self::TAOBAO_WECHAT_OPENING_TABLE)
->where('balance_date', TaobaoWechatOpeningBalanceRepository::BASELINE_DATE)
->select('store_name')
->selectRaw('COALESCE(SUM(balance), 0) AS balance')
->groupBy('store_name')
->get();
foreach ($baseline as $row) {
$opening[$this->storeName($row->store_name)] = round((float) $row->balance, 2);
}
if (CarbonImmutable::parse($start)->gt(CarbonImmutable::parse('2026-07-01'))) {
$movement = $this->groupedActivity(
$connection->table(self::TAOBAO_WECHAT_ROW_TABLE)
->where('occurred_at', '>=', '2026-07-01 00:00:00')
->where('occurred_at', '<', $start . ' 00:00:00'),
);
foreach ($opening as $storeName => $balance) {
$row = $movement[$storeName] ?? ['income' => 0.0, 'expense' => 0.0];
$opening[$storeName] = round(
$balance + (float) $row['income'] - (float) $row['expense'],
2,
);
}
}
}
return $this->mergeStoreBalances($opening, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function pinduoduoStoreBalances(string $start, string $end): array
{
$connection = $this->mirrorConnection();
$activity = $this->groupedActivity(
$connection->table(self::PINDUODUO_ROW_TABLE)
->where('occurred_at', '>=', $start . ' 00:00:00')
->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'),
);
if (! $connection->getSchemaBuilder()->hasTable(self::PINDUODUO_SNAPSHOT_TABLE)) {
return $this->mergeNormalizedStoreBalances([], [], $activity);
}
$monthStart = CarbonImmutable::parse($start)->startOfMonth()->format('Y-m-d');
$balanceDate = $connection->table(self::PINDUODUO_SNAPSHOT_TABLE)
->where('period_end', '<', $monthStart)
->orderBy('period_end')
->value('period_end');
if ($balanceDate === null) {
return $this->mergeNormalizedStoreBalances([], [], $activity);
}
$base = [];
foreach ($connection->table(self::PINDUODUO_SNAPSHOT_TABLE)
->where('period_end', $balanceDate)
->select(['store_name', 'normalized_store_name'])
->selectRaw('COALESCE(SUM(balance), 0) AS balance')
->groupBy('store_name', 'normalized_store_name')
->get() as $row) {
$normalized = (string) $row->normalized_store_name;
$base[$normalized] = [
'store_name' => $this->storeName($row->store_name),
'balance' => round((float) $row->balance, 2),
];
}
$movement = [];
foreach ($connection->table(self::PINDUODUO_ROW_TABLE)
->where('occurred_at', '>=', $balanceDate . ' 00:00:00')
->where('occurred_at', '<', $monthStart . ' 00:00:00')
->select('store_name')
->selectRaw(
'COALESCE(SUM(income_amount), 0) AS income, '
. 'COALESCE(SUM(expense_amount), 0) AS expense',
)
->groupBy('store_name')
->get() as $row) {
$normalized = JushuitanShopBalanceRepository::normalizeStoreName((string) $row->store_name);
$movement[$normalized] = [
'income' => (float) $row->income,
'expense' => (float) $row->expense,
];
}
return $this->mergeNormalizedStoreBalances($base, $movement, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function jdWalletStoreBalances(string $start, string $end): array
{
$connection = $this->mirrorConnection();
$generations = $connection->table(self::JD_WALLET_PERIOD_TABLE)
->pluck('active_generation')
->filter()
->map(static fn (mixed $value): string => (string) $value)
->values()
->all();
if ($generations === []) {
throw new RuntimeException('jd_wallet_bill_mirror_not_ready');
}
$activity = $this->groupedActivity(
$connection->table(self::JD_WALLET_ROW_TABLE)
->whereIn('generation', $generations)
->where('occurred_at', '>=', $start . ' 00:00:00')
->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00'),
'income',
'expense',
);
$cutoff = $start . ' 00:00:00';
$periodEnd = $this->dayAfter($end) . ' 00:00:00';
$ranked = $connection->table(self::JD_WALLET_ROW_TABLE)
->whereIn('generation', $generations)
->whereNotNull('balance')
->where('occurred_at', '<', $cutoff)
->select([
'store_name',
'account_name',
'occurred_at',
'income',
'expense',
'balance',
'record_code',
])
->selectRaw(
'ROW_NUMBER() OVER (' .
'PARTITION BY store_name, account_name ' .
'ORDER BY occurred_at DESC, LENGTH(record_code) DESC, record_code DESC' .
') AS row_rank',
);
$latestRows = $connection->query()
->fromSub($ranked, 'latest_jd_balances')
->where('row_rank', 1)
->get();
$opening = [];
if ($latestRows->isNotEmpty()) {
foreach ($latestRows as $row) {
$storeName = $this->storeName($row->store_name);
$opening[$storeName] = round(
(float) ($opening[$storeName] ?? 0) + (float) $row->balance,
2,
);
}
} else {
$firstRanked = $connection->table(self::JD_WALLET_ROW_TABLE)
->whereIn('generation', $generations)
->whereNotNull('balance')
->where('occurred_at', '>=', $cutoff)
->where('occurred_at', '<', $periodEnd)
->select([
'store_name',
'account_name',
'occurred_at',
'income',
'expense',
'balance',
'record_code',
])
->selectRaw(
'ROW_NUMBER() OVER (' .
'PARTITION BY store_name, account_name ' .
'ORDER BY occurred_at ASC, LENGTH(record_code) ASC, record_code ASC' .
') AS row_rank',
);
$firstRows = $connection->query()
->fromSub($firstRanked, 'first_jd_balances')
->where('row_rank', 1)
->get();
foreach ($firstRows as $row) {
$storeName = $this->storeName($row->store_name);
$opening[$storeName] = round(
(float) ($opening[$storeName] ?? 0)
+ (float) $row->balance
- (float) $row->income
+ (float) $row->expense,
2,
);
}
}
return $this->mergeStoreBalances($opening, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function douyinStoreBalances(string $start, string $end): array
{
$repository = app(DouyinAuthoritativeBillRepository::class);
if (! $repository->available()) {
throw new RuntimeException('douyin_authoritative_bills_not_ready');
}
return $repository->storeBalances([
'start' => $start,
'end' => $end,
]);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function vipshopStoreBalances(string $start, string $end): array
{
$activity = $this->accountBillActivity('vipshop', $start, $end, true);
$connection = $this->mirrorConnection();
$opening = [];
if ($connection->getSchemaBuilder()->hasTable(self::VIPSHOP_MP_SNAPSHOT_TABLE)) {
foreach ($connection->table(self::VIPSHOP_MP_SNAPSHOT_TABLE)
->where('period_end', '2026-06-30')
->select('store_name')
->selectRaw('COALESCE(SUM(balance), 0) AS balance')
->groupBy('store_name')
->get() as $row) {
$opening[$this->storeName($row->store_name)] = round((float) $row->balance, 2);
}
}
$monthStart = CarbonImmutable::parse($start)->startOfMonth();
if ($opening !== [] && $monthStart->gt(CarbonImmutable::parse('2026-07-01'))) {
$movement = $this->accountBillActivity(
'vipshop',
'2026-07-01',
$monthStart->subDay()->format('Y-m-d'),
true,
);
foreach ($opening as $storeName => $balance) {
$row = $movement[$storeName] ?? ['income' => 0.0, 'expense' => 0.0];
$opening[$storeName] = round(
$balance + (float) $row['income'] - (float) $row['expense'],
2,
);
}
}
return $this->mergeStoreBalances($opening, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function vipshopJxStoreBalances(string $start, string $end): array
{
$activity = $this->accountBillActivity('vipshop-jx', $start, $end, true);
$openingData = app(VipshopJxOpeningBalanceRepository::class)->openingBalance($start, $end);
$opening = $openingData['source'] === 'none'
? null
: round((float) $openingData['balance'], 2);
$storeNames = array_keys($activity);
if ($storeNames === []) {
$storeNames = AccountBill::query()
->where('company_id', company_id())
->where('bill_type', 'vipshop-jx')
->whereNull('deleted_at')
->whereNotNull('store_name')
->where('store_name', '<>', '')
->distinct()
->orderBy('store_name')
->pluck('store_name')
->map(fn (mixed $value): string => $this->storeName($value))
->all();
}
$openingMap = count($storeNames) === 1 && $opening !== null
? [reset($storeNames) => $opening]
: [];
return $this->mergeStoreBalances($openingMap, $activity);
}
/**
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function xiaohongshuStoreBalances(string $start, string $end): array
{
$activity = $this->accountBillActivity('xiaohongshu', $start, $end, false);
$opening = [];
$monthStart = CarbonImmutable::parse($start)->startOfMonth();
if ($monthStart->lte(CarbonImmutable::parse(self::XIAOHONGSHU_BALANCE_START))) {
foreach (array_keys($activity) as $storeName) {
$opening[$storeName] = 0.0;
}
} elseif ($monthStart->gt(CarbonImmutable::parse(self::XIAOHONGSHU_BALANCE_START))) {
$movement = $this->accountBillActivity(
'xiaohongshu',
self::XIAOHONGSHU_BALANCE_START,
$monthStart->subDay()->format('Y-m-d'),
false,
);
foreach ($movement as $storeName => $row) {
$opening[$storeName] = round(
(float) $row['income'] - (float) $row['expense'],
2,
);
}
}
if ($opening === []) {
$storeNames = AccountBill::query()
->where('company_id', company_id())
->where('bill_type', 'xiaohongshu')
->whereNull('deleted_at')
->whereNotNull('store_name')
->where('store_name', '<>', '')
->distinct()
->pluck('store_name')
->map(fn (mixed $value): string => $this->storeName($value))
->all();
foreach ($storeNames as $storeName) {
$opening[$storeName] = 0.0;
}
}
return $this->mergeStoreBalances($opening, $activity);
}
/**
* @return array<string,array{income:float,expense:float}>
*/
private function groupedActivity(
Builder|EloquentBuilder $query,
string $incomeColumn = 'income_amount',
string $expenseColumn = 'expense_amount',
): array {
$activity = [];
foreach ($query
->select('store_name')
->selectRaw(
'COALESCE(SUM(' . $incomeColumn . '), 0) AS income_total, '
. 'COALESCE(SUM(' . $expenseColumn . '), 0) AS expense_total',
)
->groupBy('store_name')
->get() as $row) {
$storeName = $this->storeName($row->store_name);
$activity[$storeName] = [
'income' => round((float) ($activity[$storeName]['income'] ?? 0) + (float) $row->income_total, 2),
'expense' => round((float) ($activity[$storeName]['expense'] ?? 0) + (float) $row->expense_total, 2),
];
}
return $activity;
}
/**
* @param array<string,float|int> $opening
* @param array<string,array{income:float,expense:float}> $activity
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function mergeStoreBalances(array $opening, array $activity): array
{
$storeNames = array_values(array_unique(array_merge(array_keys($opening), array_keys($activity))));
$rows = [];
foreach ($storeNames as $storeName) {
$rows[] = [
'store_name' => $storeName,
'opening_balance' => array_key_exists($storeName, $opening)
? round((float) $opening[$storeName], 2)
: null,
'income' => round((float) ($activity[$storeName]['income'] ?? 0), 2),
'expense' => round((float) ($activity[$storeName]['expense'] ?? 0), 2),
];
}
return $rows;
}
/**
* @param array<string,array{store_name:string,balance:float}> $base
* @param array<string,array{income:float,expense:float}> $movement
* @param array<string,array{income:float,expense:float}> $activity
* @return array<int,array{store_name:string,opening_balance:?float,income:float,expense:float}>
*/
private function mergeNormalizedStoreBalances(array $base, array $movement, array $activity): array
{
$normalizedActivity = [];
$displayNames = [];
foreach ($activity as $storeName => $row) {
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName);
$displayNames[$normalized] = $storeName;
$normalizedActivity[$normalized]['income'] = round(
(float) ($normalizedActivity[$normalized]['income'] ?? 0) + (float) $row['income'],
2,
);
$normalizedActivity[$normalized]['expense'] = round(
(float) ($normalizedActivity[$normalized]['expense'] ?? 0) + (float) $row['expense'],
2,
);
}
$storeNames = array_values(array_unique(array_merge(
array_keys($base),
array_keys($movement),
array_keys($normalizedActivity),
)));
$rows = [];
foreach ($storeNames as $normalized) {
$storeName = $displayNames[$normalized]
?? ($base[$normalized]['store_name'] ?? '未标注店铺');
$opening = array_key_exists($normalized, $base)
? round(
(float) $base[$normalized]['balance']
+ (float) ($movement[$normalized]['income'] ?? 0)
- (float) ($movement[$normalized]['expense'] ?? 0),
2,
)
: null;
$rows[] = [
'store_name' => $storeName,
'opening_balance' => $opening,
'income' => round((float) ($normalizedActivity[$normalized]['income'] ?? 0), 2),
'expense' => round((float) ($normalizedActivity[$normalized]['expense'] ?? 0), 2),
];
}
return $rows;
}
/**
* @return array<string,array{income:float,expense:float}>
*/
private function accountBillActivity(
string $billType,
string $start,
string $end,
bool $bySettlePeriod,
): array {
$query = AccountBill::query()
->where('company_id', company_id())
->where('bill_type', $billType)
->whereNull('deleted_at');
if ($bySettlePeriod) {
$query->where('payload->settle_period', '>=', substr($start, 0, 7))
->where('payload->settle_period', '<=', substr($end, 0, 7));
} else {
$query->where('occurred_at', '>=', $start . ' 00:00:00')
->where('occurred_at', '<', $this->dayAfter($end) . ' 00:00:00');
}
return $this->groupedActivity($query, 'income', 'expense');
}
private function mirrorConnection(): ConnectionInterface
{
return app(DatabaseManager::class)->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
private function storeName(mixed $value): string
{
$storeName = trim((string) $value);
return $storeName !== '' ? $storeName : '未标注店铺';
}
private function dayAfter(string $date): string
{
return CarbonImmutable::parse($date, 'Asia/Shanghai')->addDay()->format('Y-m-d');
}
/** @return iterable<int,array<string,mixed>> */
private function fetchPlatformRows(
string $platform,

View File

@ -132,11 +132,30 @@
<h3 id="monthly-closing-title">月度期末余额汇总</h3>
<span class="monthly-closing-badge">新增</span>
</div>
<p>2026 年 7-10 月各平台期末余额 · 金额单位:万元</p>
<p>
2026 年 7-10 月{{ monthlyClosingView === 'store' ? '店铺' : '各平台' }}期末余额
· 金额单位:万元
</p>
</div>
<div v-if="!monthlyClosingLoading && !monthlyClosingError" class="monthly-closing-head-actions">
<span class="monthly-closing-count">{{ monthlyClosingCountText }}</span>
<div class="monthly-closing-view-switch" role="tablist" aria-label="月度期末余额汇总方式">
<button
type="button"
role="tab"
:aria-selected="monthlyClosingView === 'platform' ? 'true' : 'false'"
:class="{ 'is-active': monthlyClosingView === 'platform' }"
@click="selectMonthlyClosingView('platform')"
>平台账户</button>
<button
type="button"
role="tab"
:aria-selected="monthlyClosingView === 'store' ? 'true' : 'false'"
:class="{ 'is-active': monthlyClosingView === 'store' }"
@click="selectMonthlyClosingView('store')"
>店铺汇总</button>
</div>
</div>
<span v-if="!monthlyClosingLoading && !monthlyClosingError" class="monthly-closing-count">
{{ monthlyClosing.summary.available_platform_count }} / {{ monthlyClosing.summary.platform_count }} 个平台
</span>
</header>
<div v-if="monthlyClosingLoading" class="monthly-closing-loading" role="status">
@ -147,7 +166,23 @@
<span>{{ monthlyClosingError }}</span>
<button type="button" @click="fetchMonthlyClosing">重新加载</button>
</div>
<div v-else class="monthly-closing-scroll">
<div
v-else-if="monthlyClosingView === 'store' && monthlyClosingStoreLoading && !monthlyStoreMonthDetails.length"
class="monthly-closing-loading"
role="status"
>
<span v-for="index in 4" :key="index"></span>
<p>正在汇总 7-10 月店铺期末余额…</p>
</div>
<div
v-else-if="monthlyClosingView === 'store' && monthlyClosingStoreError && !monthlyStoreMonthDetails.length"
class="monthly-closing-error"
role="alert"
>
<span>{{ monthlyClosingStoreError }}</span>
<button type="button" @click="fetchMonthlyClosingStores">重新加载</button>
</div>
<div v-else-if="monthlyClosingView === 'platform'" class="monthly-closing-scroll">
<table class="monthly-closing-table">
<thead>
<tr>
@ -179,9 +214,60 @@
</tbody>
</table>
</div>
<template v-else>
<div
v-if="monthlyClosingStoreLoading || monthlyClosingStoreError"
class="monthly-store-progress"
:class="{ 'is-error': monthlyClosingStoreError }"
role="status"
>
<span v-if="monthlyClosingStoreLoading">
正在补齐历史月份({{ monthlyStoreMonthDetails.length }} / {{ monthlyClosing.months.length }})…
</span>
<span v-else>{{ monthlyClosingStoreError }}</span>
<button v-if="monthlyClosingStoreError" type="button" @click="fetchMonthlyClosingStores">重新加载</button>
</div>
<div class="monthly-closing-scroll is-store">
<table class="monthly-closing-table monthly-closing-store-table">
<thead>
<tr>
<th scope="col">平台账户</th>
<th scope="col">店铺名称</th>
<th v-for="month in monthlyClosing.months" :key="month.key" scope="col" class="is-number">
{{ month.label }}
</th>
<th scope="col" class="is-number monthly-closing-compare-head">环比</th>
</tr>
</thead>
<tbody>
<tr
v-for="row in monthlyStoreRows"
:key="row.key"
:class="{ 'is-total': row.isTotal, 'is-unavailable': !row.available }"
>
<th scope="row">{{ row.platform }}</th>
<td class="monthly-store-name">{{ row.store_name }}</td>
<td v-for="month in monthlyClosing.months" :key="month.key" class="is-number">
{{ monthlyBalanceWan(row, month.key) }}
</td>
<td class="is-number monthly-closing-compare">
<span :class="changeClass(row.change.amount)">{{ signedMoneyWan(row.change.amount) }}</span>
<small v-if="row.change.rate !== null" :class="changeClass(row.change.amount)">
{{ signedPercent(row.change.rate) }}
</small>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<footer class="monthly-closing-foot">
<span>环比口径:2026年10月期末余额 − 2026年9月期末余额,金额单位为万元,百分比以上月余额为基数。</span>
<span v-if="!monthlyClosingLoading && !monthlyClosingError">8 个平台沿用各自账单页的期末余额口径。</span>
<span v-if="!monthlyClosingLoading && !monthlyClosingError">
{{ monthlyClosingView === 'store'
? '店铺期末余额 = 期初余额 + 收入 - 支出;缺少期初时显示“—”。'
: '8 个平台沿用各自账单页的期末余额口径。' }}
</span>
</footer>
</section>
@ -240,13 +326,13 @@
role="tab"
:aria-selected="detailTab === tab.key ? 'true' : 'false'"
:class="{ 'is-active': detailTab === tab.key }"
@click="detailTab = tab.key"
@click="selectDetailTab(tab.key)"
>{{ tab.label }}</button>
</div>
<div v-if="detailError" class="flow-detail-state is-error" role="alert">
<span>{{ detailError }}</span>
<button type="button" @click="fetchDetails">重新加载</button>
<button type="button" @click="retryDetails">重新加载</button>
</div>
<div v-else-if="detailLoading" class="flow-detail-state" role="status">正在汇总各平台{{ detailFlowLabel }}明细…</div>
<div v-else class="flow-detail-table-wrap">
@ -264,13 +350,17 @@
</table>
<table v-else-if="detailTab === 'store'" class="flow-detail-table">
<thead>
<tr><th scope="col">平台</th><th scope="col">店铺</th><th scope="col" class="is-number">{{ detailFlowLabel }}金额(万元)</th></tr>
<tr>
<th scope="col">平台</th>
<th scope="col">{{ detailFlow === 'balance' ? '店铺名称' : '店铺' }}</th>
<th scope="col" class="is-number">{{ detailFlow === 'balance' ? '期末余额(万元)' : `${detailFlowLabel}金额(万元)` }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in detailRows" :key="row.key">
<td>{{ row.platform }}</td>
<td>{{ row.store_name }}</td>
<td class="is-number">{{ moneyWan(row.amount) }}</td>
<td class="is-number" :title="row.amount === null ? '该店铺缺少期初余额,暂不能计算期末余额' : ''">{{ moneyWan(row.amount) }}</td>
</tr>
<tr v-if="!detailRows.length"><td colspan="3" class="flow-detail-empty">当前筛选范围内暂无{{ detailFlowLabel }}明细</td></tr>
</tbody>
@ -338,6 +428,19 @@ const dateConfig = {
onReady: (_, value, picker) => picker.calendarContainer.classList.add('overview-calendar'),
};
const closingChange = (balances, currentMonth, previousMonth) => {
const current = balances[currentMonth];
const previous = balances[previousMonth];
const amount = Number.isFinite(current) && Number.isFinite(previous)
? Math.round((current - previous) * 100) / 100
: null;
const rate = amount !== null && Math.abs(previous) >= 0.005
? Math.round((amount / Math.abs(previous)) * 10000) / 100
: (amount === 0 ? 0 : null);
return { amount, rate };
};
export default {
name: 'StoreReceivingBalanceOverview',
components: { flatPicker },
@ -360,6 +463,8 @@ export default {
detailLoading: false,
detailError: '',
detailDetails: [],
detailStoreDetails: [],
detailStoreLoaded: false,
detailRequestSerial: 0,
detailTab: 'platform',
detailPlatform: '',
@ -369,6 +474,12 @@ export default {
monthlyClosingLoading: true,
monthlyClosingError: '',
monthlyClosingRequestSerial: 0,
monthlyClosingView: 'platform',
monthlyClosingStoreLoading: false,
monthlyClosingStoreError: '',
monthlyClosingStoreLoaded: false,
monthlyClosingStoreRequestSerial: 0,
monthlyStoreMonthDetails: [],
monthlyClosing: {
months: [],
summary: {
@ -376,6 +487,10 @@ export default {
available_platform_count: 0,
complete: false,
},
comparison: {
current: '2026-10',
previous: '2026-09',
},
total: null,
platforms: [],
},
@ -460,12 +575,15 @@ export default {
},
detailDescription() {
return this.detailFlow === 'balance'
? '按平台汇总期末余额'
? '按平台和店铺汇总期末余额'
: '按平台、店铺和账单项目汇总';
},
detailTabs() {
if (this.detailFlow === 'balance') {
return [{ key: 'platform', label: '平台' }];
return [
{ key: 'platform', label: '平台' },
{ key: 'store', label: '店铺名称' },
];
}
return [
@ -501,7 +619,11 @@ export default {
)].sort((left, right) => left.localeCompare(right, 'zh-CN'));
},
detailFilteredDetails() {
return this.detailDetails.filter((row) => (
const details = this.detailFlow === 'balance' && this.detailTab === 'store'
? this.detailStoreDetails
: this.detailDetails;
return details.filter((row) => (
(!this.detailPlatform || row.platform_slug === this.detailPlatform)
&& (!this.detailStore || row.store_name === this.detailStore)
&& (!this.detailBillItem || row.bill_item === this.detailBillItem)
@ -509,6 +631,9 @@ export default {
},
detailFilteredTotal() {
if (this.detailLoading || this.detailError) return null;
if (this.detailFilteredDetails.some(row => row.amount === null || row.amount === undefined)) {
return null;
}
return this.detailFilteredDetails.reduce(
(total, row) => total + Number(row.amount || 0),
@ -547,14 +672,21 @@ export default {
platform: row.platform,
store_name: row.store_name,
bill_item: row.bill_item,
amount: 0,
amount: row.amount === null ? null : 0,
};
current.amount += Number(row.amount || 0);
if (current.amount === null || row.amount === null || row.amount === undefined) {
current.amount = null;
} else {
current.amount += Number(row.amount || 0);
}
grouped.set(key, current);
});
return Array.from(grouped.values())
.map(row => ({ ...row, amount: Math.round(row.amount * 100) / 100 }))
.map(row => ({
...row,
amount: row.amount === null ? null : Math.round(row.amount * 100) / 100,
}))
.sort((left, right) => {
if (this.detailTab === 'platform') {
return (platformOrder.get(left.platform_slug) ?? 99)
@ -562,7 +694,9 @@ export default {
}
return (
right.amount - left.amount
(left.amount === null ? 1 : 0) - (right.amount === null ? 1 : 0)
|| (left.amount === null ? 0 : right.amount)
- (left.amount === null ? 0 : left.amount)
|| (platformOrder.get(left.platform_slug) ?? 99)
- (platformOrder.get(right.platform_slug) ?? 99)
|| String(left.store_name).localeCompare(String(right.store_name), 'zh-CN')
@ -580,6 +714,81 @@ export default {
...(Array.isArray(this.monthlyClosing.platforms) ? this.monthlyClosing.platforms : []),
];
},
monthlyClosingCountText() {
if (this.monthlyClosingView === 'platform') {
return `${this.monthlyClosing.summary.available_platform_count} / ${this.monthlyClosing.summary.platform_count} 个平台`;
}
if (this.monthlyClosingStoreLoading) return '正在读取店铺…';
if (this.monthlyClosingStoreError) return '店铺数据暂不可用';
const total = this.monthlyStoreRows.filter(row => !row.isTotal).length;
const incomplete = this.monthlyStoreRows.filter(row => !row.isTotal && !row.available).length;
return incomplete > 0
? `${total} 个店铺 · ${incomplete} 个期初待补`
: `${total} 个店铺`;
},
monthlyStoreRows() {
const months = Array.isArray(this.monthlyClosing.months)
? this.monthlyClosing.months.map(month => month.key)
: [];
const platformOrder = new Map(
this.monthlyClosing.platforms.map((platform, index) => [platform.slug, index]),
);
const grouped = new Map();
this.monthlyStoreMonthDetails.forEach((result) => {
(Array.isArray(result.details) ? result.details : []).forEach((detail) => {
const key = [detail.platform_slug, detail.store_name].join('|');
const row = grouped.get(key) || {
key,
platform_slug: detail.platform_slug,
platform: detail.platform,
store_name: detail.store_name,
balances: Object.fromEntries(months.map(month => [month, null])),
};
row.balances[result.month] = detail.amount === null || detail.amount === undefined
? null
: (Number.isFinite(Number(detail.amount))
? Math.round(Number(detail.amount) * 100) / 100
: null);
grouped.set(key, row);
});
});
const currentMonth = this.monthlyClosing.comparison.current;
const previousMonth = this.monthlyClosing.comparison.previous;
const rows = Array.from(grouped.values()).map(row => ({
...row,
available: months.some(month => row.balances[month] !== null),
change: closingChange(row.balances, currentMonth, previousMonth),
}));
const latestMonth = months[months.length - 1];
rows.sort((left, right) => {
const leftBalance = left.balances[latestMonth];
const rightBalance = right.balances[latestMonth];
return (
(leftBalance === null ? 1 : 0) - (rightBalance === null ? 1 : 0)
|| (leftBalance === null ? 0 : rightBalance)
- (leftBalance === null ? 0 : leftBalance)
|| (platformOrder.get(left.platform_slug) ?? 99)
- (platformOrder.get(right.platform_slug) ?? 99)
|| left.store_name.localeCompare(right.store_name, 'zh-CN')
);
});
if (!this.monthlyClosing.total) return rows;
return [{
...this.monthlyClosing.total,
key: 'monthly-store-total',
platform: '合计',
store_name: `合计 · ${rows.length} 个店铺`,
isTotal: true,
available: true,
}, ...rows];
},
},
mounted() {
this.fetchOverview();
@ -627,6 +836,9 @@ export default {
const requestId = ++this.monthlyClosingRequestSerial;
this.monthlyClosingLoading = true;
this.monthlyClosingError = '';
++this.monthlyClosingStoreRequestSerial;
this.monthlyClosingStoreLoaded = false;
this.monthlyStoreMonthDetails = [];
try {
const response = await window.axios.get(`${this.apiBase}/monthly-closing`);
@ -640,9 +852,17 @@ export default {
complete: false,
...(body.summary || {}),
},
comparison: {
current: '2026-10',
previous: '2026-09',
...(body.comparison || {}),
},
total: body.total || null,
platforms: Array.isArray(body.platforms) ? body.platforms : [],
};
if (this.monthlyClosingView === 'store') {
this.fetchMonthlyClosingStores();
}
} catch (error) {
if (requestId !== this.monthlyClosingRequestSerial) return;
this.monthlyClosingError = (error.response && error.response.data && error.response.data.message)
@ -653,6 +873,55 @@ export default {
}
}
},
selectMonthlyClosingView(view) {
if (!['platform', 'store'].includes(view) || this.monthlyClosingView === view) return;
this.monthlyClosingView = view;
if (view === 'store' && !this.monthlyClosingStoreLoaded && !this.monthlyClosingStoreLoading) {
this.fetchMonthlyClosingStores();
}
},
async fetchMonthlyClosingStores() {
const months = Array.isArray(this.monthlyClosing.months) ? this.monthlyClosing.months : [];
if (!months.length) return;
const requestId = ++this.monthlyClosingStoreRequestSerial;
this.monthlyClosingStoreLoading = true;
this.monthlyClosingStoreError = '';
this.monthlyStoreMonthDetails = [];
try {
for (const month of months) {
const [year, monthNumber] = month.key.split('-').map(Number);
const lastDay = new Date(year, monthNumber, 0).getDate();
const response = await window.axios.get(`${this.apiBase}/balance-store-detail`, {
params: {
start: `${month.key}-01`,
end: `${month.key}-${pad(lastDay)}`,
},
});
if (requestId !== this.monthlyClosingStoreRequestSerial) return;
this.monthlyStoreMonthDetails = [...this.monthlyStoreMonthDetails, {
month: month.key,
details: Array.isArray(response.data && response.data.details)
? response.data.details
: [],
}];
}
if (requestId !== this.monthlyClosingStoreRequestSerial) return;
this.monthlyClosingStoreLoaded = true;
} catch (error) {
if (requestId !== this.monthlyClosingStoreRequestSerial) return;
this.monthlyClosingStoreLoaded = false;
this.monthlyClosingStoreError = (error.response && error.response.data && error.response.data.message)
|| '店铺月度期末余额暂时无法读取,请稍后重试。';
} finally {
if (requestId === this.monthlyClosingStoreRequestSerial) {
this.monthlyClosingStoreLoading = false;
}
}
},
changeDate(field, value) {
const date = value || '';
if (this.dateRange[field] === date) return;
@ -671,6 +940,8 @@ export default {
this.detailStore = '';
this.detailBillItem = '';
this.detailDetails = [];
this.detailStoreDetails = [];
this.detailStoreLoaded = false;
this.detailError = '';
this.lockDetailScroll();
this.$nextTick(() => {
@ -704,12 +975,55 @@ export default {
} catch (error) {
if (requestId !== this.detailRequestSerial || !this.detailOpen) return;
this.detailDetails = [];
this.detailStoreDetails = [];
this.detailError = (error.response && error.response.data && error.response.data.message)
|| `${this.detailFlowLabel}明细暂时无法读取,请稍后重试。`;
} finally {
if (requestId === this.detailRequestSerial) this.detailLoading = false;
}
},
async selectDetailTab(tab) {
if (this.detailTab === tab) return;
this.detailTab = tab;
this.detailError = '';
if (this.detailFlow === 'balance' && tab === 'store' && !this.detailStoreLoaded) {
await this.fetchStoreBalanceDetails();
}
},
async fetchStoreBalanceDetails() {
const requestId = ++this.detailRequestSerial;
this.detailLoading = true;
this.detailError = '';
try {
const response = await window.axios.get(`${this.apiBase}/balance-store-detail`, {
params: {
start: this.queryRange.start,
end: this.queryRange.end,
},
});
if (requestId !== this.detailRequestSerial || !this.detailOpen) return;
const body = response.data || {};
this.detailStoreDetails = Array.isArray(body.details) ? body.details : [];
this.detailStoreLoaded = true;
} catch (error) {
if (requestId !== this.detailRequestSerial || !this.detailOpen) return;
this.detailStoreDetails = [];
this.detailStoreLoaded = false;
this.detailError = (error.response && error.response.data && error.response.data.message)
|| '店铺期末余额明细暂时无法读取,请稍后重试。';
} finally {
if (requestId === this.detailRequestSerial) this.detailLoading = false;
}
},
retryDetails() {
if (this.detailFlow === 'balance' && this.detailTab === 'store') {
this.fetchStoreBalanceDetails();
return;
}
this.fetchDetails();
},
normalizeDetailFilters() {
if (this.detailPlatform
&& !this.detailPlatformOptions.some(item => item.slug === this.detailPlatform)) {
@ -1185,10 +1499,79 @@ export default {
font-size: .6875rem;
font-weight: 600;
}
.monthly-closing-head-actions {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: .75rem;
}
.monthly-closing-view-switch {
display: inline-flex;
padding: 2px;
border: 1px solid #d8cdbc;
border-radius: .5rem;
background: #f7f1e5;
}
.monthly-closing-view-switch button {
height: 1.9rem;
padding: 0 .75rem;
border: 0;
border-radius: .38rem;
background: transparent;
color: var(--overview-muted);
font: 600 .6875rem/1.2 inherit;
white-space: nowrap;
cursor: pointer;
}
.monthly-closing-view-switch button:hover {
color: var(--overview-gold);
}
.monthly-closing-view-switch button.is-active {
background: #fffdf8;
color: var(--overview-gold);
box-shadow: 0 1px 2px rgba(63, 50, 29, .10);
}
.monthly-closing-view-switch button:focus-visible {
box-shadow: 0 0 0 3px rgba(138, 104, 47, .18);
outline: none;
}
.monthly-closing-scroll {
overflow-x: auto;
overscroll-behavior-inline: contain;
}
.monthly-closing-scroll.is-store {
max-height: 30rem;
overflow: auto;
}
.monthly-closing-scroll.is-store .monthly-closing-table thead th {
position: sticky;
z-index: 2;
top: 0;
}
.monthly-store-progress {
display: flex;
align-items: center;
justify-content: space-between;
gap: .75rem;
padding: .5rem .8rem;
border-bottom: 1px solid #eee7da;
background: #fbf7ef;
color: var(--overview-muted);
font-size: .6875rem;
}
.monthly-store-progress.is-error {
background: #fff6f3;
color: #9b3c2d;
}
.monthly-store-progress button {
padding: .2rem .55rem;
border: 1px solid currentColor;
border-radius: .35rem;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
}
.monthly-closing-table {
width: 100%;
min-width: 44rem;
@ -1197,6 +1580,9 @@ export default {
font-size: .75rem;
font-variant-numeric: tabular-nums;
}
.monthly-closing-store-table {
min-width: 60rem;
}
.monthly-closing-table th,
.monthly-closing-table td {
padding: .65rem .8rem;
@ -1246,6 +1632,9 @@ export default {
.monthly-closing-table tbody tr.is-unavailable td {
color: #937b57;
}
.monthly-closing-store-table .monthly-store-name {
min-width: 15rem;
}
.monthly-closing-compare span,
.monthly-closing-compare small {
display: block;
@ -1275,6 +1664,10 @@ export default {
font-size: .625rem;
}
.monthly-closing-loading,
.monthly-closing-error {
min-height: 6rem;
}
.monthly-closing-loading,
.monthly-closing-error {
padding: 1rem;
}
@ -1608,6 +2001,11 @@ export default {
align-items: flex-start;
flex-direction: column;
}
.monthly-closing-head-actions {
width: 100%;
flex-wrap: wrap;
justify-content: space-between;
}
.monthly-closing-foot {
align-items: flex-start;
flex-direction: column;

View File

@ -0,0 +1,347 @@
@php
$base = $kukaPostingBase ?? [];
$directory = $base['directory'] ?? ['fields' => [], 'empty' => '基础数据尚未导入。'];
$baseRows = $base['rows'] ?? collect();
$filters = $base['filters'] ?? [];
$periods = $base['periods'] ?? [];
$statuses = $base['statuses'] ?? [];
$stores = $base['stores'] ?? [];
$import = $base['import'] ?? null;
$summary = $base['summary'] ?? [];
$error = $base['error'] ?? null;
$resetUrl = route('business.pages.show', ['section' => 'posting-data', 'page' => 'kuka-basic-data']);
@endphp
<style>
.kuka-base-page {
--kb-gold: var(--vip-content-accent, #b9954f);
--kb-gold-dark: var(--vip-content-accent-dark, #856632);
--kb-gold-soft: var(--vip-content-accent-soft, #f7f0de);
--kb-border: var(--vip-border, #d8d2c7);
--kb-ink: var(--vip-content-ink, #171717);
--kb-muted: var(--vip-content-muted, #595959);
color: var(--kb-ink);
}
.kuka-base-page * { box-sizing: border-box; }
.kuka-base-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
margin-bottom: 1rem;
}
.kuka-base-head__title {
display: flex;
align-items: flex-start;
gap: 0.65rem;
}
.kuka-base-head__title > .material-icons-outlined {
color: var(--kb-gold-dark);
font-size: 1.35rem;
}
.kuka-base-head strong {
display: block;
font-size: 0.875rem;
line-height: 1.3;
}
.kuka-base-head p {
max-width: 74rem;
margin: 0.35rem 0 0;
color: var(--kb-muted);
font-size: 0.75rem;
line-height: 1.55;
}
.kuka-base-source {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 0.35rem;
max-width: 24rem;
padding: 0.3rem 0.65rem;
border: 1px solid #d9c89c;
border-radius: 999px;
background: #fbf7ec;
color: var(--kb-gold-dark);
font-size: 0.72rem;
font-weight: 600;
white-space: nowrap;
}
.kuka-base-alert {
display: flex;
align-items: flex-start;
gap: 0.45rem;
margin-bottom: 1rem;
padding: 0.75rem 0.85rem;
border: 1px solid #dfbbbb;
border-radius: 0.6rem;
background: #fff4f4;
color: var(--vip-danger, #b80000);
font-size: 0.75rem;
line-height: 1.55;
}
.kuka-base-summary {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.7rem;
margin-bottom: 1rem;
}
.kuka-base-card {
min-width: 0;
padding: 0.8rem 0.9rem;
border: 1px solid var(--kb-border);
border-radius: 0.65rem;
background: #fffdf8;
}
.kuka-base-card span {
display: block;
color: var(--kb-muted);
font-size: 0.7rem;
line-height: 1.4;
}
.kuka-base-card strong {
display: block;
margin-top: 0.25rem;
overflow: hidden;
color: var(--kb-ink);
font-size: 1.05rem;
font-weight: 700;
line-height: 1.3;
text-overflow: ellipsis;
white-space: nowrap;
}
.kuka-base-card small {
display: block;
margin-top: 0.22rem;
overflow: hidden;
color: var(--kb-muted);
font-size: 0.68rem;
line-height: 1.4;
text-overflow: ellipsis;
white-space: nowrap;
}
.kuka-base-filter {
display: grid;
grid-template-columns: minmax(8rem, 0.8fr) minmax(13rem, 1.4fr) minmax(8rem, 0.8fr) minmax(15rem, 2fr) minmax(7rem, 0.7fr) auto;
align-items: end;
gap: 0.65rem;
margin-bottom: 1rem;
padding: 0.9rem 1rem;
border: 1px solid var(--kb-border);
border-radius: 0.75rem;
background: #fff;
}
.kuka-base-filter label {
display: grid;
min-width: 0;
gap: 0.28rem;
color: var(--kb-muted);
font-size: 0.7rem;
font-weight: 500;
}
.kuka-base-filter select,
.kuka-base-filter input {
width: 100%;
height: 2.125rem;
min-width: 0;
padding: 0 0.65rem;
border: 1px solid var(--kb-border);
border-radius: 0.5rem;
background: #fff;
color: var(--kb-ink);
font: inherit;
font-size: 0.75rem;
outline: none;
}
.kuka-base-filter select:focus,
.kuka-base-filter input:focus {
border-color: var(--kb-gold-dark);
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.16);
}
.kuka-base-filter__actions {
display: flex;
gap: 0.45rem;
}
.kuka-base-filter__actions button,
.kuka-base-filter__actions a {
display: inline-flex;
height: 2.125rem;
align-items: center;
justify-content: center;
padding: 0 0.85rem;
border-radius: 0.5rem;
font: inherit;
font-size: 0.75rem;
text-decoration: none;
white-space: nowrap;
}
.kuka-base-filter__actions button {
border: 1px solid var(--kb-gold-dark);
background: var(--kb-gold-dark);
color: #fff;
cursor: pointer;
}
.kuka-base-filter__actions a {
border: 1px solid var(--kb-border);
background: #fff;
color: var(--kb-ink);
}
.kuka-base-import-note {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.45rem 1rem;
margin: -0.1rem 0 1rem;
color: var(--kb-muted);
font-size: 0.7rem;
line-height: 1.5;
}
.kuka-base-import-note code {
max-width: 36rem;
overflow: hidden;
color: var(--kb-ink);
font-size: 0.7rem;
text-overflow: ellipsis;
white-space: nowrap;
}
@media (max-width: 1180px) {
.kuka-base-filter { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.kuka-base-filter__actions { grid-column: 1 / -1; }
}
@media (max-width: 760px) {
.kuka-base-head { flex-direction: column; }
.kuka-base-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.kuka-base-filter { grid-template-columns: 1fr; }
}
</style>
<div class="kuka-base-page">
<header class="kuka-base-head">
<div class="kuka-base-head__title">
<span class="material-icons-outlined" aria-hidden="true">dataset</span>
<div>
<strong>顾家过账 · 基础数据</strong>
<p>从聚水潭销售主题分析(新版)的“商品利润 → 明细(订单商品)”导入原始明细。这里只展示指定 12 家店铺的原始字段,不执行成本映射、报价或过账分类。</p>
</div>
</div>
<span class="kuka-base-source" title="{{ config('kuka_posting.source_name') }}">聚水潭共享镜像</span>
</header>
@if ($error)
<div class="kuka-base-alert" role="alert">
<span class="material-icons-outlined" aria-hidden="true">error_outline</span>
<span>{{ $error }}</span>
</div>
@endif
<section class="kuka-base-summary" aria-label="基础数据汇总">
<article class="kuka-base-card">
<span>账期</span>
<strong>{{ $filters['period'] ?? '—' }}</strong>
<small>当前筛选账期</small>
</article>
<article class="kuka-base-card">
<span>原始数据行</span>
<strong>{{ number_format((int) ($summary['rows'] ?? 0)) }}</strong>
<small>当前筛选 {{ number_format((int) ($summary['filtered_rows'] ?? 0)) }} 行</small>
</article>
<article class="kuka-base-card">
<span>店铺 / 订单</span>
<strong>{{ number_format((int) ($summary['stores'] ?? 0)) }} / {{ number_format((int) ($summary['orders'] ?? 0)) }}</strong>
<small>仅包含指定店铺</small>
</article>
<article class="kuka-base-card">
<span>最近导入</span>
<strong>{{ $summary['completed_at'] ? \Illuminate\Support\Carbon::parse($summary['completed_at'])->format('Y-m-d H:i') : '尚未导入' }}</strong>
<small>{{ $import['source_sheet'] ?? '等待首次导入' }}</small>
</article>
</section>
<form class="kuka-base-filter" method="GET" action="{{ route('business.pages.show', ['section' => 'posting-data', 'page' => 'kuka-basic-data']) }}">
<label>
账期
<select name="period">
@if ($periods === [])
<option value="{{ $filters['period'] ?? '' }}">{{ $filters['period'] ?? '尚无数据' }}</option>
@endif
@foreach ($periods as $period)
<option value="{{ $period }}" @selected(($filters['period'] ?? '') === $period)>{{ $period }}</option>
@endforeach
</select>
</label>
<label>
店铺
<select name="store_name">
<option value="">全部指定店铺</option>
@foreach ($stores as $store)
<option value="{{ $store }}" @selected(($filters['store_name'] ?? '') === $store)>{{ $store }}</option>
@endforeach
</select>
</label>
<label>
订单状态
<select name="status">
<option value="">全部状态</option>
@foreach ($statuses as $status)
<option value="{{ $status }}" @selected(($filters['status'] ?? '') === $status)>{{ $status }}</option>
@endforeach
</select>
</label>
<label>
内部单号 / 线上单号 / 商品编码
<input type="search" name="keyword" value="{{ $filters['keyword'] ?? '' }}" placeholder="输入单号或商品编码" autocomplete="off">
</label>
<label>
每页
<select name="per_page">
@foreach ([50, 100, 200] as $size)
<option value="{{ $size }}" @selected((int) ($filters['per_page'] ?? 50) === $size)>{{ $size }} 行</option>
@endforeach
</select>
</label>
<div class="kuka-base-filter__actions">
<button type="submit">查询</button>
<a href="{{ $resetUrl }}">重置</a>
</div>
</form>
@if ($import)
<div class="kuka-base-import-note" aria-label="导入来源">
<span>来源文件:<code title="{{ $import['file_name'] }}">{{ $import['file_name'] }}</code></span>
<span>工作表:{{ $import['source_sheet'] }}</span>
<span>SHA-256:{{ substr($import['file_sha256'], 0, 12) }}…</span>
</div>
@endif
@include('business.pages.partials.directory-table', [
'directory' => $directory,
'rows' => $baseRows,
'section' => $section,
'page' => $page,
'upstreamError' => $error,
])
</div>

View File

@ -767,7 +767,7 @@
</div>
</td>
<td class="sys-todo-table__immutable" title="创建后不可修改" data-sys-todo-immutable="created_by">{{ $item->creator?->name ?: '—' }}</td>
<td class="sys-todo-table__immutable sys-todo-table__immutable-time" title="创建后不可修改" data-sys-todo-immutable="created_at">{{ $item->created_at?->format('Y-m-d H:i') ?: '—' }}</td>
<td class="sys-todo-table__immutable sys-todo-table__immutable-time" title="创建后不可修改" data-sys-todo-immutable="created_at">{{ $item->creationTimeLabel() ?: '—' }}</td>
@php($ownerNames = $personNames($item->owner_display ?? null))
<td class="sys-todo-table__people">
<span class="sys-todo-grid-value"

View File

@ -47,6 +47,8 @@ Route::get('ecommerce-finance/account-bills/overview/expense-detail', [StoreRece
->name('ecommerce-finance.account-bills.overview.expense-detail');
Route::get('ecommerce-finance/account-bills/overview/balance-detail', [StoreReceivingBalanceOverview::class, 'balanceDetail'])
->name('ecommerce-finance.account-bills.overview.balance-detail');
Route::get('ecommerce-finance/account-bills/overview/balance-store-detail', [StoreReceivingBalanceOverview::class, 'balanceStoreDetail'])
->name('ecommerce-finance.account-bills.overview.balance-store-detail');
Route::get('ecommerce-finance/alipay-bills', [AlipayBills::class, 'index'])
->name('ecommerce-finance.alipay-bills.index');
Route::get('ecommerce-finance/alipay-bills/export', [AlipayBills::class, 'export'])

View File

@ -0,0 +1,205 @@
<?php
namespace Tests\Feature\Business;
use Illuminate\Support\Facades\DB;
use Tests\Feature\FeatureTestCase;
use ZipArchive;
class KukaPostingBasePageTest extends FeatureTestCase
{
public function test_imports_only_requested_stores_and_renders_paginated_base_data(): void
{
$file = $this->workbook();
$this->artisan('business-mirror:import-kuka-posting-base', [
'path' => $file,
'--month' => '2026-10',
'--company' => (string) $this->company->id,
])->assertExitCode(0);
$connection = DB::connection('business_mirror');
$this->assertSame(12, $connection->table('kuka_posting_base_rows')->count());
$this->assertDatabaseHas('kuka_posting_base_imports', [
'company_id' => $this->company->id,
'period' => '2026-10',
'row_count' => 12,
'store_count' => 12,
], 'business_mirror');
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'posting-data',
'page' => 'kuka-basic-data',
'store_name' => '天猫-HX旗舰店101',
]))
->assertOk()
->assertSeeText('顾家过账 · 基础数据')
->assertSeeText('内部订单号')
->assertSeeText('发货金额')
->assertSeeText('聚水潭共享镜像')
->assertSeeText('KUKA-00')
->assertSeeText('SKU-00')
->assertDontSeeText('KUKA-01')
->assertDontSeeText('SKU-01');
@unlink($file);
}
public function test_incomplete_store_export_keeps_the_previous_period_data(): void
{
$complete = $this->workbook();
$this->artisan('business-mirror:import-kuka-posting-base', [
'path' => $complete,
'--month' => '2026-10',
'--company' => (string) $this->company->id,
])->assertExitCode(0);
$incomplete = $this->workbook(skipFirstStore: true);
$this->artisan('business-mirror:import-kuka-posting-base', [
'path' => $incomplete,
'--month' => '2026-10',
'--company' => (string) $this->company->id,
])->assertExitCode(1);
$this->assertSame(
12,
DB::connection('business_mirror')->table('kuka_posting_base_rows')
->where('period', '2026-10')
->count(),
);
@unlink($complete);
@unlink($incomplete);
}
private function workbook(bool $skipFirstStore = false): string
{
$fields = config('kuka_posting.fields');
$headers = array_column($fields, 'source');
$stores = array_values(config('kuka_posting.stores'));
$rows = [];
foreach ($stores as $index => $store) {
if ($skipFirstStore && $index === 0) {
continue;
}
$rows[] = [
'内部订单号' => sprintf('KUKA-%02d', $index),
'标记多标签' => '测试标签',
'售后单号' => '',
'订单类型' => '普通订单',
'线上订单号' => sprintf('ONLINE-%02d', $index),
'订单状态' => '已发货',
'发货仓' => '测试仓',
'运营云仓' => '测试云仓',
'分销商' => '',
'货主分销' => '',
'店铺' => $store,
'买家账号' => 'buyer' . $index,
'卖家备注' => '测试备注',
'订单日期' => '2026-10-01 10:00:00',
'发货日期' => '2026-10-02 11:00:00',
'付款日期' => '2026-10-01 09:30:00',
'确认收货日期' => '2026-10-05 12:00:00',
'省' => '江苏省',
'市' => '常州市',
'区县' => '新北区',
'订单快递公司' => '测试快递',
'订单快递单号' => 'EXP-' . $index,
'售后快递公司' => '',
'售后快递单号' => '',
'收货人' => '测试收货人',
'售后登记日期' => '',
'售后确认日期' => '',
'收货仓' => '',
'售后分类' => '',
'问题类型' => '',
'商品编码' => sprintf('SKU-%02d', $index),
'原始线上订单号' => sprintf('ONLINE-%02d', $index),
'款式编码' => sprintf('STYLE-%02d', $index),
'货号' => sprintf('ITEM-%02d', $index),
'物料编号' => sprintf('MAT-%02d', $index),
'型号' => '测试型号',
'成本' => '100.00',
'产品材质' => '板材',
'实发数量' => '1',
'发货金额' => '199.00',
];
}
$path = tempnam(sys_get_temp_dir(), 'kuka-posting-base-') . '.xlsx';
$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFromString('xl/workbook.xml', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="汇总" sheetId="1" r:id="rId1"/>
<sheet name="发货明细表" sheetId="2" r:id="rId2"/>
</sheets>
</workbook>
XML);
$zip->addFromString('xl/_rels/workbook.xml.rels', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/>
</Relationships>
XML);
$zip->addFromString('xl/worksheets/sheet1.xml', $this->worksheetXml([['汇总']]));
$zip->addFromString('xl/worksheets/sheet2.xml', $this->worksheetXml(array_merge([$headers], $rows)));
$zip->close();
return $path;
}
/**
* @param list<array<int, string>|array<string, string>> $rows
*/
private function worksheetXml(array $rows): string
{
$xmlRows = [];
foreach ($rows as $rowIndex => $row) {
$cells = [];
$values = array_is_list($row) ? $row : $this->rowValues($row);
foreach ($values as $columnIndex => $value) {
$reference = $this->columnName($columnIndex + 1) . ($rowIndex + 1);
$cells[] = '<c r="' . $reference . '" t="inlineStr"><is><t>'
. htmlspecialchars((string) $value, ENT_XML1 | ENT_QUOTES, 'UTF-8')
. '</t></is></c>';
}
$xmlRows[] = '<row r="' . ($rowIndex + 1) . '">' . implode('', $cells) . '</row>';
}
return '<?xml version="1.0" encoding="UTF-8"?>'
. '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
. '<sheetData>' . implode('', $xmlRows) . '</sheetData></worksheet>';
}
/**
* @param array<string, string> $row
* @return list<string>
*/
private function rowValues(array $row): array
{
return array_map(
static fn (array $field): string => (string) ($row[$field['source']] ?? ''),
config('kuka_posting.fields'),
);
}
private function columnName(int $index): string
{
$name = '';
while ($index > 0) {
$index--;
$name = chr(65 + ($index % 26)) . $name;
$index = intdiv($index, 26);
}
return $name;
}
}

View File

@ -245,4 +245,47 @@ class StoreReceivingBalanceOverviewEndpointTest extends FeatureTestCase
->assertJsonPath('details.0.platform_slug', 'taobao-alipay')
->assertJsonPath('details.0.amount', 218.88);
}
public function test_balance_store_detail_endpoint_returns_store_closing_balances(): void
{
$this->user->attachPermission(
Permission::where('name', 'read-admin-panel')->firstOrFail()
);
$payload = [
'month' => '2026-10',
'period' => ['start' => '2026-10-01', 'end' => '2026-10-31'],
'summary' => [
'balance' => 1049.07,
'platform_count' => 8,
'available_platform_count' => 8,
'store_count' => 1,
'ready_store_count' => 1,
'complete' => true,
],
'details' => [[
'platform_slug' => 'taobao-alipay',
'platform' => '淘系支付宝账户',
'store_name' => '测试店铺',
'bill_item' => '',
'opening_balance' => 100.0,
'income' => 130.0,
'expense' => 10.0,
'amount' => 220.0,
'available' => true,
]],
];
$service = Mockery::mock(StoreReceivingBalanceOverviewService::class);
$service->shouldReceive('balanceStoreDetail')->once()->with('2026-10')->andReturn($payload);
$this->app->instance(StoreReceivingBalanceOverviewService::class, $service);
$this->loginAs()
->getJson(route('ecommerce-finance.account-bills.overview.balance-store-detail', [
'month' => '2026-10',
]))
->assertOk()
->assertJsonPath('summary.complete', true)
->assertJsonPath('details.0.store_name', '测试店铺')
->assertJsonPath('details.0.amount', 220);
}
}

View File

@ -1361,7 +1361,7 @@ class SystemizationTodosTest extends FeatureTestCase
$creatorId = (int) $todo->created_by;
$createdAt = $todo->created_at->format('Y-m-d H:i:s');
$displayedCreatedAt = $todo->created_at->format('Y-m-d H:i');
$displayedCreatedAt = $todo->creationTimeLabel();
$this->get(route('business.pages.show', [
'section' => 'other',
@ -1402,6 +1402,43 @@ class SystemizationTodosTest extends FeatureTestCase
}
}
public function test_creation_time_is_displayed_in_the_platform_timezone(): void
{
$originalTimezone = config('app.timezone');
$originalPlatformTimezone = config('app.platform_timezone');
try {
config([
'app.timezone' => 'Europe/London',
'app.platform_timezone' => 'Asia/Shanghai',
]);
date_default_timezone_set('Europe/London');
Carbon::setTestNow('2026-11-10 08:21:30');
$this->loginAs();
$todo = $this->createTodo('收入', '创建时间测试', '创建时间按上海展示', '2026-11-12', 1);
$todo->refresh();
$this->assertSame('2026-11-10 08:21', $todo->created_at->format('Y-m-d H:i'));
$this->assertSame('2026-11-10 16:21', $todo->creationTimeLabel());
$this->get(route('business.pages.show', [
'section' => 'other',
'page' => 'systemization-todos',
]))->assertOk()->assertSee(
'data-sys-todo-immutable="created_at">2026-11-10 16:21</td>',
false,
);
} finally {
Carbon::setTestNow();
config([
'app.timezone' => $originalTimezone,
'app.platform_timezone' => $originalPlatformTimezone,
]);
date_default_timezone_set((string) $originalTimezone);
}
}
public function test_edit_redirect_keeps_current_filters_and_highlight(): void
{
$this->loginAs();
@ -1519,7 +1556,7 @@ class SystemizationTodosTest extends FeatureTestCase
}
}
public function test_reminder_remains_on_first_saved_completion_date_when_option_changes(): void
public function test_reminder_keeps_the_first_saved_completion_date(): void
{
Carbon::setTestNow('2026-10-26 12:00:00');
try {

View File

@ -621,6 +621,15 @@ class NavigationTest extends FeatureTestCase
['顾家过账', '索菲亚过账'],
array_column($navigation[$postingIndex]['pages'], 'title')
);
$this->assertTrue($navigation[$postingIndex]['pages'][0]['children_inherit_parent_access']);
$this->assertSame(
['kuka-basic-data'],
array_column($navigation[$postingIndex]['pages'][0]['children'], 'slug')
);
$this->assertSame(
['基础数据'],
array_column($navigation[$postingIndex]['pages'][0]['children'], 'title')
);
$this->assertSame(
['after-sales-expenses', 'promotion-expenses'],
array_column($orderData['pages'][0]['tabs'], 'slug')

View File

@ -159,7 +159,22 @@ class UserPermissionsTest extends FeatureTestCase
['顾家过账', '索菲亚过账'],
array_column($navigation[1]['pages'], 'title')
);
$this->assertSame(
['kuka-basic-data'],
array_column($navigation[1]['pages'][0]['children'], 'slug')
);
}
setting()->set('system.sidebar_permissions', [
'configured' => [$subject],
'subjects' => [$subject => ['posting-data/kuka-posting']],
]);
$navigation = SidebarPermissions::navigationFor($regular);
$this->assertSame(
['kuka-basic-data'],
array_column($navigation[0]['pages'][0]['children'], 'slug')
);
}
public function test_refund_export_requires_a_separate_operation_grant_when_page_access_is_limited(): void

View File

@ -36,4 +36,67 @@ XML);
@unlink($path);
}
public function test_it_can_select_a_named_worksheet(): void
{
$path = tempnam(sys_get_temp_dir(), 'xlsx-named-sheet') . '.xlsx';
$zip = new ZipArchive();
$zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFromString('xl/workbook.xml', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="汇总" sheetId="1" r:id="rId1"/>
<sheet name="发货明细表" sheetId="2" r:id="rId2"/>
</sheets>
</workbook>
XML);
$zip->addFromString('xl/_rels/workbook.xml.rels', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet2.xml"/>
</Relationships>
XML);
$zip->addFromString('xl/worksheets/sheet1.xml', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1"><c r="A1" t="inlineStr"><is><t>汇总</t></is></c></row>
<row r="2"><c r="A2" t="inlineStr"><is><t>不是明细</t></is></c></row>
</sheetData>
</worksheet>
XML);
$zip->addFromString('xl/worksheets/sheet2.xml', <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1" t="inlineStr"><is><t>店铺</t></is></c>
<c r="B1" t="inlineStr"><is><t>商品编码</t></is></c>
</row>
<row r="2">
<c r="A2" t="inlineStr"><is><t>天猫-HX旗舰店101</t></is></c>
<c r="B2" t="inlineStr"><is><t>SKU-NAMED</t></is></c>
</row>
</sheetData>
</worksheet>
XML);
$zip->close();
$rows = iterator_to_array((new XlsxSheetReader())->rows(
$path,
['店铺', '商品编码'],
[],
'发货明细表',
));
$this->assertSame(
[['店铺' => '天猫-HX旗舰店101', '商品编码' => 'SKU-NAMED']],
$rows,
);
@unlink($path);
}
}

View File

@ -5,6 +5,7 @@ namespace Tests\Unit\EcommerceFinance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Repositories\DouyinAuthoritativeBillRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Services\DouyinAuthoritativeBillImporter;
@ -298,6 +299,59 @@ class DouyinAuthoritativeBillTest extends TestCase
$this->assertSame(22870.22, $august['summary']['balance']);
}
public function test_lejian_uses_confirmed_zero_backoffice_opening_and_preserves_store_name(): void
{
$store = '抖音-亿家达乐简家具专卖店';
$septemberIncome = array_replace($this->row('2000000000000000501', '288.00'), [
'店铺' => $store,
'结算时间' => '2026-09-02 09:06:52',
]);
$septemberExpense = array_replace($this->row('2000000000000000502', '0.00', '288.00'), [
'店铺' => $store,
'账单项目' => '平台服务费',
'结算时间' => '2026-09-02 09:06:52',
]);
$this->import([$septemberIncome, $septemberExpense], 2, '288.00', '288.00', null, '2026-09');
$repo = app(StoreReceivingDouyinBillMirrorRepository::class);
$july = $repo->paginate([
'store_name' => $store,
'start' => '2026-07-01',
'end' => '2026-07-31',
], 'occurred_at', 'asc', 1, 10);
$september = $repo->paginate([
'store_name' => $store,
'start' => '2026-09-01',
'end' => '2026-09-30',
], 'occurred_at', 'asc', 1, 10);
$october = $repo->paginate([
'store_name' => $store,
'start' => '2026-10-01',
'end' => '2026-10-31',
], 'occurred_at', 'asc', 1, 10);
$storeBalances = app(DouyinAuthoritativeBillRepository::class)->storeBalances([
'start' => '2026-10-01',
'end' => '2026-10-31',
]);
$lejian = array_values(array_filter(
$storeBalances,
static fn (array $row): bool => $row['store_name'] === $store,
));
$this->assertSame(0.0, $july['summary']['opening_balance']);
$this->assertSame('2026-06-30', $july['summary']['opening_balance_date']);
$this->assertSame('merchant_backoffice_zero', $july['summary']['opening_balance_source']);
$this->assertSame(0.0, $september['summary']['opening_balance']);
$this->assertSame(288.0, $september['summary']['income']);
$this->assertSame(288.0, $september['summary']['expense']);
$this->assertSame(0.0, $september['summary']['balance']);
$this->assertSame(0.0, $october['summary']['opening_balance']);
$this->assertSame(0.0, $october['summary']['balance']);
$this->assertCount(1, $lejian);
$this->assertSame(0.0, $lejian[0]['opening_balance']);
$this->assertNotContains('未标注店铺', array_column($storeBalances, 'store_name'));
}
private function import(
array $rows,
int $count,

View File

@ -210,6 +210,116 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
$this->assertSame(8, $result['summary']['available_platform_count']);
}
public function test_balance_store_detail_calculates_each_store_closing_balance(): void
{
$service = new class extends StoreReceivingBalanceOverviewService {
public function __construct()
{
}
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
{
$index = array_search($platform, array_column(StoreReceivingBalanceOverviewService::PLATFORMS, 'slug'), true) + 1;
return [[
'store_name' => '店铺-' . $index,
'opening_balance' => 100.10 * $index,
'income' => 10.20 * $index,
'expense' => 1.25 * $index,
]];
}
};
$result = $service->balanceStoreDetail('2026-10');
$this->assertSame('2026-10', $result['month']);
$this->assertSame(['start' => '2026-10-01', 'end' => '2026-10-31'], $result['period']);
$this->assertCount(8, $result['details']);
$this->assertSame([
'platform_slug' => 'taobao-alipay',
'platform' => '淘系支付宝账户',
'store_name' => '店铺-1',
'bill_item' => '',
'opening_balance' => 100.10,
'income' => 10.20,
'expense' => 1.25,
'amount' => 109.05,
'available' => true,
], $result['details'][0]);
$this->assertSame(3925.80, $result['summary']['balance']);
$this->assertSame(8, $result['summary']['store_count']);
$this->assertSame(8, $result['summary']['ready_store_count']);
$this->assertTrue($result['summary']['complete']);
}
public function test_balance_store_detail_marks_missing_opening_instead_of_using_zero(): void
{
$service = new class extends StoreReceivingBalanceOverviewService {
public function __construct()
{
}
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
{
return [[
'store_name' => '待补期初店铺',
'opening_balance' => $platform === 'vipshop-jx' ? null : 25.0,
'income' => 5.0,
'expense' => 2.0,
]];
}
};
$result = $service->balanceStoreDetail('2026-10');
$this->assertFalse($result['summary']['complete']);
$this->assertNull($result['summary']['balance']);
$this->assertSame(7, $result['summary']['ready_store_count']);
$unavailable = array_values(array_filter(
$result['details'],
static fn (array $row): bool => $row['platform_slug'] === 'vipshop-jx',
))[0];
$this->assertNull($unavailable['opening_balance']);
$this->assertNull($unavailable['amount']);
$this->assertFalse($unavailable['available']);
}
public function test_balance_store_detail_merges_duplicate_store_rows_without_creating_zero_opening(): void
{
$service = new class extends StoreReceivingBalanceOverviewService {
public function __construct()
{
}
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
{
return [[
'store_name' => '重复店铺',
'opening_balance' => null,
'income' => 5.0,
'expense' => 0.0,
], [
'store_name' => '重复店铺',
'opening_balance' => null,
'income' => 0.0,
'expense' => 2.0,
]];
}
};
$result = $service->balanceStoreDetail('2026-10');
$rows = array_values(array_filter(
$result['details'],
static fn (array $row): bool => $row['store_name'] === '重复店铺',
));
$this->assertCount(1, $rows);
$this->assertNull($rows[0]['opening_balance']);
$this->assertSame(5.0, $rows[0]['income']);
$this->assertSame(2.0, $rows[0]['expense']);
$this->assertNull($rows[0]['amount']);
}
public function test_monthly_closing_returns_july_to_october_for_all_platforms(): void
{
$monthOrdinal = ['2026-07' => 1, '2026-08' => 2, '2026-09' => 3, '2026-10' => 4];
@ -256,6 +366,11 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
{
return ($this->summaryCallback)($platform, $start, $end);
}
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
{
return [];
}
};
}
}

View File

@ -65,6 +65,11 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase
'end' => '2026-10-31',
]),
);
$this->assertSame(
['天猫-A店' => 180.0, '淘宝-B店' => 50.0],
app(TaobaoAlipaySettlementBillRepository::class)
->storeOpeningBalances('2026-10-01'),
);
}
public function test_month_balance_respects_store_filter(): void
@ -116,6 +121,11 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase
$this->assertSame(35.0, $result['summary']['income']);
$this->assertSame(15.0, $result['summary']['expense']);
$this->assertSame(320.0, $result['summary']['balance']);
$this->assertSame(
['天猫-A店' => 200.0, '淘宝-B店' => 100.0],
app(TaobaoAlipaySettlementBillRepository::class)
->storeOpeningBalances('2026-07-01'),
);
}
private function createTables(): void

View File

@ -42,11 +42,16 @@ class StoreReceivingBalanceOverviewTest extends TestCase
$this->assertStringContainsString("{ key: 'platform', label: '平台' }", $source);
$this->assertStringContainsString("{ key: 'store', label: '店铺' }", $source);
$this->assertStringContainsString("{ key: 'bill_item', label: '账单项目' }", $source);
$this->assertStringContainsString("{ key: 'store', label: '店铺名称' }", $source);
$this->assertStringContainsString('income-detail', $source);
$this->assertStringContainsString('expense-detail', $source);
$this->assertStringContainsString('balance-detail', $source);
$this->assertStringContainsString('balance-store-detail', $source);
$this->assertStringContainsString("detailFlow === 'balance'", $source);
$this->assertStringContainsString('期末余额(万元)', $source);
$this->assertStringContainsString("detailFlow === 'balance' ? '店铺名称' : '店铺'", $source);
$this->assertStringContainsString('fetchStoreBalanceDetails', $source);
$this->assertStringContainsString('该店铺缺少期初余额', $source);
$this->assertStringContainsString('当前筛选合计(万元)', $source);
}
@ -69,7 +74,8 @@ class StoreReceivingBalanceOverviewTest extends TestCase
$this->assertStringContainsString('月度期末余额汇总', $source);
$this->assertStringContainsString('平台账户', $source);
$this->assertStringContainsString('monthly-closing-table', $source);
$this->assertStringContainsString('2026 年 7-10 月各平台期末余额', $source);
$this->assertStringContainsString('2026 年 7-10 月', $source);
$this->assertStringContainsString("'各平台'", $source);
$this->assertStringContainsString('金额单位:万元', $source);
$this->assertStringContainsString('monthlyBalanceWan', $source);
$this->assertStringContainsString('signedMoneyWan', $source);
@ -78,5 +84,14 @@ class StoreReceivingBalanceOverviewTest extends TestCase
$this->assertStringContainsString('环比口径:2026年10月期末余额 − 2026年9月期末余额', $source);
$this->assertStringContainsString('monthlyClosingRows', $source);
$this->assertStringContainsString('fetchMonthlyClosing', $source);
$this->assertStringContainsString('店铺汇总', $source);
$this->assertStringContainsString('monthly-closing-view-switch', $source);
$this->assertStringContainsString('selectMonthlyClosingView', $source);
$this->assertStringContainsString('fetchMonthlyClosingStores', $source);
$this->assertStringContainsString('monthlyStoreRows', $source);
$this->assertStringContainsString('monthly-closing-store-table', $source);
$this->assertStringContainsString('...(body.comparison || {})', $source);
$this->assertStringContainsString('店铺期末余额 = 期初余额 + 收入 - 支出', $source);
$this->assertStringContainsString('缺少期初时显示“—”', $source);
}
}