feat: add store closing balance detail #1041
@ -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
|
||||
{
|
||||
|
||||
@ -98,6 +98,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);
|
||||
|
||||
@ -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,38 @@ 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\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 +326,6 @@ class StoreReceivingBalanceOverviewService
|
||||
'amount' => round((float) $platform['balance'], 2),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'month' => $overview['month'],
|
||||
'period' => $overview['period'],
|
||||
@ -315,6 +339,111 @@ 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);
|
||||
}
|
||||
|
||||
$platformRows = [];
|
||||
foreach ($rows as $row) {
|
||||
$storeName = trim((string) ($row['store_name'] ?? ''));
|
||||
$storeName = $storeName !== '' ? $storeName : '未标注店铺';
|
||||
$opening = is_numeric($row['opening_balance'] ?? null)
|
||||
? round((float) $row['opening_balance'], 2)
|
||||
: null;
|
||||
$income = round((float) ($row['income'] ?? 0), 2);
|
||||
$expense = round((float) ($row['expense'] ?? 0), 2);
|
||||
$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 +594,585 @@ 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'),
|
||||
);
|
||||
$cutoff = $start . ' 00:00:00';
|
||||
$periodEnd = $this->dayAfter($end) . ' 00:00:00';
|
||||
$ranked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE)
|
||||
->where('occurred_at', '<', $cutoff)
|
||||
->whereNotNull('alipay_account')
|
||||
->where('alipay_account', '<>', '')
|
||||
->select([
|
||||
'store_name',
|
||||
'alipay_account',
|
||||
'occurred_at',
|
||||
'source_row_number',
|
||||
'income_amount',
|
||||
'expense_amount',
|
||||
'balance_amount',
|
||||
])
|
||||
->selectRaw(
|
||||
'ROW_NUMBER() OVER (' .
|
||||
'PARTITION BY alipay_account ' .
|
||||
'ORDER BY occurred_at DESC, source_row_number DESC' .
|
||||
') AS row_rank',
|
||||
);
|
||||
$latestRows = $connection->query()
|
||||
->fromSub($ranked, 'latest_store_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_amount,
|
||||
2,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$firstRanked = $connection->table(self::TAOBAO_ALIPAY_ROW_TABLE)
|
||||
->where('occurred_at', '>=', $cutoff)
|
||||
->where('occurred_at', '<', $periodEnd)
|
||||
->whereNotNull('alipay_account')
|
||||
->where('alipay_account', '<>', '')
|
||||
->select([
|
||||
'store_name',
|
||||
'alipay_account',
|
||||
'occurred_at',
|
||||
'source_row_number',
|
||||
'income_amount',
|
||||
'expense_amount',
|
||||
'balance_amount',
|
||||
])
|
||||
->selectRaw(
|
||||
'ROW_NUMBER() OVER (' .
|
||||
'PARTITION BY alipay_account ' .
|
||||
'ORDER BY occurred_at ASC, source_row_number ASC' .
|
||||
') AS row_rank',
|
||||
);
|
||||
$firstRows = $connection->query()
|
||||
->fromSub($firstRanked, 'first_store_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_amount
|
||||
- (float) $row->income_amount
|
||||
+ (float) $row->expense_amount,
|
||||
2,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@ -240,13 +240,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 +264,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>
|
||||
@ -360,6 +364,8 @@ export default {
|
||||
detailLoading: false,
|
||||
detailError: '',
|
||||
detailDetails: [],
|
||||
detailStoreDetails: [],
|
||||
detailStoreLoaded: false,
|
||||
detailRequestSerial: 0,
|
||||
detailTab: 'platform',
|
||||
detailPlatform: '',
|
||||
@ -460,12 +466,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 +510,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 +522,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 +563,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 +585,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')
|
||||
@ -671,6 +696,8 @@ export default {
|
||||
this.detailStore = '';
|
||||
this.detailBillItem = '';
|
||||
this.detailDetails = [];
|
||||
this.detailStoreDetails = [];
|
||||
this.detailStoreLoaded = false;
|
||||
this.detailError = '';
|
||||
this.lockDetailScroll();
|
||||
this.$nextTick(() => {
|
||||
@ -704,12 +731,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)) {
|
||||
|
||||
@ -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'])
|
||||
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -210,6 +210,80 @@ 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_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 +330,11 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
|
||||
{
|
||||
return ($this->summaryCallback)($platform, $start, $end);
|
||||
}
|
||||
|
||||
protected function fetchPlatformStoreBalances(string $platform, string $start, string $end): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user