From c1166ea4f77adfbaa36abcc07b213ba08fa6571a Mon Sep 17 00:00:00 2001 From: LiZhi <417430464@qq.com> Date: Wed, 16 Sep 2026 07:01:06 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=9D=BF=E5=9D=97?= =?UTF-8?q?=E6=A0=B7=E5=BC=8F=EF=BC=8C=E8=B0=83=E6=95=B4=E4=B8=9C=E8=B4=A2?= =?UTF-8?q?=E8=A1=8C=E4=B8=9A=E8=AF=A6=E6=83=85=E8=8E=B7=E5=8F=96=E6=96=B9?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../root_cause_localization.json | 39 ++++ .../industry/entity/StockIndustryBoardEm.java | 80 ++++++- .../model/vo/StockIndustryBoardVO.java | 27 +++ .../StockIndustryBoardEmRepository.java | 8 + ...tockIndustryBoardEmPersistenceService.java | 198 ++++++++++++++++++ .../StockIndustryBoardEmQueryService.java | 10 + .../StockIndustryBoardEmSyncService.java | 157 +++----------- .../eastmoney/model/EastmoneyBoardDetail.java | 49 +++++ .../eastmoney/model/EastmoneyBoardList.java | 8 +- .../service/EastmoneyBoardService.java | 53 ++++- ...IndustryBoardEmPersistenceServiceTest.java | 155 ++++++++++++++ .../service/EastmoneyBoardServiceTest.java | 56 +++++ aquant-frontend/src/api/board.ts | 9 + .../views/industry-detail/IndustryDetail.vue | 48 +++++ stock.sql | 15 +- 15 files changed, 780 insertions(+), 132 deletions(-) create mode 100644 .bugfix/em-analysis-timeout/root_cause_localization.json create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceService.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardDetail.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceServiceTest.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardServiceTest.java diff --git a/.bugfix/em-analysis-timeout/root_cause_localization.json b/.bugfix/em-analysis-timeout/root_cause_localization.json new file mode 100644 index 00000000..568c23e1 --- /dev/null +++ b/.bugfix/em-analysis-timeout/root_cause_localization.json @@ -0,0 +1,39 @@ +{ + "issue": "行业涨幅分析页面切换东方财富数据源加载超时", + "issue_number": "em-analysis-timeout", + "symptom": "数据库已有东方财富行业数据,前端 /industrySource/analysis?source=EM 请求超过 axios 60s 超时", + "call_chain": [ + "IndustryRiseAnalysis.vue loadAnalysis -> getIndustrySourceAnalysis(timeout=60000)", + "IndustrySourceController.analysis -> resolve(source=EM, emQueryService::analysis)", + "StockIndustryBoardEmQueryService.analysis -> populateMissingChangeMetrics", + "StockIndustryBoardHistoryEmRepository.findLatestBeforeTradeDateForEachSector (阻塞点)" + ], + "root_cause": { + "summary": "findLatestBeforeTradeDateForEachSector 使用'外层全表扫描 + 相关子查询求 max(trade_date)'结构。stock_industry_board_history_em 含 2000 年至今全量 K 线 1,947,603 行(496 板块),外层每行各执行一次相关子查询(约 195 万次索引回溯),查询结构不可扩展", + "trigger_condition": "近 30 天窗口内 9920 行 change_percent 全部为 NULL(旧版落库代码未计算涨跌幅,且水位已最新导致同步永不重算)-> requiresFallback=true -> 每次请求必触发慢查询", + "evidence": [ + {"check": "表规模", "result": "1,947,603 行 / 496 板块 / 2000-01-04 ~ 2026-09-11"}, + {"check": "近30天窗口", "result": "range_rows=9920, null_pct_rows=9920 (100% NULL 触发补算路径)"}, + {"check": "旧查询实测", "result": "25 秒熔断 ERROR 3024,未执行完成(真实耗时更长,前端 60s 超时)"}, + {"check": "新查询实测", "result": "58ms,返回 496 行,语义等价;EXPLAIN: 派生表 Using index for group-by(4225行) + eq_ref 关联"}, + {"check": "THS 对照", "result": "同结构子查询在 14.6 万行 + 复合索引下可容忍,解释 THS 正常而 EM 超时"} + ] + }, + "affected_code": [ + "aquant-backend/src/main/java/com/brotherc/aquant/industry/repository/StockIndustryBoardHistoryEmRepository.java (findLatestBeforeTradeDateForEachSector)", + "aquant-backend/src/main/java/com/brotherc/aquant/industry/entity/StockIndustryBoardHistoryEm.java (@Table 索引声明缺失)" + ], + "fix": [ + "仓储查询改为'分组求 max + JOIN 回表'原生 SQL,实测 25s+ -> 58ms", + "实体补齐 uk_industry_history_em_sector_date(sector_name,trade_date 唯一) 与 idx_industry_history_em_trade_date 索引声明,与现库同名,ddl-auto:update 对现有库无操作,全新环境自动创建" + ], + "validation": [ + "MySQL 8.0.40 真实库只读实测:旧查询 >25s 未完成,新查询 58ms/496 行", + "mvn compile EXIT=0", + "调用方(StockIndustryBoardEmQueryService.analysis)签名未变,无需改动" + ], + "remaining_risks": [ + "THS 侧 StockIndustryBoardHistoryRepository.findLatestBeforeTradeDateForEachSector 为同结构查询,当前 14.6 万行可容忍,数据增长后建议同步改写", + "库中存量 change_percent=NULL 行不落库回填,由 populateMissingChangeMetrics 每次请求内存补算(现已无性能瓶颈);下次某板块同步成功时 saveHistory 会自动重算该板块全部历史" + ] +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/entity/StockIndustryBoardEm.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/entity/StockIndustryBoardEm.java index a419e310..da575a16 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/industry/entity/StockIndustryBoardEm.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/entity/StockIndustryBoardEm.java @@ -47,11 +47,89 @@ public class StockIndustryBoardEm { private BigDecimal changePercent; /** - * 总成交额 + * 总成交量(万手) + */ + @Column(name = "total_volume") + private BigDecimal totalVolume; + + /** + * 总成交额(亿元) */ @Column(name = "total_amount") private BigDecimal totalAmount; + /** + * 净流入(亿元) + */ + @Column(name = "net_inflow") + private BigDecimal netInflow; + + /** + * 涨跌额(详情快照,列表接口无此字段) + */ + @Column(name = "change_amount") + private BigDecimal changeAmount; + + /** + * 今开(详情快照) + */ + @Column(name = "open_price") + private BigDecimal openPrice; + + /** + * 昨收(详情快照) + */ + @Column(name = "pre_close_price") + private BigDecimal preClosePrice; + + /** + * 最高(详情快照) + */ + @Column(name = "high_price") + private BigDecimal highPrice; + + /** + * 最低(详情快照) + */ + @Column(name = "low_price") + private BigDecimal lowPrice; + + /** + * 换手率(%,详情快照) + */ + @Column(name = "turnover_rate") + private BigDecimal turnoverRate; + + /** + * 量比(详情快照) + */ + @Column(name = "volume_ratio") + private BigDecimal volumeRatio; + + /** + * 外盘(万手,详情快照;内盘=总成交量-外盘,不单独存储) + */ + @Column(name = "outer_disc") + private BigDecimal outerDisc; + + /** + * 流通市值(亿元,详情快照) + */ + @Column(name = "circulating_market_value") + private BigDecimal circulatingMarketValue; + + /** + * 流通股本(亿股,详情快照) + */ + @Column(name = "circulating_shares") + private BigDecimal circulatingShares; + + /** + * 详情快照抓取日期(板块盘口指标为会话快照,按日刷新门控) + */ + @Column(name = "detail_trade_date") + private LocalDate detailTradeDate; + /** * 上涨家数 */ diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/model/vo/StockIndustryBoardVO.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/model/vo/StockIndustryBoardVO.java index a552c7cd..9a1b26f3 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/industry/model/vo/StockIndustryBoardVO.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/model/vo/StockIndustryBoardVO.java @@ -42,6 +42,33 @@ public class StockIndustryBoardVO { @Schema(description = "均价") private BigDecimal averagePrice; + @Schema(description = "今开") + private BigDecimal openPrice; + + @Schema(description = "昨收") + private BigDecimal preClosePrice; + + @Schema(description = "最高") + private BigDecimal highPrice; + + @Schema(description = "最低") + private BigDecimal lowPrice; + + @Schema(description = "换手率(%)") + private BigDecimal turnoverRate; + + @Schema(description = "量比") + private BigDecimal volumeRatio; + + @Schema(description = "外盘(万手)") + private BigDecimal outerDisc; + + @Schema(description = "流通市值(亿元)") + private BigDecimal circulatingMarketValue; + + @Schema(description = "流通股本(亿股)") + private BigDecimal circulatingShares; + @Schema(description = "领涨股") private String leadingStock; diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/repository/StockIndustryBoardEmRepository.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/repository/StockIndustryBoardEmRepository.java index 1bd7ea92..13b890c5 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/industry/repository/StockIndustryBoardEmRepository.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/repository/StockIndustryBoardEmRepository.java @@ -6,11 +6,19 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.time.LocalDate; import java.util.List; @Repository public interface StockIndustryBoardEmRepository extends JpaRepository { StockIndustryBoardEm findBySectorName(String sectorName); + + StockIndustryBoardEm findBySectorCode(String sectorCode); + List findAllByOrderBySeqNoAsc(); + Page findBySectorNameContaining(String sectorName, Pageable pageable); + + /** 是否存在详情快照早于指定日期或从未抓取过的板块(详情按日刷新的门控) */ + boolean existsByDetailTradeDateLessThanOrDetailTradeDateIsNull(LocalDate detailTradeDate); } diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceService.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceService.java new file mode 100644 index 00000000..f86eb49f --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceService.java @@ -0,0 +1,198 @@ +package com.brotherc.aquant.industry.service; + +import com.brotherc.aquant.common.utils.StockHelper; +import com.brotherc.aquant.industry.entity.StockBoardConstituentEm; +import com.brotherc.aquant.industry.entity.StockIndustryBoardEm; +import com.brotherc.aquant.industry.entity.StockIndustryBoardHistoryEm; +import com.brotherc.aquant.industry.repository.StockBoardConstituentEmRepository; +import com.brotherc.aquant.industry.repository.StockIndustryBoardEmRepository; +import com.brotherc.aquant.industry.repository.StockIndustryBoardHistoryEmRepository; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardDetail; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardKline; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardList; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 东方财富行业板块数据的落库服务。独立于同步编排服务(StockIndustryBoardEmSyncService): + * 落库方法若与调用方在同一个 Bean 里,自调用会绕过 Spring 事务代理,@Transactional 静默失效, + * 派生删除(deleteBy.../deleteAll)将因无事务直接抛 TransactionRequiredException。 + * 跨 Bean 调用使事务代理生效,这也是同花顺侧 StockBoardConstituentPersistenceService 的既有模式。 + */ +@Service +@RequiredArgsConstructor +public class StockIndustryBoardEmPersistenceService { + + private final StockHelper stockHelper; + private final StockIndustryBoardEmRepository boardRepository; + private final StockIndustryBoardHistoryEmRepository historyRepository; + private final StockBoardConstituentEmRepository constituentRepository; + + @Transactional(rollbackFor = Exception.class) + public void saveBoards(List boards, LocalDateTime now) { + Map existing = boardRepository.findAll().stream() + .collect(Collectors.toMap(StockIndustryBoardEm::getSectorCode, item -> item, (first, second) -> first)); + // 上游按涨跌幅排序分页拼接,排名变动会使页边界板块在单次响应中重复出现,须批内去重 + Map saves = new LinkedHashMap<>(); + Set sourceSectorCodes = new HashSet<>(boards.size()); + int rank = 0; + for (EastmoneyBoardList.Board board : boards) { + if (board == null || board.getSectorName() == null || board.getSectorName().isBlank()) { + continue; + } + if (board.getSectorCode() == null || board.getSectorCode().isBlank()) { + continue; + } + sourceSectorCodes.add(board.getSectorCode()); + rank++; + StockIndustryBoardEm entity = existing.getOrDefault(board.getSectorCode(), new StockIndustryBoardEm()); + entity.setSeqNo(rank); + entity.setSectorName(board.getSectorName()); + entity.setSectorCode(board.getSectorCode()); + entity.setAveragePrice(board.getLatestPrice()); + entity.setChangePercent(board.getChangePercent()); + entity.setRiseCount(board.getRiseCount()); + entity.setFallCount(board.getFallCount()); + // 东财 clist 返回的成交量为手、成交额/主力净流入为元;换算为与同花顺一致的 + // 万手 / 亿元 / 亿元,前端行情数据面板按此单位展示 + entity.setTotalVolume(yuanVolumeToWanShou(board.getTotalVolume())); + entity.setTotalAmount(yuanAmountToYi(board.getTotalAmount())); + entity.setNetInflow(yuanAmountToYi(board.getNetInflow())); + entity.setLeadingStock(board.getLeadingStock()); + entity.setLeadingStockChangePercent(board.getLeadingStockChangePercent()); + entity.setTradeDate(stockHelper.latestTradeDayFallback(now.toLocalDate())); + entity.setCreateTime(now); + saves.put(board.getSectorCode(), entity); + } + boardRepository.saveAll(saves.values()); + // 与上游列表对账:上游已下线的板块从本地删除(历史/成分股以 sectorName 关联,孤儿数据保留不影响展示) + List stale = existing.values().stream() + .filter(item -> !sourceSectorCodes.contains(item.getSectorCode())) + .toList(); + if (!stale.isEmpty()) { + boardRepository.deleteAll(stale); + } + } + + @Transactional(rollbackFor = Exception.class) + public void saveHistory(String sectorName, List source, LocalDateTime now) { + Map existing = historyRepository + .findBySectorNameOrderByTradeDateAsc(sectorName).stream() + .collect(Collectors.toMap(StockIndustryBoardHistoryEm::getTradeDate, item -> item, (first, second) -> first)); + Map saves = new LinkedHashMap<>(); + for (EastmoneyBoardKline.Bar item : source) { + if (item == null || item.getTime() == null || item.getTime().isBlank()) { + continue; + } + String tradeDate = item.getTime().length() >= 10 ? item.getTime().substring(0, 10) : item.getTime(); + StockIndustryBoardHistoryEm entity = existing.getOrDefault(tradeDate, new StockIndustryBoardHistoryEm()); + entity.setSectorName(sectorName); + entity.setTradeDate(tradeDate); + entity.setOpenPrice(item.getOpenPrice()); + entity.setClosePrice(item.getClosePrice()); + entity.setHighPrice(item.getHighPrice()); + entity.setLowPrice(item.getLowPrice()); + entity.setVolume(item.getVolume()); + entity.setAmount(item.getAmount()); + entity.setChangeAmount(null); + entity.setChangePercent(null); + entity.setCreateTime(now); + saves.put(tradeDate, entity); + } + // 东财板块 K 线不返回涨跌幅,以收盘价相对前一交易日收盘推算当日涨跌幅(首条记录无昨收则留空) + Map merged = new LinkedHashMap<>(existing); + merged.putAll(saves); + List ordered = new ArrayList<>(merged.values()); + ordered.sort(Comparator.comparing(StockIndustryBoardHistoryEm::getTradeDate)); + BigDecimal previousClose = null; + for (StockIndustryBoardHistoryEm entity : ordered) { + if (entity.getClosePrice() != null && previousClose != null) { + BigDecimal changeAmount = entity.getClosePrice().subtract(previousClose); + entity.setChangeAmount(changeAmount); + entity.setChangePercent(previousClose.signum() == 0 ? BigDecimal.ZERO + : changeAmount.multiply(BigDecimal.valueOf(100)).divide(previousClose, 4, RoundingMode.HALF_UP)); + } else if (entity.getClosePrice() != null) { + entity.setChangeAmount(null); + entity.setChangePercent(null); + } + if (entity.getClosePrice() != null) { + previousClose = entity.getClosePrice(); + } + } + historyRepository.saveAll(saves.values()); + } + + @Transactional(rollbackFor = Exception.class) + public void saveConstituents(String sectorName, List source, LocalDateTime now) { + String storageBoardCode = sectorName; + Map existing = constituentRepository + .findByBoardCodeOrderByStockCodeAsc(storageBoardCode).stream() + .collect(Collectors.toMap(StockBoardConstituentEm::getStockCode, item -> item, (first, second) -> first)); + Map valid = source.stream() + .filter(item -> item != null && item.getSectorCode() != null && !item.getSectorCode().isBlank()) + .filter(item -> item.getSectorName() != null && !item.getSectorName().isBlank()) + .collect(Collectors.toMap(EastmoneyBoardList.Board::getSectorCode, item -> item, (first, second) -> second, LinkedHashMap::new)); + if (valid.isEmpty()) { + throw new IllegalStateException("东方财富行业成分股上游未包含有效股票代码"); + } + List saves = valid.values().stream().map(item -> { + StockBoardConstituentEm entity = existing.getOrDefault(item.getSectorCode(), new StockBoardConstituentEm()); + entity.setBoardCode(storageBoardCode); + entity.setStockCode(item.getSectorCode()); + entity.setStockName(item.getSectorName()); + entity.setSourceUpdatedAt(now); + return entity; + }).toList(); + constituentRepository.saveAll(saves); + constituentRepository.deleteByBoardCodeAndStockCodeNotIn(storageBoardCode, List.copyOf(valid.keySet())); + } + + /** + * 板块详情快照落库:详情页盘口指标(今开/昨收/最高/最低/换手/量比/外盘/流通市值/流通股本)。 + * 价格/换手/量比为原始值,外盘由手换算万手,流通市值由元换算亿元,流通股本由股换算亿股; + * 内盘上游不单独提供,前端按 总成交量-外盘 推算 + */ + @Transactional(rollbackFor = Exception.class) + public void applyDetail(StockIndustryBoardEm boardRow, EastmoneyBoardDetail detail, LocalDateTime now) { + boardRow.setChangeAmount(detail.getChangeAmount()); + boardRow.setOpenPrice(detail.getOpenPrice()); + boardRow.setPreClosePrice(detail.getPreClosePrice()); + boardRow.setHighPrice(detail.getHighPrice()); + boardRow.setLowPrice(detail.getLowPrice()); + boardRow.setTurnoverRate(detail.getTurnoverRate()); + boardRow.setVolumeRatio(detail.getVolumeRatio()); + boardRow.setOuterDisc(yuanVolumeToWanShou(detail.getOuterDisc())); + boardRow.setCirculatingMarketValue(yuanAmountToYi(detail.getCirculatingMarketValue())); + boardRow.setCirculatingShares(yuanAmountToYi(detail.getCirculatingShares())); + boardRow.setDetailTradeDate(now.toLocalDate()); + boardRepository.save(boardRow); + } + + private static final BigDecimal ONE_YI = BigDecimal.valueOf(100_000_000L); + private static final BigDecimal ONE_WAN_SHOU = BigDecimal.valueOf(10_000L); + + /** 东财成交额/主力净流入单位换算:元 → 亿元 */ + private BigDecimal yuanAmountToYi(BigDecimal yuan) { + if (yuan == null) return null; + return yuan.divide(ONE_YI, 4, RoundingMode.HALF_UP); + } + + /** 东财成交量单位换算:手 → 万手 */ + private BigDecimal yuanVolumeToWanShou(BigDecimal shou) { + if (shou == null) return null; + return shou.divide(ONE_WAN_SHOU, 4, RoundingMode.HALF_UP); + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmQueryService.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmQueryService.java index 7db91c48..b72a073c 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmQueryService.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmQueryService.java @@ -144,6 +144,16 @@ public StockIndustryBoardVO overview(String industry, LocalDate tradeDate) { view.setLeadingStock(null); view.setLeadingStockPrice(null); view.setLeadingStockChangePercent(null); + // 今开/昨收/最高/最低等详情快照只属于当前会话:历史日期视图改用该日K线数据,其余快照字段清空 + view.setOpenPrice(history.getOpenPrice()); + view.setHighPrice(history.getHighPrice()); + view.setLowPrice(history.getLowPrice()); + view.setPreClosePrice(null); + view.setTurnoverRate(null); + view.setVolumeRatio(null); + view.setOuterDisc(null); + view.setCirculatingMarketValue(null); + view.setCirculatingShares(null); } return view; } diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmSyncService.java b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmSyncService.java index 3f705fa0..7a3c992f 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmSyncService.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmSyncService.java @@ -2,12 +2,11 @@ import com.brotherc.aquant.common.utils.StockHelper; import com.brotherc.aquant.common.utils.StockUtils; -import com.brotherc.aquant.industry.entity.StockBoardConstituentEm; import com.brotherc.aquant.industry.entity.StockIndustryBoardEm; import com.brotherc.aquant.industry.entity.StockIndustryBoardHistoryEm; -import com.brotherc.aquant.industry.repository.StockBoardConstituentEmRepository; import com.brotherc.aquant.industry.repository.StockIndustryBoardHistoryEmRepository; import com.brotherc.aquant.industry.repository.StockIndustryBoardEmRepository; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardDetail; import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardKline; import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardList; import com.brotherc.aquant.integration.eastmoney.service.EastmoneyBoardService; @@ -19,22 +18,14 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; -import java.math.BigDecimal; -import java.math.RoundingMode; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; @Slf4j @Service @@ -52,9 +43,9 @@ public class StockIndustryBoardEmSyncService { private final StockSyncRepository stockSyncRepository; private final StockIndustryBoardEmRepository boardRepository; private final StockIndustryBoardHistoryEmRepository historyRepository; - private final StockBoardConstituentEmRepository constituentRepository; private final EastmoneyBoardService eastmoneyBoardService; private final EastmoneyQuoteGateway eastmoneyQuoteGateway; + private final StockIndustryBoardEmPersistenceService industryBoardEmPersistenceService; /** 同步进行中标志:Cookie 触发与调度触发可能并发,CAS 保证同一时刻只有一轮同步 */ private final AtomicBoolean syncRunning = new AtomicBoolean(false); @@ -84,12 +75,9 @@ public void synchronizeIfRequired(LocalDateTime now) { private void doSynchronizeIfRequired(LocalDateTime now) { long targetWatermark = stockHelper.getLatestClosedTradeDaySyncWatermark(now); Long currentWatermark = StockUtils.parseSyncTimestamp(stockSyncRepository.findByName(WATERMARK)); - if (currentWatermark != null && currentWatermark >= targetWatermark - && !boardRepository.findAll().isEmpty()) { - log.info("东方财富行业同步跳过: 水位已是最新, watermark={}", currentWatermark); - return; - } + // 板块行情列表(含成交额/成交量/净流入)随每次触发刷新:单次 clist 分页拉取成本低、幂等, + // 且修正存量字段需即时生效,不随水位跳过 EastmoneyBoardList boardList; try { boardList = callWithRetry(eastmoneyBoardService::fetchBoardList); @@ -103,11 +91,19 @@ private void doSynchronizeIfRequired(LocalDateTime now) { return; } try { - saveBoards(boards, now); + industryBoardEmPersistenceService.saveBoards(boards, now); } catch (RuntimeException exception) { log.warn("东方财富行业列表落库失败,保留缓存等待下次触发", exception); return; } + + // 历史K线/成分股按逐板块水位与断点续传,成本较高;水位已是最新且详情快照均已刷新到当日时跳过逐板块拉取 + if (currentWatermark != null && currentWatermark >= targetWatermark + && !boardRepository.existsByDetailTradeDateLessThanOrDetailTradeDateIsNull(now.toLocalDate())) { + log.info("东方财富行业列表已刷新,历史/成分股水位与详情快照已是最新, watermark={}", currentWatermark); + return; + } + long startMillis = System.currentTimeMillis(); log.info("东方财富行业同步开始: targetWatermark={}, 板块数={}", targetWatermark, boards.size()); int synced = 0; @@ -174,7 +170,10 @@ private BoardSyncOutcome synchronizeBoard(EastmoneyBoardList.Board board, LocalD Long constituentWatermark = StockUtils.parseSyncTimestamp( stockSyncRepository.findByName(CONSTITUENT_WATERMARK_PREFIX + sectorName)); boolean requiresConstituents = constituentWatermark == null || constituentWatermark < targetWatermark; - if (!requiresHistory && !requiresConstituents) { + StockIndustryBoardEm boardRow = boardRepository.findBySectorCode(board.getSectorCode()); + boolean requiresDetail = boardRow != null && (boardRow.getDetailTradeDate() == null + || boardRow.getDetailTradeDate().isBefore(now.toLocalDate())); + if (!requiresHistory && !requiresConstituents && !requiresDetail) { return BoardSyncOutcome.SKIPPED; } List history = requiresHistory ? callWithRetry(() -> @@ -191,12 +190,24 @@ private BoardSyncOutcome synchronizeBoard(EastmoneyBoardList.Board board, LocalD return BoardSyncOutcome.FAILED; } if (requiresHistory) { - saveHistory(sectorName, history, now); + industryBoardEmPersistenceService.saveHistory(sectorName, history, now); } if (requiresConstituents) { - saveConstituents(sectorName, constituents, now); + industryBoardEmPersistenceService.saveConstituents(sectorName, constituents, now); writeConstituentWatermark(sectorName, targetWatermark); } + if (requiresDetail) { + // 详情快照失败不判定板块失败:K线/成分股可能已成功落库,快照留待下次触发重抓 + try { + EastmoneyBoardDetail detail = callWithRetry( + () -> eastmoneyBoardService.fetchBoardDetail(board.getSectorCode())); + industryBoardEmPersistenceService.applyDetail(boardRow, detail, now); + } catch (EastmoneyCoolingDownException exception) { + throw exception; + } catch (RuntimeException exception) { + log.warn("东方财富板块详情快照抓取失败,sectorName={},下次触发重试", sectorName, exception); + } + } return BoardSyncOutcome.SYNCED; } catch (EastmoneyCoolingDownException exception) { log.warn("东方财富行情源熔断冷却中,板块未同步: sectorName={}, 原因={}", sectorName, exception.getMessage()); @@ -246,112 +257,6 @@ private T callWithRetry(java.util.function.Supplier request) { throw lastException == null ? new IllegalStateException("东方财富请求失败") : lastException; } - @Transactional(rollbackFor = Exception.class) - void saveBoards(List boards, LocalDateTime now) { - Map existing = boardRepository.findAll().stream() - .collect(Collectors.toMap(StockIndustryBoardEm::getSectorCode, item -> item, (first, second) -> first)); - // 上游按涨跌幅排序分页拼接,排名变动会使页边界板块在单次响应中重复出现,须批内去重 - Map saves = new LinkedHashMap<>(); - int rank = 0; - for (EastmoneyBoardList.Board board : boards) { - if (board == null || board.getSectorName() == null || board.getSectorName().isBlank()) { - continue; - } - if (board.getSectorCode() == null || board.getSectorCode().isBlank()) { - continue; - } - rank++; - StockIndustryBoardEm entity = existing.getOrDefault(board.getSectorCode(), new StockIndustryBoardEm()); - entity.setSeqNo(rank); - entity.setSectorName(board.getSectorName()); - entity.setSectorCode(board.getSectorCode()); - entity.setAveragePrice(board.getLatestPrice()); - entity.setChangePercent(board.getChangePercent()); - entity.setRiseCount(board.getRiseCount()); - entity.setFallCount(board.getFallCount()); - entity.setTotalAmount(board.getTotalMarketValue()); - entity.setLeadingStock(board.getLeadingStock()); - entity.setLeadingStockChangePercent(board.getLeadingStockChangePercent()); - entity.setTradeDate(stockHelper.latestTradeDayFallback(now.toLocalDate())); - entity.setCreateTime(now); - saves.put(board.getSectorCode(), entity); - } - boardRepository.saveAll(saves.values()); - } - - @Transactional(rollbackFor = Exception.class) - void saveHistory(String sectorName, List source, LocalDateTime now) { - Map existing = historyRepository - .findBySectorNameOrderByTradeDateAsc(sectorName).stream() - .collect(Collectors.toMap(StockIndustryBoardHistoryEm::getTradeDate, item -> item, (first, second) -> first)); - Map saves = new LinkedHashMap<>(); - for (EastmoneyBoardKline.Bar item : source) { - if (item == null || item.getTime() == null || item.getTime().isBlank()) { - continue; - } - String tradeDate = item.getTime().length() >= 10 ? item.getTime().substring(0, 10) : item.getTime(); - StockIndustryBoardHistoryEm entity = existing.getOrDefault(tradeDate, new StockIndustryBoardHistoryEm()); - entity.setSectorName(sectorName); - entity.setTradeDate(tradeDate); - entity.setOpenPrice(item.getOpenPrice()); - entity.setClosePrice(item.getClosePrice()); - entity.setHighPrice(item.getHighPrice()); - entity.setLowPrice(item.getLowPrice()); - entity.setVolume(item.getVolume()); - entity.setAmount(item.getAmount()); - entity.setChangeAmount(null); - entity.setChangePercent(null); - entity.setCreateTime(now); - saves.put(tradeDate, entity); - } - // 东财板块 K 线不返回涨跌幅,以收盘价相对前一交易日收盘推算当日涨跌幅(首条记录无昨收则留空) - Map merged = new LinkedHashMap<>(existing); - merged.putAll(saves); - List ordered = new ArrayList<>(merged.values()); - ordered.sort(Comparator.comparing(StockIndustryBoardHistoryEm::getTradeDate)); - BigDecimal previousClose = null; - for (StockIndustryBoardHistoryEm entity : ordered) { - if (entity.getClosePrice() != null && previousClose != null) { - BigDecimal changeAmount = entity.getClosePrice().subtract(previousClose); - entity.setChangeAmount(changeAmount); - entity.setChangePercent(previousClose.signum() == 0 ? BigDecimal.ZERO - : changeAmount.multiply(BigDecimal.valueOf(100)).divide(previousClose, 4, RoundingMode.HALF_UP)); - } else if (entity.getClosePrice() != null) { - entity.setChangeAmount(null); - entity.setChangePercent(null); - } - if (entity.getClosePrice() != null) { - previousClose = entity.getClosePrice(); - } - } - historyRepository.saveAll(saves.values()); - } - - @Transactional(rollbackFor = Exception.class) - void saveConstituents(String sectorName, List source, LocalDateTime now) { - String storageBoardCode = sectorName; - Map existing = constituentRepository - .findByBoardCodeOrderByStockCodeAsc(storageBoardCode).stream() - .collect(Collectors.toMap(StockBoardConstituentEm::getStockCode, item -> item, (first, second) -> first)); - Map valid = source.stream() - .filter(item -> item != null && item.getSectorCode() != null && !item.getSectorCode().isBlank()) - .filter(item -> item.getSectorName() != null && !item.getSectorName().isBlank()) - .collect(Collectors.toMap(EastmoneyBoardList.Board::getSectorCode, item -> item, (first, second) -> second, LinkedHashMap::new)); - if (valid.isEmpty()) { - throw new IllegalStateException("东方财富行业成分股上游未包含有效股票代码"); - } - List saves = valid.values().stream().map(item -> { - StockBoardConstituentEm entity = existing.getOrDefault(item.getSectorCode(), new StockBoardConstituentEm()); - entity.setBoardCode(storageBoardCode); - entity.setStockCode(item.getSectorCode()); - entity.setStockName(item.getSectorName()); - entity.setSourceUpdatedAt(now); - return entity; - }).toList(); - constituentRepository.saveAll(saves); - constituentRepository.deleteByBoardCodeAndStockCodeNotIn(storageBoardCode, List.copyOf(valid.keySet())); - } - private boolean sleep(long millis) { try { TimeUnit.MILLISECONDS.sleep(millis); diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardDetail.java b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardDetail.java new file mode 100644 index 00000000..f051d427 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardDetail.java @@ -0,0 +1,49 @@ +package com.brotherc.aquant.integration.eastmoney.model; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * 东方财富行业板块详情快照 (push2 stock/get 接口,板块详情页顶部的盘口指标)。 + * 板块列表接口(clist)只有涨跌幅/成交/资金等汇总列,今开/昨收/最高/最低/换手/量比/ + * 内外盘/流通市值/流通股本仅在单板块详情接口返回。 + */ +@Data +public class EastmoneyBoardDetail { + + /** 板块代码,如 BK1201 (f57) */ + private String sectorCode; + /** 板块名称 (f58) */ + private String sectorName; + /** 最新价 (f43) */ + private BigDecimal latestPrice; + /** 今开 (f46) */ + private BigDecimal openPrice; + /** 昨收 (f60) */ + private BigDecimal preClosePrice; + /** 最高 (f44) */ + private BigDecimal highPrice; + /** 最低 (f45) */ + private BigDecimal lowPrice; + /** 涨跌额 (f169) */ + private BigDecimal changeAmount; + /** 涨跌幅(百分比)(f170) */ + private BigDecimal changePercent; + /** 振幅(百分比)(f171) */ + private BigDecimal amplitude; + /** 成交量(手)(f47) */ + private BigDecimal volume; + /** 成交额(元)(f48) */ + private BigDecimal amount; + /** 换手率(百分比)(f168) */ + private BigDecimal turnoverRate; + /** 量比 (f50) */ + private BigDecimal volumeRatio; + /** 外盘(手)(f49)。上游无独立内盘字段,内盘=成交量-外盘 */ + private BigDecimal outerDisc; + /** 流通市值(元)(f117) */ + private BigDecimal circulatingMarketValue; + /** 流通股本(股)(f85) */ + private BigDecimal circulatingShares; +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardList.java b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardList.java index c7a42865..09ddd598 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardList.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/model/EastmoneyBoardList.java @@ -24,8 +24,12 @@ public static class Board { private BigDecimal latestPrice; /** 涨跌幅(百分比,东财 fltt=2 时已放大100倍为数值,如 2.57 表示 +2.57%) */ private BigDecimal changePercent; - /** 总市值(元) */ - private BigDecimal totalMarketValue; + /** 总成交量(手) */ + private BigDecimal totalVolume; + /** 总成交额(元) */ + private BigDecimal totalAmount; + /** 主力净流入(元,可能为负) */ + private BigDecimal netInflow; /** 上涨家数 */ private Integer riseCount; /** 下跌家数 */ diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardService.java b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardService.java index d6457b96..4c29575d 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardService.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardService.java @@ -1,6 +1,7 @@ package com.brotherc.aquant.integration.eastmoney.service; import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardDetail; import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardKline; import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardList; import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardTrends; @@ -27,6 +28,14 @@ public class EastmoneyBoardService { private static final String BOARD_MARKET_PREFIX = "90."; private static final String KLINE_URL = "https://push2his.eastmoney.com/api/qt/stock/kline/get"; private static final String TRENDS_URL = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"; + /** + * stock/get 详情快照字段(与浏览器详情页一致):f57/f58 代码名称,f43 最新,f44-f46 最高/最低/今开, + * f47 成交量(手),f48 成交额(元),f49 外盘(手),f50 量比,f60 昨收,f85 流通股本(股), + * f117 流通市值(元),f168 换手率,f169-f171 涨跌额/涨跌幅/振幅。 + * 上游无独立内盘字段(内盘=成交量-外盘),f65/f66 对板块恒为空。 + */ + private static final String DETAIL_FIELDS = + "f57,f58,f43,f44,f45,f46,f47,f48,f49,f50,f60,f85,f117,f168,f169,f170,f171"; /** * 单页条数。浏览器实际值为 20。pz=100 全量翻页请求更集中、单次响应更大, * 实测更容易触发东财按主机的频次软封(502 / 空响应体),故对齐浏览器行为。 @@ -67,7 +76,7 @@ public EastmoneyBoardList fetchBoardList() { .addQueryParameter("invt", "2") .addQueryParameter("fid", "f3") .addQueryParameter("fs", "m:90+t:2+f:!50") - .addQueryParameter("fields", "f12,f14,f2,f3,f20,f104,f105,f140,f136")) + .addQueryParameter("fields", "f12,f14,f2,f3,f5,f6,f62,f104,f105,f140,f136")) .path("data"); int total = data.path("total").asInt(0); JsonNode diff = data.path("diff"); @@ -81,7 +90,9 @@ public EastmoneyBoardList fetchBoardList() { board.setSectorName(item.path("f14").asText()); board.setLatestPrice(parseDecimal(item.path("f2"))); board.setChangePercent(parseDecimal(item.path("f3"))); - board.setTotalMarketValue(parseDecimal(item.path("f20"))); + board.setTotalVolume(parseDecimal(item.path("f5"))); + board.setTotalAmount(parseDecimal(item.path("f6"))); + board.setNetInflow(parseDecimal(item.path("f62"))); board.setRiseCount(item.path("f104").isNumber() ? item.path("f104").asInt() : null); board.setFallCount(item.path("f105").isNumber() ? item.path("f105").asInt() : null); board.setLeadingStock(item.path("f140").asText(null)); @@ -151,6 +162,44 @@ public List fetchBoardConstituents(String sectorCode) return result; } + /** + * 板块详情快照(详情页顶部盘口指标:今开/昨收/最高/最低/换手/量比/外盘/流通市值/流通股本等)。 + * 走实时行情主机(push2delay 优先),与板块列表一致。 + * + * @param sectorCode 板块代码,如 BK1201 + */ + public EastmoneyBoardDetail fetchBoardDetail(String sectorCode) { + JsonNode data = quoteGateway.executeQuote(builder -> builder + .addPathSegments("api/qt/stock/get") + .addQueryParameter("secid", BOARD_MARKET_PREFIX + sectorCode) + .addQueryParameter("fltt", "2") + .addQueryParameter("invt", "2") + .addQueryParameter("fields", DETAIL_FIELDS)) + .path("data"); + if (data.isMissingNode() || data.isNull() || data.path("f57").asText("").isBlank()) { + throw ExceptionEnum.API_REQUEST_ERROR.toException(); + } + EastmoneyBoardDetail detail = new EastmoneyBoardDetail(); + detail.setSectorCode(data.path("f57").asText()); + detail.setSectorName(data.path("f58").asText(null)); + detail.setLatestPrice(parseDecimal(data.path("f43"))); + detail.setOpenPrice(parseDecimal(data.path("f46"))); + detail.setPreClosePrice(parseDecimal(data.path("f60"))); + detail.setHighPrice(parseDecimal(data.path("f44"))); + detail.setLowPrice(parseDecimal(data.path("f45"))); + detail.setChangeAmount(parseDecimal(data.path("f169"))); + detail.setChangePercent(parseDecimal(data.path("f170"))); + detail.setAmplitude(parseDecimal(data.path("f171"))); + detail.setVolume(parseDecimal(data.path("f47"))); + detail.setAmount(parseDecimal(data.path("f48"))); + detail.setTurnoverRate(parseDecimal(data.path("f168"))); + detail.setVolumeRatio(parseDecimal(data.path("f50"))); + detail.setOuterDisc(parseDecimal(data.path("f49"))); + detail.setCirculatingMarketValue(parseDecimal(data.path("f117"))); + detail.setCirculatingShares(parseDecimal(data.path("f85"))); + return detail; + } + /** * 板块日K线 * diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceServiceTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceServiceTest.java new file mode 100644 index 00000000..7676047c --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/industry/service/StockIndustryBoardEmPersistenceServiceTest.java @@ -0,0 +1,155 @@ +package com.brotherc.aquant.industry.service; + +import com.brotherc.aquant.common.utils.StockHelper; +import com.brotherc.aquant.industry.entity.StockIndustryBoardEm; +import com.brotherc.aquant.industry.entity.StockIndustryBoardHistoryEm; +import com.brotherc.aquant.industry.repository.StockBoardConstituentEmRepository; +import com.brotherc.aquant.industry.repository.StockIndustryBoardEmRepository; +import com.brotherc.aquant.industry.repository.StockIndustryBoardHistoryEmRepository; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardDetail; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardKline; +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardList; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class StockIndustryBoardEmPersistenceServiceTest { + + @Mock + private StockHelper stockHelper; + + @Mock + private StockIndustryBoardEmRepository boardRepository; + + @Mock + private StockIndustryBoardHistoryEmRepository historyRepository; + + @Mock + private StockBoardConstituentEmRepository constituentRepository; + + @InjectMocks + private StockIndustryBoardEmPersistenceService service; + + @Test + void applyDetailStoresSnapshotWithNormalizedUnits() { + StockIndustryBoardEm row = new StockIndustryBoardEm(); + row.setSectorCode("BK1201"); + row.setTotalVolume(new BigDecimal("10184.9492")); + EastmoneyBoardDetail detail = detail(); + LocalDateTime now = LocalDateTime.of(2026, 9, 14, 16, 0); + + service.applyDetail(row, detail, now); + + assertThat(row.getChangeAmount()).isEqualByComparingTo("147.92"); + assertThat(row.getOpenPrice()).isEqualByComparingTo("12591.8"); + assertThat(row.getPreClosePrice()).isEqualByComparingTo("12730.57"); + assertThat(row.getHighPrice()).isEqualByComparingTo("12956.03"); + assertThat(row.getLowPrice()).isEqualByComparingTo("12464.95"); + assertThat(row.getTurnoverRate()).isEqualByComparingTo("2.78"); + assertThat(row.getVolumeRatio()).isEqualByComparingTo("0.98"); + // 外盘 手 → 万手 + assertThat(row.getOuterDisc()).isEqualByComparingTo("5155.072"); + // 流通市值 元 → 亿元 + assertThat(row.getCirculatingMarketValue()).isEqualByComparingTo("156836.073"); + // 流通股本 股 → 亿股 + assertThat(row.getCirculatingShares()).isEqualByComparingTo("3666.8188"); + assertThat(row.getDetailTradeDate()).isEqualTo(LocalDate.of(2026, 9, 14)); + verify(boardRepository).save(row); + } + + @Test + void saveHistoryComputesChangeMetricsFromPreviousClose() { + LocalDateTime now = LocalDateTime.of(2026, 9, 14, 16, 0); + when(historyRepository.findBySectorNameOrderByTradeDateAsc("电子")).thenReturn(List.of()); + + service.saveHistory("电子", List.of( + bar("2026-09-11 15:00", "12730.57"), + bar("2026-09-14 15:00", "12878.49")), now); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Collection.class); + verify(historyRepository).saveAll(captor.capture()); + List saved = new ArrayList<>(captor.getValue()); + assertThat(saved).hasSize(2); + // 首条无前收盘,涨跌指标留空 + assertThat(saved.get(0).getChangePercent()).isNull(); + assertThat(saved.get(0).getChangeAmount()).isNull(); + // 次日按前收盘推算 + assertThat(saved.get(1).getChangeAmount()).isEqualByComparingTo("147.92"); + BigDecimal expectedPercent = new BigDecimal("147.92").multiply(BigDecimal.valueOf(100)) + .divide(new BigDecimal("12730.57"), 4, RoundingMode.HALF_UP); + assertThat(saved.get(1).getChangePercent()).isEqualByComparingTo(expectedPercent); + } + + @Test + void saveBoardsNormalizesUnitsAndRemovesDelistedBoards() { + LocalDateTime now = LocalDateTime.of(2026, 9, 14, 16, 0); + EastmoneyBoardList.Board live = listBoard("BK1201", "电子"); + live.setTotalVolume(new BigDecimal("101849492")); + live.setTotalAmount(new BigDecimal("429962094959")); + live.setNetInflow(new BigDecimal(-5000000000L)); + StockIndustryBoardEm stale = new StockIndustryBoardEm(); + stale.setSectorCode("BK9999"); + stale.setSectorName("旧板块"); + when(boardRepository.findAll()).thenReturn(List.of(stale)); + when(stockHelper.latestTradeDayFallback(now.toLocalDate())).thenReturn(LocalDate.of(2026, 9, 14)); + + service.saveBoards(List.of(live), now); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(Collection.class); + verify(boardRepository).saveAll(captor.capture()); + StockIndustryBoardEm saved = captor.getValue().iterator().next(); + // 成交量 手 → 万手,成交额/净流入 元 → 亿元 + assertThat(saved.getTotalVolume()).isEqualByComparingTo("10184.9492"); + assertThat(saved.getTotalAmount()).isEqualByComparingTo("4299.6209"); + assertThat(saved.getNetInflow()).isEqualByComparingTo("-50"); + // 上游已下线的板块被对账删除 + verify(boardRepository).deleteAll(List.of(stale)); + } + + private EastmoneyBoardDetail detail() { + EastmoneyBoardDetail detail = new EastmoneyBoardDetail(); + detail.setSectorCode("BK1201"); + detail.setSectorName("电子"); + detail.setChangeAmount(new BigDecimal("147.92")); + detail.setOpenPrice(new BigDecimal("12591.8")); + detail.setPreClosePrice(new BigDecimal("12730.57")); + detail.setHighPrice(new BigDecimal("12956.03")); + detail.setLowPrice(new BigDecimal("12464.95")); + detail.setTurnoverRate(new BigDecimal("2.78")); + detail.setVolumeRatio(new BigDecimal("0.98")); + detail.setOuterDisc(new BigDecimal("51550720")); + detail.setCirculatingMarketValue(new BigDecimal("15683607296000")); + detail.setCirculatingShares(new BigDecimal("366681878528")); + return detail; + } + + private EastmoneyBoardKline.Bar bar(String time, String close) { + EastmoneyBoardKline.Bar bar = new EastmoneyBoardKline.Bar(); + bar.setTime(time); + bar.setClosePrice(new BigDecimal(close)); + return bar; + } + + private EastmoneyBoardList.Board listBoard(String code, String name) { + EastmoneyBoardList.Board board = new EastmoneyBoardList.Board(); + board.setSectorCode(code); + board.setSectorName(name); + return board; + } +} diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardServiceTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardServiceTest.java new file mode 100644 index 00000000..af57f95f --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyBoardServiceTest.java @@ -0,0 +1,56 @@ +package com.brotherc.aquant.integration.eastmoney.service; + +import com.brotherc.aquant.integration.eastmoney.model.EastmoneyBoardDetail; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.math.BigDecimal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EastmoneyBoardServiceTest { + + @Mock + private EastmoneyQuoteGateway quoteGateway; + + @InjectMocks + private EastmoneyBoardService service; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + void fetchBoardDetailParsesSnapshotFields() throws Exception { + // 90.BK1201 电子 2026-09-14 收盘后的 stock/get 实测响应(截取用到的字段) + String json = """ + {"rc":0,"data":{"f43":12878.49,"f44":12956.03,"f45":12464.95,"f46":12591.8, + "f47":101849492,"f48":429962094959.0,"f49":51550720,"f50":0.98,"f57":"BK1201", + "f58":"电子","f60":12730.57,"f85":366681878528.0,"f117":15683607296000.0, + "f168":2.78,"f169":147.92,"f170":1.16,"f171":3.86}} + """; + when(quoteGateway.executeQuote(any())).thenReturn(objectMapper.readTree(json)); + + EastmoneyBoardDetail detail = service.fetchBoardDetail("BK1201"); + + assertThat(detail.getSectorCode()).isEqualTo("BK1201"); + assertThat(detail.getSectorName()).isEqualTo("电子"); + assertThat(detail.getLatestPrice()).isEqualByComparingTo("12878.49"); + assertThat(detail.getOpenPrice()).isEqualByComparingTo("12591.8"); + assertThat(detail.getPreClosePrice()).isEqualByComparingTo("12730.57"); + assertThat(detail.getHighPrice()).isEqualByComparingTo("12956.03"); + assertThat(detail.getLowPrice()).isEqualByComparingTo("12464.95"); + assertThat(detail.getChangeAmount()).isEqualByComparingTo("147.92"); + assertThat(detail.getChangePercent()).isEqualByComparingTo("1.16"); + assertThat(detail.getTurnoverRate()).isEqualByComparingTo("2.78"); + assertThat(detail.getVolumeRatio()).isEqualByComparingTo("0.98"); + assertThat(detail.getOuterDisc()).isEqualByComparingTo("51550720"); + assertThat(detail.getCirculatingMarketValue()).isEqualByComparingTo(new BigDecimal("15683607296000")); + assertThat(detail.getCirculatingShares()).isEqualByComparingTo(new BigDecimal("366681878528")); + } +} diff --git a/aquant-frontend/src/api/board.ts b/aquant-frontend/src/api/board.ts index 4e181209..2dfec9b7 100644 --- a/aquant-frontend/src/api/board.ts +++ b/aquant-frontend/src/api/board.ts @@ -13,6 +13,15 @@ export interface StockIndustryBoardVO { riseCount: number; fallCount: number; averagePrice: number; + openPrice: number | null; + preClosePrice: number | null; + highPrice: number | null; + lowPrice: number | null; + turnoverRate: number | null; + volumeRatio: number | null; + outerDisc: number | null; + circulatingMarketValue: number | null; + circulatingShares: number | null; leadingStock: string; leadingStockPrice: number; leadingStockChangePercent: number; diff --git a/aquant-frontend/src/views/industry-detail/IndustryDetail.vue b/aquant-frontend/src/views/industry-detail/IndustryDetail.vue index 2d72de58..e9b80a1d 100644 --- a/aquant-frontend/src/views/industry-detail/IndustryDetail.vue +++ b/aquant-frontend/src/views/industry-detail/IndustryDetail.vue @@ -82,6 +82,22 @@ 板块均价 {{ selectedBoard.averagePrice != null ? selectedBoard.averagePrice : '-' }} +
+ 今开 + {{ formatFixed2(selectedBoard.openPrice) }} +
+
+ 昨收 + {{ formatFixed2(selectedBoard.preClosePrice) }} +
+
+ 最高 + {{ formatFixed2(selectedBoard.highPrice) }} +
+
+ 最低 + {{ formatFixed2(selectedBoard.lowPrice) }} +
总成交额 {{ selectedBoard.totalAmount != null ? selectedBoard.totalAmount + ' 亿元' : '-' }} @@ -90,6 +106,30 @@ 总成交量 {{ selectedBoard.totalVolume != null ? selectedBoard.totalVolume + ' 万手' : '-' }}
+
+ 换手率 + {{ selectedBoard.turnoverRate + '%' }} +
+
+ 量比 + {{ selectedBoard.volumeRatio }} +
+
+ 外盘 + {{ selectedBoard.outerDisc + ' 万手' }} +
+
+ 内盘 + {{ formatFixed2(selectedBoard.totalVolume - selectedBoard.outerDisc) + ' 万手' }} +
+
+ 流通市值 + {{ formatYiAmount(selectedBoard.circulatingMarketValue) }} +
+
+ 流通股本 + {{ formatYiAmount(selectedBoard.circulatingShares) }}股 +
净流入 @@ -250,6 +290,14 @@ const formatSignedPercent = (value: number | null) => { return `${value > 0 ? '+' : ''}${value.toFixed(2)}%`; }; +// 亿为单位的大数人性化:超过万亿换算为万亿展示(对齐东财详情页"15.68万亿"样式) +const formatYiAmount = (value: number | null) => { + if (value == null) return '-'; + return value >= 10000 ? `${(value / 10000).toFixed(2)} 万亿` : `${value} 亿`; +}; + +const formatFixed2 = (value: number | null) => (value == null ? '-' : value.toFixed(2)); + const getSparklinePath = (prices: number[]) => { const min = Math.min(...prices); const max = Math.max(...prices); diff --git a/stock.sql b/stock.sql index 90d6e3e9..18ff0a02 100644 --- a/stock.sql +++ b/stock.sql @@ -412,7 +412,20 @@ CREATE TABLE `stock_industry_board_em` ( `sector_code` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '行业板块代码(如 BK0475)', `sector_name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '行业板块名称(如 白酒、半导体)', `seq_no` int DEFAULT NULL COMMENT '序号 / 排名', - `total_amount` decimal(38,2) DEFAULT NULL COMMENT '总成交额', + `total_volume` decimal(38,4) DEFAULT NULL COMMENT '总成交量(万手)', + `total_amount` decimal(38,2) DEFAULT NULL COMMENT '总成交额(亿元)', + `net_inflow` decimal(38,4) DEFAULT NULL COMMENT '净流入(亿元)', + `change_amount` decimal(38,4) DEFAULT NULL COMMENT '涨跌额(详情快照)', + `open_price` decimal(38,4) DEFAULT NULL COMMENT '今开(详情快照)', + `pre_close_price` decimal(38,4) DEFAULT NULL COMMENT '昨收(详情快照)', + `high_price` decimal(38,4) DEFAULT NULL COMMENT '最高(详情快照)', + `low_price` decimal(38,4) DEFAULT NULL COMMENT '最低(详情快照)', + `turnover_rate` decimal(38,4) DEFAULT NULL COMMENT '换手率(%)(详情快照)', + `volume_ratio` decimal(38,4) DEFAULT NULL COMMENT '量比(详情快照)', + `outer_disc` decimal(38,4) DEFAULT NULL COMMENT '外盘(万手,详情快照;内盘=总成交量-外盘)', + `circulating_market_value` decimal(38,4) DEFAULT NULL COMMENT '流通市值(亿元,详情快照)', + `circulating_shares` decimal(38,4) DEFAULT NULL COMMENT '流通股本(亿股,详情快照)', + `detail_trade_date` date DEFAULT NULL COMMENT '详情快照抓取日期', `trade_date` date DEFAULT NULL COMMENT '交易日期', PRIMARY KEY (`id`), UNIQUE KEY `uk_industry_board_em_sector_code` (`sector_code`) From 226c62745abec14882607daec70f076f3efcc3c2 Mon Sep 17 00:00:00 2001 From: LiZhi <417430464@qq.com> Date: Fri, 18 Sep 2026 08:18:58 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E9=80=82=E9=85=8D=E4=B8=9C=E8=B4=A2?= =?UTF-8?q?=E6=8C=81=E4=BB=93=E4=BA=A4=E6=98=93=E6=95=B0=E6=8D=AE=E8=8E=B7?= =?UTF-8?q?=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/EastmoneyJywgClient.java | 303 ++++++++++++ .../easytrader/EasytraderClient.java | 99 ++++ .../PortfolioJywgCookieController.java | 77 +++ .../controller/UserPortfolioController.java | 30 +- .../entity/UserPortfolioPosition.java | 12 + .../model/vo/BrokerPositionSnapshotVO.java | 93 ++++ .../model/vo/PortfolioPositionVO.java | 4 + .../service/PortfolioTradeImportService.java | 27 +- .../service/UserPortfolioService.java | 203 +++++++- .../importer/BrokerTradeFileAdapter.java | 5 + .../CMSSecuritiesTradeFileAdapter.java | 5 + .../importer/EastmoneyTradeFileAdapter.java | 363 ++++++++++++++ .../sync/EastmoneyWebTradeSyncProvider.java | 447 ++++++++++++++++++ .../sync/EasytraderTradeSyncProvider.java | 229 +++++++++ .../sync/PortfolioBrokerSyncProvider.java | 27 ++ .../sync/PortfolioBrokerSyncService.java | 156 ++++++ .../aquant/sync/entity/StockSync.java | 3 +- .../src/main/resources/application-demo.yaml | 12 + .../service/EastmoneyJywgClientTest.java | 173 +++++++ .../EastmoneyTradeFileAdapterTest.java | 126 +++++ .../EastmoneyWebTradeSyncProviderTest.java | 159 +++++++ .../sync/EasytraderTradeSyncProviderTest.java | 89 ++++ .../sync/PortfolioBrokerSyncServiceTest.java | 181 +++++++ aquant-frontend/src/api/eastmoney.ts | 29 ++ aquant-frontend/src/api/portfolio.ts | 30 +- aquant-frontend/src/layout/BasicLayout.vue | 165 ++++++- aquant-frontend/src/types/portfolio.ts | 43 +- .../src/views/portfolio/Portfolio.vue | 177 ++++++- .../portfolio/components/AccountManager.vue | 31 +- .../components/ImportUploadSection.vue | 19 +- .../portfolio/components/PositionTable.vue | 55 ++- .../sources/EastmoneyPositionView.vue | 372 +++++++++++++++ .../src/views/portfolio/sources/registry.ts | 57 +++ stock.sql | 5 +- 34 files changed, 3749 insertions(+), 57 deletions(-) create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClient.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/integration/easytrader/EasytraderClient.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/PortfolioJywgCookieController.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/BrokerPositionSnapshotVO.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapter.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProvider.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProvider.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncProvider.java create mode 100644 aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncService.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClientTest.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapterTest.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProviderTest.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProviderTest.java create mode 100644 aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncServiceTest.java create mode 100644 aquant-frontend/src/views/portfolio/sources/EastmoneyPositionView.vue create mode 100644 aquant-frontend/src/views/portfolio/sources/registry.ts diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClient.java b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClient.java new file mode 100644 index 00000000..c1f1fa37 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClient.java @@ -0,0 +1,303 @@ +package com.brotherc.aquant.integration.eastmoney.service; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.sync.entity.StockSync; +import com.brotherc.aquant.sync.repository.StockSyncRepository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * 东方财富证券网页交易(jywg.eastmoneysec.com,原 jywg.18.cn)只读查询客户端。 + * + *

不做登录自动化(滑块验证 + 密码 RSA + 图形验证码逆向成本高且易碎),复用项目既有的 + * 「东财 Cookie 热更新」模式:用户在浏览器完成 jywg 登录后,从 DevTools 复制 + * 会话 Cookie 与 validatekey(任意查询请求 URL 参数,或页面 #em_validatekey 的 value), + * 调 POST /portfolio/jywg/cookie 热更新并选择在线时长(15/30/180 分钟,对应 jywg 登录 + * duration 语义),前端按过期时间倒计时。仅实现只读查询(持仓/资产/当日成交/资金流水), + * 不封装下单等写操作。

+ * + *

接口契约参考 wmo-v/eastmoneyapi(Go 逆向实现): + * 查询类 GET 端点统一带 {@code validatekey} 参数,响应为 {@code {Status:0, Data:[...], Message}}, + * 字段名为拼音首字母(Zqdm 证券代码、Zqmc 证券名称、Cjjg 成交价格、Cjsl 成交数量、 + * Cjbh 成交编号、Kysl 可用数量、Zqsl 持仓数量、Cbjg 成本价等)。

+ * + *

注意:这里的交易会话与行情中心的东财 Cookie({@code aquant.eastmoney.cookie}, + * 作用于 push2 行情接口)是两个完全独立的凭证,互不通用。

+ */ +@Slf4j +@Service +public class EastmoneyJywgClient { + + /** 在线时长可选项(分钟),对齐 jywg 登录 duration 语义 */ + public static final Set ALLOWED_DURATIONS = Set.of(15, 30, 180); + + /** 会话在 stock_sync 表中的持久化键:记录更新时间与在线时长,重启后倒计时可续算 */ + public static final String SESSION_STORAGE_KEY = "portfolio_jywg_session"; + + private final OkHttpClient okHttpClient; + private final ObjectMapper objectMapper; + private final String baseUrl; + private final StockSyncRepository stockSyncRepository; + + /** + * 当前会话。expireAtMillis 为空表示未计时(如来自静态配置且尚未热更新过), + * 到期后查询直接拒绝并提示重新获取(上游 Cookie 同步过期)。 + */ + private volatile Session session; + + private record Session(String cookie, String validateKey, Long expireAtMillis, + Integer durationMinutes, Long updateTimeMillis) { + } + + public EastmoneyJywgClient(OkHttpClient okHttpClient, ObjectMapper objectMapper, + @Value("${aquant.portfolio.jywg-base-url:https://jywg.eastmoneysec.com}") String baseUrl, + @Value("${aquant.portfolio.jywg-cookie:}") String cookie, + @Value("${aquant.portfolio.jywg-validate-key:}") String validateKey, + StockSyncRepository stockSyncRepository) { + this.okHttpClient = okHttpClient; + this.objectMapper = objectMapper; + this.baseUrl = trimToEmpty(baseUrl); + this.stockSyncRepository = stockSyncRepository; + // 启动恢复顺序:优先用上次热更新持久化的会话(更新时间+时长可续算倒计时), + // 其次回落到静态配置(不计时)。两者都无则视为未配置 + Session restored = restorePersistedSession(); + if (restored != null) { + this.session = restored; + log.info("东财网页交易会话已从持久化记录恢复: updateTime={}, duration={}min", + Instant.ofEpochMilli(restored.updateTimeMillis()), restored.durationMinutes()); + return; + } + String configuredCookie = trimToEmpty(cookie); + String configuredValidateKey = trimToEmpty(validateKey); + this.session = configuredCookie.isBlank() || configuredValidateKey.isBlank() ? null + : new Session(configuredCookie, configuredValidateKey, null, null, null); + if (this.session != null) { + log.info("东财网页交易会话已从配置初始化(未计时,倒计时以热更新为准)"); + } + } + + /** 从 stock_sync 读取上次热更新的会话(Cookie/validatekey/更新时间/时长),倒计时按 updateTime+duration 续算 */ + private Session restorePersistedSession() { + try { + StockSync stored = stockSyncRepository.findByName(SESSION_STORAGE_KEY); + if (stored == null || StringUtils.isBlank(stored.getValue())) { + return null; + } + JsonNode node = objectMapper.readTree(stored.getValue()); + String cookie = node.path("cookie").asText(""); + String validateKey = node.path("validateKey").asText(""); + long updateTime = node.path("updateTime").asLong(0); + int durationMinutes = node.path("durationMinutes").asInt(0); + if (cookie.isBlank() || validateKey.isBlank() || updateTime <= 0 || durationMinutes <= 0) { + return null; + } + return new Session(cookie, validateKey, updateTime + durationMinutes * 60_000L, + durationMinutes, updateTime); + } catch (Exception exception) { + log.warn("东财网页交易会话持久化记录恢复失败,忽略", exception); + return null; + } + } + + private void persistSession(Session current) { + try { + StockSync stored = stockSyncRepository.findByName(SESSION_STORAGE_KEY); + if (stored == null) { + stored = new StockSync(); + stored.setName(SESSION_STORAGE_KEY); + } + Map payload = new LinkedHashMap<>(); + payload.put("cookie", current.cookie()); + payload.put("validateKey", current.validateKey()); + payload.put("durationMinutes", current.durationMinutes()); + payload.put("updateTime", current.updateTimeMillis()); + stored.setValue(objectMapper.writeValueAsString(payload)); + stockSyncRepository.save(stored); + } catch (RuntimeException | IOException exception) { + // 持久化失败不影响本次热更新生效,仅重启后倒计时/凭证不可恢复 + log.warn("东财网页交易会话持久化失败(重启后需重新设置)", exception); + } + } + + public boolean isConfigured() { + return session != null; + } + + /** 热更新交易会话:立即生效,无需重启。durationMinutes 由控制器校验取值范围(15/30/180) */ + public void updateSession(String cookie, String validateKey, int durationMinutes) { + String normalizedCookie = trimToEmpty(cookie); + String normalizedValidateKey = trimToEmpty(validateKey); + if (normalizedCookie.isBlank() || normalizedValidateKey.isBlank()) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, "Cookie 与 validatekey 均不能为空"); + } + long updateTime = System.currentTimeMillis(); + session = new Session(normalizedCookie, normalizedValidateKey, + updateTime + durationMinutes * 60_000L, durationMinutes, updateTime); + persistSession(session); + log.info("东财网页交易会话已更新: duration={}min, expireAt={}", durationMinutes, + Instant.ofEpochMilli(session.expireAtMillis())); + } + + /** 会话状态(前端倒计时数据源) */ + public Map sessionStatus() { + Session current = session; + Map status = new LinkedHashMap<>(); + status.put("configured", current != null); + if (current == null) { + status.put("expired", false); + status.put("remainingSeconds", 0); + status.put("updateTime", null); + return status; + } + boolean timed = current.expireAtMillis() != null; + boolean expired = timed && System.currentTimeMillis() >= current.expireAtMillis(); + status.put("expired", expired); + status.put("remainingSeconds", timed && !expired + ? Math.max(0, (current.expireAtMillis() - System.currentTimeMillis()) / 1000) : 0); + status.put("durationMinutes", current.durationMinutes()); + status.put("expireAt", timed ? Instant.ofEpochMilli(current.expireAtMillis()).toString() : null); + status.put("updateTime", current.updateTimeMillis() == null + ? null : Instant.ofEpochMilli(current.updateTimeMillis()).toString()); + return status; + } + + private boolean usable() { + Session current = session; + if (current == null) { + return false; + } + return current.expireAtMillis() == null || System.currentTimeMillis() < current.expireAtMillis(); + } + + // ==================== 查询接口(契约来自 jywg 页面实际抓包,均为 POST form) ==================== + + /** 单次查询行数。浏览器页面默认 20,放大以避免漏单(成交多于 20 笔时翻页参数未知) */ + private static final String QUERY_ROW_COUNT = "500"; + + /** 资金余额 + 持仓明细(多证券)。form: moneyType=RMB;Data[0] = {Zzc 总资产, Kyzj 可用资金, positions: [持仓]} */ + public JsonNode assetAndPosition() { + return postForm("/Com/queryAssetAndPositionV1", Map.of("moneyType", "RMB")); + } + + /** 当日委托(多证券)。form: qqhs=行数&dwc= */ + public JsonNode todayOrders() { + return postForm("/Search/queryTodayOrderWEB", form("qqhs", QUERY_ROW_COUNT, "dwc", "")); + } + + /** 当日成交(多证券)。form: qqhs=行数&dwc= */ + public JsonNode todayMatches() { + return postForm("/Search/queryTodayMatchWEB", form("qqhs", QUERY_ROW_COUNT, "dwc", "")); + } + + /** 历史委托(多证券)。日期格式 yyyyMMdd;form: strdate&enddate&count&poststr= */ + public JsonNode historyOrders(String beginYmd, String endYmd) { + return postForm("/Search/queryHisOrderMergeWEB", + form("strdate", beginYmd, "enddate", endYmd, "count", QUERY_ROW_COUNT, "poststr", "")); + } + + /** 历史成交(多证券)。日期格式 yyyyMMdd;form: strdate&enddate&count&poststr= */ + public JsonNode historyMatches(String beginYmd, String endYmd) { + return postForm("/Search/queryHisMatchMergeWEB", + form("strdate", beginYmd, "enddate", endYmd, "count", QUERY_ROW_COUNT, "poststr", "")); + } + + /** 交割单(资金流水,含费用明细)。日期格式 yyyy-MM-dd;form: st&et&qqhs&dwc= */ + public JsonNode fundsFlow(String beginDate, String endDate) { + return postForm("/Search/GetFundsFlow", + form("st", beginDate, "et", endDate, "qqhs", QUERY_ROW_COUNT, "dwc", "")); + } + + private static Map form(String... pairs) { + Map form = new LinkedHashMap<>(); + for (int i = 0; i + 1 < pairs.length; i += 2) { + form.put(pairs[i], pairs[i + 1]); + } + return form; + } + + /** POST 表单查询:validatekey 走 URL 参数(与浏览器一致),业务参数走 form body */ + private JsonNode postForm(String path, Map form) { + Session current = session; + if (current == null) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "未配置东方财富网页交易会话,请先设置交易 Cookie 与 validatekey"); + } + if (!usable()) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "交易会话已过期(在线时长已到,上游 Cookie 同步过期),请在浏览器重新登录 jywg 并更新交易 Cookie"); + } + okhttp3.HttpUrl url = okhttp3.HttpUrl.get(baseUrl + path).newBuilder() + .addQueryParameter("validatekey", current.validateKey()) + .build(); + okhttp3.FormBody.Builder body = new okhttp3.FormBody.Builder(); + form.forEach(body::add); + // 请求头对齐浏览器 XHR:jywg 部分校验会校验 X-Requested-With/User-Agent, + // 缺失时即使 Cookie 有效也可能返回登录页 HTML + Request request = new Request.Builder() + .url(url) + .header("Cookie", current.cookie()) + .header("Referer", baseUrl + "/Search/Position") + .header("X-Requested-With", "XMLHttpRequest") + .header("Accept", "application/json, text/javascript, */*; q=0.01") + .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36") + .post(body.build()) + .build(); + return execute(path, request); + } + + private JsonNode execute(String path, Request request) { + try (Response response = okHttpClient.newCall(request).execute()) { + String body = response.body() == null ? "" : response.body().string(); + if (!response.isSuccessful()) { + log.warn("东财网页交易接口失败: path={}, status={}, bodyLen={}", path, response.code(), body.length()); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "东方财富网页交易接口调用失败:HTTP " + response.code() + ",会话可能已过期,请重新复制 Cookie 与 validatekey"); + } + // 会话失效时 jywg 返回 200 + 登录页 HTML(而非 JSON/错误码),据此精确识别并指引重新登录 + if (body.stripLeading().startsWith("<")) { + log.warn("东财网页交易接口返回登录页(会话失效): path={}, bodyLen={}, title={}", + path, body.length(), bodySnippet(body)); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "交易会话已失效(Cookie 过期或 validatekey 不匹配,上游返回了登录页)。" + + "请在浏览器重新登录 jywg,然后更新交易 Cookie 与 validatekey"); + } + JsonNode root = objectMapper.readTree(body); + JsonNode status = root.path("Status"); + if (!status.isMissingNode() && !status.isNull() && status.asInt(-1) != 0) { + log.warn("东财网页交易接口业务失败: path={}, message={}, body={}", + path, root.path("Message").asText(""), bodySnippet(body)); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "东方财富网页交易接口失败:" + root.path("Message").asText("Status=" + status.asInt())); + } + return root.path("Data"); + } catch (IOException e) { + log.warn("东财网页交易接口不可达: path={}, base={}", path, baseUrl, e); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "东方财富网页交易接口不可达:" + e.getMessage()); + } + } + + private static String trimToEmpty(String value) { + return value == null ? "" : value.trim(); + } + + private static String bodySnippet(String body) { + String flat = body == null ? "" : body.replaceAll("\\s+", " ").trim(); + return flat.length() <= 200 ? flat : flat.substring(0, 200) + "..."; + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/integration/easytrader/EasytraderClient.java b/aquant-backend/src/main/java/com/brotherc/aquant/integration/easytrader/EasytraderClient.java new file mode 100644 index 00000000..d8e1901e --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/integration/easytrader/EasytraderClient.java @@ -0,0 +1,99 @@ +package com.brotherc.aquant.integration.easytrader; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * easytrader 远程客户端(https://github.com/shidenggui/easytrader 的 Flask 服务模式)。 + * + *

用户在常驻 Windows 机器上以东财证券客户端启动 easytrader 的 web 服务, + * 本客户端轮询读取持仓与当日成交。网格数据列名随券商客户端版本变化,调用方需做宽容字段映射。 + * 典型部署:{@code python -m easytrader.server}(或按其文档以 server 模式运行), + * 先 POST /prepare 完成客户端登录,再 GET 以下数据端点。

+ */ +@Slf4j +@Service +public class EasytraderClient { + + private final OkHttpClient okHttpClient; + private final ObjectMapper objectMapper; + private final String baseUrl; + + public EasytraderClient(OkHttpClient okHttpClient, ObjectMapper objectMapper, + @Value("${aquant.portfolio.easytrader-base-url:}") String baseUrl) { + this.okHttpClient = okHttpClient; + this.objectMapper = objectMapper; + this.baseUrl = baseUrl == null ? "" : baseUrl.trim(); + } + + public boolean isConfigured() { + return !baseUrl.isBlank(); + } + + /** 当前持仓(多证券列表,列名随券商客户端变化,如 证券代码/证券名称/股票余额/成本价/市值) */ + public List> position() { + return fetch("/position"); + } + + /** 当日成交(多证券列表,常见列:成交日期/证券代码/证券名称/操作/成交价格/成交数量/成交金额/合同编号/成交编号) */ + public List> todayTrades() { + return fetch("/today_trades"); + } + + /** 资金余额(可用金额/总资产等,列名随客户端变化) */ + public Map balance() { + List> rows = fetch("/balance"); + return rows.isEmpty() ? Map.of() : rows.get(0); + } + + private List> fetch(String path) { + if (!isConfigured()) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "未配置 easytrader 服务地址(aquant.portfolio.easytrader-base-url)"); + } + Request request = new Request.Builder() + .url(baseUrl + path) + .get() + .build(); + try (Response response = okHttpClient.newCall(request).execute()) { + String body = response.body() == null ? "" : response.body().string(); + if (!response.isSuccessful()) { + String error = parseError(body); + log.warn("easytrader 接口失败: path={}, status={}, error={}", path, response.code(), error); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "easytrader 客户端调用失败:" + StringUtils.defaultIfBlank(error, "HTTP " + response.code())); + } + return objectMapper.readValue(body, new TypeReference<>() {}); + } catch (IOException e) { + log.warn("easytrader 接口不可达: path={}, base={}", path, baseUrl, e); + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "easytrader 服务不可达,请确认客户端服务已启动:" + e.getMessage()); + } + } + + private String parseError(String body) { + try { + return objectMapper.readTree(body).path("error").asText(null); + } catch (IOException e) { + return null; + } + } + + private static final class StringUtils { + private static String defaultIfBlank(String value, String fallback) { + return value == null || value.isBlank() ? fallback : value; + } + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/PortfolioJywgCookieController.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/PortfolioJywgCookieController.java new file mode 100644 index 00000000..5094db83 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/PortfolioJywgCookieController.java @@ -0,0 +1,77 @@ +package com.brotherc.aquant.portfolio.controller; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.common.model.dto.ResponseDTO; +import com.brotherc.aquant.common.utils.UserContext; +import com.brotherc.aquant.integration.eastmoney.service.EastmoneyJywgClient; +import com.brotherc.aquant.portfolio.service.sync.PortfolioBrokerSyncService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +/** + * 东方财富证券网页交易会话(交易 Cookie)管理。 + * + *

与行情中心的东财 Cookie(/eastmoney/cookie,作用于 push2 行情接口)是两个 + * 完全独立的凭证:本控制器维护 jywg.eastmoneysec.com 的交易会话。设置时选择在线 + * 时长(15/30/180 分钟,对应 jywg 登录 duration 语义),到期后上游 Cookie 同步过期, + * 查询接口会明确提示重新获取;前端据此倒计时。

+ */ +@Tag(name = "东财交易会话") +@RestController +@RequiredArgsConstructor +@RequestMapping("/portfolio/jywg") +public class PortfolioJywgCookieController { + + private final EastmoneyJywgClient jywgClient; + private final PortfolioBrokerSyncService portfolioBrokerSyncService; + + @Operation(summary = "设置交易 Cookie 与 validatekey", description = "浏览器登录 jywg 后从 DevTools 复制;" + + "在线时长仅支持 15/30/180 分钟,到期后上游 Cookie 同步过期,需重新获取。立即生效,无需重启;" + + "设置成功后异步自动同步 EM_WEB 渠道账户的当日成交并重建持仓/收益") + @PostMapping("/cookie") + public ResponseDTO> updateCookie(@RequestBody @Valid JywgCookieUpdateReqVO reqVO) { + if (!EastmoneyJywgClient.ALLOWED_DURATIONS.contains(reqVO.getDurationMinutes())) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "在线时长仅支持 " + EastmoneyJywgClient.ALLOWED_DURATIONS + " 分钟"); + } + jywgClient.updateSession(reqVO.getCookie(), reqVO.getValidateKey(), reqVO.getDurationMinutes()); + portfolioBrokerSyncService.triggerSynchronizeAfterCookieUpdate( + UserContext.requireCurrentUserId(), UserContext.getCurrentUsername()); + return ResponseDTO.success(jywgClient.sessionStatus()); + } + + @Operation(summary = "查询交易会话状态", description = "返回是否已配置、是否过期、剩余秒数(前端倒计时数据源)") + @GetMapping("/cookie") + public ResponseDTO> cookieStatus() { + return ResponseDTO.success(jywgClient.sessionStatus()); + } + + @Data + public static class JywgCookieUpdateReqVO { + + /** 完整的 Cookie 请求头字符串(浏览器登录 jywg 后从 DevTools 复制) */ + @NotBlank(message = "Cookie 不能为空") + private String cookie; + + /** jywg 会话密钥(任意查询请求 URL 的 validatekey 参数,或页面 #em_validatekey 的 value) */ + @NotBlank(message = "validatekey 不能为空") + private String validateKey; + + /** 在线时长(分钟):15/30/180 */ + @NotNull(message = "在线时长不能为空") + private Integer durationMinutes; + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/UserPortfolioController.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/UserPortfolioController.java index f5895e5e..625abec9 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/UserPortfolioController.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/controller/UserPortfolioController.java @@ -8,6 +8,7 @@ import com.brotherc.aquant.portfolio.model.vo.*; import com.brotherc.aquant.portfolio.service.UserPortfolioService; import com.brotherc.aquant.portfolio.service.PortfolioTradeImportService; +import com.brotherc.aquant.portfolio.service.sync.PortfolioBrokerSyncService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; @@ -27,6 +28,7 @@ import java.time.LocalDate; import java.util.List; +import java.util.Map; @Tag(name = "用户持仓") @RestController @@ -36,6 +38,7 @@ public class UserPortfolioController { private final UserPortfolioService portfolioService; private final PortfolioTradeImportService tradeImportService; + private final PortfolioBrokerSyncService portfolioBrokerSyncService; @Operation(summary = "查询当前用户的投资组合") @GetMapping("/list") @@ -84,17 +87,38 @@ public ResponseDTO saveTrades(@RequestBody @Valid Portf @Operation(summary = "校验并预览 CSV/Excel 交易流水文件") @PostMapping(value = "/trade/import/preview", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseDTO previewTradeFile( - @RequestParam Long accountId, @RequestPart("file") MultipartFile file) { - return ResponseDTO.success(tradeImportService.preview(accountId, file)); + @RequestParam Long accountId, + @RequestParam(required = false) String brokerCode, + @RequestPart("file") MultipartFile file) { + return ResponseDTO.success(tradeImportService.preview(accountId, brokerCode, file)); } @Operation(summary = "导入 CSV/Excel 交易流水文件") @PostMapping(value = "/trade/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseDTO importTradeFile( @RequestParam Long accountId, + @RequestParam(required = false) String brokerCode, @RequestParam(defaultValue = "true") boolean syncCashBalance, @RequestPart("file") MultipartFile file) { - return ResponseDTO.success(tradeImportService.importFile(accountId, file, syncCashBalance)); + return ResponseDTO.success(tradeImportService.importFile(accountId, brokerCode, file, syncCashBalance)); + } + + @Operation(summary = "按账户同步方式拉取最近成交并入库(EASYTRADER/EM_WEB)") + @PostMapping("/account/{accountId}/sync/trades") + public ResponseDTO syncBrokerTrades(@PathVariable Long accountId) { + return ResponseDTO.success(portfolioBrokerSyncService.syncTrades(accountId)); + } + + @Operation(summary = "查询最近一次同步的券商持仓快照", description = "读持久化数据,Cookie 失效后仍可展示") + @GetMapping("/account/{accountId}/sync/positions") + public ResponseDTO syncBrokerPositions(@PathVariable Long accountId) { + return ResponseDTO.success(portfolioBrokerSyncService.positions(accountId)); + } + + @Operation(summary = "实时刷新券商持仓快照", description = "需交易会话有效;成功后覆盖持久化快照并返回") + @PostMapping("/account/{accountId}/sync/positions/refresh") + public ResponseDTO refreshBrokerPositions(@PathVariable Long accountId) { + return ResponseDTO.success(portfolioBrokerSyncService.refreshPositions(accountId)); } @Operation(summary = "下载交易流水导入模板") diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/entity/UserPortfolioPosition.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/entity/UserPortfolioPosition.java index e586e0b7..e54e9c01 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/entity/UserPortfolioPosition.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/entity/UserPortfolioPosition.java @@ -58,6 +58,18 @@ public class UserPortfolioPosition { @Column(name = "unrealized_profit", precision = 24, scale = 4) private BigDecimal unrealizedProfit; + /** 持仓盈亏比例(%)。本地计算源由流水重算;券商同步源直取接口原值(如东财 income_rate) */ + @Column(name = "income_rate", precision = 24, scale = 4) + private BigDecimal incomeRate; + + /** 当日盈亏。券商同步源直取接口原值 */ + @Column(name = "day_income", precision = 24, scale = 4) + private BigDecimal dayIncome; + + /** 当日盈亏比例(%)。券商同步源直取接口原值 */ + @Column(name = "day_income_rate", precision = 24, scale = 4) + private BigDecimal dayIncomeRate; + @Column(name = "quote_date") private LocalDate quoteDate; diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/BrokerPositionSnapshotVO.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/BrokerPositionSnapshotVO.java new file mode 100644 index 00000000..77bb5e97 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/BrokerPositionSnapshotVO.java @@ -0,0 +1,93 @@ +package com.brotherc.aquant.portfolio.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * 券商渠道实时持仓快照(多证券)。资产与持仓指标全部直取券商接口原值 + * (jywg queryAssetAndPositionV1 实测:total_asset/security_market_value/ + * enable_balance/fetch_balance/frozen_balance/money_balance/position_income/ + * day_income + positions[].security_code/holding_quantity/cost_price/last_price/ + * market_value/income/income_rate/day_income/day_income_rate 等), + * 本地不做推算,避免与券商口径(如摊薄成本为负、盈亏比例缺省 0.000%)不一致。 + */ +@Data +public class BrokerPositionSnapshotVO { + + @Schema(description = "总资产") + private BigDecimal totalAsset; + + @Schema(description = "证券市值") + private BigDecimal securityMarketValue; + + @Schema(description = "可用资金") + private BigDecimal enableBalance; + + @Schema(description = "可取资金") + private BigDecimal fetchBalance; + + @Schema(description = "冻结资金") + private BigDecimal frozenBalance; + + @Schema(description = "资金余额") + private BigDecimal moneyBalance; + + @Schema(description = "持仓盈亏") + private BigDecimal positionIncome; + + @Schema(description = "当日盈亏") + private BigDecimal dayIncome; + + @Schema(description = "渠道名(EM_WEB/EASYTRADER),前端按渠道渲染") + private String channel; + + @Schema(description = "快照获取时间(ISO 8601)") + private String fetchTime; + + @Schema(description = "持仓明细(多证券)") + private List positions = new ArrayList<>(); + + @Data + public static class BrokerPositionItemVO { + + @Schema(description = "证券代码") + private String securityCode; + + @Schema(description = "证券名称") + private String securityName; + + @Schema(description = "持仓数量") + private BigDecimal holdingQuantity; + + @Schema(description = "可用数量") + private BigDecimal enableQuantity; + + @Schema(description = "成本价(券商口径,摊薄后可为负)") + private BigDecimal costPrice; + + @Schema(description = "最新价") + private BigDecimal lastPrice; + + @Schema(description = "最新市值") + private BigDecimal marketValue; + + @Schema(description = "持仓盈亏") + private BigDecimal income; + + @Schema(description = "持仓盈亏比例(%)") + private BigDecimal incomeRate; + + @Schema(description = "当日盈亏") + private BigDecimal dayIncome; + + @Schema(description = "当日盈亏比例(%)") + private BigDecimal dayIncomeRate; + + @Schema(description = "保本价") + private BigDecimal keepCostPrice; + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/PortfolioPositionVO.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/PortfolioPositionVO.java index 29d67dcb..80078088 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/PortfolioPositionVO.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/model/vo/PortfolioPositionVO.java @@ -24,6 +24,10 @@ public class PortfolioPositionVO { private BigDecimal marketValue; private BigDecimal unrealizedProfit; private BigDecimal unrealizedProfitRate; + /** 当日盈亏。券商同步源直取接口值,本地计算源为空 */ + private BigDecimal dayIncome; + /** 当日盈亏比例(%)。券商同步源直取接口值 */ + private BigDecimal dayIncomeRate; private BigDecimal positionRatio; private LocalDate quoteDate; } diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/PortfolioTradeImportService.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/PortfolioTradeImportService.java index f248922a..58e8c5e3 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/PortfolioTradeImportService.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/PortfolioTradeImportService.java @@ -13,6 +13,7 @@ import com.brotherc.aquant.portfolio.repository.UserPortfolioImportBatchRepository; import com.brotherc.aquant.portfolio.service.importer.BrokerTradeFileAdapter; import lombok.RequiredArgsConstructor; +import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -33,8 +34,8 @@ public class PortfolioTradeImportService { private final UserPortfolioImportBatchRepository importBatchRepository; private final List brokerTradeFileAdapters; - public PortfolioTradeImportPreviewVO preview(Long accountId, MultipartFile file) { - String brokerCode = validateAccount(accountId).getBrokerCode(); + public PortfolioTradeImportPreviewVO preview(Long accountId, String brokerCodeOverride, MultipartFile file) { + String brokerCode = resolveBrokerCode(accountId, brokerCodeOverride); PortfolioTradeFileParseResult parsed = parse(brokerCode, file); PortfolioTradeImportPreviewVO preview = new PortfolioTradeImportPreviewVO(); preview.setFileName(parsed.getFileName()); @@ -53,8 +54,9 @@ public PortfolioTradeImportPreviewVO preview(Long accountId, MultipartFile file) } @Transactional(rollbackFor = Exception.class) - public PortfolioImportResultVO importFile(Long accountId, MultipartFile file, boolean syncCashBalance) { - String brokerCode = validateAccount(accountId).getBrokerCode(); + public PortfolioImportResultVO importFile(Long accountId, String brokerCodeOverride, MultipartFile file, + boolean syncCashBalance) { + String brokerCode = resolveBrokerCode(accountId, brokerCodeOverride); PortfolioTradeFileParseResult parsed = parse(brokerCode, file); if (!parsed.getErrors().isEmpty()) { String firstError = parsed.getErrors().get(0).getMessage(); @@ -99,9 +101,14 @@ private PortfolioTradeFileParseResult parse(String brokerCode, MultipartFile fil } try { byte[] content = file.getBytes(); + // 优先按指定/账户券商匹配适配器;都不中时按文件内容签名兜底识别(避免账户券商代码 + // 与实际文件来源不符——如东财账户挂着 CMS 代码——导致走错解析器) return brokerTradeFileAdapters.stream() .filter(adapter -> adapter.supports(brokerCode, file.getOriginalFilename(), content)) .findFirst() + .or(() -> brokerTradeFileAdapters.stream() + .filter(adapter -> adapter.supports("*", file.getOriginalFilename(), content)) + .findFirst()) .map(adapter -> adapter.parse(file.getOriginalFilename(), content)) .orElseGet(() -> fileParser.parse(file.getOriginalFilename(), content)); } catch (IOException e) { @@ -109,6 +116,18 @@ private PortfolioTradeFileParseResult parse(String brokerCode, MultipartFile fil } } + /** + * 导入券商代码:显式指定(前端券商选择器)优先,其次回落账户配置的 brokerCode。 + * MANUAL 是同步方式的缺省值而非券商代码,不作为匹配依据。 + */ + private String resolveBrokerCode(Long accountId, String brokerCodeOverride) { + UserBrokerAccount account = validateAccount(accountId); + if (StringUtils.isNotBlank(brokerCodeOverride) && !"MANUAL".equalsIgnoreCase(brokerCodeOverride)) { + return brokerCodeOverride; + } + return StringUtils.defaultIfBlank(account.getBrokerCode(), "STANDARD"); + } + private UserBrokerAccount validateAccount(Long accountId) { if (accountId == null) { throw ExceptionEnum.PORTFOLIO_ACCOUNT_NOT_FOUND.toException(); diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/UserPortfolioService.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/UserPortfolioService.java index fb8c8e94..4ab377a3 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/UserPortfolioService.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/UserPortfolioService.java @@ -3,16 +3,21 @@ import com.brotherc.aquant.common.exception.BusinessException; import com.brotherc.aquant.common.exception.ExceptionEnum; import com.brotherc.aquant.common.utils.DigestUtils; +import com.brotherc.aquant.sync.entity.StockSync; +import com.brotherc.aquant.sync.repository.StockSyncRepository; +import com.brotherc.aquant.common.utils.StockUtils; import com.brotherc.aquant.common.utils.UserContext; import com.brotherc.aquant.fund.entity.StockFundNetValue; import com.brotherc.aquant.fund.repository.StockFundNetValueRepository; import com.brotherc.aquant.portfolio.entity.*; import com.brotherc.aquant.portfolio.model.vo.*; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO.BrokerPositionItemVO; import com.brotherc.aquant.portfolio.repository.*; import com.brotherc.aquant.stock.entity.StockQuote; import com.brotherc.aquant.stock.entity.StockQuoteHistory; import com.brotherc.aquant.stock.repository.StockQuoteHistoryRepository; import com.brotherc.aquant.stock.repository.StockQuoteRepository; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -21,6 +26,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.StandardCharsets; @@ -37,6 +43,8 @@ public class UserPortfolioService { private static final Set ASSET_TYPES = Set.of("STOCK", "ETF", "FUND", "BOND", "CASH"); private static final Set POSITION_IN_TYPES = Set.of("BUY", "SUBSCRIBE", "POSITION_INIT", "TRANSFER_IN", "DIVIDEND_SHARE"); private static final Set POSITION_OUT_TYPES = Set.of("SELL", "REDEEM", "TRANSFER_OUT"); + /** 券商持仓代码的 ETF 前缀(与导入适配器口径一致) */ + private static final Set BROKER_ETF_PREFIXES = Set.of("15", "16", "50", "51", "52", "53", "56", "58"); private static final Set AMOUNT_ONLY_TYPES = Set.of( "DIVIDEND_CASH", "FEE", "TAX", "INTEREST", "CASH_DEPOSIT", "CASH_WITHDRAW" ); @@ -51,6 +59,8 @@ public class UserPortfolioService { private final StockQuoteRepository stockQuoteRepository; private final StockQuoteHistoryRepository stockQuoteHistoryRepository; private final StockFundNetValueRepository fundNetValueRepository; + private final com.brotherc.aquant.sync.repository.StockSyncRepository stockSyncRepository; + private final ObjectMapper objectMapper; @Transactional(rollbackFor = Exception.class) public List getPortfolios() { @@ -220,7 +230,12 @@ public PortfolioImportResultVO saveTrades(PortfolioTradeBatchReqVO reqVO) { successCount++; } } - rebuildPositions(account); + // 券商同步渠道(EM_WEB/EASYTRADER)的持仓与资产由接口快照直取落库 + // (replacePositionsFromBroker,由 PortfolioBrokerSyncService 同步时调用); + // 其成交接口只提供增量数据,用它重算会因历史持仓缺失把持仓错误清零,故不在此重算 + if (!isBrokerSyncChannel(source)) { + rebuildPositions(account, isLenientOverSellSource(account, source)); + } batch.setSuccessCount(successCount); batch.setSkipCount(skipCount); batch.setStatus("SUCCESS"); @@ -499,6 +514,161 @@ public List getSnapshots(Long portfolioId, LocalDa } private void rebuildPositions(UserBrokerAccount account) { + rebuildPositions(account, false); + } + + /** + * 卖出超持仓是否按宽松模式处理(钳制清仓而非报错)。 + * 东财自动同步(EM_WEB)与客户端同步(EASYTRADER)只有当日成交、无历史持仓流水, + * 卖出必然"超额";东财交割单文件导入同理。招商(CMS)及手动录入保持严格校验。 + */ + private boolean isLenientOverSellSource(UserBrokerAccount account, String source) { + String normalizedSource = StringUtils.defaultString(source).toUpperCase(Locale.ROOT); + if ("EASYTRADER".equals(normalizedSource) || "EM_WEB".equals(normalizedSource)) { + return true; + } + String syncMode = StringUtils.defaultString(account.getSyncMode()).toUpperCase(Locale.ROOT); + String brokerCode = StringUtils.defaultString(account.getBrokerCode()).toUpperCase(Locale.ROOT); + return "EM_WEB".equals(syncMode) || "EM".equals(brokerCode) || "EASTMONEY".equals(brokerCode); + } + + /** 是否为券商自动同步渠道(持仓以接口快照为准,不用成交流水重算) */ + private boolean isBrokerSyncChannel(String source) { + String normalized = StringUtils.defaultString(source).toUpperCase(Locale.ROOT); + return "EASYTRADER".equals(normalized) || "EM_WEB".equals(normalized); + } + + /** 券商持仓快照在 stock_sync 表中的键前缀(按账户隔离) */ + private static final String BROKER_SNAPSHOT_KEY_PREFIX = "portfolio_broker_snapshot_"; + + /** 持久化最近一次成功同步的券商持仓快照(Cookie 失效后页面仍可展示该数据) */ + public void saveBrokerSnapshot(Long accountId, BrokerPositionSnapshotVO snapshot) { + try { + StockSync stored = stockSyncRepository.findByName(BROKER_SNAPSHOT_KEY_PREFIX + accountId); + if (stored == null) { + stored = new StockSync(); + stored.setName(BROKER_SNAPSHOT_KEY_PREFIX + accountId); + } + stored.setValue(objectMapper.writeValueAsString(snapshot)); + stockSyncRepository.save(stored); + } catch (RuntimeException | IOException exception) { + // 持久化失败不影响本次同步结果,仅下次打开页面看不到缓存 + log.warn("券商持仓快照持久化失败: accountId={}", accountId, exception); + } + } + + /** 读取最近一次成功同步的券商持仓快照(无则返回 null,前端展示引导文案) */ + public BrokerPositionSnapshotVO getBrokerSnapshot(Long accountId) { + try { + StockSync stored = stockSyncRepository.findByName(BROKER_SNAPSHOT_KEY_PREFIX + accountId); + if (stored == null || StringUtils.isBlank(stored.getValue())) { + return null; + } + return objectMapper.readValue(stored.getValue(), BrokerPositionSnapshotVO.class); + } catch (RuntimeException | IOException exception) { + log.warn("券商持仓快照读取失败: accountId={}", accountId, exception); + return null; + } + } + + /** + * 用券商接口持仓快照覆盖本地持仓(全部为券商口径原值,本地不做推算)。 + * + *

券商渠道的成交接口只提供增量数据(当日至最近若干日),账户历史持仓不在其中, + * 用成交流水重算必然把持仓错误清零,因此这类账户的持仓以此方法为准: + * 持仓数量/可用数量/成本价/最新价/市值/持仓盈亏均直取接口值, + * 资金可用/冻结同步写入现金表(总资产含证券市值,不写现金余额以免重复计账)。

+ */ + @Transactional(rollbackFor = Exception.class) + public void replacePositionsFromBroker(Long accountId, Long userId, BrokerPositionSnapshotVO snapshot) { + UserBrokerAccount account = getAccount(accountId, userId); + LocalDateTime now = LocalDateTime.now(); + LocalDate today = now.toLocalDate(); + + // 旧持仓按代码留存:jywg 盘前/非交易时段返回的最新价/市值/盈亏为空, + // 这些字段用旧值兜底,避免把上一次同步的有效数据清成 NULL + Map previousByCode = positionRepository + .findAllByAccountIdOrderByMarketValueDesc(account.getId()).stream() + .collect(Collectors.toMap(UserPortfolioPosition::getAssetCode, item -> item, (first, second) -> first)); + + List positions = new ArrayList<>(); + for (BrokerPositionItemVO item : snapshot.getPositions()) { + if (StringUtils.isBlank(item.getSecurityCode()) || item.getHoldingQuantity() == null + || item.getHoldingQuantity().signum() <= 0) { + continue; + } + UserPortfolioPosition previous = previousByCode.get(item.getSecurityCode()); + UserPortfolioPosition position = new UserPortfolioPosition(); + position.setAccountId(account.getId()); + position.setAssetType(brokerAssetType(item.getSecurityCode())); + position.setMarket(StockUtils.market(item.getSecurityCode())); + position.setAssetCode(item.getSecurityCode()); + position.setAssetName(item.getSecurityName()); + position.setCurrency("CNY"); + position.setQuantity(item.getHoldingQuantity()); + position.setAvailableQuantity(item.getEnableQuantity() == null + ? item.getHoldingQuantity() : item.getEnableQuantity()); + position.setCostPrice(item.getCostPrice()); + // 成本额按券商成本价×数量推算;摊薄成本价可为负,属券商正常口径,原样保留 + position.setCostAmount(item.getCostPrice() == null + ? null : item.getCostPrice().multiply(item.getHoldingQuantity())); + // 最新价/市值/盈亏盘前或非交易时段可能为空:空值保留上一次同步的旧值(最后已知价模式) + position.setLatestPrice(item.getLastPrice() != null ? item.getLastPrice() + : previous != null ? previous.getLatestPrice() : null); + position.setMarketValue(item.getMarketValue() != null ? item.getMarketValue() + : previous != null ? previous.getMarketValue() : null); + position.setUnrealizedProfit(item.getIncome() != null ? item.getIncome() + : previous != null ? previous.getUnrealizedProfit() : null); + position.setIncomeRate(item.getIncomeRate() != null ? item.getIncomeRate() + : previous != null ? previous.getIncomeRate() : null); + position.setDayIncome(item.getDayIncome() != null ? item.getDayIncome() + : previous != null ? previous.getDayIncome() : null); + position.setDayIncomeRate(item.getDayIncomeRate() != null ? item.getDayIncomeRate() + : previous != null ? previous.getDayIncomeRate() : null); + position.setQuoteDate(today); + position.setCalculateTime(now); + positions.add(position); + } + positionRepository.deleteByAccountId(account.getId()); + positionRepository.saveAll(positions); + + if (snapshot.getEnableBalance() != null || snapshot.getFrozenBalance() != null) { + BigDecimal available = snapshot.getEnableBalance() == null + ? BigDecimal.ZERO : snapshot.getEnableBalance(); + BigDecimal frozen = snapshot.getFrozenBalance() == null + ? BigDecimal.ZERO : snapshot.getFrozenBalance(); + UserPortfolioCash cash = cashRepository.findByAccountIdAndCurrency(account.getId(), "CNY") + .orElseGet(UserPortfolioCash::new); + cash.setAccountId(account.getId()); + cash.setCurrency("CNY"); + cash.setAvailableBalance(available); + cash.setFrozenBalance(frozen); + cash.setTotalBalance(available.add(frozen)); + cashRepository.save(cash); + } + rebuildAccountHistoricalSnapshots(account); + } + + /** 券商持仓代码推断资产类型(ETF 前缀 → ETF,债券代码 → BOND,其余 STOCK) */ + private String brokerAssetType(String assetCode) { + if (StockUtils.isBond(assetCode)) { + return "BOND"; + } + if (assetCode.length() >= 2 && BROKER_ETF_PREFIXES.contains(assetCode.substring(0, 2))) { + return "ETF"; + } + return "STOCK"; + } + + /** + * 全量重算账户持仓。 + * + * @param lenientOverSell 卖出超持仓时的处理:false 严格模式抛异常(手动录入/招商文件, + * 数据可追溯、必须准确);true 宽松模式按现有数量钳制扣减并告警 + * (东财等自动同步/交割单导入只有当日成交,账户此前历史持仓不在 + * 流水里,卖出必然"超额",属正常业务形态而非数据错误) + */ + private void rebuildPositions(UserBrokerAccount account, boolean lenientOverSell) { Map positionMap = new LinkedHashMap<>(); for (UserPortfolioTrade trade : tradeRepository .findAllByAccountIdAndStatusOrderByTradeTimeAscIdAsc(account.getId(), "NORMAL")) { @@ -526,8 +696,14 @@ private void rebuildPositions(UserBrokerAccount account) { } } else { if (position.getQuantity().compareTo(quantity) < 0) { - throw new BusinessException(ExceptionEnum.PORTFOLIO_POSITION_INSUFFICIENT, - trade.getAssetCode() + "卖出或转出数量超过当前持仓"); + if (!lenientOverSell) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_POSITION_INSUFFICIENT, + trade.getAssetCode() + "卖出或转出数量超过当前持仓"); + } + // 宽松模式:历史持仓不在本流水内,按现有数量钳制扣减(数量归 0、成本全扣) + log.warn("账户 {} 流水 {} 卖出数量 {} 超过当前持仓 {},已按清仓处理(历史持仓不在导入流水内)", + account.getId(), trade.getId(), quantity, position.getQuantity()); + quantity = position.getQuantity(); } BigDecimal reducedCost = position.getQuantity().signum() == 0 ? BigDecimal.ZERO : position.getCostAmount().multiply(quantity) @@ -582,12 +758,15 @@ private void refreshPositionPrices(List accounts) { quoteDate = netValues.get(0).getNavDate() == null ? null : netValues.get(0).getNavDate().toLocalDate(); } } - position.setLatestPrice(latestPrice); - position.setQuoteDate(quoteDate); - position.setMarketValue(latestPrice == null ? null - : latestPrice.multiply(position.getQuantity()).setScale(4, RoundingMode.HALF_UP)); - position.setUnrealizedProfit(position.getMarketValue() == null ? null - : position.getMarketValue().subtract(position.getCostAmount())); + // 无报价(券商同步的代码不在行情表内)时保留最后已知值,避免读取路径把数据清空 + if (latestPrice != null) { + position.setLatestPrice(latestPrice); + position.setQuoteDate(quoteDate); + position.setMarketValue(latestPrice.multiply(position.getQuantity()).setScale(4, RoundingMode.HALF_UP)); + if (position.getCostAmount() != null) { + position.setUnrealizedProfit(position.getMarketValue().subtract(position.getCostAmount())); + } + } position.setCalculateTime(LocalDateTime.now()); } positionRepository.saveAll(positions); @@ -622,10 +801,14 @@ private List buildPositionVOs(UserPortfolio portfolio, List vo.setLatestPrice(position.getLatestPrice()); vo.setMarketValue(position.getMarketValue()); vo.setUnrealizedProfit(position.getUnrealizedProfit()); - vo.setUnrealizedProfitRate(position.getCostAmount() == null || position.getCostAmount().signum() == 0 + // 券商同步源直取接口的盈亏比例(含费用口径更准确);本地计算源按成本推算 + vo.setUnrealizedProfitRate(position.getIncomeRate() != null ? position.getIncomeRate() + : position.getCostAmount() == null || position.getCostAmount().signum() == 0 || position.getUnrealizedProfit() == null ? null : position.getUnrealizedProfit().multiply(BigDecimal.valueOf(100)) .divide(position.getCostAmount(), 4, RoundingMode.HALF_UP)); + vo.setDayIncome(position.getDayIncome()); + vo.setDayIncomeRate(position.getDayIncomeRate()); vo.setPositionRatio(position.getMarketValue() == null || denominator.signum() == 0 || !portfolio.getBaseCurrency().equals(position.getCurrency()) ? null : position.getMarketValue().multiply(BigDecimal.valueOf(100)) diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/BrokerTradeFileAdapter.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/BrokerTradeFileAdapter.java index ffedb881..e9a3b2cc 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/BrokerTradeFileAdapter.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/BrokerTradeFileAdapter.java @@ -7,6 +7,11 @@ */ public interface BrokerTradeFileAdapter { + /** 适配器服务的券商代码(与 UserBrokerAccount.brokerCode 同一取值域),用于按账户路由优先匹配 */ + default String brokerCode() { + return ""; + } + boolean supports(String brokerCode, String fileName, byte[] content); PortfolioTradeFileParseResult parse(String fileName, byte[] content); diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/CMSSecuritiesTradeFileAdapter.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/CMSSecuritiesTradeFileAdapter.java index 2c6e8080..27c7b235 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/CMSSecuritiesTradeFileAdapter.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/CMSSecuritiesTradeFileAdapter.java @@ -38,6 +38,11 @@ public class CMSSecuritiesTradeFileAdapter implements BrokerTradeFileAdapter { "证券买入", "证券卖出", "新股入账", "市值申购中签", "托管转出" ); + @Override + public String brokerCode() { + return BROKER_CODE; + } + @Override public boolean supports(String brokerCode, String fileName, byte[] content) { if (!BROKER_CODE.equalsIgnoreCase(brokerCode) || content.length == 0) { diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapter.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapter.java new file mode 100644 index 00000000..3c0a7262 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapter.java @@ -0,0 +1,363 @@ +package com.brotherc.aquant.portfolio.service.importer; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.common.utils.DigestUtils; +import com.brotherc.aquant.common.utils.StockUtils; +import com.brotherc.aquant.portfolio.model.dto.PortfolioTradeFileParseResult; +import com.brotherc.aquant.portfolio.model.dto.SourceRow; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeImportErrorVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DataFormatter; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayInputStream; +import java.math.BigDecimal; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; + +/** + * 东方财富证券交割单(对账单)适配器。 + * + *

东方财富 App/网页导出的交割单为真正的 xlsx/CSV,表头以「交割日期」为特征列 + * (区别于招商证券的「成交日期」),一文件包含多只证券的成交流水。列名在不同导出 + * 渠道间存在变体(如「流水号/合同编号/成交编号」「手续费/佣金」),统一走宽容别名映射。

+ */ +@Component +@Order(20) +public class EastmoneyTradeFileAdapter implements BrokerTradeFileAdapter { + + private static final String BROKER_CODE = "EM"; + private static final int MAX_ROWS = 5000; + /** 表头行识别特征:东财交割单独有「交割日期」,配合业务/金额列足以与其他券商文件区分 */ + private static final Set HEADER_SIGNATURE = Set.of("交割日期", "业务名称", "证券代码", "发生金额"); + private static final Set POSITION_BUSINESS_NAMES = Set.of( + "证券买入", "证券卖出", "担保品买入", "担保品卖出", "配股", "新股入账", "中签入账", "送股入账", + "基金申购", "场内申购", "基金赎回", "场内赎回" + ); + private static final Set ETF_PREFIXES = Set.of("15", "16", "50", "51", "52", "53", "56", "58"); + + @Override + public String brokerCode() { + return BROKER_CODE; + } + + @Override + public boolean supports(String brokerCode, String fileName, byte[] content) { + // 兼容前端券商选择器的 EASTMONEY 写法 + if ((!BROKER_CODE.equalsIgnoreCase(brokerCode) && !"EASTMONEY".equalsIgnoreCase(brokerCode)) + || content.length == 0) { + return false; + } + try { + List> rows = readRows(content, 20); + for (List row : rows) { + if (new HashSet<>(row).containsAll(HEADER_SIGNATURE)) { + return true; + } + } + return false; + } catch (RuntimeException e) { + return false; + } + } + + @Override + public PortfolioTradeFileParseResult parse(String fileName, byte[] content) { + List sourceRows = toSourceRows(content); + if (sourceRows.isEmpty()) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_IMPORT_FILE_INVALID, + "东方财富交割单中没有可读取的数据"); + } + + PortfolioTradeFileParseResult result = new PortfolioTradeFileParseResult(); + result.setFileName(sanitizeFileName(fileName)); + result.setFileHash(DigestUtils.sha256(content)); + fillLatestCashBalance(result, sourceRows); + for (SourceRow sourceRow : sourceRows) { + result.setTotalCount(result.getTotalCount() + 1); + if (result.getTotalCount() > MAX_ROWS) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_IMPORT_FILE_INVALID, + "单个文件最多允许 5000 条交易流水"); + } + try { + result.getTrades().add(toTrade(sourceRow)); + } catch (IllegalArgumentException e) { + result.getErrors().add(new PortfolioTradeImportErrorVO(sourceRow.getRowNumber(), e.getMessage())); + } + } + return result; + } + + private void fillLatestCashBalance(PortfolioTradeFileParseResult result, List sourceRows) { + LocalDate latestTradeDate = sourceRows.stream() + .filter(row -> StringUtils.isNotBlank(row.get("资金余额"))) + .map(row -> parseDate(row.required("交割日期"))) + .max(LocalDate::compareTo).orElse(null); + if (latestTradeDate == null) { + return; + } + // 东财交割单按时间正序排列,最新余额取最新交割日期的最后一行 + List sameDateRows = sourceRows.stream() + .filter(row -> StringUtils.isNotBlank(row.get("资金余额"))) + .filter(row -> latestTradeDate.equals(parseDate(row.required("交割日期")))) + .toList(); + if (sameDateRows.isEmpty()) { + return; + } + SourceRow row = sameDateRows.get(sameDateRows.size() - 1); + result.setLatestCashBalance(StockUtils.decimal(row.get("资金余额"), "资金余额")); + result.setCashBalanceDate(latestTradeDate); + result.setCashBalanceCurrency(currency(row.get("币种"))); + } + + private PortfolioTradeSaveReqVO toTrade(SourceRow row) { + String businessName = row.required("业务名称"); + String assetCode = StringUtils.trimToNull(row.get("证券代码")); + String assetName = StringUtils.trimToNull(row.get("证券名称")); + BigDecimal quantity = StockUtils.decimal(row.get("成交数量"), "成交数量"); + BigDecimal price = StockUtils.decimal(row.get("成交价格"), "成交价格"); + BigDecimal tradeAmount = StockUtils.decimal(row.get("成交金额"), "成交金额"); + BigDecimal netAmount = StockUtils.decimal(row.get("发生金额"), "发生金额"); + + PortfolioTradeSaveReqVO trade = new PortfolioTradeSaveReqVO(); + trade.setTradeType(tradeType(businessName)); + trade.setAssetType(assetType(assetCode)); + trade.setAssetCode(assetCode); + trade.setAssetName(assetName); + trade.setMarket(StockUtils.market(assetCode)); + trade.setTradeTime(parseDate(row.required("交割日期")).atStartOfDay()); + trade.setCurrency(currency(row.get("币种"))); + trade.setSourceTradeId(firstNonBlank(row.get("流水号"), row.get("合同编号"), row.get("成交编号"))); + trade.setNetAmount(netAmount); + trade.setCommission(fee(row, "手续费", "佣金")); + trade.setStampDuty(fee(row, "印花税")); + trade.setTransferFee(fee(row, "过户费")); + trade.setOtherFee(fee(row, "结算费", "规费", "经手费", "证管费", "其他费用")); + trade.setRemark(remark(row, businessName)); + + if (POSITION_BUSINESS_NAMES.contains(businessName)) { + if (StringUtils.isBlank(assetCode) || quantity == null || quantity.signum() == 0) { + throw new IllegalArgumentException(businessName + "缺少有效的证券代码或成交数量"); + } + trade.setQuantity(quantity.abs()); + trade.setPrice(price == null || price.signum() == 0 + ? BigDecimal.ZERO : price.abs()); + if ("新股入账".equals(businessName) || "中签入账".equals(businessName) || "送股入账".equals(businessName)) { + trade.setGrossAmount(BigDecimal.ZERO); + } else if (tradeAmount != null && tradeAmount.signum() != 0) { + trade.setGrossAmount(tradeAmount.abs()); + } else { + trade.setGrossAmount(trade.getPrice().multiply(trade.getQuantity())); + } + } else { + trade.setGrossAmount(netAmount == null ? null : netAmount.abs()); + } + return trade; + } + + private String tradeType(String businessName) { + return switch (businessName) { + case "证券买入", "担保品买入", "配股", "证券买入(配股)" -> "BUY"; + case "证券卖出", "担保品卖出" -> "SELL"; + case "股息入账", "红利入账" -> "DIVIDEND_CASH"; + case "股息红利税补缴", "红利补税", "利息税", "红利税" -> "TAX"; + case "利息归本" -> "INTEREST"; + case "银行转存", "银行转入", "资金转入" -> "CASH_DEPOSIT"; + case "银行转取", "银行转出", "资金转出" -> "CASH_WITHDRAW"; + case "新股入账", "中签入账", "送股入账" -> "TRANSFER_IN"; + case "基金申购", "场内申购" -> "SUBSCRIBE"; + case "基金赎回", "场内赎回" -> "REDEEM"; + default -> throw new IllegalArgumentException("暂不支持东方财富业务类型:" + businessName); + }; + } + + private String assetType(String assetCode) { + if (StringUtils.isBlank(assetCode)) { + return "CASH"; + } + if (assetCode.length() >= 2 && ETF_PREFIXES.contains(assetCode.substring(0, 2))) { + return "ETF"; + } + return StockUtils.isBond(assetCode) ? "BOND" : "STOCK"; + } + + private String remark(SourceRow row, String businessName) { + return StringUtils.isBlank(row.get("备注")) + ? "东方财富:" + businessName + : "东方财富:" + businessName + ";" + row.get("备注"); + } + + private List toSourceRows(byte[] content) { + List> rows = readRows(content, MAX_ROWS + 100); + int headerLine = -1; + List headers = List.of(); + for (int i = 0; i < Math.min(rows.size(), 20); i++) { + if (new HashSet<>(rows.get(i)).containsAll(HEADER_SIGNATURE)) { + headerLine = i; + headers = rows.get(i); + break; + } + } + if (headerLine < 0) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_IMPORT_FILE_INVALID, + "无法识别东方财富交割单表头,请确认导出的是交割单(对账单)明细文件"); + } + Map columns = new HashMap<>(); + for (int i = 0; i < headers.size(); i++) { + String header = normalize(headers.get(i)); + if (StringUtils.isNotBlank(header) && !columns.containsKey(header)) { + columns.put(header, i); + } + } + List result = new ArrayList<>(); + for (int i = headerLine + 1; i < rows.size(); i++) { + List values = rows.get(i); + if (values.stream().allMatch(StringUtils::isBlank)) { + continue; + } + Map data = new HashMap<>(); + columns.forEach((header, index) -> data.put(header, + index < values.size() ? values.get(index) : "")); + result.add(new SourceRow(i + 1, data)); + } + return result; + } + + /** + * 读文件为行列文本。xlsx/xls(zip 魔数)走 POI,其余按 UTF-8 → GB18030 文本解析; + * 单元格允许 ="值" 包装(券商导出软件常见格式)。 + */ + private List> readRows(byte[] content, int maxRows) { + if (content.length >= 2 && content[0] == 'P' && content[1] == 'K') { + return readWorkbook(content, maxRows); + } + return readText(decode(content), maxRows); + } + + private List> readWorkbook(byte[] content, int maxRows) { + try (Workbook workbook = WorkbookFactory.create(new ByteArrayInputStream(content))) { + List> rows = new ArrayList<>(); + if (workbook.getNumberOfSheets() == 0) { + return rows; + } + Sheet sheet = workbook.getSheetAt(0); + DataFormatter formatter = new DataFormatter(Locale.CHINA); + int lastRow = Math.min(sheet.getLastRowNum(), maxRows); + for (int rowIndex = sheet.getFirstRowNum(); rowIndex <= lastRow; rowIndex++) { + Row row = sheet.getRow(rowIndex); + List values = new ArrayList<>(); + int lastCell = row == null ? 0 : Math.min(row.getLastCellNum(), 50); + for (int column = 0; column < lastCell; column++) { + Cell cell = row.getCell(column, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL); + values.add(cell == null ? "" : formatter.formatCellValue(cell).trim()); + } + rows.add(values); + } + return rows; + } catch (Exception e) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_IMPORT_FILE_INVALID, + "无法读取东方财富交割单文件,请确认文件未损坏"); + } + } + + private List> readText(String text, int maxRows) { + String[] lines = text.split("\\R", -1); + boolean tabbed = lines.length > 0 && lines[0].indexOf('\t') >= 0; + List> rows = new ArrayList<>(); + for (int i = 0; i < Math.min(lines.length, maxRows); i++) { + List values = Arrays.stream(lines[i].split(tabbed ? "\\t" : ",", -1)) + .map(this::unwrapCell).toList(); + rows.add(values); + } + return rows; + } + + private String unwrapCell(String value) { + String text = value.trim(); + if (text.startsWith("=\"") && text.endsWith("\"") && text.length() >= 3) { + return text.substring(2, text.length() - 1).replace("\"\"", "\"").trim(); + } + return text; + } + + private String decode(byte[] content) { + try { + return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(content)).toString(); + } catch (CharacterCodingException e) { + try { + return java.nio.charset.Charset.forName("GB18030").newDecoder() + .decode(ByteBuffer.wrap(content)).toString(); + } catch (CharacterCodingException ex) { + throw new BusinessException(ExceptionEnum.PORTFOLIO_IMPORT_FILE_INVALID, + "东方财富交割单编码无法识别"); + } + } + } + + private LocalDate parseDate(String text) { + String value = StringUtils.trimToEmpty(text); + if (value.length() > 10 && value.charAt(10) == ' ') { + value = value.substring(0, 10); + } + for (DateTimeFormatter formatter : List.of(DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ofPattern("yyyy/MM/dd"), DateTimeFormatter.BASIC_ISO_DATE)) { + try { + return LocalDate.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + throw new IllegalArgumentException("交割日期格式无法识别:" + text); + } + + private BigDecimal fee(SourceRow row, String... fields) { + BigDecimal total = BigDecimal.ZERO; + for (String field : fields) { + BigDecimal value = StockUtils.decimal(row.get(field), field); + total = total.add(value == null ? BigDecimal.ZERO : value.abs()); + } + return total; + } + + private String firstNonBlank(String... values) { + for (String value : values) { + if (StringUtils.isNotBlank(value)) { + return value.trim(); + } + } + return null; + } + + private String currency(String value) { + return switch (StringUtils.defaultIfBlank(value, "人民币").toUpperCase(Locale.ROOT)) { + case "人民币", "CNY", "RMB" -> "CNY"; + case "港币", "HKD" -> "HKD"; + case "美元", "USD" -> "USD"; + default -> throw new IllegalArgumentException("暂不支持币种:" + value); + }; + } + + private String normalize(String value) { + return StringUtils.defaultString(value).replaceAll("[\\s_()()/-]", ""); + } + + private String sanitizeFileName(String value) { + String normalized = StringUtils.defaultIfBlank(value, "em-statement.xlsx").replace('\\', '/'); + return normalized.substring(normalized.lastIndexOf('/') + 1); + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProvider.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProvider.java new file mode 100644 index 00000000..5a0e329f --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProvider.java @@ -0,0 +1,447 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.common.utils.StockUtils; +import com.brotherc.aquant.integration.eastmoney.service.EastmoneyJywgClient; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO.BrokerPositionItemVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * 东方财富证券网页交易渠道(UserBrokerAccount.syncMode = EM_WEB)。 + * + *

经 EastmoneyJywgClient(浏览器会话 Cookie + validatekey)读取当日与最近 7 天成交、 + * 资金持仓。成交接口无费用明细(费用在次日交割单/资金流水中),现金净发生额按 + * 方向推算;同一账户建议以网页同步为主,避免再导交割单造成重复计账。

+ */ +@Slf4j +@Component +public class EastmoneyWebTradeSyncProvider implements PortfolioBrokerSyncProvider { + + public static final String CHANNEL = "EM_WEB"; + private static final Set ETF_PREFIXES = Set.of("15", "16", "50", "51", "52", "53", "56", "58"); + + private final EastmoneyJywgClient jywgClient; + + public EastmoneyWebTradeSyncProvider(EastmoneyJywgClient jywgClient) { + this.jywgClient = jywgClient; + } + + @Override + public String channel() { + return CHANNEL; + } + + @Override + public List fetchTrades() { + // 当日成交 + 最近 7 天历史成交合并(历史接口含当日数据,两接口重叠行按 + // 成交编号+代码+时间+数量去重),避免跨天未同步时漏单;落库另有 dedupKey 幂等兜底 + LocalDate today = LocalDate.now(); + JsonNode todayMatches = jywgClient.todayMatches(); + JsonNode historyMatches = jywgClient.historyMatches( + today.minusDays(6).format(DateTimeFormatter.BASIC_ISO_DATE), + today.format(DateTimeFormatter.BASIC_ISO_DATE)); + Map merged = new LinkedHashMap<>(); + for (JsonNode row : todayMatches) { + merged.putIfAbsent(rowKey(row), row); + } + for (JsonNode row : historyMatches) { + merged.putIfAbsent(rowKey(row), row); + } + List trades = new ArrayList<>(); + for (JsonNode row : merged.values()) { + trades.add(toTrade(row)); + } + return trades; + } + + /** 跨接口去重键:成交编号优先,缺失时退化为 代码|日期|时间|数量|金额 */ + private String rowKey(JsonNode row) { + String dealId = firstNonBlank(text(row, "matchcode", "Cjbh", "成交编号"), + text(row, "orderid", "Wtbh", "委托编号")); + if (StringUtils.isNotBlank(dealId)) { + return "id:" + dealId; + } + return String.join("|", + StringUtils.defaultString(text(row, "stkcode", "Zqdm")), + StringUtils.defaultString(text(row, "bizdate", "Wtrq")), + StringUtils.defaultString(text(row, "matchtime", "Cjsj")), + StringUtils.defaultString(text(row, "matchqty", "Cjsl")), + StringUtils.defaultString(text(row, "matchamt"))); + } + + /** 依次取第一个非空文本字段 */ + private String text(JsonNode row, String... fields) { + for (String field : fields) { + String value = normalizeDigits(row.path(field).asText("")); + if (StringUtils.isNotBlank(value)) { + return value; + } + } + return ""; + } + + /** 依次取第一个可解析的非空数值字段(缺失或不可解析返回 null,不抛错) */ + private BigDecimal firstDecimal(JsonNode row, String... fields) { + for (String field : fields) { + String value = normalizeDigits(row.path(field).asText("")); + if (StringUtils.isBlank(value)) { + continue; + } + try { + return new BigDecimal(value); + } catch (NumberFormatException ignored) { + // 尝试下一个候选字段。 + } + } + return null; + } + + /** + * 券商实时持仓快照(多证券)。jywg queryAssetAndPositionV1 实测为 snake_case: + * 资产层 total_asset/security_market_value/enable_balance/fetch_balance/frozen_balance/ + * money_balance/position_income/day_income;持仓层 security_code/security_name/ + * holding_quantity/enable_quantity/cost_price/last_price/market_value/income/ + * income_rate/day_income/day_income_rate/keep_cost_price。 + * 所有指标直取券商原值(成本价摊薄可为负、比例带 %),本地不做任何推算; + * 同时兼容旧的大写拼音缩写体系字段名。 + */ + @Override + public BrokerPositionSnapshotVO fetchPositions() { + JsonNode data = jywgClient.assetAndPosition(); + JsonNode first = data.isArray() && !data.isEmpty() ? data.get(0) : data; + BrokerPositionSnapshotVO snapshot = new BrokerPositionSnapshotVO(); + snapshot.setChannel(CHANNEL); + snapshot.setFetchTime(java.time.LocalDateTime.now().toString()); + if (first == null || first.isMissingNode()) { + return snapshot; + } + // 字段映射诊断:东财 jywg 各接口字段命名不一致(成交行实测为 stkcode/matchprice 小写体系), + // 持仓字段若与下方映射不匹配会被记为缺失;该日志输出真实字段名与值,便于精确对齐映射 + log.info("东财持仓接口原始响应(资产层): {}", first); + // 候选字段覆盖三种命名风格:snake_case(官方文档)、无下划线小写(东财实测 stkcode 体系)、拼音缩写(旧逆向) + snapshot.setTotalAsset(decimal(first, "Zzc", "zzc", "total_asset", "totalasset")); + snapshot.setSecurityMarketValue(decimal(first, "Zxsz", "zxsz", "totalSecMkval", "totalsecmkval", + "security_market_value", "securitymarketvalue")); + snapshot.setEnableBalance(decimal(first, "Kyzj", "kyzj", "enable_balance", "enablebalance", "fundbal")); + snapshot.setFetchBalance(decimal(first, "Kqzj", "kqzj", "fetch_balance", "fetchbalance")); + snapshot.setFrozenBalance(decimal(first, "Djzj", "djzj", "frozen_balance", "frozenbalance")); + snapshot.setMoneyBalance(decimal(first, "Zjye", "zjye", "money_balance", "moneybalance", "fund_balance")); + snapshot.setPositionIncome(decimal(first, "Ljyk", "ljyk", "position_income", "positionincome")); + snapshot.setDayIncome(decimal(first, "Dryk", "dryk", "day_income", "dayincome")); + + JsonNode rows = first.path("positions"); + for (String candidate : List.of("positions", "positionlist", "stocklist", "holdings", "list", "data")) { + if (rows.isArray() && !rows.isEmpty()) { + break; + } + JsonNode value = first.path(candidate); + if (value.isArray() && !value.isEmpty()) { + rows = value; + } + } + if (!rows.isArray() || rows.isEmpty()) { + for (JsonNode field : first) { + if (field.isArray() && !field.isEmpty() && field.get(0).isObject()) { + rows = field; + break; + } + } + } + // 持仓行字段同样输出一例(首个持仓),用于校准持仓层字段映射 + if (rows.isArray() && !rows.isEmpty()) { + log.info("东财持仓接口原始响应(持仓示例行): {}", rows.get(0)); + } + for (JsonNode position : rows) { + BrokerPositionItemVO item = new BrokerPositionItemVO(); + item.setSecurityCode(text(position, "Zqdm", "zqdm", "stkcode", "security_code")); + item.setSecurityName(text(position, "Zqmc", "zqmc", "stkname", "security_name")); + item.setHoldingQuantity(decimal(position, "Zqsl", "zqsl", "stkqty", "holding_quantity")); + item.setEnableQuantity(decimal(position, "Kysl", "kysl", "enableqty", "enable_quantity")); + item.setCostPrice(decimal(position, "Cbjg", "cbjg", "costprice", "cost_price")); + item.setLastPrice(decimal(position, "Zxjg", "zxjg", "lastprice", "last_price")); + item.setMarketValue(decimal(position, "Zxsz", "zxsz", "zxsznew", "marketvalue", "market_value")); + item.setIncome(decimal(position, "Ljyk", "ljyk", "Ckyk", "income")); + // Ykbl 为小数比例(-0.056604 = -5.660%),需放大 100 倍与官网百分比口径一致 + BigDecimal ykbl = scaledPercent(position, "Ykbl", "ykbl"); + item.setIncomeRate(ykbl != null ? ykbl : percent(position, "income_rate")); + BigDecimal drykbl = scaledPercent(position, "Drykbl", "drykbl"); + item.setDayIncomeRate(drykbl != null ? drykbl : percent(position, "day_income_rate")); + item.setDayIncome(decimal(position, "Dryk", "dryk", "day_income")); + item.setKeepCostPrice(decimal(position, "Cbjgex", "cbjgex", "keep_cost_price", "keepcostprice")); + snapshot.getPositions().add(item); + } + return snapshot; + } + + /** 数值解析:去除千分位/百分号外字符;失败返回 null(快照字段可缺省) */ + private BigDecimal decimal(JsonNode row, String... fields) { + return firstDecimal(row, fields); + } + + /** 小数比例解析(如 -0.056604),放大 100 倍转为百分比口径(-5.6604),失败返回 null */ + private BigDecimal scaledPercent(JsonNode row, String... fields) { + for (String field : fields) { + String value = normalizeDigits(row.path(field).asText("")).replace("%", ""); + if (StringUtils.isBlank(value)) { + continue; + } + try { + return new BigDecimal(value).multiply(BigDecimal.valueOf(100)); + } catch (NumberFormatException ignored) { + // 尝试下一个候选字段。 + } + } + return null; + } + + /** 比例解析:接口带 % 后缀(如 "-5.660%"),去 % 后返回数值;支持多候选字段 */ + private BigDecimal percent(JsonNode row, String... fields) { + for (String field : fields) { + String value = normalizeDigits(row.path(field).asText("")).replace("%", ""); + if (StringUtils.isBlank(value)) { + continue; + } + try { + return new BigDecimal(value); + } catch (NumberFormatException ignored) { + // 尝试下一个候选字段。 + } + } + return null; + } + + /** + * 成交行映射。jywg 实测字段为小写体系( stkcode/matchprice/matchqty/matchamt/fundeffect/ + * bsflag_ex/matchtime/bizdate/fee_* ),同时兼容旧逆向文档的 Zqdm/Cjsj 大写体系。 + * 交割/成交行自带费用明细与签名资金净额(fundeffect),直接采用,不再推算。 + */ + private PortfolioTradeSaveReqVO toTrade(JsonNode row) { + String assetCode = firstNonBlank(text(row, "stkcode", "Zqdm", "证券代码")); + if (StringUtils.isBlank(assetCode)) { + throw new IllegalArgumentException("成交行缺少证券代码:" + row); + } + String operation = firstNonBlank(text(row, "bsflag_ex", "Mmsm", "操作", "买卖标志")); + String bsflag = text(row, "bsflag"); + BigDecimal price = firstDecimal(row, "matchprice", "Cjjg", "成交价格"); + BigDecimal quantity = firstDecimal(row, "matchqty", "Cjsl", "成交数量"); + BigDecimal amount = firstDecimal(row, "matchamt", "成交金额"); + BigDecimal gross = amount != null ? amount.abs() + : price == null || quantity == null ? null : price.multiply(quantity).abs(); + + PortfolioTradeSaveReqVO trade = new PortfolioTradeSaveReqVO(); + trade.setTradeType(tradeType(operation, bsflag, assetCode)); + trade.setAssetType(assetType(assetCode)); + trade.setMarket(StockUtils.market(assetCode)); + trade.setAssetCode(assetCode); + trade.setAssetName(firstNonBlank(text(row, "stkname", "Zqmc", "证券名称"))); + trade.setTradeTime(parseTradeTime(row)); + trade.setQuantity(quantity); + trade.setPrice(price); + trade.setGrossAmount(gross); + // 费用明细实测(买入样例):fee_sxf≈万分之2.5 佣金、fee_yhs 印花税(买入为 0)、 + // fee_ghf≈十万分之1 过户费、fee_jsxf 经手费等其他费用 + trade.setCommission(firstDecimal(row, "fee_sxf", "佣金")); + trade.setStampDuty(firstDecimal(row, "fee_yhs", "印花税")); + trade.setTransferFee(firstDecimal(row, "fee_ghf", "过户费")); + trade.setOtherFee(firstDecimal(row, "fee_jsxf", "其他费用", "经手费")); + // fundeffect 为签名资金净发生额(含费,买入为负),上游权威值直接采用 + BigDecimal netAmount = firstDecimal(row, "fundeffect", "发生金额"); + trade.setNetAmount(netAmount != null ? netAmount + : "BUY".equals(trade.getTradeType()) ? (gross == null ? null : gross.negate()) : gross); + trade.setCurrency("CNY"); + trade.setSourceTradeId(firstNonBlank(text(row, "matchcode", "Cjbh", "成交编号"), + text(row, "orderid", "Wtbh", "委托编号"))); + trade.setRemark("东方财富网页交易:" + StringUtils.defaultIfBlank(operation, "成交")); + return trade; + } + + private String tradeType(String operation, String bsflag, String assetCode) { + String text = StringUtils.defaultString(operation); + if (text.contains("买")) { + return "BUY"; + } + if (text.contains("卖")) { + return "SELL"; + } + // bsflag 代码形如 0B/0S + String flag = StringUtils.defaultString(bsflag); + if (flag.endsWith("B")) { + return "BUY"; + } + if (flag.endsWith("S")) { + return "SELL"; + } + throw new IllegalArgumentException("暂不支持东财网页成交方向:" + operation + "(" + assetCode + ")"); + } + + private String assetType(String assetCode) { + if (assetCode.length() >= 2 && ETF_PREFIXES.contains(assetCode.substring(0, 2))) { + return "ETF"; + } + return StockUtils.isBond(assetCode) ? "BOND" : "STOCK"; + } + + /** 成交时间优先字段:matchtime(成交时间 HHmmss) / bizdate(业务日期 yyyyMMdd),兼容旧体系 */ + private static final List PREFERRED_TIME_FIELDS = + List.of("matchtime", "Cjsj", "成交时间", "Wtsj", "委托时间", "Sj"); + /** 日期优先字段:bizdate(业务日期) / cleardate(清算日期) / sortdate(交收日期),兼容旧体系 */ + private static final List PREFERRED_DATE_FIELDS = + List.of("bizdate", "cleardate", "sortdate", "Wtrq", "成交日期", "委托日期"); + + /** + * 成交时间解析:优先 matchtime+bizdate 组合(实测 134357 + 20260916), + * 失败后全行扫描兜底,仍失败抛错并打印整行字段。 + */ + private LocalDateTime parseTradeTime(JsonNode row) { + LocalTime preferredTime = null; + for (String field : PREFERRED_TIME_FIELDS) { + LocalTime time = tryParseTime(row.path(field).asText("")); + if (time != null) { + preferredTime = time; + break; + } + } + LocalDate preferredDate = null; + for (String field : PREFERRED_DATE_FIELDS) { + LocalDate date = tryParseDate(row.path(field).asText("")); + if (date != null) { + preferredDate = date; + break; + } + } + if (preferredDate != null) { + return preferredDate.atTime(preferredTime == null ? LocalTime.MIN : preferredTime); + } + // 偏好字段缺失时全行扫描兜底 + LocalDate date = null; + LocalTime fallbackTime = null; + for (Iterator> fields = row.fields(); fields.hasNext(); ) { + Map.Entry field = fields.next(); + String name = field.getKey(); + String value = normalizeDigits(field.getValue().asText("")); + if (value.isEmpty() || isNonDateTimeField(name)) { + continue; + } + LocalDateTime full = tryParseDateTime(value); + if (full != null) { + return full; + } + if (date == null) { + date = tryParseDate(value); + } + if (fallbackTime == null) { + fallbackTime = tryParseTime(value); + } + } + if (date != null) { + LocalTime time = preferredTime != null ? preferredTime : fallbackTime; + return date.atTime(time == null ? LocalTime.MIN : time); + } + log.warn("东财网页成交行时间字段无法识别,原始行: {}", row); + throw new IllegalArgumentException("成交时间格式无法识别:" + row); + } + + /** 全角数字转半角,去千分位与引用符号 */ + private String normalizeDigits(String text) { + return text.replace(",", ",").replace(",", "").replace("\"", "").trim(); + } + + /** 编号/数量/价格/金额/代码等字段不参与日期时间识别 */ + private boolean isNonDateTimeField(String fieldName) { + String lower = fieldName.toLowerCase(Locale.ROOT); + return lower.contains("bh") || lower.contains("sl") || lower.contains("jg") + || lower.contains("je") || lower.contains("dm") || lower.contains("mc"); + } + + private LocalTime tryParseTime(String text) { + String value = normalizeDigits(StringUtils.trimToEmpty(text)); + for (DateTimeFormatter formatter : List.of( + DateTimeFormatter.ofPattern("HHmmss"), + DateTimeFormatter.ofPattern("HH:mm:ss"), + DateTimeFormatter.ofPattern("HH:mm"))) { + try { + return LocalTime.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + return null; + } + + private LocalDateTime tryParseDateTime(String text) { + String value = normalizeDigits(StringUtils.trimToEmpty(text)); + if (value.isEmpty()) { + return null; + } + for (DateTimeFormatter formatter : List.of( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HHmmss"), + DateTimeFormatter.ofPattern("yyyyMMdd HHmmss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"), + DateTimeFormatter.ofPattern("yyyyMMdd HH:mm"))) { + try { + return LocalDateTime.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + return null; + } + + private LocalDate tryParseDate(String text) { + String value = normalizeDigits(StringUtils.trimToEmpty(text)); + if (value.length() > 10 && value.charAt(10) == ' ') { + value = value.substring(0, 10); + } + for (DateTimeFormatter formatter : List.of(DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ofPattern("yyyy/MM/dd"), DateTimeFormatter.BASIC_ISO_DATE)) { + try { + return LocalDate.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + return null; + } + + private BigDecimal parseDecimal(JsonNode row, String field) { + JsonNode value = row.path(field); + if (value.isMissingNode() || value.isNull() || value.asText().isBlank()) { + return null; + } + try { + return new BigDecimal(value.asText().replace(",", "")); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("数值字段无法解析:" + field + "=" + value.asText()); + } + } + + private String firstNonBlank(String... values) { + for (String value : values) { + if (StringUtils.isNotBlank(value)) { + return value.trim(); + } + } + return null; + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProvider.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProvider.java new file mode 100644 index 00000000..b9f51164 --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProvider.java @@ -0,0 +1,229 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.common.utils.StockUtils; +import com.brotherc.aquant.integration.easytrader.EasytraderClient; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO.BrokerPositionItemVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * easytrader 客户端渠道(UserBrokerAccount.syncMode = EASYTRADER)。 + * + *

easytrader 以券商客户端 GUI 自动化方式提供 /position 与 /today_trades, + * 网格列名随券商客户端版本变化,统一走宽容别名映射。当日成交网格不含费用明细 + * (费用次日出现在交割单),故佣金/印花税等按 0 记录,现金净发生额按买卖方向 + * 用成交金额推算;同一账户建议以客户端同步为主,避免再导交割单造成重复计账。

+ */ +@Component +public class EasytraderTradeSyncProvider implements PortfolioBrokerSyncProvider { + + public static final String CHANNEL = "EASYTRADER"; + private static final Set ETF_PREFIXES = Set.of("15", "16", "50", "51", "52", "53", "56", "58"); + + private final EasytraderClient easytraderClient; + + public EasytraderTradeSyncProvider(EasytraderClient easytraderClient) { + this.easytraderClient = easytraderClient; + } + + @Override + public String channel() { + return CHANNEL; + } + + @Override + public List fetchTrades() { + return easytraderClient.todayTrades().stream().map(this::toTrade).toList(); + } + + @Override + public BrokerPositionSnapshotVO fetchPositions() { + BrokerPositionSnapshotVO snapshot = new BrokerPositionSnapshotVO(); + snapshot.setChannel(CHANNEL); + snapshot.setFetchTime(java.time.LocalDateTime.now().toString()); + // easytrader /position 为券商客户端网格原始行(中文列名随客户端变化), + // 只映射可稳定获取的代码/名称/数量/成本价/市值,盈亏类指标客户端不一定提供,留空 + for (Map row : easytraderClient.position()) { + BrokerPositionItemVO item = new BrokerPositionItemVO(); + item.setSecurityCode(text(row, "证券代码", "代码")); + item.setSecurityName(text(row, "证券名称", "名称")); + item.setHoldingQuantity(decimal(row, "股票余额", "持仓数量", "证券余额")); + item.setEnableQuantity(decimal(row, "可用余额", "可用数量")); + item.setCostPrice(decimal(row, "成本价", "摊薄成本价")); + item.setMarketValue(decimal(row, "市值", "最新市值")); + snapshot.getPositions().add(item); + } + return snapshot; + } + + private String text(Map row, String... keys) { + for (String key : keys) { + Object value = row.get(key); + if (value != null && StringUtils.isNotBlank(value.toString())) { + return value.toString().trim(); + } + } + return ""; + } + + private BigDecimal decimal(Map row, String... keys) { + String value = text(row, keys); + if (StringUtils.isBlank(value)) { + return null; + } + try { + return new BigDecimal(value.replace(",", "")); + } catch (NumberFormatException e) { + return null; + } + } + + private PortfolioTradeSaveReqVO toTrade(Map row) { + String assetCode = text(row, "证券代码", "代码", "zqdm"); + if (StringUtils.isBlank(assetCode)) { + throw new IllegalArgumentException("成交行缺少证券代码:" + row); + } + String operation = text(row, "操作", "买卖标志", "业务名称", "mmsm"); + String assetName = text(row, "证券名称", "名称", "zqmc"); + BigDecimal price = decimal(row, "成交价格", "成交均价"); + BigDecimal quantity = decimal(row, "成交数量", "数量"); + BigDecimal amount = decimal(row, "成交金额"); + String tradeId = StringUtils.trimToNull(text(row, "合同编号", "成交编号")); + + PortfolioTradeSaveReqVO trade = new PortfolioTradeSaveReqVO(); + trade.setTradeType(tradeType(operation, assetCode)); + trade.setAssetType(assetType(assetCode)); + trade.setMarket(StockUtils.market(assetCode)); + trade.setAssetCode(assetCode); + trade.setAssetName(assetName); + trade.setTradeTime(parseTradeTime(text(row, "成交日期", "委托日期"), text(row, "成交时间", "委托时间"))); + trade.setQuantity(quantity == null ? null : quantity.abs()); + trade.setPrice(price); + trade.setGrossAmount(amount == null + ? (price == null || quantity == null ? null : price.multiply(quantity).abs()) + : amount.abs()); + trade.setCommission(BigDecimal.ZERO); + trade.setStampDuty(BigDecimal.ZERO); + trade.setTransferFee(BigDecimal.ZERO); + trade.setOtherFee(BigDecimal.ZERO); + // 当日成交网格无费用明细:现金净发生额按方向由成交金额推算(买入扣减、卖出增加) + trade.setNetAmount("BUY".equals(trade.getTradeType()) + ? (amount == null ? null : amount.abs().negate()) + : (amount == null ? null : amount.abs())); + trade.setCurrency("CNY"); + trade.setSourceTradeId(tradeId); + trade.setRemark("easytrader:当日成交" + (StringUtils.isBlank(operation) ? "" : "(" + operation + ")") + + ",费用以后续交割单为准"); + return trade; + } + + private String tradeType(String operation, String assetCode) { + String text = StringUtils.defaultString(operation); + if (text.contains("买")) { + return "BUY"; + } + if (text.contains("卖")) { + return "SELL"; + } + throw new IllegalArgumentException("暂不支持 easytrader 成交方向:" + operation + "(" + assetCode + ")"); + } + + private String assetType(String assetCode) { + if (assetCode.length() >= 2 && ETF_PREFIXES.contains(assetCode.substring(0, 2))) { + return "ETF"; + } + return StockUtils.isBond(assetCode) ? "BOND" : "STOCK"; + } + + /** + * 成交时间解析。券商客户端网格常见返回:成交日期(20260917 或 2026-09-17)与 + * 成交时间(102502 或 10:25:02)分离,也可能已是完整时间串。 + */ + private LocalDateTime parseTradeTime(String date, String time) { + LocalDateTime parsed = tryParseDateTime(time); + if (parsed == null) { + parsed = tryParseDateTime(joinDateAndTime(date, time)); + } + if (parsed != null) { + return parsed; + } + LocalDate parsedDate = tryParseDate(firstNonBlank(time, date)); + if (parsedDate != null) { + return parsedDate.atStartOfDay(); + } + throw new IllegalArgumentException("成交时间格式无法识别:" + + (date + " " + time).trim()); + } + + private String joinDateAndTime(String date, String time) { + String dateText = normalizeDigits(StringUtils.trimToEmpty(date)); + String timeText = normalizeDigits(StringUtils.trimToEmpty(time)); + if (dateText.isEmpty() || timeText.isEmpty()) { + return ""; + } + return dateText + " " + timeText; + } + + private String normalizeDigits(String text) { + return text.replace(",", ",").replace(",", "").replace("\"", "").trim(); + } + + private LocalDateTime tryParseDateTime(String text) { + String value = normalizeDigits(StringUtils.trimToEmpty(text)); + if (value.isEmpty()) { + return null; + } + for (DateTimeFormatter formatter : List.of( + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HHmmss"), + DateTimeFormatter.ofPattern("yyyyMMdd HHmmss"), + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"), + DateTimeFormatter.ofPattern("yyyyMMdd HH:mm"))) { + try { + return LocalDateTime.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + return null; + } + + private LocalDate tryParseDate(String text) { + String value = normalizeDigits(StringUtils.trimToEmpty(text)); + if (value.length() > 10 && value.charAt(10) == ' ') { + value = value.substring(0, 10); + } + for (DateTimeFormatter formatter : List.of(DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.ofPattern("yyyy/MM/dd"), DateTimeFormatter.BASIC_ISO_DATE)) { + try { + return LocalDate.parse(value, formatter); + } catch (DateTimeParseException ignored) { + // 尝试下一种常见格式。 + } + } + return null; + } + + private String firstNonBlank(String... values) { + for (String value : values) { + if (StringUtils.isNotBlank(value)) { + return value.trim(); + } + } + return ""; + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncProvider.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncProvider.java new file mode 100644 index 00000000..3115784d --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncProvider.java @@ -0,0 +1,27 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; + +import java.util.List; + +/** + * 券商持仓/成交数据的自动同步渠道。每种渠道对应 {@code UserBrokerAccount.syncMode} + * 的一个取值(如 EASYTRADER 客户端自动化、EM_WEB 网页交易会话), + * 由 PortfolioBrokerSyncService 按账户配置路由,文件导入(MANUAL)不在此列。 + * + *

所有实现返回的都是多证券数据:一次同步覆盖账户下全部持仓/当日全部成交; + * 持仓快照的资产与成本/盈亏指标直取券商接口原值,本地不推算。

+ */ +public interface PortfolioBrokerSyncProvider { + + /** 渠道标识,与 UserBrokerAccount.syncMode 的取值对应 */ + String channel(); + + /** 拉取最近成交并转换为标准流水(多证券) */ + List fetchTrades(); + + /** 拉取券商实时持仓快照(多证券,指标直取券商口径) */ + BrokerPositionSnapshotVO fetchPositions(); + +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncService.java b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncService.java new file mode 100644 index 00000000..3f2755ec --- /dev/null +++ b/aquant-backend/src/main/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncService.java @@ -0,0 +1,156 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.common.exception.ExceptionEnum; +import com.brotherc.aquant.common.utils.UserContext; +import com.brotherc.aquant.portfolio.entity.UserBrokerAccount; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioImportResultVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeBatchReqVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import com.brotherc.aquant.portfolio.repository.UserBrokerAccountRepository; +import com.brotherc.aquant.portfolio.service.UserPortfolioService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 券商账户持仓/成交的自动同步入口:按 {@code UserBrokerAccount.syncMode} + * 把账户路由到对应的数据渠道(多数据源切换)。 + * + *
    + *
  • MANUAL —— 手动导入交割单文件,不走本服务
  • + *
  • EASYTRADER —— easytrader 客户端自动化(Windows 常驻)
  • + *
  • EM_WEB —— 东方财富证券网页交易会话(Cookie + validatekey)
  • + *
+ * + *

每次同步按渠道拉取全量「当日成交」(多证券),经 saveTrades 的 + * dedupKey 幂等去重后落库,重复触发安全。

+ */ +@Slf4j +@Service +@RequiredArgsConstructor +public class PortfolioBrokerSyncService { + + private final UserBrokerAccountRepository accountRepository; + private final UserPortfolioService portfolioService; + private final List providers; + + /** 按账户同步方式拉取最近成交并入库 */ + public PortfolioImportResultVO syncTrades(Long accountId) { + return syncTrades(accountId, UserContext.requireCurrentUserId()); + } + + PortfolioImportResultVO syncTrades(Long accountId, Long userId) { + UserBrokerAccount account = validateAccount(accountId, userId); + return syncAccount(account); + } + + /** + * 查询券商持仓快照:读最近一次成功同步的持久化数据(Cookie 失效后仍可展示), + * 实时刷新走 {@link #refreshPositions(Long)}。 + */ + public BrokerPositionSnapshotVO positions(Long accountId) { + return positions(accountId, UserContext.requireCurrentUserId()); + } + + BrokerPositionSnapshotVO positions(Long accountId, Long userId) { + UserBrokerAccount account = validateAccount(accountId, userId); + return portfolioService.getBrokerSnapshot(account.getId()); + } + + /** 实时刷新券商持仓快照(需交易会话有效),成功后持久化并返回 */ + public BrokerPositionSnapshotVO refreshPositions(Long accountId) { + Long userId = UserContext.requireCurrentUserId(); + UserBrokerAccount account = validateAccount(accountId, userId); + PortfolioBrokerSyncProvider provider = route(account.getSyncMode()); + BrokerPositionSnapshotVO snapshot = provider.fetchPositions(); + portfolioService.replacePositionsFromBroker(account.getId(), userId, snapshot); + portfolioService.saveBrokerSnapshot(account.getId(), snapshot); + return snapshot; + } + + /** + * 交易 Cookie 更新后自动触发:同步当前用户所有 EM_WEB 渠道账户的最近成交 + * (成交入库后由 saveTrades 联动重建持仓与收益快照)。逐账户独立容错, + * 单个渠道失败不影响其他账户。异步执行,Cookie 保存接口立即返回。 + */ + @Async + public void triggerSynchronizeAfterCookieUpdate(Long userId, String username) { + List accounts = accountRepository.findAllByUserIdAndDeletedFalse(userId).stream() + .filter(account -> "EM_WEB".equalsIgnoreCase(account.getSyncMode())) + .toList(); + if (accounts.isEmpty()) { + log.info("交易 Cookie 已更新,但当前用户没有 EM_WEB 渠道的券商账户,跳过自动同步"); + return; + } + // @Async 线程没有 HTTP 请求上下文(UserContext 为 ThreadLocal), + // saveTrades 内部的 requireCurrentUserId 需要它,必须显式重建;结束后清理防泄漏 + UserContext.set(userId, username); + try { + for (UserBrokerAccount account : accounts) { + try { + PortfolioImportResultVO result = syncAccount(account); + log.info("交易 Cookie 更新后自动同步完成: accountId={}, 总数={}, 成功={}, 跳过={}", + account.getId(), result.getTotalCount(), result.getSuccessCount(), result.getSkipCount()); + } catch (RuntimeException exception) { + log.warn("交易 Cookie 更新后自动同步失败(不影响其他账户): accountId={}, 原因={}", + account.getId(), exception.getMessage()); + } + } + } finally { + UserContext.clear(); + } + } + + /** 单账户同步核心:按 syncMode 路由渠道,拉取成交与持仓快照落库 */ + private PortfolioImportResultVO syncAccount(UserBrokerAccount account) { + PortfolioBrokerSyncProvider provider = route(account.getSyncMode()); + List trades = provider.fetchTrades(); + if (trades.isEmpty()) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + provider.channel() + " 渠道未返回任何成交(当日无交易或客户端/会话未就绪)"); + } + PortfolioTradeBatchReqVO request = new PortfolioTradeBatchReqVO(); + request.setAccountId(account.getId()); + request.setSource(provider.channel()); + request.setTrades(trades); + PortfolioImportResultVO result = portfolioService.saveTrades(request); + // 券商渠道持仓以接口快照为准(成交流水只有增量,反推会把历史持仓算丢); + // 快照失败不影响成交入库,持仓维持原值,下次同步重试 + try { + BrokerPositionSnapshotVO snapshot = provider.fetchPositions(); + portfolioService.replacePositionsFromBroker(account.getId(), account.getUserId(), snapshot); + } catch (RuntimeException exception) { + log.warn("券商持仓快照同步失败(成交已入库):accountId={}, 原因={}", + account.getId(), exception.getMessage()); + } + return result; + } + + private PortfolioBrokerSyncProvider route(String syncMode) { + String mode = StringUtils.defaultIfBlank(syncMode, "MANUAL").toUpperCase(); + if ("MANUAL".equals(mode)) { + throw new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "该账户为手动导入模式(MANUAL),请使用交割单文件导入"); + } + return providers.stream() + .filter(provider -> provider.channel().equalsIgnoreCase(mode)) + .findFirst() + .orElseThrow(() -> new BusinessException(ExceptionEnum.SYS_CHECK_ERROR, + "暂不支持该账户同步方式:" + mode + "(可用:" + providers.stream() + .map(PortfolioBrokerSyncProvider::channel).toList() + ")")); + } + + private UserBrokerAccount validateAccount(Long accountId, Long userId) { + if (accountId == null) { + throw ExceptionEnum.PORTFOLIO_ACCOUNT_NOT_FOUND.toException(); + } + return accountRepository.findByIdAndUserIdAndDeletedFalse(accountId, userId) + .orElseThrow(ExceptionEnum.PORTFOLIO_ACCOUNT_NOT_FOUND::toException); + } +} diff --git a/aquant-backend/src/main/java/com/brotherc/aquant/sync/entity/StockSync.java b/aquant-backend/src/main/java/com/brotherc/aquant/sync/entity/StockSync.java index da2168bc..42995842 100644 --- a/aquant-backend/src/main/java/com/brotherc/aquant/sync/entity/StockSync.java +++ b/aquant-backend/src/main/java/com/brotherc/aquant/sync/entity/StockSync.java @@ -21,8 +21,9 @@ public class StockSync { private String name; /** - * 值 + * 值(交易会话 JSON 等凭证内容长度超过 255,使用 TEXT) */ + @Column(name = "value", columnDefinition = "text") private String value; } diff --git a/aquant-backend/src/main/resources/application-demo.yaml b/aquant-backend/src/main/resources/application-demo.yaml index 99cc288e..9c3b0989 100644 --- a/aquant-backend/src/main/resources/application-demo.yaml +++ b/aquant-backend/src/main/resources/application-demo.yaml @@ -109,6 +109,18 @@ aquant: # push2 实时主机对程序化客户端做间歇性主机级软封(时段性 502,浏览器正常,akshare#7230), # push2delay 为 akshare 官方采用的延迟行情主机,数据滞后约 1-2 分钟,收盘后同步无影响 quote-base-urls: ${EASTMONEY_QUOTE_BASE_URLS:https://push2delay.eastmoney.com,https://push2.eastmoney.com} + portfolio: + # 券商持仓自动同步(多数据源切换,账户的 syncMode 决定走哪个渠道:EASYTRADER / EM_WEB) + # 渠道一:easytrader 客户端自动化服务地址(Windows 常驻,见 https://github.com/shidenggui/easytrader),留空停用 + easytrader-base-url: ${EASYTRADER_BASE_URL:} + # 渠道二:东方财富证券网页交易(jywg.eastmoneysec.com,原 jywg.18.cn)。浏览器登录后从 DevTools + # 复制会话 Cookie 与 validatekey(任意查询请求 URL 参数或页面 #em_validatekey 的 value)粘贴到这里, + # 会话失效后重新复制;仅做持仓/成交只读查询,不含下单。 + # 注意:这是 jywg 交易会话的 Cookie,与上面行情中心的东财 Cookie(aquant.eastmoney.cookie, + # 作用于 push2 行情接口)是两个完全独立的 Cookie,互不通用、需分别维护 + jywg-base-url: ${JYWG_BASE_URL:https://jywg.eastmoneysec.com} + jywg-cookie: ${JYWG_COOKIE:} + jywg-validate-key: ${JYWG_VALIDATE_KEY:} jwt: # JWT 签名密钥(演示默认值,生产环境务必替换) secret: AQuant@2025!SecretKey#Jwt diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClientTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClientTest.java new file mode 100644 index 00000000..18985695 --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/integration/eastmoney/service/EastmoneyJywgClientTest.java @@ -0,0 +1,173 @@ +package com.brotherc.aquant.integration.eastmoney.service; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.sync.entity.StockSync; +import com.brotherc.aquant.sync.repository.StockSyncRepository; +import com.fasterxml.jackson.databind.ObjectMapper; +import okhttp3.OkHttpClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EastmoneyJywgClientTest { + + @Mock + private StockSyncRepository stockSyncRepository; + + private EastmoneyJywgClient client(String cookie, String validateKey) { + return new EastmoneyJywgClient(new OkHttpClient(), new ObjectMapper(), + "https://jywg.eastmoneysec.com", cookie, validateKey, stockSyncRepository); + } + + @Test + void startsUnconfiguredWithoutCookie() { + EastmoneyJywgClient client = client("", ""); + assertThat(client.isConfigured()).isFalse(); + assertThat(client.sessionStatus()) + .containsEntry("configured", false) + .containsEntry("expired", false); + } + + @Test + void configuredFromPropertiesIsUsableWithoutCountdown() { + // 不可达地址:验证未计时的配置态会话会直接发起查询(过期由上游接口报错兜底) + EastmoneyJywgClient client = new EastmoneyJywgClient(new OkHttpClient(), new ObjectMapper(), + "https://127.0.0.1:1", "SESSION=abc", "vk123", stockSyncRepository); + + assertThat(client.isConfigured()).isTrue(); + Map status = client.sessionStatus(); + assertThat(status) + .containsEntry("configured", true) + .containsEntry("expired", false) + .containsEntry("remainingSeconds", 0L) + .containsEntry("expireAt", null); + assertThatThrownBy(() -> client.todayMatches()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("不可达"); + } + + @Test + void hotUpdatedSessionCountsDownPersistsUpdateTimeAndExpires() { + EastmoneyJywgClient client = client("", ""); + long before = System.currentTimeMillis(); + client.updateSession("SESSION=abc", "vk123", 15); + + assertThat(client.isConfigured()).isTrue(); + Map status = client.sessionStatus(); + assertThat(status) + .containsEntry("configured", true) + .containsEntry("expired", false) + .containsEntry("durationMinutes", 15); + // 剩余秒数约 900(15 分钟) + assertThat(((Number) status.get("remainingSeconds")).intValue()).isBetween(895, 900); + // 记录更新时间(前端展示 + 重启恢复倒计时的依据) + assertThat((CharSequence) status.get("updateTime")).isNotNull(); + + // 更新时间与凭证持久化到 stock_sync,重启后可恢复倒计时 + ArgumentCaptor captor = ArgumentCaptor.forClass(StockSync.class); + verify(stockSyncRepository).save(captor.capture()); + StockSync stored = captor.getValue(); + assertThat(stored.getName()).isEqualTo(EastmoneyJywgClient.SESSION_STORAGE_KEY); + assertThat(stored.getValue()) + .contains("SESSION=abc").contains("vk123") + .contains("\"durationMinutes\":15"); + long persistedUpdateTime = com.jayway.jsonpath.JsonPath.parse(stored.getValue()) + .read("$.updateTime", Long.class); + assertThat(persistedUpdateTime).isBetween(before, System.currentTimeMillis()); + + // 负时长模拟已到期的会话:查询直接拒绝并提示重新获取(上游 Cookie 同步过期),不再发起 HTTP 请求 + client.updateSession("SESSION=abc", "vk123", -1); + assertThat(client.sessionStatus()).containsEntry("expired", true); + assertThat(client.isConfigured()).isTrue(); + assertThatThrownBy(() -> client.todayMatches()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("交易会话已过期"); + } + + @Test + void restoresPersistedSessionOnStartupWithContinuedCountdown() throws Exception { + long updateTime = System.currentTimeMillis() - 5 * 60_000L; // 5 分钟前更新 + StockSync stored = new StockSync(); + stored.setName(EastmoneyJywgClient.SESSION_STORAGE_KEY); + stored.setValue(new ObjectMapper().writeValueAsString(Map.of( + "cookie", "SESSION=abc", "validateKey", "vk123", + "durationMinutes", 30, "updateTime", updateTime))); + when(stockSyncRepository.findByName(EastmoneyJywgClient.SESSION_STORAGE_KEY)).thenReturn(stored); + + EastmoneyJywgClient client = client("", ""); + assertThat(client.isConfigured()).isTrue(); + Map status = client.sessionStatus(); + // 30 分钟在线、已过 5 分钟 → 剩余约 25 分钟(倒计时按持久化的更新时间续算) + assertThat(status).containsEntry("configured", true).containsEntry("expired", false); + assertThat(((Number) status.get("remainingSeconds")).intValue()).isBetween(1490, 1510); + assertThat((CharSequence) status.get("updateTime")).isNotNull(); + } + + @Test + void restoredPersistedSessionAlreadyExpiredIsRejected() throws Exception { + long updateTime = System.currentTimeMillis() - 31 * 60_000L; // 31 分钟前更新,30 分钟时长已到期 + StockSync stored = new StockSync(); + stored.setName(EastmoneyJywgClient.SESSION_STORAGE_KEY); + stored.setValue(new ObjectMapper().writeValueAsString(Map.of( + "cookie", "SESSION=abc", "validateKey", "vk123", + "durationMinutes", 30, "updateTime", updateTime))); + when(stockSyncRepository.findByName(EastmoneyJywgClient.SESSION_STORAGE_KEY)).thenReturn(stored); + + EastmoneyJywgClient client = client("", ""); + assertThat(client.sessionStatus()).containsEntry("expired", true); + assertThatThrownBy(() -> client.todayMatches()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("交易会话已过期"); + } + + @Test + void rejectsBlankSessionValues() { + EastmoneyJywgClient client = client("", ""); + // 在线时长取值范围由控制器校验;客户端只校验凭证非空 + assertThatThrownBy(() -> client.updateSession(" ", "vk", 15)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("不能为空"); + assertThatThrownBy(() -> client.updateSession("c", " ", 30)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("不能为空"); + assertThat(client.isConfigured()).isFalse(); + } + + @Test + void loginPageHtmlResponseIsReportedAsSessionExpired() throws Exception { + // 会话失效时 jywg 返回 200 + 登录页 HTML:必须明确报"会话失效",而不是当成解析错误 + com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create( + new java.net.InetSocketAddress(0), 0); + server.createContext("/Com/queryAssetAndPositionV1", exchange -> { + byte[] page = ("在线交易 东方财富在线交易,安全,便捷!" + + "login page").getBytes(java.nio.charset.StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8"); + exchange.sendResponseHeaders(200, page.length); + exchange.getResponseBody().write(page); + exchange.close(); + }); + server.start(); + try { + EastmoneyJywgClient client = new EastmoneyJywgClient(new OkHttpClient(), new ObjectMapper(), + "http://127.0.0.1:" + server.getAddress().getPort(), "SESSION=abc", "vk123", stockSyncRepository); + client.updateSession("SESSION=abc", "vk123", 180); + + assertThatThrownBy(() -> client.assetAndPosition()) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("交易会话已失效") + .hasMessageContaining("重新登录"); + } finally { + server.stop(0); + } + } +} diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapterTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapterTest.java new file mode 100644 index 00000000..6fb1b22e --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/importer/EastmoneyTradeFileAdapterTest.java @@ -0,0 +1,126 @@ +package com.brotherc.aquant.portfolio.service.importer; + +import com.brotherc.aquant.portfolio.model.dto.PortfolioTradeFileParseResult; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.Charset; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class EastmoneyTradeFileAdapterTest { + + private final EastmoneyTradeFileAdapter adapter = new EastmoneyTradeFileAdapter(); + + private static final List HEADERS = List.of( + "交割日期", "业务名称", "证券代码", "证券名称", "成交价格", "成交数量", "成交金额", "发生金额", + "手续费", "印花税", "过户费", "资金余额", "币种", "合同编号", "备注"); + + @Test + void supportsOnlyEastmoneyStatements() throws Exception { + assertThat(adapter.supports("EM", "交割单.xlsx", xlsx())).isTrue(); + // 兼容前端券商选择器的 EASTMONEY 写法 + assertThat(adapter.supports("EASTMONEY", "交割单.xlsx", xlsx())).isTrue(); + assertThat(adapter.supports("CMS", "交割单.xlsx", xlsx())).isFalse(); + assertThat(adapter.supports("EM", "other.xlsx", new byte[]{1, 2, 3})).isFalse(); + } + + @Test + void parsesMultiSecurityStatementWithBusinessTypes() throws Exception { + PortfolioTradeFileParseResult result = adapter.parse("交割单.xlsx", xlsx()); + + assertThat(result.getTotalCount()).isEqualTo(5); + assertThat(result.getErrors()).hasSize(1); + assertThat(result.getErrors().get(0).getRowNumber()).isEqualTo(6); + + List trades = result.getTrades(); + assertThat(trades).hasSize(4); + + PortfolioTradeSaveReqVO buy = trades.get(0); + assertThat(buy.getTradeType()).isEqualTo("BUY"); + assertThat(buy.getAssetType()).isEqualTo("STOCK"); + assertThat(buy.getMarket()).isEqualTo("SH"); + assertThat(buy.getAssetCode()).isEqualTo("600519"); + assertThat(buy.getQuantity()).isEqualByComparingTo("100"); + assertThat(buy.getGrossAmount()).isEqualByComparingTo("150000"); + // 买入发生金额为负数(现金扣减),原值保留 + assertThat(buy.getNetAmount()).isEqualByComparingTo("-150030"); + assertThat(buy.getCommission()).isEqualByComparingTo("150"); + assertThat(buy.getSourceTradeId()).isEqualTo("HT001"); + + PortfolioTradeSaveReqVO sell = trades.get(1); + assertThat(sell.getTradeType()).isEqualTo("SELL"); + assertThat(sell.getAssetType()).isEqualTo("ETF"); + // 510300 沪深300ETF 为沪市品种(51 开头) + assertThat(sell.getMarket()).isEqualTo("SH"); + assertThat(sell.getNetAmount()).isEqualByComparingTo("3990"); + assertThat(sell.getRemark()).contains("部分止盈"); + + PortfolioTradeSaveReqVO deposit = trades.get(2); + assertThat(deposit.getTradeType()).isEqualTo("CASH_DEPOSIT"); + assertThat(deposit.getAssetType()).isEqualTo("CASH"); + assertThat(deposit.getGrossAmount()).isEqualByComparingTo("10000"); + + PortfolioTradeSaveReqVO dividend = trades.get(3); + assertThat(dividend.getTradeType()).isEqualTo("DIVIDEND_CASH"); + assertThat(dividend.getAssetCode()).isEqualTo("601398"); + + // 最新交割日期行的资金余额 + assertThat(result.getLatestCashBalance()).isEqualByComparingTo("64490"); + assertThat(result.getCashBalanceCurrency()).isEqualTo("CNY"); + assertThat(result.getCashBalanceDate().toString()).isEqualTo("2026-09-16"); + } + + @Test + void parsesGb18030CsvStatement() { + String csv = String.join("\n", + "交割日期,业务名称,证券代码,证券名称,成交价格,成交数量,成交金额,发生金额,手续费,资金余额,币种,合同编号", + "2026-09-16,证券买入,600036,招商银行,35.00,200,7000.00,-7010.00,10.00,92990.00,人民币,HT101", + "2026-09-16,证券卖出,159915,创业板ETF,2.50,5000,12500.00,12490.00,10.00,105480.00,人民币,HT102"); + byte[] content = csv.getBytes(Charset.forName("GB18030")); + + assertThat(adapter.supports("EM", "对账单.csv", content)).isTrue(); + PortfolioTradeFileParseResult result = adapter.parse("对账单.csv", content); + + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getTrades()).hasSize(2); + assertThat(result.getTrades().get(0).getMarket()).isEqualTo("SH"); + assertThat(result.getTrades().get(1).getAssetType()).isEqualTo("ETF"); + assertThat(result.getLatestCashBalance()).isEqualByComparingTo("105480"); + } + + private byte[] xlsx() throws Exception { + try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream output = new ByteArrayOutputStream()) { + Sheet sheet = workbook.createSheet("交割单"); + Row header = sheet.createRow(0); + for (int i = 0; i < HEADERS.size(); i++) { + header.createCell(i).setCellValue(HEADERS.get(i)); + } + writeRow(sheet, 1, "2026-09-16", "证券买入", "600519", "贵州茅台", "1500.00", "100", "150000.00", + "-150030.00", "150.00", "1500.00", "30.00", "50000.00", "人民币", "HT001", ""); + writeRow(sheet, 2, "2026-09-16", "证券卖出", "510300", "沪深300ETF", "4.00", "1000", "4000.00", + "3990.00", "5.00", "4.00", "1.00", "53990.00", "人民币", "HT002", "部分止盈"); + writeRow(sheet, 3, "2026-09-16", "银行转存", "", "", "", "", "", "10000.00", "", "", "", + "63990.00", "人民币", "HT003", "银证转入"); + writeRow(sheet, 4, "2026-09-16", "股息入账", "601398", "工商银行", "", "", "", "500.00", "", "", "", + "64490.00", "人民币", "HT004", "现金分红"); + writeRow(sheet, 5, "2026-09-16", "测试业务", "600000", "浦发银行", "1.00", "100", "100.00", + "-101.00", "1.00", "", "", "64490.00", "人民币", "HT005", ""); + workbook.write(output); + return output.toByteArray(); + } + } + + private void writeRow(Sheet sheet, int rowIndex, Object... values) { + Row row = sheet.createRow(rowIndex); + for (int i = 0; i < values.length; i++) { + row.createCell(i).setCellValue(String.valueOf(values[i])); + } + } +} diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProviderTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProviderTest.java new file mode 100644 index 00000000..45dfc4e1 --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EastmoneyWebTradeSyncProviderTest.java @@ -0,0 +1,159 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.integration.eastmoney.service.EastmoneyJywgClient; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EastmoneyWebTradeSyncProviderTest { + + @Mock + private EastmoneyJywgClient jywgClient; + + @InjectMocks + private EastmoneyWebTradeSyncProvider provider; + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + void mapsRealJywgMatchRowWithFeesAndSignedAmount() throws Exception { + // 2026-09-17 实际抓包行(queryTodayMatchWEB/queryHisMatchMergeWEB 小写体系) + String json = """ + [ + {"bizdate":"20260916","bsflag":"0B","bsflag_ex":"证券买入","cleardate":"20260916", + "fee_ghf":"0.45","fee_jsxf":"8.94","fee_sxf":"11.41","fee_yhs":"0.00", + "fundbal":"355.59","fundeffect":"-45644.86","market":"HA","market_ex":"沪市A股", + "matchamt":"45633.00","matchcode":"48222364","matchprice":"3.7100", + "matchqty":"12300","matchtime":"134357","orderid":"0701201748", + "stkbal":"135200","stkcode":"600255","stkname":"鑫科材料","stktype":"0"} + ] + """; + when(jywgClient.todayMatches()).thenReturn(objectMapper.readTree(json)); + when(jywgClient.historyMatches(any(), any())).thenReturn(objectMapper.readTree("[]")); + + assertThat(provider.channel()).isEqualTo("EM_WEB"); + List trades = provider.fetchTrades(); + + assertThat(trades).hasSize(1); + PortfolioTradeSaveReqVO buy = trades.get(0); + assertThat(buy.getTradeType()).isEqualTo("BUY"); + assertThat(buy.getAssetType()).isEqualTo("STOCK"); + assertThat(buy.getMarket()).isEqualTo("SH"); + assertThat(buy.getAssetCode()).isEqualTo("600255"); + assertThat(buy.getAssetName()).isEqualTo("鑫科材料"); + // 日期 bizdate + 时分秒 matchtime 组合 + assertThat(buy.getTradeTime().toString()).isEqualTo("2026-09-16T13:43:57"); + assertThat(buy.getQuantity()).isEqualByComparingTo("12300"); + assertThat(buy.getPrice()).isEqualByComparingTo("3.7100"); + assertThat(buy.getGrossAmount()).isEqualByComparingTo("45633.00"); + // 真实费用明细直接采用,不再推算 + assertThat(buy.getCommission()).isEqualByComparingTo("11.41"); + assertThat(buy.getStampDuty()).isEqualByComparingTo("0.00"); + assertThat(buy.getTransferFee()).isEqualByComparingTo("0.45"); + assertThat(buy.getOtherFee()).isEqualByComparingTo("8.94"); + // fundeffect 签名资金净额(含费)直接采用 + assertThat(buy.getNetAmount()).isEqualByComparingTo("-45644.86"); + assertThat(buy.getSourceTradeId()).isEqualTo("48222364"); + } + + @Test + void mergesTodayAndHistoryRowsWithDeduplication() throws Exception { + // 同一笔成交在当日与历史接口都出现,按成交编号去重为一条 + String sellRow = """ + {"bizdate":"20260917","bsflag":"0S","bsflag_ex":"证券卖出","matchamt":"1000.00", + "matchcode":"9001","matchprice":"10.00","matchqty":"100","matchtime":"093100", + "stkcode":"600036","stkname":"招商银行"} + """; + String buyRow = """ + {"bizdate":"20260916","bsflag":"0B","bsflag_ex":"证券买入","matchamt":"900.00", + "matchcode":"9002","matchprice":"9.00","matchqty":"100","matchtime":"100000", + "stkcode":"600036","stkname":"招商银行"} + """; + when(jywgClient.todayMatches()).thenReturn(objectMapper.readTree("[" + sellRow + "]")); + when(jywgClient.historyMatches(any(), any())) + .thenReturn(objectMapper.readTree("[" + sellRow + "," + buyRow + "]")); + + List trades = provider.fetchTrades(); + + assertThat(trades).hasSize(2); + assertThat(trades.stream().map(PortfolioTradeSaveReqVO::getSourceTradeId)) + .containsExactlyInAnyOrder("9001", "9002"); + assertThat(trades.get(0).getTradeType()).isEqualTo("SELL"); + } + + @Test + void mapsAssetAndPositionSnapshotFromRealFields() throws Exception { + // 2026-09-18 queryAssetAndPositionV1 实际抓包:持仓层为拼音缩写体系, + // Ykbl/Drykbl 为小数比例(×100=百分比口径),行级 Dryk 盘后可能为空 + String json = """ + [{"Zzc":"491950.03","RMBZzc":"491950.03","Zxsz":"491815.00","totalSecMkval":"491815.00", + "Kyzj":"135.03","Kqzj":"135.03","Zjye":"135.03","Ljyk":"5320.24","Dryk":"","bonds":[], + "positions":[ + {"Bz":"RMB","Cbjg":"54.484","Cbjgex":"51.633","Ckcb":"256074.42","Ckcbj":"54.484", + "Ckyk":"-14494.42","Dryk":"","Drykbl":"","Gddm":"0340835149","Ksssl":"4700", + "Kysl":"4700","Ljyk":"-14494.42","Market":"SA","Ykbl":"-0.056604", + "Zqdm":"300677","Zqmc":"英科医疗","Zqsl":"4700","Zxjg":"51.400","Zxsz":"241580.00"}, + {"Bz":"RMB","Cbjg":"-16.003","Cbjgex":"3.584","Ckcb":"-19204.05","Ckcbj":"-16.003", + "Ckyk":"23524.05","Dryk":"","Drykbl":"","Kysl":"1200","Ljyk":"23524.05","Ykbl":"0.000000", + "Zqdm":"600255","Zqmc":"鑫科材料","Zqsl":"1200","Zxjg":"3.600","Zxsz":"4320.00"}]}] + """; + when(jywgClient.assetAndPosition()).thenReturn(objectMapper.readTree(json)); + + BrokerPositionSnapshotVO snapshot = provider.fetchPositions(); + + assertThat(snapshot.getChannel()).isEqualTo("EM_WEB"); + assertThat(snapshot.getTotalAsset()).isEqualByComparingTo("491950.03"); + assertThat(snapshot.getSecurityMarketValue()).isEqualByComparingTo("491815.00"); + assertThat(snapshot.getEnableBalance()).isEqualByComparingTo("135.03"); + assertThat(snapshot.getFetchBalance()).isEqualByComparingTo("135.03"); + assertThat(snapshot.getMoneyBalance()).isEqualByComparingTo("135.03"); + assertThat(snapshot.getPositionIncome()).isEqualByComparingTo("5320.24"); + // 顶层当日盈亏为空字符串 → 解析为 null + assertThat(snapshot.getDayIncome()).isNull(); + assertThat(snapshot.getPositions()).hasSize(2); + + var first = snapshot.getPositions().get(0); + assertThat(first.getSecurityCode()).isEqualTo("300677"); + assertThat(first.getSecurityName()).isEqualTo("英科医疗"); + assertThat(first.getHoldingQuantity()).isEqualByComparingTo("4700"); + assertThat(first.getEnableQuantity()).isEqualByComparingTo("4700"); + assertThat(first.getCostPrice()).isEqualByComparingTo("54.484"); + assertThat(first.getLastPrice()).isEqualByComparingTo("51.400"); + assertThat(first.getMarketValue()).isEqualByComparingTo("241580.00"); + assertThat(first.getIncome()).isEqualByComparingTo("-14494.42"); + // Ykbl 小数比例放大 100 倍 = 官网百分比口径 + assertThat(first.getIncomeRate()).isEqualByComparingTo("-5.6604"); + assertThat(first.getDayIncome()).isNull(); + assertThat(first.getDayIncomeRate()).isNull(); + + var second = snapshot.getPositions().get(1); + assertThat(second.getCostPrice()).isEqualByComparingTo("-16.003"); + assertThat(second.getIncome()).isEqualByComparingTo("23524.05"); + assertThat(second.getIncomeRate()).isEqualByComparingTo("0"); + } + + @Test + void rejectsUnknownTradeDirection() throws Exception { + when(jywgClient.todayMatches()) + .thenReturn(objectMapper.readTree("[{\"stkcode\":\"600036\",\"bsflag_ex\":\"未知操作\"}]")); + when(jywgClient.historyMatches(any(), any())).thenReturn(objectMapper.readTree("[]")); + + assertThatThrownBy(() -> provider.fetchTrades()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("暂不支持东财网页成交方向"); + } +} diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProviderTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProviderTest.java new file mode 100644 index 00000000..68ee7714 --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/EasytraderTradeSyncProviderTest.java @@ -0,0 +1,89 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.integration.easytrader.EasytraderClient; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class EasytraderTradeSyncProviderTest { + + @Mock + private EasytraderClient easytraderClient; + + @InjectMocks + private EasytraderTradeSyncProvider provider; + + @Test + void mapsTodayTradesOfMultipleSecurities() { + when(easytraderClient.todayTrades()).thenReturn(List.of( + Map.of("成交日期", "2026-09-16", "成交时间", "14:57:03", "证券代码", "600519", + "证券名称", "贵州茅台", "操作", "证券买入", "成交价格", "1500.00", + "成交数量", "100", "成交金额", "150000.00", "合同编号", "HT001"), + Map.of("成交日期", "2026-09-16", "成交时间", "10:00:00", "证券代码", "510300", + "证券名称", "沪深300ETF", "操作", "证券卖出", "成交价格", "4.00", + "成交数量", "1000", "成交金额", "4000.00", "合同编号", "HT002"))); + + assertThat(provider.channel()).isEqualTo("EASYTRADER"); + List trades = provider.fetchTrades(); + + assertThat(trades).hasSize(2); + PortfolioTradeSaveReqVO buy = trades.get(0); + assertThat(buy.getTradeType()).isEqualTo("BUY"); + assertThat(buy.getMarket()).isEqualTo("SH"); + assertThat(buy.getQuantity()).isEqualByComparingTo("100"); + assertThat(buy.getGrossAmount()).isEqualByComparingTo("150000"); + // 买入扣减现金 + assertThat(buy.getNetAmount()).isEqualByComparingTo("-150000"); + assertThat(buy.getTradeTime().toString()).isEqualTo("2026-09-16T14:57:03"); + assertThat(buy.getSourceTradeId()).isEqualTo("HT001"); + + PortfolioTradeSaveReqVO sell = trades.get(1); + assertThat(sell.getTradeType()).isEqualTo("SELL"); + assertThat(sell.getAssetType()).isEqualTo("ETF"); + // 510300 沪深300ETF 为沪市品种(51 开头) + assertThat(sell.getMarket()).isEqualTo("SH"); + assertThat(sell.getNetAmount()).isEqualByComparingTo("4000"); + } + + @Test + void rejectsUnknownTradeDirection() { + when(easytraderClient.todayTrades()).thenReturn(List.of( + Map.of("证券代码", "600519", "操作", "未知操作"))); + + assertThatThrownBy(() -> provider.fetchTrades()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("暂不支持 easytrader 成交方向"); + } + + @Test + void mapsClientGridRowsToSnapshot() { + when(easytraderClient.position()).thenReturn(List.of( + Map.of("证券代码", "600519", "证券名称", "贵州茅台", "股票余额", "100", + "可用余额", "100", "成本价", "1500.00", "市值", "150000.00"))); + + BrokerPositionSnapshotVO snapshot = provider.fetchPositions(); + + assertThat(snapshot.getChannel()).isEqualTo("EASYTRADER"); + assertThat(snapshot.getPositions()).hasSize(1); + var item = snapshot.getPositions().get(0); + assertThat(item.getSecurityCode()).isEqualTo("600519"); + assertThat(item.getHoldingQuantity()).isEqualByComparingTo("100"); + assertThat(item.getCostPrice()).isEqualByComparingTo("1500.00"); + assertThat(item.getMarketValue()).isEqualByComparingTo("150000.00"); + // 客户端网格不含盈亏指标,留空 + assertThat(item.getIncome()).isNull(); + } + +} diff --git a/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncServiceTest.java b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncServiceTest.java new file mode 100644 index 00000000..f2c0a63f --- /dev/null +++ b/aquant-backend/src/test/java/com/brotherc/aquant/portfolio/service/sync/PortfolioBrokerSyncServiceTest.java @@ -0,0 +1,181 @@ +package com.brotherc.aquant.portfolio.service.sync; + +import com.brotherc.aquant.common.exception.BusinessException; +import com.brotherc.aquant.portfolio.entity.UserBrokerAccount; +import com.brotherc.aquant.portfolio.model.vo.BrokerPositionSnapshotVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioImportResultVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeBatchReqVO; +import com.brotherc.aquant.portfolio.model.vo.PortfolioTradeSaveReqVO; +import com.brotherc.aquant.portfolio.repository.UserBrokerAccountRepository; +import com.brotherc.aquant.portfolio.service.UserPortfolioService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@org.mockito.junit.jupiter.MockitoSettings(strictness = org.mockito.quality.Strictness.LENIENT) +class PortfolioBrokerSyncServiceTest { + + @Mock + private UserBrokerAccountRepository accountRepository; + + @Mock + private UserPortfolioService portfolioService; + + @Mock + private PortfolioBrokerSyncProvider easytraderProvider; + + @Mock + private PortfolioBrokerSyncProvider emWebProvider; + + private PortfolioBrokerSyncService service() { + when(easytraderProvider.channel()).thenReturn("EASYTRADER"); + when(emWebProvider.channel()).thenReturn("EM_WEB"); + return new PortfolioBrokerSyncService(accountRepository, portfolioService, + List.of(easytraderProvider, emWebProvider)); + } + + private UserBrokerAccount account(String syncMode) { + UserBrokerAccount account = new UserBrokerAccount(); + account.setId(1L); + account.setUserId(9L); + account.setSyncMode(syncMode); + return account; + } + + @Test + void routesToEasytraderProviderByAccountSyncMode() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("EASYTRADER"))); + when(easytraderProvider.fetchTrades()).thenReturn(List.of(new PortfolioTradeSaveReqVO())); + + service().syncTrades(1L, 9L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(PortfolioTradeBatchReqVO.class); + verify(portfolioService).saveTrades(captor.capture()); + assertThat(captor.getValue().getSource()).isEqualTo("EASYTRADER"); + assertThat(captor.getValue().getAccountId()).isEqualTo(1L); + assertThat(captor.getValue().getTrades()).hasSize(1); + } + + @Test + void routesToEastmoneyWebProviderByAccountSyncMode() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("EM_WEB"))); + when(emWebProvider.fetchTrades()).thenReturn(List.of(new PortfolioTradeSaveReqVO())); + + service().syncTrades(1L, 9L); + + verify(portfolioService).saveTrades(any(PortfolioTradeBatchReqVO.class)); + verify(emWebProvider).fetchTrades(); + } + + @Test + void rejectsManualAccountsWithFileImportHint() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("MANUAL"))); + + assertThatThrownBy(() -> service().syncTrades(1L, 9L)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("手动导入模式"); + } + + @Test + void rejectsUnknownSyncMode() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("UNKNOWN"))); + + assertThatThrownBy(() -> service().syncTrades(1L, 9L)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("暂不支持该账户同步方式"); + } + + @Test + void rejectsEmptyTradesFromChannel() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("EASYTRADER"))); + when(easytraderProvider.fetchTrades()).thenReturn(List.of()); + + assertThatThrownBy(() -> service().syncTrades(1L, 9L)) + .isInstanceOf(BusinessException.class) + .hasMessageContaining("未返回任何成交"); + } + + @Test + void positionsRouteByAccountSyncMode() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("EM_WEB"))); + BrokerPositionSnapshotVO snapshot = new BrokerPositionSnapshotVO(); + snapshot.setChannel("EM_WEB"); + when(emWebProvider.fetchPositions()).thenReturn(snapshot); + when(portfolioService.getBrokerSnapshot(1L)).thenReturn(snapshot); + + assertThat(service().positions(1L, 9L)).isSameAs(snapshot); + } + + @Test + void saveTradesResultIsReturnedToCaller() { + when(accountRepository.findByIdAndUserIdAndDeletedFalse(1L, 9L)) + .thenReturn(Optional.of(account("EASYTRADER"))); + when(easytraderProvider.fetchTrades()).thenReturn(List.of(new PortfolioTradeSaveReqVO())); + when(portfolioService.saveTrades(any(PortfolioTradeBatchReqVO.class))) + .thenReturn(new PortfolioImportResultVO(10L, 1, 1, 0)); + + assertThat(service().syncTrades(1L, 9L).getSuccessCount()).isEqualTo(1); + } + + @Test + void cookieUpdateTriggerSyncsOnlyEmWebAccounts() { + UserBrokerAccount emWeb = account("EM_WEB"); + UserBrokerAccount easytrader = account("EASYTRADER"); + UserBrokerAccount manual = account("MANUAL"); + when(accountRepository.findAllByUserIdAndDeletedFalse(9L)).thenReturn(List.of(emWeb, easytrader, manual)); + when(emWebProvider.fetchTrades()).thenReturn(List.of(new PortfolioTradeSaveReqVO())); + + service().triggerSynchronizeAfterCookieUpdate(9L, "uitest"); + + // 仅 EM_WEB 账户参与 Cookie 驱动的自动同步,EASYTRADER/MANUAL 不触发 + verify(emWebProvider).fetchTrades(); + verify(easytraderProvider, org.mockito.Mockito.never()).fetchTrades(); + // 成交入库 + 持仓快照落库(券商渠道持仓以接口为准) + verify(portfolioService).saveTrades(any(PortfolioTradeBatchReqVO.class)); + verify(portfolioService).replacePositionsFromBroker(eq(1L), eq(9L), any()); + } + + @Test + void cookieUpdateTriggerSurvivesSingleAccountFailure() { + UserBrokerAccount failing = account("EM_WEB"); + UserBrokerAccount healthy = account("EM_WEB"); + when(accountRepository.findAllByUserIdAndDeletedFalse(9L)).thenReturn(List.of(failing, healthy)); + when(emWebProvider.fetchTrades()) + .thenThrow(new RuntimeException("会话过期")) + .thenReturn(List.of(new PortfolioTradeSaveReqVO())); + + service().triggerSynchronizeAfterCookieUpdate(9L, "uitest"); + + // 第一个账户失败(会话过期等)不影响第二个账户继续同步 + verify(portfolioService, org.mockito.Mockito.times(1)).saveTrades(any(PortfolioTradeBatchReqVO.class)); + } + + @Test + void cookieUpdateTriggerSkipsWhenNoEmWebAccount() { + when(accountRepository.findAllByUserIdAndDeletedFalse(9L)).thenReturn(List.of(account("MANUAL"))); + + service().triggerSynchronizeAfterCookieUpdate(9L, "uitest"); + + org.mockito.Mockito.verifyNoInteractions(emWebProvider, portfolioService); + } +} diff --git a/aquant-frontend/src/api/eastmoney.ts b/aquant-frontend/src/api/eastmoney.ts index e4836ca5..e37bca27 100644 --- a/aquant-frontend/src/api/eastmoney.ts +++ b/aquant-frontend/src/api/eastmoney.ts @@ -14,3 +14,32 @@ export function getEastmoneyCookieStatus() { export function updateEastmoneyCookie(data: EastmoneyCookieUpdateReq) { return request.post('/eastmoney/cookie', data); } + +export interface JywgCookieUpdateReq { + /** 完整的 Cookie 请求头字符串(浏览器登录 jywg.eastmoneysec.com 后从 DevTools 复制) */ + cookie: string; + /** jywg 会话密钥(任意查询请求 URL 的 validatekey 参数,或页面 #em_validatekey 的 value) */ + validateKey: string; + /** 在线时长(分钟):15/30/180,到期后上游 Cookie 同步过期 */ + durationMinutes: number; +} + +export interface JywgCookieStatus { + configured: boolean; + expired: boolean; + remainingSeconds: number; + durationMinutes: number | null; + expireAt: string | null; + /** 本次会话凭证的更新时间(ISO 8601),重启/重开弹窗时倒计时按它续算 */ + updateTime: string | null; +} + +/** 查询东财交易会话状态(持仓模块多证券同步的凭证,与行情 Cookie 相互独立) */ +export function getJywgCookieStatus() { + return request.get('/portfolio/jywg/cookie'); +} + +/** 设置/热更新东财交易会话(选择在线时长),立即生效,无需重启后端 */ +export function updateJywgCookie(data: JywgCookieUpdateReq) { + return request.post('/portfolio/jywg/cookie', data); +} diff --git a/aquant-frontend/src/api/portfolio.ts b/aquant-frontend/src/api/portfolio.ts index d8ca3e31..6b2f670c 100644 --- a/aquant-frontend/src/api/portfolio.ts +++ b/aquant-frontend/src/api/portfolio.ts @@ -1,4 +1,5 @@ import request from '@/utils/request'; +import type { BrokerPositionSnapshot } from '@/types/portfolio'; import type { ResponseDTO } from './stock'; import type { UserPortfolio, @@ -154,6 +155,30 @@ export const reverseTrade = async ( }); }; +/** 按账户同步方式手动拉取最近成交并入库(EM_WEB/EASYTRADER 渠道),联动重建持仓与收益 */ +export const syncBrokerTrades = async (accountId: number): Promise => { + const res = await request.post>( + `/portfolio/account/${accountId}/sync/trades` + ); + return res.data?.data; +}; + +/** 查询最近一次同步的券商持仓快照(持久化数据,Cookie 失效后仍可展示) */ +export const getBrokerPositions = async (accountId: number): Promise => { + const res = await request.get>( + `/portfolio/account/${accountId}/sync/positions` + ); + return res.data?.data; +}; + +/** 实时刷新券商持仓快照(需交易会话有效),成功后覆盖持久化快照 */ +export const refreshBrokerPositions = async (accountId: number): Promise => { + const res = await request.post>( + `/portfolio/account/${accountId}/sync/positions/refresh` + ); + return res.data?.data; +}; + /** 下载 AQuant 标准交易流水 Excel 模板 */ export const downloadTradeImportTemplate = async (): Promise => { const res = await request.get('/portfolio/trade/import/template', { @@ -167,12 +192,13 @@ export const downloadTradeImportTemplate = async (): Promise => { export const importTradeFile = async ( accountId: number, file: File, - syncCashBalance = true + syncCashBalance = true, + brokerCode?: string ): Promise => { const formData = new FormData(); formData.append('file', file); const res = await request.post>('/portfolio/trade/import', formData, { - params: { accountId, syncCashBalance }, + params: { accountId, brokerCode, syncCashBalance }, headers: { 'Content-Type': 'multipart/form-data' } }); return res.data?.data; diff --git a/aquant-frontend/src/layout/BasicLayout.vue b/aquant-frontend/src/layout/BasicLayout.vue index be79aa1d..99cb41e7 100644 --- a/aquant-frontend/src/layout/BasicLayout.vue +++ b/aquant-frontend/src/layout/BasicLayout.vue @@ -73,6 +73,10 @@ 东财 Cookie + + + 交易 Cookie + @@ -155,6 +159,52 @@
+ + + + + + + 15 分钟 + 30 分钟 + 3 小时 + + + + + + + + + + + + diff --git a/aquant-frontend/src/views/portfolio/components/ImportUploadSection.vue b/aquant-frontend/src/views/portfolio/components/ImportUploadSection.vue index 05f0822b..0bb852c1 100644 --- a/aquant-frontend/src/views/portfolio/components/ImportUploadSection.vue +++ b/aquant-frontend/src/views/portfolio/components/ImportUploadSection.vue @@ -47,14 +47,10 @@ placeholder="请选择券商类型" style="width: 100%;" > - 招商证券 (支持原始流水) + 自动识别 (推荐) + 东方财富 (交割单) + 招商证券 (原始流水) 标准模板 (CSV / Excel) - 华泰证券 (涨乐财富通) - 中信证券 - 国泰君安 - 东方财富 - 同花顺导出流水 - 其他券商 (标准模板) @@ -139,11 +135,11 @@ const props = defineProps<{ }>(); const emit = defineEmits<{ - (e: 'fileSelected', file: File, accountId?: number): void; + (e: 'fileSelected', file: File, accountId?: number, brokerCode?: string): void; (e: 'downloadTemplate'): void; }>(); -const selectedBroker = ref('CMS'); +const selectedBroker = ref('AUTO'); const targetAccountId = ref(props.selectedAccountId); watch( @@ -167,6 +163,9 @@ const currentHintText = computed(() => { if (selectedBroker.value === 'CMS') { return '招商证券支持直接上传客户端导出的原始资金流水文件 (XLS/XLSX/CSV)。'; } + if (selectedBroker.value === 'EM') { + return '东方财富支持直接上传交割单 (对账单) 文件 (XLSX/CSV),自动识别多只证券的成交流水。'; + } return '当前券商暂推荐使用 AQuant 标准模板格式导入,请下载模板并按规范整理后上传。'; }); @@ -180,7 +179,7 @@ const handleFileChange = (e: Event) => { const target = e.target as HTMLInputElement; if (target.files && target.files.length > 0 && target.files[0]) { const file = target.files[0]; - emit('fileSelected', file, targetAccountId.value); + emit('fileSelected', file, targetAccountId.value, selectedBroker.value); target.value = ''; } }; diff --git a/aquant-frontend/src/views/portfolio/components/PositionTable.vue b/aquant-frontend/src/views/portfolio/components/PositionTable.vue index 4f46a8dd..3b8b7d92 100644 --- a/aquant-frontend/src/views/portfolio/components/PositionTable.vue +++ b/aquant-frontend/src/views/portfolio/components/PositionTable.vue @@ -27,7 +27,7 @@ :pagination="false" row-key="id" size="middle" - :scroll="{ x: 1000 }" + :scroll="{ x: 1300 }" class="clean-data-table" > + + + + + + + + +