From 730522d1a5a2d864941380de88456d9ffea7807b Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Tue, 15 Sep 2026 09:49:31 +0800 Subject: [PATCH 001/249] fix: use official jushuitan worklog contract --- .../SyncJushuitanCostPriceHistory.php | 2 +- config/services.php | 16 ++-- docs/上游业务镜像清单.md | 4 +- .../JushuitanCostPriceHistorySynchronizer.php | 20 +++-- .../Services/JushuitanOpenApiClient.php | 89 +++++++++---------- ...huitanCostPriceHistorySynchronizerTest.php | 21 ++--- .../JushuitanOpenApiClientTest.php | 76 ++++++++-------- 7 files changed, 113 insertions(+), 115 deletions(-) diff --git a/app/Console/Commands/SyncJushuitanCostPriceHistory.php b/app/Console/Commands/SyncJushuitanCostPriceHistory.php index ddda7a45..61dd2d4a 100644 --- a/app/Console/Commands/SyncJushuitanCostPriceHistory.php +++ b/app/Console/Commands/SyncJushuitanCostPriceHistory.php @@ -12,7 +12,7 @@ class SyncJushuitanCostPriceHistory extends Command { protected $signature = 'business-mirror:sync-jushuitan-cost-price-history {--full : 强制启动或继续首次全量同步} - {--page-size= : 聚水潭接口每页读取条数,最大 2000} + {--page-size= : 聚水潭接口每页读取条数,最大 50} {--max-pages= : 本轮最多读取页数,0 表示直到完成}'; protected $description = '按时间窗和页码同步聚水潭商品操作日志中的采购价变更到共享业务镜像'; diff --git a/config/services.php b/config/services.php index 3c1bdf21..33c52cf5 100644 --- a/config/services.php +++ b/config/services.php @@ -59,16 +59,18 @@ return [ 'jushuitan' => [ // 聚水潭开放平台凭据只从私有 runtime/.env 读取,不进入代码仓库。 - 'base_url' => env('JUSHUITAN_OPEN_API_URL', 'https://openapi.jushuitan.com'), - 'app_key' => env('JUSHUITAN_APP_KEY'), - 'app_secret' => env('JUSHUITAN_APP_SECRET'), - 'access_token' => env('JUSHUITAN_ACCESS_TOKEN'), + // 商品操作日志仍使用经典开放接口;兼容现有 APP_* 环境变量名, + // 实际含义依次为 partnerid、partnerkey、token。 + 'base_url' => env('JUSHUITAN_OPEN_API_URL', 'https://open.erp321.com/api/open/query.aspx'), + 'partner_id' => env('JUSHUITAN_PARTNER_ID', env('JUSHUITAN_APP_KEY')), + 'partner_key' => env('JUSHUITAN_PARTNER_KEY', env('JUSHUITAN_APP_SECRET')), + 'token' => env('JUSHUITAN_TOKEN', env('JUSHUITAN_ACCESS_TOKEN')), 'timeout' => (int) env('JUSHUITAN_OPEN_API_TIMEOUT', 20), - 'product_operation_history_path' => '/open/webapi/itemapi/itemsku/queryitemskuopshistory', + 'product_operation_history_method' => 'worklog.query', 'cost_price_history_start' => env('JUSHUITAN_COST_PRICE_HISTORY_START', '2000-01-01 00:00:00'), - 'cost_price_history_window_days' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_WINDOW_DAYS', 30), + 'cost_price_history_window_days' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_WINDOW_DAYS', 7), 'cost_price_history_overlap_hours' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_OVERLAP_HOURS', 48), - 'cost_price_history_page_size' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_PAGE_SIZE', 2000), + 'cost_price_history_page_size' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_PAGE_SIZE', 50), 'cost_price_history_max_pages' => (int) env('JUSHUITAN_COST_PRICE_HISTORY_MAX_PAGES', 30), ], diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 8d1e95fc..8d624f40 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -28,7 +28,7 @@ | 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | -| 本次接入 | 普通商品成本价变更读取聚水潭开放平台“商品及库存管理”的商品操作日志接口 `/open/webapi/itemapi/itemsku/queryitemskuopshistory`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;审计历史按 `operation_id` 只追加或更新,全量回补不删除旧记录;页面按商品编码分别展示聚水潭成本价记录和工作平台价格记录,不混用来源。 | +| 本次接入 | 普通商品成本价变更读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;审计历史按稳定记录键只追加或更新,全量回补不删除旧记录;页面按商品编码分别展示聚水潭成本价记录和工作平台价格记录,不混用来源。 | ## 经营分析副本库(operations_replica) @@ -96,7 +96,7 @@ 10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步由 Codex 备份后自主安排在生产同步节点低峰期分批续传,无需另行授权;页面请求和普通开发机不启动刷新 worker。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。 淘系支付宝账户账单当前仍读取此 MariaDB 镜像,统一调度须持续增量,不因 ClickHouse 尚未启用而暂停。账单冲减则复用“订单数据 → 原始数据 → 订单售后费用明细”,不按该表费用名称推断 500112。 11. 拼多多货款账户账单使用 `jiansun.dbo.jst_originalBillInfo.pinduoduo_receiving` 数据集。同步器必须以参数绑定固定 `channel = PinduoduoImport`,只复制该渠道切片;页面 Repository 只读 `js_jst_pdd_receiving_bill_rows`。首次全量按 `Id` 断点推进,后续按 `updateTime` 保留重叠窗口,不得切回落后一天的 `operations_replica` 副本。 12. 三方仓进销存首次全量按头表 `Id` 区间小批断点续传,头表只保存 `io_date >= 2026-08-01` 的目标仓数据,不激活半份数据;日常增量以头表 `(modified, Id)` 作稳定游标并保留 48 小时时间重叠,由命中头单驱动整单明细替换。全量和增量都先写待发布代次,库存抓取完成后再把流水追平到库存抓取之后的固定源时间边界,三部分成功后才一次切换;运行中或失败时页面始终读取上一成功代次。增量扫描不先限定仓库或业务日期,确保单据移出目标仓或日期改到起始日前时可从镜像撤回,重载当前版本时再固定仓库和起始日期。页面只统计 `Confirmed` 的 12 类进销存流水,数量按上游 `qty * qty_type` 保留符号。库存同时保存上游 `source_modified_at` 和实际 `captured_at`,历史余额以每个 SKU 的抓取时间为回推锚点;页面始终按“日期 + 商品”输出,日期区间固定为 `[当天 00:00, 次日 00:00)`。每天 `00:00` 执行增量同步,失败时继续展示上一成功代次。 -13. 聚水潭商品操作日志按最多 30 天的固定时间窗和接口页码稳定断点同步,首次全量从 `2000-01-01` 起扫描;只保留操作内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按操作日志 `autoid` 幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。 +13. 聚水潭商品操作日志按最多 7 天的固定时间窗和接口页码稳定断点同步,每页最多 50 条,首次全量从 `2000-01-01` 起扫描;只保留备注内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按接口记录字段生成稳定键幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。 工作平台采购价格首次全量需在备份和负责人授权后单独执行: diff --git a/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php b/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php index 5caa4edf..95cdae60 100644 --- a/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php +++ b/modules/EcommerceFinance/Services/JushuitanCostPriceHistorySynchronizer.php @@ -42,11 +42,11 @@ class JushuitanCostPriceHistorySynchronizer $until = Carbon::parse((string) $state['window_ends_at']); } elseif ($full) { $since = $this->historyStart(); - $until = now()->addSecond(); + $until = now(); } else { $overlap = max((int) config('services.jushuitan.cost_price_history_overlap_hours', 48), 1); $since = Carbon::parse((string) $state['last_succeeded_at'])->subHours($overlap); - $until = now()->addSecond(); + $until = now(); } $state = $this->mirror->startRun($mode, $generation, $since, $until, $resume); @@ -55,9 +55,9 @@ class JushuitanCostPriceHistorySynchronizer : Carbon::parse((string) $state['cursor_window_started_at']); $page = max((int) ($state['cursor_page'] ?? 1), 1); $pageSize = min(max( - $pageSize ?? (int) config('services.jushuitan.cost_price_history_page_size', 2000), + $pageSize ?? (int) config('services.jushuitan.cost_price_history_page_size', 50), 1, - ), 2000); + ), 50); $maxPages = max( $maxPages ?? (int) config('services.jushuitan.cost_price_history_max_pages', 30), 0, @@ -66,9 +66,9 @@ class JushuitanCostPriceHistorySynchronizer $processedSourceRows = (int) ($state['last_processed_source_rows'] ?? 0); $upsertedRows = (int) ($state['last_upserted_rows'] ?? 0); $windowDays = min(max( - (int) config('services.jushuitan.cost_price_history_window_days', 30), + (int) config('services.jushuitan.cost_price_history_window_days', 7), 1, - ), 30); + ), 7); try { while ($windowStartedAt->lt($until)) { @@ -88,7 +88,7 @@ class JushuitanCostPriceHistorySynchronizer $upsertedRows += count($records); $pages++; - $hasNextPage = $result['total_pages'] > 0 && $page < $result['total_pages']; + $hasNextPage = $result['has_next']; // 相邻窗口在边界秒保留一次重叠,避免接口时间精度高于秒时漏掉记录; // operation_id 的幂等 upsert 会消除边界重复。 $nextWindowStartedAt = $hasNextPage @@ -133,7 +133,11 @@ class JushuitanCostPriceHistorySynchronizer 'rows' => $upsertedRows, ]; } catch (Throwable $exception) { - $this->mirror->fail($exception::class); + $message = trim($exception->getMessage()); + $errorCode = preg_match('/^[a-z0-9_]+$/', $message) === 1 + ? $message + : $exception::class; + $this->mirror->fail($errorCode); throw $exception; } } diff --git a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php index 0bfc6b11..4f68fec3 100644 --- a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php +++ b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php @@ -10,7 +10,7 @@ use RuntimeException; class JushuitanOpenApiClient { /** - * @return array{records:list>,source_rows:int,current_page:int,total_pages:int,total_count:int} + * @return array{records:list>,source_rows:int,current_page:int,has_next:bool} */ public function getCostPriceOperationHistory( Carbon $start, @@ -19,56 +19,57 @@ class JushuitanOpenApiClient int $pageSize, ): array { $payload = $this->request([ - 'current_page' => max($page, 1), - 'page_size' => min(max($pageSize, 1), 2000), - 'start_time' => $start->format('Y-m-d H:i:s'), - 'end_time' => $end->format('Y-m-d H:i:s'), + 'page_index' => max($page, 1), + 'page_size' => min(max($pageSize, 1), 50), + 'modified_begin' => $start->format('Y-m-d H:i:s'), + 'modified_end' => $end->format('Y-m-d H:i:s'), ]); - $data = is_array($payload['data'] ?? null) ? $payload['data'] : []; - $pageInfo = is_array($data['page'] ?? null) ? $data['page'] : []; + $records = is_array($payload['datas'] ?? null) ? $payload['datas'] : []; return [ - 'records' => $this->normalizeCostPriceOperations($data['list'] ?? []), - 'source_rows' => is_array($data['list'] ?? null) ? count($data['list']) : 0, - 'current_page' => max((int) ($pageInfo['current_page'] ?? $page), 1), - 'total_pages' => max((int) ($pageInfo['pages'] ?? 0), 0), - 'total_count' => max((int) ($pageInfo['count'] ?? 0), 0), + 'records' => $this->normalizeCostPriceOperations($records), + 'source_rows' => count($records), + 'current_page' => max((int) ($payload['page_index'] ?? $page), 1), + 'has_next' => (bool) ($payload['has_next'] ?? false), ]; } /** @param array $biz @return array */ private function request(array $biz): array { - $appKey = trim((string) config('services.jushuitan.app_key')); - $appSecret = trim((string) config('services.jushuitan.app_secret')); - $accessToken = trim((string) config('services.jushuitan.access_token')); - if ($appKey === '' || $appSecret === '' || $accessToken === '') { + $partnerId = trim((string) config('services.jushuitan.partner_id')); + $partnerKey = trim((string) config('services.jushuitan.partner_key')); + $token = trim((string) config('services.jushuitan.token')); + if ($partnerId === '' || $partnerKey === '' || $token === '') { throw new RuntimeException('jushuitan_api_credentials_missing'); } + $method = (string) config( + 'services.jushuitan.product_operation_history_method', + 'worklog.query', + ); + $timestamp = (string) now()->timestamp; + // URL parameter order is part of the classic API signature contract. $params = [ - 'access_token' => $accessToken, - 'app_key' => $appKey, - 'biz' => json_encode( - $biz, - JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, - ), - 'charset' => 'utf-8', - 'timestamp' => (string) now()->timestamp, - 'version' => '2', + 'method' => $method, + 'partnerid' => $partnerId, + 'token' => $token, + 'ts' => $timestamp, ]; - $params['sign'] = $this->sign($params, $appSecret); + $params['sign'] = $this->sign($method, $partnerId, $token, $timestamp, $partnerKey); - $baseUrl = rtrim((string) config('services.jushuitan.base_url'), '/'); - $path = (string) config( - 'services.jushuitan.product_operation_history_path', - '/open/webapi/itemapi/itemsku/queryitemskuopshistory', + $baseUrl = (string) config( + 'services.jushuitan.base_url', + 'https://open.erp321.com/api/open/query.aspx', ); /** @var PendingRequest $request */ - $request = Http::asForm() + $request = Http::asJson() ->acceptJson() ->timeout(max((int) config('services.jushuitan.timeout', 20), 1)); - $response = $request->post($baseUrl . '/' . ltrim($path, '/'), $params); + $response = $request->post( + $baseUrl . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986), + $biz, + ); if (! $response->successful()) { throw new RuntimeException('jushuitan_api_http_' . $response->status()); @@ -86,19 +87,15 @@ class JushuitanOpenApiClient return $payload; } - /** @param array $params */ - private function sign(array $params, string $appSecret): string + private function sign( + string $method, + string $partnerId, + string $token, + string $timestamp, + string $partnerKey, + ): string { - ksort($params, SORT_STRING); - $plain = $appSecret; - foreach ($params as $key => $value) { - if ($key === 'sign' || $value === null || $value === '') { - continue; - } - $plain .= $key . (string) $value; - } - - return md5($plain); + return md5($method . $partnerId . 'token' . $token . 'ts' . $timestamp . $partnerKey); } /** @param mixed $records @return list> */ @@ -114,7 +111,7 @@ class JushuitanOpenApiClient continue; } $skuId = trim((string) ($record['sku_id'] ?? '')); - $description = trim((string) ($record['operation_description'] ?? '')); + $description = trim((string) ($record['remark'] ?? $record['operation_description'] ?? '')); if ($skuId === '' || ! str_contains($description, '采购价')) { continue; } @@ -127,7 +124,7 @@ class JushuitanOpenApiClient 'product_name' => $this->nullableString($record['name'] ?? null), 'properties_value' => $this->nullableString($record['properties_value'] ?? null), 'sku_type' => $this->nullableString($record['sku_type'] ?? null), - 'operation_type' => $this->nullableString($record['operation_type'] ?? null), + 'operation_type' => $this->nullableString($record['type'] ?? $record['operation_type'] ?? null), 'operation_description' => $description, 'operator_name' => $this->nullableString($record['creator_name'] ?? null), 'operated_at' => $this->nullableString($record['created'] ?? null), diff --git a/tests/Unit/EcommerceFinance/JushuitanCostPriceHistorySynchronizerTest.php b/tests/Unit/EcommerceFinance/JushuitanCostPriceHistorySynchronizerTest.php index 3503c429..1fca0cd1 100644 --- a/tests/Unit/EcommerceFinance/JushuitanCostPriceHistorySynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/JushuitanCostPriceHistorySynchronizerTest.php @@ -32,27 +32,24 @@ class JushuitanCostPriceHistorySynchronizerTest extends TestCase public function test_full_sync_uses_stable_time_windows_and_page_cursor(): void { - Carbon::setTestNow('2026-09-14 00:00:00'); + Carbon::setTestNow('2026-08-15 00:00:00'); config()->set('services.jushuitan.cost_price_history_start', '2026-08-01 00:00:00'); config()->set('services.jushuitan.cost_price_history_window_days', 30); $responses = [[ 'records' => [['operation_id' => '10', 'sku_id' => 'SKU-10']], 'source_rows' => 2, 'current_page' => 1, - 'total_pages' => 2, - 'total_count' => 3, + 'has_next' => true, ], [ 'records' => [['operation_id' => '20', 'sku_id' => 'SKU-20']], 'source_rows' => 1, 'current_page' => 2, - 'total_pages' => 2, - 'total_count' => 3, + 'has_next' => false, ], [ 'records' => [], 'source_rows' => 1, 'current_page' => 1, - 'total_pages' => 1, - 'total_count' => 1, + 'has_next' => false, ]]; $apiCalls = []; $upstream = $this->createMock(JushuitanOpenApiClient::class); @@ -85,13 +82,13 @@ class JushuitanCostPriceHistorySynchronizerTest extends TestCase $result = (new JushuitanCostPriceHistorySynchronizer($upstream, $mirror))->sync(true, 2000, 0); $this->assertSame([ - ['2026-08-01 00:00:00', '2026-08-31 00:00:00', 1, 2000], - ['2026-08-01 00:00:00', '2026-08-31 00:00:00', 2, 2000], - ['2026-08-31 00:00:00', '2026-09-14 00:00:01', 1, 2000], + ['2026-08-01 00:00:00', '2026-08-08 00:00:00', 1, 50], + ['2026-08-01 00:00:00', '2026-08-08 00:00:00', 2, 50], + ['2026-08-08 00:00:00', '2026-08-15 00:00:00', 1, 50], ], $apiCalls); $this->assertSame('2026-08-01 00:00:00', $storedPages[0][1]->format('Y-m-d H:i:s')); $this->assertSame(2, $storedPages[0][2]); - $this->assertSame('2026-08-31 00:00:00', $storedPages[1][1]->format('Y-m-d H:i:s')); + $this->assertSame('2026-08-08 00:00:00', $storedPages[1][1]->format('Y-m-d H:i:s')); $this->assertSame(1, $storedPages[1][2]); $this->assertSame('succeeded', $result['status']); $this->assertSame(4, $result['source_rows']); @@ -118,7 +115,7 @@ class JushuitanCostPriceHistorySynchronizerTest extends TestCase ]); $mirror->expects($this->never())->method('storePage'); $mirror->expects($this->never())->method('complete'); - $mirror->expects($this->once())->method('fail')->with(RuntimeException::class); + $mirror->expects($this->once())->method('fail')->with('upstream_unavailable'); $this->expectExceptionMessage('upstream_unavailable'); (new JushuitanCostPriceHistorySynchronizer($upstream, $mirror))->sync(); diff --git a/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php b/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php index 801375db..beb93128 100644 --- a/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php +++ b/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php @@ -16,12 +16,12 @@ class JushuitanOpenApiClientTest extends TestCase parent::setUp(); Carbon::setTestNow('2026-09-14 06:00:00'); config()->set('services.jushuitan', [ - 'base_url' => 'https://jushuitan.example.test', - 'app_key' => 'test-app-key', - 'app_secret' => 'test-app-secret', - 'access_token' => 'test-access-token', + 'base_url' => 'https://jushuitan.example.test/api/open/query.aspx', + 'partner_id' => 'test-partner-id', + 'partner_key' => 'test-partner-key', + 'token' => 'test-token', 'timeout' => 20, - 'product_operation_history_path' => '/open/webapi/itemapi/itemsku/queryitemskuopshistory', + 'product_operation_history_method' => 'worklog.query', ]); Http::preventStrayRequests(); } @@ -32,17 +32,18 @@ class JushuitanOpenApiClientTest extends TestCase parent::tearDown(); } - public function test_it_posts_signed_form_and_keeps_only_cost_price_operations(): void + public function test_it_posts_signed_json_and_keeps_only_cost_price_operations(): void { Http::fake([ 'https://jushuitan.example.test/*' => Http::response([ 'code' => 0, - 'data' => [ - 'page' => ['current_page' => 1, 'page_size' => 2000, 'count' => 2, 'pages' => 1], - 'list' => [[ + 'page_size' => 2, + 'page_index' => 1, + 'has_next' => false, + 'datas' => [[ 'autoid' => 101, - 'operation_type' => '商品与库存管理导入', - 'operation_description' => '采购价:72.2222->65', + 'type' => '商品与库存管理导入', + 'remark' => '采购价:72.2222->65', 'created' => '2026-06-06 14:32:02.993', 'creator_name' => '简尚', 'sku_id' => '15961G', @@ -52,19 +53,18 @@ class JushuitanOpenApiClientTest extends TestCase 'sku_type' => 'normal', ], [ 'autoid' => 102, - 'operation_type' => '编辑', - 'operation_description' => '商品名称:旧名称->新名称', + 'type' => '编辑', + 'remark' => '商品名称:旧名称->新名称', 'created' => '2026-06-06 14:33:00', 'creator_name' => '测试人', 'sku_id' => '15961G', ]], - ], ]), ]); $result = (new JushuitanOpenApiClient())->getCostPriceOperationHistory( Carbon::parse('2026-06-01 00:00:00'), - Carbon::parse('2026-06-30 23:59:59'), + Carbon::parse('2026-06-08 00:00:00'), 1, 2000, ); @@ -78,25 +78,24 @@ class JushuitanOpenApiClientTest extends TestCase $this->assertSame('简尚', $result['records'][0]['operator_name']); Http::assertSent(function (Request $request): bool { - $data = $request->data(); - $sign = $data['sign'] ?? null; - unset($data['sign']); - ksort($data, SORT_STRING); - $plain = 'test-app-secret'; - foreach ($data as $key => $value) { - $plain .= $key . (string) $value; - } - $biz = json_decode((string) ($data['biz'] ?? ''), true); + parse_str((string) parse_url($request->url(), PHP_URL_QUERY), $query); + $timestamp = (string) Carbon::now()->timestamp; return $request->method() === 'POST' - && $request->url() === 'https://jushuitan.example.test/open/webapi/itemapi/itemsku/queryitemskuopshistory' - && str_starts_with((string) $request->header('Content-Type')[0], 'application/x-www-form-urlencoded') - && $sign === md5($plain) - && $biz === [ - 'current_page' => 1, - 'page_size' => 2000, - 'start_time' => '2026-06-01 00:00:00', - 'end_time' => '2026-06-30 23:59:59', + && str_starts_with($request->url(), 'https://jushuitan.example.test/api/open/query.aspx?') + && str_starts_with((string) $request->header('Content-Type')[0], 'application/json') + && $query === [ + 'method' => 'worklog.query', + 'partnerid' => 'test-partner-id', + 'token' => 'test-token', + 'ts' => $timestamp, + 'sign' => md5('worklog.querytest-partner-idtokentest-tokents' . $timestamp . 'test-partner-key'), + ] + && $request->data() === [ + 'page_index' => 1, + 'page_size' => 50, + 'modified_begin' => '2026-06-01 00:00:00', + 'modified_end' => '2026-06-08 00:00:00', ]; }); } @@ -106,15 +105,14 @@ class JushuitanOpenApiClientTest extends TestCase Http::fake([ '*' => Http::response([ 'code' => 0, - 'data' => [ - 'page' => ['current_page' => 1, 'count' => 1, 'pages' => 1], - 'list' => [[ + 'page_index' => 1, + 'has_next' => false, + 'datas' => [[ 'autoid' => 103, - 'operation_description' => '采购价已由批量任务更新', + 'remark' => '采购价已由批量任务更新', 'created' => '2026-06-07 08:00:00', 'sku_id' => 'SKU-UNPARSED', ]], - ], ]), ]); @@ -133,7 +131,7 @@ class JushuitanOpenApiClientTest extends TestCase public function test_it_rejects_missing_credentials_and_upstream_error_codes(): void { - config()->set('services.jushuitan.access_token', null); + config()->set('services.jushuitan.token', null); try { (new JushuitanOpenApiClient())->getCostPriceOperationHistory(now(), now(), 1, 100); $this->fail('Expected missing credential exception.'); @@ -141,7 +139,7 @@ class JushuitanOpenApiClientTest extends TestCase $this->assertSame('jushuitan_api_credentials_missing', $exception->getMessage()); } - config()->set('services.jushuitan.access_token', 'test-access-token'); + config()->set('services.jushuitan.token', 'test-token'); Http::fake(['*' => Http::response(['code' => 10001, 'msg' => 'denied'])]); $this->expectExceptionMessage('jushuitan_api_code_10001'); From edb32c33cfb943497ad4521813984c0687b2f666 Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Tue, 15 Sep 2026 11:09:03 +0800 Subject: [PATCH 002/249] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E5=BE=97=E7=89=A9?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E8=B4=A6=E5=8D=95=E9=95=9C=E5=83=8F=20(#185)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 固定同步 Dewu 主收款渠道,接入得物账户分页、筛选、汇总和导出,并补充镜像与回归测试。 未部署,未执行生产首次同步。 --- config/business_data.php | 3 + config/upstream_mirrors.php | 25 +++ docs/上游业务镜像清单.md | 1 + .../Http/Controllers/AccountBills.php | 21 +- ...oreReceivingAlipayBillMirrorRepository.php | 60 +++++- ...StoreReceivingDewuBillMirrorRepository.php | 49 +++++ .../js/components/business/AccountBills.vue | 2 +- .../Business/DewuReceivingBillsTest.php | 124 ++++++++++++ .../BusinessMirrorSynchronizerTest.php | 6 + ...eReceivingDewuBillMirrorRepositoryTest.php | 189 ++++++++++++++++++ tests/Unit/View/AccountBillsTableTest.php | 2 +- 11 files changed, 467 insertions(+), 15 deletions(-) create mode 100644 modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php create mode 100644 tests/Feature/Business/DewuReceivingBillsTest.php create mode 100644 tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php diff --git a/config/business_data.php b/config/business_data.php index 7a1c31aa..782d5f90 100644 --- a/config/business_data.php +++ b/config/business_data.php @@ -97,6 +97,9 @@ return [ 'jiansun.dbo.jst_originalBillInfo.pinduoduo_receiving' => [ 'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/拼多多账户', ], + 'jiansun.dbo.jst_originalBillInfo.dewu_receiving' => [ + 'role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/得物账户', + ], 'jiansun.dbo.alipay_Bill_Detail' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '店铺收款账单/淘系支付宝账户'], 'jiansun.dbo.tmall_spread_bills' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '淘宝推广账单'], 'jiansun.dbo.pdd_spread_bills' => ['role' => 'serving_fact', 'target_store' => 'mariadb', 'consumer' => '拼多多推广账单'], diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index 585a67d5..1325eb65 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -436,6 +436,31 @@ return [ ['fee_name'], ], ], + // 聚水潭得物货款账户:只复制主账单渠道,保证金、跨境和推广流水 + // 由其他账户域处理,不混入店铺收款账户页面。 + 'jiansun.dbo.jst_originalBillInfo.dewu_receiving' => [ + 'source_key' => 'jiansun', + 'schema' => 'dbo', + 'object' => 'jst_originalBillInfo', + 'target' => 'js_jst_dewu_receiving_bill_rows', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'fixed_filters' => [ + 'channel' => 'Dewu', + ], + 'columns' => [ + 'Id', 'shop_id', 'channel', 'fee_time', 'del_flag', 'primary_key', + 'createTime', 'updateTime', 'auto_id', 'fee_name', 'inout_type', + 'oc_amount', 'p_auto_id', 'shop_i_id', 'shop_sku_id', 'sku_id', + 'so_id', 'combine_type', 'amount', + ], + 'indexes' => [ + ['Id'], + ['fee_time', 'Id', 'inout_type', 'amount'], + ['shop_id', 'fee_time', 'Id', 'inout_type', 'amount', 'fee_name'], + ['fee_name'], + ], + ], 'jiansun.dbo.alipay_Bill_Detail' => [ 'source_key' => 'jiansun', 'schema' => 'dbo', diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 8d624f40..ed4ccf1b 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -25,6 +25,7 @@ | 页面已切换 | 店铺收款账单的淘系支付宝账户读取 `operations_replica.rpt.jst_originalBillInfo`,并关联 `rpt.jst_shopInfo` 展示店铺;分页、筛选、汇总和导出统一读取共享业务镜像。 | | 抖音按月校准 | 抖音账户对已核对的完整月份读取 `douyin_authoritative_bills` 中胜算原始明细,`douyin_authoritative_periods` 原子选择有效版本;该月份不再叠加聚水潭拆分行。未校准月份继续读取原始账单镜像。导入命令为 `business-mirror:import-douyin-authoritative --count=<核对笔数> --income=<收入> --expense=<支出>`,只接受完整月份和精确核对值,保留旧版本、文件摘要及原镜像供回滚。生产执行前备份状态与受影响月份镜像,并使用 `/run/caiwu-upstream-sync.lock`。实际财务数据只放私有目录,不进入 Git。 | | 已接入待首次同步 | 店铺收款账单的拼多多账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = PinduoduoImport` 的独立切片镜像 `js_jst_pdd_receiving_bill_rows`;不使用慢一天的 `operations_replica` 副本或营销账户 `pdd_spread_bills`。 | +| 已接入待首次同步 | 店铺收款账单的得物账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = Dewu` 的独立切片镜像 `js_jst_dewu_receiving_bill_rows`;`Dewubzj`、`DewuKJ`、`DewuTK` 保留给保证金、跨境或推广等其他账户域,不混入得物收款账户。 | | 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | diff --git a/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index d7067d5f..aa9df058 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -8,6 +8,7 @@ use Illuminate\Routing\Controller; use Modules\EcommerceFinance\AccountBillColumns; use Modules\EcommerceFinance\Models\AccountBill; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; +use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository; use RuntimeException; @@ -28,7 +29,7 @@ class AccountBills extends Controller abort(404, '未知的账户类型。'); } - if (in_array($billType, ['douyin', 'pinduoduo'], true)) { + if (in_array($billType, ['douyin', 'pinduoduo', 'dewu'], true)) { return $request->boolean('export') ? $this->export($request, $billType) : $this->mirrorIndex($request, $billType); @@ -117,7 +118,7 @@ class AccountBills extends Controller abort_unless(AccountBillColumns::has($bill_type), 404, '未知的账户类型。'); - if (in_array($bill_type, ['douyin', 'pinduoduo'], true)) { + if (in_array($bill_type, ['douyin', 'pinduoduo', 'dewu'], true)) { return $this->exportMirror($request, $bill_type); } @@ -141,7 +142,7 @@ class AccountBills extends Controller { $this->authorizeStoreReceivingBills(); - abort_unless(in_array($bill_type, ['douyin', 'pinduoduo'], true), 404, '该账户类型没有可用的筛选选项。'); + abort_unless(in_array($bill_type, ['douyin', 'pinduoduo', 'dewu'], true), 404, '该账户类型没有可用的筛选选项。'); $label = $this->mirrorLabel($bill_type); @@ -362,14 +363,20 @@ class AccountBills extends Controller private function mirrorRepository(string $billType): object { - return $billType === 'pinduoduo' - ? app(StoreReceivingPinduoduoBillMirrorRepository::class) - : app(StoreReceivingDouyinBillMirrorRepository::class); + return match ($billType) { + 'pinduoduo' => app(StoreReceivingPinduoduoBillMirrorRepository::class), + 'dewu' => app(StoreReceivingDewuBillMirrorRepository::class), + default => app(StoreReceivingDouyinBillMirrorRepository::class), + }; } private function mirrorLabel(string $billType): string { - return $billType === 'pinduoduo' ? '拼多多' : '抖音'; + return match ($billType) { + 'pinduoduo' => '拼多多', + 'dewu' => '得物', + default => '抖音', + }; } private function sort(Request $request): string diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php index 1080b831..de4dcffc 100644 --- a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php @@ -58,7 +58,7 @@ class StoreReceivingAlipayBillMirrorRepository $perPage = min(max($perPage, 1), 100); $direction = $direction === 'asc' ? 'asc' : 'desc'; $sortColumn = [ - 'record_code' => $mapping === 'pinduoduo' ? 'b.auto_id' : 'b.Id', + 'record_code' => in_array($mapping, ['pinduoduo', 'dewu'], true) ? 'b.auto_id' : 'b.Id', 'occurred_at' => 'b.fee_time', 'income' => 'b.amount', 'expense' => 'b.amount', @@ -103,7 +103,7 @@ class StoreReceivingAlipayBillMirrorRepository 'summary' => [ 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'count' => $total, ], 'sync' => [ @@ -146,7 +146,7 @@ class StoreReceivingAlipayBillMirrorRepository $shopNames = $this->allShopNames(); $direction = $direction === 'desc' ? 'desc' : 'asc'; $sortColumn = [ - 'record_code' => $mapping === 'pinduoduo' ? 'b.auto_id' : 'b.Id', + 'record_code' => in_array($mapping, ['pinduoduo', 'dewu'], true) ? 'b.auto_id' : 'b.Id', 'occurred_at' => 'b.fee_time', 'income' => 'b.amount', 'expense' => 'b.amount', @@ -491,7 +491,7 @@ class StoreReceivingAlipayBillMirrorRepository 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'business_type' => $this->directionName($row->inout_type), 'remark' => null, 'online_order_no' => $row->so_id, @@ -512,6 +512,10 @@ class StoreReceivingAlipayBillMirrorRepository return $this->mapPinduoduoRow($row, $shopName); } + if ($mapping === 'dewu') { + return $this->mapDewuRow($row, $shopName); + } + if ($mapping !== 'douyin') { return $this->mapRow($row, $shopName); } @@ -533,7 +537,7 @@ class StoreReceivingAlipayBillMirrorRepository 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'remark' => null, 'modifier' => '聚水潭', 'created_at' => $this->dateTime($row->createTime), @@ -576,7 +580,7 @@ class StoreReceivingAlipayBillMirrorRepository 'occurred_at' => $this->dateTime($row->fee_time), 'income' => $income, 'expense' => $expense, - 'balance' => $income - $expense, + 'balance' => round($income - $expense, 2), 'remark' => null, 'updated_at' => $this->dateTime($row->updateTime), 'modifier' => 'RPA', @@ -589,6 +593,50 @@ class StoreReceivingAlipayBillMirrorRepository ]; } + /** @return array */ + private function mapDewuRow(object $row, ?string $shopName): array + { + $amount = abs((float) ($row->amount ?? 0)); + $income = (string) ($row->inout_type ?? '') === '1' ? $amount : 0.0; + $expense = (string) ($row->inout_type ?? '') === '-1' ? $amount : 0.0; + $orderNo = $row->so_id ?: $row->p_auto_id; + $goodsNo = $row->sku_id ?: $row->shop_sku_id ?: $row->shop_i_id; + + return [ + 'id' => (string) $row->Id, + 'record_code' => (string) ($row->auto_id ?: $row->Id), + 'store_name' => $shopName, + 'finance_remark' => null, + 'order_no' => $orderNo, + 'amount' => $amount, + 'custom_remark' => null, + 'bill_item' => $row->fee_name, + 'occurred_at' => $this->dateTime($row->fee_time), + 'income' => $income, + 'expense' => $expense, + 'balance' => round($income - $expense, 2), + 'remark' => null, + 'updated_at' => $this->dateTime($row->updateTime), + 'modifier' => '聚水潭', + 'payload' => [ + 'online_order_no' => $orderNo, + 'store_2' => $shopName, + 'order_type' => null, + 'goods_name' => null, + 'goods_no' => $goodsNo, + 'quantity' => null, + 'channel' => $row->channel, + 'business_type' => $this->directionName($row->inout_type), + 'online_real_store' => $shopName, + 'order_created_at' => null, + 'ship_return_at' => null, + 'settle_status' => null, + 'pay_period' => null, + 'pulled_at' => $this->dateTime($row->createTime), + ], + ]; + } + private function directionCode(string $value): string { return match ($value) { diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php new file mode 100644 index 00000000..1af74db8 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php @@ -0,0 +1,49 @@ + */ + public function paginate(array $filters, string $sort, string $direction, int $page, int $perPage): array + { + return $this->source->paginateChannel( + $filters, + $sort, + $direction, + $page, + $perPage, + self::SOURCE_CHANNEL, + 'dewu', + self::DATASET, + ); + } + + /** @return iterable> */ + public function exportRows(array $filters, string $sort = 'occurred_at', string $direction = 'asc'): iterable + { + return $this->source->exportChannelRows( + $filters, + $sort, + $direction, + self::SOURCE_CHANNEL, + 'dewu', + self::DATASET, + ); + } + + /** @return array{shops:array,bill_items:array} */ + public function filterOptions(): array + { + return $this->source->filterOptionsForChannel(self::SOURCE_CHANNEL, self::DATASET); + } +} diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index b94daeac..11f32e02 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -59,7 +59,7 @@ export default { data(){return{loading:false,loadError:false,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,balance:0,count:0},total:0,currentPage:1,lastPage:1,perPage:20,filters:{store_name:'',bill_item:'',start:'',end:'',keyword:''},filterOptions:{shops:[],bill_items:[]},filterOptionsLoading:false,filterOptionsError:false,requestSerial:0,sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible'};}, computed:{ isDouyin(){return this.billType==='douyin';}, - usesMirrorOptions(){return ['douyin','pinduoduo'].indexOf(this.billType)!==-1;}, + usesMirrorOptions(){return ['douyin','pinduoduo','dewu'].indexOf(this.billType)!==-1;}, invalidDateRange(){return Boolean(this.filters.start&&this.filters.end&&this.filters.start>this.filters.end);}, visibleColumns(){return this.configuredColumns.filter(column=>column.visible);}, visibleGroups(){return this.visibleColumns.reduce((groups,column)=>{if(!column.group)return groups;const last=groups[groups.length-1];if(last&&last.label===column.group)last.span+=1;else groups.push({label:column.group,span:1});return groups;},[]);}, diff --git a/tests/Feature/Business/DewuReceivingBillsTest.php b/tests/Feature/Business/DewuReceivingBillsTest.php new file mode 100644 index 00000000..4f7de9fc --- /dev/null +++ b/tests/Feature/Business/DewuReceivingBillsTest.php @@ -0,0 +1,124 @@ +allowPage(); + $filters = [ + 'store_name' => '得物-测试店', + 'bill_item' => '交易收入', + 'start' => '2026-08-01', + 'end' => '2026-08-31', + 'keyword' => '110211', + ]; + $repository = Mockery::mock(StoreReceivingDewuBillMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->with( + $filters, 'occurred_at', 'desc', 2, 20, + )->andReturn([ + 'current_page' => 2, + 'last_page' => 3, + 'per_page' => 20, + 'total' => 41, + 'data' => [[ + 'id' => '14654480', + 'record_code' => '2000000001248775179', + 'store_name' => '得物-测试店', + 'income' => 21.0, + 'expense' => 0.0, + 'payload' => [ + 'online_order_no' => '110211311661075313', + 'channel' => 'Dewu', + ], + ]], + 'summary' => ['income' => 21.0, 'expense' => 0.0, 'balance' => 21.0, 'count' => 41], + ]); + $this->app->instance(StoreReceivingDewuBillMirrorRepository::class, $repository); + + $this->withExceptionHandling() + ->loginAs() + ->getJson(route('ecommerce-finance.account-bills.index', [ + 'bill_type' => 'dewu', + ...$filters, + 'page' => 2, + 'limit' => 20, + ])) + ->assertOk() + ->assertJsonPath('data.0.payload.channel', 'Dewu') + ->assertJsonPath('columns.title', '得物账户') + ->assertJsonPath('summary.count', 41); + } + + public function test_filter_options_and_selected_column_export_use_the_same_mirror(): void + { + $this->allowPage(); + $repository = Mockery::mock(StoreReceivingDewuBillMirrorRepository::class); + $repository->shouldReceive('filterOptions')->once()->andReturn([ + 'shops' => ['得物-A店', '得物-B店'], + 'bill_items' => ['交易收入', '平台服务费'], + ]); + $repository->shouldReceive('exportRows')->once()->with( + ['store_name' => '得物-A店'], 'record_code', 'asc', + )->andReturn([[ + 'record_code' => '2000000001248775179', + 'store_name' => '得物-A店', + 'payload' => ['channel' => 'Dewu'], + ]]); + $this->app->instance(StoreReceivingDewuBillMirrorRepository::class, $repository); + + $this->loginAs() + ->withHeader('X-Requested-With', 'XMLHttpRequest') + ->get(route('ecommerce-finance.account-bills.filter-options', ['bill_type' => 'dewu'])) + ->assertOk() + ->assertExactJson([ + 'shops' => ['得物-A店', '得物-B店'], + 'bill_items' => ['交易收入', '平台服务费'], + ]); + + $response = $this->loginAs()->get(route('ecommerce-finance.account-bills.export', [ + 'bill_type' => 'dewu', + 'store_name' => '得物-A店', + 'sort' => 'record_code', + 'dir' => 'asc', + 'columns' => 'payload.channel,record_code,store_name', + ])); + + $response->assertOk() + ->assertHeader('content-type', 'text/csv; charset=UTF-8') + ->assertDownload('dewu_account_bills.csv'); + $csv = $response->streamedContent(); + $this->assertStringContainsString('渠道,记录编码,店铺', $csv); + $this->assertStringContainsString('Dewu,"=""2000000001248775179""",得物-A店', $csv); + } + + public function test_unready_mirror_returns_a_clear_retryable_response(): void + { + $this->allowPage(); + $repository = Mockery::mock(StoreReceivingDewuBillMirrorRepository::class); + $repository->shouldReceive('paginate')->once()->andThrow( + new RuntimeException('store_receiving_alipay_bill_mirror_not_ready') + ); + $this->app->instance(StoreReceivingDewuBillMirrorRepository::class, $repository); + + $this->loginAs() + ->withHeader('X-Requested-With', 'XMLHttpRequest') + ->get(route('ecommerce-finance.account-bills.index', ['bill_type' => 'dewu'])) + ->assertStatus(503) + ->assertJsonPath('message', '得物账户账单共享业务镜像正在首次同步,完成后将自动显示。'); + } + + private function allowPage(): void + { + $this->user->attachPermission( + Permission::where('name', 'read-admin-panel')->firstOrFail() + ); + } +} diff --git a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php index 7861c781..a92cb530 100644 --- a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php @@ -483,6 +483,12 @@ class BusinessMirrorSynchronizerTest extends TestCase $this->assertSame('jst_originalBillInfo', $pinduoduo->sourceObject()); $this->assertSame('js_jst_pdd_receiving_bill_rows', $pinduoduo->targetTable()); $this->assertSame(['channel' => 'PinduoduoImport'], $pinduoduo->fixedFilters()); + + $dewu = $datasets['jiansun.dbo.jst_originalBillInfo.dewu_receiving']; + $this->assertSame('jiansun', $dewu->sourceKey()); + $this->assertSame('jst_originalBillInfo', $dewu->sourceObject()); + $this->assertSame('js_jst_dewu_receiving_bill_rows', $dewu->targetTable()); + $this->assertSame(['channel' => 'Dewu'], $dewu->fixedFilters()); } /** @return array */ diff --git a/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php new file mode 100644 index 00000000..e97f98c8 --- /dev/null +++ b/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php @@ -0,0 +1,189 @@ + [ + 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'upstream_mirrors.datasets' => [ + StoreReceivingDewuBillMirrorRepository::DATASET => [ + 'source_key' => 'jiansun', 'schema' => 'dbo', + 'object' => 'jst_originalBillInfo', 'target' => 'js_jst_dewu_receiving_bill_rows', + 'keys' => ['Id'], + 'fixed_filters' => ['channel' => StoreReceivingDewuBillMirrorRepository::SOURCE_CHANNEL], + ], + StoreReceivingAlipayBillMirrorRepository::SHOP_DATASET => [ + 'source_key' => 'operations_replica', 'schema' => 'rpt', + 'object' => 'jst_shopInfo', 'target' => 'ops_jst_shop_info', 'keys' => ['Id'], + ], + ], + ]); + DB::purge('business_mirror'); + $schema = Schema::connection('business_mirror'); + $schema->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->dateTime('initial_completed_at')->nullable(); + $table->string('status')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->nullable(); + $table->boolean('mirror_row_count_is_exact')->default(false); + }); + $schema->create('js_jst_dewu_receiving_bill_rows', function (Blueprint $table): void { + $table->integer('Id'); + $table->integer('shop_id')->nullable(); + foreach (['channel', 'primary_key', 'fee_name', 'inout_type', 'p_auto_id', 'shop_i_id', 'shop_sku_id', 'sku_id', 'so_id', 'combine_type'] as $column) { + $table->string($column)->nullable(); + } + $table->dateTime('fee_time')->nullable(); + $table->dateTime('createTime')->nullable(); + $table->dateTime('updateTime')->nullable(); + $table->bigInteger('auto_id')->nullable(); + $table->decimal('amount', 20, 6)->nullable(); + }); + $schema->create('ops_jst_shop_info', function (Blueprint $table): void { + $table->integer('Id'); + $table->integer('shop_id')->nullable(); + $table->string('shop_name')->nullable(); + }); + + $source = new StoreReceivingAlipayBillMirrorRepository( + new BusinessMirrorDatasetRegistry(), new GenericBusinessMirrorRepository(app('db')), + ); + $this->repository = new StoreReceivingDewuBillMirrorRepository($source); + $this->markReady(); + } + + public function test_it_reads_only_the_dewu_dataset_and_maps_available_source_fields(): void + { + DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ + ['Id' => 10, 'shop_id' => 7, 'shop_name' => '得物-测试店'], + ['Id' => 11, 'shop_id' => 8, 'shop_name' => '其他店'], + ]); + DB::connection('business_mirror')->table('js_jst_dewu_receiving_bill_rows')->insert([ + $this->row(1, 7, '2026-09-13 18:48:12', '1', 21.00, '交易收入'), + $this->row(2, 7, '2026-09-13 19:00:00', '-1', 18.07, '平台服务费'), + ]); + + $result = $this->repository->paginate([], 'occurred_at', 'desc', 1, 10); + + $this->assertSame(2, $result['total']); + $this->assertSame('200000000000000002', $result['data'][0]['record_code']); + $this->assertSame('得物-测试店', $result['data'][0]['store_name']); + $this->assertSame('110211-ORDER-2', $result['data'][0]['order_no']); + $this->assertSame('Dewu', $result['data'][0]['payload']['channel']); + $this->assertSame('支出', $result['data'][0]['payload']['business_type']); + $this->assertSame('SKU-2', $result['data'][0]['payload']['goods_no']); + $this->assertSame('聚水潭', $result['data'][0]['modifier']); + $this->assertSame(21.0, $result['summary']['income']); + $this->assertSame(18.07, $result['summary']['expense']); + $this->assertSame(2.93, $result['summary']['balance']); + } + + public function test_filters_options_export_and_exact_total_use_the_fixed_channel_slice(): void + { + DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ + ['Id' => 10, 'shop_id' => 7, 'shop_name' => '得物-A店'], + ['Id' => 11, 'shop_id' => 8, 'shop_name' => '得物-B店'], + ]); + DB::connection('business_mirror')->table('js_jst_dewu_receiving_bill_rows')->insert([ + $this->row(1, 7, '2026-08-12 09:00:00', '1', 22.80, '交易收入'), + $this->row(2, 8, '2026-08-13 09:00:00', '-1', 0.14, '平台服务费'), + ]); + $connection = DB::connection('business_mirror'); + $connection->table('business_mirror_table_states') + ->where('dataset_key', StoreReceivingDewuBillMirrorRepository::DATASET) + ->update(['mirror_row_count' => 2, 'mirror_row_count_is_exact' => true]); + $connection->enableQueryLog(); + $connection->flushQueryLog(); + + $unfiltered = $this->repository->paginate([], 'record_code', 'asc', 1, 10); + $filtered = $this->repository->paginate([ + 'store_name' => 'A店', + 'bill_item' => '交易', + 'start' => '2026-08-12', + 'end' => '2026-08-12', + 'keyword' => '110211-ORDER-1', + ], 'record_code', 'asc', 1, 10); + $options = $this->repository->filterOptions(); + $export = iterator_to_array($this->repository->exportRows(['bill_item' => '平台服务费'])); + + $this->assertSame(2, $unfiltered['total']); + $this->assertSame(1, $filtered['total']); + $this->assertSame('200000000000000001', $filtered['data'][0]['record_code']); + $this->assertSame(['得物-A店', '得物-B店'], $options['shops']); + $this->assertSame(['交易收入', '平台服务费'], $options['bill_items']); + $this->assertCount(1, $export); + $this->assertSame('200000000000000002', $export[0]['record_code']); + + $targetQueries = array_filter( + $connection->getQueryLog(), + static fn (array $query): bool => str_contains($query['query'], 'js_jst_dewu_receiving_bill_rows'), + ); + $this->assertNotEmpty($targetQueries); + $this->assertCount(0, array_filter( + $targetQueries, + static fn (array $query): bool => str_contains($query['query'], '"b"."channel" = ?'), + )); + $connection->disableQueryLog(); + } + + private function markReady(): void + { + foreach ([StoreReceivingDewuBillMirrorRepository::DATASET, StoreReceivingAlipayBillMirrorRepository::SHOP_DATASET] as $dataset) { + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => $dataset, + 'initial_completed_at' => '2026-09-14 09:00:00', + 'status' => 'succeeded', + 'last_succeeded_at' => '2026-09-14 09:00:00', + ]); + } + } + + private function row( + int $id, + int $shopId, + string $time, + string $direction, + float $amount, + string $feeName, + ): array { + return [ + 'Id' => $id, + 'shop_id' => $shopId, + 'channel' => 'Dewu', + 'primary_key' => 'KEY-' . $id, + 'fee_name' => $feeName, + 'inout_type' => $direction, + 'p_auto_id' => 'P-' . $id, + 'shop_i_id' => 'ITEM-' . $id, + 'shop_sku_id' => 'SHOP-SKU-' . $id, + 'sku_id' => 'SKU-' . $id, + 'so_id' => '110211-ORDER-' . $id, + 'combine_type' => 'normal', + 'fee_time' => $time, + 'createTime' => '2026-09-14 13:00:48', + 'updateTime' => '2026-09-14 13:02:32', + 'auto_id' => 200000000000000000 + $id, + 'amount' => $amount, + ]; + } +} diff --git a/tests/Unit/View/AccountBillsTableTest.php b/tests/Unit/View/AccountBillsTableTest.php index ff92c907..119f2d83 100644 --- a/tests/Unit/View/AccountBillsTableTest.php +++ b/tests/Unit/View/AccountBillsTableTest.php @@ -11,7 +11,7 @@ class AccountBillsTableTest extends TestCase $source = file_get_contents(__DIR__ . '/../../../resources/assets/js/components/business/AccountBills.vue'); $this->assertStringContainsString("isDouyin(){return this.billType==='douyin';}", $source); - $this->assertStringContainsString("['douyin','pinduoduo'].indexOf(this.billType)!==-1", $source); + $this->assertStringContainsString("['douyin','pinduoduo','dewu'].indexOf(this.billType)!==-1", $source); $this->assertStringContainsString('v-if="usesMirrorOptions && !filterOptionsError"', $source); $this->assertStringContainsString('page-key="store-receiving-bills"', $source); $this->assertStringContainsString(':tab-key="billType"', $source); From 8f150080c582b3625e5925ea6b75d5f4a1912f66 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 15 Sep 2026 11:39:09 +0800 Subject: [PATCH 003/249] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E8=81=9A=E6=B0=B4?= =?UTF-8?q?=E6=BD=AD=E6=88=90=E6=9C=AC=E4=BB=B7=E5=8E=86=E5=8F=B2=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E8=BE=B9=E7=95=8C=E4=B8=8E=E6=9C=AA=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=8A=B6=E6=80=81=20(#186)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 保留完整成本价历史方案,区分经典接口凭据与新开放平台凭据;首次同步未完成时显示待同步,不误报 0 条。 验证:33 passed,260 assertions。 --- .../SyncJushuitanCostPriceHistory.php | 8 ++- app/Http/Controllers/Business/Pages.php | 10 ++++ config/services.php | 12 ++--- docs/上游业务镜像清单.md | 2 +- .../ProductCatalogMirrorRepository.php | 4 +- .../Services/JushuitanOpenApiClient.php | 15 +++++- .../normal-products.blade.php | 29 +++++++++- .../Business/ProductCatalogPageTest.php | 54 +++++++++++++++++++ .../JushuitanOpenApiClientTest.php | 31 ++++++++++- .../ProductCatalogMirrorRepositoryTest.php | 2 + 10 files changed, 152 insertions(+), 15 deletions(-) diff --git a/app/Console/Commands/SyncJushuitanCostPriceHistory.php b/app/Console/Commands/SyncJushuitanCostPriceHistory.php index 61dd2d4a..110ab52b 100644 --- a/app/Console/Commands/SyncJushuitanCostPriceHistory.php +++ b/app/Console/Commands/SyncJushuitanCostPriceHistory.php @@ -35,13 +35,17 @@ class SyncJushuitanCostPriceHistory extends Command ); } catch (Throwable $exception) { Log::error('聚水潭历史成本价镜像同步失败。', ['exception' => $exception::class]); - $this->error('聚水潭成本价历史同步失败,已保留上一版共享数据。'); + $this->error(match ($exception->getMessage()) { + 'jushuitan_classic_api_credentials_missing' => '聚水潭经典开放接口凭据未配置,请配置 partnerid、partnerkey 和 token。', + 'jushuitan_classic_api_partner_id_invalid' => '聚水潭经典开放接口 partnerid 无效,请核对同一应用的 partnerid、partnerkey 和 token。', + default => '聚水潭成本价历史同步失败,已保留上一版共享数据。', + }); return self::FAILURE; } if ($result['status'] === 'requires_full_sync') { - $this->warn('聚水潭成本价历史尚未完成首次全量同步,请在凭据和备份确认后显式使用 --full。'); + $this->warn('聚水潭成本价历史尚未完成首次全量同步,请配置经典开放接口凭据后显式使用 --full。'); return self::SUCCESS; } diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 3d5a9dca..ba531d40 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -2307,6 +2307,11 @@ class Pages extends Controller 'initialized' => false, 'last_succeeded_at' => null, ], + 'productCatalogJushuitanCostPriceHistorySyncStatus' => $result['jushuitan_cost_price_history_sync_status'] ?? [ + 'code' => 'unavailable', + 'initialized' => false, + 'last_succeeded_at' => null, + ], ]; } catch (Throwable $exception) { report($exception); @@ -2586,6 +2591,11 @@ class Pages extends Controller 'initialized' => false, 'last_succeeded_at' => null, ], + 'productCatalogJushuitanCostPriceHistorySyncStatus' => [ + 'code' => 'unavailable', + 'initialized' => false, + 'last_succeeded_at' => null, + ], ]; } diff --git a/config/services.php b/config/services.php index 33c52cf5..58b7392b 100644 --- a/config/services.php +++ b/config/services.php @@ -59,12 +59,12 @@ return [ 'jushuitan' => [ // 聚水潭开放平台凭据只从私有 runtime/.env 读取,不进入代码仓库。 - // 商品操作日志仍使用经典开放接口;兼容现有 APP_* 环境变量名, - // 实际含义依次为 partnerid、partnerkey、token。 - 'base_url' => env('JUSHUITAN_OPEN_API_URL', 'https://open.erp321.com/api/open/query.aspx'), - 'partner_id' => env('JUSHUITAN_PARTNER_ID', env('JUSHUITAN_APP_KEY')), - 'partner_key' => env('JUSHUITAN_PARTNER_KEY', env('JUSHUITAN_APP_SECRET')), - 'token' => env('JUSHUITAN_TOKEN', env('JUSHUITAN_ACCESS_TOKEN')), + // 商品操作日志使用经典开放接口。经典接口的 partnerid / partnerkey / token + // 与新开放平台的 App Key / App Secret / Access Token 不是同一套凭据,禁止混用。 + 'base_url' => env('JUSHUITAN_CLASSIC_API_URL', 'https://open.erp321.com/api/open/query.aspx'), + 'partner_id' => env('JUSHUITAN_PARTNER_ID'), + 'partner_key' => env('JUSHUITAN_PARTNER_KEY'), + 'token' => env('JUSHUITAN_TOKEN'), 'timeout' => (int) env('JUSHUITAN_OPEN_API_TIMEOUT', 20), 'product_operation_history_method' => 'worklog.query', 'cost_price_history_start' => env('JUSHUITAN_COST_PRICE_HISTORY_START', '2000-01-01 00:00:00'), diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index ed4ccf1b..8f58b741 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -29,7 +29,7 @@ | 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | -| 本次接入 | 普通商品成本价变更读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;审计历史按稳定记录键只追加或更新,全量回补不删除旧记录;页面按商品编码分别展示聚水潭成本价记录和工作平台价格记录,不混用来源。 | +| 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 | ## 经营分析副本库(operations_replica) diff --git a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php index 2d3e147d..0f49c1aa 100644 --- a/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/ProductCatalogMirrorRepository.php @@ -112,7 +112,8 @@ class ProductCatalogMirrorRepository * total:int, * purchase_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, * price_change_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, - * work_platform_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string} + * work_platform_price_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string}, + * jushuitan_cost_price_history_sync_status:array{code:string,initialized:bool,last_succeeded_at:?string} * } */ public function paginate(array $filters, int $page, int $perPage): array @@ -147,6 +148,7 @@ class ProductCatalogMirrorRepository 'purchase_price_sync_status' => $purchasePriceSyncStatus, 'price_change_sync_status' => $priceChangeSyncStatus, 'work_platform_price_sync_status' => $workPlatformPriceSyncStatus, + 'jushuitan_cost_price_history_sync_status' => $jushuitanCostPriceHistorySyncStatus, ]; } diff --git a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php index 4f68fec3..c5b37720 100644 --- a/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php +++ b/modules/EcommerceFinance/Services/JushuitanOpenApiClient.php @@ -41,7 +41,7 @@ class JushuitanOpenApiClient $partnerKey = trim((string) config('services.jushuitan.partner_key')); $token = trim((string) config('services.jushuitan.token')); if ($partnerId === '' || $partnerKey === '' || $token === '') { - throw new RuntimeException('jushuitan_api_credentials_missing'); + throw new RuntimeException('jushuitan_classic_api_credentials_missing'); } $method = (string) config( @@ -81,12 +81,23 @@ class JushuitanOpenApiClient } $code = (int) ($payload['code'] ?? -1); if ($code !== 0) { - throw new RuntimeException('jushuitan_api_code_' . $code); + throw new RuntimeException($this->errorCode($code, $payload)); } return $payload; } + /** @param array $payload */ + private function errorCode(int $code, array $payload): string + { + $message = mb_strtolower(trim((string) ($payload['msg'] ?? $payload['message'] ?? ''))); + if ($code === 100 && str_contains($message, 'partnerid')) { + return 'jushuitan_classic_api_partner_id_invalid'; + } + + return 'jushuitan_api_code_' . $code; + } + private function sign( string $method, string $partnerId, diff --git a/resources/views/business/pages/product-inventory/normal-products.blade.php b/resources/views/business/pages/product-inventory/normal-products.blade.php index f4db1af5..5686b786 100644 --- a/resources/views/business/pages/product-inventory/normal-products.blade.php +++ b/resources/views/business/pages/product-inventory/normal-products.blade.php @@ -19,6 +19,11 @@ 'initialized' => false, 'last_succeeded_at' => null, ]; + $productCatalogJushuitanCostPriceHistorySyncStatus = $content['productCatalogJushuitanCostPriceHistorySyncStatus'] ?? [ + 'code' => 'unavailable', + 'initialized' => false, + 'last_succeeded_at' => null, + ]; $hasFilters = collect($productCatalogFilters)->contains( static fn ($value) => $value !== null && $value !== '' ); @@ -773,6 +778,25 @@ @endif + @if (!($productCatalogJushuitanCostPriceHistorySyncStatus['initialized'] ?? false) && !$productCatalogError) +
+ + + @if (($productCatalogJushuitanCostPriceHistorySyncStatus['code'] ?? '') === 'initializing') + 聚水潭成本价记录正在执行首次同步,完成前不显示记录数量。 + @elseif (($productCatalogJushuitanCostPriceHistorySyncStatus['code'] ?? '') === 'initial_failed') + 聚水潭成本价记录首次同步失败,当前记录数量不代表聚水潭真实历史。 + @else + 聚水潭成本价记录尚未完成首次同步,完成前不显示记录数量。 + @endif + +
+ @endif +
@@ -854,6 +878,7 @@ @php $jushuitanHistory = $row->jushuitan_cost_price_history ?? []; $jushuitanHistoryCount = (int) ($row->jushuitan_cost_price_history_count ?? count($jushuitanHistory)); + $jushuitanHistoryInitialized = (bool) ($productCatalogJushuitanCostPriceHistorySyncStatus['initialized'] ?? false); $jushuitanHistoryId = 'product-jushuitan-cost-history-' . (int) ($row->autoid ?? 0); $workPlatformHistory = $row->work_platform_price_history ?? $row->price_change_history ?? []; $workPlatformHistoryCount = (int) ($row->work_platform_price_history_count ?? $row->price_change_history_count ?? count($workPlatformHistory)); @@ -872,12 +897,12 @@ data-cost-price="{{ $row->cost_price ?? '' }}" data-work-platform-price="{{ $row->work_platform_price ?? '' }}" aria-label="查看 {{ $row->sku_id ?? '当前商品' }} 的聚水潭成本价记录" - title="{{ $jushuitanHistoryCount > 0 ? '查看聚水潭成本价记录' : '当前商品暂无聚水潭成本价记录' }}" + title="{{ !$jushuitanHistoryInitialized ? '聚水潭成本价记录尚未完成首次同步' : ($jushuitanHistoryCount > 0 ? '查看聚水潭成本价记录' : '当前商品暂无聚水潭成本价记录') }}" @disabled($jushuitanHistoryCount === 0) > - {{ $jushuitanHistoryCount }} 条 + {{ $jushuitanHistoryInitialized ? $jushuitanHistoryCount . ' 条' : '待同步' }} diff --git a/tests/Feature/Business/ProductCatalogPageTest.php b/tests/Feature/Business/ProductCatalogPageTest.php index 4c84c1c1..abbdbdff 100644 --- a/tests/Feature/Business/ProductCatalogPageTest.php +++ b/tests/Feature/Business/ProductCatalogPageTest.php @@ -142,6 +142,11 @@ class ProductCatalogPageTest extends FeatureTestCase 'initialized' => true, 'last_succeeded_at' => '2026-09-01 03:02:00', ], + 'jushuitan_cost_price_history_sync_status' => [ + 'code' => 'ready', + 'initialized' => true, + 'last_succeeded_at' => '2026-09-15 00:05:00', + ], ]); $this->app->instance(ProductCatalogMirrorRepository::class, $repository); @@ -221,6 +226,55 @@ class ProductCatalogPageTest extends FeatureTestCase ->assertDontSee('pic_url'); } + public function test_normal_products_page_does_not_report_zero_jushuitan_history_before_initial_sync(): void + { + $this->grantAdminPermission(); + + $state = [ + 'status' => 'succeeded', + 'initial_completed_at' => '2026-08-14 21:15:36', + 'last_succeeded_at' => '2026-09-15 10:00:00', + 'mirror_row_count' => 558035, + ]; + $repository = \Mockery::mock(ProductCatalogMirrorRepository::class); + $repository->shouldReceive('available')->once()->andReturnTrue(); + $repository->shouldReceive('state')->once()->andReturn($state); + $repository->shouldReceive('syncStatus')->once()->with($state)->andReturn([ + 'code' => 'healthy', + 'lag_minutes' => 2, + ]); + $repository->shouldReceive('ready')->once()->andReturnTrue(); + $repository->shouldReceive('paginate')->once()->andReturn([ + 'data' => [(object) [ + 'autoid' => 15961, + 'sku_id' => '15961G', + 'name' => '测试商品', + 'cost_price' => 65, + 'jushuitan_cost_price_history' => [], + 'jushuitan_cost_price_history_count' => 0, + ]], + 'total' => 1, + 'jushuitan_cost_price_history_sync_status' => [ + 'code' => 'initial_failed', + 'initialized' => false, + 'last_succeeded_at' => null, + ], + ]); + $this->app->instance(ProductCatalogMirrorRepository::class, $repository); + + $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', + 'page' => 'normal-products', + 'sku_id' => '15961G', + ])) + ->assertOk() + ->assertSee('data-jushuitan-cost-price-history-sync-state="initial_failed"', false) + ->assertSeeText('聚水潭成本价记录首次同步失败') + ->assertSeeText('当前记录数量不代表聚水潭真实历史') + ->assertSeeText('待同步') + ->assertSee('title="聚水潭成本价记录尚未完成首次同步"', false); + } + public function test_normal_products_export_uses_all_filters_and_includes_data_source_column(): void { $this->grantAdminPermission(); diff --git a/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php b/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php index beb93128..a4a5e9ff 100644 --- a/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php +++ b/tests/Unit/EcommerceFinance/JushuitanOpenApiClientTest.php @@ -136,7 +136,7 @@ class JushuitanOpenApiClientTest extends TestCase (new JushuitanOpenApiClient())->getCostPriceOperationHistory(now(), now(), 1, 100); $this->fail('Expected missing credential exception.'); } catch (RuntimeException $exception) { - $this->assertSame('jushuitan_api_credentials_missing', $exception->getMessage()); + $this->assertSame('jushuitan_classic_api_credentials_missing', $exception->getMessage()); } config()->set('services.jushuitan.token', 'test-token'); @@ -145,4 +145,33 @@ class JushuitanOpenApiClientTest extends TestCase $this->expectExceptionMessage('jushuitan_api_code_10001'); (new JushuitanOpenApiClient())->getCostPriceOperationHistory(now(), now(), 1, 100); } + + public function test_it_reports_an_invalid_classic_partner_id_without_exposing_upstream_text(): void + { + Http::fake(['*' => Http::response([ + 'code' => 100, + 'msg' => '验证失败! partnerid 无效', + ])]); + + $this->expectExceptionMessage('jushuitan_classic_api_partner_id_invalid'); + (new JushuitanOpenApiClient())->getCostPriceOperationHistory(now(), now(), 1, 50); + } + + public function test_new_platform_app_credentials_do_not_replace_classic_credentials(): void + { + config()->set('services.jushuitan.partner_id', null); + config()->set('services.jushuitan.partner_key', null); + config()->set('services.jushuitan.token', null); + config()->set('services.jushuitan.app_key', 'new-platform-app-key'); + config()->set('services.jushuitan.app_secret', 'new-platform-app-secret'); + config()->set('services.jushuitan.access_token', 'new-platform-access-token'); + + try { + (new JushuitanOpenApiClient())->getCostPriceOperationHistory(now(), now(), 1, 50); + $this->fail('Expected missing classic credential exception.'); + } catch (RuntimeException $exception) { + $this->assertSame('jushuitan_classic_api_credentials_missing', $exception->getMessage()); + } + Http::assertNothingSent(); + } } diff --git a/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php index a724ac58..6184348a 100644 --- a/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/ProductCatalogMirrorRepositoryTest.php @@ -303,6 +303,8 @@ class ProductCatalogMirrorRepositoryTest extends TestCase $this->assertSame('聚水潭商品及库存管理', $row->jushuitan_cost_price_history[0]['source']); $this->assertSame('66.5', (string) $row->jushuitan_cost_price_history[0]['cost_price']); $this->assertSame('简尚', $row->jushuitan_cost_price_history[0]['operator']); + $this->assertSame('ready', $result['jushuitan_cost_price_history_sync_status']['code']); + $this->assertTrue($result['jushuitan_cost_price_history_sync_status']['initialized']); $this->assertSame(1, $row->work_platform_price_history_count); $this->assertSame('工作平台价格', $row->work_platform_price_history[0]['source']); $this->assertSame('68', (string) $row->work_platform_price_history[0]['after_price']); From 9dbdef5e2e70820af3419a77ceebfbd32f743eef Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 15 Sep 2026 11:44:20 +0800 Subject: [PATCH 004/249] =?UTF-8?q?=E6=AF=8F=E6=97=A5=E5=95=86=E5=93=81?= =?UTF-8?q?=E4=BB=93=E5=82=A8=E8=B4=B9=E6=98=8E=E7=BB=86=20(#187)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 增加逐日逐商品仓储费明细、日期切换、Excel 导出和公司数据隔离。 --- ...hirdPartyWarehouseStorageFeeCalculator.php | 21 +++- ...dPartyWarehouseStorageSettlementExport.php | 46 ++++++- .../Business/ThirdPartyWarehouseQuotes.php | 112 +++++++++++++++++- .../third-party-warehouse-quotes.blade.php | 111 ++++++++++++++++- .../ThirdPartyWarehouseQuotePageTest.php | 86 ++++++++++++++ ...PartyWarehouseStorageFeeCalculatorTest.php | 19 +++ 6 files changed, 384 insertions(+), 11 deletions(-) diff --git a/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php b/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php index 73f8875b..b1fe3902 100644 --- a/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php +++ b/app/Business/ThirdPartyWarehouseStorageFeeCalculator.php @@ -37,7 +37,7 @@ class ThirdPartyWarehouseStorageFeeCalculator } /** - * @return array{summary:array,daily:list>,per_sku:list>} + * @return array{summary:array,daily:list>,per_sku:list>,daily_sku:list>} */ public function calculate(int $warehouseId, string $warehouseName, string $period): array { @@ -63,6 +63,10 @@ class ThirdPartyWarehouseStorageFeeCalculator $daily = []; /** @var array> $skus */ $skus = []; + $dailySku = []; + $storagePerPiecePerDay = $days > 0 && $piecesPerPallet > 0 + ? $palletArea * $sqmRate / $piecesPerPallet / $days + : 0.0; foreach ($this->mirror->exportRows(['dimension' => 'month', 'period' => $period], 5000) as $row) { $date = trim((string) ($row['date'] ?? '')); @@ -90,6 +94,20 @@ class ThirdPartyWarehouseStorageFeeCalculator $daily[$date]['inbound_qty'] += $inboundQty; $daily[$date]['outbound_qty'] += $outboundQty; + $dailySku[] = [ + 'date' => $date, + 'owner' => (string) ($row['owner'] ?? ''), + 'sku_code' => $code, + 'product_name' => (string) ($row['product_name'] ?? ''), + 'supplier' => (string) ($row['supplier'] ?? ''), + 'category' => (string) ($row['category'] ?? ''), + 'unit' => (string) ($row['unit'] ?? ''), + 'opening' => round($opening, 2), + 'net_movement' => round($closing - $opening, 2), + 'closing' => round($closing, 2), + 'storage_fee' => round($closing * $storagePerPiecePerDay, 6), + ]; + if (! isset($skus[$code])) { $skus[$code] = [ 'owner' => (string) ($row['owner'] ?? ''), @@ -198,6 +216,7 @@ class ThirdPartyWarehouseStorageFeeCalculator ], 'daily' => $dailyRows, 'per_sku' => $perSku, + 'daily_sku' => $dailySku, ]; } } diff --git a/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php b/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php index 0b7eb648..f158198c 100644 --- a/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php +++ b/app/Exports/ThirdPartyWarehouseStorageSettlementExport.php @@ -11,13 +11,14 @@ use Maatwebsite\Excel\Concerns\WithMultipleSheets; use Maatwebsite\Excel\Concerns\WithTitle; /** - * 三方仓仓储费核算明细导出:汇总 / 进销存数据汇总(每日) / 进销存(逐商品) 三张表。 + * 三方仓仓储费核算明细导出:汇总 / 进销存数据汇总(每日) / 进销存(逐商品) / + * 每日商品仓储费四张表。 * 数据来自 ThirdPartyWarehouseStorageFeeCalculator 的核算结果(或存档快照)。 */ class ThirdPartyWarehouseStorageSettlementExport implements WithMultipleSheets { /** - * @param array{summary:array,daily:list>,per_sku:list>} $result + * @param array{summary:array,daily:list>,per_sku:list>,daily_sku?:list>} $result */ public function __construct(private readonly array $result) { @@ -30,6 +31,7 @@ class ThirdPartyWarehouseStorageSettlementExport implements WithMultipleSheets new StorageSettlementSummarySheet($this->result['summary']), new StorageSettlementDailySheet($this->result['summary'], $this->result['daily']), new StorageSettlementSkuSheet($this->result['per_sku']), + new StorageSettlementDailySkuSheet($this->result['daily_sku'] ?? []), ]; } } @@ -184,3 +186,43 @@ class StorageSettlementSkuSheet implements FromArray, WithHeadings, WithTitle ], $this->perSku); } } + +class StorageSettlementDailySkuSheet implements FromArray, WithHeadings, WithTitle +{ + /** @param list> $dailySku */ + public function __construct(private readonly array $dailySku) + { + } + + public function title(): string + { + return '每日商品仓储费'; + } + + /** @return array */ + public function headings(): array + { + return [ + '日期', '货主', '商品编码', '商品名称', '供应商', '分类', '单位', + '上日结余', '当日进出净额', '当日库存结余', '当天仓储费', + ]; + } + + /** @return array> */ + public function array(): array + { + return array_map(static fn (array $row): array => [ + $row['date'], + $row['owner'], + $row['sku_code'], + $row['product_name'], + $row['supplier'], + $row['category'], + $row['unit'], + (float) $row['opening'], + (float) $row['net_movement'], + (float) $row['closing'], + (float) $row['storage_fee'], + ], $this->dailySku); + } +} diff --git a/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php b/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php index 083d837e..6e7a992c 100644 --- a/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php +++ b/app/Http/Livewire/Business/ThirdPartyWarehouseQuotes.php @@ -45,6 +45,15 @@ class ThirdPartyWarehouseQuotes extends Component public ?string $settlementError = null; + public ?string $settlementDetailPeriod = null; + + public string $settlementDetailDate = ''; + + /** @var list */ + public array $settlementDetailDates = []; + + public ?string $settlementDetailMessage = null; + public function mount(): void { $this->effectiveAt = now()->toDateString(); @@ -130,7 +139,11 @@ class ThirdPartyWarehouseQuotes extends Component 'loss_fee' => $summary['loss_fee'], 'compensation_fee' => $summary['compensation_fee'], 'total_fee' => $summary['total_fee'], - 'detail_json' => ['daily' => $result['daily'], 'per_sku' => $result['per_sku']], + 'detail_json' => [ + 'daily' => $result['daily'], + 'per_sku' => $result['per_sku'], + 'daily_sku' => $result['daily_sku'], + ], 'calculated_by' => (int) user_id(), ], ); @@ -144,6 +157,7 @@ class ThirdPartyWarehouseQuotes extends Component $this->ensureAuthenticated(); $settlement = ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) ->where('warehouse_id', self::WAREHOUSE_ID) ->where('period', $period) ->first(); @@ -154,11 +168,12 @@ class ThirdPartyWarehouseQuotes extends Component return null; } - $detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => []]; + $detail = $settlement->detail_json ?: ['daily' => [], 'per_sku' => [], 'daily_sku' => []]; $result = [ 'summary' => $this->summaryFromSettlement($settlement), 'daily' => $detail['daily'] ?? [], 'per_sku' => $detail['per_sku'] ?? [], + 'daily_sku' => $detail['daily_sku'] ?? [], ]; $fileName = $settlement->warehouse_name . '仓储费用_' . $period . '.xlsx'; @@ -166,11 +181,51 @@ class ThirdPartyWarehouseQuotes extends Component return Excel::download(new ThirdPartyWarehouseStorageSettlementExport($result), $fileName); } + public function viewSettlementDetails(string $period): void + { + $this->ensureAuthenticated(); + abort_unless(preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1, 422); + + $this->settlementDetailPeriod = $period; + $this->settlementDetailDate = ''; + $this->settlementDetailDates = []; + $this->settlementDetailMessage = null; + + $settlement = $this->settlementForPeriod($period); + if ($settlement === null) { + $this->settlementDetailMessage = '未找到 ' . $period . ' 的核算存档。'; + + return; + } + + $detail = $settlement->detail_json ?: []; + $dailySku = $detail['daily_sku'] ?? []; + if ($dailySku === []) { + $this->settlementDetailMessage = $period . ' 的原存档没有每日商品明细,请重新核算该月份后查看。'; + + return; + } + + $dates = array_values(array_unique(array_column($dailySku, 'date'))); + sort($dates); + $this->settlementDetailDates = $dates; + $this->settlementDetailDate = $dates[0] ?? ''; + } + + public function closeSettlementDetails(): void + { + $this->settlementDetailPeriod = null; + $this->settlementDetailDate = ''; + $this->settlementDetailDates = []; + $this->settlementDetailMessage = null; + } + public function render(): View { $data = $this->repository()->pageData(); $history = ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) ->where('warehouse_id', self::WAREHOUSE_ID) ->orderByDesc('period') ->limit(24) @@ -184,12 +239,15 @@ class ThirdPartyWarehouseQuotes extends Component 'calculated_at' => optional($row->updated_at)->format('Y-m-d H:i'), ]) ->all(); + $settlementDetail = $this->settlementDetailData(); return view('business.pages.courier-payables.partials.third-party-warehouse-quotes', [ 'warehouseQuotes' => $data['rows'], 'warehouseQuoteSummary' => $data['summary'], 'warehouseQuotesReady' => $data['ready'], 'settlementHistory' => $history, + 'settlementDetailRows' => $settlementDetail['rows'], + 'settlementDetailSummary' => $settlementDetail['summary'], ]); } @@ -219,6 +277,56 @@ class ThirdPartyWarehouseQuotes extends Component ]; } + /** + * 明细行只参与当前服务端渲染,不进入 Livewire 公共快照,避免日期切换时回传整张表。 + * + * @return array{rows:list>,summary:array|null} + */ + private function settlementDetailData(): array + { + $empty = ['rows' => [], 'summary' => null]; + + if ($this->settlementDetailPeriod === null + || ! in_array($this->settlementDetailDate, $this->settlementDetailDates, true)) { + return $empty; + } + + $settlement = $this->settlementForPeriod($this->settlementDetailPeriod); + if ($settlement === null) { + return $empty; + } + + $detail = $settlement->detail_json ?: []; + $rows = array_values(array_filter( + $detail['daily_sku'] ?? [], + fn (array $row): bool => ($row['date'] ?? null) === $this->settlementDetailDate, + )); + usort($rows, static fn (array $left, array $right): int => strcmp( + (string) ($left['sku_code'] ?? ''), + (string) ($right['sku_code'] ?? ''), + )); + + return [ + 'rows' => $rows, + 'summary' => [ + 'sku_count' => count($rows), + 'opening' => array_sum(array_column($rows, 'opening')), + 'net_movement' => array_sum(array_column($rows, 'net_movement')), + 'closing' => array_sum(array_column($rows, 'closing')), + 'storage_fee' => array_sum(array_column($rows, 'storage_fee')), + ], + ]; + } + + private function settlementForPeriod(string $period): ?ThirdPartyWarehouseStorageSettlement + { + return ThirdPartyWarehouseStorageSettlement::query() + ->where('company_id', (int) company_id()) + ->where('warehouse_id', self::WAREHOUSE_ID) + ->where('period', $period) + ->first(); + } + /** @return array> */ protected function rules(): array { diff --git a/resources/views/business/pages/courier-payables/partials/third-party-warehouse-quotes.blade.php b/resources/views/business/pages/courier-payables/partials/third-party-warehouse-quotes.blade.php index 22c16d7e..ed7f631c 100644 --- a/resources/views/business/pages/courier-payables/partials/third-party-warehouse-quotes.blade.php +++ b/resources/views/business/pages/courier-payables/partials/third-party-warehouse-quotes.blade.php @@ -26,10 +26,10 @@ .warehouse-quote-field { display:grid; min-width:0; gap:.35rem; } .warehouse-quote-field--wide { grid-column:span 2; } .warehouse-quote-field label { color:var(--quote-muted); font-size:.75rem; font-weight:600; } - .warehouse-quote-field input,.warehouse-quote-field textarea { width:100%; min-width:0; border:1px solid var(--quote-border); border-radius:.5rem; background:#fff; color:var(--quote-ink); font:inherit; } - .warehouse-quote-field input { height:34px; padding:0 .625rem; } + .warehouse-quote-field input,.warehouse-quote-field select,.warehouse-quote-field textarea { width:100%; min-width:0; border:1px solid var(--quote-border); border-radius:.5rem; background:#fff; color:var(--quote-ink); font:inherit; } + .warehouse-quote-field input,.warehouse-quote-field select { height:34px; padding:0 .625rem; } .warehouse-quote-field textarea { min-height:34px; padding:.5rem .625rem; resize:vertical; } - .warehouse-quote-field input:focus,.warehouse-quote-field textarea:focus { border-color:var(--quote-accent); outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.2); } + .warehouse-quote-field input:focus,.warehouse-quote-field select:focus,.warehouse-quote-field textarea:focus { border-color:var(--quote-accent); outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.2); } .warehouse-quote-formulas { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:1px; margin:0 1rem 1rem; overflow:hidden; border:1px solid var(--quote-border); border-radius:.5rem; background:var(--quote-border); } .warehouse-quote-formula { min-width:0; padding:.7rem .75rem; background:#FCFAF5; } .warehouse-quote-formula dt { color:var(--quote-muted); font-size:.7rem; font-weight:600; } @@ -66,8 +66,34 @@ .warehouse-quote-card dt { color:var(--quote-muted); font-size:.7rem; font-weight:600; } .warehouse-quote-card dd { margin:.2rem 0 0; font-size:1rem; font-weight:700; font-variant-numeric:tabular-nums; } .warehouse-quote-card--total dd { color:var(--quote-accent); } + .warehouse-settlement-actions { display:flex; align-items:center; gap:.65rem; } + .warehouse-settlement-detail { border-top:1px solid var(--quote-border); } + .warehouse-settlement-detail__head { display:flex; align-items:flex-end; justify-content:space-between; gap:1rem; padding:1rem; } + .warehouse-settlement-detail__title { display:flex; min-width:0; align-items:center; gap:.55rem; } + .warehouse-settlement-detail__title .material-icons-outlined { color:var(--quote-accent); font-size:20px; } + .warehouse-settlement-detail__controls { display:flex; align-items:flex-end; gap:.65rem; } + .warehouse-settlement-detail__close { display:grid; width:34px; height:34px; place-items:center; border:1px solid var(--quote-border); border-radius:.5rem; background:#fff; color:var(--quote-muted); cursor:pointer; } + .warehouse-settlement-detail__close:hover { border-color:var(--quote-accent); background:#FCFAF5; color:var(--quote-ink); } + .warehouse-settlement-detail__close:focus-visible { outline:none; box-shadow:0 0 0 3px rgba(133,102,50,.2); } + .warehouse-settlement-detail__close .material-icons-outlined { font-size:18px; } + .warehouse-settlement-detail__summary { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); border-top:1px solid var(--quote-border); border-bottom:1px solid var(--quote-border); background:#FCFAF5; } + .warehouse-settlement-detail__metric { min-width:0; padding:.65rem 1rem; border-left:1px solid var(--quote-border); } + .warehouse-settlement-detail__metric:first-child { border-left:0; } + .warehouse-settlement-detail__metric dt { color:var(--quote-muted); font-size:.7rem; font-weight:600; } + .warehouse-settlement-detail__metric dd { margin:.15rem 0 0; font-size:.875rem; font-weight:600; font-variant-numeric:tabular-nums; } + .warehouse-settlement-detail__table-wrap { max-height:min(32rem,65vh); overflow:auto; } + .warehouse-settlement-detail__table { min-width:76rem; } + .warehouse-settlement-detail__table th { position:sticky; top:0; z-index:1; } + .warehouse-settlement-detail__notice { margin:0; padding:1rem; border-top:1px solid var(--quote-border); color:var(--quote-muted); } @media (max-width:1050px){ .warehouse-quote-cards { grid-template-columns:repeat(2,minmax(0,1fr)); } } - @media (max-width:640px){ .warehouse-quote-cards { grid-template-columns:1fr; } } + @media (max-width:760px){ .warehouse-settlement-detail__summary { grid-template-columns:repeat(2,minmax(0,1fr)); } .warehouse-settlement-detail__metric { border-top:1px solid var(--quote-border); } } + @media (max-width:640px){ + .warehouse-quote-cards,.warehouse-settlement-detail__summary { grid-template-columns:1fr; } + .warehouse-settlement-detail__head { align-items:flex-start; flex-direction:column; } + .warehouse-settlement-detail__controls { width:100%; } + .warehouse-settlement-detail__controls .warehouse-quote-field { flex:1; max-width:none; } + .warehouse-settlement-detail__metric { border-left:0; } + }
@@ -170,7 +196,7 @@

仓储费核算

-
选择结算月份,一键按当期生效报价核算并存档,可导出核算明细(汇总/每日/逐商品)
+
选择结算月份,一键按当期生效报价核算并存档,可查看和导出每日商品仓储费
@if ($settlementError) @@ -188,6 +214,9 @@ 核算仓储费 @if ($settlementSummary) + @@ -219,7 +248,10 @@
@empty @@ -228,6 +260,73 @@
{{ number_format($item['total_fee'], 2) }} {{ $item['calculated_at'] }} - +
+ + +
+ @if ($settlementDetailPeriod) +
+
+
+ +
+

每日商品仓储费明细

+
{{ $settlementDetailPeriod }} · 上月结转库存按商品编码逐日延续
+
+
+
+ @if ($settlementDetailDates !== []) +
+ + +
+ @endif + +
+
+ @if ($settlementDetailMessage) +

{{ $settlementDetailMessage }}

+ @elseif ($settlementDetailSummary) +
+
商品编码数
{{ number_format($settlementDetailSummary['sku_count']) }}
+
上日结余
{{ number_format($settlementDetailSummary['opening'], 2) }}
+
当日进出净额
{{ number_format($settlementDetailSummary['net_movement'], 2) }}
+
当日库存结余
{{ number_format($settlementDetailSummary['closing'], 2) }}
+
当天仓储费
{{ number_format($settlementDetailSummary['storage_fee'], 4) }}
+
+
+ + + + + + + + + + @forelse ($settlementDetailRows as $row) + + + + + + + + + + + + @empty + + @endforelse + +
商品编码商品名称供应商分类单位上日结余当日进出净额当日库存结余当天仓储费
{{ $row['sku_code'] }}{{ $row['product_name'] }}{{ $row['supplier'] }}{{ $row['category'] }}{{ $row['unit'] }}{{ number_format($row['opening'], 2) }}{{ number_format($row['net_movement'], 2) }}{{ number_format($row['closing'], 2) }}{{ number_format($row['storage_fee'], 6) }}
该日期没有商品库存明细。
+
+ @endif +
+ @endif
diff --git a/tests/Feature/Business/ThirdPartyWarehouseQuotePageTest.php b/tests/Feature/Business/ThirdPartyWarehouseQuotePageTest.php index 6f93701a..2c880eaa 100644 --- a/tests/Feature/Business/ThirdPartyWarehouseQuotePageTest.php +++ b/tests/Feature/Business/ThirdPartyWarehouseQuotePageTest.php @@ -5,6 +5,7 @@ namespace Tests\Feature\Business; use App\Http\Livewire\Business\ThirdPartyWarehouseQuotes as WarehouseQuoteComponent; use App\Models\Auth\Permission; use App\Models\Business\ThirdPartyWarehouseQuote; +use App\Models\Business\ThirdPartyWarehouseStorageSettlement; use Illuminate\Database\Eloquent\ModelNotFoundException; use Livewire\Livewire; use Tests\Feature\FeatureTestCase; @@ -120,6 +121,57 @@ class ThirdPartyWarehouseQuotePageTest extends FeatureTestCase ->call('setStatus', $quote->id, ThirdPartyWarehouseQuote::STATUS_INACTIVE); } + public function test_daily_sku_storage_detail_can_be_opened_and_switched_by_date(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + $quote = $this->createQuote(); + $this->createSettlement($quote, [ + ['date' => '2026-08-01', 'owner' => '甲', 'sku_code' => 'SKU-A', 'product_name' => '商品A', 'supplier' => '供应商甲', 'category' => '桌类', 'unit' => '件', 'opening' => 100, 'net_movement' => 0, 'closing' => 100, 'storage_fee' => 4.417952], + ['date' => '2026-08-01', 'owner' => '甲', 'sku_code' => 'SKU-B', 'product_name' => '商品B', 'supplier' => '供应商乙', 'category' => '柜类', 'unit' => '件', 'opening' => 50, 'net_movement' => 10, 'closing' => 60, 'storage_fee' => 2.650771], + ['date' => '2026-08-02', 'owner' => '甲', 'sku_code' => 'SKU-A', 'product_name' => '商品A', 'supplier' => '供应商甲', 'category' => '桌类', 'unit' => '件', 'opening' => 100, 'net_movement' => -10, 'closing' => 90, 'storage_fee' => 3.976157], + ]); + + Livewire::test(WarehouseQuoteComponent::class) + ->call('viewSettlementDetails', '2026-08') + ->assertSet('settlementDetailDate', '2026-08-01') + ->assertSee('每日商品仓储费明细') + ->assertSee('160.00') + ->assertSee('SKU-A') + ->assertSee('SKU-B') + ->set('settlementDetailDate', '2026-08-02') + ->assertSee('90.00') + ->assertSee('3.976157') + ->assertDontSee('SKU-B'); + } + + public function test_legacy_settlement_explains_that_recalculation_is_required(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + $quote = $this->createQuote(); + $this->createSettlement($quote, []); + + Livewire::test(WarehouseQuoteComponent::class) + ->call('viewSettlementDetails', '2026-08') + ->assertSee('原存档没有每日商品明细,请重新核算该月份后查看'); + } + + public function test_settlement_history_detail_and_export_are_company_scoped(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + $quote = $this->createQuote(); + $this->createSettlement($quote, [], company_id() + 999, '2026-07'); + + Livewire::test(WarehouseQuoteComponent::class) + ->assertDontSee('2026-07') + ->call('viewSettlementDetails', '2026-07') + ->assertSet('settlementDetailMessage', '未找到 2026-07 的核算存档。') + ->call('exportSettlement', '2026-07') + ->assertSet('settlementError', '未找到 2026-07 的核算存档,请先核算。'); + } + private function createQuote(): ThirdPartyWarehouseQuote { return ThirdPartyWarehouseQuote::query()->create([ @@ -137,4 +189,38 @@ class ThirdPartyWarehouseQuotePageTest extends FeatureTestCase 'updated_by' => $this->user->id, ]); } + + /** @param list> $dailySku */ + private function createSettlement( + ThirdPartyWarehouseQuote $quote, + array $dailySku, + ?int $companyId = null, + string $period = '2026-08', + ): void + { + ThirdPartyWarehouseStorageSettlement::query()->create([ + 'company_id' => $companyId ?? company_id(), + 'warehouse_id' => WarehouseQuoteComponent::WAREHOUSE_ID, + 'warehouse_name' => '南昌樵舍仓', + 'period' => $period, + 'quote_id' => $quote->id, + 'inbound_rate_per_ton' => 20, + 'outbound_rate_per_order' => 0.85, + 'pieces_per_pallet' => 23, + 'pallet_area_sqm' => 3, + 'storage_rate_per_sqm_month' => 10.5, + 'days_in_month' => 31, + 'inbound_tons' => 0, + 'outbound_qty' => 0, + 'inbound_fee' => 0, + 'outbound_fee' => 0, + 'storage_fee' => array_sum(array_column($dailySku, 'storage_fee')), + 'memo_fee' => 0, + 'loss_fee' => 0, + 'compensation_fee' => 0, + 'total_fee' => array_sum(array_column($dailySku, 'storage_fee')), + 'detail_json' => ['daily' => [], 'per_sku' => [], 'daily_sku' => $dailySku], + 'calculated_by' => user_id(), + ]); + } } diff --git a/tests/Feature/Business/ThirdPartyWarehouseStorageFeeCalculatorTest.php b/tests/Feature/Business/ThirdPartyWarehouseStorageFeeCalculatorTest.php index f1c6b76b..cf58011e 100644 --- a/tests/Feature/Business/ThirdPartyWarehouseStorageFeeCalculatorTest.php +++ b/tests/Feature/Business/ThirdPartyWarehouseStorageFeeCalculatorTest.php @@ -4,6 +4,7 @@ namespace Tests\Feature\Business; use App\Business\ThirdPartyWarehouseProductWeightRepository; use App\Business\ThirdPartyWarehouseStorageFeeCalculator; +use App\Exports\ThirdPartyWarehouseStorageSettlementExport; use App\Models\Business\ThirdPartyWarehouseQuote; use Mockery; use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository; @@ -67,6 +68,24 @@ class ThirdPartyWarehouseStorageFeeCalculatorTest extends FeatureTestCase $this->assertSame(round(46.0 + 8.5 + $expectedStorage, 2), (float) $summary['total_fee']); $this->assertCount(2, $result['daily']); $this->assertCount(2, $result['per_sku']); + $this->assertCount(3, $result['daily_sku']); + + $firstDay = collect($result['daily_sku'])->where('date', '2026-08-01'); + $carriedStock = $firstDay->firstWhere('sku_code', 'A'); + $this->assertSame(100.0, (float) $carriedStock['opening']); + $this->assertSame(0.0, (float) $carriedStock['net_movement']); + $this->assertSame(100.0, (float) $carriedStock['closing']); + $this->assertEqualsWithDelta(100 / 23 * 3 * 10.5 / 31, $carriedStock['storage_fee'], 0.000001); + $this->assertEqualsWithDelta( + $result['daily'][0]['storage_fee'], + $firstDay->sum('storage_fee'), + 0.0001, + ); + + $sheets = (new ThirdPartyWarehouseStorageSettlementExport($result))->sheets(); + $this->assertCount(4, $sheets); + $this->assertSame('每日商品仓储费', $sheets[3]->title()); + $this->assertSame('A', $sheets[3]->array()[0][2]); } public function test_requires_effective_quote(): void From 7146b19bd321bd6721273abc9326e30db0f9640a Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 15 Sep 2026 11:53:17 +0800 Subject: [PATCH 005/249] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=94=9F=E4=BA=A7?= =?UTF-8?q?=E5=8F=91=E5=B8=83=E5=81=A5=E5=BA=B7=E6=8E=A2=E9=92=88=20(#188)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用容器已声明的公开静态资源执行发布健康检查,避免根路径被 Laravel 防火墙拒绝后误回滚。 --- deploy/activate-incremental-release.sh | 4 ++-- deploy/activate-release.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 642f5690..206518d0 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -140,7 +140,7 @@ fi healthy=0 attempt=1 while [ "$attempt" -le 30 ]; do - if curl -fsS -o /dev/null http://127.0.0.1:18088/; then + if curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then healthy=1 break fi @@ -164,7 +164,7 @@ if ! docker exec -u www-data caiwu_app php artisan storage:business-files:sync - exit 1 fi -if ! curl -fsS -o /dev/null http://127.0.0.1:18088/; then +if ! curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then restore_previous_image echo "Release failed after business storage activation; previous image was restored when available" >&2 exit 1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 066acca4..db27238d 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -144,7 +144,7 @@ fi healthy=0 attempt=1 while [ "$attempt" -le 30 ]; do - if curl -fsS -o /dev/null http://127.0.0.1:18088/; then + if curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then healthy=1 break fi @@ -168,7 +168,7 @@ if ! docker exec -u www-data caiwu_app php artisan storage:business-files:sync - exit 1 fi -if ! curl -fsS -o /dev/null http://127.0.0.1:18088/; then +if ! curl -fsS -o /dev/null http://127.0.0.1:18088/serviceworker.js; then restore_previous_image echo "Release failed after business storage activation; previous image was restored when available" >&2 exit 1 From 23f55ea774807333a1dfe9a8d5611bcc2b1e0513 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Tue, 15 Sep 2026 13:36:03 +0800 Subject: [PATCH 006/249] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E4=B8=89=E6=96=B9?= =?UTF-8?q?=E4=BB=93=E8=BF=9B=E9=94=80=E5=AD=98=E8=B4=B9=E7=94=A8=E6=B1=87?= =?UTF-8?q?=E6=80=BB=E5=85=A5=E5=8F=A3=20(#189)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third-party-warehouse-storage.blade.php | 39 +------------------ .../ThirdPartyWarehouseStorageViewTest.php | 17 ++++++++ 2 files changed, 19 insertions(+), 37 deletions(-) diff --git a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php index d192f2f3..4992a695 100644 --- a/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php +++ b/resources/views/business/pages/courier-payables/third-party-warehouse-storage.blade.php @@ -87,19 +87,6 @@ : (is_countable($rows) ? count($rows) : 0); $summaryReady = ! $pending && collect(['count', 'opening_qty', 'closing_qty']) ->every(static fn (string $key): bool => array_key_exists($key, $summary)); - $settlement = [ - 'ready' => false, 'complete' => false, - 'inbound_fee' => 0, 'outbound_fee' => 0, 'storage_fee' => 0, 'total_fee' => 0, - 'message' => null, - ]; - if ($summaryReady) { - try { - $settlement = app(\Modules\EcommerceFinance\Services\ThirdPartyWarehouseStorageSettlementService::class)->settle($filters); - } catch (\Throwable) { - $settlement['message'] = '仓储费暂时无法核算,请稍后重试。'; - } - } - $settlementComplete = ($settlement['ready'] ?? false) && ($settlement['complete'] ?? false); $showingLastVersion = $rowTotal > 0 && ($error !== '' || in_array($statusCode, [ 'syncing', 'reconciling', 'stale', 'delayed', 'failed', ], true)); @@ -108,7 +95,6 @@ $filters, static fn (mixed $value): bool => $value !== null && $value !== '' ); - $settlementExportUrl = route('business.courier-payables.third-party-warehouse-storage.settlement-export', $activeFilters); if (is_object($rows) && method_exists($rows, 'appends')) { $rows->appends($activeFilters); } @@ -233,7 +219,7 @@ .third-party-warehouse-actions [data-finance-server-export] { display:none; } .third-party-warehouse-page[data-finance-enhanced] .third-party-warehouse-actions [data-finance-server-export] { display:inline-flex; } .third-party-warehouse-page .finance-table-field-picker__panel { right:0; left:auto; } - .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(7,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } + .third-party-warehouse-summary { display:grid; grid-template-columns:repeat(3,minmax(8rem,1fr)); overflow:hidden; border:1px solid var(--warehouse-border); border-radius:.5rem; background:#fff; } .third-party-warehouse-summary__item { min-width:0; padding:.625rem .75rem; border-right:1px solid var(--warehouse-border); } .third-party-warehouse-summary__item:last-child { border-right:0; } .third-party-warehouse-summary__label { display:block; color:var(--warehouse-muted); font-size:.7rem; } @@ -377,13 +363,6 @@ - $settlementComplete, 'is-disabled' => ! $settlementComplete]) - href="{{ $settlementComplete ? $settlementExportUrl : '#' }}" - @if (! $settlementComplete) aria-disabled="true" @endif - > - 导出仓储费核算 -
- @if (! empty($settlement['message'])) -
- - {{ $settlement['message'] }} -
- @endif -
assertStringContainsString('referrerpolicy="no-referrer"', $source); } + public function test_summary_only_displays_inventory_counts(): void + { + $source = $this->viewSource(); + + $this->assertStringContainsString('grid-template-columns:repeat(3,minmax(8rem,1fr))', $source); + $this->assertStringContainsString("['key' => 'count', 'label' => '明细记录数'", $source); + $this->assertStringContainsString("['key' => 'opening_qty', 'label' => '期初数量合计'", $source); + $this->assertStringContainsString("['key' => 'closing_qty', 'label' => '期末数量合计'", $source); + $this->assertStringNotContainsString("['key' => 'inbound_fee'", $source); + $this->assertStringNotContainsString("['key' => 'outbound_fee'", $source); + $this->assertStringNotContainsString("['key' => 'storage_fee'", $source); + $this->assertStringNotContainsString("['key' => 'total_fee'", $source); + $this->assertStringNotContainsString('ThirdPartyWarehouseStorageSettlementService', $source); + $this->assertStringNotContainsString('导出仓储费核算', $source); + $this->assertStringNotContainsString('仓储费暂时无法核算', $source); + } + private function viewSource(): string { $root = dirname(__DIR__, 3); From 94adb5b547a0fb8e5959a0ce29b9510d648ad270 Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Tue, 15 Sep 2026 14:39:38 +0800 Subject: [PATCH 007/249] =?UTF-8?q?=E5=BE=97=E7=89=A9=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E7=BA=B3=E5=85=A5=E9=80=80=E6=AC=BE=E5=8F=8A=E5=85=B6=E4=BB=96?= =?UTF-8?q?=E8=B4=B9=E7=94=A8=E6=B8=A0=E9=81=93=20(#190)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/upstream_mirrors.php | 6 +- docs/上游业务镜像清单.md | 8 ++- .../EcommerceFinance/AccountBillColumns.php | 1 + .../Contracts/BusinessMirrorDataset.php | 2 +- ...oreReceivingAlipayBillMirrorRepository.php | 53 ++++++++++++----- ...StoreReceivingDewuBillMirrorRepository.php | 8 +-- .../BusinessMirrorDatasetRegistry.php | 13 ++++- .../Services/BusinessMirrorSynchronizer.php | 9 ++- .../Business/DewuReceivingBillsTest.php | 32 ++++++++-- .../BusinessMirrorSynchronizerTest.php | 50 +++++++++++++++- ...eReceivingDewuBillMirrorRepositoryTest.php | 58 +++++++++++-------- 11 files changed, 176 insertions(+), 64 deletions(-) diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index 1325eb65..cc839d6a 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -436,8 +436,8 @@ return [ ['fee_name'], ], ], - // 聚水潭得物货款账户:只复制主账单渠道,保证金、跨境和推广流水 - // 由其他账户域处理,不混入店铺收款账户页面。 + // 聚水潭得物货款账户:复制主账单、退货退款和其他费用扣减渠道; + // 保证金及其他账户域流水不混入店铺收款账户页面。 'jiansun.dbo.jst_originalBillInfo.dewu_receiving' => [ 'source_key' => 'jiansun', 'schema' => 'dbo', @@ -446,7 +446,7 @@ return [ 'keys' => ['Id'], 'watermark' => 'updateTime', 'fixed_filters' => [ - 'channel' => 'Dewu', + 'channel' => ['Dewu', 'DewuTK', 'DewuKJ'], ], 'columns' => [ 'Id', 'shop_id', 'channel', 'fee_time', 'del_flag', 'primary_key', diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 8f58b741..285132de 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -25,7 +25,7 @@ | 页面已切换 | 店铺收款账单的淘系支付宝账户读取 `operations_replica.rpt.jst_originalBillInfo`,并关联 `rpt.jst_shopInfo` 展示店铺;分页、筛选、汇总和导出统一读取共享业务镜像。 | | 抖音按月校准 | 抖音账户对已核对的完整月份读取 `douyin_authoritative_bills` 中胜算原始明细,`douyin_authoritative_periods` 原子选择有效版本;该月份不再叠加聚水潭拆分行。未校准月份继续读取原始账单镜像。导入命令为 `business-mirror:import-douyin-authoritative --count=<核对笔数> --income=<收入> --expense=<支出>`,只接受完整月份和精确核对值,保留旧版本、文件摘要及原镜像供回滚。生产执行前备份状态与受影响月份镜像,并使用 `/run/caiwu-upstream-sync.lock`。实际财务数据只放私有目录,不进入 Git。 | | 已接入待首次同步 | 店铺收款账单的拼多多账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = PinduoduoImport` 的独立切片镜像 `js_jst_pdd_receiving_bill_rows`;不使用慢一天的 `operations_replica` 副本或营销账户 `pdd_spread_bills`。 | -| 已接入待首次同步 | 店铺收款账单的得物账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = Dewu` 的独立切片镜像 `js_jst_dewu_receiving_bill_rows`;`Dewubzj`、`DewuKJ`、`DewuTK` 保留给保证金、跨境或推广等其他账户域,不混入得物收款账户。 | +| 已接入待首次同步 | 店铺收款账单的得物账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel IN (Dewu, DewuTK, DewuKJ)` 的独立切片镜像 `js_jst_dewu_receiving_bill_rows`;主账单、退货退款订单和扣减其他费用明细统一展示,`Dewubzj` 保证金继续排除。 | | 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | @@ -74,6 +74,7 @@ | 快递资料 | `dbo.wp_express`、`dbo.wp_express_expNet`、`dbo.wp_express_account`、`dbo.wp_express_extension` | | 聚水潭小额打款工单 | `dbo.jst_workOrderInfo`(稳定键 `Id`、增量字段 `updateTime`)与 `dbo.jst_small_payment_order_map`(稳定键 `woNo`、增量字段 `updated_at`) | | 拼多多货款账户账单 | `dbo.jst_originalBillInfo`(固定 `channel = PinduoduoImport`,镜像 `js_jst_pdd_receiving_bill_rows`) | +| 得物货款账户账单 | `dbo.jst_originalBillInfo`(固定 `channel IN (Dewu, DewuTK, DewuKJ)`,镜像 `js_jst_dewu_receiving_bill_rows`;排除 `Dewubzj`) | ## JSDataMiddlePlatform 中台库(js_data_middle_platform) @@ -96,8 +97,9 @@ 9. 店铺维度报表是已批准的中央专用数据集:生产节点按 `Id` 断点推进并回看最近 50000 行;原始账单同步后增量维护按店铺/日期汇总的 `store_report_daily_rows`,页面不得现场扫描千万级原始账单。开发机不运行刷新 worker。 10. `operations_replica.rpt.jst_originalBillInfo` 是供多个业务功能复用的原始账单镜像。首次同步由 Codex 备份后自主安排在生产同步节点低峰期分批续传,无需另行授权;页面请求和普通开发机不启动刷新 worker。同步完成后,开发者通过固定 Repository 查询 `ops_jst_original_bill_info`,不得各自创建整表快照。 淘系支付宝账户账单当前仍读取此 MariaDB 镜像,统一调度须持续增量,不因 ClickHouse 尚未启用而暂停。账单冲减则复用“订单数据 → 原始数据 → 订单售后费用明细”,不按该表费用名称推断 500112。 11. 拼多多货款账户账单使用 `jiansun.dbo.jst_originalBillInfo.pinduoduo_receiving` 数据集。同步器必须以参数绑定固定 `channel = PinduoduoImport`,只复制该渠道切片;页面 Repository 只读 `js_jst_pdd_receiving_bill_rows`。首次全量按 `Id` 断点推进,后续按 `updateTime` 保留重叠窗口,不得切回落后一天的 `operations_replica` 副本。 -12. 三方仓进销存首次全量按头表 `Id` 区间小批断点续传,头表只保存 `io_date >= 2026-08-01` 的目标仓数据,不激活半份数据;日常增量以头表 `(modified, Id)` 作稳定游标并保留 48 小时时间重叠,由命中头单驱动整单明细替换。全量和增量都先写待发布代次,库存抓取完成后再把流水追平到库存抓取之后的固定源时间边界,三部分成功后才一次切换;运行中或失败时页面始终读取上一成功代次。增量扫描不先限定仓库或业务日期,确保单据移出目标仓或日期改到起始日前时可从镜像撤回,重载当前版本时再固定仓库和起始日期。页面只统计 `Confirmed` 的 12 类进销存流水,数量按上游 `qty * qty_type` 保留符号。库存同时保存上游 `source_modified_at` 和实际 `captured_at`,历史余额以每个 SKU 的抓取时间为回推锚点;页面始终按“日期 + 商品”输出,日期区间固定为 `[当天 00:00, 次日 00:00)`。每天 `00:00` 执行增量同步,失败时继续展示上一成功代次。 -13. 聚水潭商品操作日志按最多 7 天的固定时间窗和接口页码稳定断点同步,每页最多 50 条,首次全量从 `2000-01-01` 起扫描;只保留备注内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按接口记录字段生成稳定键幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。 +12. 得物货款账户账单使用 `jiansun.dbo.jst_originalBillInfo.dewu_receiving` 数据集。同步器必须以参数绑定固定 `channel IN (Dewu, DewuTK, DewuKJ)`,页面 Repository 对列表、分页、筛选、汇总和导出使用相同渠道范围,并保留原始渠道代码用于审计;`Dewubzj` 保证金不得混入。 +13. 三方仓进销存首次全量按头表 `Id` 区间小批断点续传,头表只保存 `io_date >= 2026-08-01` 的目标仓数据,不激活半份数据;日常增量以头表 `(modified, Id)` 作稳定游标并保留 48 小时时间重叠,由命中头单驱动整单明细替换。全量和增量都先写待发布代次,库存抓取完成后再把流水追平到库存抓取之后的固定源时间边界,三部分成功后才一次切换;运行中或失败时页面始终读取上一成功代次。增量扫描不先限定仓库或业务日期,确保单据移出目标仓或日期改到起始日前时可从镜像撤回,重载当前版本时再固定仓库和起始日期。页面只统计 `Confirmed` 的 12 类进销存流水,数量按上游 `qty * qty_type` 保留符号。库存同时保存上游 `source_modified_at` 和实际 `captured_at`,历史余额以每个 SKU 的抓取时间为回推锚点;页面始终按“日期 + 商品”输出,日期区间固定为 `[当天 00:00, 次日 00:00)`。每天 `00:00` 执行增量同步,失败时继续展示上一成功代次。 +14. 聚水潭商品操作日志按最多 7 天的固定时间窗和接口页码稳定断点同步,每页最多 50 条,首次全量从 `2000-01-01` 起扫描;只保留备注内容含“采购价”的记录,并从“采购价:旧值->新值”解析前后价格和差额。日常同步回看 48 小时,按接口记录字段生成稳定键幂等更新;接口失败时保留上一版镜像。页面不得把这些聚水潭记录与 `jiansun.dbo.pm_priceAdjustment` 的工作平台价格记录混为同一来源。 工作平台采购价格首次全量需在备份和负责人授权后单独执行: diff --git a/modules/EcommerceFinance/AccountBillColumns.php b/modules/EcommerceFinance/AccountBillColumns.php index 9c4ef75d..568bc088 100644 --- a/modules/EcommerceFinance/AccountBillColumns.php +++ b/modules/EcommerceFinance/AccountBillColumns.php @@ -194,6 +194,7 @@ class AccountBillColumns ['商品货号', 'payload.goods_no', 'num'], ['数量', 'payload.quantity', 'num'], ['渠道', 'payload.channel', 'text'], + ['源渠道代码', 'payload.source_channel', 'text'], ['业务类型', 'payload.business_type', 'text'], ['收入金额', 'income', 'money_in'], ['支出金额', 'expense', 'money_out'], diff --git a/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php b/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php index 77ca082c..de3b1fb2 100644 --- a/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php +++ b/modules/EcommerceFinance/Contracts/BusinessMirrorDataset.php @@ -19,7 +19,7 @@ interface BusinessMirrorDataset public function watermarkColumn(): ?string; - /** @return array */ + /** @return array> */ public function fixedFilters(): array; /** @return list> */ diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php index de4dcffc..8e0c68f3 100644 --- a/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReceivingAlipayBillMirrorRepository.php @@ -42,7 +42,7 @@ class StoreReceivingAlipayBillMirrorRepository string $direction, int $page, int $perPage, - ?string $channel, + string|array|null $channel, string $mapping = 'taobao', string $datasetKey = self::DATASET, bool $excludeNonTaobaoPlatforms = false, @@ -124,7 +124,7 @@ class StoreReceivingAlipayBillMirrorRepository array $filters, string $sort = 'occurred_at', string $direction = 'asc', - ?string $channel = null, + string|array|null $channel = null, string $mapping = 'taobao', string $datasetKey = self::DATASET, bool $excludeNonTaobaoPlatforms = false, @@ -157,7 +157,7 @@ class StoreReceivingAlipayBillMirrorRepository } /** @return array{shops:array,bill_items:array} */ - public function filterOptionsForChannel(string $channel, string $datasetKey = self::DATASET): array + public function filterOptionsForChannel(string|array $channel, string $datasetKey = self::DATASET): array { $dataset = $this->datasets->get($datasetKey); if (! $this->mirror->ready($dataset) @@ -258,7 +258,7 @@ class StoreReceivingAlipayBillMirrorRepository int $page, int $perPage, array $filters, - ?string $channel, + string|array|null $channel, string $targetTable, ): array { if ($channel === null || ($filters['bill_item'] ?? '') === '') { @@ -298,7 +298,7 @@ class StoreReceivingAlipayBillMirrorRepository private function summary( Builder $billQuery, array $filters, - ?string $channel = null, + string|array|null $channel = null, ): array { if ($channel === null && $this->dailySummarySupports($filters)) { @@ -402,12 +402,24 @@ class StoreReceivingAlipayBillMirrorRepository } } - /** @param array $fixedFilters */ - private function applyChannel(Builder $query, ?string $channel, array $fixedFilters): void + /** @param array> $fixedFilters */ + private function applyChannel(Builder $query, string|array|null $channel, array $fixedFilters): void { - if ($this->channelCoversDataset($channel, $fixedFilters)) return; + if ($channel === null || $channel === '') return; + if (is_string($channel)) { + if (! $this->channelCoversDataset($channel, $fixedFilters)) { + $query->where('b.channel', $channel); + } + return; + } - $query->where('b.channel', $channel); + $channels = array_values($channel); + if ($channels === []) { + $query->whereRaw('1 = 0'); + return; + } + + $query->whereIn('b.channel', $channels); } private function applyTaobaoPlatformScope(Builder $query): void @@ -423,17 +435,22 @@ class StoreReceivingAlipayBillMirrorRepository $query->whereNotIn('b.shop_id', $excludedShopIds); } - /** @param array $fixedFilters */ - private function channelCoversDataset(?string $channel, array $fixedFilters): bool + /** @param array> $fixedFilters */ + private function channelCoversDataset(string|array|null $channel, array $fixedFilters): bool { if ($channel === null || $channel === '') { return true; } foreach ($fixedFilters as $column => $value) { - if (strcasecmp($column, 'channel') === 0 && (string) $value === $channel) { - return true; - } + if (strcasecmp($column, 'channel') !== 0) continue; + + $requested = is_array($channel) ? array_map('strval', $channel) : [(string) $channel]; + $configured = is_array($value) ? array_map('strval', $value) : [(string) $value]; + sort($requested); + sort($configured); + + return $requested === $configured; } return false; @@ -625,7 +642,13 @@ class StoreReceivingAlipayBillMirrorRepository 'goods_name' => null, 'goods_no' => $goodsNo, 'quantity' => null, - 'channel' => $row->channel, + 'channel' => match ((string) $row->channel) { + 'Dewu' => '得物', + 'DewuTK' => '退货退款订单', + 'DewuKJ' => '扣减其他费用明细', + default => (string) $row->channel, + }, + 'source_channel' => $row->channel, 'business_type' => $this->directionName($row->inout_type), 'online_real_store' => $shopName, 'order_created_at' => null, diff --git a/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php index 1af74db8..b1d8aab3 100644 --- a/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReceivingDewuBillMirrorRepository.php @@ -6,7 +6,7 @@ namespace Modules\EcommerceFinance\Repositories; class StoreReceivingDewuBillMirrorRepository { public const DATASET = 'jiansun.dbo.jst_originalBillInfo.dewu_receiving'; - public const SOURCE_CHANNEL = 'Dewu'; + public const SOURCE_CHANNELS = ['Dewu', 'DewuTK', 'DewuKJ']; public function __construct( private readonly StoreReceivingAlipayBillMirrorRepository $source, @@ -22,7 +22,7 @@ class StoreReceivingDewuBillMirrorRepository $direction, $page, $perPage, - self::SOURCE_CHANNEL, + self::SOURCE_CHANNELS, 'dewu', self::DATASET, ); @@ -35,7 +35,7 @@ class StoreReceivingDewuBillMirrorRepository $filters, $sort, $direction, - self::SOURCE_CHANNEL, + self::SOURCE_CHANNELS, 'dewu', self::DATASET, ); @@ -44,6 +44,6 @@ class StoreReceivingDewuBillMirrorRepository /** @return array{shops:array,bill_items:array} */ public function filterOptions(): array { - return $this->source->filterOptionsForChannel(self::SOURCE_CHANNEL, self::DATASET); + return $this->source->filterOptionsForChannel(self::SOURCE_CHANNELS, self::DATASET); } } diff --git a/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php b/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php index ec9f9c8e..3ea66e29 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorDatasetRegistry.php @@ -71,7 +71,7 @@ class BusinessMirrorDatasetRegistry return $this->definitions()[$key]['columns'] ?? null; } - /** @return array */ + /** @return array> */ public function fixedFilters(string $key): array { $definitions = $this->definitions(); @@ -145,7 +145,7 @@ class BusinessMirrorDatasetRegistry }; } - /** @return array */ + /** @return array> */ private function normalizeFixedFilters(string $key, array $filters): array { $normalized = []; @@ -157,7 +157,14 @@ class BusinessMirrorDatasetRegistry if ($column === '' || mb_strlen($column) > 128 || str_contains($column, "\0") || isset($seen[$canonical])) { throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤字段:' . $key); } - if (! is_scalar($value)) { + if (is_array($value)) { + if (! array_is_list($value) || $value === [] || collect($value)->contains( + static fn (mixed $item): bool => ! is_scalar($item) + )) { + throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤值:' . $key); + } + $value = array_values($value); + } elseif (! is_scalar($value)) { throw new InvalidArgumentException('业务镜像数据集包含无效的固定过滤值:' . $key); } diff --git a/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php b/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php index bb1a0441..4c06be98 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorSynchronizer.php @@ -121,8 +121,13 @@ class BusinessMirrorSynchronizer $bindings = []; foreach ($dataset->fixedFilters() as $column => $value) { - $where[] = $this->quote($column) . ' = ?'; - $bindings[] = $value; + if (is_array($value)) { + $where[] = $this->quote($column) . ' IN (' . implode(', ', array_fill(0, count($value), '?')) . ')'; + array_push($bindings, ...$value); + } else { + $where[] = $this->quote($column) . ' = ?'; + $bindings[] = $value; + } } if ($mode === 'incremental' && $dataset->watermarkColumn() !== null) { diff --git a/tests/Feature/Business/DewuReceivingBillsTest.php b/tests/Feature/Business/DewuReceivingBillsTest.php index 4f7de9fc..f5ad4f15 100644 --- a/tests/Feature/Business/DewuReceivingBillsTest.php +++ b/tests/Feature/Business/DewuReceivingBillsTest.php @@ -36,8 +36,23 @@ class DewuReceivingBillsTest extends FeatureTestCase 'expense' => 0.0, 'payload' => [ 'online_order_no' => '110211311661075313', - 'channel' => 'Dewu', + 'channel' => '得物', + 'source_channel' => 'Dewu', ], + ], [ + 'id' => '14654481', + 'record_code' => '2000000001248775180', + 'store_name' => '得物-测试店', + 'income' => 0.0, + 'expense' => 18.07, + 'payload' => ['channel' => '退货退款订单', 'source_channel' => 'DewuTK'], + ], [ + 'id' => '14654482', + 'record_code' => '2000000001248775181', + 'store_name' => '得物-测试店', + 'income' => 0.0, + 'expense' => 3.50, + 'payload' => ['channel' => '扣减其他费用明细', 'source_channel' => 'DewuKJ'], ]], 'summary' => ['income' => 21.0, 'expense' => 0.0, 'balance' => 21.0, 'count' => 41], ]); @@ -52,7 +67,12 @@ class DewuReceivingBillsTest extends FeatureTestCase 'limit' => 20, ])) ->assertOk() - ->assertJsonPath('data.0.payload.channel', 'Dewu') + ->assertJsonPath('data.0.payload.channel', '得物') + ->assertJsonPath('data.0.payload.source_channel', 'Dewu') + ->assertJsonPath('data.1.payload.channel', '退货退款订单') + ->assertJsonPath('data.1.payload.source_channel', 'DewuTK') + ->assertJsonPath('data.2.payload.channel', '扣减其他费用明细') + ->assertJsonPath('data.2.payload.source_channel', 'DewuKJ') ->assertJsonPath('columns.title', '得物账户') ->assertJsonPath('summary.count', 41); } @@ -70,7 +90,7 @@ class DewuReceivingBillsTest extends FeatureTestCase )->andReturn([[ 'record_code' => '2000000001248775179', 'store_name' => '得物-A店', - 'payload' => ['channel' => 'Dewu'], + 'payload' => ['channel' => '退货退款订单', 'source_channel' => 'DewuTK'], ]]); $this->app->instance(StoreReceivingDewuBillMirrorRepository::class, $repository); @@ -88,15 +108,15 @@ class DewuReceivingBillsTest extends FeatureTestCase 'store_name' => '得物-A店', 'sort' => 'record_code', 'dir' => 'asc', - 'columns' => 'payload.channel,record_code,store_name', + 'columns' => 'payload.channel,payload.source_channel,record_code,store_name', ])); $response->assertOk() ->assertHeader('content-type', 'text/csv; charset=UTF-8') ->assertDownload('dewu_account_bills.csv'); $csv = $response->streamedContent(); - $this->assertStringContainsString('渠道,记录编码,店铺', $csv); - $this->assertStringContainsString('Dewu,"=""2000000001248775179""",得物-A店', $csv); + $this->assertStringContainsString('渠道,源渠道代码,记录编码,店铺', $csv); + $this->assertStringContainsString('退货退款订单,DewuTK,"=""2000000001248775179""",得物-A店', $csv); } public function test_unready_mirror_returns_a_clear_retryable_response(): void diff --git a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php index a92cb530..64c883b3 100644 --- a/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/BusinessMirrorSynchronizerTest.php @@ -11,6 +11,7 @@ use Modules\EcommerceFinance\Services\BusinessMirrorSchemaManager; use Modules\EcommerceFinance\Services\BusinessMirrorSynchronizer; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery; use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory; +use PHPUnit\Framework\Attributes\DataProvider; use Tests\TestCase; class BusinessMirrorSynchronizerTest extends TestCase @@ -176,7 +177,40 @@ class BusinessMirrorSynchronizerTest extends TestCase ); } - public function test_registry_rejects_non_scalar_fixed_filter_values(): void + public function test_fixed_filter_lists_are_validated_and_bound_to_every_source_batch(): void + { + DB::table('upstream_schema_columns')->insert($this->column('channel', 5, 'nvarchar', 50)); + $datasets = (array) config('upstream_mirrors.datasets', []); + $datasets['test.dbo.records.dewu'] = [ + 'source_key' => 'test', + 'schema' => 'dbo', + 'object' => 'records', + 'target' => 'test_dewu_records', + 'keys' => ['Id'], + 'watermark' => 'updateTime', + 'fixed_filters' => ['channel' => ['Dewu', 'DewuTK', 'DewuKJ']], + ]; + config(['upstream_mirrors.datasets' => $datasets]); + $this->query->batches = [[[ + 'Id' => 1, + 'updateTime' => '2026-08-14 10:00:00', + 'displayName' => '得物退款记录', + 'businessDate' => '2026-08-14', + 'channel' => 'DewuTK', + ]]]; + + $this->synchronizer->sync('test.dbo.records.dewu', true, 10, 1); + + $this->assertStringContainsString('WHERE ([channel] IN (?, ?, ?))', $this->query->calls[0]['sql']); + $this->assertSame(['Dewu', 'DewuTK', 'DewuKJ'], $this->query->calls[0]['bindings']); + $this->assertSame( + ['channel' => ['Dewu', 'DewuTK', 'DewuKJ']], + (new BusinessMirrorDatasetRegistry())->fixedFilters('test.dbo.records.dewu'), + ); + } + + #[DataProvider('invalidFixedFilterLists')] + public function test_registry_rejects_invalid_fixed_filter_lists(mixed $value): void { $datasets = (array) config('upstream_mirrors.datasets', []); $datasets['test.dbo.invalid_filter'] = [ @@ -185,7 +219,7 @@ class BusinessMirrorSynchronizerTest extends TestCase 'object' => 'records', 'target' => 'test_invalid_filter', 'keys' => ['Id'], - 'fixed_filters' => ['channel' => ['PinduoduoImport']], + 'fixed_filters' => ['channel' => $value], ]; config(['upstream_mirrors.datasets' => $datasets]); @@ -193,6 +227,16 @@ class BusinessMirrorSynchronizerTest extends TestCase (new BusinessMirrorDatasetRegistry())->get('test.dbo.invalid_filter'); } + public static function invalidFixedFilterLists(): array + { + return [ + 'empty list' => [[]], + 'associative array' => [['main' => 'Dewu']], + 'nested list' => [[['Dewu']]], + 'non-scalar item' => [[null]], + ]; + } + public function test_incremental_keyset_keeps_watermark_out_of_pagination_cursor(): void { $this->query->batches = [[ @@ -488,7 +532,7 @@ class BusinessMirrorSynchronizerTest extends TestCase $this->assertSame('jiansun', $dewu->sourceKey()); $this->assertSame('jst_originalBillInfo', $dewu->sourceObject()); $this->assertSame('js_jst_dewu_receiving_bill_rows', $dewu->targetTable()); - $this->assertSame(['channel' => 'Dewu'], $dewu->fixedFilters()); + $this->assertSame(['channel' => ['Dewu', 'DewuTK', 'DewuKJ']], $dewu->fixedFilters()); } /** @return array */ diff --git a/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php index e97f98c8..6d70e649 100644 --- a/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/StoreReceivingDewuBillMirrorRepositoryTest.php @@ -29,7 +29,7 @@ class StoreReceivingDewuBillMirrorRepositoryTest extends TestCase 'source_key' => 'jiansun', 'schema' => 'dbo', 'object' => 'jst_originalBillInfo', 'target' => 'js_jst_dewu_receiving_bill_rows', 'keys' => ['Id'], - 'fixed_filters' => ['channel' => StoreReceivingDewuBillMirrorRepository::SOURCE_CHANNEL], + 'fixed_filters' => ['channel' => StoreReceivingDewuBillMirrorRepository::SOURCE_CHANNELS], ], StoreReceivingAlipayBillMirrorRepository::SHOP_DATASET => [ 'source_key' => 'operations_replica', 'schema' => 'rpt', @@ -72,30 +72,35 @@ class StoreReceivingDewuBillMirrorRepositoryTest extends TestCase $this->markReady(); } - public function test_it_reads_only_the_dewu_dataset_and_maps_available_source_fields(): void + public function test_it_reads_all_three_dewu_channels_and_excludes_deposit_rows(): void { DB::connection('business_mirror')->table('ops_jst_shop_info')->insert([ ['Id' => 10, 'shop_id' => 7, 'shop_name' => '得物-测试店'], ['Id' => 11, 'shop_id' => 8, 'shop_name' => '其他店'], ]); DB::connection('business_mirror')->table('js_jst_dewu_receiving_bill_rows')->insert([ - $this->row(1, 7, '2026-09-13 18:48:12', '1', 21.00, '交易收入'), - $this->row(2, 7, '2026-09-13 19:00:00', '-1', 18.07, '平台服务费'), + $this->row(1, 7, '2026-09-13 18:48:12', '1', 21.00, '交易收入', 'Dewu'), + $this->row(2, 7, '2026-09-13 19:00:00', '-1', 18.07, '退款', 'DewuTK'), + $this->row(3, 7, '2026-09-13 19:30:00', '-1', 3.50, '其他费用', 'DewuKJ'), + $this->row(4, 8, '2026-09-13 20:00:00', '1', 100.00, '保证金充值', 'Dewubzj'), ]); $result = $this->repository->paginate([], 'occurred_at', 'desc', 1, 10); + $rowsBySource = collect($result['data'])->keyBy('payload.source_channel'); - $this->assertSame(2, $result['total']); - $this->assertSame('200000000000000002', $result['data'][0]['record_code']); - $this->assertSame('得物-测试店', $result['data'][0]['store_name']); - $this->assertSame('110211-ORDER-2', $result['data'][0]['order_no']); - $this->assertSame('Dewu', $result['data'][0]['payload']['channel']); - $this->assertSame('支出', $result['data'][0]['payload']['business_type']); - $this->assertSame('SKU-2', $result['data'][0]['payload']['goods_no']); - $this->assertSame('聚水潭', $result['data'][0]['modifier']); + $this->assertSame(3, $result['total']); + $this->assertSame(['DewuKJ', 'DewuTK', 'Dewu'], collect($result['data'])->pluck('payload.source_channel')->all()); + $this->assertSame('得物', $rowsBySource['Dewu']['payload']['channel']); + $this->assertSame('退货退款订单', $rowsBySource['DewuTK']['payload']['channel']); + $this->assertSame('扣减其他费用明细', $rowsBySource['DewuKJ']['payload']['channel']); + $this->assertSame('得物-测试店', $rowsBySource['DewuTK']['store_name']); + $this->assertSame('110211-ORDER-2', $rowsBySource['DewuTK']['order_no']); + $this->assertSame('支出', $rowsBySource['DewuTK']['payload']['business_type']); + $this->assertSame('SKU-2', $rowsBySource['DewuTK']['payload']['goods_no']); + $this->assertSame('聚水潭', $rowsBySource['DewuTK']['modifier']); $this->assertSame(21.0, $result['summary']['income']); - $this->assertSame(18.07, $result['summary']['expense']); - $this->assertSame(2.93, $result['summary']['balance']); + $this->assertSame(21.57, $result['summary']['expense']); + $this->assertSame(-0.57, $result['summary']['balance']); } public function test_filters_options_export_and_exact_total_use_the_fixed_channel_slice(): void @@ -105,13 +110,15 @@ class StoreReceivingDewuBillMirrorRepositoryTest extends TestCase ['Id' => 11, 'shop_id' => 8, 'shop_name' => '得物-B店'], ]); DB::connection('business_mirror')->table('js_jst_dewu_receiving_bill_rows')->insert([ - $this->row(1, 7, '2026-08-12 09:00:00', '1', 22.80, '交易收入'), - $this->row(2, 8, '2026-08-13 09:00:00', '-1', 0.14, '平台服务费'), + $this->row(1, 7, '2026-08-12 09:00:00', '1', 22.80, '交易收入', 'Dewu'), + $this->row(2, 8, '2026-08-13 09:00:00', '-1', 0.14, '退货退款', 'DewuTK'), + $this->row(3, 8, '2026-08-14 09:00:00', '-1', 1.26, '扣减其他费用', 'DewuKJ'), + $this->row(4, 8, '2026-08-15 09:00:00', '-1', 8.88, '保证金扣减', 'Dewubzj'), ]); $connection = DB::connection('business_mirror'); $connection->table('business_mirror_table_states') ->where('dataset_key', StoreReceivingDewuBillMirrorRepository::DATASET) - ->update(['mirror_row_count' => 2, 'mirror_row_count_is_exact' => true]); + ->update(['mirror_row_count' => 3, 'mirror_row_count_is_exact' => true]); $connection->enableQueryLog(); $connection->flushQueryLog(); @@ -124,24 +131,26 @@ class StoreReceivingDewuBillMirrorRepositoryTest extends TestCase 'keyword' => '110211-ORDER-1', ], 'record_code', 'asc', 1, 10); $options = $this->repository->filterOptions(); - $export = iterator_to_array($this->repository->exportRows(['bill_item' => '平台服务费'])); + $export = iterator_to_array($this->repository->exportRows(['bill_item' => '扣减其他费用'])); - $this->assertSame(2, $unfiltered['total']); + $this->assertSame(3, $unfiltered['total']); $this->assertSame(1, $filtered['total']); $this->assertSame('200000000000000001', $filtered['data'][0]['record_code']); $this->assertSame(['得物-A店', '得物-B店'], $options['shops']); - $this->assertSame(['交易收入', '平台服务费'], $options['bill_items']); + $this->assertSame(['交易收入', '扣减其他费用', '退货退款'], $options['bill_items']); $this->assertCount(1, $export); - $this->assertSame('200000000000000002', $export[0]['record_code']); + $this->assertSame('200000000000000003', $export[0]['record_code']); + $this->assertSame('扣减其他费用明细', $export[0]['payload']['channel']); + $this->assertSame('DewuKJ', $export[0]['payload']['source_channel']); $targetQueries = array_filter( $connection->getQueryLog(), static fn (array $query): bool => str_contains($query['query'], 'js_jst_dewu_receiving_bill_rows'), ); $this->assertNotEmpty($targetQueries); - $this->assertCount(0, array_filter( + $this->assertNotEmpty(array_filter( $targetQueries, - static fn (array $query): bool => str_contains($query['query'], '"b"."channel" = ?'), + static fn (array $query): bool => str_contains($query['query'], '"b"."channel" in (?, ?, ?)'), )); $connection->disableQueryLog(); } @@ -165,11 +174,12 @@ class StoreReceivingDewuBillMirrorRepositoryTest extends TestCase string $direction, float $amount, string $feeName, + string $channel, ): array { return [ 'Id' => $id, 'shop_id' => $shopId, - 'channel' => 'Dewu', + 'channel' => $channel, 'primary_key' => 'KEY-' . $id, 'fee_name' => $feeName, 'inout_type' => $direction, From 3f387cd1947b1bd111d34ad737334c51f117fd55 Mon Sep 17 00:00:00 2001 From: 92451 <924518135@qq.com> Date: Tue, 15 Sep 2026 20:16:25 +0800 Subject: [PATCH 008/249] =?UTF-8?q?=E6=8E=A5=E5=85=A5=E8=81=9A=E8=83=9C?= =?UTF-8?q?=E7=AE=97=E4=BA=AC=E4=B8=9C=E9=92=B1=E5=8C=85=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E4=BD=99=E9=A2=9D=20(#192)=20Co-authored-by:=2092451=20<924518?= =?UTF-8?q?135@qq.com>=20Co-committed-by:=2092451=20<924518135@qq.com>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/上游业务镜像清单.md | 2 +- .../JushuitanShopBalanceRepository.php | 4 +- .../Services/JushuitanShopBalanceImporter.php | 192 +++++++++++++++++- .../JushuitanShopBalanceRepositoryTest.php | 102 ++++++++++ 4 files changed, 287 insertions(+), 13 deletions(-) diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 285132de..66974ada 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -26,7 +26,7 @@ | 抖音按月校准 | 抖音账户对已核对的完整月份读取 `douyin_authoritative_bills` 中胜算原始明细,`douyin_authoritative_periods` 原子选择有效版本;该月份不再叠加聚水潭拆分行。未校准月份继续读取原始账单镜像。导入命令为 `business-mirror:import-douyin-authoritative --count=<核对笔数> --income=<收入> --expense=<支出>`,只接受完整月份和精确核对值,保留旧版本、文件摘要及原镜像供回滚。生产执行前备份状态与受影响月份镜像,并使用 `/run/caiwu-upstream-sync.lock`。实际财务数据只放私有目录,不进入 Git。 | | 已接入待首次同步 | 店铺收款账单的拼多多账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel = PinduoduoImport` 的独立切片镜像 `js_jst_pdd_receiving_bill_rows`;不使用慢一天的 `operations_replica` 副本或营销账户 `pdd_spread_bills`。 | | 已接入待首次同步 | 店铺收款账单的得物账户读取 `jiansun.dbo.jst_originalBillInfo` 中固定 `channel IN (Dewu, DewuTK, DewuKJ)` 的独立切片镜像 `js_jst_dewu_receiving_bill_rows`;主账单、退货退款订单和扣减其他费用明细统一展示,`Dewubzj` 保证金继续排除。 | -| 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX 及多平台“平台资金账户余额”导出,进入 `jushuitan_shop_balance_snapshots`;已导入 2026-09-11 的淘系、拼多多和抖音共 164 条余额。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | +| 已完成首次导入 | 提现管理的每日店铺余额读取聚水潭“平台原始账单[新] → 店铺余额表”接口 JSON/XLSX、多平台“平台资金账户余额”导出及“京东商城 → 京东钱包”流水,进入 `jushuitan_shop_balance_snapshots`。京东钱包按前一天作为截止日,每个店铺取最新费用结算时间的最后一笔账户余额,同一时间以最大记录编码消歧;每天 05:00 原子覆盖各来源范围,异常或空数据保留上一快照。页面按店铺名称精确匹配并强制使用平台消歧,未匹配和多匹配不会显示为零。 | | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | | 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 | diff --git a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php index 4046fcdb..eec7cb07 100644 --- a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php +++ b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php @@ -112,7 +112,7 @@ class JushuitanShopBalanceRepository { $value = trim(str_replace(['-', '—', '–'], '-', $value)); $value = preg_replace( - '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-_::]+/u', + '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|京喜小店|京喜|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-_::]+/u', '', $value, ) ?? $value; @@ -124,7 +124,7 @@ class JushuitanShopBalanceRepository public static function sourcePlatform(string $storeName): ?string { if (preg_match( - '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-—–_::]+/u', + '/^(支付宝|天猫|淘宝|阿里巴巴|1688|京东商城|京东|京喜小店|京喜|拼多多|抖音|快手|小红书|唯品会|得物|淘工厂)[\s\-—–_::]+/u', trim($storeName), $matches, ) === 1) { diff --git a/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php b/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php index a1b442af..9b5dd533 100644 --- a/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php +++ b/modules/EcommerceFinance/Services/JushuitanShopBalanceImporter.php @@ -45,15 +45,34 @@ class JushuitanShopBalanceImporter 'xlsx', 'xls' => $this->workbookRows($realPath), default => throw new InvalidArgumentException('店铺余额仅支持聚水潭接口 JSON 或官方 XLSX/XLS 导出文件。'), }; - [$selectedDate, $storeField, $accountField, $balanceField, $platformField] = $this->fields($headers, $requestedDate); - $rows = $this->normalizeRows( - $dataRows, - $selectedDate, - $storeField, - $accountField, - $balanceField, - $platformField, - ); + $walletFields = $this->jdWalletFields($headers); + if ($walletFields !== null) { + if ($requestedDate === null) { + throw new InvalidArgumentException('京东钱包余额缺少截止日期,请使用 --balance-date 指定导出截止日期。'); + } + + [$storeField, $accountField, $settledAtField, $recordCodeField, $balanceField] = $walletFields; + $selectedDate = $requestedDate; + $rows = $this->normalizeJdWalletRows( + $dataRows, + $selectedDate, + $storeField, + $accountField, + $settledAtField, + $recordCodeField, + $balanceField, + ); + } else { + [$selectedDate, $storeField, $accountField, $balanceField, $platformField] = $this->fields($headers, $requestedDate); + $rows = $this->normalizeRows( + $dataRows, + $selectedDate, + $storeField, + $accountField, + $balanceField, + $platformField, + ); + } if ($rows === []) { throw new InvalidArgumentException('聚水潭店铺余额文件中没有可导入的数据行,已保留原有快照。'); @@ -153,6 +172,7 @@ class JushuitanShopBalanceImporter foreach (array_slice($matrix, 0, 20, true) as $rowNumber => $row) { $values = array_map(static fn (mixed $value): string => trim((string) $value), $row); $hasBalanceColumn = in_array('平台实际期末余额', $values, true) + || in_array('账户余额', $values, true) || count(array_filter($values, fn (string $value): bool => $this->dateFromHeader($value, null) !== null)) > 0; if (in_array('店铺', $values, true) && $hasBalanceColumn) { $headerNumber = $rowNumber; @@ -160,7 +180,7 @@ class JushuitanShopBalanceImporter } } if ($headerNumber === null) { - throw new InvalidArgumentException('聚水潭导出文件中未找到“店铺”和日期列。'); + throw new InvalidArgumentException('聚水潭导出文件中未找到“店铺”和余额列。'); } $headers = []; @@ -176,6 +196,40 @@ class JushuitanShopBalanceImporter ))]; } + /** @return array{0:string,1:?string,2:string,3:string,4:string}|null */ + private function jdWalletFields(array $headers): ?array + { + $fields = []; + + foreach ($headers as $header) { + $title = trim((string) ($header['title'] ?? '')); + $field = trim((string) ($header['fld'] ?? '')); + if ($title !== '' && $field !== '') { + $fields[$title] = $field; + } + } + + if (! isset($fields['费用结算时间']) && ! isset($fields['记录编码']) && ! isset($fields['账户余额'])) { + return null; + } + + $missing = array_values(array_filter( + ['店铺', '费用结算时间', '记录编码', '账户余额'], + static fn (string $title): bool => ! isset($fields[$title]), + )); + if ($missing !== []) { + throw new InvalidArgumentException('京东钱包余额数据缺少“' . implode('”“', $missing) . '”列。'); + } + + return [ + $fields['店铺'], + $fields['账户名称'] ?? null, + $fields['费用结算时间'], + $fields['记录编码'], + $fields['账户余额'], + ]; + } + /** @return array{0:string,1:string,2:?string,3:string,4:?string} */ private function fields(array $headers, ?string $requestedDate): array { @@ -289,6 +343,124 @@ class JushuitanShopBalanceImporter return array_values($rows); } + /** @return list> */ + private function normalizeJdWalletRows( + array $dataRows, + string $balanceDate, + string $storeField, + ?string $accountField, + string $settledAtField, + string $recordCodeField, + string $balanceField, + ): array { + $cutoff = CarbonImmutable::createFromFormat( + '!Y-m-d', + $balanceDate, + (string) config('app.timezone', 'Asia/Shanghai'), + )->endOfDay(); + $latestByStore = []; + + foreach ($dataRows as $row) { + if (! is_array($row)) { + continue; + } + + $storeName = trim((string) ($row[$storeField] ?? '')); + if ($storeName === '' || $storeName === '总计') { + continue; + } + if (mb_strlen($storeName) > 255) { + throw new InvalidArgumentException('聚水潭店铺名称超过 255 个字符:' . mb_substr($storeName, 0, 40)); + } + + $settledAt = $this->settledAt($row[$settledAtField] ?? null, $storeName); + if ($settledAt->isAfter($cutoff)) { + continue; + } + + $recordCode = trim((string) ($row[$recordCodeField] ?? '')); + if (preg_match('/^\d+$/', $recordCode) !== 1) { + throw new InvalidArgumentException("店铺 {$storeName} 的记录编码不是有效非负整数。"); + } + + $sourcePlatform = JushuitanShopBalanceRepository::sourcePlatform($storeName) ?? ''; + $normalizedName = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + $storeKey = hash('sha256', implode("\0", [$sourcePlatform, $normalizedName])); + $candidate = [ + 'settled_at' => $settledAt, + 'record_code' => $recordCode, + 'balance' => $this->amount($row[$balanceField] ?? null, $storeName, $balanceDate), + 'account_id' => $accountField === null ? '' : trim((string) ($row[$accountField] ?? '')), + 'source_platform' => $sourcePlatform, + 'store_name' => $storeName, + 'normalized_store_name' => $normalizedName, + ]; + $current = $latestByStore[$storeKey] ?? null; + + if ($current !== null) { + $comparison = $settledAt->getTimestamp() <=> $current['settled_at']->getTimestamp(); + if ($comparison === 0) { + $comparison = $this->compareNumericStrings($recordCode, $current['record_code']); + if ($comparison === 0 && $candidate['balance'] !== $current['balance']) { + throw new InvalidArgumentException("店铺 {$storeName} 的同一京东钱包记录存在冲突余额。"); + } + } + if ($comparison <= 0) { + continue; + } + } + + $latestByStore[$storeKey] = $candidate; + } + + return array_values(array_map(static function (array $row): array { + $accountId = $row['account_id']; + $rowKey = hash('sha256', implode("\0", [ + $row['source_platform'], + $row['normalized_store_name'], + $accountId, + ])); + + return [ + 'source_platform' => $row['source_platform'], + 'store_name' => $row['store_name'], + 'normalized_store_name' => $row['normalized_store_name'], + 'platform_account_id' => $accountId === '' ? null : mb_substr($accountId, 0, 191), + 'balance' => $row['balance'], + 'source_row_key' => $rowKey, + ]; + }, $latestByStore)); + } + + private function settledAt(mixed $value, string $storeName): CarbonImmutable + { + $raw = trim((string) $value); + + try { + $settledAt = CarbonImmutable::createFromFormat( + '!Y-m-d H:i:s', + $raw, + (string) config('app.timezone', 'Asia/Shanghai'), + ); + } catch (\Throwable) { + throw new InvalidArgumentException("店铺 {$storeName} 的费用结算时间格式无效。"); + } + + if (! $settledAt instanceof CarbonImmutable || $settledAt->format('Y-m-d H:i:s') !== $raw) { + throw new InvalidArgumentException("店铺 {$storeName} 的费用结算时间格式无效。"); + } + + return $settledAt; + } + + private function compareNumericStrings(string $left, string $right): int + { + $left = ltrim($left, '0') ?: '0'; + $right = ltrim($right, '0') ?: '0'; + + return strlen($left) <=> strlen($right) ?: strcmp($left, $right); + } + private function amount(mixed $value, string $storeName, string $date): float { $normalized = str_replace([',', ',', '¥', '¥'], '', trim((string) $value)); diff --git a/tests/Unit/EcommerceFinance/JushuitanShopBalanceRepositoryTest.php b/tests/Unit/EcommerceFinance/JushuitanShopBalanceRepositoryTest.php index 1feb3bf7..7e582fc7 100644 --- a/tests/Unit/EcommerceFinance/JushuitanShopBalanceRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/JushuitanShopBalanceRepositoryTest.php @@ -208,6 +208,95 @@ class JushuitanShopBalanceRepositoryTest extends TestCase $this->assertSame(350.25, (float) $rows->first()->balance); } + public function testItImportsTheLatestJdWalletBalanceAtTheRequestedCutoff(): void + { + $path = $this->xlsxFile([ + ['记录编码', '店铺', '账户名称', '费用结算时间', '账户余额'], + ['90000000000000000001', '京东-同名钱包店', '京东账户', '2026-09-13 22:00:00', 10], + ['90000000000000000002', '京东-同名钱包店', '京东账户', '2026-09-14 22:00:00', 20], + ['100000000000000000003', '京东-同名钱包店', '京东账户', '2026-09-14 22:00:00', 25.5], + ['100000000000000000004', '京东-同名钱包店', '京东账户', '2026-09-15 00:00:00', 999], + ['200000000000000000001', '京喜-京喜钱包店', '京喜账户', '2026-09-14 16:00:00', 30.75], + ['300000000000000000001', '京喜小店-制造店', '京喜小店账户', '2026-09-14 17:00:00', 40.25], + ]); + + $result = app(JushuitanShopBalanceImporter::class)->import( + $path, + '2026-09-14', + 'jd-wallet', + ); + $matches = app(JushuitanShopBalanceRepository::class)->matchesForStores([ + (object) ['id' => 40, 'store_platform' => '京东', 'shop_name' => '同名钱包店', 'erp_store_name' => 'ERP京东店'], + (object) ['id' => 41, 'store_platform' => '京喜', 'shop_name' => '京喜钱包店', 'erp_store_name' => 'ERP京喜店'], + (object) ['id' => 42, 'store_platform' => '京喜', 'shop_name' => '制造店', 'erp_store_name' => 'ERP京喜小店'], + ], '2026-09-14'); + + $this->assertSame(3, $result['total']); + $this->assertSame(25.5, $matches[40]['balance']); + $this->assertSame('京东', $matches[40]['source_platform']); + $this->assertSame(30.75, $matches[41]['balance']); + $this->assertSame('京喜', $matches[41]['source_platform']); + $this->assertSame(40.25, $matches[42]['balance']); + $this->assertSame('京喜小店', $matches[42]['source_platform']); + } + + public function testJdWalletValidationFailureKeepsThePreviousSnapshot(): void + { + $validPath = $this->xlsxFile([ + ['记录编码', '店铺', '账户名称', '费用结算时间', '账户余额'], + ['1', '京东-保留旧余额店', '京东账户', '2026-09-14 12:00:00', 88.88], + ]); + $invalidPath = $this->xlsxFile([ + ['记录编码', '店铺', '账户名称', '账户余额'], + ['2', '京东-保留旧余额店', '京东账户', 99.99], + ]); + + app(JushuitanShopBalanceImporter::class)->import($validPath, '2026-09-14', 'jd-wallet'); + + try { + app(JushuitanShopBalanceImporter::class)->import($invalidPath, '2026-09-14', 'jd-wallet'); + $this->fail('缺少费用结算时间的京东钱包文件不应被导入。'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('费用结算时间', $exception->getMessage()); + } + + $row = DB::connection('business_mirror') + ->table(JushuitanShopBalanceRepository::TABLE) + ->where('balance_date', '2026-09-14') + ->where('source_scope', 'jd-wallet') + ->sole(); + + $this->assertSame('京东-保留旧余额店', $row->store_name); + $this->assertSame(88.88, (float) $row->balance); + } + + public function testJdWalletRowsAfterTheCutoffKeepThePreviousSnapshot(): void + { + $validPath = $this->xlsxFile([ + ['记录编码', '店铺', '费用结算时间', '账户余额'], + ['1', '京东-截止日前店铺', '2026-09-14 23:59:59', 66.66], + ]); + $futurePath = $this->xlsxFile([ + ['记录编码', '店铺', '费用结算时间', '账户余额'], + ['2', '京东-截止日前店铺', '2026-09-15 00:00:00', 77.77], + ]); + + app(JushuitanShopBalanceImporter::class)->import($validPath, '2026-09-14', 'jd-wallet'); + + try { + app(JushuitanShopBalanceImporter::class)->import($futurePath, '2026-09-14', 'jd-wallet'); + $this->fail('截止日期后没有可用数据时不应替换旧快照。'); + } catch (\InvalidArgumentException $exception) { + $this->assertStringContainsString('已保留原有快照', $exception->getMessage()); + } + + $this->assertSame(66.66, (float) DB::connection('business_mirror') + ->table(JushuitanShopBalanceRepository::TABLE) + ->where('balance_date', '2026-09-14') + ->where('source_scope', 'jd-wallet') + ->value('balance')); + } + /** @param array $payload */ private function jsonFile(array $payload): string { @@ -217,4 +306,17 @@ class JushuitanShopBalanceRepositoryTest extends TestCase return $path; } + + /** @param list> $rows */ + private function xlsxFile(array $rows): string + { + $spreadsheet = new Spreadsheet(); + $spreadsheet->getActiveSheet()->fromArray($rows); + $path = sys_get_temp_dir() . '/jushuitan-shop-balance-' . uniqid('', true) . '.xlsx'; + (new Xlsx($spreadsheet))->save($path); + $spreadsheet->disconnectWorksheets(); + $this->temporaryFiles[] = $path; + + return $path; + } } From 769d9a6ad5db375010ed3ae3a5256f7cc51720eb Mon Sep 17 00:00:00 2001 From: renshen <1005457301@qq.com> Date: Wed, 16 Sep 2026 10:23:03 +0800 Subject: [PATCH 009/249] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=BF=AB=E9=80=92?= =?UTF-8?q?=E8=B5=84=E6=96=99=E5=88=86=E9=A1=B5=E7=BB=9F=E8=AE=A1=E9=A6=96?= =?UTF-8?q?=E5=B1=8F=E4=B8=8D=E5=8F=AF=E8=A7=81=20(#191)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../courier-information.blade.php | 45 +++++++++++++------ .../Business/CourierInformationPageTest.php | 8 +++- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/resources/views/business/pages/courier-payables/courier-information.blade.php b/resources/views/business/pages/courier-payables/courier-information.blade.php index 150ddbec..67d23d3f 100644 --- a/resources/views/business/pages/courier-payables/courier-information.blade.php +++ b/resources/views/business/pages/courier-payables/courier-information.blade.php @@ -205,13 +205,21 @@ color: var(--vip-danger, #b80000); } - .courier-information-table-wrap { - overflow-x: auto; + .courier-information-table-panel { + overflow: hidden; border: 1px solid var(--vip-border, #d8d2c7); border-radius: 12px; background: #fff; } + .courier-information-table-wrap { + overflow: auto; + } + + .courier-information-table-wrap.finance-table-scroll-owner { + max-height: max(12rem, calc(100vh - 27.75rem)); + } + .courier-information-table { width: 100%; min-width: 2260px; @@ -265,6 +273,7 @@ justify-content: space-between; gap: 12px; padding: 10px 12px; + border-top: 1px solid var(--vip-border, #d8d2c7); color: var(--vip-content-muted, #595959); font-size: 0.75rem; } @@ -399,8 +408,9 @@ @endif @if ($tab === 'logs') -
-
+
+
+
@forelse ($rows ?? [] as $row) @@ -409,14 +419,16 @@ @endforelse -
ID快递代码操作时间创建时间修改时间
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有操作日志。' }}
+ +
@if ($rows && !$courierError) @endif
@elseif ($tab === 'express') -
- +
+
+
@@ -449,7 +461,8 @@ @endforelse -
ID快递公司代码快递公司名称外部编码杉橙快递代码运费打款方式
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有快递资料。' }}
+ +
@if ($rows && !$courierError) @elseif ($tab === 'networks') -
- +
+
+
@forelse ($rows ?? [] as $row) @@ -471,14 +485,16 @@ @endforelse -
ID快递代码网点代码网点名称网点号省市区乡镇地址联系人联系电话是否启用接口平台创建时间剩余单号
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有网点资料。' }}
+ +
@if ($rows && !$courierError) @endif @else -
- +
+
+
@forelse ($rows ?? [] as $row) @@ -487,7 +503,8 @@ @endforelse -
ID快递代码快递名称账户类型账户账户名称开户行创建时间发票信息ERP账户ID
{{ $courierError ? '数据暂时不可用。' : '当前筛选条件下没有打款账户。' }}
+ +
@if ($rows && !$courierError) @endif diff --git a/tests/Feature/Business/CourierInformationPageTest.php b/tests/Feature/Business/CourierInformationPageTest.php index 56d6e3aa..c89afbbe 100644 --- a/tests/Feature/Business/CourierInformationPageTest.php +++ b/tests/Feature/Business/CourierInformationPageTest.php @@ -74,7 +74,7 @@ class CourierInformationPageTest extends FeatureTestCase ]); $this->app->instance(CourierInformationMirrorRepository::class, $repository); - $this->loginAs() + $response = $this->loginAs() ->get(route('business.pages.show', [ 'section' => 'courier-payables', 'page' => 'courier-information', @@ -86,6 +86,12 @@ class CourierInformationPageTest extends FeatureTestCase ->assertSeeText('SF') ->assertSeeText('同步正常') ->assertSeeText('可达服务') + ->assertSeeText('第 1 / 1 页,本页 1 条,共 1 条') ->assertSee('name="expcode"', false); + + $this->assertMatchesRegularExpression( + '/
\s*
.*?<\/table>\s*<\/div>\s*