fix: use local sqlite for store report
This commit is contained in:
parent
9a15f64490
commit
f397fbb976
@ -157,13 +157,24 @@ SQL);
|
||||
/** @return array{data:array<int,array<string,mixed>>,total:int} */
|
||||
private function allStores(): array
|
||||
{
|
||||
if (! $this->mirror->ready('store-information.read')) {
|
||||
throw new ServiceUnavailableHttpException(null, '店铺资料共享镜像尚未完成首次同步。');
|
||||
if ($this->mirror->ready('store-information.read')) {
|
||||
$rows = $this->mirror->allStores();
|
||||
return [
|
||||
'data' => array_map(fn (array $row): array => $this->mapStore($row), $rows),
|
||||
'total' => count($rows),
|
||||
];
|
||||
}
|
||||
|
||||
$rows = $this->mirror->allStores();
|
||||
$rows = array_map(fn (array $row): array => $this->mapStore($row), $rows);
|
||||
return ['data' => $rows, 'total' => count($rows)];
|
||||
if ((app(\App\Utilities\SystemDatabaseConfiguration::class)->current()['mode'] ?? '') === 'bootstrap'
|
||||
&& ! config('upstreams.local_configuration.enabled', false)) {
|
||||
throw new ServiceUnavailableHttpException(null, '当前仍使用本机临时引导库。请先连接团队共享数据库,然后重新登录。');
|
||||
}
|
||||
|
||||
return $this->caches->forSource(self::SOURCE)->remember(
|
||||
'store-information.read',
|
||||
['all' => true],
|
||||
fn () => $this->storeSnapshotAll(new UpstreamReadOnlyQuery(self::SOURCE)),
|
||||
);
|
||||
}
|
||||
|
||||
private function subjectOperatingReportPage(int $page, int $perPage): array
|
||||
@ -241,6 +252,50 @@ SQL);
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{data:array<int,array<string,mixed>>,total:int} */
|
||||
private function storeSnapshotAll(UpstreamReadOnlyQuery $query): array
|
||||
{
|
||||
$rows = $query->select(<<<SQL
|
||||
SELECT
|
||||
s.Id AS id,
|
||||
s.sotreId AS store_id,
|
||||
s.openTime AS opened_at,
|
||||
s.renewalTime AS renewed_at,
|
||||
s.erpShopName AS erp_store_name,
|
||||
s.unifiedSocialCreditCode AS unified_social_credit_code,
|
||||
c.businessLicenseName AS company_name,
|
||||
c.businessLicenseType AS company_type,
|
||||
s.trademarkNumber AS trademark_number,
|
||||
t.trademarkName AS trademark_name,
|
||||
s.platform AS platform,
|
||||
s.responsibleDepartment AS profit_center,
|
||||
s.shopHead AS store_manager,
|
||||
s.customerDeptManager AS department_manager,
|
||||
s.shopState AS store_status,
|
||||
s.shopBankAccount AS withdrawal_account,
|
||||
s.shopType AS store_type,
|
||||
s.channelType AS channel_mode
|
||||
FROM rpt.fys_shopInfo AS s
|
||||
OUTER APPLY (
|
||||
SELECT TOP 1 company.businessLicenseName, company.businessLicenseType
|
||||
FROM rpt.fys_companyInfo AS company
|
||||
WHERE company.unifiedSocialCreditCode = NULLIF(s.unifiedSocialCreditCode, '')
|
||||
ORDER BY company.Id DESC
|
||||
) AS c
|
||||
OUTER APPLY (
|
||||
SELECT TOP 1 trademark.trademarkName
|
||||
FROM rpt.fys_TrademarkInfo AS trademark
|
||||
WHERE trademark.trademarkNumber = NULLIF(s.trademarkNumber, '')
|
||||
AND trademark.isDelete = 0
|
||||
ORDER BY trademark.Id DESC
|
||||
) AS t
|
||||
ORDER BY s.Id DESC
|
||||
SQL);
|
||||
$rows = array_map(fn (array $row): array => $this->mapStore($row), $rows);
|
||||
|
||||
return ['data' => $rows, 'total' => count($rows)];
|
||||
}
|
||||
|
||||
private function trademarkPage(int $page, int $perPage): array
|
||||
{
|
||||
return $this->page(
|
||||
|
||||
@ -67,6 +67,7 @@ services:
|
||||
- "127.0.0.1:18088:18088"
|
||||
volumes:
|
||||
- ./runtime/.env:/var/www/html/.env
|
||||
- ./runtime/bills.sqlite:/var/www/html/runtime/bills.sqlite:ro
|
||||
- caiwu_storage:/var/www/html/storage
|
||||
healthcheck:
|
||||
test:
|
||||
|
||||
@ -159,9 +159,9 @@ return [
|
||||
'title' => '店铺维度报表',
|
||||
'directory' => [
|
||||
'icon' => 'query_stats',
|
||||
'status' => '共享镜像',
|
||||
'description' => '店铺资料、主体生效区间和平台账单统一读取团队共享业务镜像;销量按账单收入汇总。',
|
||||
'empty' => '店铺维度报表尚未完成共享数据导入。',
|
||||
'status' => '已接入真实账单与生命周期',
|
||||
'description' => '店铺资料来自经营分析副本库;主体生效区间和月度销量来自本地 bills.sqlite。',
|
||||
'empty' => '暂无可匹配的店铺生命周期或账单数据。',
|
||||
'fields' => [
|
||||
['name' => 'erp_store_name', 'label' => 'ERP系统店铺名称'],
|
||||
['name' => 'store_id', 'label' => '店铺ID(唯一值)'],
|
||||
|
||||
@ -71,6 +71,17 @@ return [
|
||||
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
|
||||
],
|
||||
|
||||
// 店铺维度报表的本地只读账单与生命周期数据源。
|
||||
'bills_sqlite' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => env('BILLS_SQLITE_PATH', base_path('runtime/bills.sqlite')),
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => null,
|
||||
'options' => [
|
||||
PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READONLY,
|
||||
],
|
||||
],
|
||||
|
||||
'mysql' => [
|
||||
'driver' => 'mysql',
|
||||
'url' => env('DATABASE_URL'),
|
||||
|
||||
@ -24,6 +24,7 @@ services:
|
||||
- "127.0.0.1:18088:18088"
|
||||
volumes:
|
||||
- ./runtime/.env:/var/www/html/.env
|
||||
- ./runtime/bills.sqlite:/var/www/html/runtime/bills.sqlite:ro
|
||||
- jiangling_storage:/var/www/html/storage
|
||||
- ./app:/var/www/html/app
|
||||
- ./config:/var/www/html/config
|
||||
@ -55,6 +56,7 @@ services:
|
||||
- while true; do php artisan upstream:snapshots:refresh-all --quiet || true; sleep 60; done
|
||||
volumes:
|
||||
- ./runtime/.env:/var/www/html/.env
|
||||
- ./runtime/bills.sqlite:/var/www/html/runtime/bills.sqlite:ro
|
||||
- jiangling_storage:/var/www/html/storage
|
||||
- ./app:/var/www/html/app
|
||||
- ./config:/var/www/html/config
|
||||
|
||||
@ -4,49 +4,47 @@ namespace Modules\EcommerceFinance\Repositories;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
|
||||
/** 店铺维度报表只读取团队共享业务镜像。 */
|
||||
/**
|
||||
* 将经营分析副本库中的店铺资料与本地账单 SQLite 组合为店铺维度报表。
|
||||
*
|
||||
* SQLite 只读保存店铺生命周期和平台账单;生命周期区间统一使用
|
||||
* [effective_at, expires_at),避免主体切换日的账单被重复统计。
|
||||
*/
|
||||
class StoreReportRepository
|
||||
{
|
||||
// 保留导入命令使用的数据集键;报表页面本身读取本地 SQLite。
|
||||
public const BILLS_DATASET = 'store-report.platform-bills';
|
||||
public const LIFECYCLES_DATASET = 'store-report.store-lifecycles';
|
||||
|
||||
private const DEFAULT_EFFECTIVE_AT = '2026-05-01';
|
||||
private const DEFAULT_EXPIRES_AT = '2999-01-01';
|
||||
private const REPORT_YEAR = '2026';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
private ?ConnectionInterface $connection = null;
|
||||
|
||||
public function __construct(DatabaseManager $databases)
|
||||
{
|
||||
$this->connection = $databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
public function __construct(private readonly DatabaseManager $database) {}
|
||||
|
||||
/**
|
||||
* @param array<int,array<string,mixed>> $stores
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function rows(array $stores, ?int $reportYear = null): array
|
||||
public function rows(array $stores): array
|
||||
{
|
||||
if ($stores === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
[$billGeneration, $lifecycleGeneration] = $this->activeGenerations();
|
||||
$reportYear ??= (int) now()->format('Y');
|
||||
if ($reportYear < 2000 || $reportYear > 2999) {
|
||||
throw new RuntimeException('店铺维度报表年份无效。');
|
||||
}
|
||||
|
||||
$this->assertDatabaseFile();
|
||||
$this->connection ??= $this->database->connection('bills_sqlite');
|
||||
$names = array_values(array_unique(array_filter(array_map(
|
||||
static fn (array $row): string => trim((string) ($row['erp_store_name'] ?? '')),
|
||||
$stores,
|
||||
))));
|
||||
$lifecycles = $this->lifecycles($names, $lifecycleGeneration);
|
||||
$lifecycleSales = $this->lifecycleSales($names, $billGeneration, $lifecycleGeneration);
|
||||
$fallbackSales = $this->fallbackSales(array_values(array_diff($names, array_keys($lifecycles))), $billGeneration);
|
||||
$lifecycles = $this->lifecycles($names);
|
||||
$lifecycleSales = $this->lifecycleSales($names);
|
||||
$fallbackSales = $this->fallbackSales(array_values(array_diff($names, array_keys($lifecycles))));
|
||||
$rows = [];
|
||||
|
||||
foreach ($stores as $store) {
|
||||
@ -57,7 +55,7 @@ class StoreReportRepository
|
||||
|
||||
$periods = $lifecycles[$storeName] ?? [[
|
||||
'company_name' => $store['company_name'] ?? null,
|
||||
'effective_at' => $store['opened_at'] ?? sprintf('%d-01-01', $reportYear),
|
||||
'effective_at' => self::DEFAULT_EFFECTIVE_AT,
|
||||
'expires_at' => self::DEFAULT_EXPIRES_AT,
|
||||
'lifecycle_id' => null,
|
||||
]];
|
||||
@ -69,16 +67,16 @@ class StoreReportRepository
|
||||
$monthly = [];
|
||||
for ($month = 1; $month <= 12; $month++) {
|
||||
$monthly[sprintf('sales_%02d', $month)] = (float) (
|
||||
$saleData['months'][sprintf('%d-%02d', $reportYear, $month)] ?? 0
|
||||
$saleData['months'][sprintf('%s-%02d', self::REPORT_YEAR, $month)] ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
...$store,
|
||||
'store_id' => $store['store_id'] ?? $storeName,
|
||||
'store_id' => $storeName,
|
||||
'status' => $this->status($store['store_status'] ?? null),
|
||||
'entity' => $period['company_name'] ?: ($store['company_name'] ?? null),
|
||||
'effective_at' => $this->date($period['effective_at'] ?? null, sprintf('%d-01-01', $reportYear)),
|
||||
'effective_at' => $this->date($period['effective_at'] ?? null, self::DEFAULT_EFFECTIVE_AT),
|
||||
'invalid_at' => $this->date($period['expires_at'] ?? null, self::DEFAULT_EXPIRES_AT),
|
||||
'period_sales' => (float) $saleData['period'],
|
||||
...$monthly,
|
||||
@ -89,41 +87,24 @@ class StoreReportRepository
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:string} */
|
||||
private function activeGenerations(): array
|
||||
private function assertDatabaseFile(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection->getName());
|
||||
foreach (['store_report_import_states', 'store_report_bill_rows', 'store_report_lifecycle_rows'] as $table) {
|
||||
if (! $schema->hasTable($table)) {
|
||||
throw new RuntimeException('店铺维度报表共享镜像尚未完成迁移。');
|
||||
}
|
||||
$path = (string) config('database.connections.bills_sqlite.database');
|
||||
if ($path === '' || ! is_file($path)) {
|
||||
throw new RuntimeException('店铺账单 SQLite 尚未挂载:' . $path);
|
||||
}
|
||||
|
||||
$states = $this->connection->table('store_report_import_states')
|
||||
->whereIn('dataset_key', [self::BILLS_DATASET, self::LIFECYCLES_DATASET])
|
||||
->get(['dataset_key', 'status', 'active_generation'])
|
||||
->keyBy('dataset_key');
|
||||
|
||||
foreach ([self::BILLS_DATASET, self::LIFECYCLES_DATASET] as $dataset) {
|
||||
$state = $states->get($dataset);
|
||||
if ($state === null || empty($state->active_generation)) {
|
||||
throw new RuntimeException('店铺维度报表共享数据尚未完成首次导入。');
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
(string) $states->get(self::BILLS_DATASET)->active_generation,
|
||||
(string) $states->get(self::LIFECYCLES_DATASET)->active_generation,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,array<int,array<string,mixed>>> */
|
||||
private function lifecycles(array $names, string $generation): array
|
||||
private function lifecycles(array $names): array
|
||||
{
|
||||
if (! $this->hasTable('store_lifecycles')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach (array_chunk($names, 500) as $chunk) {
|
||||
$rows = $this->connection->table('store_report_lifecycle_rows')
|
||||
->where('generation', $generation)
|
||||
foreach (array_chunk($names, 900) as $chunk) {
|
||||
$rows = $this->connection->table('store_lifecycles')
|
||||
->whereIn('erp_store_name', $chunk)
|
||||
->orderBy('erp_store_name')->orderBy('effective_at')->orderBy('id')
|
||||
->get(['id', 'erp_store_name', 'company_name', 'effective_at', 'expires_at']);
|
||||
@ -142,23 +123,27 @@ class StoreReportRepository
|
||||
}
|
||||
|
||||
/** @return array<string,array{period:float,months:array<string,float>}> */
|
||||
private function lifecycleSales(array $names, string $billGeneration, string $lifecycleGeneration): array
|
||||
private function lifecycleSales(array $names): array
|
||||
{
|
||||
if ($names === [] || ! $this->hasTable('store_lifecycles') || ! $this->hasTable('bills')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$month = $this->monthExpression('b.occurred_at');
|
||||
foreach (array_chunk($names, 500) as $chunk) {
|
||||
foreach (array_chunk($names, 900) as $chunk) {
|
||||
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
|
||||
$rows = $this->connection->select(
|
||||
"SELECT l.id AS lifecycle_id, {$month} AS bill_month,
|
||||
"SELECT l.id AS lifecycle_id, substr(b.occurred_at, 1, 7) AS bill_month,
|
||||
SUM(COALESCE(b.income, 0)) AS income_total
|
||||
FROM store_report_lifecycle_rows AS l
|
||||
INNER JOIN store_report_bill_rows AS b
|
||||
ON b.generation = ? AND b.store_name = l.erp_store_name AND b.occurred_at IS NOT NULL
|
||||
AND b.occurred_at >= COALESCE(l.effective_at, '1000-01-01 00:00:00')
|
||||
AND b.occurred_at < COALESCE(l.expires_at, '2999-01-01 00:00:00')
|
||||
WHERE l.generation = ? AND l.erp_store_name IN ($placeholders)
|
||||
GROUP BY l.id, {$month}",
|
||||
[$billGeneration, $lifecycleGeneration, ...$chunk],
|
||||
FROM store_lifecycles AS l
|
||||
INNER JOIN bills AS b
|
||||
ON b.store_name = l.erp_store_name
|
||||
AND b.occurred_at IS NOT NULL AND b.occurred_at <> ''
|
||||
AND b.occurred_at >= COALESCE(NULLIF(l.effective_at, ''), ?)
|
||||
AND b.occurred_at < COALESCE(NULLIF(l.expires_at, ''), ?)
|
||||
WHERE l.erp_store_name IN ($placeholders)
|
||||
GROUP BY l.id, substr(b.occurred_at, 1, 7)",
|
||||
[self::DEFAULT_EFFECTIVE_AT, self::DEFAULT_EXPIRES_AT, ...$chunk],
|
||||
);
|
||||
$this->collectSales($result, $rows, 'lifecycle_id');
|
||||
}
|
||||
@ -167,19 +152,24 @@ class StoreReportRepository
|
||||
}
|
||||
|
||||
/** @return array<string,array{period:float,months:array<string,float>}> */
|
||||
private function fallbackSales(array $names, string $generation): array
|
||||
private function fallbackSales(array $names): array
|
||||
{
|
||||
if ($names === [] || ! $this->hasTable('bills')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$result = [];
|
||||
$month = $this->monthExpression('occurred_at');
|
||||
foreach (array_chunk($names, 500) as $chunk) {
|
||||
foreach (array_chunk($names, 900) as $chunk) {
|
||||
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
|
||||
$rows = $this->connection->select(
|
||||
"SELECT store_name, {$month} AS bill_month,
|
||||
"SELECT store_name, substr(occurred_at, 1, 7) AS bill_month,
|
||||
SUM(COALESCE(income, 0)) AS income_total
|
||||
FROM store_report_bill_rows
|
||||
WHERE generation = ? AND store_name IN ($placeholders) AND occurred_at IS NOT NULL
|
||||
GROUP BY store_name, {$month}",
|
||||
[$generation, ...$chunk],
|
||||
FROM bills
|
||||
WHERE store_name IN ($placeholders)
|
||||
AND occurred_at IS NOT NULL AND occurred_at <> ''
|
||||
AND occurred_at >= ? AND occurred_at < ?
|
||||
GROUP BY store_name, substr(occurred_at, 1, 7)",
|
||||
[...$chunk, self::DEFAULT_EFFECTIVE_AT, self::DEFAULT_EXPIRES_AT],
|
||||
);
|
||||
$this->collectSales($result, $rows, 'store_name');
|
||||
}
|
||||
@ -197,11 +187,13 @@ class StoreReportRepository
|
||||
}
|
||||
}
|
||||
|
||||
private function monthExpression(string $column): string
|
||||
/** SQLite Schema Builder 在只读/WAL 挂载下可能尝试写入,因此使用普通查询。 */
|
||||
private function hasTable(string $table): bool
|
||||
{
|
||||
return $this->connection->getDriverName() === 'sqlite'
|
||||
? "strftime('%Y-%m', {$column})"
|
||||
: "DATE_FORMAT({$column}, '%Y-%m')";
|
||||
return $this->connection->select(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",
|
||||
[$table],
|
||||
) !== [];
|
||||
}
|
||||
|
||||
private function date(mixed $value, string $fallback): string
|
||||
|
||||
@ -201,7 +201,7 @@ class ManagementCrudTest extends FeatureTestCase
|
||||
->assertSeeText('2999-01-01')
|
||||
->assertSeeText('25,916.80')
|
||||
->assertSeeText('关店中')
|
||||
->assertSeeText('共享镜像');
|
||||
->assertSeeText('已接入真实账单与生命周期');
|
||||
|
||||
preg_match_all('/<th(?:\s|>)/', $response->getContent(), $headers);
|
||||
$this->assertCount(26, $headers[0]);
|
||||
|
||||
@ -11,93 +11,119 @@ use Modules\EcommerceFinance\Repositories\BusinessInformationMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\InstallationDetailMirrorRepository;
|
||||
use Modules\EcommerceFinance\Repositories\StoreReportRepository;
|
||||
use Modules\EcommerceFinance\Services\UpstreamQueryCacheFactory;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
class StoreReportRepositoryTest extends TestCase
|
||||
{
|
||||
private string $databasePath;
|
||||
private StoreReportRepository $repository;
|
||||
|
||||
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();
|
||||
DB::connection('business_mirror')->table('store_report_import_states')->insert([
|
||||
['dataset_key' => StoreReportRepository::BILLS_DATASET, 'status' => 'succeeded', 'active_generation' => 'bills-v1'],
|
||||
['dataset_key' => StoreReportRepository::LIFECYCLES_DATASET, 'status' => 'succeeded', 'active_generation' => 'lifecycles-v1'],
|
||||
]);
|
||||
$this->databasePath = tempnam(sys_get_temp_dir(), 'store-report-');
|
||||
config(['database.connections.bills_sqlite' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => $this->databasePath,
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => false,
|
||||
]]);
|
||||
DB::purge('bills_sqlite');
|
||||
$schema = Schema::connection('bills_sqlite');
|
||||
$schema->create('store_lifecycles', function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('erp_store_name');
|
||||
$table->string('company_name')->nullable();
|
||||
$table->string('effective_at')->nullable();
|
||||
$table->string('expires_at')->nullable();
|
||||
});
|
||||
$schema->create('bills', function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('store_name');
|
||||
$table->string('occurred_at')->nullable();
|
||||
$table->decimal('income', 18, 2)->default(0);
|
||||
});
|
||||
$this->repository = new StoreReportRepository(app('db'));
|
||||
}
|
||||
|
||||
public function test_lifecycle_boundaries_split_monthly_income_without_double_counting(): void
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$db = DB::connection('business_mirror');
|
||||
$db->table('store_report_lifecycle_rows')->insert([
|
||||
$this->lifecycle(1, '店铺A', '主体甲', '2026-05-01', '2026-07-01'),
|
||||
$this->lifecycle(2, '店铺A', '主体乙', '2026-07-01', null),
|
||||
DB::purge('bills_sqlite');
|
||||
if (is_file($this->databasePath)) {
|
||||
unlink($this->databasePath);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_lifecycle_boundaries_split_monthly_and_period_income_without_double_counting(): void
|
||||
{
|
||||
$db = DB::connection('bills_sqlite');
|
||||
$db->table('store_lifecycles')->insert([
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体甲', 'effective_at' => '2026-05-01', 'expires_at' => '2026-07-01'],
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体乙', 'effective_at' => '2026-07-01', 'expires_at' => null],
|
||||
]);
|
||||
$db->table('store_report_bill_rows')->insert([
|
||||
$this->bill(1, '店铺A', '2026-04-30 23:59:59', 9),
|
||||
$this->bill(2, '店铺A', '2026-05-01 00:00:00', 100),
|
||||
$this->bill(3, '店铺A', '2026-06-30 23:59:59', 60),
|
||||
$this->bill(4, '店铺A', '2026-07-01 00:00:00', 70),
|
||||
$this->bill(5, '店铺A', '2026-08-01 00:00:00', 80),
|
||||
$this->bill(6, '店铺A', '2027-01-01 00:00:00', 5),
|
||||
$db->table('bills')->insert([
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-04-30 23:59:59', 'income' => 9],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-05-01 00:00:00', 'income' => 100],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-06-30 23:59:59', 'income' => 60],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-07-01 00:00:00', 'income' => 70],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-08-01 00:00:00', 'income' => 80],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2027-01-01 00:00:00', 'income' => 5],
|
||||
]);
|
||||
|
||||
$rows = $this->repository->rows([
|
||||
['erp_store_name' => '店铺A', 'store_id' => 'STORE-001', 'company_name' => '旧主体', 'store_status' => '3'],
|
||||
], 2026);
|
||||
['erp_store_name' => '店铺A', 'company_name' => '旧主体', 'store_status' => '3'],
|
||||
]);
|
||||
|
||||
$this->assertCount(2, $rows);
|
||||
$this->assertSame(['主体甲', '主体乙'], array_column($rows, 'entity'));
|
||||
$this->assertSame('STORE-001', $rows[0]['store_id']);
|
||||
$this->assertSame(['2026-05-01', '2026-07-01'], array_column($rows, 'effective_at'));
|
||||
$this->assertSame(['2026-07-01', '2999-01-01'], array_column($rows, 'invalid_at'));
|
||||
$this->assertSame([160.0, 155.0], array_column($rows, 'period_sales'));
|
||||
$this->assertSame([100.0, 0.0], array_column($rows, 'sales_05'));
|
||||
$this->assertSame([0.0, 70.0], array_column($rows, 'sales_07'));
|
||||
$this->assertSame(['关店中', '关店中'], array_column($rows, 'status'));
|
||||
}
|
||||
|
||||
public function test_failed_refresh_keeps_the_previous_active_generation_readable(): void
|
||||
public function test_missing_lifecycle_uses_upstream_company_and_default_period(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('store_report_import_states')
|
||||
->where('dataset_key', StoreReportRepository::BILLS_DATASET)
|
||||
->update(['status' => 'failed', 'pending_generation' => null]);
|
||||
DB::connection('business_mirror')->table('store_report_bill_rows')->insert(
|
||||
$this->bill(1, '店铺A', '2026-05-03 12:00:00', 25.5),
|
||||
);
|
||||
DB::connection('bills_sqlite')->table('bills')->insert([
|
||||
['store_name' => '无生命周期店铺', 'occurred_at' => '2026-05-03 12:00:00', 'income' => 25.5],
|
||||
]);
|
||||
|
||||
$rows = $this->repository->rows([
|
||||
['erp_store_name' => '店铺A', 'company_name' => '公司表主体', 'opened_at' => '2026-05-01'],
|
||||
], 2026);
|
||||
['erp_store_name' => '无生命周期店铺', 'company_name' => '公司表主体', 'store_status' => '0'],
|
||||
]);
|
||||
|
||||
$this->assertSame(25.5, $rows[0]['period_sales']);
|
||||
$this->assertSame(25.5, $rows[0]['sales_05']);
|
||||
$this->assertSame('公司表主体', $rows[0]['entity']);
|
||||
$this->assertSame('2026-05-01', $rows[0]['effective_at']);
|
||||
$this->assertSame('2999-01-01', $rows[0]['invalid_at']);
|
||||
$this->assertSame(25.5, $rows[0]['period_sales']);
|
||||
$this->assertSame('开店中', $rows[0]['status']);
|
||||
}
|
||||
|
||||
public function test_missing_first_import_is_reported_instead_of_returning_misleading_zeroes(): void
|
||||
public function test_shop_state_mapping_keeps_opening_closing_and_closed_labels(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('store_report_import_states')
|
||||
->where('dataset_key', StoreReportRepository::BILLS_DATASET)->delete();
|
||||
$rows = $this->repository->rows([
|
||||
['erp_store_name' => '开店中店铺', 'store_status' => '0'],
|
||||
['erp_store_name' => '关店中店铺', 'store_status' => '3'],
|
||||
['erp_store_name' => '已关店店铺', 'store_status' => '6'],
|
||||
]);
|
||||
|
||||
$this->expectException(RuntimeException::class);
|
||||
$this->expectExceptionMessage('尚未完成首次导入');
|
||||
$this->repository->rows([['erp_store_name' => '店铺A']], 2026);
|
||||
$this->assertSame(['开店中', '关店中', '关店'], array_column($rows, 'status'));
|
||||
}
|
||||
|
||||
public function test_upstream_business_information_exposes_shared_store_report_rows(): void
|
||||
public function test_upstream_business_information_exposes_expanded_rows_for_store_report(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('store_report_lifecycle_rows')->insert([
|
||||
$this->lifecycle(1, '店铺A', '主体甲', '2026-05-01', null),
|
||||
DB::connection('bills_sqlite')->table('store_lifecycles')->insert([
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体甲', 'effective_at' => '2026-05-01', 'expires_at' => '2026-07-01'],
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体乙', 'effective_at' => '2026-07-01', 'expires_at' => null],
|
||||
]);
|
||||
DB::connection('business_mirror')->table('store_report_bill_rows')->insert([
|
||||
$this->bill(1, '店铺A', '2026-06-30 23:59:59', 60),
|
||||
DB::connection('bills_sqlite')->table('bills')->insert([
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-06-30 23:59:59', 'income' => 60],
|
||||
['store_name' => '店铺A', 'occurred_at' => '2026-07-01 00:00:00', 'income' => 70],
|
||||
]);
|
||||
|
||||
$mirror = Mockery::mock(BusinessInformationMirrorRepository::class);
|
||||
$mirror->shouldReceive('ready')->with('store-information.read')->andReturnTrue();
|
||||
$mirror->shouldReceive('allStores')->once()->andReturn([[
|
||||
@ -112,47 +138,8 @@ class StoreReportRepositoryTest extends TestCase
|
||||
|
||||
$paginator = $service->paginate('store-management', 'store-report', 50);
|
||||
|
||||
$this->assertSame(1, $paginator->total());
|
||||
$this->assertSame('主体甲', $paginator->items()[0]->entity);
|
||||
$this->assertSame(60.0, $paginator->items()[0]->period_sales);
|
||||
}
|
||||
|
||||
private function createTables(): void
|
||||
{
|
||||
$schema = Schema::connection('business_mirror');
|
||||
$schema->create('store_report_import_states', function (Blueprint $table): void {
|
||||
$table->string('dataset_key')->primary();
|
||||
$table->string('status');
|
||||
$table->string('active_generation')->nullable();
|
||||
$table->string('pending_generation')->nullable();
|
||||
});
|
||||
$schema->create('store_report_bill_rows', function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('generation');
|
||||
$table->string('store_name');
|
||||
$table->dateTime('occurred_at')->nullable();
|
||||
$table->decimal('income', 20, 4)->default(0);
|
||||
});
|
||||
$schema->create('store_report_lifecycle_rows', function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('generation');
|
||||
$table->string('erp_store_name');
|
||||
$table->string('company_name')->nullable();
|
||||
$table->dateTime('effective_at')->nullable();
|
||||
$table->dateTime('expires_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
private function bill(int $id, string $store, string $time, float $income): array
|
||||
{
|
||||
return ['id' => $id, 'generation' => 'bills-v1', 'store_name' => $store, 'occurred_at' => $time, 'income' => $income];
|
||||
}
|
||||
|
||||
private function lifecycle(int $id, string $store, string $company, ?string $from, ?string $to): array
|
||||
{
|
||||
return [
|
||||
'id' => $id, 'generation' => 'lifecycles-v1', 'erp_store_name' => $store,
|
||||
'company_name' => $company, 'effective_at' => $from, 'expires_at' => $to,
|
||||
];
|
||||
$this->assertSame(2, $paginator->total());
|
||||
$this->assertSame(['主体甲', '主体乙'], array_map(static fn (object $row): string => $row->entity, $paginator->items()));
|
||||
$this->assertSame([60.0, 70.0], array_map(static fn (object $row): float => $row->period_sales, $paginator->items()));
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user