From 84db8fed9ba1d8749920f8585db913641db1a787 Mon Sep 17 00:00:00 2001 From: aaron Date: Wed, 21 Oct 2026 10:02:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=B4=A2=E5=8A=A1=E5=8F=B0=E8=B4=A6):=20?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=20AI=20=E8=BD=BB=E9=87=8F=E8=A7=86=E5=9B=BE?= =?UTF-8?q?=E5=B9=B6=E6=94=B9=E4=B8=BA=E5=88=86=E6=89=B9=E5=A2=9E=E9=87=8F?= =?UTF-8?q?=E5=BF=AB=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/SyncFinanceLedgerRpt.php | 13 +- app/Console/Kernel.php | 2 +- config/finance_ledger.php | 3 + deploy/activate-incremental-release.sh | 2 +- deploy/activate-release.sh | 2 +- deploy/ai-fin-ledger-views.sql | 100 ++++++++++++ docs/财务台账开发说明.md | 30 +++- .../Services/FinanceLedgerRptSynchronizer.php | 150 +++++++++++------- .../FinanceLedgerTransactionWriter.php | 50 ++++-- .../Services/UpstreamConnection.php | 4 +- .../Services/UpstreamOdbcConnection.php | 28 +++- .../Services/UpstreamReadOnlyQuery.php | 10 +- .../Services/UpstreamReadOnlyQueryFactory.php | 12 ++ 13 files changed, 316 insertions(+), 90 deletions(-) create mode 100644 deploy/ai-fin-ledger-views.sql diff --git a/app/Console/Commands/SyncFinanceLedgerRpt.php b/app/Console/Commands/SyncFinanceLedgerRpt.php index 1c79a8627..9d3053f17 100644 --- a/app/Console/Commands/SyncFinanceLedgerRpt.php +++ b/app/Console/Commands/SyncFinanceLedgerRpt.php @@ -11,17 +11,28 @@ class SyncFinanceLedgerRpt extends Command protected $signature = 'finance-ledger:sync-rpt {--from= : 业务日期起,默认读取配置} {--to= : 业务日期止,默认读取配置或当天} + {--days= : 只拉取最近 N 天并合并到现有明细} + {--merge : 合并到现有明细,不删除历史} {--no-recalculate : 只同步明细,不重算流水}'; protected $description = '从 AI 库 rpt 同步财务台账动账明细,并重算每日流水'; public function handle(FinanceLedgerRptSynchronizer $synchronizer): int { + $days = (int) ($this->option('days') ?: 0); + $from = $this->option('from') ?: null; + $merge = (bool) $this->option('merge'); + if ($days > 0) { + $from = now()->subDays(max(1, $days) - 1)->toDateString(); + $merge = true; + } + try { $result = $synchronizer->sync( ! $this->option('no-recalculate'), - $this->option('from') ?: null, + $from, $this->option('to') ?: null, + $merge, ); } catch (Throwable $exception) { $this->error($exception->getMessage()); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index f5561de71..3c6762f46 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -78,7 +78,7 @@ class Kernel extends ConsoleKernel // 财务台账:从 AI 库 rpt 同步动账明细,按日重算账户流水。 // 生产宿主机 cron 仍需配置对应的 finance-ledger:sync-rpt 入口。 - $schedule->command('finance-ledger:sync-rpt') + $schedule->command('finance-ledger:sync-rpt --days=7 --merge') ->dailyAt('02:30') ->timezone('Asia/Shanghai') ->withoutOverlapping(120) diff --git a/config/finance_ledger.php b/config/finance_ledger.php index d2cc830df..cf8992776 100644 --- a/config/finance_ledger.php +++ b/config/finance_ledger.php @@ -12,6 +12,9 @@ return [ // 动账明细的唯一上游来源;本地调试可切换到本地快照导入。 'source' => env('FINANCE_LEDGER_RPT_SOURCE', 'operations_replica'), + // 台账上游查询允许更长的超时;普通页面仍使用共享连接的 15 秒。 + 'query_timeout' => (int) env('FINANCE_LEDGER_QUERY_TIMEOUT', 120), + // 具备账户映射写权限的角色;超级管理员始终可写。 'mapping_editor_roles' => env('FINANCE_LEDGER_MAPPING_EDITOR_ROLES', '财务台账管理员'), diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 1a1a80143..4dcc88f77 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -222,7 +222,7 @@ CRON_TZ=Asia/Shanghai 15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 # 财务台账:每天 02:30 从 AI 库 rpt 同步动账明细并重算流水。 -30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --quiet >/dev/null 2>&1 +30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index c6d3d7c63..336197053 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -226,7 +226,7 @@ CRON_TZ=Asia/Shanghai 15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 # 财务台账:每天 02:30 从 AI 库 rpt 同步动账明细并重算流水。 -30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --quiet >/dev/null 2>&1 +30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 diff --git a/deploy/ai-fin-ledger-views.sql b/deploy/ai-fin-ledger-views.sql new file mode 100644 index 000000000..78051db0d --- /dev/null +++ b/deploy/ai-fin-ledger-views.sql @@ -0,0 +1,100 @@ +-- 财务台账 AI 库轻量视图与索引 +-- 目标库:JSReportReplica +-- 只新增视图/索引并授予 caiwu 只读 SELECT;不修改任何 base 业务数据。 +-- 建议用具备 DDL 权限的维护账号执行。 + +CREATE OR ALTER VIEW rpt.fin_ledger_workorder AS +SELECT Id, woNo, createby, created, completeTime, businessFieldList +FROM rpt.jst_workOrderInfo +WHERE woTypeId = N'9E5A531F48D94AF4B8611FA6918ADA29' + AND status = N'CONFIRMED'; +GO + +CREATE OR ALTER VIEW rpt.fin_ledger_withdrawal AS +SELECT a.Id, a.shop_id, b.shop_name, a.channel, a.fee_time, a.fee_name, a.amount, a.primary_key +FROM rpt.jst_originalBillInfo a +LEFT JOIN rpt.jst_shopInfo b ON b.shop_id = a.shop_id +WHERE a.inout_type = N'-1' + AND a.fee_name LIKE N'%提现%' + AND a.fee_time >= '2026-01-01'; +GO + +CREATE OR ALTER VIEW rpt.fin_ledger_dingtalk_workflow AS +SELECT processInstanceId, processCode, businessId, title, status, originatorUserId, + originatorDeptName, joinAt, finishTime +FROM rpt.ding_Workflow +WHERE processCode IN ( + 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F', + 'PROC-C5159B8D-F412-4DF8-981D-64EBB8D03EB6', + 'PROC-39DD70DE-DAB2-4A5F-B8F1-0B0B68BD0C88', + 'PROC-BBAC7187-9E59-4942-941A-59C7EAF0CEDA', + 'PROC-ACF09A14-B094-46B1-A9E2-8BB1F4E1FDCF', + 'PROC-6407E98B-040A-4C96-AA7D-696650FC1A25' +); +GO + +CREATE OR ALTER VIEW rpt.fin_ledger_dingtalk_scheme AS +SELECT s.id, s.processInstanceId, s.name, s.value +FROM rpt.ding_WorkflowScheme s +WHERE s.name IN (N'付款明细', N'收款费用明细', N'应付明细', N'固定资产报废或出售明细', N'收款合计', N'付款金额合计'); +GO + +CREATE OR ALTER VIEW rpt.fin_ledger_store_opening AS +SELECT a.flowId, a.AccountCode, a.AccountName, a.costType, a.money, a.paymentTime, + a.paymentAccount, b.erpShopName, b.platform, b.applyUser, b.applyDepartment +FROM rpt.fys_shopInfo_kingdeeCode_flow a +LEFT JOIN rpt.fys_shopInfo_flow b ON a.flowId = b.flowId +WHERE a.flowId IN (SELECT flowId FROM rpt.flow_flow WHERE flowType = 8 AND flowStatus = 3) + AND a.type = 1 AND a.isPaymentMade = 1 AND a.money > 0; +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_jst_workOrderInfo_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_jst_workOrderInfo_fin_ledger + ON base.jst_workOrderInfo (Id) + INCLUDE (woNo, createby, created, completeTime) + WHERE woTypeId = N'9E5A531F48D94AF4B8611FA6918ADA29' AND status = N'CONFIRMED' + WITH (ONLINE = ON, MAXDOP = 2); +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_jst_originalBillInfo_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_jst_originalBillInfo_fin_ledger + ON base.jst_originalBillInfo (fee_time) + INCLUDE (Id, shop_id, channel, fee_name, amount, primary_key) + WHERE inout_type = N'-1' AND fee_time >= '2026-01-01' + WITH (ONLINE = ON, MAXDOP = 4, SORT_IN_TEMPDB = ON); +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_ding_Workflow_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_ding_Workflow_fin_ledger + ON base.ding_Workflow (joinAt, processCode) + INCLUDE (processInstanceId, businessId, title, status, originatorUserId, originatorDeptName, finishTime) + WITH (ONLINE = ON, MAXDOP = 2); +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_flow_flow_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_flow_flow_fin_ledger + ON base.flow_flow (flowType, flowStatus, flowId) + INCLUDE (applyUser) + WITH (ONLINE = ON, MAXDOP = 2); +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_fys_shopInfo_kingdeeCode_flow_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_fys_shopInfo_kingdeeCode_flow_fin_ledger + ON base.fys_shopInfo_kingdeeCode_flow (flowId) + INCLUDE (type, isPaymentMade, paymentTime, paymentAccount, costType, money, AccountCode, AccountName) + WITH (ONLINE = ON, MAXDOP = 2); +GO + +IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = 'IX_base_fys_shopInfo_flow_fin_ledger') + CREATE NONCLUSTERED INDEX IX_base_fys_shopInfo_flow_fin_ledger + ON base.fys_shopInfo_flow (flowId) + INCLUDE (erpShopName, platform, applyUser, applyDepartment) + WITH (ONLINE = ON, MAXDOP = 2); +GO + +GRANT SELECT ON OBJECT::rpt.fin_ledger_workorder TO [caiwu]; +GRANT SELECT ON OBJECT::rpt.fin_ledger_withdrawal TO [caiwu]; +GRANT SELECT ON OBJECT::rpt.fin_ledger_dingtalk_workflow TO [caiwu]; +GRANT SELECT ON OBJECT::rpt.fin_ledger_dingtalk_scheme TO [caiwu]; +GRANT SELECT ON OBJECT::rpt.fin_ledger_store_opening TO [caiwu]; +GO diff --git a/docs/财务台账开发说明.md b/docs/财务台账开发说明.md index 0821a212a..428a5b0ff 100644 --- a/docs/财务台账开发说明.md +++ b/docs/财务台账开发说明.md @@ -34,7 +34,7 @@ docker compose -f docker-compose.local.yml exec -u www-data app \ ```bash docker compose -f docker-compose.local.yml exec -u www-data app \ - php artisan finance-ledger:sync-rpt + php artisan finance-ledger:sync-rpt --days=7 --merge ``` 本地尚未接入共享系统数据库时,可在 `runtime/.env` 临时启用 @@ -60,11 +60,33 @@ docker compose -f docker-compose.local.yml exec -u www-data app \ - 路由:`/workspace/financial-ledger/ledger` - 页面:账户总表、店铺台账、每日资金流水、动账明细、账户映射、数据来源 - 写权限:账户映射修改仅系统管理员;其他账号只读 -- 调度:`finance-ledger:sync-rpt` 每天 02:30(Asia/Shanghai) +- 调度:`finance-ledger:sync-rpt --days=7 --merge` 每天 02:30(Asia/Shanghai) 生产宿主机 `/etc/cron.d` 仍需增加每日调用入口;本项目当前没有运行 `schedule:run` 的容器,调度登记不能替代宿主机 cron。 + +## AI 库前置对象 + +生产同步读取以下轻量视图,不再直接查大表: + +- `rpt.fin_ledger_workorder` +- `rpt.fin_ledger_withdrawal` +- `rpt.fin_ledger_dingtalk_workflow` +- `rpt.fin_ledger_dingtalk_scheme` +- `rpt.fin_ledger_store_opening` + +对应索引、视图和 `caiwu` 只读授权脚本在 `deploy/ai-fin-ledger-views.sql`。 +AI 库 ETL 重建 base 表后,需要确认这些索引仍存在。 + +日常同步使用最近 7 天增量合并: + +```bash +php artisan finance-ledger:sync-rpt --days=7 --merge +``` + +历史全量(会删除并重建 `fin_transactions`)使用 `--from/--to`,仅在明确需要重建快照时执行。 + ## 数据安全 真实期初、账户余额和动账明细不得提交到 Git。本地导入文件放在仓库外的 @@ -78,14 +100,14 @@ docker compose -f docker-compose.local.yml exec -u www-data app \ ```bash docker exec -u www-data caiwu_app php artisan finance-ledger:import-base /path/银行当前余额-*.xlsx --recalculate -docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt +docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge docker exec -u www-data caiwu_app php artisan finance-ledger:verify ``` 4. 在宿主机 `/etc/cron.d/caiwu-jiansun-snapshots` 增加: ```cron -30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --quiet >/dev/null 2>&1 +30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 ``` 5. 在「系统设置 → 权限」把「财务台账」页面分配给财务角色;账户映射修改允许超级管理员和「财务台账管理员」角色(可用 `FINANCE_LEDGER_MAPPING_EDITOR_ROLES` 覆盖)。 diff --git a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php index 9bf14f9ab..a10b38c1c 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php @@ -47,13 +47,14 @@ class FinanceLedgerRptSynchronizer ) { } - public function sync(bool $recalculate = true, ?string $from = null, ?string $to = null): array + public function sync(bool $recalculate = true, ?string $from = null, ?string $to = null, bool $merge = false): array { $from = trim((string) ($from ?? config('finance_ledger.window_start', '2026-04-18'))); $to = trim((string) ($to ?? config('finance_ledger.window_end', ''))) ?: now()->toDateString(); + $lookback = $merge ? $from : self::DING_SINCE; $transactions = array_merge( - $this->dingTalkRows(), + $this->dingTalkRows($lookback, $to), $this->workOrderRows(), $this->payableRows($from), $this->storeOpeningRows($from), @@ -69,42 +70,40 @@ class FinanceLedgerRptSynchronizer throw new RuntimeException('rpt 没有返回窗口内的动账明细。'); } - $result = $this->writer->replace($transactions, $recalculate); + $result = $merge + ? $this->writer->merge($transactions, $recalculate) + : $this->writer->replace($transactions, $recalculate); $result['source_counts'] = array_count_values(array_column($transactions, 'process_type')); return $result; } /** @return array> */ - private function dingTalkRows(): array + private function dingTalkRows(string $from, string $to): array { - $processCodes = array_keys((array) config('finance_ledger.dingtalk_process_codes', [])); - if ($processCodes === []) { - throw new RuntimeException('未配置钉钉审批流程编码。'); - } - - $placeholders = implode(',', array_fill(0, count($processCodes), '?')); - $query = $this->queries->forSource(self::SOURCE); + $query = $this->query(); $workflows = $query->select( 'SELECT processInstanceId, processCode, businessId, title, status, originatorUserId, ' - . 'originatorDeptName, joinAt, finishTime FROM rpt.ding_Workflow ' - . 'WHERE joinAt >= ? AND processCode IN (' . $placeholders . ')', - [self::DING_SINCE, ...$processCodes], + . 'originatorDeptName, joinAt, finishTime FROM rpt.fin_ledger_dingtalk_workflow ' + . 'WHERE joinAt >= ? AND joinAt < ?', + [$from, \Carbon\CarbonImmutable::parse($to)->addDay()->toDateString()], ); if ($workflows === []) { return []; } - $schemes = $query->select( - 'SELECT s.id, s.processInstanceId, s.name, CAST(s.value AS VARCHAR(MAX)) AS value ' - . 'FROM rpt.ding_WorkflowScheme s JOIN rpt.ding_Workflow w ON w.processInstanceId = s.processInstanceId ' - . 'WHERE w.joinAt >= ? AND w.processCode IN (' . $placeholders . ') ' - . "AND s.name IN ('付款明细','收款费用明细','应付明细','固定资产报废或出售明细','收款合计','付款金额合计') " - . 'ORDER BY s.id', - [self::DING_SINCE, ...$processCodes], - ); + $schemes = []; + foreach (array_chunk(array_values(array_unique(array_column($workflows, 'processInstanceId'))), 100) as $ids) { + $placeholders = implode(',', array_fill(0, count($ids), '?')); + $batch = $query->select( + 'SELECT s.id, s.processInstanceId, s.name, s.value FROM rpt.fin_ledger_dingtalk_scheme s ' + . 'WHERE s.processInstanceId IN (' . $placeholders . ') ORDER BY s.id', + $ids, + ); + array_push($schemes, ...$batch); + } $employees = []; foreach ($query->select('SELECT userid, name FROM rpt.hr_employee') as $employee) { @@ -260,10 +259,8 @@ class FinanceLedgerRptSynchronizer /** @return array> */ private function workOrderRows(): array { - $rows = $this->queries->forSource(self::SOURCE)->select( - 'SELECT Id, woNo, createby, created, completeTime, businessFieldList FROM rpt.jst_workOrderInfo ' - . 'WHERE woTypeId = ? AND status = ?', - [self::JST_WORK_ORDER_TYPE, 'CONFIRMED'], + $rows = $this->query()->select( + 'SELECT Id, woNo, createby, created, completeTime, businessFieldList FROM rpt.fin_ledger_workorder', ); $result = []; @@ -319,7 +316,7 @@ class FinanceLedgerRptSynchronizer . 'FROM detail d JOIN rpt.biz_bank_receipt_detail r ON r.DetailId = d.id AND r.TaskId = d.business_no ' . "WHERE d.receipt_pay_status IN (N'打款中',N'打款完成')"; - $rows = $this->queries->forSource(self::SOURCE)->select($sql); + $rows = $this->query()->select($sql); $result = []; foreach ($rows as $row) { $amount = $this->toNumber($row['amountLower'] ?? null); @@ -354,14 +351,11 @@ class FinanceLedgerRptSynchronizer /** @return array> */ private function storeOpeningRows(string $from): array { - $sql = 'SELECT a.flowId, a.AccountCode, a.AccountName, a.costType, a.money, a.paymentTime, ' - . 'a.paymentAccount, b.erpShopName, b.platform, b.applyUser, b.applyDepartment ' - . 'FROM rpt.fys_shopInfo_kingdeeCode_flow a ' - . 'LEFT JOIN rpt.fys_shopInfo_flow b ON a.flowId = b.flowId ' - . 'WHERE a.flowId IN (SELECT flowId FROM rpt.flow_flow WHERE flowType = 8 AND flowStatus = 3) ' - . 'AND a.type = 1 AND a.paymentTime >= ? AND a.isPaymentMade = 1 AND a.money > 0'; + $sql = 'SELECT flowId, AccountCode, AccountName, costType, money, paymentTime, ' + . 'paymentAccount, erpShopName, platform, applyUser, applyDepartment ' + . 'FROM rpt.fin_ledger_store_opening WHERE paymentTime >= ?'; - $rows = $this->queries->forSource(self::SOURCE)->select($sql, [$from]); + $rows = $this->query()->select($sql, [$from]); $seen = []; $result = []; foreach ($rows as $row) { @@ -414,38 +408,76 @@ class FinanceLedgerRptSynchronizer /** @return array> */ private function withdrawalRows(string $from): array { - $sql = 'WITH d AS (' - . 'SELECT a.Id, a.shop_id, a.channel, a.fee_time, a.fee_name, a.inout_type, a.amount, a.primary_key, ' - . 'ROW_NUMBER() OVER (PARTITION BY a.primary_key ORDER BY a.Id) AS rn ' - . "FROM rpt.jst_originalBillInfo a WHERE a.fee_name LIKE N'%提现%' AND a.fee_time >= ?" - . ') SELECT d.Id, d.channel, d.fee_time, d.fee_name, d.amount, b.shop_name, d.inout_type ' - . 'FROM d LEFT JOIN rpt.jst_shopInfo b ON d.shop_id = b.shop_id WHERE d.rn = 1'; - - $rows = $this->queries->forSource(self::SOURCE)->select($sql, [$from]); + $query = $this->query(); $result = []; - foreach ($rows as $row) { - if ((string) ($row['inout_type'] ?? '') !== '-1') { - continue; + $seen = []; + + // 视图已经按 fee_time + inout_type 建了过滤索引;这里按月份拉取, + // 应用侧按 primary_key 去重,避免视图内 ROW_NUMBER 全量排序。 + foreach ($this->monthWindows($from, now()->toDateString()) as [$windowStart, $windowEnd]) { + $rows = $query->select( + 'SELECT Id, shop_name, channel, fee_time, fee_name, amount, primary_key ' + . 'FROM rpt.fin_ledger_withdrawal WHERE fee_time >= ? AND fee_time < ?', + [$windowStart, $windowEnd], + ); + + foreach ($rows as $row) { + $primaryKey = trim((string) ($row['primary_key'] ?? '')); + $dedupeKey = $primaryKey !== '' ? $primaryKey : 'ID:' . (string) ($row['Id'] ?? ''); + if (isset($seen[$dedupeKey])) { + continue; + } + $seen[$dedupeKey] = true; + + $shop = trim((string) ($row['shop_name'] ?? '')); + $channel = self::CHANNEL_NAMES[(string) ($row['channel'] ?? '')] ?? (string) ($row['channel'] ?? ''); + $result[] = $this->row([ + 'date' => $this->date($row['fee_time'] ?? null), + 'account_short' => $shop, + 'source_value' => $shop, + 'source' => 'shop', + 'process_type' => '店铺提现', + 'approval_no' => (string) ($row['Id'] ?? ''), + 'detail' => $this->joinParts([$shop, $channel, trim((string) ($row['fee_name'] ?? ''))]), + 'income' => $this->toNumber($row['amount'] ?? null), + 'expense' => 0, + 'pid' => 'BILL-' . (string) ($row['Id'] ?? ''), + ]); } - $shop = trim((string) ($row['shop_name'] ?? '')); - $channel = self::CHANNEL_NAMES[(string) ($row['channel'] ?? '')] ?? (string) ($row['channel'] ?? ''); - $result[] = $this->row([ - 'date' => $this->date($row['fee_time'] ?? null), - 'account_short' => $shop, - 'source_value' => $shop, - 'source' => 'shop', - 'process_type' => '店铺提现', - 'approval_no' => (string) ($row['Id'] ?? ''), - 'detail' => $this->joinParts([$shop, $channel, trim((string) ($row['fee_name'] ?? ''))]), - 'income' => $this->toNumber($row['amount'] ?? null), - 'expense' => 0, - 'pid' => 'BILL-' . (string) ($row['Id'] ?? ''), - ]); } return $result; } + /** @return array */ + private function monthWindows(string $from, string $to): array + { + if ($from === '' || $to === '' || $from > $to) { + return []; + } + + $cursor = \Carbon\CarbonImmutable::parse($from)->startOfMonth(); + $end = \Carbon\CarbonImmutable::parse($to)->addDay()->startOfDay(); + $windows = []; + + while ($cursor->lessThan($end) && count($windows) < 240) { + $next = $cursor->addMonth(); + $upper = $next->lessThan($end) ? $next : $end; + $windows[] = [$cursor->toDateString(), $upper->toDateString()]; + $cursor = $next; + } + + return $windows; + } + + private function query(): UpstreamReadOnlyQuery + { + return $this->queries->forSourceWithTimeout( + self::SOURCE, + (int) config('finance_ledger.query_timeout', 120), + ); + } + private function row(array $data): array { return [ diff --git a/modules/EcommerceFinance/Services/FinanceLedgerTransactionWriter.php b/modules/EcommerceFinance/Services/FinanceLedgerTransactionWriter.php index d5f6238c6..27dfc2fa7 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerTransactionWriter.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerTransactionWriter.php @@ -14,6 +14,17 @@ use RuntimeException; class FinanceLedgerTransactionWriter { public function replace(array $transactions, bool $recalculate = true): array + { + return $this->persist($transactions, $recalculate, true); + } + + /** 只更新/插入本次快照,不删除历史明细;用于每日增量。 */ + public function merge(array $transactions, bool $recalculate = true): array + { + return $this->persist($transactions, $recalculate, false); + } + + private function persist(array $transactions, bool $recalculate, bool $replaceExisting): array { if ($transactions === []) { throw new RuntimeException('没有可写入的动账明细。'); @@ -74,12 +85,23 @@ class FinanceLedgerTransactionWriter throw new RuntimeException('动账明细没有有效日期。'); } - $connection->transaction(function () use ($connection, $rows, $now): void { - $connection->table('fin_transactions')->delete(); - foreach (array_chunk($rows, 500) as $chunk) { - $connection->table('fin_transactions')->insert($chunk); + $connection->transaction(function () use ($connection, $rows, $now, $replaceExisting): void { + if ($replaceExisting) { + $connection->table('fin_transactions')->delete(); } - $this->refreshMappingStats($connection, $now); + foreach (array_chunk($rows, 500) as $chunk) { + if ($replaceExisting) { + $connection->table('fin_transactions')->insert($chunk); + } else { + $connection->table('fin_transactions')->upsert( + $chunk, + ['row_key'], + ['txn_date', 'account_short', 'detail', 'income', 'expense', 'approval_no', + 'source', 'source_value', 'process_type', 'synced_at', 'updated_at'], + ); + } + } + $this->refreshMappingStats($connection, $now, $replaceExisting); }); $result = [ @@ -97,7 +119,7 @@ class FinanceLedgerTransactionWriter return $result; } - private function refreshMappingStats($connection, $now): void + private function refreshMappingStats($connection, $now, bool $pruneStale = true): void { $stats = $connection->table('fin_transactions') ->selectRaw('source, source_value, COUNT(*) AS txn_count, SUM(income) AS income_sum, SUM(expense) AS expense_sum') @@ -125,14 +147,16 @@ class FinanceLedgerTransactionWriter // 上游删除或改写的来源值不能继续留在映射表里;只清理本次未出现的行, // 保留已有 account_short,避免重同步覆盖人工映射。 - $stale = []; - foreach ($connection->table('fin_account_map')->get(['id', 'source', 'source_value']) as $existing) { - if (! isset($keys[(string) $existing->source . "\0" . (string) $existing->source_value])) { - $stale[] = (int) $existing->id; + if ($pruneStale) { + $stale = []; + foreach ($connection->table('fin_account_map')->get(['id', 'source', 'source_value']) as $existing) { + if (! isset($keys[(string) $existing->source . "\0" . (string) $existing->source_value])) { + $stale[] = (int) $existing->id; + } + } + foreach (array_chunk($stale, 500) as $ids) { + $connection->table('fin_account_map')->whereIn('id', $ids)->delete(); } - } - foreach (array_chunk($stale, 500) as $ids) { - $connection->table('fin_account_map')->whereIn('id', $ids)->delete(); } foreach (array_chunk($rows, 500) as $chunk) { diff --git a/modules/EcommerceFinance/Services/UpstreamConnection.php b/modules/EcommerceFinance/Services/UpstreamConnection.php index 8ebc7f082..1e9d57947 100644 --- a/modules/EcommerceFinance/Services/UpstreamConnection.php +++ b/modules/EcommerceFinance/Services/UpstreamConnection.php @@ -12,11 +12,11 @@ class UpstreamConnection /** @var array */ private static array $native = []; - public static function get(string $source): PDO + public static function get(string $source, ?int $queryTimeout = null): PDO { $registry = app(UpstreamSourceRegistry::class); if ($registry->driver($source) === 'sqlsrv') { - return UpstreamOdbcConnection::get($source); + return UpstreamOdbcConnection::get($source, $queryTimeout); } if (! $registry->enabled($source)) { throw new ServiceUnavailableHttpException(30, '该数据源尚未启用。'); diff --git a/modules/EcommerceFinance/Services/UpstreamOdbcConnection.php b/modules/EcommerceFinance/Services/UpstreamOdbcConnection.php index 88b16bc0d..5396220e4 100644 --- a/modules/EcommerceFinance/Services/UpstreamOdbcConnection.php +++ b/modules/EcommerceFinance/Services/UpstreamOdbcConnection.php @@ -20,12 +20,21 @@ class UpstreamOdbcConnection /** @var array */ private static array $instances = []; - public static function get(string $source): PDO + /** @var array */ + private static array $timeoutInstances = []; + + public static function get(string $source, ?int $queryTimeout = null): PDO { $definition = app(UpstreamSourceRegistry::class)->definition($source); $key = $definition['key']; - return self::$instances[$key] ??= self::create($key); + if ($queryTimeout === null) { + return self::$instances[$key] ??= self::create($key); + } + + $cacheKey = $key . '@' . $queryTimeout; + + return self::$timeoutInstances[$cacheKey] ??= self::connect($key, true, $queryTimeout); } public static function create(string $source): PDO @@ -125,7 +134,7 @@ PHP; } } - private static function connect(string $source, bool $requireEnabled): PDO + private static function connect(string $source, bool $requireEnabled, ?int $queryTimeout = null): PDO { $sources = app(UpstreamSourceRegistry::class); $definition = $sources->definition($source); @@ -134,8 +143,13 @@ PHP; throw new ServiceUnavailableHttpException(60, '该上游数据同步尚未启用,请联系管理员。'); } + $connection = (array) $sources->value($source, 'connection', []); + if ($queryTimeout !== null) { + $connection['query_timeout'] = $queryTimeout; + } + return self::open( - (array) $sources->value($source, 'connection', []), + $connection, $definition['key'], $definition['label'], ); @@ -219,12 +233,18 @@ PHP; { if ($source === null) { self::$instances = []; + self::$timeoutInstances = []; return; } $key = app(UpstreamSourceRegistry::class)->definition($source)['key']; unset(self::$instances[$key]); + foreach (array_keys(self::$timeoutInstances) as $cacheKey) { + if (str_starts_with($cacheKey, $key . '@')) { + unset(self::$timeoutInstances[$cacheKey]); + } + } } private static function quoteOdbcValue(string $value): string diff --git a/modules/EcommerceFinance/Services/UpstreamReadOnlyQuery.php b/modules/EcommerceFinance/Services/UpstreamReadOnlyQuery.php index 8d2f6ea1c..f0ae33308 100644 --- a/modules/EcommerceFinance/Services/UpstreamReadOnlyQuery.php +++ b/modules/EcommerceFinance/Services/UpstreamReadOnlyQuery.php @@ -13,8 +13,10 @@ use PDO; */ class UpstreamReadOnlyQuery { - public function __construct(private readonly string $source) - { + public function __construct( + private readonly string $source, + private readonly ?int $queryTimeout = null, + ) { } public function sourceKey(): string @@ -27,7 +29,7 @@ class UpstreamReadOnlyQuery { self::assertReadOnlySql($sql); - $statement = UpstreamConnection::get($this->source)->prepare($sql); + $statement = UpstreamConnection::get($this->source, $this->queryTimeout)->prepare($sql); $statement->execute($bindings); return $statement->fetchAll(PDO::FETCH_ASSOC); @@ -45,7 +47,7 @@ class UpstreamReadOnlyQuery { self::assertReadOnlySql($sql); - $statement = UpstreamConnection::get($this->source)->prepare($sql); + $statement = UpstreamConnection::get($this->source, $this->queryTimeout)->prepare($sql); $statement->execute($bindings); return $statement->fetchColumn(); diff --git a/modules/EcommerceFinance/Services/UpstreamReadOnlyQueryFactory.php b/modules/EcommerceFinance/Services/UpstreamReadOnlyQueryFactory.php index 27c3ebbf0..3ad8838d2 100644 --- a/modules/EcommerceFinance/Services/UpstreamReadOnlyQueryFactory.php +++ b/modules/EcommerceFinance/Services/UpstreamReadOnlyQueryFactory.php @@ -7,6 +7,9 @@ class UpstreamReadOnlyQueryFactory /** @var array */ private array $instances = []; + /** @var array */ + private array $timedInstances = []; + public function __construct(private readonly UpstreamSourceRegistry $sources) { } @@ -17,4 +20,13 @@ class UpstreamReadOnlyQueryFactory return $this->instances[$key] ??= new UpstreamReadOnlyQuery($key); } + + public function forSourceWithTimeout(string $source, int $timeoutSeconds): UpstreamReadOnlyQuery + { + $key = $this->sources->definition($source)['key']; + $timeoutSeconds = max(1, min($timeoutSeconds, 120)); + $cacheKey = $key . '@' . $timeoutSeconds; + + return $this->timedInstances[$cacheKey] ??= new UpstreamReadOnlyQuery($key, $timeoutSeconds); + } } -- 2.47.2