feat: 店铺台账接入每日余额、预留标准与预警
完成店铺台账每日余额来源、日期筛选、预留标准和连续3天预警。 Co-authored-by: 92451 <924518135@qq.com> Co-committed-by: 92451 <924518135@qq.com>
This commit is contained in:
parent
c33bb7308e
commit
1cb04adc7b
@ -45,7 +45,7 @@ class WithdrawalBalanceAlertSynchronizer
|
||||
/**
|
||||
* @return array{balance_date:string,dates:list<string>,alerts:array<int,array<string,mixed>>,created:int,updated:int}
|
||||
*/
|
||||
public function syncForDate(int $companyId, string $balanceDate): array
|
||||
public function syncForDate(int $companyId, string $balanceDate, ?string $sourceScope = null): array
|
||||
{
|
||||
$dates = self::datesEndingAt($balanceDate);
|
||||
$stores = StoreReceivingAccount::withoutGlobalScopes()
|
||||
@ -64,7 +64,12 @@ class WithdrawalBalanceAlertSynchronizer
|
||||
];
|
||||
}
|
||||
|
||||
$balancesByDate = $this->shopBalances->matchesForStoresOnDates($stores, $dates);
|
||||
$balancesByDate = $this->shopBalances->matchesForStoresOnDates(
|
||||
$stores,
|
||||
$dates,
|
||||
null,
|
||||
$sourceScope,
|
||||
);
|
||||
$reserveStandards = $stores->mapWithKeys(
|
||||
static fn (StoreReceivingAccount $store): array => [
|
||||
(int) $store->id => WithdrawalReserveStandard::amountFor(
|
||||
|
||||
@ -13,9 +13,10 @@ class SyncFinanceLedgerShopData extends Command
|
||||
{--to= : 提现业务日期止,最晚只同步到前一晚}
|
||||
{--days= : 只同步最近 N 天}
|
||||
{--rebuild : 先用最新余额快照清空并重建店铺台账}
|
||||
{--balance-only : 只生成店铺余额快照并更新台账,不处理平台提现}
|
||||
{--no-recalculate : 只同步数据,不重算流水}';
|
||||
|
||||
protected $description = '同步上一晚店铺余额,并把平台账单中的提现对应到财务账户收入';
|
||||
protected $description = '生成上一晚店铺余额快照(店铺收款账户账单优先),并把平台提现对应到财务账户收入';
|
||||
|
||||
public function handle(FinanceLedgerShopDataSynchronizer $synchronizer): int
|
||||
{
|
||||
@ -26,12 +27,32 @@ class SyncFinanceLedgerShopData extends Command
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $synchronizer->sync(
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
! $this->option('no-recalculate'),
|
||||
(bool) $this->option('rebuild'),
|
||||
);
|
||||
if ($this->option('balance-only')) {
|
||||
$balance = $synchronizer->syncShopBalances(
|
||||
$this->option('to') ?: null,
|
||||
(bool) $this->option('rebuild'),
|
||||
);
|
||||
$result = [
|
||||
'balance' => $balance,
|
||||
'withdrawals' => [
|
||||
'processed' => 0,
|
||||
'written' => 0,
|
||||
'upstream_duplicates' => 0,
|
||||
'unmatched' => 0,
|
||||
'account_missing' => 0,
|
||||
'income' => 0.0,
|
||||
'expense' => 0.0,
|
||||
],
|
||||
'recalculated' => null,
|
||||
];
|
||||
} else {
|
||||
$result = $synchronizer->sync(
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
! $this->option('no-recalculate'),
|
||||
(bool) $this->option('rebuild'),
|
||||
);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
@ -41,6 +62,8 @@ class SyncFinanceLedgerShopData extends Command
|
||||
$this->table(['项目', '值'], [
|
||||
['店铺余额日期', $result['balance']['date'] ?: '-'],
|
||||
['余额源记录', $result['balance']['source']],
|
||||
['店铺账单余额来源', $result['balance']['receiving_bill']],
|
||||
['聚水潭补录来源', $result['balance']['jushuitan']],
|
||||
['补充确认店铺', $result['balance']['added']],
|
||||
['重建店铺台账', $result['balance']['rebuilt']],
|
||||
['已更新店铺余额', $result['balance']['matched']],
|
||||
@ -52,6 +75,8 @@ class SyncFinanceLedgerShopData extends Command
|
||||
['账户缺失', $result['withdrawals']['account_missing']],
|
||||
['提现收入合计', number_format((float) $result['withdrawals']['income'], 2)],
|
||||
['提现冲回支出', number_format((float) $result['withdrawals']['expense'], 2)],
|
||||
['余额预警待办新增', $result['balance']['alerts']['created']],
|
||||
['余额预警待办更新', $result['balance']['alerts']['updated']],
|
||||
['每日流水行数', $result['recalculated']['flows'] ?? '-'],
|
||||
['PHP 峰值内存', number_format(memory_get_peak_usage(true) / 1048576, 1) . ' MiB'],
|
||||
]);
|
||||
|
||||
@ -225,8 +225,9 @@ CRON_TZ=Asia/Shanghai
|
||||
# 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。
|
||||
15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 财务台账:每天 02:30 同步 AI 库动账并重算流水;店铺台账默认不自动回填。
|
||||
# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。
|
||||
30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1
|
||||
30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1
|
||||
# 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。
|
||||
20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
|
||||
@ -229,8 +229,9 @@ CRON_TZ=Asia/Shanghai
|
||||
# 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。
|
||||
15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1
|
||||
*/2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1
|
||||
# 财务台账:每天 02:30 同步 AI 库动账并重算流水;店铺台账默认不自动回填。
|
||||
# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。
|
||||
30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1
|
||||
30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1
|
||||
# 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。
|
||||
20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
|
||||
@ -24,11 +24,16 @@ class JushuitanShopBalanceRepository
|
||||
|
||||
/**
|
||||
* @param iterable<object> $stores
|
||||
* @return array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>
|
||||
* @return array<int,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string,source_file_name:?string}>
|
||||
*/
|
||||
public function matchesForStores(iterable $stores, string $balanceDate): array
|
||||
public function matchesForStores(
|
||||
iterable $stores,
|
||||
string $balanceDate,
|
||||
?string $dataSource = null,
|
||||
?string $sourceScope = null,
|
||||
): array
|
||||
{
|
||||
$matches = $this->matchesForStoresOnDates($stores, [$balanceDate]);
|
||||
$matches = $this->matchesForStoresOnDates($stores, [$balanceDate], $dataSource, $sourceScope);
|
||||
|
||||
return array_map(
|
||||
static fn (array $dates): array => $dates[$balanceDate],
|
||||
@ -39,12 +44,13 @@ class JushuitanShopBalanceRepository
|
||||
/**
|
||||
* @param iterable<object> $stores
|
||||
* @param list<string> $balanceDates
|
||||
* @return array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string}>>
|
||||
* @return array<int,array<string,array{status:string,balance:?float,source_store_name:?string,source_platform:?string,data_source:?string,source_file_name:?string}>>
|
||||
*/
|
||||
public function matchesForStoresOnDates(
|
||||
iterable $stores,
|
||||
array $balanceDates,
|
||||
?string $dataSource = null,
|
||||
?string $sourceScope = null,
|
||||
): array
|
||||
{
|
||||
$stores = is_array($stores) ? array_values($stores) : iterator_to_array($stores, false);
|
||||
@ -71,10 +77,14 @@ class JushuitanShopBalanceRepository
|
||||
$dataSource !== null,
|
||||
static fn ($query) => $query->where('data_source', $dataSource),
|
||||
)
|
||||
->when(
|
||||
$sourceScope !== null,
|
||||
static fn ($query) => $query->where('source_scope', $sourceScope),
|
||||
)
|
||||
->orderBy('id')
|
||||
->get([
|
||||
'id', 'balance_date', 'data_source', 'source_platform', 'store_name',
|
||||
'normalized_store_name', 'platform_account_id', 'balance',
|
||||
'normalized_store_name', 'platform_account_id', 'balance', 'source_file_name',
|
||||
])
|
||||
->groupBy(static fn (object $row): string => substr((string) $row->balance_date, 0, 10));
|
||||
|
||||
@ -134,6 +144,7 @@ class JushuitanShopBalanceRepository
|
||||
'source_store_name' => (string) $match->store_name,
|
||||
'source_platform' => $match->source_platform === null ? null : (string) $match->source_platform,
|
||||
'data_source' => (string) $match->data_source,
|
||||
'source_file_name' => $match->source_file_name === null ? null : (string) $match->source_file_name,
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -141,7 +152,7 @@ class JushuitanShopBalanceRepository
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function countForDate(string $balanceDate): int
|
||||
public function countForDate(string $balanceDate, ?string $sourceScope = null): int
|
||||
{
|
||||
if (! $this->hasTable()) {
|
||||
return 0;
|
||||
@ -149,13 +160,17 @@ class JushuitanShopBalanceRepository
|
||||
|
||||
return $this->connection->table(self::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->when(
|
||||
$sourceScope !== null,
|
||||
static fn ($query) => $query->where('source_scope', $sourceScope),
|
||||
)
|
||||
->count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 取不晚于今天的最新余额日期;没有任何快照时返回 null。
|
||||
*/
|
||||
public function latestBalanceDate(?CarbonInterface $today = null): ?string
|
||||
public function latestBalanceDate(?CarbonInterface $today = null, ?string $sourceScope = null): ?string
|
||||
{
|
||||
if (! $this->hasTable()) {
|
||||
return null;
|
||||
@ -164,6 +179,10 @@ class JushuitanShopBalanceRepository
|
||||
$today = ($today ?? now())->copy()->startOfDay();
|
||||
$latest = $this->connection->table(self::TABLE)
|
||||
->where('balance_date', '<=', $today->toDateString())
|
||||
->when(
|
||||
$sourceScope !== null,
|
||||
static fn ($query) => $query->where('source_scope', $sourceScope),
|
||||
)
|
||||
->max('balance_date');
|
||||
|
||||
return $latest === null ? null : substr((string) $latest, 0, 10);
|
||||
@ -188,7 +207,7 @@ class JushuitanShopBalanceRepository
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function availableDates(?CarbonInterface $today = null): array
|
||||
public function availableDates(?CarbonInterface $today = null, ?string $sourceScope = null): array
|
||||
{
|
||||
if (! $this->hasTable()) {
|
||||
return [];
|
||||
@ -198,6 +217,10 @@ class JushuitanShopBalanceRepository
|
||||
|
||||
return $this->connection->table(self::TABLE)
|
||||
->where('balance_date', '<=', $today->toDateString())
|
||||
->when(
|
||||
$sourceScope !== null,
|
||||
static fn ($query) => $query->where('source_scope', $sourceScope),
|
||||
)
|
||||
->distinct()
|
||||
->orderByDesc('balance_date')
|
||||
->pluck('balance_date')
|
||||
@ -259,7 +282,7 @@ class JushuitanShopBalanceRepository
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return array{status:string,balance:null,source_store_name:null,source_platform:null,data_source:null} */
|
||||
/** @return array{status:string,balance:null,source_store_name:null,source_platform:null,data_source:null,source_file_name:null} */
|
||||
private function emptyMatch(string $status): array
|
||||
{
|
||||
return [
|
||||
@ -268,6 +291,7 @@ class JushuitanShopBalanceRepository
|
||||
'source_store_name' => null,
|
||||
'source_platform' => null,
|
||||
'data_source' => null,
|
||||
'source_file_name' => null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use App\Business\WithdrawalBalanceAlertSynchronizer;
|
||||
use App\Models\Business\StoreReceivingAccount;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
@ -19,6 +20,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
DatabaseManager $databases,
|
||||
private readonly JushuitanShopBalanceRepository $shopBalances,
|
||||
private readonly BillingDetailsPageData $billingDetails,
|
||||
private readonly StoreReceivingBillBalanceSnapshotSynchronizer $balanceSnapshots,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
@ -27,7 +29,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* balance:array{date:?string,source:int,added:int,rebuilt:int,matched:int,amount:float},
|
||||
* balance:array{date:?string,source:int,receiving_bill:int,jushuitan:int,added:int,rebuilt:int,matched:int,amount:float,alerts:array{created:int,updated:int}},
|
||||
* withdrawals:array{from:string,to:string,processed:int,written:int,upstream_duplicates:int,unmatched:int,account_missing:int,income:float,expense:float},
|
||||
* recalculated:?array
|
||||
* }
|
||||
@ -64,9 +66,25 @@ class FinanceLedgerShopDataSynchronizer
|
||||
public function syncShopBalances(?string $through = null, bool $rebuild = false): array
|
||||
{
|
||||
$through = $this->validDate($through) ?? now()->startOfDay()->subDay()->toDateString();
|
||||
$balanceDate = $this->shopBalances->latestBalanceDate(CarbonImmutable::parse($through));
|
||||
$snapshot = $this->balanceSnapshots->sync($through);
|
||||
$balanceDate = $snapshot['total'] > 0
|
||||
? (string) $snapshot['date']
|
||||
: $this->shopBalances->latestBalanceDate(
|
||||
CarbonImmutable::parse($through),
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
);
|
||||
if ($balanceDate === null) {
|
||||
return ['date' => null, 'source' => 0, 'added' => 0, 'rebuilt' => 0, 'matched' => 0, 'amount' => 0.0];
|
||||
return [
|
||||
'date' => null,
|
||||
'source' => 0,
|
||||
'receiving_bill' => 0,
|
||||
'jushuitan' => 0,
|
||||
'added' => 0,
|
||||
'rebuilt' => 0,
|
||||
'matched' => 0,
|
||||
'amount' => 0.0,
|
||||
'alerts' => ['created' => 0, 'updated' => 0],
|
||||
];
|
||||
}
|
||||
|
||||
$rebuilt = $rebuild ? $this->rebuildShopLedger($balanceDate) : 0;
|
||||
@ -79,7 +97,12 @@ class FinanceLedgerShopDataSynchronizer
|
||||
->orderBy('id')
|
||||
->get(['id', 'shop_name', 'platform', 'account_short']);
|
||||
}
|
||||
$matches = $this->shopBalances->matchesForStores($shops, $balanceDate);
|
||||
$matches = $this->shopBalances->matchesForStores(
|
||||
$shops,
|
||||
$balanceDate,
|
||||
null,
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
);
|
||||
$updates = [];
|
||||
foreach ($matches as $id => $match) {
|
||||
if (($match['status'] ?? '') === 'matched' && $match['balance'] !== null) {
|
||||
@ -109,13 +132,41 @@ class FinanceLedgerShopDataSynchronizer
|
||||
}
|
||||
}
|
||||
|
||||
$alerts = ['created' => 0, 'updated' => 0];
|
||||
if ($updates !== []) {
|
||||
$companyIds = StoreReceivingAccount::withoutGlobalScopes()
|
||||
->whereNull('deleted_at')
|
||||
->distinct()
|
||||
->pluck('company_id')
|
||||
->filter()
|
||||
->map(static fn (mixed $id): int => (int) $id)
|
||||
->unique()
|
||||
->values();
|
||||
$alertSynchronizer = app(WithdrawalBalanceAlertSynchronizer::class);
|
||||
foreach ($companyIds as $companyId) {
|
||||
$result = $alertSynchronizer->syncForDate(
|
||||
$companyId,
|
||||
$balanceDate,
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
);
|
||||
$alerts['created'] += $result['created'];
|
||||
$alerts['updated'] += $result['updated'];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'date' => $balanceDate,
|
||||
'source' => $this->shopBalances->countForDate($balanceDate),
|
||||
'source' => $this->shopBalances->countForDate(
|
||||
$balanceDate,
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
),
|
||||
'receiving_bill' => $snapshot['receiving_bill'],
|
||||
'jushuitan' => $snapshot['jushuitan'],
|
||||
'added' => $added,
|
||||
'rebuilt' => $rebuilt,
|
||||
'matched' => count($updates),
|
||||
'amount' => round(array_sum($updates), 2),
|
||||
'alerts' => $alerts,
|
||||
];
|
||||
}
|
||||
|
||||
@ -123,6 +174,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
{
|
||||
$sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE)
|
||||
->orderByRaw("CASE WHEN data_source = 'jushuitan' THEN 0 ELSE 1 END")
|
||||
->orderBy('id')
|
||||
->get(['source_platform', 'store_name']);
|
||||
@ -200,6 +252,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
{
|
||||
$sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE)
|
||||
->get(['source_platform', 'store_name']);
|
||||
$existingExact = [];
|
||||
$existingNormalized = [];
|
||||
|
||||
@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use InvalidArgumentException;
|
||||
use Modules\EcommerceFinance\Repositories\FinanceBillBalanceRepository;
|
||||
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 生成店铺台账专用日余额快照。
|
||||
*
|
||||
* 店铺收款账户账单中具备真实累计余额的来源优先(淘系支付宝、京东钱包);
|
||||
* 其他平台暂时沿用聚水潭店铺余额。结果单独写入 store-ledger 来源范围,
|
||||
* 不改变提现管理现有余额口径。
|
||||
*/
|
||||
class StoreReceivingBillBalanceSnapshotSynchronizer
|
||||
{
|
||||
public const SOURCE_SCOPE = 'store-ledger';
|
||||
|
||||
public const DATA_SOURCE_RECEIVING_BILL = 'store_receiving_bill';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(
|
||||
DatabaseManager $databases,
|
||||
private readonly FinanceBillBalanceRepository $billBalances,
|
||||
) {
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* date:string,total:int,receiving_bill:int,jushuitan:int,
|
||||
* replaced:int,source_errors:list<string>
|
||||
* }
|
||||
*/
|
||||
public function sync(string $balanceDate): array
|
||||
{
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $balanceDate);
|
||||
if (! $date instanceof CarbonImmutable || $date->format('Y-m-d') !== $balanceDate) {
|
||||
throw new InvalidArgumentException('店铺余额日期必须使用 YYYY-MM-DD 格式。');
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
$sourceErrors = [];
|
||||
$receivingBillCount = 0;
|
||||
|
||||
foreach ([FinanceBillBalanceRepository::SCOPE_TAOBAO, FinanceBillBalanceRepository::SCOPE_JD_WALLET] as $scope) {
|
||||
try {
|
||||
foreach ($this->billBalances->latestBalances($scope, $balanceDate) as $source) {
|
||||
$key = $this->key(
|
||||
(string) ($source['source_platform'] ?? ''),
|
||||
(string) ($source['store_name'] ?? ''),
|
||||
);
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[$key] = $this->snapshotRow(
|
||||
$balanceDate,
|
||||
self::DATA_SOURCE_RECEIVING_BILL,
|
||||
$key,
|
||||
$source,
|
||||
);
|
||||
$receivingBillCount++;
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$sourceErrors[] = $scope . ':' . $exception->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
$legacy = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->where('source_scope', '<>', self::SOURCE_SCOPE)
|
||||
->orderByRaw("CASE WHEN data_source = 'jushuitan' THEN 0 ELSE 1 END")
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
$jushuitanCount = 0;
|
||||
foreach ($legacy as $source) {
|
||||
$key = $this->key(
|
||||
(string) ($source->source_platform ?? ''),
|
||||
(string) ($source->store_name ?? ''),
|
||||
);
|
||||
if ($key === '' || isset($rows[$key])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$dataSource = (string) ($source->data_source ?? JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN);
|
||||
$rows[$key] = $this->snapshotRow($balanceDate, $dataSource, $key, (array) $source);
|
||||
if ($dataSource === JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN) {
|
||||
$jushuitanCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$rows = array_values($rows);
|
||||
$existing = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->where('source_scope', self::SOURCE_SCOPE)
|
||||
->count();
|
||||
|
||||
if ($rows === []) {
|
||||
return [
|
||||
'date' => $balanceDate,
|
||||
'total' => 0,
|
||||
'receiving_bill' => 0,
|
||||
'jushuitan' => 0,
|
||||
'replaced' => $existing,
|
||||
'source_errors' => $sourceErrors,
|
||||
];
|
||||
}
|
||||
|
||||
$this->connection->transaction(function () use ($balanceDate, $rows): void {
|
||||
$this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->where('source_scope', self::SOURCE_SCOPE)
|
||||
->delete();
|
||||
|
||||
foreach (array_chunk($rows, 500) as $chunk) {
|
||||
$this->connection->table(JushuitanShopBalanceRepository::TABLE)->insert($chunk);
|
||||
}
|
||||
});
|
||||
|
||||
return [
|
||||
'date' => $balanceDate,
|
||||
'total' => count($rows),
|
||||
'receiving_bill' => $receivingBillCount,
|
||||
'jushuitan' => $jushuitanCount,
|
||||
'replaced' => $existing,
|
||||
'source_errors' => $sourceErrors,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $source
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function snapshotRow(string $balanceDate, string $dataSource, string $key, array $source): array
|
||||
{
|
||||
$now = now();
|
||||
$storeName = trim((string) ($source['store_name'] ?? ''));
|
||||
$normalized = trim((string) ($source['normalized_store_name'] ?? ''));
|
||||
if ($normalized === '') {
|
||||
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName);
|
||||
}
|
||||
|
||||
$sourceFileName = trim((string) ($source['source_file_name'] ?? ''));
|
||||
if ($sourceFileName === '') {
|
||||
$sourceFileName = match ($dataSource) {
|
||||
self::DATA_SOURCE_RECEIVING_BILL => '财务系统/店铺收款账户账单',
|
||||
JushuitanShopBalanceRepository::DATA_SOURCE_FINANCE => '财务系统账单补录',
|
||||
default => '聚水潭店铺余额',
|
||||
};
|
||||
}
|
||||
|
||||
return [
|
||||
'balance_date' => $balanceDate,
|
||||
'source_scope' => self::SOURCE_SCOPE,
|
||||
'data_source' => $dataSource,
|
||||
'source_platform' => trim((string) ($source['source_platform'] ?? '')) ?: null,
|
||||
'store_name' => $storeName,
|
||||
'normalized_store_name' => $normalized,
|
||||
'platform_account_id' => trim((string) ($source['platform_account_id'] ?? '')) ?: null,
|
||||
'balance' => round((float) ($source['balance'] ?? 0), 6),
|
||||
'source_row_key' => hash('sha256', implode("\0", [
|
||||
self::SOURCE_SCOPE,
|
||||
$dataSource,
|
||||
$key,
|
||||
])),
|
||||
'source_file_name' => mb_substr($sourceFileName, 0, 255),
|
||||
'source_sha256' => hash('sha256', implode("\0", [
|
||||
$balanceDate,
|
||||
$dataSource,
|
||||
$key,
|
||||
(string) ($source['occurred_at'] ?? ''),
|
||||
number_format((float) ($source['balance'] ?? 0), 6, '.', ''),
|
||||
])),
|
||||
'imported_at' => $now,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
}
|
||||
|
||||
private function key(string $sourcePlatform, string $storeName): string
|
||||
{
|
||||
$storeName = trim($storeName);
|
||||
if ($storeName === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$platform = JushuitanShopBalanceRepository::platformKey($sourcePlatform)
|
||||
?? mb_strtolower(trim($sourcePlatform));
|
||||
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName);
|
||||
|
||||
return $normalized === '' ? '' : $platform . "\0" . $normalized;
|
||||
}
|
||||
|
||||
public static function sourceLabel(?string $dataSource, ?string $sourceFileName = null): string
|
||||
{
|
||||
return match ($dataSource) {
|
||||
self::DATA_SOURCE_RECEIVING_BILL => str_replace(
|
||||
'财务系统/店铺收款账户账单/',
|
||||
'店铺收款账户账单 · ',
|
||||
trim((string) $sourceFileName) ?: '财务系统/店铺收款账户账单',
|
||||
),
|
||||
JushuitanShopBalanceRepository::DATA_SOURCE_FINANCE => '财务系统账单补录',
|
||||
JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN => '聚水潭店铺余额',
|
||||
default => trim((string) $sourceFileName) ?: '未标明来源',
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
namespace Modules\EcommerceFinance\View;
|
||||
|
||||
use App\Business\WithdrawalBalanceAlertSynchronizer;
|
||||
use App\Business\WithdrawalReserveStandard;
|
||||
use App\Utilities\FinanceLedgerAccountStatus;
|
||||
use App\Utilities\FinanceLedgerAccountShouldKeep;
|
||||
use App\Utilities\FinanceLedgerAccountType;
|
||||
@ -12,6 +14,7 @@ use Illuminate\Pagination\Paginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\FinanceLedgerShopDirectory;
|
||||
use Modules\EcommerceFinance\Services\StoreReceivingBillBalanceSnapshotSynchronizer;
|
||||
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
|
||||
|
||||
/**
|
||||
@ -35,6 +38,7 @@ class FinanceLedgerPageData
|
||||
|
||||
public function __construct(
|
||||
private readonly FinanceLedgerShopDirectory $shopDirectory,
|
||||
private readonly JushuitanShopBalanceRepository $shopBalances,
|
||||
) {
|
||||
}
|
||||
|
||||
@ -59,7 +63,8 @@ class FinanceLedgerPageData
|
||||
'ledgerAccountSummary' => $accounts['summary'],
|
||||
'ledgerShops' => $shops['rows'],
|
||||
'ledgerShopSummary' => $shops['summary'],
|
||||
'ledgerShopBalanceDate' => $this->latestShopBalanceDate(),
|
||||
'ledgerShopBalanceDate' => $shops['balance_date'] ?? null,
|
||||
'ledgerShopBalanceDates' => $shops['balance_dates'] ?? [],
|
||||
'ledgerAvailableBreakdown' => $availableBreakdown,
|
||||
'ledgerFlows' => $flows['rows'],
|
||||
'ledgerFlowSummary' => $flows['summary'],
|
||||
@ -226,16 +231,125 @@ class FinanceLedgerPageData
|
||||
{
|
||||
$directoryRows = $this->shopDirectory->rows();
|
||||
|
||||
return $directoryRows === null
|
||||
? $this->shopsFromLedgerTable()
|
||||
: $this->shopsFromStoreReport($directoryRows);
|
||||
if ($directoryRows === null) {
|
||||
return $this->shopsFromLedgerTable();
|
||||
}
|
||||
|
||||
$context = $this->storeLedgerBalanceContext($directoryRows);
|
||||
|
||||
return $this->shopsFromStoreReport($context['rows'], $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺余额按日期读取专用快照。店铺收款账户账单有真实余额的平台
|
||||
* 优先使用账单来源,其余平台由同步任务以聚水潭余额补足并明确标注。
|
||||
*
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return array{
|
||||
* rows:list<array<string,mixed>>,balance_date:?string,
|
||||
* balance_dates:list<string>,alert_count:int
|
||||
* }
|
||||
*/
|
||||
private function storeLedgerBalanceContext(array $rows): array
|
||||
{
|
||||
$latestAllowed = now()->startOfDay()->subDay();
|
||||
$balanceDates = $this->shopBalances->availableDates(
|
||||
$latestAllowed,
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
);
|
||||
$requestedDate = trim((string) request('shops_balance_date', ''));
|
||||
$balanceDate = in_array($requestedDate, $balanceDates, true)
|
||||
? $requestedDate
|
||||
: ($balanceDates[0] ?? null);
|
||||
|
||||
$reserveStandards = [];
|
||||
foreach ($rows as $index => $row) {
|
||||
$reserveStandards[(int) ($row['id'] ?? $index)] = WithdrawalReserveStandard::amountFor(
|
||||
(string) ($row['platform'] ?? ''),
|
||||
(string) ($row['shop_name'] ?? ''),
|
||||
);
|
||||
$rows[$index]['shop_balance_source'] = ($row['shop_balance_date'] ?? null)
|
||||
? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel(
|
||||
JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN,
|
||||
)
|
||||
: '未同步';
|
||||
$rows[$index]['shop_balance_status'] = ($row['shop_balance_date'] ?? null) ? 'matched' : 'not_ready';
|
||||
$rows[$index]['reserve_standard'] = $reserveStandards[(int) ($row['id'] ?? $index)];
|
||||
$rows[$index]['balance_alert'] = '否';
|
||||
$rows[$index]['balance_alert_message'] = null;
|
||||
}
|
||||
|
||||
if ($balanceDate === null) {
|
||||
return [
|
||||
'rows' => $rows,
|
||||
'balance_date' => null,
|
||||
'balance_dates' => [],
|
||||
'alert_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
$stores = array_map(
|
||||
static fn (array $row): object => (object) $row,
|
||||
$rows,
|
||||
);
|
||||
$historyDates = WithdrawalBalanceAlertSynchronizer::datesEndingAt($balanceDate);
|
||||
$matches = $this->shopBalances->matchesForStoresOnDates(
|
||||
$stores,
|
||||
$historyDates,
|
||||
null,
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
);
|
||||
$alerts = WithdrawalBalanceAlertSynchronizer::detect(
|
||||
$stores,
|
||||
$matches,
|
||||
array_map(
|
||||
static fn (?int $amount): ?int => $amount === null ? null : (int) $amount,
|
||||
$reserveStandards,
|
||||
),
|
||||
$historyDates,
|
||||
);
|
||||
|
||||
foreach ($rows as $index => $row) {
|
||||
$id = (int) ($row['id'] ?? $index);
|
||||
$match = $matches[$id][$balanceDate] ?? [
|
||||
'status' => 'not_ready',
|
||||
'balance' => null,
|
||||
'data_source' => null,
|
||||
'source_file_name' => null,
|
||||
];
|
||||
$matched = ($match['status'] ?? '') === 'matched' && ($match['balance'] ?? null) !== null;
|
||||
$rows[$index]['shop_balance'] = $matched ? round((float) $match['balance'], 2) : null;
|
||||
$rows[$index]['shop_balance_date'] = $matched ? $balanceDate : null;
|
||||
$rows[$index]['shop_balance_status'] = (string) ($match['status'] ?? 'not_ready');
|
||||
$rows[$index]['shop_balance_source'] = $matched
|
||||
? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel(
|
||||
$match['data_source'] ?? null,
|
||||
$match['source_file_name'] ?? null,
|
||||
)
|
||||
: '未同步';
|
||||
$alert = $alerts[$id] ?? null;
|
||||
$rows[$index]['balance_alert'] = $alert === null ? '否' : '是';
|
||||
$rows[$index]['balance_alert_message'] = $alert['message'] ?? null;
|
||||
}
|
||||
|
||||
return [
|
||||
'rows' => $rows,
|
||||
'balance_date' => $balanceDate,
|
||||
'balance_dates' => $balanceDates,
|
||||
'alert_count' => count($alerts),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string,mixed>> $rows
|
||||
* @return array{rows:LengthAwarePaginator,summary:array{count:int,balance:float},overall_summary:array{count:int,balance:float}}
|
||||
* @param array{balance_date:?string,balance_dates:list<string>,alert_count:int}|array{} $context
|
||||
* @return array{
|
||||
* rows:LengthAwarePaginator,summary:array{count:int,balance:float,alert_count:int},
|
||||
* overall_summary:array{count:int,balance:float},balance_date:?string,
|
||||
* balance_dates:list<string>,alert_count:int
|
||||
* }
|
||||
*/
|
||||
private function shopsFromStoreReport(array $rows): array
|
||||
private function shopsFromStoreReport(array $rows, array $context = []): array
|
||||
{
|
||||
$overallSummary = [
|
||||
'count' => count($rows),
|
||||
@ -289,6 +403,10 @@ class FinanceLedgerPageData
|
||||
static fn (array $row): float => (float) ($row['shop_balance'] ?? 0),
|
||||
$rows,
|
||||
)), 2),
|
||||
'alert_count' => count(array_filter(
|
||||
$rows,
|
||||
static fn (array $row): bool => ($row['balance_alert'] ?? '') === '是',
|
||||
)),
|
||||
];
|
||||
$perPage = 100;
|
||||
$currentPage = Paginator::resolveCurrentPage('shops_page');
|
||||
@ -311,6 +429,9 @@ class FinanceLedgerPageData
|
||||
))->withQueryString(),
|
||||
'summary' => $summary,
|
||||
'overall_summary' => $overallSummary,
|
||||
'balance_date' => $context['balance_date'] ?? null,
|
||||
'balance_dates' => $context['balance_dates'] ?? [],
|
||||
'alert_count' => $summary['alert_count'],
|
||||
];
|
||||
}
|
||||
|
||||
@ -340,6 +461,7 @@ class FinanceLedgerPageData
|
||||
$summary = [
|
||||
'count' => (clone $query)->count(),
|
||||
'balance' => round((float) (clone $query)->sum('shop_balance'), 2),
|
||||
'alert_count' => 0,
|
||||
];
|
||||
|
||||
$sorted = $this->applyLedgerHeaderSort($query, 'shops', $headerColumns);
|
||||
@ -347,11 +469,35 @@ class FinanceLedgerPageData
|
||||
$query->orderBy('company_name')->orderBy('shop_name');
|
||||
}
|
||||
|
||||
$rows = $query
|
||||
->paginate(100, ['*'], 'shops_page')->withQueryString();
|
||||
$rows->getCollection()->transform(static function ($row) {
|
||||
$row->shop_balance_source = ($row->shop_balance_date ?? null)
|
||||
? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel(
|
||||
JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN,
|
||||
)
|
||||
: '未同步';
|
||||
$row->shop_balance_status = ($row->shop_balance_date ?? null) ? 'matched' : 'not_ready';
|
||||
$row->reserve_standard = WithdrawalReserveStandard::amountFor(
|
||||
(string) ($row->platform ?? ''),
|
||||
(string) ($row->shop_name ?? ''),
|
||||
);
|
||||
$row->balance_alert = '否';
|
||||
$row->balance_alert_message = null;
|
||||
|
||||
return $row;
|
||||
});
|
||||
|
||||
return [
|
||||
'rows' => $query
|
||||
->paginate(100, ['*'], 'shops_page')->withQueryString(),
|
||||
'rows' => $rows,
|
||||
'summary' => $summary,
|
||||
'overall_summary' => $overallSummary,
|
||||
'balance_date' => $this->latestShopBalanceDate(),
|
||||
'balance_dates' => $this->shopBalances->availableDates(
|
||||
now()->startOfDay()->subDay(),
|
||||
StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
),
|
||||
'alert_count' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
@ -369,7 +515,7 @@ class FinanceLedgerPageData
|
||||
'bank_available' => $bankAvailable,
|
||||
'shop_available' => $shopAvailable,
|
||||
'total' => round($bankAvailable + $shopAvailable, 2),
|
||||
'shop_balance_date' => $this->latestShopBalanceDate(),
|
||||
'shop_balance_date' => $shops['balance_date'] ?? $this->latestShopBalanceDate(),
|
||||
];
|
||||
}
|
||||
|
||||
@ -617,6 +763,7 @@ class FinanceLedgerPageData
|
||||
}
|
||||
|
||||
$latest = $this->db()->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE)
|
||||
->where('balance_date', '<=', now()->startOfDay()->subDay()->toDateString())
|
||||
->max('balance_date');
|
||||
|
||||
@ -851,7 +998,10 @@ class FinanceLedgerPageData
|
||||
'store_manager' => ['sort' => 'shop_name', 'type' => 'text'],
|
||||
'department_manager' => ['sort' => 'shop_name', 'type' => 'text'],
|
||||
'payout_account' => ['sort' => 'payout_account', 'type' => 'text'],
|
||||
'shop_balance_source' => ['sort' => 'shop_balance_source', 'type' => 'text'],
|
||||
'shop_balance' => ['sort' => 'shop_balance', 'type' => 'number'],
|
||||
'reserve_standard' => ['sort' => 'reserve_standard', 'type' => 'number'],
|
||||
'balance_alert' => ['sort' => 'balance_alert', 'type' => 'enum'],
|
||||
'remark' => ['sort' => 'remark', 'type' => 'text'],
|
||||
];
|
||||
}
|
||||
|
||||
@ -63,6 +63,7 @@
|
||||
$tabUrl = static fn (string $tab): string => $ledgerPageUrl . '?' . http_build_query(['tab' => $tab]);
|
||||
$sourceLabels = ['dingtalk' => '钉钉审批', 'shop' => '店铺提现', 'shop_bill' => '店铺账单提现', 'payable' => '供应商应付', 'store' => '店铺开店', 'workorder' => '聚工单', 'manual' => '手工录入'];
|
||||
$shopBalanceDate = $ledgerShopBalanceDate ?? null;
|
||||
$shopBalanceDates = $ledgerShopBalanceDates ?? [];
|
||||
$manualTransactionAccountOptions = $ledgerManualTransactionAccountOptions ?? [];
|
||||
$transactionAccountHeaderOptions = $ledgerTransactionAccountHeaderOptions ?? [];
|
||||
$transactionDateHeaderOptions = $ledgerTransactionDateHeaderOptions ?? [];
|
||||
@ -118,7 +119,10 @@
|
||||
['store_manager', '店铺负责人', 'text'],
|
||||
['department_manager', '部门负责人', 'text'],
|
||||
['payout_account', '回款账户', 'text'],
|
||||
['shop_balance_source', '余额来源', 'text'],
|
||||
['shop_balance', '店铺余额', 'number', ['headerClass' => 'num', 'align' => 'end']],
|
||||
['reserve_standard', '预留标准', 'number', ['headerClass' => 'num', 'align' => 'end']],
|
||||
['balance_alert', '余额预警', 'enum', ['options' => ['是' => '是', '否' => '否']]],
|
||||
['remark', '备注', 'text'],
|
||||
],
|
||||
'flows' => [
|
||||
@ -445,6 +449,9 @@
|
||||
.ledger-toast.is-visible { display:block; }
|
||||
.ledger-toast.is-error { border-color:var(--vip-danger, #B80000); color:var(--vip-danger, #B80000); }
|
||||
.ledger-source-tag { display:inline-flex; align-items:center; padding:.1rem .4rem; border-radius:.25rem; background:#f4f1eb; color:var(--vip-content-muted, #595959); font-size:.68rem; }
|
||||
.ledger-source-tag--receiving { background:var(--vip-content-accent-soft, #F7F0DE); color:var(--vip-content-accent-dark, #856632); }
|
||||
.ledger-balance-alert { display:inline-flex; align-items:center; gap:.2rem; color:var(--vip-warning, #935F07); font-size:.72rem; font-weight:600; white-space:nowrap; }
|
||||
.ledger-balance-alert .material-icons-outlined { font-size:.95rem; }
|
||||
.ledger-mono { font-variant-numeric:tabular-nums; }
|
||||
@media (max-width: 900px) { .ledger-hero { align-items:flex-start; flex-direction:column; } .ledger-field { min-width:calc(50% - .5rem); } }
|
||||
@media (max-width: 760px) { .ledger-company-form__body { grid-template-columns:repeat(2, minmax(0, 1fr)); } .ledger-company-field--wide { grid-column:span 2; } }
|
||||
@ -789,6 +796,7 @@
|
||||
<div class="ledger-field"><label for="shops-q">店铺/平台/公司</label><input id="shops-q" name="shops_q" value="{{ request('shops_q') }}" placeholder="关键词"></div>
|
||||
<div class="ledger-field"><label for="shops-platform">平台</label><input id="shops-platform" name="shops_platform" value="{{ request('shops_platform') }}" placeholder="如 天猫"></div>
|
||||
<div class="ledger-field"><label for="shops-company">所属公司</label><input id="shops-company" name="shops_company" value="{{ request('shops_company') }}" placeholder="公司名称"></div>
|
||||
<div class="ledger-field"><label for="shops-balance-date">余额日期</label><select id="shops-balance-date" name="shops_balance_date"><option value="">最新可用日期</option>@foreach ($shopBalanceDates as $availableBalanceDate)<option value="{{ $availableBalanceDate }}" @selected($shopBalanceDate === $availableBalanceDate)>{{ $availableBalanceDate }}</option>@endforeach</select></div>
|
||||
<div class="ledger-actions"><button class="ledger-btn primary" type="submit"><span class="material-icons-outlined">search</span>查询</button><a class="ledger-btn" href="{{ $tabUrl('shops') }}"><span class="material-icons-outlined">refresh</span>重置</a></div>
|
||||
</form>
|
||||
@if ($canEditAccountStatus)
|
||||
@ -798,12 +806,12 @@
|
||||
<span class="material-icons-outlined" aria-hidden="true">sync</span>
|
||||
同步上一晚余额与提现
|
||||
</button>
|
||||
<span>{{ $shopBalanceDate ? '店铺余额日期:' . $shopBalanceDate : '尚未同步店铺余额' }}</span>
|
||||
<span>{{ $shopBalanceDate ? '店铺余额日期:' . $shopBalanceDate . ';店铺收款账户账单优先,其他平台标记为聚水潭补录。' : '尚未同步店铺余额' }}</span>
|
||||
</form>
|
||||
@endif
|
||||
<div class="ledger-summary"><div class="ledger-summary__item"><span>店铺数</span><b>{{ number_format((int) ($ledgerShopSummary['count'] ?? 0)) }}</b></div><div class="ledger-summary__item"><span>店铺余额合计</span><b>{{ $money($ledgerShopSummary['balance'] ?? 0) }}</b></div><div class="ledger-summary__item"><span>余额口径</span><b>{{ $shopBalanceDate ? '上一晚店铺余额(' . $shopBalanceDate . ')' : '尚未同步' }}</b></div></div>
|
||||
<div class="ledger-summary"><div class="ledger-summary__item"><span>店铺数</span><b>{{ number_format((int) ($ledgerShopSummary['count'] ?? 0)) }}</b></div><div class="ledger-summary__item"><span>店铺余额合计</span><b>{{ $money($ledgerShopSummary['balance'] ?? 0) }}</b></div><div class="ledger-summary__item"><span>余额日期</span><b>{{ $shopBalanceDate ?: '尚未同步' }}</b></div><div class="ledger-summary__item"><span>连续3天预警</span><b>{{ number_format((int) ($ledgerShopSummary['alert_count'] ?? 0)) }}</b></div></div>
|
||||
<div class="ledger-table-wrap">
|
||||
<table class="ledger-table" style="min-width:66rem"><thead><tr>
|
||||
<table class="ledger-table" style="min-width:82rem"><thead><tr>
|
||||
@foreach ($ledgerTableHeaders['shops'] as $header)
|
||||
@include('business.pages.financial-ledger.partials.table-header', [
|
||||
'column' => $header[0],
|
||||
@ -817,7 +825,7 @@
|
||||
])
|
||||
@endforeach
|
||||
</tr></thead>
|
||||
<tbody>@forelse ($ledgerShops as $row)<tr><td>{{ $row->platform }}</td><td>{{ $row->shop_name }}</td><td>{{ $row->company_name }}</td><td>{{ $row->account_short }}</td><td><span class="{{ $row->status === '在营' ? 'success' : 'muted' }}">{{ $row->status }}</span></td><td>{{ $row->store_manager ?? '' }}</td><td>{{ $row->department_manager ?? '' }}</td><td>{{ $row->payout_account }}</td><td class="num" @if ($row->shop_balance_date ?? null) title="余额日期:{{ $row->shop_balance_date }}" @endif>{{ $money($row->shop_balance) }}</td><td>{{ $row->remark }}</td></tr>@empty<tr><td colspan="{{ count($ledgerTableHeaders['shops']) }}"><div class="ledger-empty">没有匹配的店铺数据。</div></td></tr>@endforelse</tbody>
|
||||
<tbody>@forelse ($ledgerShops as $row)<tr><td>{{ $row->platform }}</td><td>{{ $row->shop_name }}</td><td>{{ $row->company_name }}</td><td>{{ $row->account_short }}</td><td><span class="{{ $row->status === '在营' ? 'success' : 'muted' }}">{{ $row->status }}</span></td><td>{{ $row->store_manager ?? '' }}</td><td>{{ $row->department_manager ?? '' }}</td><td>{{ $row->payout_account }}</td><td><span class="ledger-source-tag {{ ($row->shop_balance_source ?? '') !== '聚水潭店铺余额' && ($row->shop_balance_source ?? '') !== '未同步' ? 'ledger-source-tag--receiving' : '' }}" title="{{ $row->shop_balance_source ?? '未同步' }}">{{ $row->shop_balance_source ?? '未同步' }}</span></td><td class="num" @if ($row->shop_balance_date ?? null) title="余额日期:{{ $row->shop_balance_date }}" @endif>{{ ($row->shop_balance ?? null) === null ? '—' : $money($row->shop_balance) }}</td><td class="num">{{ ($row->reserve_standard ?? null) === null ? '—' : $money($row->reserve_standard) }}</td><td>@if (($row->balance_alert ?? '否') === '是')<span class="ledger-balance-alert" title="{{ $row->balance_alert_message ?? '余额连续3天高于预留标准' }}"><span class="material-icons-outlined" aria-hidden="true">warning</span>预警</span>@else<span class="muted">否</span>@endif</td><td>{{ $row->remark }}</td></tr>@empty<tr><td colspan="{{ count($ledgerTableHeaders['shops']) }}"><div class="ledger-empty">没有匹配的店铺数据。</div></td></tr>@endforelse</tbody>
|
||||
</table>
|
||||
@include('business.pages.financial-ledger.partials.pagination', [
|
||||
'rows' => $ledgerShops,
|
||||
|
||||
@ -130,8 +130,8 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase
|
||||
$response = $this->loginAs()->get($this->pageUrl());
|
||||
$html = $response->assertOk()->getContent();
|
||||
|
||||
$this->assertSame(65, preg_match_all('/<details\b[^>]*data-ledger-header-details/', $html));
|
||||
$this->assertSame(65, preg_match_all('/<span\b[^>]*data-ledger-header-label/', $html));
|
||||
$this->assertSame(68, preg_match_all('/<details\b[^>]*data-ledger-header-details/', $html));
|
||||
$this->assertSame(68, preg_match_all('/<span\b[^>]*data-ledger-header-label/', $html));
|
||||
$this->assertSame(2, preg_match_all('/<select name="transactions_filter_value"/', $html));
|
||||
$this->assertSame(1, preg_match_all('/<input\b[^>]*name="transactions_filter_value"[^>]*list="ledger-header-options-transactions-effective_account_short"/', $html));
|
||||
$this->assertStringContainsString(
|
||||
@ -170,6 +170,9 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase
|
||||
$this->assertStringContainsString('data-ledger-header-label>店铺主体</span>', $headerHtml);
|
||||
$this->assertStringContainsString('data-ledger-header-label>店铺负责人</span>', $headerHtml);
|
||||
$this->assertStringContainsString('data-ledger-header-label>部门负责人</span>', $headerHtml);
|
||||
$this->assertStringContainsString('data-ledger-header-label>余额来源</span>', $headerHtml);
|
||||
$this->assertStringContainsString('data-ledger-header-label>预留标准</span>', $headerHtml);
|
||||
$this->assertStringContainsString('data-ledger-header-label>余额预警</span>', $headerHtml);
|
||||
$this->assertStringNotContainsString('data-ledger-header-label>店铺名称</span>', $headerHtml);
|
||||
$this->assertStringNotContainsString('data-ledger-header-label>所属公司</span>', $headerHtml);
|
||||
}
|
||||
|
||||
@ -5,8 +5,10 @@ namespace Tests\Feature\Business;
|
||||
use App\Models\Auth\Permission;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreAccountMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\StoreReportPeriodBuilder;
|
||||
use Modules\EcommerceFinance\Services\StoreReceivingBillBalanceSnapshotSynchronizer;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class FinanceLedgerShopDirectoryTest extends FeatureTestCase
|
||||
@ -222,6 +224,59 @@ class FinanceLedgerShopDirectoryTest extends FeatureTestCase
|
||||
$this->assertStringNotContainsString('网商银行账户', $shopHtml);
|
||||
}
|
||||
|
||||
public function test_shop_ledger_filters_daily_balance_and_shows_source_reserve_and_alert(): void
|
||||
{
|
||||
$store = [
|
||||
'id' => 921,
|
||||
'platform' => '京东',
|
||||
'erp_store_name' => '京东-余额预警测试店',
|
||||
'company_name' => '历史主体',
|
||||
'store_status' => '0',
|
||||
'store_manager' => '店铺负责人',
|
||||
'department_manager' => '部门负责人',
|
||||
'withdrawal_account' => null,
|
||||
];
|
||||
$this->mock(BusinessInformationMirrorRepository::class)
|
||||
->shouldReceive('allStores')
|
||||
->once()
|
||||
->andReturn([$store]);
|
||||
$this->mock(StoreReportPeriodBuilder::class)
|
||||
->shouldReceive('build')
|
||||
->once()
|
||||
->with([$store])
|
||||
->andReturn([
|
||||
'京东-余额预警测试店' => [[
|
||||
'company_name' => '当前主体有限公司',
|
||||
'effective_at' => '2026-10-01',
|
||||
'expires_at' => null,
|
||||
'source' => 'crawl',
|
||||
]],
|
||||
]);
|
||||
$this->mock(StoreAccountMirrorRepository::class)
|
||||
->shouldReceive('ownershipByStoreName')
|
||||
->once()
|
||||
->andReturn([]);
|
||||
|
||||
foreach (['2026-10-22', '2026-10-23', '2026-10-24'] as $date) {
|
||||
$this->insertStoreLedgerBalance($date, '京东-余额预警测试店', 6000);
|
||||
}
|
||||
|
||||
$html = $this->loginAs()->get($this->pageUrl() . '?' . http_build_query([
|
||||
'tab' => 'shops',
|
||||
'shops_balance_date' => '2026-10-24',
|
||||
]))->assertOk()->getContent();
|
||||
$panelStart = strpos($html, 'id="ledger-panel-shops"');
|
||||
$panelEnd = strpos($html, 'id="ledger-panel-flows"', $panelStart);
|
||||
$shopHtml = substr($html, $panelStart, $panelEnd - $panelStart);
|
||||
|
||||
$this->assertStringContainsString('value="2026-10-24" selected', $shopHtml);
|
||||
$this->assertStringContainsString('店铺收款账户账单 · 京东钱包', $shopHtml);
|
||||
$this->assertStringContainsString('>6,000.00</td>', $shopHtml);
|
||||
$this->assertStringContainsString('>5,000.00</td>', $shopHtml);
|
||||
$this->assertStringContainsString('余额连续 3 天保持 6,000.00 元,高于预留标准 5,000.00 元。', $shopHtml);
|
||||
$this->assertStringContainsString('预警', $shopHtml);
|
||||
}
|
||||
|
||||
private function pageUrl(): string
|
||||
{
|
||||
return route('business.pages.show', [
|
||||
@ -230,4 +285,24 @@ class FinanceLedgerShopDirectoryTest extends FeatureTestCase
|
||||
'page' => 'ledger',
|
||||
]);
|
||||
}
|
||||
|
||||
private function insertStoreLedgerBalance(string $date, string $storeName, float $balance): void
|
||||
{
|
||||
DB::connection('business_mirror')->table(JushuitanShopBalanceRepository::TABLE)->insert([
|
||||
'balance_date' => $date,
|
||||
'source_scope' => StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
'data_source' => StoreReceivingBillBalanceSnapshotSynchronizer::DATA_SOURCE_RECEIVING_BILL,
|
||||
'source_platform' => '京东',
|
||||
'store_name' => $storeName,
|
||||
'normalized_store_name' => JushuitanShopBalanceRepository::normalizeStoreName($storeName),
|
||||
'platform_account_id' => 'TEST-JD',
|
||||
'balance' => $balance,
|
||||
'source_row_key' => hash('sha256', $date . '|' . $storeName),
|
||||
'source_file_name' => '财务系统/店铺收款账户账单/京东钱包',
|
||||
'source_sha256' => hash('sha256', $date . '|' . $storeName . '|' . $balance),
|
||||
'imported_at' => now(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Repositories\FinanceBillBalanceRepository;
|
||||
use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository;
|
||||
use Modules\EcommerceFinance\Services\StoreReceivingBillBalanceSnapshotSynchronizer;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class StoreReceivingBillBalanceSnapshotSynchronizerTest extends FeatureTestCase
|
||||
{
|
||||
public function test_receiving_bill_balances_override_legacy_and_are_replaced_atomically(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$this->insertBalance($connection, [
|
||||
'source_scope' => 'all',
|
||||
'data_source' => JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN,
|
||||
'source_platform' => '京东',
|
||||
'store_name' => '京东-同店测试',
|
||||
'balance' => 100,
|
||||
]);
|
||||
$this->insertBalance($connection, [
|
||||
'source_scope' => 'pinduoduo',
|
||||
'data_source' => JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN,
|
||||
'source_platform' => '拼多多',
|
||||
'store_name' => '拼多多-补录测试店',
|
||||
'balance' => 200,
|
||||
]);
|
||||
$this->insertBalance($connection, [
|
||||
'source_scope' => StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
'data_source' => StoreReceivingBillBalanceSnapshotSynchronizer::DATA_SOURCE_RECEIVING_BILL,
|
||||
'source_platform' => '京东',
|
||||
'store_name' => '京东-旧快照',
|
||||
'balance' => 999,
|
||||
]);
|
||||
|
||||
$billBalances = Mockery::mock(FinanceBillBalanceRepository::class);
|
||||
$billBalances->shouldReceive('latestBalances')
|
||||
->once()
|
||||
->with(FinanceBillBalanceRepository::SCOPE_TAOBAO, '2026-10-26')
|
||||
->andReturn([[
|
||||
'source_scope' => FinanceBillBalanceRepository::SCOPE_TAOBAO,
|
||||
'source_platform' => '天猫',
|
||||
'store_name' => '天猫-账单余额店',
|
||||
'normalized_store_name' => JushuitanShopBalanceRepository::normalizeStoreName('天猫-账单余额店'),
|
||||
'platform_account_id' => 'ALI-1',
|
||||
'balance' => 300.25,
|
||||
'occurred_at' => '2026-10-26 23:58:00',
|
||||
'source_row_key' => 'taobao-row',
|
||||
'source_file_name' => '财务系统/店铺收款账户账单/淘系支付宝',
|
||||
]]);
|
||||
$billBalances->shouldReceive('latestBalances')
|
||||
->once()
|
||||
->with(FinanceBillBalanceRepository::SCOPE_JD_WALLET, '2026-10-26')
|
||||
->andReturn([[
|
||||
'source_scope' => FinanceBillBalanceRepository::SCOPE_JD_WALLET,
|
||||
'source_platform' => '京东',
|
||||
'store_name' => '京东-同店测试',
|
||||
'normalized_store_name' => JushuitanShopBalanceRepository::normalizeStoreName('京东-同店测试'),
|
||||
'platform_account_id' => 'JD-1',
|
||||
'balance' => 400.50,
|
||||
'occurred_at' => '2026-10-26 23:59:59',
|
||||
'source_row_key' => 'jd-row',
|
||||
'source_file_name' => '财务系统/店铺收款账户账单/京东钱包',
|
||||
]]);
|
||||
$this->app->instance(FinanceBillBalanceRepository::class, $billBalances);
|
||||
|
||||
$result = app(StoreReceivingBillBalanceSnapshotSynchronizer::class)->sync('2026-10-26');
|
||||
|
||||
$this->assertSame(3, $result['total']);
|
||||
$this->assertSame(2, $result['receiving_bill']);
|
||||
$this->assertSame(1, $result['jushuitan']);
|
||||
$this->assertSame(1, $result['replaced']);
|
||||
$this->assertDatabaseMissing('jushuitan_shop_balance_snapshots', [
|
||||
'balance_date' => '2026-10-26',
|
||||
'source_scope' => StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
'store_name' => '京东-旧快照',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('jushuitan_shop_balance_snapshots', [
|
||||
'balance_date' => '2026-10-26',
|
||||
'source_scope' => StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
'data_source' => StoreReceivingBillBalanceSnapshotSynchronizer::DATA_SOURCE_RECEIVING_BILL,
|
||||
'store_name' => '京东-同店测试',
|
||||
'balance' => 400.50,
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('jushuitan_shop_balance_snapshots', [
|
||||
'balance_date' => '2026-10-26',
|
||||
'source_scope' => StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE,
|
||||
'data_source' => JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN,
|
||||
'store_name' => '拼多多-补录测试店',
|
||||
'balance' => 200,
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
private function insertBalance($connection, array $values): void
|
||||
{
|
||||
$date = '2026-10-26';
|
||||
$storeName = (string) $values['store_name'];
|
||||
$connection->table(JushuitanShopBalanceRepository::TABLE)->insert([
|
||||
'balance_date' => $date,
|
||||
'source_scope' => $values['source_scope'],
|
||||
'data_source' => $values['data_source'],
|
||||
'source_platform' => $values['source_platform'],
|
||||
'store_name' => $storeName,
|
||||
'normalized_store_name' => JushuitanShopBalanceRepository::normalizeStoreName($storeName),
|
||||
'platform_account_id' => null,
|
||||
'balance' => $values['balance'],
|
||||
'source_row_key' => hash('sha256', $values['source_scope'] . '|' . $storeName),
|
||||
'source_file_name' => 'fixture',
|
||||
'source_sha256' => hash('sha256', $date . '|' . $storeName),
|
||||
'imported_at' => now(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -125,9 +125,9 @@ class BusinessMirrorScheduleTest extends TestCase
|
||||
$this->assertStringContainsString('esign:poll-signatures --quiet', $contents, $script);
|
||||
$this->assertStringContainsString('/run/caiwu-esign-polling.lock', $contents, $script);
|
||||
$this->assertSame(1, substr_count($contents, 'esign:poll-signatures --quiet'), $script);
|
||||
$this->assertStringNotContainsString('finance-ledger:sync-shop-data', $contents, $script);
|
||||
$this->assertSame(1, substr_count($contents, 'finance-ledger:sync-shop-data --balance-only --quiet'), $script);
|
||||
$this->assertStringContainsString(
|
||||
'# 财务台账:每天 02:30 同步 AI 库动账并重算流水;店铺台账默认不自动回填。',
|
||||
'# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。',
|
||||
$contents,
|
||||
$script,
|
||||
);
|
||||
@ -136,6 +136,11 @@ class BusinessMirrorScheduleTest extends TestCase
|
||||
$contents,
|
||||
$script,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1',
|
||||
$contents,
|
||||
$script,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user