Explorar el Código

评估:博微-电力设备抓取

Alex hace 1 semana
padre
commit
ea39916d69
Se han modificado 30 ficheros con 2183 adiciones y 25 borrados
  1. 65 0
      docs/sql/addsql/20261113.sql
  2. 67 0
      docs/sql/fullsql/20261113.sql
  3. 17 0
      jeeplus-api/jeeplus-system-api/src/main/java/com/jeeplus/flowable/factory/AssessApiFallbackFactory.java
  4. 17 0
      jeeplus-api/jeeplus-system-api/src/main/java/com/jeeplus/flowable/feign/IAssessApi.java
  5. 8 11
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/materialPrice/client/MaterialPriceScraperClient.java
  6. 193 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/PowerScraperClient.java
  7. 21 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/CompletedFileDTO.java
  8. 16 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/CompletedFilesResponseDTO.java
  9. 16 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedDataPushDTO.java
  10. 21 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedDataResponseDTO.java
  11. 32 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedPeriodDTO.java
  12. 59 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/controller/PowerPriceController.java
  13. 74 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/controller/PowerPriceFeignController.java
  14. 76 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/domain/MaterialBoweiyunPriceRecord.java
  15. 44 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/domain/MaterialBoweiyunSaveData.java
  16. 100 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/job/BoweiyunDataJobs.java
  17. 26 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/MaterialBoweiyunPriceRecordMapper.java
  18. 24 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/MaterialBoweiyunSaveDataMapper.java
  19. 37 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/xml/MaterialBoweiyunPriceRecordMapper.xml
  20. 21 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/xml/MaterialBoweiyunSaveDataMapper.xml
  21. 489 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/BoweiyunDataSyncService.java
  22. 475 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/MaterialBoweiyunPriceRecordService.java
  23. 20 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceModeDTO.java
  24. 52 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceOptionsDTO.java
  25. 38 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPricePointDTO.java
  26. 53 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceQueryDTO.java
  27. 26 0
      jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/scraper/config/ScraperProperties.java
  28. 8 7
      jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-development.yml
  29. 8 7
      jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-production.yml
  30. 80 0
      jeeplus-modules/jeeplus-xxl-job-executor-sample/src/main/java/com/xxl/job/executor/service/jobhandler/BoweiyunPriceJob.java

+ 65 - 0
docs/sql/addsql/20261113.sql

@@ -0,0 +1,65 @@
+-- 电力设备价格采集:完整表结构快照(手工在目标库执行,仓库无迁移框架)
+--
+
+CREATE TABLE IF NOT EXISTS `material_boweiyun_price_record` (
+                                                                `id`               varchar(64)   NOT NULL COMMENT '主键 UUID',
+    `site_code`        varchar(32)   NOT NULL DEFAULT 'boweiyun' COMMENT '站点编码,固定 boweiyun',
+    `site_name`        varchar(128)  NOT NULL DEFAULT '博微电力云计价平台' COMMENT '站点名称',
+    `mode_code`        varchar(16)   NOT NULL COMMENT '页签编码 national/quota/province/market',
+    `mode_name`        varchar(32)   NOT NULL COMMENT '页签名称 国网信息价/定额站信息价/各省信息价/市场价',
+    `province`         varchar(32)   NOT NULL DEFAULT '' COMMENT '省份',
+    `city`             varchar(64)   NOT NULL DEFAULT '' COMMENT '城市',
+    `fir_catalog`      varchar(128)  NOT NULL DEFAULT '' COMMENT '一级分类',
+    `seco_catalog`     varchar(128)  NOT NULL DEFAULT '' COMMENT '二级分类',
+    `third_catalog`    varchar(128)  NOT NULL DEFAULT '' COMMENT '三级分类',
+    `material_name`    varchar(255)  NOT NULL DEFAULT '' COMMENT '物料/设备名称',
+    `original_spec`    varchar(512)  NOT NULL DEFAULT '' COMMENT '规格型号',
+    `original_unit`    varchar(32)   NOT NULL DEFAULT '' COMMENT '单位',
+    `particular_year`  varchar(8)    NOT NULL DEFAULT '' COMMENT '年份,如 2026',
+    `time_version`     varchar(32)   NOT NULL DEFAULT '' COMMENT '期数,如 10(10 月)或 二季度',
+    `tax_free_price`   decimal(18,4) DEFAULT NULL COMMENT '不含税价',
+    `tax_price`        decimal(18,4) DEFAULT NULL COMMENT '含税价',
+    `market_value_name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商',
+    `brand`            varchar(255)  NOT NULL DEFAULT '' COMMENT '品牌(仅市场价)',
+    `remark`           varchar(512)  NOT NULL DEFAULT '' COMMENT '备注',
+    `source_url`       varchar(1024) NOT NULL DEFAULT '' COMMENT '详情页地址',
+    `file_name`        varchar(255)  NOT NULL DEFAULT '' COMMENT '导入的数据文件名,如 boweiyun__market__2025__10.jsonl.gz',
+    `scraped_at`       datetime      DEFAULT NULL COMMENT '采集时间',
+    `dedupe_key`       char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'sha256(网站+模块+省份+城市+年+期数+名称+规格+原始单位)',
+    `create_time`      datetime      DEFAULT NULL,
+    `create_by_id`     varchar(64)   DEFAULT NULL,
+    `update_time`      datetime      DEFAULT NULL,
+    `update_by_id`     varchar(64)   DEFAULT NULL,
+    `del_flag`         int           DEFAULT 0,
+    `tenant_id`        varchar(64)   DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    UNIQUE KEY `uk_mbpr_dedupe` (`dedupe_key`),
+    KEY `idx_mbpr_list` (`del_flag`, `mode_code`, `province`, `city`, `create_time`),
+    KEY `idx_mbpr_trend` (`mode_code`, `material_name`, `create_time`),
+    KEY `idx_mbpr_catalog` (`fir_catalog`, `seco_catalog`, `third_catalog`),
+    KEY `idx_mbpr_file` (`file_name`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力设备价格采集记录';
+
+
+
+CREATE TABLE IF NOT EXISTS `material_boweiyun_save_data` (
+                                                             `id`               varchar(64)   NOT NULL COMMENT '主键 UUID',
+    `site_code`        varchar(32)   NOT NULL DEFAULT 'boweiyun' COMMENT '网站编码,固定 boweiyun',
+    `site_name`        varchar(128)  NOT NULL DEFAULT '博微电力云计价平台' COMMENT '网站名称',
+    `mode_code`        varchar(16)   NOT NULL COMMENT '模块编码 national/quota/province/market',
+    `mode_name`        varchar(32)   NOT NULL COMMENT '模块名称 国网信息价/定额站信息价/各省信息价/市场价',
+    `particular_year`  varchar(8)    NOT NULL DEFAULT '' COMMENT '年份,如 2025',
+    `time_version`     varchar(32)   NOT NULL DEFAULT '' COMMENT '时间/期数,如 10、二季度、全年',
+    `file_name`        varchar(255)  NOT NULL COMMENT '数据文件名,如 boweiyun__market__2025__10__106463.jsonl.gz',
+    `row_count`        int           NOT NULL DEFAULT 0 COMMENT '该数据文件的记录条数',
+    `create_time`      datetime      DEFAULT NULL,
+    `create_by_id`     varchar(64)   DEFAULT NULL,
+    `update_time`      datetime      DEFAULT NULL,
+    `update_by_id`     varchar(64)   DEFAULT NULL,
+    `del_flag`         int           DEFAULT 0,
+    `tenant_id`        varchar(64)   DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    UNIQUE KEY `uk_mbysd_period` (`site_code`, `mode_code`, `particular_year`, `time_version`),
+    UNIQUE KEY `uk_mbysd_file` (`file_name`),
+    KEY `idx_mbysd_year` (`particular_year`, `time_version`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力价格已入库期数登记';

+ 67 - 0
docs/sql/fullsql/20261113.sql

@@ -0,0 +1,67 @@
+-- 电力设备价格采集:完整表结构快照(手工在目标库执行,仓库无迁移框架)
+--
+
+CREATE TABLE IF NOT EXISTS `material_boweiyun_price_record` (
+  `id`               varchar(64)   NOT NULL COMMENT '主键 UUID',
+  `site_code`        varchar(32)   NOT NULL DEFAULT 'boweiyun' COMMENT '站点编码,固定 boweiyun',
+  `site_name`        varchar(128)  NOT NULL DEFAULT '博微电力云计价平台' COMMENT '站点名称',
+  `mode_code`        varchar(16)   NOT NULL COMMENT '页签编码 national/quota/province/market',
+  `mode_name`        varchar(32)   NOT NULL COMMENT '页签名称 国网信息价/定额站信息价/各省信息价/市场价',
+  `province`         varchar(32)   NOT NULL DEFAULT '' COMMENT '省份',
+  `city`             varchar(64)   NOT NULL DEFAULT '' COMMENT '城市',
+  `fir_catalog`      varchar(128)  NOT NULL DEFAULT '' COMMENT '一级分类',
+  `seco_catalog`     varchar(128)  NOT NULL DEFAULT '' COMMENT '二级分类',
+  `third_catalog`    varchar(128)  NOT NULL DEFAULT '' COMMENT '三级分类',
+  `material_name`    varchar(255)  NOT NULL DEFAULT '' COMMENT '物料/设备名称',
+  `original_spec`    varchar(512)  NOT NULL DEFAULT '' COMMENT '规格型号',
+  `original_unit`    varchar(32)   NOT NULL DEFAULT '' COMMENT '单位',
+  `particular_year`  varchar(8)    NOT NULL DEFAULT '' COMMENT '年份,如 2026',
+  `time_version`     varchar(32)   NOT NULL DEFAULT '' COMMENT '期数,如 10(10 月)或 二季度',
+  `tax_free_price`   decimal(18,4) DEFAULT NULL COMMENT '不含税价',
+  `tax_price`        decimal(18,4) DEFAULT NULL COMMENT '含税价',
+  `market_value_name` varchar(255) NOT NULL DEFAULT '' COMMENT '供应商',
+  `brand`            varchar(255)  NOT NULL DEFAULT '' COMMENT '品牌(仅市场价)',
+  `remark`           varchar(512)  NOT NULL DEFAULT '' COMMENT '备注',
+  `source_url`       varchar(1024) NOT NULL DEFAULT '' COMMENT '详情页地址',
+  `file_name`        varchar(255)  NOT NULL DEFAULT '' COMMENT '导入的数据文件名,如 boweiyun__market__2025__10.jsonl.gz',
+  `scraped_at`       datetime      DEFAULT NULL COMMENT '采集时间',
+  `dedupe_key`       char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'sha256(网站+模块+省份+城市+年+期数+名称+规格+原始单位)',
+  `create_time`      datetime      DEFAULT NULL,
+  `create_by_id`     varchar(64)   DEFAULT NULL,
+  `update_time`      datetime      DEFAULT NULL,
+  `update_by_id`     varchar(64)   DEFAULT NULL,
+  `del_flag`         int           DEFAULT 0,
+  `tenant_id`        varchar(64)   DEFAULT '10000',
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_mbpr_dedupe` (`dedupe_key`),
+  KEY `idx_mbpr_list` (`del_flag`, `mode_code`, `province`, `city`, `create_time`),
+  KEY `idx_mbpr_name_scan` (`del_flag`, `mode_code`, `material_name`),
+  KEY `idx_mbpr_list_time` (`del_flag`, `mode_code`, `create_time`, `id`),
+  KEY `idx_mbpr_trend` (`mode_code`, `material_name`, `create_time`),
+  KEY `idx_mbpr_catalog` (`fir_catalog`, `seco_catalog`, `third_catalog`),
+  KEY `idx_mbpr_file` (`file_name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力设备价格采集记录';
+
+
+
+CREATE TABLE IF NOT EXISTS `material_boweiyun_save_data` (
+    `id`               varchar(64)   NOT NULL COMMENT '主键 UUID',
+    `site_code`        varchar(32)   NOT NULL DEFAULT 'boweiyun' COMMENT '网站编码,固定 boweiyun',
+    `site_name`        varchar(128)  NOT NULL DEFAULT '博微电力云计价平台' COMMENT '网站名称',
+    `mode_code`        varchar(16)   NOT NULL COMMENT '模块编码 national/quota/province/market',
+    `mode_name`        varchar(32)   NOT NULL COMMENT '模块名称 国网信息价/定额站信息价/各省信息价/市场价',
+    `particular_year`  varchar(8)    NOT NULL DEFAULT '' COMMENT '年份,如 2025',
+    `time_version`     varchar(32)   NOT NULL DEFAULT '' COMMENT '时间/期数,如 10、二季度、全年',
+    `file_name`        varchar(255)  NOT NULL COMMENT '数据文件名,如 boweiyun__market__2025__10__106463.jsonl.gz',
+    `row_count`        int           NOT NULL DEFAULT 0 COMMENT '该数据文件的记录条数',
+    `create_time`      datetime      DEFAULT NULL,
+    `create_by_id`     varchar(64)   DEFAULT NULL,
+    `update_time`      datetime      DEFAULT NULL,
+    `update_by_id`     varchar(64)   DEFAULT NULL,
+    `del_flag`         int           DEFAULT 0,
+    `tenant_id`        varchar(64)   DEFAULT '10000',
+    PRIMARY KEY (`id`),
+    UNIQUE KEY `uk_mbysd_period` (`site_code`, `mode_code`, `particular_year`, `time_version`),
+    UNIQUE KEY `uk_mbysd_file` (`file_name`),
+    KEY `idx_mbysd_year` (`particular_year`, `time_version`)
+    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='博微电力价格已入库期数登记';

+ 17 - 0
jeeplus-api/jeeplus-system-api/src/main/java/com/jeeplus/flowable/factory/AssessApiFallbackFactory.java

@@ -119,6 +119,23 @@ public class AssessApiFallbackFactory implements FallbackFactory<IAssessApi> {
                 result.put("msg", "assess service unavailable");
                 return result;
             }
+
+            /** 博微推送/拉取同样返回 code=500,避免 XXL 任务被静默判定为成功。 */
+            @Override
+            public Map<String, Object> pushBoweiyunSavedData() {
+                Map<String, Object> result = new HashMap<>();
+                result.put("code", 500);
+                result.put("msg", "assess service unavailable");
+                return result;
+            }
+
+            @Override
+            public Map<String, Object> pullBoweiyunCompletedFiles() {
+                Map<String, Object> result = new HashMap<>();
+                result.put("code", 500);
+                result.put("msg", "assess service unavailable");
+                return result;
+            }
         };
     }
 }

+ 17 - 0
jeeplus-api/jeeplus-system-api/src/main/java/com/jeeplus/flowable/feign/IAssessApi.java

@@ -131,4 +131,21 @@ public interface IAssessApi {
      */
     @PostMapping(value = MATERIAL_PRICE_BASE_URL + "/sync")
     Map<String, Object> syncMaterialPrice(@RequestParam(value = "date", required = false) String date);
+
+    /** 博微电力价格内部接口前缀:服务间调用,不经 Gateway,也没有登录态校验 */
+    String POWER_PRICE_BASE_URL = "/feign/assess/powerPrice";
+
+    /**
+     * 推送博微已入库期数快照,Python 收到后算缺口并在后台抓取。
+     * 返回值 {code, skipped, msg}:skipped=true 表示另一实例正在执行。
+     */
+    @PostMapping(value = POWER_PRICE_BASE_URL + "/push-saved-data")
+    Map<String, Object> pushBoweiyunSavedData();
+
+    /**
+     * 拉取 Python 已完成的博微数据文件并按缺口导入。
+     * 返回值 {code, skipped, msg, rows}:rows 为实际入库条数。
+     */
+    @PostMapping(value = POWER_PRICE_BASE_URL + "/pull-import")
+    Map<String, Object> pullBoweiyunCompletedFiles();
 }

+ 8 - 11
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/materialPrice/client/MaterialPriceScraperClient.java

@@ -6,10 +6,11 @@ import cn.hutool.http.HttpResponse;
 import com.alibaba.fastjson.JSON;
 import com.jeeplus.assess.materialPrice.client.dto.MaterialPriceScrapeRequest;
 import com.jeeplus.assess.materialPrice.client.dto.MaterialPriceScrapeResponse;
+import com.jeeplus.assess.scraper.config.ScraperProperties;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
+import javax.annotation.Resource;
 import java.time.LocalDate;
 import java.util.List;
 
@@ -18,19 +19,15 @@ import java.util.List;
  *
  * 前端永远不直连 Python:只有 Java 通过内网调用本客户端,
  * XXL 定时任务(最新数据)与管理员区间采集(补历史)共用同一条链路。
- * 配置项在 Nacos 的 material-price.scraper.* 下,未配置时使用本地默认值。
+ * 地址与密钥与电力价格模块共用 scraper.* 配置。
  */
 @Slf4j
 @Component
 public class MaterialPriceScraperClient {
 
-    /** 抓取服务地址,生产环境必须改为实际部署地址 */
-    @Value("${material-price.scraper.base-url:http://127.0.0.1:8100}")
-    private String baseUrl;
-
-    /** 与 Python 的 SCRAPER_API_KEY 保持一致 */
-    @Value("${material-price.scraper.api-key:dev-key-change-me}")
-    private String apiKey;
+    /** 抓取服务地址与密钥,与电力价格模块共用同一份配置 */
+    @Resource
+    private ScraperProperties properties;
 
     /** HTTP 读超时,必须大于 Python 侧整批超时 */
     private int timeoutMs=600000;
@@ -83,11 +80,11 @@ public class MaterialPriceScraperClient {
         log.info("调用抓取服务 scene={} date={} startDate={} keys={} timeoutMs={}",
                 scene, request.getDate(), request.getStartDate(), request.getScraperKeys(), readTimeoutMs);
 
-        String url = StrUtil.removeSuffix(baseUrl, "/") + "/api/v1/scrape";
+        String url = StrUtil.removeSuffix(properties.getBaseUrl(), "/") + "/api/v1/scrape";
         HttpResponse response;
         try {
             response = HttpRequest.post(url)
-                    .header("X-API-KEY", apiKey)
+                    .header("X-API-KEY", properties.getApiKey())
                     .header("Content-Type", "application/json")
                     .body(JSON.toJSONString(request), "application/json")
                     .setConnectionTimeout(5000)

+ 193 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/PowerScraperClient.java

@@ -0,0 +1,193 @@
+package com.jeeplus.assess.powerPrice.client;
+
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.http.HttpRequest;
+import cn.hutool.http.HttpResponse;
+import com.alibaba.fastjson.JSON;
+import com.jeeplus.assess.powerPrice.client.dto.CompletedFileDTO;
+import com.jeeplus.assess.powerPrice.client.dto.CompletedFilesResponseDTO;
+import com.jeeplus.assess.powerPrice.client.dto.SavedDataPushDTO;
+import com.jeeplus.assess.powerPrice.client.dto.SavedDataResponseDTO;
+import com.jeeplus.assess.powerPrice.client.dto.SavedPeriodDTO;
+import com.jeeplus.assess.scraper.config.ScraperProperties;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.io.File;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.List;
+
+/**
+ * 调用 Python 抓取服务(xg_material_scraper)电力价格三个接口的 HTTP 客户端。
+ *
+ * 前端永远不直连 Python:推送、列文件、下载都只走这里。
+ * 三个接口都要求 X-API-KEY,密钥与 Python 的 SCRAPER_API_KEY 保持一致。
+ */
+@Slf4j
+@Component
+public class PowerScraperClient {
+
+    /** 抓取服务地址与密钥,与物料价格模块共用同一份配置 */
+    @Resource
+    private ScraperProperties properties;
+
+    /** 建连超时,内网固定 5 秒 */
+    private static final int CONNECT_TIMEOUT_MS = 5000;
+
+    /** 推送只是写快照并立即返回,读超时 60 秒足够 */
+    private static final int PUSH_TIMEOUT_MS = 60000;
+
+    /** 列文件是本地目录扫描,30 秒足够 */
+    private static final int LIST_TIMEOUT_MS = 30000;
+
+    /** 单文件下载超时:一期数据压缩后通常在几 MB 到几十 MB,给足 10 分钟 */
+    private static final int DOWNLOAD_TIMEOUT_MS = 600000;
+
+    /**
+     * 推送已入库期数快照。
+     *
+     * @param records 登记表全表快照,允许为空(首次部署时 Python 会抓全部期数)
+     * @return Python 响应;网络错误、HTTP 非 200、内容无法解析时抛 IllegalStateException
+     */
+    public SavedDataResponseDTO pushSavedData(List<SavedPeriodDTO> records) {
+        SavedDataPushDTO payload = new SavedDataPushDTO();
+        payload.setRecords(records);
+        long begin = System.currentTimeMillis();
+        String body = post("/api/v1/power/saved-data", JSON.toJSONString(payload), PUSH_TIMEOUT_MS);
+        SavedDataResponseDTO result;
+        try {
+            result = JSON.parseObject(body, SavedDataResponseDTO.class);
+        } catch (Exception e) {
+            log.error("推送响应无法解析 elapsedMs={} body={}",
+                    System.currentTimeMillis() - begin, StrUtil.maxLength(body, 500), e);
+            throw new IllegalStateException("推送响应无法解析", e);
+        }
+        if (result == null) {
+            throw new IllegalStateException("推送响应为空");
+        }
+        log.info("推送已入库期数 records={} accepted={} skipped={} elapsedMs={}",
+                records.size(), result.getAccepted(), result.getSkipped(), System.currentTimeMillis() - begin);
+        return result;
+    }
+
+    /**
+     * 查询 Python 侧已完成的数据文件(按修改时间升序,不含 .temp)。
+     */
+    public List<CompletedFileDTO> listCompletedFiles() {
+        long begin = System.currentTimeMillis();
+        String body = get("/api/v1/power/files/completed", LIST_TIMEOUT_MS);
+        CompletedFilesResponseDTO result;
+        try {
+            result = JSON.parseObject(body, CompletedFilesResponseDTO.class);
+        } catch (Exception e) {
+            log.error("文件列表响应无法解析 elapsedMs={} body={}",
+                    System.currentTimeMillis() - begin, StrUtil.maxLength(body, 500), e);
+            throw new IllegalStateException("文件列表响应无法解析", e);
+        }
+        List<CompletedFileDTO> files = result == null ? null : result.getFiles();
+        if (files == null) {
+            throw new IllegalStateException("文件列表响应缺少 files 字段");
+        }
+        log.info("抓取服务文件列表 files={} elapsedMs={}", files.size(), System.currentTimeMillis() - begin);
+        return files;
+    }
+
+    /**
+     * 下载单个数据文件到本地路径。
+     *
+     * 先写调用方给的临时文件,由调用方校验大小后再原子改名;
+     * 非 200、内容为空、写盘异常都会删除临时文件并抛 IllegalStateException。
+     *
+     * @param fileName Python 侧文件名
+     * @param tempFile 本地临时文件(<local-dir>/download.tmp)
+     * @return 实际写入的字节数
+     */
+    public long download(String fileName, File tempFile) {
+        String encoded;
+        try {
+            // Java 8 没有 URLEncoder.encode(String, Charset),必须用字符集名并处理受检异常
+            encoded = URLEncoder.encode(fileName, "UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            throw new IllegalStateException("文件名编码失败: " + fileName, e);
+        }
+        String url = StrUtil.removeSuffix(properties.getBaseUrl(), "/")
+                + "/api/v1/power/files/" + encoded + "/download";
+        long begin = System.currentTimeMillis();
+        log.info("下载数据文件 fileName={}", fileName);
+        HttpResponse response = null;
+        try {
+            response = HttpRequest.get(url)
+                    .header("X-API-KEY", properties.getApiKey())
+                    .setConnectionTimeout(CONNECT_TIMEOUT_MS)
+                    .setReadTimeout(DOWNLOAD_TIMEOUT_MS)
+                    .execute();
+            if (!response.isOk()) {
+                throw new IllegalStateException("下载失败,HTTP " + response.getStatus());
+            }
+            response.writeBody(tempFile);
+        } catch (Exception e) {
+            deleteQuietly(tempFile);
+            log.error("下载数据文件失败 fileName={} elapsedMs={}",
+                    fileName, System.currentTimeMillis() - begin, e);
+            throw e instanceof IllegalStateException
+                    ? (IllegalStateException) e
+                    : new IllegalStateException("下载数据文件失败: " + e.getMessage(), e);
+        } finally {
+            if (response != null) {
+                response.close();
+            }
+        }
+        long size = tempFile.length();
+        if (size <= 0) {
+            deleteQuietly(tempFile);
+            throw new IllegalStateException("下载的数据文件为空: " + fileName);
+        }
+        log.info("下载完成 fileName={} size={} elapsedMs={}", fileName, size, System.currentTimeMillis() - begin);
+        return size;
+    }
+
+    private String post(String path, String json, int readTimeoutMs) {
+        return execute(path, readTimeoutMs, true, json);
+    }
+
+    private String get(String path, int readTimeoutMs) {
+        return execute(path, readTimeoutMs, false, null);
+    }
+
+    private String execute(String path, int readTimeoutMs, boolean post, String json) {
+        String url = StrUtil.removeSuffix(properties.getBaseUrl(), "/") + path;
+        try {
+            HttpRequest request = post
+                    ? HttpRequest.post(url).body(json, "application/json")
+                    : HttpRequest.get(url);
+            HttpResponse response = request
+                    .header("X-API-KEY", properties.getApiKey())
+                    .setConnectionTimeout(CONNECT_TIMEOUT_MS)
+                    .setReadTimeout(readTimeoutMs)
+                    .execute();
+            try {
+                if (!response.isOk()) {
+                    log.error("抓取服务返回异常 url={} status={} body={}",
+                            url, response.getStatus(), StrUtil.maxLength(response.body(), 500));
+                    throw new IllegalStateException("抓取服务返回 HTTP " + response.getStatus());
+                }
+                return response.body();
+            } finally {
+                response.close();
+            }
+        } catch (IllegalStateException e) {
+            throw e;
+        } catch (Exception e) {
+            log.error("调用抓取服务失败 url={}", url, e);
+            throw new IllegalStateException("调用抓取服务失败: " + e.getMessage(), e);
+        }
+    }
+
+    private static void deleteQuietly(File file) {
+        if (file != null && file.exists() && !file.delete()) {
+            log.warn("删除临时文件失败: {}", file.getAbsolutePath());
+        }
+    }
+}

+ 21 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/CompletedFileDTO.java

@@ -0,0 +1,21 @@
+package com.jeeplus.assess.powerPrice.client.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/** 一个已完成(非 .temp)的数据文件。 */
+@Data
+public class CompletedFileDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 文件名,如 boweiyun__market__2025__10.jsonl.gz */
+    private String fileName;
+
+    /** 文件字节数 */
+    private Long size;
+
+    /** 最后修改时间(ISO8601),列表已按修改时间升序 */
+    private String modifiedAt;
+}

+ 16 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/CompletedFilesResponseDTO.java

@@ -0,0 +1,16 @@
+package com.jeeplus.assess.powerPrice.client.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/** GET /api/v1/power/files/completed 的响应。 */
+@Data
+public class CompletedFilesResponseDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private List<CompletedFileDTO> files = new ArrayList<>();
+}

+ 16 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedDataPushDTO.java

@@ -0,0 +1,16 @@
+package com.jeeplus.assess.powerPrice.client.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/** POST /api/v1/power/saved-data 的请求体:整表已入库期数快照。 */
+@Data
+public class SavedDataPushDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private List<SavedPeriodDTO> records = new ArrayList<>();
+}

+ 21 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedDataResponseDTO.java

@@ -0,0 +1,21 @@
+package com.jeeplus.assess.powerPrice.client.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * POST /api/v1/power/saved-data 的响应。
+ *
+ * skipped=true 表示 Python 正在抓上一轮,本次推送没有被处理;
+ * 这不是失败,Java 记一条日志后等下一次定时推送即可。
+ */
+@Data
+public class SavedDataResponseDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private Boolean accepted;
+
+    private Boolean skipped;
+}

+ 32 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/client/dto/SavedPeriodDTO.java

@@ -0,0 +1,32 @@
+package com.jeeplus.assess.powerPrice.client.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 推送给 Python 的一条「已入库期数」记录。
+ *
+ * site_name / mode_name 不传:Python 侧只按编码判断缺口,
+ * 名称在 Python 内是固定值,传了也会被忽略。
+ */
+@Data
+public class SavedPeriodDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 网站编码,固定 boweiyun */
+    private String siteCode = "boweiyun";
+
+    /** 页签编码 national / quota / province / market */
+    private String modeCode;
+
+    /** 年份,如 2025 */
+    private String particularYear;
+
+    /** 期数,如 10、二季度、全年 */
+    private String timeVersion;
+
+    /** 已入库的数据文件名,Python 侧据此删除已入库文件(当前未启用) */
+    private String fileName;
+}

+ 59 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/controller/PowerPriceController.java

@@ -0,0 +1,59 @@
+package com.jeeplus.assess.powerPrice.controller;
+
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunPriceRecord;
+import com.jeeplus.assess.powerPrice.service.MaterialBoweiyunPriceRecordService;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPriceOptionsDTO;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPricePointDTO;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPriceQueryDTO;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+/**
+ * 电力设备价格对外接口(经 Gateway 的 /assess-server 前缀访问)。
+ *
+ * 只提供只读查询:下拉选项、分页列表、单物料走势。
+ * 数据采集由定时任务完成,页面没有提交抓取或任务日志入口。
+ */
+@Api(tags = "电力设备价格")
+@RestController
+@RequestMapping("/powerPrice/record")
+public class PowerPriceController {
+
+    @Resource
+    private MaterialBoweiyunPriceRecordService recordService;
+
+    /** 筛选框下拉选项:页签、省份、城市、年份、期数、一级/二级分类(一次查全,前端本地级联)。 */
+    @ApiOperation(value = "筛选框下拉选项")
+    @PreAuthorize("hasAuthority('program:powerPrice:list')")
+    @GetMapping("/options")
+    public ResponseEntity<PowerPriceOptionsDTO> options() {
+        return ResponseEntity.ok(recordService.options());
+    }
+
+    /** 分页列表。current/size 由 MyBatis-Plus 的 Page 自动绑定。 */
+    @ApiOperation(value = "分页查询电力设备价格")
+    @PreAuthorize("hasAuthority('program:powerPrice:list')")
+    @GetMapping("/list")
+    public ResponseEntity<IPage<MaterialBoweiyunPriceRecord>> list(Page<MaterialBoweiyunPriceRecord> page,
+                                                        PowerPriceQueryDTO query) {
+        return ResponseEntity.ok(recordService.pageQuery(page, query));
+    }
+
+    /** 单物料走势:前端按当前行的页签/名称/规格/单位/地区带入条件。 */
+    @ApiOperation(value = "查询单物料历史价格")
+    @PreAuthorize("hasAuthority('program:powerPrice:list')")
+    @GetMapping("/history")
+    public ResponseEntity<List<PowerPricePointDTO>> history(PowerPriceQueryDTO query) {
+        return ResponseEntity.ok(recordService.history(query));
+    }
+}

+ 74 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/controller/PowerPriceFeignController.java

@@ -0,0 +1,74 @@
+package com.jeeplus.assess.powerPrice.controller;
+
+import com.jeeplus.assess.powerPrice.job.BoweiyunDataJobs;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * 内部 Feign 接口:供 XXL 定时任务调用博微电力价格的推送与拉取。
+ *
+ * 不走 Gateway、不加 @PreAuthorize(服务间调用没有登录态),只依赖内网隔离;
+ * 返回统一带 code,job 按 code 判定任务成败,skipped=true 表示 Redis 锁被其它实例持有。
+ */
+@Slf4j
+@RestController
+@RequestMapping("/feign/assess/powerPrice")
+public class PowerPriceFeignController {
+
+    @Resource
+    private BoweiyunDataJobs dataJobs;
+
+    /** 推送已入库期数快照,Python 收到后算缺口并在后台抓取。 */
+    @PostMapping("/push-saved-data")
+    public Map<String, Object> pushSavedData() {
+        try {
+            Boolean executed = dataJobs.pushSavedData();
+            if (executed == null) {
+                return result(false, "另一实例正在执行,本次跳过");
+            }
+            return result(true, "推送完成");
+        } catch (Exception e) {
+            log.error("推送已入库期数快照失败", e);
+            return fail("推送异常: " + e.getMessage());
+        }
+    }
+
+    /** 拉取 Python 已完成文件并导入,rows 为实际入库条数。 */
+    @PostMapping("/pull-import")
+    public Map<String, Object> pullAndImport() {
+        try {
+            Integer rows = dataJobs.pullAndImport();
+            if (rows == null) {
+                return result(false, "另一实例正在执行,本次跳过");
+            }
+            Map<String, Object> body = result(true, "导入完成");
+            body.put("rows", rows);
+            return body;
+        } catch (Exception e) {
+            log.error("拉取完成文件并导入失败", e);
+            return fail("导入异常: " + e.getMessage());
+        }
+    }
+
+    private static Map<String, Object> result(boolean executed, String msg) {
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("code", 200);
+        body.put("skipped", !executed);
+        body.put("msg", msg);
+        return body;
+    }
+
+    private static Map<String, Object> fail(String msg) {
+        Map<String, Object> body = new LinkedHashMap<>();
+        body.put("code", 500);
+        body.put("skipped", false);
+        body.put("msg", msg);
+        return body;
+    }
+}

+ 76 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/domain/MaterialBoweiyunPriceRecord.java

@@ -0,0 +1,76 @@
+package com.jeeplus.assess.powerPrice.domain;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.jeeplus.core.domain.BaseEntity;
+import lombok.Data;
+
+import java.math.BigDecimal;
+import java.util.Date;
+
+/**
+ * 电力设备价格记录,对应表 material_boweiyun_price_record。
+ *
+ * 主键沿用 BaseEntity 的 String id(UUID);表前缀 material_ 已被租户拦截器忽略,
+ * 数据全局共享。幂等键 dedupe_key 由 Python 生成,缺失时 Java 按同一公式重算。
+ */
+@Data
+@TableName("material_boweiyun_price_record")
+public class MaterialBoweiyunPriceRecord extends BaseEntity {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 站点编码,固定 boweiyun */
+    private String siteCode;
+    private String siteName;
+
+    /** 页签编码:national / quota / province / market */
+    private String modeCode;
+    private String modeName;
+
+    /** 地区:国网固定总部,定额站空串,各省是省份+城市,市场价是省份 */
+    private String province;
+    private String city;
+
+    /** 分类树三级 */
+    private String firCatalog;
+    private String secoCatalog;
+    private String thirdCatalog;
+
+    /** 物料/设备名称 */
+    private String materialName;
+
+    /** 规格型号,保留接口原文 */
+    private String originalSpec;
+
+    /** 接口原始单位(如 m³) */
+    private String originalUnit;
+
+    private String particularYear;
+    private String timeVersion;
+
+    /** 不含税价 / 含税价;接口 "-" 存 null */
+    private BigDecimal taxFreePrice;
+    private BigDecimal taxPrice;
+
+    /** 市场价供应商/报价来源,其他页签为空串 */
+    private String marketValueName;
+
+    /** 市场价品牌,其他页签为空串 */
+    private String brand;
+
+    private String remark;
+
+    /** 详情页地址 */
+    private String sourceUrl;
+
+    /** 导入的数据文件名,如 boweiyun__market__2025__10.jsonl.gz */
+    private String fileName;
+
+    /** 采集时间 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date scrapedAt;
+
+    /** 幂等键:sha256(站点|模块|省份|城市|年|期数|名称|规格|单位),64 位小写 hex */
+    private String dedupeKey;
+}

+ 44 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/domain/MaterialBoweiyunSaveData.java

@@ -0,0 +1,44 @@
+package com.jeeplus.assess.powerPrice.domain;
+
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.jeeplus.core.domain.BaseEntity;
+import lombok.Data;
+
+import java.util.Date;
+
+/**
+ * 已入库期数登记,对应表 material_boweiyun_save_data。
+ *
+ * 一行 = 网站 × 模块 × 年份 × 期数 + 数据文件名;
+ */
+@Data
+@TableName("material_boweiyun_save_data")
+public class MaterialBoweiyunSaveData extends BaseEntity {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 网站编码,固定 boweiyun */
+    private String siteCode;
+    private String siteName;
+
+    /** 模块编码:national / quota / province / market */
+    private String modeCode;
+    private String modeName;
+
+    /** 年份,如 2025 */
+    private String particularYear;
+
+    /** 时间/期数,如 10、二季度、全年 */
+    private String timeVersion;
+
+    /** 数据文件名,如 boweiyun__market__2025__10__106463.jsonl.gz */
+    private String fileName;
+
+    /** 该数据文件的记录条数(实际入库行数) */
+    private Integer rowCount;
+
+    /** 最后入档时间,便于人工排查 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date updateTime;
+}

+ 100 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/job/BoweiyunDataJobs.java

@@ -0,0 +1,100 @@
+package com.jeeplus.assess.powerPrice.job;
+
+import cn.hutool.core.util.IdUtil;
+import com.jeeplus.assess.powerPrice.service.BoweiyunDataSyncService;
+import com.jeeplus.common.redis.RedisUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
+import java.util.function.Supplier;
+
+/**
+ * 博微电力价格的两条月度链路入口,由 XXL-Job 调度(xxl-job-executor-sample 模块里的
+ * BoweiyunPriceJob 通过 Feign 调用 PowerPriceFeignController):
+ *
+ */
+@Slf4j
+@Component
+public class BoweiyunDataJobs {
+
+    /** 推送锁:TTL 30 分钟,推送本身是秒级操作 */
+    private static final String PUSH_LOCK_KEY = "lock:boweiyun.saved.push";
+    private static final long PUSH_LOCK_SECONDS = 30 * 60L;
+
+    /** 拉取锁:TTL 12 小时,覆盖一整轮多文件下载与入库 */
+    private static final String PULL_LOCK_KEY = "lock:boweiyun.file.pull";
+    private static final long PULL_LOCK_SECONDS = 12 * 60 * 60L;
+
+    /** 实例标识:释放锁前校验 value,避免误删其它实例重新获取的锁 */
+    private final String instanceId = IdUtil.fastSimpleUUID();
+
+    @Resource
+    private BoweiyunDataSyncService syncService;
+
+    @Resource
+    private RedisUtils redisUtils;
+
+    /**
+     * 推送已入库期数快照。
+     *
+     * @return true=本次已执行;null=另一实例正在执行,本次跳过
+     */
+    public Boolean pushSavedData() {
+        return runWithLock(PUSH_LOCK_KEY, PUSH_LOCK_SECONDS, () -> {
+            syncService.pushSavedData();
+            return Boolean.TRUE;
+        });
+    }
+
+    /**
+     * 拉取 Python 已完成文件并导入。
+     *
+     * @return 实际入库条数;null=另一实例正在执行,本次跳过
+     */
+    public Integer pullAndImport() {
+        return runWithLock(PULL_LOCK_KEY, PULL_LOCK_SECONDS, syncService::pullAndImport);
+    }
+
+    /**
+     * 抢锁执行,异常原样抛出,由调用方(Feign 接口 → XXL)判定任务失败。
+     *
+     * Redis 不可用时退化为「不互斥直接执行」:两条链路本身幂等,
+     * 可用性优先于多实例互斥的严格性。
+     */
+    private <T> T runWithLock(String key, long ttlSeconds, Supplier<T> action) {
+        Boolean acquired;
+        try {
+            acquired = redisUtils.setIfAbsent(key, instanceId);
+            if (Boolean.TRUE.equals(acquired)) {
+                redisUtils.expire(key, ttlSeconds);
+            }
+        } catch (Exception e) {
+            log.warn("Redis 锁不可用,直接执行定时任务 key={}: {}", key, e.getMessage());
+            acquired = null;
+        }
+        if (Boolean.FALSE.equals(acquired)) {
+            log.info("另一实例正在执行定时任务,跳过 key={}", key);
+            return null;
+        }
+        try {
+            return action.get();
+        } finally {
+            if (Boolean.TRUE.equals(acquired)) {
+                releaseLock(key);
+            }
+        }
+    }
+
+    /** 只释放自己持有的锁:value 不是本实例说明锁已过期并被其它实例获取。 */
+    private void releaseLock(String key) {
+        try {
+            Object value = redisUtils.get(key);
+            if (instanceId.equals(value)) {
+                redisUtils.delete(key);
+            }
+        } catch (Exception e) {
+            log.warn("释放定时任务锁失败 key={}: {}", key, e.getMessage());
+        }
+    }
+}

+ 26 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/MaterialBoweiyunPriceRecordMapper.java

@@ -0,0 +1,26 @@
+package com.jeeplus.assess.powerPrice.mapper;
+
+import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunPriceRecord;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+
+/**
+ * 电力设备价格记录 Mapper。
+ *
+ */
+@Mapper
+@InterceptorIgnore(tenantLine = "true")
+public interface MaterialBoweiyunPriceRecordMapper extends BaseMapper<MaterialBoweiyunPriceRecord> {
+
+    /**
+     * 批量幂等写入:靠 dedupe_key 唯一索引 + ON DUPLICATE KEY UPDATE 实现「同一期重复导入只更新」。
+     *
+     * @param list 同一批次内 dedupe_key 已去重的记录(调用方保证)
+     * @return 受影响行数(MySQL 新增计 1、更新计 2,仅用于监控,不作为业务条数)
+     */
+    int upsertBatch(@Param("list") List<MaterialBoweiyunPriceRecord> list);
+}

+ 24 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/MaterialBoweiyunSaveDataMapper.java

@@ -0,0 +1,24 @@
+package com.jeeplus.assess.powerPrice.mapper;
+
+import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunSaveData;
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+
+/**
+ * 已入库期数登记 Mapper。
+ *
+ */
+@Mapper
+@InterceptorIgnore(tenantLine = "true")
+public interface MaterialBoweiyunSaveDataMapper extends BaseMapper<MaterialBoweiyunSaveData> {
+
+    /**
+     * 登记一个已入库的数据文件。
+     *
+     * @param data 审计字段(id/时间/操作人/租户)由调用方预填,不走 MyMetaObjectHandler
+     * @return 受影响行数
+     */
+    int upsert(@Param("it") MaterialBoweiyunSaveData data);
+}

+ 37 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/xml/MaterialBoweiyunPriceRecordMapper.xml

@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+
+<mapper namespace="com.jeeplus.assess.powerPrice.mapper.MaterialBoweiyunPriceRecordMapper">
+
+    <insert id="upsertBatch">
+        INSERT INTO material_boweiyun_price_record
+        (id, site_code, site_name, mode_code, mode_name, province, city,
+         fir_catalog, seco_catalog, third_catalog,
+         material_name, original_spec, original_unit, particular_year, time_version,
+         tax_free_price, tax_price, market_value_name, brand, remark,
+         source_url, file_name, scraped_at, dedupe_key,
+         create_time, create_by_id, update_time, update_by_id, del_flag, tenant_id)
+        VALUES
+        <foreach collection="list" item="it" separator=",">
+            (#{it.id}, #{it.siteCode}, #{it.siteName}, #{it.modeCode}, #{it.modeName},
+             #{it.province}, #{it.city}, #{it.firCatalog}, #{it.secoCatalog}, #{it.thirdCatalog},
+             #{it.materialName}, #{it.originalSpec}, #{it.originalUnit},
+             #{it.particularYear}, #{it.timeVersion},
+             #{it.taxFreePrice}, #{it.taxPrice}, #{it.marketValueName}, #{it.brand}, #{it.remark},
+             #{it.sourceUrl}, #{it.fileName}, #{it.scrapedAt}, #{it.dedupeKey},
+             #{it.createTime}, #{it.createById}, #{it.updateTime}, #{it.updateById},
+             #{it.delFlag}, #{it.tenantId})
+        </foreach>
+        ON DUPLICATE KEY UPDATE
+            tax_free_price = VALUES(tax_free_price),
+            tax_price = VALUES(tax_price),
+            market_value_name = VALUES(market_value_name),
+            brand = VALUES(brand),
+            source_url = VALUES(source_url),
+            scraped_at = VALUES(scraped_at),
+            file_name = VALUES(file_name),
+            update_time = NOW(),
+            update_by_id = VALUES(update_by_id),
+            del_flag = 0
+    </insert>
+</mapper>

+ 21 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/mapper/xml/MaterialBoweiyunSaveDataMapper.xml

@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.jeeplus.assess.powerPrice.mapper.MaterialBoweiyunSaveDataMapper">
+
+    <insert id="upsert">
+        INSERT INTO material_boweiyun_save_data
+        (id, site_code, site_name, mode_code, mode_name, particular_year, time_version,
+         file_name, row_count, create_time, create_by_id, update_time, update_by_id, del_flag, tenant_id)
+        VALUES
+        (#{it.id}, #{it.siteCode}, #{it.siteName}, #{it.modeCode}, #{it.modeName},
+         #{it.particularYear}, #{it.timeVersion}, #{it.fileName}, #{it.rowCount},
+         #{it.createTime}, #{it.createById}, #{it.updateTime}, #{it.updateById},
+         #{it.delFlag}, #{it.tenantId})
+        ON DUPLICATE KEY UPDATE
+            file_name = VALUES(file_name),
+            row_count = VALUES(row_count),
+            update_time = NOW(),
+            update_by_id = VALUES(update_by_id),
+            del_flag = 0
+    </insert>
+</mapper>

+ 489 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/BoweiyunDataSyncService.java

@@ -0,0 +1,489 @@
+package com.jeeplus.assess.powerPrice.service;
+
+import cn.hutool.core.util.IdUtil;
+import cn.hutool.core.util.StrUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.jeeplus.assess.powerPrice.client.PowerScraperClient;
+import com.jeeplus.assess.powerPrice.client.dto.CompletedFileDTO;
+import com.jeeplus.assess.powerPrice.client.dto.SavedDataResponseDTO;
+import com.jeeplus.assess.powerPrice.client.dto.SavedPeriodDTO;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunSaveData;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunPriceRecord;
+import com.jeeplus.assess.powerPrice.mapper.MaterialBoweiyunSaveDataMapper;
+import com.jeeplus.assess.scraper.config.ScraperProperties;
+import com.jeeplus.common.constant.CommonConstants;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.time.LocalDateTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneId;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * 博微电力价格数据同步服务:Java 侧与 Python 文件交换的唯一入口。
+ *
+ */
+@Slf4j
+@Service
+public class BoweiyunDataSyncService {
+
+    /** 站点固定值,与 Python file_store.SITE_CODE 一致 */
+    private static final String SITE_CODE = "boweiyun";
+    private static final String SITE_NAME = "博微电力云计价平台";
+
+    /** 页签编码 -> 中文名,与 Python flows.py 一致 */
+    private static final Map<String, String> MODE_NAMES = new LinkedHashMap<>();
+
+    static {
+        MODE_NAMES.put("national", "国网信息价");
+        MODE_NAMES.put("quota", "定额站信息价");
+        MODE_NAMES.put("province", "各省信息价");
+        MODE_NAMES.put("market", "市场价");
+    }
+
+    /** 完成文件后缀;Python 侧抓取中的文件额外带 .temp,不会出现在已完成列表 */
+    private static final String DONE_SUFFIX = ".jsonl.gz";
+
+    /** 下载临时文件名 */
+    private static final String TEMP_FILE_NAME = "download.tmp";
+
+    /** 定时任务没有登录态,审计字段统一记 system */
+    private static final String SYSTEM_OPERATOR = "system";
+
+    /** Python 文件格式版本;版本不认识时直接失败,避免按错格式解析 */
+    private static final int SUPPORTED_FILE_VERSION = 1;
+    private static final String FILE_TYPE = "boweiPowerPrice";
+
+    private static final ZoneId CN_ZONE = ZoneId.of("Asia/Shanghai");
+
+    /** 每批从文件读出并交给入库服务的行数 */
+    private static final int BATCH_SIZE = 500;
+
+    @Resource
+    private PowerScraperClient client;
+
+    @Resource
+    private MaterialBoweiyunSaveDataMapper saveDataMapper;
+
+    @Resource
+    private MaterialBoweiyunPriceRecordService recordService;
+
+    @Resource
+    private ScraperProperties scraperProperties;
+
+    /**
+     * 推送已入库期数快照。
+     *
+     * Python 正在抓上一轮时会返回 skipped=true,这不视为失败:
+     * 本轮没抓完的缺口由下一次推送继续。
+     */
+    public void pushSavedData() {
+        List<MaterialBoweiyunSaveData> rows = saveDataMapper.selectList(new QueryWrapper<>());
+        List<SavedPeriodDTO> records = rows.stream()
+                .filter(row -> StringUtils.isNotBlank(row.getModeCode())
+                        && StringUtils.isNotBlank(row.getParticularYear())
+                        && StringUtils.isNotBlank(row.getTimeVersion()))
+                .map(row -> {
+                    SavedPeriodDTO dto = new SavedPeriodDTO();
+                    dto.setSiteCode(SITE_CODE);
+                    dto.setModeCode(row.getModeCode().trim());
+                    dto.setParticularYear(row.getParticularYear().trim());
+                    dto.setTimeVersion(row.getTimeVersion().trim());
+                    dto.setFileName(row.getFileName());
+                    return dto;
+                })
+                .collect(Collectors.toList());
+
+        SavedDataResponseDTO response = client.pushSavedData(records);
+        if (Boolean.TRUE.equals(response.getSkipped())) {
+            log.info("Python 正在抓取上一轮,本次推送被跳过,等待下一次定时推送");
+        } else {
+            log.info("推送已入库期数完成 records={}", records.size());
+        }
+    }
+
+    /**
+     * 拉取完成文件并逐个导入、登记。
+     * @return 本轮成功导入的文件数
+     */
+    public int pullAndImport() {
+        List<CompletedFileDTO> completed = client.listCompletedFiles();
+        if (completed.isEmpty()) {
+            log.info("抓取服务没有已完成文件");
+            return 0;
+        }
+
+        Map<String, Date> registeredAt = registeredFileTimes();
+        List<CompletedFileDTO> pending = completed.stream()
+                .filter(file -> StringUtils.isNotBlank(file.getFileName()))
+                .filter(file -> shouldImport(file, registeredAt))
+                .collect(Collectors.toList());
+        if (pending.isEmpty()) {
+            log.info("已完成文件全部已入库 files={}", completed.size());
+            return 0;
+        }
+        log.info("待导入文件 {} 个(已完成 {},已登记 {})", pending.size(), completed.size(), registeredAt.size());
+
+        int imported = 0;
+        for (CompletedFileDTO file : pending) {
+            try {
+                // 文件名格式不对说明不是本链路产物,跳过但继续处理后面的文件
+                if (parseFileName(file.getFileName()) == null) {
+                    log.warn("跳过不合法的数据文件名 {}", file.getFileName());
+                    continue;
+                }
+                importOne(file.getFileName());
+                imported++;
+            } catch (Exception e) {
+                // 单文件失败即结束本轮:可能数据库异常,继续处理只会扩大影响
+                log.error("导入数据文件失败,本轮结束 fileName={}", file.getFileName(), e);
+                break;
+            }
+        }
+
+        if (imported > 0) {
+            recordService.refreshQueryCache();
+        }
+        log.info("本轮导入完成 files={}", imported);
+        return imported;
+    }
+
+    /** 已登记文件及其登记时间(逻辑删除的行不算)。 */
+    private Map<String, Date> registeredFileTimes() {
+        QueryWrapper<MaterialBoweiyunSaveData> wrapper = new QueryWrapper<>();
+        wrapper.select("file_name", "update_time", "create_time");
+        Map<String, Date> times = new LinkedHashMap<>();
+        for (MaterialBoweiyunSaveData row : saveDataMapper.selectList(wrapper)) {
+            if (StringUtils.isBlank(row.getFileName())) {
+                continue;
+            }
+            Date registeredAt = row.getUpdateTime() != null ? row.getUpdateTime() : row.getCreateTime();
+            times.put(row.getFileName(), registeredAt);
+        }
+        return times;
+    }
+
+    /**
+     * 是否需要在本次导入:没登记过,或文件在登记之后被重新生成。
+     *
+     * 重抓会覆盖同名文件,修改时间晚于登记时间,据此识别"数据被修正过的文件";
+     * 导入成功后登记时间刷新为当前时间,下一轮自然不会重复导入。
+     */
+    private static boolean shouldImport(CompletedFileDTO file, Map<String, Date> registeredAt) {
+        Date lastRegistered = registeredAt.get(file.getFileName());
+        if (lastRegistered == null) {
+            return true;
+        }
+        Date modifiedAt = parseIsoTime(file.getModifiedAt());
+        return modifiedAt != null && modifiedAt.after(lastRegistered);
+    }
+
+    /**
+     * 单个文件:清目录 -> 下载 -> 改名 -> 解析入库 -> 登记 -> 再清目录。
+     *
+     * 本地目录只是下载与解析之间的中转,不是队列;失败时也清空,
+     * 下一轮从头下载。
+     */
+    private void importOne(String fileName) throws Exception {
+        Path dir = localDir();
+        String[] parts = parseFileName(fileName);
+        if (parts == null) {
+            throw new IllegalStateException("不合法的数据文件名: " + fileName);
+        }
+
+        // 进入单个文件前清空目录:崩溃残留的旧文件不能参与本轮解析
+        clearLocalDir(dir);
+        try {
+            File tempFile = dir.resolve(TEMP_FILE_NAME).toFile();
+            long size = client.download(fileName, tempFile);
+
+            File dataFile = dir.resolve(fileName).toFile();
+            try {
+                Files.move(tempFile.toPath(), dataFile.toPath(),
+                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
+            } catch (Exception e) {
+                // 某些文件系统不支持 ATOMIC_MOVE,退化为普通替换(同目录内仍然安全)
+                Files.move(tempFile.toPath(), dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
+            }
+            log.info("下载完成 fileName={} size={}", fileName, size);
+
+            JSONObject meta = readMeta(dataFile, fileName, parts);
+            int rows = importRows(dataFile, meta, fileName);
+            register(parts[0], parts[1], parts[2], fileName, rows);
+            log.info("文件入库并登记完成 fileName={} rows={}", fileName, rows);
+        } finally {
+            // 成功或失败都清空:目录里不保留任何中转文件
+            clearLocalDir(dir);
+        }
+    }
+
+    /**
+     * 读第一行 _meta 并与文件名交叉校验,防止把 A 文件的数据写成 B 期。
+     */
+    private JSONObject readMeta(File dataFile, String fileName, String[] parts) throws Exception {
+        JSONObject meta;
+        try (BufferedReader reader = openReader(dataFile)) {
+            String line = reader.readLine();
+            if (StringUtils.isBlank(line)) {
+                throw new IllegalStateException("数据文件为空: " + fileName);
+            }
+            meta = JSON.parseObject(line);
+        }
+        if (meta == null || !Boolean.TRUE.equals(meta.getBoolean("_meta"))) {
+            throw new IllegalStateException("数据文件缺少 _meta 首行: " + fileName);
+        }
+        Integer fileVersion = meta.getInteger("fileVersion");
+        if (fileVersion == null || fileVersion != SUPPORTED_FILE_VERSION) {
+            throw new IllegalStateException("不认识的文件版本 fileVersion=" + fileVersion + " fileName=" + fileName);
+        }
+        if (!FILE_TYPE.equals(meta.getString("fileType"))) {
+            throw new IllegalStateException("文件类型不匹配 fileType=" + meta.getString("fileType"));
+        }
+        checkMeta(meta, "siteCode", SITE_CODE, fileName);
+        checkMeta(meta, "modeCode", parts[0], fileName);
+        checkMeta(meta, "particularYear", parts[1], fileName);
+        checkMeta(meta, "timeVersion", parts[2], fileName);
+
+        int cappedCount = meta.getIntValue("cappedCount");
+        if (cappedCount > 0) {
+            // 触顶的切片客观取不全,只提示不阻断:数据仍然可用,但统计口径要留意
+            log.warn("文件存在触顶切片 fileName={} cappedCount={} capped={}",
+                    fileName, cappedCount, StrUtil.maxLength(meta.getString("capped"), 1000));
+        }
+        return meta;
+    }
+
+    /** 逐行解析并分批入库;单行解析失败计数后继续,不影响整份文件。 */
+    private int importRows(File dataFile, JSONObject meta, String fileName) throws Exception {
+        String metaMode = meta.getString("modeCode");
+        String metaModeName = StrUtil.blankToDefault(meta.getString("modeName"), MODE_NAMES.get(metaMode));
+        String metaYear = meta.getString("particularYear");
+        String metaVersion = meta.getString("timeVersion");
+
+        int total = 0;
+        int failed = 0;
+        List<MaterialBoweiyunPriceRecord> batch = new ArrayList<>(BATCH_SIZE);
+        Date now = new Date();
+
+        try (BufferedReader reader = openReader(dataFile)) {
+            // 跳过第一行 _meta
+            reader.readLine();
+            String line;
+            while ((line = reader.readLine()) != null) {
+                if (StringUtils.isBlank(line)) {
+                    continue;
+                }
+                total++;
+                MaterialBoweiyunPriceRecord record;
+                try {
+                    record = toRecord(JSON.parseObject(line), metaMode, metaModeName,
+                            metaYear, metaVersion, fileName, now);
+                } catch (Exception e) {
+                    failed++;
+                    log.warn("解析数据行失败 fileName={} row={} reason={}", fileName, total, e.getMessage());
+                    continue;
+                }
+                if (record == null) {
+                    failed++;
+                    continue;
+                }
+                batch.add(record);
+                if (batch.size() >= BATCH_SIZE) {
+                    recordService.upsertBatch(batch);
+                    batch.clear();
+                }
+            }
+            if (!batch.isEmpty()) {
+                recordService.upsertBatch(batch);
+            }
+        }
+
+        int expected = meta.getIntValue("dataLines");
+        if (expected > 0 && expected != total) {
+            log.warn("文件行数与 _meta 不一致 fileName={} dataLines={} actual={}", fileName, expected, total);
+        }
+        log.info("解析完成 fileName={} rows={} failed={}", fileName, total, failed);
+        return total;
+    }
+
+    /**
+     * JSON 行 -> 实体。缺少关键身份字段时返回 null(计入失败),其余字段一律兜底成空串,
+     * 避免显式插入 null 触发 NOT NULL 约束。
+     */
+    private MaterialBoweiyunPriceRecord toRecord(JSONObject obj, String metaMode, String metaModeName,
+                                      String metaYear, String metaVersion, String fileName, Date now) {
+        if (obj == null) {
+            return null;
+        }
+        String modeCode = StrUtil.blankToDefault(obj.getString("modeCode"), metaMode);
+        String materialName = StrUtil.nullToEmpty(obj.getString("materialName")).trim();
+        String particularYear = StrUtil.blankToDefault(obj.getString("particularYear"), metaYear);
+        String timeVersion = StrUtil.blankToDefault(obj.getString("timeVersion"), metaVersion);
+        if (StringUtils.isBlank(modeCode) || StringUtils.isBlank(materialName)
+                || StringUtils.isBlank(particularYear) || StringUtils.isBlank(timeVersion)) {
+            return null;
+        }
+
+        MaterialBoweiyunPriceRecord record = new MaterialBoweiyunPriceRecord();
+        record.setId(IdUtil.fastSimpleUUID());
+        record.setSiteCode(StrUtil.blankToDefault(obj.getString("siteCode"), SITE_CODE));
+        record.setSiteName(StrUtil.blankToDefault(obj.getString("siteName"), SITE_NAME));
+        record.setModeCode(modeCode);
+        record.setModeName(StrUtil.blankToDefault(obj.getString("modeName"), metaModeName));
+        record.setProvince(StrUtil.nullToEmpty(obj.getString("province")));
+        record.setCity(StrUtil.nullToEmpty(obj.getString("city")));
+        record.setFirCatalog(StrUtil.nullToEmpty(obj.getString("firCatalog")));
+        record.setSecoCatalog(StrUtil.nullToEmpty(obj.getString("secoCatalog")));
+        record.setThirdCatalog(StrUtil.nullToEmpty(obj.getString("thirdCatalog")));
+        record.setMaterialName(materialName);
+        record.setOriginalSpec(StrUtil.nullToEmpty(obj.getString("originalSpec")));
+        record.setOriginalUnit(StrUtil.nullToEmpty(obj.getString("originalUnit")));
+        record.setParticularYear(particularYear.trim());
+        record.setTimeVersion(timeVersion.trim());
+        // 接口无值时 Python 写 null,这里保持 null;字符串价格由 BigDecimal 解析,不经过 double
+        record.setTaxFreePrice(obj.getBigDecimal("taxFreePrice"));
+        record.setTaxPrice(obj.getBigDecimal("taxPrice"));
+        record.setMarketValueName(StrUtil.nullToEmpty(obj.getString("marketValueName")));
+        record.setBrand(StrUtil.nullToEmpty(obj.getString("brand")));
+        record.setRemark(StrUtil.nullToEmpty(obj.getString("remark")));
+        record.setSourceUrl(StrUtil.nullToEmpty(obj.getString("sourceUrl")));
+        record.setFileName(fileName);
+        record.setScrapedAt(parseScrapedAt(obj.getString("scrapedAt"), now));
+        // 交给 upsertBatch 校验;缺失或非法时按冻结公式重算
+        record.setDedupeKey(obj.getString("dedupeKey"));
+
+        // 审计字段预填:定时任务线程没有登录态,不能依赖 MyMetaObjectHandler
+        record.setCreateById(SYSTEM_OPERATOR);
+        record.setCreateTime(now);
+        record.setUpdateById(SYSTEM_OPERATOR);
+        record.setUpdateTime(now);
+        record.setDelFlag(0);
+        record.setTenantId(CommonConstants.DEFAULT_TENANT_ID);
+        return record;
+    }
+
+    /** Python 写的是带时区的 ISO8601;解析失败时退回文件级默认时间。 */
+    private static Date parseScrapedAt(String raw, Date fallback) {
+        Date parsed = parseIsoTime(raw);
+        return parsed != null ? parsed : fallback;
+    }
+
+    /** 解析带时区的 ISO8601;不带时区按东八区解释,无法解析返回 null。 */
+    private static Date parseIsoTime(String raw) {
+        if (StringUtils.isBlank(raw)) {
+            return null;
+        }
+        String text = raw.trim();
+        try {
+            return Date.from(OffsetDateTime.parse(text).toInstant());
+        } catch (Exception ignored) {
+            // 不带时区的写法按东八区解释
+        }
+        try {
+            return Date.from(LocalDateTime.parse(text).atZone(CN_ZONE).toInstant());
+        } catch (Exception ignored) {
+            return null;
+        }
+    }
+
+    /** 登记一期:唯一键命中时只刷新文件名、记录条数与更新时间。 */
+    private void register(String modeCode, String particularYear, String timeVersion, String fileName, int rowCount) {
+        Date now = new Date();
+        MaterialBoweiyunSaveData data = new MaterialBoweiyunSaveData();
+        data.setId(IdUtil.fastSimpleUUID());
+        data.setSiteCode(SITE_CODE);
+        data.setSiteName(SITE_NAME);
+        data.setModeCode(modeCode);
+        data.setModeName(MODE_NAMES.getOrDefault(modeCode, modeCode));
+        data.setParticularYear(particularYear);
+        data.setTimeVersion(timeVersion);
+        data.setFileName(fileName);
+        // 记录条数取实际入库行数,与文件名里的条数互为校验
+        data.setRowCount(rowCount);
+        data.setCreateById(SYSTEM_OPERATOR);
+        data.setCreateTime(now);
+        data.setUpdateById(SYSTEM_OPERATOR);
+        data.setUpdateTime(now);
+        data.setDelFlag(0);
+        data.setTenantId(CommonConstants.DEFAULT_TENANT_ID);
+        saveDataMapper.upsert(data);
+    }
+
+    /**
+     * 从文件名反解 [modeCode, year, timeVersion];不合法返回 null。
+     * 与 Python file_store.parse_file_name 保持同一规则:
+     * <site>__<mode>__<year>__<time>__<count>.jsonl.gz;老文件没有 count 段也兼容。
+     */
+    private static String[] parseFileName(String fileName) {
+        String name = StrUtil.nullToEmpty(fileName).trim();
+        if (!name.endsWith(DONE_SUFFIX) || name.contains("/") || name.contains("\\")) {
+            return null;
+        }
+        String base = name.substring(0, name.length() - DONE_SUFFIX.length());
+        String[] parts = base.split("__", -1);
+        if (parts.length == 5) {
+            if (!parts[4].matches("\\d+")) {
+                return null;
+            }
+            parts = Arrays.copyOf(parts, 4);
+        }
+        if (parts.length != 4 || !SITE_CODE.equals(parts[0]) || !MODE_NAMES.containsKey(parts[1])
+                || StringUtils.isBlank(parts[2]) || StringUtils.isBlank(parts[3])) {
+            return null;
+        }
+        return Arrays.copyOfRange(parts, 1, 4);
+    }
+
+    private static void checkMeta(JSONObject meta, String field, String expected, String fileName) {
+        String actual = meta.getString(field);
+        if (!expected.equals(actual)) {
+            throw new IllegalStateException(
+                    "文件名与 _meta 不一致 fileName=" + fileName + " " + field + "=" + actual + " expected=" + expected);
+        }
+    }
+
+    private static BufferedReader openReader(File file) throws Exception {
+        return new BufferedReader(new InputStreamReader(
+                new GZIPInputStream(new FileInputStream(file)), StandardCharsets.UTF_8));
+    }
+
+    private Path localDir() throws Exception {
+        Path dir = Paths.get(scraperProperties.getLocalDir());
+        Files.createDirectories(dir);
+        return dir;
+    }
+
+    /** 删除目录下所有普通文件;不递归子目录(本目录按约定只放中转文件)。 */
+    private static void clearLocalDir(Path dir) {
+        File[] files = dir.toFile().listFiles(File::isFile);
+        if (files == null) {
+            return;
+        }
+        for (File file : files) {
+            if (!file.delete()) {
+                log.warn("清理中转文件失败: {}", file.getAbsolutePath());
+            }
+        }
+    }
+}

+ 475 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/MaterialBoweiyunPriceRecordService.java

@@ -0,0 +1,475 @@
+package com.jeeplus.assess.powerPrice.service;
+
+import cn.hutool.crypto.digest.DigestUtil;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunSaveData;
+import com.jeeplus.assess.powerPrice.domain.MaterialBoweiyunPriceRecord;
+import com.jeeplus.assess.powerPrice.mapper.MaterialBoweiyunSaveDataMapper;
+import com.jeeplus.assess.powerPrice.mapper.MaterialBoweiyunPriceRecordMapper;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPriceModeDTO;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPriceOptionsDTO;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPricePointDTO;
+import com.jeeplus.assess.powerPrice.service.dto.PowerPriceQueryDTO;
+import com.jeeplus.common.redis.RedisUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.annotation.Resource;
+import java.time.LocalDate;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * 电力设备价格的查询与写入服务。
+ *
+ * 查询侧提供分页列表、走势图和下拉选项;写入侧只做幂等 upsert,
+ * 数据由同步服务(BoweiyunDataSyncService)从 Python 数据文件解析后准备。
+ */
+@Slf4j
+@Service
+public class MaterialBoweiyunPriceRecordService extends ServiceImpl<MaterialBoweiyunPriceRecordMapper, MaterialBoweiyunPriceRecord> {
+
+    /** 下拉选项缓存 key:导入新文件后主动重建,不设过期时间;DTO 加字段时升版本避免读到旧缓存 */
+    private static final String OPTIONS_CACHE_KEY = "power-price:options:v2";
+
+    /** 走势最多返回的点数,防止异常查询把图表撑爆 */
+    private static final int HISTORY_LIMIT = 500;
+
+    /** 单条 upsert SQL 的最大行数,避免一次提交的数据包过大 */
+    private static final int SQL_BATCH_SIZE = 250;
+
+    /** 与 Python 一致的空白归一化;UNICODE_CHARACTER_CLASS 让 \s 也匹配全角空格 */
+    private static final Pattern WHITESPACE = Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);
+
+    /** 页签固定顺序与中文名 */
+    private static final Map<String, String> MODE_NAMES = new LinkedHashMap<>();
+
+    static {
+        MODE_NAMES.put("national", "国网信息价");
+        MODE_NAMES.put("quota", "定额站信息价");
+        MODE_NAMES.put("province", "各省信息价");
+        MODE_NAMES.put("market", "市场价");
+    }
+
+    @Resource
+    private RedisUtils redisUtils;
+
+    @Resource
+    private MaterialBoweiyunSaveDataMapper saveDataMapper;
+
+    /**
+     * 分页查询。按导入时间倒序,同一时间导入的记录按主键倒序兜底。
+     *
+     * 两个排序方向都必须是 DESC:与 idx_mbpr_list_time(del_flag, mode_code, create_time, id)
+     * 的最左前缀方向一致时,MySQL 能反向扫索引直接取前 N 行;混用 ASC 会退化成 filesort。
+     */
+    public IPage<MaterialBoweiyunPriceRecord> pageQuery(Page<MaterialBoweiyunPriceRecord> page, PowerPriceQueryDTO query) {
+        QueryWrapper<MaterialBoweiyunPriceRecord> wrapper = new QueryWrapper<>();
+        buildWrapper(query, true, wrapper);
+        wrapper.orderByDesc("create_time").orderByDesc("id");
+        return this.page(page, wrapper);
+    }
+
+    /**
+     * 单物料走势:页签与名称必填,规格/单位/地区由前端按当前行带入,全部精确匹配。
+     *
+     * 不按年份/期数过滤,返回该物料的全部期数;市场价的供应商/品牌不参与条件,
+     * 只用于弹窗展示。按导入时间升序返回,最多 500 个点。
+     */
+    public List<PowerPricePointDTO> history(PowerPriceQueryDTO query) {
+        if (StringUtils.isBlank(query.getModeCode()) || StringUtils.isBlank(query.getMaterialName())) {
+            return Collections.emptyList();
+        }
+        QueryWrapper<MaterialBoweiyunPriceRecord> wrapper = new QueryWrapper<>();
+        wrapper.select("province", "city", "particular_year", "time_version",
+                "tax_free_price", "tax_price", "market_value_name", "scraped_at");
+        buildWrapper(query, false, wrapper);
+        wrapper.orderByAsc("create_time").last("LIMIT " + HISTORY_LIMIT);
+
+        return this.list(wrapper).stream().map(record -> {
+            PowerPricePointDTO point = new PowerPricePointDTO();
+            point.setProvince(record.getProvince());
+            point.setCity(record.getCity());
+            point.setParticularYear(record.getParticularYear());
+            point.setTimeVersion(record.getTimeVersion());
+            point.setTaxFreePrice(record.getTaxFreePrice());
+            point.setTaxPrice(record.getTaxPrice());
+            point.setMarketValueName(record.getMarketValueName());
+            point.setScrapedAt(record.getScrapedAt());
+            return point;
+        }).collect(Collectors.toList());
+    }
+
+    /** 筛选框下拉选项;第一次查询(或 Redis 被清空后)才回源查库。 */
+    public PowerPriceOptionsDTO options() {
+        PowerPriceOptionsDTO cached = readOptionsCache();
+        if (cached != null) {
+            return cached;
+        }
+        PowerPriceOptionsDTO dto = loadOptions();
+        writeOptionsCache(dto);
+        return dto;
+    }
+
+    /**
+     * 导入入库后刷新下拉选项:先查库重建再覆盖,查库失败时保留旧缓存。
+     */
+    public void refreshQueryCache() {
+        PowerPriceOptionsDTO dto;
+        try {
+            dto = loadOptions();
+        } catch (Exception e) {
+            log.warn("导入后重建下拉选项缓存失败,保留旧缓存: {}", e.getMessage());
+            return;
+        }
+        writeOptionsCache(dto);
+    }
+
+    /**
+     * 批量幂等写入。
+     *
+     * 1. 校验 dedupe_key,缺失或非法时按冻结公式重算;
+     * 2. 同一批内按 dedupe_key 去重;
+     * 3. 按 sqlBatchSize 分片执行,避免单条 SQL 过大。
+     *
+     * @return 实际提交给数据库的记录数
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public int upsertBatch(List<MaterialBoweiyunPriceRecord> records) {
+        if (records == null || records.isEmpty()) {
+            return 0;
+        }
+        Map<String, MaterialBoweiyunPriceRecord> unique = new LinkedHashMap<>();
+        for (MaterialBoweiyunPriceRecord record : records) {
+            if (!isValidDedupeKey(record.getDedupeKey())) {
+                record.setDedupeKey(buildDedupeKey(record));
+            }
+            unique.putIfAbsent(record.getDedupeKey(), record);
+        }
+        List<MaterialBoweiyunPriceRecord> list = new ArrayList<>(unique.values());
+        for (int from = 0; from < list.size(); from += SQL_BATCH_SIZE) {
+            int to = Math.min(from + SQL_BATCH_SIZE, list.size());
+            baseMapper.upsertBatch(list.subList(from, to));
+        }
+        return list.size();
+    }
+
+    /** dedupe_key 必须是大写化后仍匹配的 64 位小写十六进制。 */
+    public static boolean isValidDedupeKey(String key) {
+        if (key == null || key.length() != 64) {
+            return false;
+        }
+        for (int i = 0; i < key.length(); i++) {
+            char c = key.charAt(i);
+            if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * 按冻结公式重算 dedupe_key(与 Python app/power/dedupe.py 保持一致):
+     * sha256(site \u001f mode \u001f province \u001f city \u001f year \u001f version \u001f name \u001f spec \u001f unit)。
+     * 名称/规格/单位压缩连续空白,其余字段只 trim。
+     */
+    public static String buildDedupeKey(MaterialBoweiyunPriceRecord record) {
+        // Java 字符串没有 \x 转义,单元分隔符 0x1F 必须写成 \u001f
+        String raw = String.join("\u001f",
+                "boweiyun",
+                trim(record.getModeCode()),
+                trim(record.getProvince()),
+                trim(record.getCity()),
+                trim(record.getParticularYear()),
+                trim(record.getTimeVersion()),
+                normalizeText(record.getMaterialName()),
+                normalizeText(record.getOriginalSpec()),
+                normalizeText(record.getOriginalUnit()));
+        return DigestUtil.sha256Hex(raw);
+    }
+
+    private static String trim(String value) {
+        return value == null ? "" : value.trim();
+    }
+
+    private static String normalizeText(String value) {
+        return value == null ? "" : WHITESPACE.matcher(value.trim()).replaceAll(" ");
+    }
+
+    /**
+     * 组装查询条件。空字符串一律忽略。
+     *
+     * @param fuzzyName true=名称模糊匹配(列表);false=名称/规格/单位精确匹配(走势)
+     */
+    private void buildWrapper(PowerPriceQueryDTO query, boolean fuzzyName, QueryWrapper<MaterialBoweiyunPriceRecord> wrapper) {
+        wrapper.in(!splitValues(query.getModeCode()).isEmpty(), "mode_code", splitValues(query.getModeCode()));
+        wrapper.in(!splitValues(query.getProvince()).isEmpty(), "province", splitValues(query.getProvince()));
+        wrapper.in(!splitValues(query.getCity()).isEmpty(), "city", splitValues(query.getCity()));
+        wrapper.in(!splitValues(query.getParticularYear()).isEmpty(),
+                "particular_year", splitValues(query.getParticularYear()));
+        wrapper.in(!splitValues(query.getTimeVersion()).isEmpty(),
+                "time_version", splitValues(query.getTimeVersion()));
+        wrapper.in(!splitValues(query.getFirCatalog()).isEmpty(),
+                "fir_catalog", splitValues(query.getFirCatalog()));
+        wrapper.in(!splitValues(query.getSecoCatalog()).isEmpty(),
+                "seco_catalog", splitValues(query.getSecoCatalog()));
+
+        if (StringUtils.isNotBlank(query.getMaterialName())) {
+            if (fuzzyName) {
+                wrapper.like("material_name", query.getMaterialName().trim());
+            } else {
+                wrapper.eq("material_name", query.getMaterialName().trim());
+            }
+        }
+        if (StringUtils.isNotBlank(query.getOriginalSpec())) {
+            wrapper.eq("original_spec", query.getOriginalSpec().trim());
+        }
+        if (StringUtils.isNotBlank(query.getOriginalUnit())) {
+            wrapper.eq("original_unit", query.getOriginalUnit().trim());
+        }
+
+        // 导入日期区间必须成对出现;结束日补到 23:59:59,避免只查到 0 点
+        String[] dates = query.getCreateDates();
+        if (dates != null && dates.length == 2
+                && StringUtils.isNotBlank(dates[0]) && StringUtils.isNotBlank(dates[1])) {
+            String start = normalizeDay(dates[0], " 00:00:00");
+            String end = normalizeDay(dates[1], " 23:59:59");
+            if (start != null && end != null) {
+                wrapper.between("create_time", start, end);
+            }
+        }
+    }
+
+    /** 校验 yyyy-MM-dd 并拼上时间部分;非法日期返回 null(条件忽略)。 */
+    private static String normalizeDay(String raw, String timeSuffix) {
+        String text = raw == null ? "" : raw.trim();
+        if (text.length() >= 10) {
+            text = text.substring(0, 10);
+        }
+        try {
+            LocalDate.parse(text);
+        } catch (DateTimeParseException e) {
+            return null;
+        }
+        return text + timeSuffix;
+    }
+
+    private static List<String> splitValues(String raw) {
+        if (StringUtils.isBlank(raw)) {
+            return Collections.emptyList();
+        }
+        return Arrays.stream(raw.split(","))
+                .map(String::trim)
+                .filter(StringUtils::isNotBlank)
+                .distinct()
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * 回源查询下拉选项。
+     *
+     * 页签/年份/期数从登记表查(行数很少);地区、一级/二级分类从价格表查去重组合,
+     * 地区只取三列走 idx_mbpr_list,分类只取四列走 idx_mbpr_catalog,不扫整行。
+     */
+    private PowerPriceOptionsDTO loadOptions() {
+        QueryWrapper<MaterialBoweiyunSaveData> registryWrapper = new QueryWrapper<>();
+        registryWrapper.select("DISTINCT mode_code, mode_name, particular_year, time_version");
+        List<Map<String, Object>> registryRows = saveDataMapper.selectMaps(registryWrapper);
+
+        QueryWrapper<MaterialBoweiyunPriceRecord> geoWrapper = new QueryWrapper<>();
+        geoWrapper.select("DISTINCT mode_code, province, city");
+        List<Map<String, Object>> geoRows = baseMapper.selectMaps(geoWrapper);
+
+        // 分类下拉:一级/二级成对去重,走 idx_mbpr_catalog;三级分类不参与筛选
+        QueryWrapper<MaterialBoweiyunPriceRecord> catalogWrapper = new QueryWrapper<>();
+        catalogWrapper.select("DISTINCT mode_code, fir_catalog, seco_catalog");
+        List<Map<String, Object>> catalogRows = baseMapper.selectMaps(catalogWrapper);
+
+        Set<String> provinces = new TreeSet<>();
+        Map<String, Set<String>> citySets = new TreeMap<>();
+        Map<String, Set<String>> modeProvinceSets = new TreeMap<>();
+        Map<String, Map<String, Set<String>>> modeCitySets = new TreeMap<>();
+
+        for (Map<String, Object> row : geoRows) {
+            String mode = stringValue(row, "mode_code").trim();
+            String province = stringValue(row, "province").trim();
+            String city = stringValue(row, "city").trim();
+            if (StringUtils.isBlank(province)) {
+                continue;
+            }
+            provinces.add(province);
+            if (StringUtils.isNotBlank(mode)) {
+                modeProvinceSets.computeIfAbsent(mode, key -> new TreeSet<>()).add(province);
+            }
+            if (StringUtils.isNotBlank(city)) {
+                citySets.computeIfAbsent(province, key -> new TreeSet<>()).add(city);
+                if (StringUtils.isNotBlank(mode)) {
+                    modeCitySets.computeIfAbsent(mode, key -> new TreeMap<>())
+                            .computeIfAbsent(province, key -> new TreeSet<>()).add(city);
+                }
+            }
+        }
+
+        Set<String> years = new TreeSet<>(Comparator.reverseOrder());
+        Map<String, Map<String, Set<String>>> versionSets = new TreeMap<>();
+        for (Map<String, Object> row : registryRows) {
+            String mode = stringValue(row, "mode_code").trim();
+            String year = stringValue(row, "particular_year").trim();
+            String version = stringValue(row, "time_version").trim();
+            if (StringUtils.isNotBlank(year)) {
+                years.add(year);
+            }
+            if (StringUtils.isNotBlank(mode) && StringUtils.isNotBlank(year) && StringUtils.isNotBlank(version)) {
+                versionSets.computeIfAbsent(mode, key -> new TreeMap<>(Comparator.reverseOrder()))
+                        .computeIfAbsent(year, key -> new TreeSet<>(VERSION_COMPARATOR)).add(version);
+            }
+        }
+
+        // 分类层级:一级去重;二级挂在一级下;再按页签各存一份,供前端本地级联
+        Set<String> firCatalogs = new TreeSet<>();
+        Map<String, Set<String>> secoSets = new TreeMap<>();
+        Map<String, Set<String>> modeFirSets = new TreeMap<>();
+        Map<String, Map<String, Set<String>>> modeFirSecoSets = new TreeMap<>();
+        for (Map<String, Object> row : catalogRows) {
+            String mode = stringValue(row, "mode_code").trim();
+            String fir = stringValue(row, "fir_catalog").trim();
+            String seco = stringValue(row, "seco_catalog").trim();
+            if (StringUtils.isBlank(fir)) {
+                continue;
+            }
+            firCatalogs.add(fir);
+            if (StringUtils.isNotBlank(seco)) {
+                secoSets.computeIfAbsent(fir, key -> new TreeSet<>()).add(seco);
+            }
+            if (StringUtils.isNotBlank(mode)) {
+                modeFirSets.computeIfAbsent(mode, key -> new TreeSet<>()).add(fir);
+                if (StringUtils.isNotBlank(seco)) {
+                    modeFirSecoSets.computeIfAbsent(mode, key -> new TreeMap<>())
+                            .computeIfAbsent(fir, key -> new TreeSet<>()).add(seco);
+                }
+            }
+        }
+
+        PowerPriceOptionsDTO dto = new PowerPriceOptionsDTO();
+        dto.setModes(MODE_NAMES.entrySet().stream()
+                .map(entry -> new PowerPriceModeDTO(entry.getKey(), entry.getValue()))
+                .collect(Collectors.toList()));
+        dto.setProvinces(new ArrayList<>(provinces));
+        dto.setCitiesByProvince(toListMap(citySets));
+        dto.setProvincesByMode(toListMap(modeProvinceSets));
+
+        Map<String, Map<String, List<String>>> citiesByModeProvince = new TreeMap<>();
+        modeCitySets.forEach((mode, byProvince) -> citiesByModeProvince.put(mode, toListMap(byProvince)));
+        dto.setCitiesByModeProvince(citiesByModeProvince);
+
+        dto.setYears(new ArrayList<>(years));
+
+        Map<String, Map<String, List<String>>> versions = new TreeMap<>();
+        versionSets.forEach((mode, byYear) -> {
+            Map<String, List<String>> target = new LinkedHashMap<>();
+            byYear.forEach((year, values) -> target.put(year, new ArrayList<>(values)));
+            versions.put(mode, target);
+        });
+        dto.setTimeVersionsByModeYear(versions);
+
+        dto.setFirCatalogs(new ArrayList<>(firCatalogs));
+        dto.setSecoCatalogsByFir(toListMap(secoSets));
+        dto.setFirCatalogsByMode(toListMap(modeFirSets));
+
+        Map<String, Map<String, List<String>>> secoByModeFir = new TreeMap<>();
+        modeFirSecoSets.forEach((mode, byFir) -> secoByModeFir.put(mode, toListMap(byFir)));
+        dto.setSecoCatalogsByModeFir(secoByModeFir);
+        return dto;
+    }
+
+    /**
+     * 期数排序:月份按数字升序,季度/半年/全年按自然顺序插在对应位置。
+     * 不同页签的期数不会混在同一列表里,这里只需保证同一页签内顺序合理。
+     */
+    private static final Comparator<String> VERSION_COMPARATOR = (left, right) -> {
+        int rankCompare = Integer.compare(versionRank(left), versionRank(right));
+        return rankCompare != 0 ? rankCompare : left.compareTo(right);
+    };
+
+    private static int versionRank(String version) {
+        String text = version == null ? "" : version.trim();
+        switch (text) {
+            case "上半年":
+                return 25;
+            case "一季度":
+                return 21;
+            case "二季度":
+                return 22;
+            case "三季度":
+                return 23;
+            case "四季度":
+                return 24;
+            case "下半年":
+                return 27;
+            case "全年":
+                return 30;
+            default:
+                break;
+        }
+        if (text.matches("\\d{1,2}")) {
+            return Integer.parseInt(text);
+        }
+        return 100;
+    }
+
+    private static Map<String, List<String>> toListMap(Map<String, Set<String>> source) {
+        Map<String, List<String>> target = new TreeMap<>();
+        source.forEach((key, values) -> target.put(key, new ArrayList<>(values)));
+        return target;
+    }
+
+    private PowerPriceOptionsDTO readOptionsCache() {
+        try {
+            Object value = redisUtils.get(OPTIONS_CACHE_KEY);
+            return value instanceof PowerPriceOptionsDTO ? (PowerPriceOptionsDTO) value : null;
+        } catch (Exception e) {
+            // 缓存里可能是旧版本 DTO,反序列化失败时清掉并回源
+            log.warn("读取下拉选项缓存失败,改为直接查询: {}", e.getMessage());
+            try {
+                redisUtils.delete(OPTIONS_CACHE_KEY);
+            } catch (Exception ignored) {
+                // 清缓存失败不影响本次查询
+            }
+            return null;
+        }
+    }
+
+    private void writeOptionsCache(PowerPriceOptionsDTO dto) {
+        try {
+            redisUtils.set(OPTIONS_CACHE_KEY, dto);
+        } catch (Exception e) {
+            log.warn("写入下拉选项缓存失败: {}", e.getMessage());
+        }
+    }
+
+    /** selectMaps 的 key 大小写依赖驱动,这里做不区分大小写的取值。 */
+    private static String stringValue(Map<String, Object> row, String column) {
+        for (Map.Entry<String, Object> entry : row.entrySet()) {
+            if (column.equalsIgnoreCase(entry.getKey())) {
+                return entry.getValue() == null ? "" : String.valueOf(entry.getValue());
+            }
+        }
+        return "";
+    }
+}

+ 20 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceModeDTO.java

@@ -0,0 +1,20 @@
+package com.jeeplus.assess.powerPrice.service.dto;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.io.Serializable;
+
+/** 页签选项:编码 + 中文名。 */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class PowerPriceModeDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private String code;
+
+    private String name;
+}

+ 52 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceOptionsDTO.java

@@ -0,0 +1,52 @@
+package com.jeeplus.assess.powerPrice.service.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 前端筛选框的下拉选项。
+ *
+ * 一次把页签、地区、年份、期数、分类查全并在 Java 里分组,前端切换条件时在本地级联,
+ * 不再回后端;结果常驻 Redis,导入新文件后由 refreshQueryCache 覆盖。
+ */
+@Data
+public class PowerPriceOptionsDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 页签,固定四个,按 国网/定额站/各省/市场价 排序 */
+    private List<PowerPriceModeDTO> modes;
+
+    /** 省份(去重、排序) */
+    private List<String> provinces;
+
+    /** 省份 -> 城市;没有城市的数据不出现 */
+    private Map<String, List<String>> citiesByProvince;
+
+    /** 页签 -> 该页签下出现过的省份,用于「选了页签收窄省份」 */
+    private Map<String, List<String>> provincesByMode;
+
+    /** 页签 -> 省份 -> 城市,用于「页签 + 省份收窄城市」 */
+    private Map<String, Map<String, List<String>>> citiesByModeProvince;
+
+    /** 年份,倒序(最新在前) */
+    private List<String> years;
+
+    /** 页签 -> 年份 -> 期数,用于「选了页签和年份后再选期数」 */
+    private Map<String, Map<String, List<String>>> timeVersionsByModeYear;
+
+    /** 设备一级分类(去重、排序) */
+    private List<String> firCatalogs;
+
+    /** 一级分类 -> 二级分类,用于「选了二级分类后收窄」 */
+    private Map<String, List<String>> secoCatalogsByFir;
+
+    /** 页签 -> 该页签下出现过的一级分类,用于「选了页签收窄一级分类」 */
+    private Map<String, List<String>> firCatalogsByMode;
+
+    /** 页签 -> 一级分类 -> 二级分类,用于「页签 + 一级分类收窄二级分类」 */
+    private Map<String, Map<String, List<String>>> secoCatalogsByModeFir;
+}

+ 38 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPricePointDTO.java

@@ -0,0 +1,38 @@
+package com.jeeplus.assess.powerPrice.service.dto;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.Date;
+
+/**
+ * 走势图上的一个价格点。
+ *
+ * 同一物料在不同期数各一个点;含税/不含税两条线由前端按非空字段动态绘制。
+ * 省份/城市一并返回,便于前端在没有筛选地区时区分数据来源。
+ */
+@Data
+public class PowerPricePointDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private String province;
+
+    private String city;
+
+    private String particularYear;
+
+    private String timeVersion;
+
+    private BigDecimal taxFreePrice;
+
+    private BigDecimal taxPrice;
+
+    private String marketValueName;
+
+    /** 采集时间,用于同一年份/期数下的排序提示 */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
+    private Date scrapedAt;
+}

+ 53 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/powerPrice/service/dto/PowerPriceQueryDTO.java

@@ -0,0 +1,53 @@
+package com.jeeplus.assess.powerPrice.service.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 电力设备价格查询条件,列表与走势共用。
+ *
+ * 页签/省份/城市/年份/期数支持逗号分隔的多个值(同名参数重复传也会被 Spring 拼成 A,B);
+ * 名称在列表中模糊匹配,走势图要求精确匹配。
+ */
+@Data
+public class PowerPriceQueryDTO implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /** 页签编码:national / quota / province / market */
+    private String modeCode;
+
+    /** 省份 */
+    private String province;
+
+    /** 城市;国网之外没有城市的数据该字段为空串 */
+    private String city;
+
+    /** 年份,如 2025 */
+    private String particularYear;
+
+    /** 期数,如 10、二季度、全年 */
+    private String timeVersion;
+
+    /** 物料/设备名称,列表模糊匹配,走势图精确匹配 */
+    private String materialName;
+
+    /** 设备一级分类,需与二级分类配合使用(二级只在选定一级下才有意义) */
+    private String firCatalog;
+
+    /** 设备二级分类 */
+    private String secoCatalog;
+
+    /** 规格型号,列表与走势图都精确匹配;列表要求同时传名称 */
+    private String originalSpec;
+
+    /** 单位,走势图精确匹配 */
+    private String originalUnit;
+
+    /**
+     * 导入日期区间 [开始, 结束],由前端 daterange 序列化成 createDates[0]/createDates[1],
+     * 两个值都存在时才按 create_time 过滤。
+     */
+    private String[] createDates;
+}

+ 26 - 0
jeeplus-modules/jeeplus-assess/src/main/java/com/jeeplus/assess/scraper/config/ScraperProperties.java

@@ -0,0 +1,26 @@
+package com.jeeplus.assess.scraper.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+/**
+ * Python 价格抓取服务(xg_material_scraper)的公共配置,对应 application-assess.yml 的 scraper.*。
+ *
+ * 物料价格与电力设备价格请求的是同一个 Python 服务,地址和密钥只保留一份,
+ * 两个模块的客户端都从这里读取,避免配置漂移。
+ */
+@Data
+@Component
+@ConfigurationProperties(prefix = "scraper")
+public class ScraperProperties {
+
+    /** Python 抓取服务地址 */
+    private String baseUrl = "http://127.0.0.1:8100";
+
+    /** 与 Python 的 SCRAPER_API_KEY 保持一致 */
+    private String apiKey = "dev-key-change-me";
+
+    /** 电力价格下载中转目录:只放 download.tmp 与当前入库文件,处理完即清空 */
+    private String localDir = System.getProperty("java.io.tmpdir") + "/bowei-scraperdata";
+}

+ 8 - 7
jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-development.yml

@@ -68,10 +68,11 @@ INQUIRE_STATUS: ccpm
 
 CAS_PATH: http://www.casserver.com:8443
 
-# ==================== 物料价格采集 ====================
-material-price:
-  scraper:
-    # 抓取服务地址
-    base-url: http://127.0.0.1:8100
-    # 与 Python 的 SCRAPER_API_KEY 保持一致
-    api-key: dev-key-change-me
+# ==================== 价格抓取服务(物料 + 电力共用同一个 Python 服务) ====================
+scraper:
+  # 抓取服务地址
+  base-url: http://127.0.0.1:8100
+  # 与 Python 的 SCRAPER_API_KEY 保持一致
+  api-key: dev-key-change-me
+  # 电力价格下载中转目录:只放 download.tmp 与当前入库文件,处理完即清空
+  local-dir: ${java.io.tmpdir}/bowei-scraperdata

+ 8 - 7
jeeplus-modules/jeeplus-assess/src/main/resources/application-assess-production.yml

@@ -56,10 +56,11 @@ signature_daily_office_work: 3206161416121062057
 #评估-报告签章流程id
 signature_report_caregory_id: 3206161481749336766
 
-# ==================== 物料价格采集 ====================
-material-price:
-  scraper:
-    # 抓取服务地址
-    base-url: http://127.0.0.1:8100
-    # 与 Python 的 SCRAPER_API_KEY 保持一致
-    api-key: dev-key-change-me
+# ==================== 价格抓取服务(物料 + 电力共用同一个 Python 服务) ====================
+scraper:
+  # 抓取服务地址(按实际部署修改)
+  base-url: http://127.0.0.1:8100
+  # 与 Python 的 SCRAPER_API_KEY 保持一致,生产环境用环境变量覆盖
+  api-key: ${SCRAPER_API_KEY:dev-key-change-me}
+  # 电力价格下载中转目录:只放 download.tmp 与当前入库文件,处理完即清空;
+  local-dir: ${POWER_LOCAL_DIR:${java.io.tmpdir}/bowei-scraperdata}

+ 80 - 0
jeeplus-modules/jeeplus-xxl-job-executor-sample/src/main/java/com/xxl/job/executor/service/jobhandler/BoweiyunPriceJob.java

@@ -0,0 +1,80 @@
+package com.xxl.job.executor.service.jobhandler;
+
+import cn.hutool.extra.spring.SpringUtil;
+import com.alibaba.fastjson.JSON;
+import com.xxl.job.core.context.XxlJobHelper;
+import com.xxl.job.core.handler.annotation.XxlJob;
+import com.xxl.job.executor.feign.AssessFeignApi;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+/**
+ * 博微电力价格的两条月度链路,调度时间在 XXL 任务管理里配置:
+ *
+ * - boweiyunPushSavedDataJob(每月 2 日 23:00,cron 0 0 23 2 * ?):推送已入库期数快照,
+ *   Python 收到后算缺口并在后台抓取;
+ * - boweiyunPullImportJob(每月 5 日 23:00,cron 0 0 23 5 * ?):拉取 Python 已完成文件并导入
+ *   (下载 + 入库,耗时长)。
+ *
+ * 失败语义:
+ * - code != 200(assess 不可用 / 链路异常)→ handleFail,由 XXL 按配置重试并告警;
+ * - code = 200 且 skipped = true → 只打 WARN,说明另一实例正持有 Redis 锁,不算失败。
+ */
+@Component
+public class BoweiyunPriceJob {
+
+    private static final Logger logger = LoggerFactory.getLogger(BoweiyunPriceJob.class);
+
+    /** 推送已入库期数快照:本身是秒级操作,抓取由 Python 后台执行 */
+    @XxlJob("boweiyunPushSavedDataJob")
+    public void pushSavedDataJob() {
+        XxlJobHelper.log("开始推送博微已入库期数快照");
+        try {
+            Map<String, Object> result = SpringUtil.getBean(AssessFeignApi.class).pushBoweiyunSavedData();
+            XxlJobHelper.log("推送结果: {}", JSON.toJSONString(result));
+            if (result == null) {
+                XxlJobHelper.handleFail("assess 无响应");
+                return;
+            }
+            if (!"200".equals(String.valueOf(result.get("code")))) {
+                XxlJobHelper.handleFail("推送失败: " + JSON.toJSONString(result));
+                return;
+            }
+            if (Boolean.TRUE.equals(result.get("skipped"))) {
+                XxlJobHelper.log("WARN 另一实例正在执行推送,本次跳过");
+            }
+        } catch (Exception e) {
+            logger.error("博微推送任务异常", e);
+            XxlJobHelper.log(e);
+            XxlJobHelper.handleFail("推送异常: " + e.getMessage());
+        }
+    }
+
+    /** 拉取 Python 已完成文件并入库:耗时取决于缺口文件数,超时时间建议填 0(不限) */
+    @XxlJob("boweiyunPullImportJob")
+    public void pullImportJob() {
+        XxlJobHelper.log("开始拉取博微完成文件并导入");
+        try {
+            Map<String, Object> result = SpringUtil.getBean(AssessFeignApi.class).pullBoweiyunCompletedFiles();
+            XxlJobHelper.log("导入结果: {}", JSON.toJSONString(result));
+            if (result == null) {
+                XxlJobHelper.handleFail("assess 无响应");
+                return;
+            }
+            if (!"200".equals(String.valueOf(result.get("code")))) {
+                XxlJobHelper.handleFail("导入失败: " + JSON.toJSONString(result));
+                return;
+            }
+            if (Boolean.TRUE.equals(result.get("skipped"))) {
+                XxlJobHelper.log("WARN 另一实例正在执行导入,本次跳过");
+            }
+        } catch (Exception e) {
+            logger.error("博微拉取导入任务异常", e);
+            XxlJobHelper.log(e);
+            XxlJobHelper.handleFail("导入异常: " + e.getMessage());
+        }
+    }
+}