feat: 计算淘系微信账户7月余额 #1003

Merged
qiuxiang merged 1 commits from feature/qiuxiang-taobao-wechat-july-balance into main 2026-11-09 10:27:24 +08:00
6 changed files with 393 additions and 51 deletions

View File

@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
$schema = Schema::connection($this->connection());
if ($schema->hasTable('taobao_wechat_opening_balances')) {
return;
}
$schema->create('taobao_wechat_opening_balances', function (Blueprint $table): void {
$table->id();
$table->date('balance_date');
$table->string('store_name', 191);
$table->decimal('balance', 20, 2);
$table->string('source', 191);
$table->text('source_note')->nullable();
$table->timestamp('imported_at');
$table->timestamps();
$table->unique(['balance_date', 'store_name'], 'taobao_wechat_opening_store_uq');
});
}
public function down(): void
{
if (app()->environment('testing')
|| (string) config('system_database.mode', 'bootstrap') === 'bootstrap') {
return;
}
Schema::connection($this->connection())->dropIfExists('taobao_wechat_opening_balances');
}
};

View File

@ -7,7 +7,7 @@ use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\EcommerceFinance\AccountBillColumns;
use Modules\EcommerceFinance\Http\Concerns\DecoratesLedgerRemarks;
use Modules\EcommerceFinance\Repositories\TaobaoAlipaySettlementBillRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use RuntimeException;
@ -17,7 +17,7 @@ class TaobaoWechatAccountBills extends Controller
public function index(
Request $request,
TaobaoWechatSettlementBillRepository $repository,
TaobaoAlipaySettlementBillRepository $alipayRepository,
TaobaoWechatOpeningBalanceRepository $openingBalanceRepository,
)
{
$this->authorizeStoreReceivingBills();
@ -60,23 +60,25 @@ class TaobaoWechatAccountBills extends Controller
], 503);
}
$alipaySummary = null;
try {
// 微信账单没有余额列;期初待各店铺6月期末余额录入,暂时固定为0,
// 期末仍按现有口径取同一筛选条件下淘系支付宝的账户余额。
$alipaySummary = $alipayRepository->summary($filters);
} catch (RuntimeException $exception) {
if ($exception->getMessage() !== 'taobao_alipay_authoritative_bills_not_ready') {
throw $exception;
}
}
$opening = $openingBalanceRepository->openingBalance(
$filters['store_name'] ?? null,
$filters['start'] ?? null,
);
$openingBalance = $opening['balance'];
$data['summary'] = array_merge($data['summary'], [
'opening_balance' => 0,
'opening_balance_date' => null,
'opening_balance_source' => 'pending_june_ending',
'balance' => $alipaySummary['balance'] ?? null,
'balance_source' => $alipaySummary === null ? 'unavailable' : 'taobao_alipay',
'opening_balance' => $openingBalance,
'opening_balance_date' => $opening['date'],
'opening_balance_source' => $opening['source'],
'opening_balance_store_count' => $opening['store_count'],
'balance' => $openingBalance === null
? null
: round(
$openingBalance
+ (float) ($data['summary']['income'] ?? 0)
- (float) ($data['summary']['expense'] ?? 0),
2,
),
'balance_source' => $openingBalance === null ? 'unavailable' : 'opening_plus_period_activity',
]);
$data['columns'] = AccountBillColumns::for('taobao-wechat');
@ -89,9 +91,10 @@ class TaobaoWechatAccountBills extends Controller
return [
'income' => 0,
'expense' => 0,
'opening_balance' => 0,
'opening_balance' => null,
'opening_balance_date' => null,
'opening_balance_source' => 'pending_june_ending',
'opening_balance_source' => 'unavailable',
'opening_balance_store_count' => 0,
'balance' => null,
'balance_source' => 'unavailable',
'count' => 0,

View File

@ -0,0 +1,110 @@
<?php
namespace Modules\EcommerceFinance\Repositories;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Schema;
class TaobaoWechatOpeningBalanceRepository
{
public const TABLE = 'taobao_wechat_opening_balances';
public const BASELINE_DATE = '2026-06-30';
private const BILL_TABLE = 'taobao_wechat_bill_rows';
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/**
* @return array{balance:?float,date:?string,source:string,store_count:int}
*/
public function openingBalance(?string $storeName, ?string $periodStart): array
{
if (! $this->hasTable(self::TABLE)) {
return $this->unavailable();
}
$query = $this->connection->table(self::TABLE)
->where('balance_date', self::BASELINE_DATE);
if ($storeName !== null && $storeName !== '') {
$query->where('store_name', $storeName);
}
$baseline = (clone $query)->selectRaw(
'COALESCE(SUM(balance), 0) AS balance, COUNT(*) AS store_count'
)->first();
$storeCount = (int) ($baseline->store_count ?? 0);
if ($storeCount === 0) {
return $this->unavailable();
}
$balance = round((float) $baseline->balance, 2);
$date = self::BASELINE_DATE;
$source = 'data_cube_june_ending';
$start = $this->date($periodStart);
if ($start !== null && $start->gt('2026-07-01')) {
$movement = $this->connection->table(self::BILL_TABLE)
->where('occurred_at', '>=', '2026-07-01 00:00:00')
->where('occurred_at', '<', $start->format('Y-m-d') . ' 00:00:00')
->when($storeName !== null && $storeName !== '', function ($query) use ($storeName): void {
$query->where('store_name', $storeName);
})
->selectRaw(
'COALESCE(SUM(income_amount), 0) AS income, '
. 'COALESCE(SUM(expense_amount), 0) AS expense'
)
->first();
$balance = round(
$balance + (float) ($movement->income ?? 0) - (float) ($movement->expense ?? 0),
2,
);
$date = $start->subDay()->format('Y-m-d');
$source = 'data_cube_june_ending_carried_forward';
}
return [
'balance' => $balance,
'date' => $date,
'source' => $source,
'store_count' => $storeCount,
];
}
/** @return array{balance:null,date:null,source:string,store_count:int} */
private function unavailable(): array
{
return [
'balance' => null,
'date' => null,
'source' => 'unavailable',
'store_count' => 0,
];
}
private function date(?string $value): ?CarbonImmutable
{
if ($value === null || preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value);
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
private function hasTable(string $table): bool
{
return Schema::connection($this->connection->getName())->hasTable($table);
}
}

View File

@ -318,17 +318,17 @@ export default {
if(this.billType==='taobao-wechat'){
const openingSource=this.summary.opening_balance_source;
const openingDate=this.summary.opening_balance_date;
const openingNote=openingSource==='pending_june_ending'
const openingNote=openingSource==='unavailable'
?'待录入各店铺6月期末余额'
:(openingSource==='first_row_estimate'
?'首月按淘系支付宝首笔余额倒推'
:(openingDate?`截至 ${openingDate} 淘系支付宝最后一笔`:'淘系支付宝上月最后一笔'));
const balanceNote=this.summary.balance_source==='unavailable'?'淘系支付宝余额暂不可用':'同淘系支付宝账户';
:(openingSource==='data_cube_june_ending_carried_forward'
?`数据魔方6月末余额结转至 ${openingDate}`
:(openingDate?`数据魔方 ${openingDate} 期末余额`:'数据魔方6月末余额'));
const balanceNote=this.summary.balance_source==='unavailable'?'期初余额未就绪':'期初余额 + 收入合计 - 支出合计';
return [
{label:'期初余额',value:this.moneyWan(this.summary.opening_balance),note:openingNote,className:''},
{label:'收入合计',value:this.moneyWan(this.summary.income),note:`${this.summary.count} 笔交易`,className:'is-income'},
{label:'支出合计',value:this.moneyWan(this.summary.expense),note:'按当前筛选',className:'is-expense'},
{label:'期末余额(最新)',value:this.moneyWan(this.summary.balance),note:balanceNote,className:''},
{label:'期末余额',value:this.moneyWan(this.summary.balance),note:balanceNote,className:''},
{label:'交易笔数',value:this.summary.count,note:'当前筛选结果',className:''},
];
}

View File

@ -4,7 +4,7 @@ namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use Mockery;
use Modules\EcommerceFinance\Repositories\TaobaoAlipaySettlementBillRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository;
use Modules\EcommerceFinance\Repositories\TaobaoWechatSettlementBillRepository;
use RuntimeException;
use Tests\Feature\FeatureTestCase;
@ -44,17 +44,17 @@ class TaobaoWechatReceivingBillsTest extends FeatureTestCase
]);
$this->app->instance(TaobaoWechatSettlementBillRepository::class, $repository);
$alipayRepository = Mockery::mock(TaobaoAlipaySettlementBillRepository::class);
$alipayRepository->shouldReceive('summary')->once()->with($filters)->andReturn([
'income' => 320.0,
'expense' => 25.0,
'opening_balance' => 230.0,
'opening_balance_date' => '2026-08-31',
'opening_balance_source' => 'previous_period',
'balance' => 525.0,
'count' => 12,
]);
$this->app->instance(TaobaoAlipaySettlementBillRepository::class, $alipayRepository);
$openingRepository = Mockery::mock(TaobaoWechatOpeningBalanceRepository::class);
$openingRepository->shouldReceive('openingBalance')
->once()
->with('淘系微信-测试店', '2026-08-12')
->andReturn([
'balance' => 230.0,
'date' => '2026-08-11',
'source' => 'data_cube_june_ending_carried_forward',
'store_count' => 1,
]);
$this->app->instance(TaobaoWechatOpeningBalanceRepository::class, $openingRepository);
$this->withExceptionHandling()
->loginAs()
@ -68,14 +68,60 @@ class TaobaoWechatReceivingBillsTest extends FeatureTestCase
->assertJsonPath('data.0.payload.entry_type', '收入')
->assertJsonPath('columns.title', '淘系微信账户')
->assertJsonPath('summary.count', 41)
->assertJsonPath('summary.opening_balance', 0)
->assertJsonPath('summary.opening_balance_date', null)
->assertJsonPath('summary.opening_balance_source', 'pending_june_ending')
->assertJsonPath('summary.balance', 525)
->assertJsonPath('summary.balance_source', 'taobao_alipay');
->assertJsonPath('summary.opening_balance', 230)
->assertJsonPath('summary.opening_balance_date', '2026-08-11')
->assertJsonPath('summary.opening_balance_source', 'data_cube_june_ending_carried_forward')
->assertJsonPath('summary.opening_balance_store_count', 1)
->assertJsonPath('summary.balance', 321.64)
->assertJsonPath('summary.balance_source', 'opening_plus_period_activity');
}
public function test_opening_balance_stays_zero_when_alipay_summary_is_unavailable(): void
public function test_july_closing_equals_june_ending_plus_income_minus_expense(): void
{
$this->allowPage();
$filters = [
'start' => '2026-07-01',
'end' => '2026-07-31',
];
$repository = Mockery::mock(TaobaoWechatSettlementBillRepository::class);
$repository->shouldReceive('paginateAccountBills')->once()->andReturn([
'current_page' => 1,
'last_page' => 1,
'per_page' => 20,
'total' => 2,
'data' => [],
'summary' => ['income' => 100.0, 'expense' => 25.5, 'balance' => 74.5, 'count' => 2],
]);
$this->app->instance(TaobaoWechatSettlementBillRepository::class, $repository);
$openingRepository = Mockery::mock(TaobaoWechatOpeningBalanceRepository::class);
$openingRepository->shouldReceive('openingBalance')
->once()
->with(null, '2026-07-01')
->andReturn([
'balance' => 230.0,
'date' => '2026-06-30',
'source' => 'data_cube_june_ending',
'store_count' => 21,
]);
$this->app->instance(TaobaoWechatOpeningBalanceRepository::class, $openingRepository);
$this->withExceptionHandling()
->loginAs()
->getJson(route('ecommerce-finance.account-bills.index', [
'bill_type' => 'taobao-wechat',
...$filters,
]))
->assertOk()
->assertJsonPath('summary.opening_balance', 230)
->assertJsonPath('summary.opening_balance_date', '2026-06-30')
->assertJsonPath('summary.opening_balance_source', 'data_cube_june_ending')
->assertJsonPath('summary.opening_balance_store_count', 21)
->assertJsonPath('summary.balance', 304.5)
->assertJsonPath('summary.balance_source', 'opening_plus_period_activity');
}
public function test_balance_stays_unavailable_when_opening_balance_is_not_imported(): void
{
$this->allowPage();
$repository = Mockery::mock(TaobaoWechatSettlementBillRepository::class);
@ -89,11 +135,14 @@ class TaobaoWechatReceivingBillsTest extends FeatureTestCase
]);
$this->app->instance(TaobaoWechatSettlementBillRepository::class, $repository);
$alipayRepository = Mockery::mock(TaobaoAlipaySettlementBillRepository::class);
$alipayRepository->shouldReceive('summary')->once()->andThrow(
new RuntimeException('taobao_alipay_authoritative_bills_not_ready')
);
$this->app->instance(TaobaoAlipaySettlementBillRepository::class, $alipayRepository);
$openingRepository = Mockery::mock(TaobaoWechatOpeningBalanceRepository::class);
$openingRepository->shouldReceive('openingBalance')->once()->andReturn([
'balance' => null,
'date' => null,
'source' => 'unavailable',
'store_count' => 0,
]);
$this->app->instance(TaobaoWechatOpeningBalanceRepository::class, $openingRepository);
$this->withExceptionHandling()
->loginAs()
@ -103,9 +152,10 @@ class TaobaoWechatReceivingBillsTest extends FeatureTestCase
'end' => '2026-11-30',
]))
->assertOk()
->assertJsonPath('summary.opening_balance', 0)
->assertJsonPath('summary.opening_balance', null)
->assertJsonPath('summary.opening_balance_date', null)
->assertJsonPath('summary.opening_balance_source', 'pending_june_ending')
->assertJsonPath('summary.opening_balance_source', 'unavailable')
->assertJsonPath('summary.opening_balance_store_count', 0)
->assertJsonPath('summary.balance', null)
->assertJsonPath('summary.balance_source', 'unavailable');
}

View File

@ -0,0 +1,130 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\EcommerceFinance\Repositories\TaobaoWechatOpeningBalanceRepository;
use Tests\TestCase;
class TaobaoWechatOpeningBalanceRepositoryTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
$this->createTables();
}
public function test_july_opening_uses_the_june_ending_balance(): void
{
$this->insertOpening('淘系微信一店', '669385.40');
$result = app(TaobaoWechatOpeningBalanceRepository::class)
->openingBalance('淘系微信一店', '2026-07-01');
$this->assertSame(669385.4, $result['balance']);
$this->assertSame('2026-06-30', $result['date']);
$this->assertSame('data_cube_june_ending', $result['source']);
$this->assertSame(1, $result['store_count']);
}
public function test_later_periods_carry_the_opening_balance_forward(): void
{
$this->insertOpening('淘系微信一店', '100.00');
$this->insertBill('淘系微信一店', '2026-07-05 10:00:00', '50.00', '20.00');
$this->insertBill('淘系微信一店', '2026-08-02 10:00:00', '10.00', '5.00');
$result = app(TaobaoWechatOpeningBalanceRepository::class)
->openingBalance('淘系微信一店', '2026-08-01');
$this->assertSame(130.0, $result['balance']);
$this->assertSame('2026-07-31', $result['date']);
$this->assertSame('data_cube_june_ending_carried_forward', $result['source']);
}
public function test_all_store_openings_are_summed_when_no_store_is_selected(): void
{
$this->insertOpening('淘系微信一店', '100.00');
$this->insertOpening('淘系微信二店', '200.25');
$result = app(TaobaoWechatOpeningBalanceRepository::class)
->openingBalance(null, '2026-07-01');
$this->assertSame(300.25, $result['balance']);
$this->assertSame(2, $result['store_count']);
}
public function test_missing_opening_balance_is_unavailable(): void
{
$result = app(TaobaoWechatOpeningBalanceRepository::class)
->openingBalance('未录入店铺', '2026-07-01');
$this->assertNull($result['balance']);
$this->assertNull($result['date']);
$this->assertSame('unavailable', $result['source']);
$this->assertSame(0, $result['store_count']);
}
private function createTables(): void
{
$schema = Schema::connection('business_mirror');
$schema->create(TaobaoWechatOpeningBalanceRepository::TABLE, function (Blueprint $table): void {
$table->id();
$table->date('balance_date');
$table->string('store_name', 191);
$table->decimal('balance', 20, 2);
$table->string('source', 191);
$table->text('source_note')->nullable();
$table->timestamp('imported_at');
$table->timestamps();
$table->unique(['balance_date', 'store_name']);
});
$schema->create('taobao_wechat_bill_rows', function (Blueprint $table): void {
$table->string('record_code', 191)->primary();
$table->string('store_name')->nullable();
$table->dateTime('occurred_at');
$table->decimal('income_amount', 20, 2);
$table->decimal('expense_amount', 20, 2);
});
}
private function insertOpening(string $storeName, string $balance): void
{
DB::connection('business_mirror')->table(TaobaoWechatOpeningBalanceRepository::TABLE)->insert([
'balance_date' => '2026-06-30',
'store_name' => $storeName,
'balance' => $balance,
'source' => 'DataCube淘系微信7月首笔余额倒推',
'source_note' => '用7月第一笔交易后的账户余额减去第一笔交易金额',
'imported_at' => '2026-11-09 10:00:00',
]);
}
private function insertBill(
string $storeName,
string $occurredAt,
string $income,
string $expense,
): void {
static $sequence = 0;
$sequence++;
DB::connection('business_mirror')->table('taobao_wechat_bill_rows')->insert([
'record_code' => 'TEST-' . $sequence,
'store_name' => $storeName,
'occurred_at' => $occurredAt,
'income_amount' => $income,
'expense_amount' => $expense,
]);
}
}