Compare commits
1 Commits
main
...
feature/aa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84db8fed9b |
@ -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());
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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', '财务台账管理员'),
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
100
deploy/ai-fin-ledger-views.sql
Normal file
100
deploy/ai-fin-ledger-views.sql
Normal file
@ -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
|
||||
@ -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` 覆盖)。
|
||||
|
||||
@ -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<int,array<string,mixed>> */
|
||||
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<int,array<string,mixed>> */
|
||||
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<int,array<string,mixed>> */
|
||||
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<int,array<string,mixed>> */
|
||||
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<int,array{0:string,1:string}> */
|
||||
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 [
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -12,11 +12,11 @@ class UpstreamConnection
|
||||
/** @var array<string,PDO> */
|
||||
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, '该数据源尚未启用。');
|
||||
|
||||
@ -20,12 +20,21 @@ class UpstreamOdbcConnection
|
||||
/** @var array<string,PDO> */
|
||||
private static array $instances = [];
|
||||
|
||||
public static function get(string $source): PDO
|
||||
/** @var array<string,PDO> */
|
||||
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
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -7,6 +7,9 @@ class UpstreamReadOnlyQueryFactory
|
||||
/** @var array<string,UpstreamReadOnlyQuery> */
|
||||
private array $instances = [];
|
||||
|
||||
/** @var array<string,UpstreamReadOnlyQuery> */
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user