> $payloads
+ */
+ private function resolveProductNames(array &$payloads): void
+ {
+ $ids = [];
+ foreach ($payloads as $payload) {
+ $id = trim((string) ($payload['product_id'] ?? ''));
+ if ($id !== '' && ! isset($ids[$id])) {
+ $ids[$id] = true;
+ }
+ }
+ if ($ids === []) {
+ return;
+ }
+ $idList = array_keys($ids);
+
+ $names = [];
+ if ($this->connection->getSchemaBuilder()->hasTable('ops_jst_sku_map')) {
+ $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku_map')
+ ->whereIn('shop_i_id', $idList)
+ ->select(['shop_i_id', 'sku_id', 'i_id', 'name'])
+ ->limit(5000)
+ ->get());
+ foreach ($rows as $row) {
+ $id = (string) $row->shop_i_id;
+ if (! isset($names[$id])) {
+ $name = $this->cleanProductName($row->name ?? null);
+ if ($name !== null) {
+ $names[$id] = $name;
+ }
+ }
+ }
+ }
+
+ $missing = array_values(array_filter($idList, static fn (string $id): bool => ! isset($names[$id])));
+ if ($missing !== [] && $this->connection->getSchemaBuilder()->hasTable('ops_jst_sku')) {
+ $rows = $this->guardedQuery(4000, fn () => $this->connection->table('ops_jst_sku')
+ ->whereIn('i_id', $missing)
+ ->orWhereIn('sku_id', $missing)
+ ->select(['i_id', 'sku_id', 'name'])
+ ->limit(5000)
+ ->get());
+ foreach ($rows as $row) {
+ foreach ([(string) $row->i_id, (string) $row->sku_id] as $candidate) {
+ if ($candidate !== '' && isset($names[$candidate]) === false) {
+ $name = $this->cleanProductName($row->name ?? null);
+ if ($name !== null) {
+ $names[$candidate] = $name;
+ }
+ }
+ }
+ }
+ }
+
+ foreach ($payloads as &$payload) {
+ $id = trim((string) ($payload['product_id'] ?? ''));
+ $payload['product_name'] = $id !== '' && isset($names[$id]) ? $names[$id] : null;
+ }
+ unset($payload);
+ }
+
+ private function cleanProductName(mixed $value): ?string
+ {
+ if ($value === null) {
+ return null;
+ }
+ $name = trim((string) $value);
+ return $name === '' ? null : $name;
+ }
+
+ /**
+ * 对可能命中大表的查询加会话级超时,避免索引缺失时整批同步被拖垮。
+ * 超时后该批商品名称留空,页面仍可正常展示(仅缺失匹配名),不影响同步完成。
+ *
+ * @template T
+ * @param callable():T $callback
+ * @return T
+ */
+ private function guardedQuery(int $milliseconds, callable $callback)
+ {
+ $conn = $this->connection;
+ try {
+ $conn->statement('SET SESSION MAX_EXECUTION_TIME=' . $milliseconds);
+ return $callback();
+ } catch (Throwable $exception) {
+ // 超时(SQLSTATE HY000/3024)或其它只读异常:放弃匹配该批商品名称,
+ // 不让同步链路中断。
+ return [];
+ } finally {
+ try {
+ $conn->statement('SET SESSION MAX_EXECUTION_TIME=0');
+ } catch (Throwable) {
+ // 忽略重置失败。
+ }
+ }
+ }
}
diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue
index 09823b67..6b5d9c6a 100644
--- a/resources/assets/js/components/business/TaobaoAlipayBills.vue
+++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue
@@ -13,9 +13,9 @@
按当前筛选
-
期末余额(最新)
+
收支净额
{{ money(summary.balance) }}
-
最新一条记录
+
收入合计 - 支出合计
-
-
+
+
-
+
-
+
@@ -65,12 +54,13 @@
-
-
+
+
+
@@ -97,17 +87,17 @@
原始店铺 |
自定义备注 |
账单项目 |
- 支付宝账号 |
+ 平台渠道 |
账务订单号 |
业务流水号 |
商户订单号 |
业务基础订单号 |
- 商品名称 |
+ 商品编码 |
对方账号 |
发生时间 ⇅ |
收入 ⇅ |
支出 ⇅ |
- 余额 ⇅ |
+ 收支净额 ⇅ |
业务类型 |
备注 |
线上单号 |
@@ -188,6 +178,7 @@ export default {
props: {
apiBase: { type: String, required: true },
+ exportBase: { type: String, required: true },
},
data() {
@@ -283,6 +274,11 @@ export default {
this.fetch();
},
+ exportRows() {
+ const params = new URLSearchParams(this.filters);
+ window.location.href = `${this.exportBase}?${params.toString()}`;
+ },
+
toggleSort(key) {
if (this.sort.key === key) {
this.sort.dir = this.sort.dir === 'asc' ? 'desc' : 'asc';
diff --git a/resources/assets/js/views/business/pages.js b/resources/assets/js/views/business/pages.js
index 3ca5bc28..ddd4f876 100644
--- a/resources/assets/js/views/business/pages.js
+++ b/resources/assets/js/views/business/pages.js
@@ -4,7 +4,7 @@
* 路由:/{company_id}/workspace/{section}/{page}/{tab}
*
* 店铺收款账户账单(store-receiving-bills)下各 tab:
- * - taobao-alipay → 独立实现 TaobaoAlipayBills(表 ec_alipay_bills)
+ * - taobao-alipay → 独立实现 TaobaoAlipayBills(经营分析副本共享镜像)
* - taobao-wechat / pinduoduo / jd-wallet / jd-transactions / douyin / dewu
* → 通用实现 AccountBills(表 ec_account_bills,按 bill_type 区分,列配置由后端下发)
*/
@@ -43,7 +43,10 @@ function resolveComponent(context) {
: `/ecommerce-finance/account-bills/type/${encodeURIComponent(context.tab)}`;
// 店铺收款账户账单 › 淘系支付宝账户(独立实现)
if (context.page === 'store-receiving-bills' && context.tab === 'taobao-alipay') {
- return { Component: TaobaoAlipayBills, props: { apiBase: alipayBase } };
+ const exportBase = context.companyId
+ ? `/${context.companyId}/ecommerce-finance/alipay-bills/export`
+ : '/ecommerce-finance/alipay-bills/export';
+ return { Component: TaobaoAlipayBills, props: { apiBase: alipayBase, exportBase } };
}
// 店铺收款账户账单 › 其它账户类型(通用实现)
diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php
index bce18cb2..b84f83a6 100644
--- a/resources/views/business/pages/partials/directory-table.blade.php
+++ b/resources/views/business/pages/partials/directory-table.blade.php
@@ -494,11 +494,17 @@
@endphp
@if (($page['slug'] ?? '') === 'store-accounts' && $field['name'] === 'password_configured')
- {{ filled($display) ? $display : '—' }}
- @if (\App\Utilities\SystemAccess::canOpenSettings() && $value !== false)
-
-
-
+ {{ filled($display) ? $display : '—' }}
+ @if ($value === false)
+ 未设置
+ @else
+
+ 读取中…
+
@endif
@else
@@ -554,7 +560,7 @@
@endif
-@if (($page['slug'] ?? '') === 'store-accounts' && \App\Utilities\SystemAccess::canOpenSettings())
+@if (($page['slug'] ?? '') === 'store-accounts')
@include('business.pages.partials.store-account-password')
@endif
diff --git a/resources/views/business/pages/partials/store-account-password.blade.php b/resources/views/business/pages/partials/store-account-password.blade.php
index 94d427dc..79f6c0c5 100644
--- a/resources/views/business/pages/partials/store-account-password.blade.php
+++ b/resources/views/business/pages/partials/store-account-password.blade.php
@@ -1,95 +1,169 @@
@once
-
-
+
+ 正在读取当前页密码…
+
+
@endonce
diff --git a/resources/views/business/pages/product-inventory/online-daifa-price.blade.php b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php
new file mode 100644
index 00000000..d7abafdc
--- /dev/null
+++ b/resources/views/business/pages/product-inventory/online-daifa-price.blade.php
@@ -0,0 +1,157 @@
+@php
+ $rows = $onlineDaifaRows ?? null;
+ $filters = $onlineDaifaFilters ?? [];
+ $status = (string) ($onlineDaifaStatus ?? 'unknown');
+ $syncedAt = $onlineDaifaSyncedAt ?? null;
+ $summary = $onlineDaifaSummary ?? [];
+ $error = $onlineDaifaError ?? null;
+ $json = static fn (mixed $value): string => is_array($value)
+ ? (json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) ?: '-')
+ : (string) ($value ?? '-');
+ $statusOptions = \Modules\EcommerceFinance\Services\DingPayableWorkflowStatus::filterOptions();
+ $num = static fn (mixed $value): string => $value === null || $value === '' ? '-' : (string) $value;
+ $money = static fn (mixed $value): string => $value === null ? '-' : number_format((float) $value, 2);
+ $productName = static fn (array $row): string => $row['matched_product']['matched'] ?? false
+ ? (string) ($row['matched_product']['name'] ?? '-')
+ : '(未匹配)';
+ $payeeScope = trim((string) config('upstream_mirrors.ding_online_daifa_price.row_filters.payee_name', ''));
+@endphp
+
+
+
+
+
+
+ @if ($error)
+ {{ $error }}
+ @endif
+
+
+ 固定流程:线上代发业务报销流程(钉钉 OA 审批)
+ @if ($payeeScope !== '') 固定收款人:{{ $payeeScope }} @endif
+ 镜像状态:{{ $status }}
+ @if ($syncedAt) 最近同步:{{ $syncedAt }} @endif
+ 共 {{ $rows?->total() ?? 0 }} 条
+
+
+
+ 代发订单金额合计{{ $money($summary['daifa_amount'] ?? null) }}
+ 订单实付金额合计{{ $money($summary['paid_amount'] ?? null) }}
+ 差价合计{{ $money($summary['price_diff'] ?? null) }}
+ 已匹配商品目录{{ (int) ($summary['matched_count'] ?? 0) }} / {{ (int) ($summary['count'] ?? 0) }}
+
+
+
+
+
+ | 审批编号 | 标题 | 状态 | 申请人 | 收款人全称 |
+ 商品ID | 商品名称(匹配) | 店铺名称 |
+ 代发交易单号 | 店铺交易单号 |
+ 发货数量 | 订单实付金额 | 代发订单金额 | 差价 |
+ 供应商名称 | 料号 | 创建时间 | 原始表单 |
+
+
+ @forelse ($rows ?? [] as $row)
+ @php($workflow = $row['workflow'] ?? [])
+ @php($approvalNumber = trim((string) ($workflow['businessId'] ?? '')) ?: (string) ($row['process_instance_id'] ?? '-'))
+ @php($originator = trim((string) ($workflow['originatorUserName'] ?? '')) ?: trim((string) ($workflow['originatorUserId'] ?? '-')))
+
+ | {{ $approvalNumber }} |
+ {{ $workflow['title'] ?? '-' }} |
+ {{ $row['status_label'] ?? '-' }} |
+ {{ $originator }} |
+ {{ $num($row['payee_name']) }} |
+ {{ $num($row['product_id']) }} |
+ {{ $productName($row) }} |
+ {{ $num($row['shop_name']) }} |
+ {{ $num($row['daifa_trade_no']) }} |
+ {{ $num($row['shop_trade_no']) }} |
+ {{ $num($row['ship_qty']) }} |
+ {{ $money($row['paid_amount']) }} |
+ {{ $money($row['daifa_amount']) }} |
+ {{ $money($row['price_diff']) }} |
+ {{ $num($row['supplier_name']) }} |
+ {{ $num($row['material_no']) }} |
+ {{ $row['workflow_created_at'] ?? '-' }} |
+ 展开表单({{ count($row['scheme'] ?? []) }} 项){{ $json($row['scheme'] ?? []) }} |
+
+ @empty
+ {{ $error ? '镜像读取失败,请稍后重试。' : '暂无符合条件的线上代发价格数据;同步完成后会自动显示。' }} |
+ @endforelse
+
+
+
+
+
diff --git a/routes/admin.php b/routes/admin.php
index 4f46bcc7..0f044fba 100644
--- a/routes/admin.php
+++ b/routes/admin.php
@@ -11,11 +11,15 @@ use Modules\EcommerceFinance\Http\Controllers\AlipayBills;
use Modules\EcommerceFinance\Http\Controllers\Api\GoodsReconciliations;
use Modules\EcommerceFinance\Http\Controllers\Api\SupplierPayables;
+Route::post('store-account-passwords/visible-page/reveal', 'Business\StoreAccountPasswords@revealVisiblePage')
+ ->name('business.store-account-passwords.reveal-visible-page');
Route::post('store-account-passwords/{account}/reveal', 'Business\StoreAccountPasswords@reveal')
->name('business.store-account-passwords.reveal');
Route::get('ecommerce-finance/alipay-bills', [AlipayBills::class, 'index'])
->name('ecommerce-finance.alipay-bills.index');
+Route::get('ecommerce-finance/alipay-bills/export', [AlipayBills::class, 'export'])
+ ->name('ecommerce-finance.alipay-bills.export');
Route::get('ecommerce-finance/alipay-bills/{bill}', [AlipayBills::class, 'show'])
->name('ecommerce-finance.alipay-bills.show');
diff --git a/tests/Feature/Auth/DingTalkLoginTest.php b/tests/Feature/Auth/DingTalkLoginTest.php
index f3657056..de9acffc 100644
--- a/tests/Feature/Auth/DingTalkLoginTest.php
+++ b/tests/Feature/Auth/DingTalkLoginTest.php
@@ -131,6 +131,27 @@ class DingTalkLoginTest extends FeatureTestCase
$this->get(route('dashboard', ['company_id' => $this->company->id]))->assertRedirectContains('/workspace/');
}
+ public function test_explicitly_designated_identity_gets_highest_role_only_on_first_provisioning(): void
+ {
+ config(['dingtalk.super_admin_user_ids' => ['ding-user-1']]);
+ Http::preventStrayRequests();
+ Http::fake($this->dingtalkResponses('union-designated', 'open-designated'));
+ $state = $this->startAuthorization();
+ $this->get(route('login.dingtalk.callback', ['code' => 'fixture', 'state' => $state]));
+ $created = auth()->user();
+ $this->assertNotNull($created);
+ $this->assertTrue(\App\Utilities\SystemAccess::isSuperAdmin($created));
+ $id = $created->id;
+ $created->syncRoles([\App\Models\Auth\Role::where('name', 'user')->firstOrFail()->id]);
+ $created->flushCache();
+ auth()->logout();
+ session()->invalidate();
+ $state = $this->startAuthorization();
+ $this->get(route('login.dingtalk.callback', ['code' => 'fixture-again', 'state' => $state]));
+ $this->assertSame($id, auth()->id());
+ $this->assertFalse(\App\Utilities\SystemAccess::isSuperAdmin(auth()->user()));
+ }
+
public function test_shared_mobile_does_not_claim_an_existing_account(): void
{
Http::preventStrayRequests();
diff --git a/tests/Feature/Business/OnlineDaifaPricePageTest.php b/tests/Feature/Business/OnlineDaifaPricePageTest.php
new file mode 100644
index 00000000..ff5e0979
--- /dev/null
+++ b/tests/Feature/Business/OnlineDaifaPricePageTest.php
@@ -0,0 +1,131 @@
+user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
+ $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class);
+ $repository->shouldReceive('paginate')->once()->andReturn([
+ 'data' => [[
+ 'process_instance_id' => 'DEMO-6927049845766979458',
+ 'detail_index' => 0,
+ 'product_id' => '3821829253650055444',
+ 'daifa_trade_no' => '6927049845766979458',
+ 'shop_trade_no' => '6927049845766979458',
+ 'shop_name' => '抖音-HX旗舰店101',
+ 'payee_name' => '宁波顾家望业家居有限公司',
+ 'supplier_name' => '',
+ 'material_no' => '',
+ 'ship_qty' => 1,
+ 'paid_amount' => 616.61,
+ 'daifa_amount' => 375.0,
+ 'price_diff' => 241.61,
+ 'workflow' => [
+ 'businessId' => '20260901001',
+ 'title' => '线上代发业务报销',
+ 'status' => 'COMPLETED',
+ 'result' => 'agree',
+ 'originatorUserName' => '扬灵',
+ 'createAt' => '2026-09-01 10:00:00',
+ ],
+ 'scheme' => [['name' => '商品ID', 'value' => '3821829253650055444']],
+ 'tasks' => [],
+ 'status_key' => 'COMPLETED',
+ 'status_label' => '已完成',
+ 'matched_product' => ['matched' => true, 'name' => '演示商品', 'sku_id' => null, 'i_id' => null],
+ 'workflow_created_at' => '2026-09-01 10:00:00',
+ ]],
+ 'total' => 1,
+ 'status' => 'succeeded',
+ 'last_synced_at' => '2026-09-08 00:00:05',
+ 'summary' => [
+ 'count' => 1,
+ 'matched_count' => 1,
+ 'daifa_amount' => 375.0,
+ 'paid_amount' => 616.61,
+ 'price_diff' => 241.61,
+ ],
+ ]);
+ $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository);
+
+ $this->loginAs()->get(route('business.pages.show', [
+ 'section' => 'product-inventory',
+ 'page' => 'online-daifa-price',
+ ]))->assertOk()
+ ->assertSee('线上代发价格')
+ ->assertSee('固定流程:线上代发业务报销流程(钉钉 OA 审批)')
+ ->assertSee('固定收款人:')
+ ->assertSee('宁波顾家望业家居有限公司')
+ ->assertSee('镜像状态:succeeded')
+ ->assertSee('3821829253650055444')
+ ->assertSee('演示商品')
+ ->assertSee('抖音-HX旗舰店101')
+ ->assertSee('6927049845766979458')
+ ->assertSee('已完成')
+ ->assertSee('扬灵')
+ ->assertSee('已匹配商品目录')
+ ->assertSee('展开表单(1 项)');
+ }
+
+ public function test_online_daifa_price_page_keeps_an_unavailable_mirror_readable(): void
+ {
+ $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
+ $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class);
+ $repository->shouldReceive('paginate')->andThrow(new \RuntimeException('not ready'));
+ $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository);
+
+ $this->loginAs()->get(route('business.pages.show', [
+ 'section' => 'product-inventory',
+ 'page' => 'online-daifa-price',
+ ]))->assertOk()
+ ->assertSee('线上代发价格镜像尚未完成同步,请稍后重试。')
+ ->assertSee('镜像读取失败,请稍后重试。');
+ }
+
+ public function test_online_daifa_price_page_passes_filters_to_repository(): void
+ {
+ $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
+ $repository = Mockery::mock(DingOnlineDaifaPriceMirrorRepository::class);
+ $repository->shouldReceive('paginate')->once()->with(
+ [
+ 'keyword' => '6927049845766979458',
+ 'product_id' => '3821829253650055444',
+ 'shop_name' => '抖音-HX旗舰店101',
+ 'status' => '',
+ 'created_from' => '2026-09-01',
+ 'created_to' => '2026-09-07',
+ ],
+ 1,
+ Mockery::type('int'),
+ )->andReturn([
+ 'data' => [],
+ 'total' => 0,
+ 'status' => 'succeeded',
+ 'last_synced_at' => '2026-09-08 00:00:05',
+ 'summary' => [],
+ ]);
+ $this->app->instance(DingOnlineDaifaPriceMirrorRepository::class, $repository);
+
+ $this->loginAs()->get(route('business.pages.show', [
+ 'section' => 'product-inventory',
+ 'page' => 'online-daifa-price',
+ 'keyword' => '6927049845766979458',
+ 'product_id' => '3821829253650055444',
+ 'shop_name' => '抖音-HX旗舰店101',
+ 'created_from' => '2026-09-01',
+ 'created_to' => '2026-09-07',
+ ]))->assertOk()
+ ->assertSee('商品ID')
+ ->assertSee('店铺名称')
+ ->assertSee('2026-09-01')
+ ->assertSee('2026-09-07');
+ }
+}
diff --git a/tests/Feature/Business/PagesTest.php b/tests/Feature/Business/PagesTest.php
index 26b1f90c..d8d037ca 100644
--- a/tests/Feature/Business/PagesTest.php
+++ b/tests/Feature/Business/PagesTest.php
@@ -117,6 +117,37 @@ class PagesTest extends FeatureTestCase
->assertSee('public/js/business/pages.min.js', false);
}
+ public function testTaobaoAlipayBillsExportUsesTheMirrorRepository()
+ {
+ $this->user->attachPermission(
+ Permission::where('name', 'read-admin-panel')->firstOrFail()
+ );
+
+ $repository = Mockery::mock(StoreReceivingAlipayBillMirrorRepository::class);
+ $repository->shouldReceive('exportRows')->once()->with(Mockery::on(
+ static fn (array $filters): bool => ($filters['store_name'] ?? '') === '天猫-经营店'
+ && ($filters['start'] ?? '') === '2026-08-01'
+ && ($filters['end'] ?? '') === '2026-08-31'
+ ))->andReturn([[
+ 'record_code' => '1', 'store_name' => '天猫-经营店', 'alipay_account' => 'CommonBillTGCPay',
+ 'bill_item' => '交易佣金', 'account_order_no' => 'KEY-1', 'business_serial_no' => '1001',
+ 'merchant_order_no' => 'P-1', 'business_base_order_no' => 'ORDER-1', 'goods_name' => 'SKU-1',
+ 'occurred_at' => '2026-08-01 09:00:00', 'income' => 100.25, 'expense' => 0,
+ 'balance' => 100.25, 'business_type' => '收入', 'online_order_no' => 'ORDER-1',
+ 'business_description' => 'double', 'business_bill_source' => 'CommonBillTGCPay',
+ 'created_at' => '2026-08-02 09:00:00', 'updated_at' => '2026-08-02 10:00:00',
+ ]]);
+ $this->app->instance(StoreReceivingAlipayBillMirrorRepository::class, $repository);
+
+ $this->loginAs()
+ ->get(route('ecommerce-finance.alipay-bills.export', [
+ 'store_name' => '天猫-经营店', 'start' => '2026-08-01', 'end' => '2026-08-31',
+ ]))
+ ->assertOk()
+ ->assertHeader('content-type', 'text/csv; charset=UTF-8')
+ ->assertDownload('taobao_alipay_bills.csv');
+ }
+
public function testSupplierPayablesPageRendersItsSpecificContent()
{
$this->user->attachPermission(
diff --git a/tests/Feature/Business/StoreAccountPasswordsTest.php b/tests/Feature/Business/StoreAccountPasswordsTest.php
index 949b1806..ca97b2fd 100644
--- a/tests/Feature/Business/StoreAccountPasswordsTest.php
+++ b/tests/Feature/Business/StoreAccountPasswordsTest.php
@@ -23,8 +23,14 @@ class StoreAccountPasswordsTest extends FeatureTestCase
protected function setUp(): void
{
parent::setUp();
- config(['store_account_password.token' => str_repeat('t', 43), 'store_account_password.url' => 'https://upstream.example.test/internal/store-accounts/{id}/password/reveal']);
- $this->mock(StoreAccountMirrorRepository::class)->shouldReceive('containsAccount')->with('fixture-account')->andReturnTrue()->byDefault();
+ config([
+ 'store_account_password.token' => str_repeat('t', 43),
+ 'store_account_password.url' => 'https://upstream.example.test/internal/store-accounts/{id}/password/reveal',
+ 'store_account_password.visible_page_url' => 'https://upstream.example.test/internal/store-accounts/visible-page/password/reveal',
+ ]);
+ $mirror = $this->mock(StoreAccountMirrorRepository::class);
+ $mirror->shouldReceive('containsAccount')->with('fixture-account')->andReturnTrue()->byDefault();
+ $mirror->shouldReceive('containsAccounts')->andReturnTrue()->byDefault();
}
private function transport(int $status = 200, ?array $body = null, array $headers = ['Cache-Control' => 'no-store']): void
@@ -41,6 +47,21 @@ class StoreAccountPasswordsTest extends FeatureTestCase
return route('business.store-account-passwords.reveal', ['account' => 'fixture-account']);
}
+ private function visiblePageEndpoint(): string
+ {
+ return route('business.store-account-passwords.reveal-visible-page');
+ }
+
+ private function visiblePageTransport(array $items, array $headers = ['Cache-Control' => 'private, no-store']): void
+ {
+ $handler = HandlerStack::create(new MockHandler([new Response(200, $headers, json_encode([
+ 'requestId' => '12345678-1234-4123-8123-123456789012',
+ 'items' => $items,
+ ]))]));
+ $handler->push(Middleware::history($this->history));
+ $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler])));
+ }
+
public function test_admin_view_uses_trusted_actor_and_persists_password_free_audit(): void
{
$this->transport();
@@ -67,12 +88,13 @@ class StoreAccountPasswordsTest extends FeatureTestCase
$this->assertDatabaseHas('store_account_password_audits', ['purpose' => 'copy', 'status' => 200]);
}
- public function test_regular_user_cannot_call_upstream(): void
+ public function test_regular_user_with_store_accounts_page_can_reveal_and_copy(): void
{
$this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
$this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
- $this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('reveal');
- $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden();
+ $this->transport();
+ $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'copy'])->assertOk()->assertJsonPath('password', $this->fixture);
+ $this->assertDatabaseHas('store_account_password_audits', ['purpose' => 'copy', 'status' => 200]);
}
public function test_restricted_admin_cannot_bypass_store_page_scope(): void
@@ -83,6 +105,134 @@ class StoreAccountPasswordsTest extends FeatureTestCase
$this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden();
}
+ public function test_regular_user_without_store_accounts_page_cannot_call_upstream(): void
+ {
+ $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
+ $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
+ setting()->set('system.sidebar_permissions', [
+ 'configured' => ['user_'.$this->user->id],
+ 'subjects' => ['user_'.$this->user->id => ['store-management/basic-information']],
+ ]);
+ $client = $this->mock(StoreAccountPasswordClient::class);
+ $client->shouldNotReceive('reveal');
+ $client->shouldNotReceive('revealVisiblePage');
+ $this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertForbidden();
+ $this->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account']])->assertForbidden();
+ }
+
+ public function test_visible_page_loads_passwords_for_regular_user_and_audits_every_account(): void
+ {
+ $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
+ $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
+ $this->visiblePageTransport([
+ ['accountId' => 'fixture-account', 'status' => 200, 'requestId' => '12345678-1234-4123-8123-123456789013', 'password' => $this->fixture],
+ ['accountId' => 'fixture-empty', 'status' => 404, 'requestId' => '12345678-1234-4123-8123-123456789014'],
+ ]);
+
+ $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), [
+ 'accounts' => ['fixture-account', 'fixture-empty'],
+ ])->assertOk()->assertJsonCount(2, 'items')
+ ->assertJsonPath('items.0.password', $this->fixture)
+ ->assertJsonPath('items.1.status', 404)
+ ->assertJsonMissingPath('items.1.password');
+
+ $this->assertStringContainsString('no-store', $response->headers->get('Cache-Control'));
+ $this->assertSame(2, DB::table('store_account_password_audits')->count());
+ $this->assertEqualsCanonicalizing([200, 404], DB::table('store_account_password_audits')->pluck('status')->all());
+ $this->assertStringNotContainsString($this->fixture, json_encode(DB::table('store_account_password_audits')->get()));
+ $sent = json_decode((string) $this->history[0]['request']->getBody(), true);
+ $this->assertSame([
+ 'requesterId' => 'finance-user-'.$this->user->id,
+ 'purpose' => 'view',
+ 'accountIds' => ['fixture-account', 'fixture-empty'],
+ ], $sent);
+ }
+
+ public function test_fifty_visible_accounts_are_sent_as_two_gateway_safe_chunks(): void
+ {
+ $accountIds = array_map(fn ($index) => sprintf('fixture-account-%02d', $index), range(1, 50));
+ $responses = [];
+ foreach (array_chunk($accountIds, 25) as $batchIndex => $batch) {
+ $items = [];
+ foreach ($batch as $index => $accountId) {
+ $items[] = [
+ 'accountId' => $accountId,
+ 'status' => 200,
+ 'requestId' => sprintf('12345678-1234-4123-8123-%012d', ($batchIndex * 25) + $index + 1),
+ 'password' => $this->fixture,
+ ];
+ }
+ $responses[] = new Response(200, ['Cache-Control' => 'private, no-store'], json_encode([
+ 'requestId' => sprintf('22345678-1234-4123-8123-%012d', $batchIndex + 1),
+ 'items' => $items,
+ ]));
+ }
+ $handler = HandlerStack::create(new MockHandler($responses));
+ $handler->push(Middleware::history($this->history));
+ $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler])));
+
+ $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => $accountIds])
+ ->assertOk()->assertJsonCount(50, 'items');
+
+ $this->assertCount(2, $this->history);
+ foreach ($this->history as $index => $transaction) {
+ $body = (string) $transaction['request']->getBody();
+ $sent = json_decode($body, true);
+ $this->assertSame(array_slice($accountIds, $index * 25, 25), $sent['accountIds']);
+ $this->assertLessThanOrEqual(1024, strlen($body));
+ }
+ $this->assertSame(50, DB::table('store_account_password_audits')->count());
+ $this->assertSame(50, DB::table('store_account_password_audits')->where('status', 200)->count());
+ $this->assertStringNotContainsString($this->fixture, json_encode(DB::table('store_account_password_audits')->get()));
+ $this->assertSame($this->fixture, $response->json('items.49.password'));
+ }
+
+ public function test_later_chunk_failure_suppresses_passwords_from_earlier_chunks(): void
+ {
+ $accountIds = array_map(fn ($index) => sprintf('fixture-account-%02d', $index), range(1, 50));
+ $items = array_map(fn ($accountId, $index) => [
+ 'accountId' => $accountId,
+ 'status' => 200,
+ 'requestId' => sprintf('12345678-1234-4123-8123-%012d', $index + 1),
+ 'password' => $this->fixture,
+ ], array_slice($accountIds, 0, 25), range(0, 24));
+ $handler = HandlerStack::create(new MockHandler([
+ new Response(200, ['Cache-Control' => 'private, no-store'], json_encode([
+ 'requestId' => '22345678-1234-4123-8123-123456789001',
+ 'items' => $items,
+ ])),
+ new Response(403, ['Cache-Control' => 'no-store'], json_encode(['message' => $this->fixture])),
+ ]));
+ $handler->push(Middleware::history($this->history));
+ $this->app->instance(StoreAccountPasswordClient::class, new StoreAccountPasswordClient(new Client(['handler' => $handler])));
+
+ $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => $accountIds])
+ ->assertStatus(503)->assertJsonMissingPath('items')->assertJsonMissingPath('password');
+
+ $this->assertCount(2, $this->history);
+ $this->assertStringNotContainsString($this->fixture, $response->getContent());
+ $this->assertSame(50, DB::table('store_account_password_audits')->where('status', 503)->count());
+ }
+
+ public function test_visible_page_rejects_duplicates_and_more_than_fifty_accounts(): void
+ {
+ $this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('revealVisiblePage');
+ $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account', 'fixture-account']])->assertUnprocessable();
+ $this->postJson($this->visiblePageEndpoint(), ['accounts' => array_map(fn ($index) => 'account-'.$index, range(1, 51))])->assertUnprocessable();
+ $this->assertSame(0, DB::table('store_account_password_audits')->count());
+ }
+
+ public function test_visible_page_rejects_malformed_or_cacheable_upstream_response(): void
+ {
+ $this->visiblePageTransport([
+ ['accountId' => 'fixture-account', 'status' => 200, 'requestId' => 'bad-request-id', 'password' => $this->fixture],
+ ], []);
+ $response = $this->loginAs()->postJson($this->visiblePageEndpoint(), ['accounts' => ['fixture-account']])->assertStatus(503);
+ $response->assertJsonMissingPath('items')->assertJsonMissingPath('password');
+ $this->assertStringNotContainsString($this->fixture, $response->getContent());
+ $this->assertDatabaseHas('store_account_password_audits', ['store_account_id' => 'fixture-account', 'status' => 503]);
+ }
+
public function test_actor_spoofing_is_rejected(): void
{
$this->mock(StoreAccountPasswordClient::class)->shouldNotReceive('reveal');
@@ -150,17 +300,22 @@ class StoreAccountPasswordsTest extends FeatureTestCase
$this->loginAs()->postJson($this->endpoint(), ['purpose' => 'view'])->assertStatus(429);
}
- public function test_admin_page_has_explicit_actions_and_no_plaintext_in_table(): void
+ public function test_store_accounts_page_auto_loads_visible_password_cells_without_a_dialog(): void
{
$this->mock(\App\Business\UpstreamBusinessInformation::class)->shouldReceive('paginate')->andReturn(
new \Illuminate\Pagination\LengthAwarePaginator([(object) [
'id' => 'fixture-account', 'store_name' => '测试店铺', 'account' => 'fixture-login', 'password_configured' => true,
]], 1, 50, 1)
);
+ $this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);
+ $this->user->permissions()->attach(\App\Models\Auth\Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
$response = $this->loginAs()->get(route('business.pages.show', ['section' => 'store-management', 'page' => 'store-accounts']))->assertOk();
- $response->assertSee('data-store-password="view"', false)->assertSee('data-store-password="copy"', false)
- ->assertSee('data-password-dialog', false)->assertDontSee($this->fixture);
- $html = $response->getContent();
- $this->assertGreaterThan(strpos($html, ''), strpos($html, ' |