CaiWuXiTong/modules/EcommerceFinance/Repositories/VipshopMpOpeningBalanceRepository.php

202 lines
7.8 KiB
PHP

<?php
namespace Modules\EcommerceFinance\Repositories;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Modules\EcommerceFinance\Services\VipshopMpOpeningBalanceImporter;
class VipshopMpOpeningBalanceRepository
{
public const BASELINE_PERIOD_END = '2026-06-30';
private readonly ConnectionInterface $mirror;
private readonly ConnectionInterface $bills;
public function __construct(DatabaseManager $databases)
{
$this->mirror = $databases->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
$this->bills = $databases->connection();
}
/**
* @return array{
* balance:float,
* date:?string,
* source:string,
* settlement_amount:float,
* settlement_count:int,
* settlement_available:bool,
* settlement_history_complete:bool,
* settlement_missing_periods:list<string>
* }
*/
public function openingBalance(?string $storeName, ?string $startDate, ?string $endDate): array
{
$start = $this->monthStart($startDate) ?? $this->monthStart($endDate);
$end = $this->monthStart($endDate) ?? $start;
$baselineMonth = CarbonImmutable::create(2026, 7, 1)->startOfDay();
if ($start === null || $start->lt($baselineMonth)) {
return $this->none();
}
if ($end === null || $end->lt($start)) {
$end = $start;
}
if (! $this->mirror->getSchemaBuilder()->hasTable(VipshopMpOpeningBalanceImporter::TABLE)) {
return $this->none();
}
$store = trim((string) $storeName);
$snapshot = $this->mirror->table(VipshopMpOpeningBalanceImporter::TABLE)
->where('period_end', self::BASELINE_PERIOD_END)
->when($store !== '', static fn ($query) => $query->where('store_name', $store));
if ((clone $snapshot)->doesntExist()) {
return $this->none();
}
$balance = round((float) (clone $snapshot)->sum('balance'), 2);
$settlementColumnsReady = $this->mirror->getSchemaBuilder()->hasColumn(
VipshopMpOpeningBalanceImporter::TABLE,
'settled_amount',
);
$settledBefore = $settlementColumnsReady
? round((float) $this->mirror->table(VipshopMpOpeningBalanceImporter::TABLE)
->where('period_end', '>', self::BASELINE_PERIOD_END)
->where('period_end', '<', $start->format('Y-m-d'))
->when($store !== '', static fn ($query) => $query->where('store_name', $store))
->sum('settled_amount'), 2)
: 0.0;
$balance = round($balance - $settledBefore, 2);
if ($start->gt($baselineMonth)) {
$movement = $this->bills->table('ec_account_bills')
->where('company_id', (int) (company_id() ?: 1))
->where('bill_type', 'vipshop')
->whereNull('deleted_at')
->where('payload->settle_period', '>=', '2026-07')
->where('payload->settle_period', '<', $start->format('Y-m'))
->when($store !== '', static fn ($query) => $query->where('store_name', $store))
->selectRaw('COALESCE(SUM(income), 0) AS income, COALESCE(SUM(expense), 0) AS expense')
->first();
$balance = round(
$balance
+ (float) ($movement->income ?? 0)
- (float) ($movement->expense ?? 0),
2,
);
}
$settlementAmount = 0.0;
$settlementCount = 0;
$settlementAvailable = false;
$settlementMissingPeriods = [];
if ($settlementColumnsReady) {
$periodSnapshot = $this->mirror->table(VipshopMpOpeningBalanceImporter::TABLE)
->whereBetween('period_end', [
$start->endOfMonth()->format('Y-m-d'),
$end->endOfMonth()->format('Y-m-d'),
])
->when($store !== '', static fn ($query) => $query->where('store_name', $store));
$settlementAvailable = (clone $periodSnapshot)->exists();
$currentSettlement = (clone $periodSnapshot)
->selectRaw('COALESCE(SUM(settled_amount), 0) AS amount, COALESCE(SUM(settled_row_count), 0) AS rows_count');
$currentSettlement = $currentSettlement->first();
$settlementAmount = round((float) ($currentSettlement->amount ?? 0), 2);
$settlementCount = (int) ($currentSettlement->rows_count ?? 0);
$settlementMissingPeriods = $this->missingSettlementPeriods($end, $store, $baselineMonth);
}
return [
'balance' => $balance,
'date' => $start->subDay()->format('Y-m-d'),
'source' => $start->equalTo($baselineMonth) ? 'june_ending' : 'previous_period',
'settlement_amount' => $settlementAmount,
'settlement_count' => $settlementCount,
'settlement_available' => $settlementAvailable,
'settlement_history_complete' => $settlementMissingPeriods === [],
'settlement_missing_periods' => $settlementMissingPeriods,
];
}
/**
* @return array{
* balance:float,
* date:null,
* source:string,
* settlement_amount:float,
* settlement_count:int,
* settlement_available:bool,
* settlement_history_complete:bool,
* settlement_missing_periods:list<string>
* }
*/
private function none(): array
{
return [
'balance' => 0.0,
'date' => null,
'source' => 'none',
'settlement_amount' => 0.0,
'settlement_count' => 0,
'settlement_available' => false,
'settlement_history_complete' => false,
'settlement_missing_periods' => [],
];
}
/** @return list<string> */
private function missingSettlementPeriods(
CarbonImmutable $end,
string $store,
CarbonImmutable $baselineMonth,
): array {
$expectedPeriods = [];
for ($month = $baselineMonth; $month->lte($end); $month = $month->addMonthNoOverflow()) {
$expectedPeriods[] = $month->endOfMonth()->format('Y-m-d');
}
$baselineStores = $this->mirror->table(VipshopMpOpeningBalanceImporter::TABLE)
->where('period_end', self::BASELINE_PERIOD_END)
->when($store !== '', static fn ($query) => $query->where('store_name', $store))
->distinct()
->pluck('store_name')
->all();
if ($baselineStores === []) {
return $expectedPeriods;
}
$available = $this->mirror->table(VipshopMpOpeningBalanceImporter::TABLE)
->whereIn('period_end', $expectedPeriods)
->when($store !== '', static fn ($query) => $query->where('store_name', $store))
->get(['period_end', 'store_name']);
$completePeriods = $available
->groupBy('period_end')
->filter(static fn ($rows): bool => count(array_unique($rows->pluck('store_name')->all())) >= count($baselineStores))
->keys()
->all();
return array_values(array_diff($expectedPeriods, $completePeriods));
}
private function monthStart(?string $value): ?CarbonImmutable
{
$date = trim((string) $value);
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) {
return null;
}
try {
$parsed = CarbonImmutable::createFromFormat('!Y-m-d', $date);
} catch (\Throwable) {
return null;
}
return $parsed instanceof CarbonImmutable && $parsed->format('Y-m-d') === $date
? $parsed->startOfMonth()
: null;
}
}