| | |
| | | import java.math.RoundingMode; |
| | | import java.text.DecimalFormat; |
| | | import java.time.*; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | |
| | | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; |
| | |
| | | import com.ruoyi.chargingPile.api.model.TChargingGun; |
| | | import com.ruoyi.chargingPile.api.model.TChargingPile; |
| | | import com.ruoyi.chargingPile.api.model.TParkingRecord; |
| | | import com.ruoyi.chargingPile.api.model.TPartnerAppUser; |
| | | import com.ruoyi.chargingPile.api.vo.GetChargingGunByChargingPileIdsVo; |
| | | import com.ruoyi.common.core.domain.R; |
| | | import com.ruoyi.common.core.dto.ChargingOrderGroup; |
| | |
| | | import com.ruoyi.common.core.web.domain.AjaxResult; |
| | | import com.ruoyi.common.core.web.page.PageInfo; |
| | | import com.ruoyi.order.api.dto.ChargingStatisticeDTO; |
| | | import com.ruoyi.order.api.dto.DeviceStartChargingDTO; |
| | | import com.ruoyi.order.api.model.*; |
| | | import com.ruoyi.order.api.query.ChargingOrderQuery; |
| | | import com.ruoyi.common.core.dto.MongoChargingOrderQuery; |
| | |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.*; |
| | | import java.util.List; |
| | | import java.util.concurrent.CompletableFuture; |
| | | import java.util.concurrent.ExecutorService; |
| | | import java.util.concurrent.Executors; |
| | | import java.util.stream.Collectors; |
| | | |
| | | import com.ruoyi.common.core.utils.DateUtils; |
| | |
| | | |
| | | @Resource |
| | | private TChargingOrderService chargingOrderService; |
| | | @Resource |
| | | private TCardChargingOrderService cardChargingOrderService; |
| | | @Resource |
| | | private TVinChargingOrderService vinChargingOrderService; |
| | | @Autowired |
| | | private TokenService tokenService; |
| | | @Autowired |
| | |
| | | @Resource |
| | | private TChargingOrderMapper chargingOrderMapper; |
| | | |
| | | /** 尖峰平谷反查时分块 IN 的上限,避免超大 IN 触发 MyCat 读超时。 */ |
| | | private static final int PHASE_ID_BATCH_SIZE = 5000; |
| | | /** 尖峰平谷反查分块 id 上限:MyCat/druid 对 IN 列表的解析路由成本随 id 数非线性增长 |
| | | * (实测 500 个约 5s、5000 个 70s+ 触发读超时;100 个内约 0.2s/块,约 2ms/个)。 */ |
| | | private static final int PHASE_ID_BATCH_SIZE = 100; |
| | | /** 尖峰平谷分块反查并发度:46k id 实测 ~20s,典型加盟商 <3s(串行 5000/块 >70s 读超时)。 */ |
| | | private static final ExecutorService PHASE_QUERY_EXECUTOR = Executors.newFixedThreadPool(16); |
| | | |
| | | @GetMapping("/reservationRecommendation") |
| | | @ApiOperation(value = "获取站点预约充电推荐时段", tags = {"管理后台-充电桩信息"}) |
| | |
| | | List<Integer> siteIds = franchiseeSiteIds(params); |
| | | LocalDateTime[] range = franchiseeRange(params); |
| | | List<FranchiseeDayStat> dayStats = franchiseeDayStats(siteIds, range); |
| | | List<Map<String, Object>> managementOrderStats = franchiseeManagementOrderStats(siteIds, range); |
| | | Map<String, Object> summary = new LinkedHashMap<>(); |
| | | summary.put("orderAmountWan", sum(dayStats, FranchiseeDayStat::getOrderAmount).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP)); |
| | | BigDecimal incomeWan = franchiseeIncomeWan(dayStats); |
| | | BigDecimal totalChargingCapacityWan = sum(dayStats, FranchiseeDayStat::getCapacity).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP); |
| | | summary.put("incomeWan", incomeWan); |
| | | summary.put("orderAmountWan", incomeWan); |
| | | summary.put("serviceFeeWan", sum(dayStats, FranchiseeDayStat::getServiceFee).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP)); |
| | | summary.put("chargingPowerWan", sum(dayStats, FranchiseeDayStat::getCapacity).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP)); |
| | | summary.put("chargingAmount", sum(dayStats, FranchiseeDayStat::getPaymentAmount)); |
| | | summary.put("chargingOrderCount", dayStats.stream().mapToLong(stat -> numberValue(stat.getOrderCount())).sum()); |
| | | summary.put("totalChargingCapacityWan", totalChargingCapacityWan); |
| | | summary.put("chargingPowerWan", totalChargingCapacityWan); |
| | | summary.put("chargingAmount", sumManagementOrderField(managementOrderStats, "paymoney")); |
| | | summary.put("chargingOrderCount", sumManagementOrderField(managementOrderStats, "orderCount").longValue()); |
| | | summary.put("powerUtilizationRate", observedPowerUtilization(dayStats)); |
| | | summary.put("demandPowerSatisfactionRate", demandPowerSatisfaction(dayStats)); |
| | | Map<String, Object> result = new LinkedHashMap<>(); |
| | | result.put("summary", summary); |
| | | result.put("keyDataLine", franchiseeDailyTrend(dayStats, range, "订单金额", FranchiseeDayStat::getOrderAmountEffective)); |
| | | result.put("keyDataLine", franchiseeDailyTrend(dayStats, range, "收入合计", FranchiseeDayStat::getChargingIncome)); |
| | | result.put("keyDataRing", franchiseePhaseRing(siteIds, range)); |
| | | result.put("orderStats", franchiseeOrderTrend(dayStats, range)); |
| | | result.put("orderStats", franchiseeManagementOrderTrend(managementOrderStats)); |
| | | result.put("efficiency", franchiseeEfficiencyTrend(dayStats, range)); |
| | | result.put("powerDistribution", franchiseePowerDistribution(siteIds, range)); |
| | | return R.ok(result); |
| | |
| | | @PostMapping("/app/franchisee/income") |
| | | public R<Map<String, Object>> franchiseeIncome(@RequestBody(required = false) Map<String, Object> params) { |
| | | List<Integer> siteIds = franchiseeSiteIds(params); |
| | | LocalDate firstMonth = YearMonth.now().minusMonths(5).atDay(1); |
| | | LocalDate nextMonth = YearMonth.now().plusMonths(1).atDay(1); |
| | | List<FranchiseeDayStat> dayStats = franchiseeDayStats(siteIds, |
| | | new LocalDateTime[]{firstMonth.atStartOfDay(), nextMonth.atStartOfDay()}); |
| | | List<SixChargingDto> sixChargingDtos; |
| | | if (siteIds.isEmpty()) { |
| | | // 无授权站点:返回近6月全零骨架,避免空 IN 导致全站点统计 |
| | | sixChargingDtos = generateLastSixMonths(LocalDate.now()); |
| | | } else { |
| | | // 与后台 数据分析-平台总收入分析 电站收入分析口径一致:历史月读结算账单、当月补原始订单 |
| | | LocalDate sixBefore = PreviousSixMonths.get(); |
| | | List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, false); |
| | | LocalDate statisticsEndMonth = resolveStatisticsEndMonth(LocalDate.now(), chargingDtos); |
| | | sixChargingDtos = generateLastSixMonths(statisticsEndMonth); |
| | | for (SixChargingDto sixChargingDto : sixChargingDtos) { |
| | | for (SixChargingDto chargingDto : chargingDtos) { |
| | | if (sixChargingDto.getMonth().equals(chargingDto.getMonth())) { |
| | | BeanUtils.copyProperties(chargingDto, sixChargingDto); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | BigDecimal electricity = sixChargingDtos.stream() |
| | | .filter(Objects::nonNull) |
| | | .map(SixChargingDto::getElectrovalence) |
| | | .filter(Objects::nonNull) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add); |
| | | BigDecimal service = sixChargingDtos.stream() |
| | | .filter(Objects::nonNull) |
| | | .map(SixChargingDto::getServiceCharge) |
| | | .filter(Objects::nonNull) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add); |
| | | Map<String, Object> result = new LinkedHashMap<>(); |
| | | result.put("totalIncome", sum(dayStats, FranchiseeDayStat::getPaymentAmount)); |
| | | result.put("electricityFee", sum(dayStats, FranchiseeDayStat::getElectrovalence)); |
| | | result.put("serviceFee", sum(dayStats, FranchiseeDayStat::getServiceFee)); |
| | | result.put("incomeColumn", franchiseeIncomeTrend(dayStats, firstMonth, 6)); |
| | | List<Map<String, Object>> incomePie = new ArrayList<>(); |
| | | Map<String, Object> electricityItem = new LinkedHashMap<>(); |
| | | electricityItem.put("name", "充电费"); |
| | | electricityItem.put("value", sum(dayStats, FranchiseeDayStat::getElectrovalence)); |
| | | incomePie.add(electricityItem); |
| | | Map<String, Object> serviceItem = new LinkedHashMap<>(); |
| | | serviceItem.put("name", "服务费"); |
| | | serviceItem.put("value", sum(dayStats, FranchiseeDayStat::getServiceFee)); |
| | | incomePie.add(serviceItem); |
| | | result.put("incomePie", incomePie); |
| | | result.put("totalIncome", electricity.add(service)); |
| | | result.put("electricityFee", electricity); |
| | | result.put("serviceFee", service); |
| | | result.put("incomeColumn", franchiseeIncomeTrendFromSix(sixChargingDtos)); |
| | | // 电站收入占比:口径与后台 /six/circle 一致(近6月结算账单按站点分组,电费+服务费-三方佣金) |
| | | result.put("incomePie", franchiseeIncomePieBySite(siteIds)); |
| | | return R.ok(result); |
| | | } |
| | | |
| | | /** 加盟商看板"电站收入占比":复用 /six/circle 统计口径,按金额降序返回站点占比列表 */ |
| | | private List<Map<String, Object>> franchiseeIncomePieBySite(List<Integer> siteIds) { |
| | | List<Map<String, Object>> incomePie = new ArrayList<>(); |
| | | if (siteIds == null || siteIds.isEmpty()) { |
| | | return incomePie; |
| | | } |
| | | List<SixCircleDto> circleDtos = chargingOrderService.circle(siteIds, PreviousSixMonths.get(), false); |
| | | if (circleDtos == null || circleDtos.isEmpty()) { |
| | | return incomePie; |
| | | } |
| | | // 站点名批量映射,避免逐个远程调用 |
| | | Map<Integer, String> siteNameMap = new HashMap<>(); |
| | | R<List<Site>> siteResult = siteClient.getSiteAll(); |
| | | List<Site> sites = siteResult == null ? null : siteResult.getData(); |
| | | if (sites != null) { |
| | | for (Site site : sites) { |
| | | if (site != null && site.getId() != null) { |
| | | siteNameMap.put(site.getId(), site.getName()); |
| | | } |
| | | } |
| | | } |
| | | circleDtos.sort((a, b) -> { |
| | | BigDecimal amountA = a == null || a.getPaymentAmount() == null ? BigDecimal.ZERO : a.getPaymentAmount(); |
| | | BigDecimal amountB = b == null || b.getPaymentAmount() == null ? BigDecimal.ZERO : b.getPaymentAmount(); |
| | | return amountB.compareTo(amountA); |
| | | }); |
| | | // 总额用于计算各站点占比,name+value 为服务端拼好的饼图标签文本(站点名 xx.x%) |
| | | BigDecimal total = BigDecimal.ZERO; |
| | | for (SixCircleDto dto : circleDtos) { |
| | | if (dto != null && dto.getPaymentAmount() != null) { |
| | | total = total.add(dto.getPaymentAmount()); |
| | | } |
| | | } |
| | | for (SixCircleDto dto : circleDtos) { |
| | | if (dto == null || dto.getSiteId() == null || dto.getPaymentAmount() == null) { |
| | | continue; |
| | | } |
| | | Map<String, Object> item = new LinkedHashMap<>(); |
| | | String name = siteNameMap.getOrDefault(dto.getSiteId(), "电站" + dto.getSiteId()); |
| | | item.put("name", name); |
| | | item.put("value", dto.getPaymentAmount()); |
| | | String percent = total.compareTo(BigDecimal.ZERO) > 0 |
| | | ? dto.getPaymentAmount().multiply(BigDecimal.valueOf(100)).divide(total, 1, RoundingMode.HALF_UP).toPlainString() |
| | | : "0.0"; |
| | | item.put("name+value", name + " " + percent + "%"); |
| | | incomePie.add(item); |
| | | } |
| | | return incomePie; |
| | | } |
| | | |
| | | @PostMapping("/app/franchisee/user") |
| | |
| | | } |
| | | chargingUsersByDay.computeIfAbsent(agg.getStatDay(), key -> new HashSet<>()).add(agg.getAppUserId()); |
| | | } |
| | | List<TPartnerAppUser> relations = Collections.emptyList(); |
| | | if (partner != null && partner.getId() != null) { |
| | | R<List<TPartnerAppUser>> relationResult = partnerClient.getBoundAppUserRelations(partner.getId()); |
| | | if (relationResult != null && relationResult.getData() != null) { |
| | | relations = relationResult.getData(); |
| | | Map<LocalDate, Long> newUsersByDay = new LinkedHashMap<>(); |
| | | if (siteIds != null && !siteIds.isEmpty() && range != null && range[0] != null && range[1] != null) { |
| | | List<FranchiseeUserFirstCharge> firstCharges = chargingOrderMapper.franchiseeUserFirstChargedDays(siteIds, range[0], range[1]); |
| | | if (firstCharges != null) { |
| | | for (FranchiseeUserFirstCharge fc : firstCharges) { |
| | | if (fc != null && fc.getAppUserId() != null && fc.getFirstChargedDay() != null) { |
| | | newUsersByDay.merge(fc.getFirstChargedDay(), 1L, Long::sum); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | FranchiseeUserStatistics.Result userStatistics = FranchiseeUserStatistics.calculateByUserDays( |
| | | chargingUsersByDay, relations, range[0], range[1]); |
| | | chargingUsersByDay, newUsersByDay, range[0], range[1]); |
| | | |
| | | Set<Long> users = aggs.stream().map(FranchiseeUserAgg::getAppUserId).filter(Objects::nonNull).collect(Collectors.toSet()); |
| | | List<TAppUser> appUsers = Collections.emptyList(); |
| | |
| | | public R<Map<String, Object>> franchiseeOperation(@RequestBody(required = false) Map<String, Object> params) { |
| | | Map<String, Object> result = new LinkedHashMap<>(); |
| | | List<Integer> siteIds = franchiseeSiteIds(params); |
| | | List<TChargingPile> piles = Collections.emptyList(); |
| | | if (!siteIds.isEmpty()) { R<List<TChargingPile>> pileResult = chargingPileClient.getChargingPileBySiteIds(siteIds); if (pileResult != null && pileResult.getData() != null) piles = pileResult.getData(); } |
| | | List<TChargingGun> guns = Collections.emptyList(); |
| | | List<Integer> pileIds = piles.stream().map(TChargingPile::getId).filter(Objects::nonNull).collect(Collectors.toList()); |
| | | if (!pileIds.isEmpty()) { |
| | | GetChargingGunByChargingPileIdsVo query = new GetChargingGunByChargingPileIdsVo(); query.setChargingPileIds(pileIds); |
| | | R<List<TChargingGun>> gunResult = chargingGunClient.getChargingGunByChargingPileIds(query); |
| | | if (gunResult != null && gunResult.getData() != null) guns = gunResult.getData(); |
| | | } |
| | | BigDecimal total = BigDecimal.valueOf(guns.size()); |
| | | BigDecimal available = BigDecimal.valueOf(guns.stream().filter(this::isAvailableGun).count()); |
| | | BigDecimal fault = countGuns(guns, 7), offline = countGuns(guns, 1); |
| | | LocalDateTime[] range = franchiseeRange(params); |
| | | List<FranchiseeDayStat> operationStats = franchiseeDayStats(siteIds, range); |
| | | BigDecimal powerSatisfaction = demandPowerSatisfaction(operationStats); |
| | | Map<Integer, FranchiseeGunSat> gunSatMap = Collections.emptyMap(); |
| | | if (!siteIds.isEmpty() && range[0] != null && range[1] != null) { |
| | | gunSatMap = chargingOrderMapper.franchiseeGunSatisfaction(siteIds, range[0], range[1]).stream() |
| | | .filter(sat -> sat != null && sat.getChargingGunId() != null) |
| | | .collect(Collectors.toMap(FranchiseeGunSat::getChargingGunId, sat -> sat, (left, right) -> left)); |
| | | ChargingStatisticsQueryDto query = new ChargingStatisticsQueryDto(); |
| | | String dateType = params == null ? "today" : String.valueOf(params.getOrDefault("dateType", "today")); |
| | | int dayType = "week".equals(dateType) ? 2 : "month".equals(dateType) ? 3 : "year".equals(dateType) ? 4 : "custom".equals(dateType) ? 5 : 1; |
| | | query.setDayType(dayType); |
| | | if (dayType == 5) { |
| | | query.setStartTime(range[0].toLocalDate()); |
| | | query.setEndTime(range[1].toLocalDate().minusDays(1)); |
| | | } |
| | | Map<String, Object> summary = new LinkedHashMap<>(); summary.put("availableRate", rate(available, total)); summary.put("faultRate", rate(fault, total)); summary.put("offlineRate", rate(offline, total)); summary.put("powerSatisfactionRate", powerSatisfaction); |
| | | result.put("summary", summary); result.put("dcCharts", operationCharts(guns, gunSatMap, true)); result.put("acCharts", operationCharts(guns, gunSatMap, false)); |
| | | |
| | | List<Map<String, Object>> dcAvailable = safeList(chargingOrderService.equipmentUserType1(siteIds, query)); |
| | | List<Map<String, Object>> acAvailable = safeList(chargingOrderService.equipmentUserType2(siteIds, query)); |
| | | List<Map<String, Object>> dcFault = safeList(chargingOrderService.equipmentMapbroke1(siteIds, query)); |
| | | List<Map<String, Object>> acFault = safeList(chargingOrderService.equipmentMapbroke2(siteIds, query)); |
| | | List<Map<String, Object>> dcOffline = safeList(chargingOrderService.equipmentMapOut1(siteIds, query)); |
| | | List<Map<String, Object>> acOffline = safeList(chargingOrderService.equipmentMapOut2(siteIds, query)); |
| | | List<Map<String, Object>> dcSatisfaction = safeList(chargingOrderService.needElec(siteIds, query)); |
| | | List<Map<String, Object>> acSatisfaction = safeList(chargingOrderService.needElec1(siteIds, query)); |
| | | normalizeOperationPercents(dcAvailable); |
| | | normalizeOperationPercents(acAvailable); |
| | | normalizeOperationPercents(dcFault); |
| | | normalizeOperationPercents(acFault); |
| | | normalizeOperationPercents(dcOffline); |
| | | normalizeOperationPercents(acOffline); |
| | | normalizeOperationPercents(dcSatisfaction); |
| | | normalizeOperationPercents(acSatisfaction); |
| | | |
| | | Map<String, Object> summary = new LinkedHashMap<>(); |
| | | summary.put("availableRate", calculateAveragePercent(dcAvailable, acAvailable)); |
| | | summary.put("faultRate", calculateAveragePercent(dcFault, acFault)); |
| | | summary.put("offlineRate", calculateAveragePercent(dcOffline, acOffline)); |
| | | summary.put("powerSatisfactionRate", calculateAveragePercent(dcSatisfaction, acSatisfaction)); |
| | | result.put("summary", summary); |
| | | result.put("dcCharts", Arrays.asList( |
| | | operationChart(dcAvailable, "可用率"), |
| | | operationChart(dcFault, "故障率"), |
| | | operationChart(dcOffline, "离网率"), |
| | | operationChart(dcSatisfaction, "需求电流满足率"))); |
| | | result.put("acCharts", Arrays.asList( |
| | | operationChart(acAvailable, "可用率"), |
| | | operationChart(acFault, "故障率"), |
| | | operationChart(acOffline, "离网率"), |
| | | operationChart(acSatisfaction, "需求电流满足率"))); |
| | | return R.ok(result); |
| | | } |
| | | |
| | | private Map<String, Object> operationChart(List<Map<String, Object>> rows, String name) { |
| | | List<String> categories = rows.stream().map(row -> { |
| | | String gunName = row.get("name") == null ? "" : String.valueOf(row.get("name")); |
| | | return StringUtils.isBlank(gunName) ? "未命名充电枪" : gunName; |
| | | }).collect(Collectors.toList()); |
| | | List<Object> values = rows.stream().map(row -> row.getOrDefault("percent", "0")).collect(Collectors.toList()); |
| | | Map<String, Object> chart = new LinkedHashMap<>(); |
| | | chart.put("categories", categories); |
| | | Map<String, Object> series = new LinkedHashMap<>(); |
| | | series.put("name", name); |
| | | series.put("data", values); |
| | | chart.put("series", Collections.singletonList(series)); |
| | | return chart; |
| | | } |
| | | |
| | | private void normalizeOperationPercents(List<Map<String, Object>> rows) { |
| | | for (Map<String, Object> row : rows) { |
| | | Object raw = row.get("percent"); |
| | | try { |
| | | BigDecimal percent = raw == null ? BigDecimal.ZERO : new BigDecimal(String.valueOf(raw)); |
| | | row.put("percent", percent.abs().toPlainString()); |
| | | } catch (NumberFormatException ignored) { |
| | | row.put("percent", "0"); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** 加盟商看板按日聚合(siteIds 为空直接返回空,避免空 IN)。 */ |
| | |
| | | return new LocalDateTime[]{today.atStartOfDay(), today.plusDays(1).atStartOfDay()}; |
| | | } |
| | | |
| | | static BigDecimal franchiseeIncomeWan(List<FranchiseeDayStat> stats) { |
| | | return stats.stream().map(FranchiseeDayStat::getChargingIncome) |
| | | .map(value -> value == null ? BigDecimal.ZERO : value) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add) |
| | | .divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_UP); |
| | | } |
| | | |
| | | private <T> BigDecimal sum(List<T> items, java.util.function.Function<T, BigDecimal> getter) { return items.stream().map(getter).map(this::value).reduce(BigDecimal.ZERO, BigDecimal::add); } |
| | | private BigDecimal value(BigDecimal value) { return value == null ? BigDecimal.ZERO : value; } |
| | | private Map<LocalDate, FranchiseeDayStat> dayStatByDay(List<FranchiseeDayStat> stats) { |
| | |
| | | Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", categories); |
| | | Map<String, Object> series = new LinkedHashMap<>(); series.put("name", name); series.put("data", data); chart.put("series", new ArrayList<>(Collections.singletonList(series))); return chart; |
| | | } |
| | | private Map<String, Object> franchiseeOrderTrend(List<FranchiseeDayStat> stats, LocalDateTime[] range) { |
| | | Map<String, Object> chart = franchiseeDailyTrend(stats, range, "充电金额", FranchiseeDayStat::getOrderAmountEffective); |
| | | ((List<Map<String, Object>>) chart.get("series")).get(0).put("type", "column"); |
| | | Map<LocalDate, FranchiseeDayStat> byDay = dayStatByDay(stats); |
| | | List<BigDecimal> countData = new ArrayList<>(); List<String> categories = (List<String>) chart.get("categories"); |
| | | LocalDate start = range[0] == null ? LocalDate.now() : range[0].toLocalDate(); |
| | | for (int i = 0; i < categories.size(); i++) { LocalDate day = start.plusDays(i); FranchiseeDayStat stat = byDay.get(day); countData.add(BigDecimal.valueOf(stat == null ? 0L : numberValue(stat.getOrderCount()))); } |
| | | Map<String, Object> countSeries = new LinkedHashMap<>(); countSeries.put("name", "充电订单"); countSeries.put("data", countData); countSeries.put("type", "line"); countSeries.put("style", "curve"); countSeries.put("index", 1); ((List<Map<String, Object>>) chart.get("series")).add(countSeries); return chart; |
| | | private List<Map<String, Object>> franchiseeManagementOrderStats(List<Integer> siteIds, LocalDateTime[] range) { |
| | | if (siteIds == null || siteIds.isEmpty() || range == null || range.length < 2 |
| | | || range[0] == null || range[1] == null || !range[1].isAfter(range[0])) { |
| | | return Collections.emptyList(); |
| | | } |
| | | LocalDate start = range[0].toLocalDate(); |
| | | LocalDate end = range[1].minusNanos(1).toLocalDate(); |
| | | return safeList(chargingOrderService.getByDate(start, end, siteIds)); |
| | | } |
| | | |
| | | private BigDecimal sumManagementOrderField(List<Map<String, Object>> stats, String field) { |
| | | return safeList(stats).stream() |
| | | .map(row -> decimalValue(row == null ? null : row.get(field))) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add); |
| | | } |
| | | |
| | | private BigDecimal decimalValue(Object value) { |
| | | if (value == null) return BigDecimal.ZERO; |
| | | try { |
| | | return new BigDecimal(String.valueOf(value)); |
| | | } catch (NumberFormatException ignored) { |
| | | return BigDecimal.ZERO; |
| | | } |
| | | } |
| | | |
| | | private Map<String, Object> franchiseeManagementOrderTrend(List<Map<String, Object>> stats) { |
| | | List<String> categories = new ArrayList<>(); |
| | | List<BigDecimal> amountData = new ArrayList<>(); |
| | | List<BigDecimal> countData = new ArrayList<>(); |
| | | for (Map<String, Object> row : safeList(stats)) { |
| | | if (row == null) continue; |
| | | categories.add(String.valueOf(row.get("time"))); |
| | | amountData.add(decimalValue(row.get("paymoney"))); |
| | | countData.add(decimalValue(row.get("orderCount"))); |
| | | } |
| | | Map<String, Object> amountSeries = new LinkedHashMap<>(); |
| | | amountSeries.put("name", "充电金额"); amountSeries.put("data", amountData); amountSeries.put("type", "column"); |
| | | Map<String, Object> countSeries = new LinkedHashMap<>(); |
| | | countSeries.put("name", "充电订单"); countSeries.put("data", countData); countSeries.put("type", "line"); |
| | | countSeries.put("style", "curve"); countSeries.put("index", 1); |
| | | Map<String, Object> chart = new LinkedHashMap<>(); |
| | | chart.put("categories", categories); |
| | | chart.put("series", new ArrayList<>(Arrays.asList(amountSeries, countSeries))); |
| | | return chart; |
| | | } |
| | | |
| | | private Map<String, Object> franchiseePhaseRing(List<Integer> siteIds, LocalDateTime[] range) { |
| | | Map<Integer, BigDecimal> phase = new LinkedHashMap<>(); phase.put(1, BigDecimal.ZERO); phase.put(2, BigDecimal.ZERO); phase.put(3, BigDecimal.ZERO); phase.put(4, BigDecimal.ZERO); |
| | | if (siteIds != null && !siteIds.isEmpty() && range != null && range[0] != null && range[1] != null) { |
| | | List<Long> ids = chargingOrderMapper.franchiseeOrderIds(siteIds, range[0], range[1]); |
| | | for (int from = 0; from < ids.size(); from += PHASE_ID_BATCH_SIZE) { |
| | | List<Long> chunk = ids.subList(from, Math.min(from + PHASE_ID_BATCH_SIZE, ids.size())); |
| | | chargingOrderMapper.franchiseePhaseStatsByOrderIds(chunk).forEach(item -> { |
| | | if (item != null && item.getType() != null) { |
| | | phase.computeIfPresent(item.getType(), (key, total) -> total.add(value(item.getCapacity()))); |
| | | } |
| | | }); |
| | | if (!ids.isEmpty()) { |
| | | // 分块并行反查 strategy 表(分片键 charging_order_id):MyCat 按 id 路由成本约 2ms/个, |
| | | // 串行 5000/块在大范围下 70s+ 读超时;100/块 × 16 线程实测 46k id 约 20s(代理并发吞吐有限)。 |
| | | List<CompletableFuture<Void>> futures = new ArrayList<>(); |
| | | for (int from = 0; from < ids.size(); from += PHASE_ID_BATCH_SIZE) { |
| | | List<Long> chunk = ids.subList(from, Math.min(from + PHASE_ID_BATCH_SIZE, ids.size())); |
| | | futures.add(CompletableFuture.runAsync(() -> { |
| | | List<FranchiseePhaseStat> items = chargingOrderMapper.franchiseePhaseStatsByOrderIds(chunk); |
| | | if (items != null) { |
| | | synchronized (phase) { |
| | | items.forEach(item -> { |
| | | if (item != null && item.getType() != null) { |
| | | phase.computeIfPresent(item.getType(), (key, total) -> total.add(value(item.getCapacity()))); |
| | | } |
| | | }); |
| | | } |
| | | } |
| | | }, PHASE_QUERY_EXECUTOR)); |
| | | } |
| | | CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); |
| | | } |
| | | } |
| | | String[] names = {"尖", "峰", "平", "谷"}; List<Map<String, Object>> data = new ArrayList<>(); |
| | |
| | | List<Map<String, Object>> data = new ArrayList<>(); for (int i = 0; i < names.length; i++) { Map<String, Object> item = new LinkedHashMap<>(); item.put("name", names[i]); item.put("value", counts[i]); data.add(item); } |
| | | return Collections.singletonMap("series", Collections.singletonList(Collections.singletonMap("data", data))); |
| | | } |
| | | private Map<String, Object> franchiseeIncomeTrend(List<FranchiseeDayStat> stats, LocalDate firstMonth, int monthCount) { |
| | | /** 收支分析近6月柱状图:与后台 电站收入分析 一致(历史月结算账单 + 当月原始订单)。 */ |
| | | private Map<String, Object> franchiseeIncomeTrendFromSix(List<SixChargingDto> months) { |
| | | List<String> categories = new ArrayList<>(); |
| | | List<BigDecimal> electricity = new ArrayList<>(), service = new ArrayList<>(); |
| | | Map<YearMonth, List<FranchiseeDayStat>> byMonth = stats.stream().filter(stat -> stat != null && stat.getStatDay() != null) |
| | | .collect(Collectors.groupingBy(stat -> YearMonth.from(stat.getStatDay()))); |
| | | for (int i = 0; i < monthCount; i++) { |
| | | YearMonth month = YearMonth.from(firstMonth).plusMonths(i); |
| | | categories.add(String.format("%02d月", month.getMonthValue())); |
| | | List<FranchiseeDayStat> monthStats = byMonth.getOrDefault(month, Collections.emptyList()); |
| | | electricity.add(sum(monthStats, FranchiseeDayStat::getElectrovalence)); |
| | | service.add(sum(monthStats, FranchiseeDayStat::getServiceFee)); |
| | | for (SixChargingDto month : months) { |
| | | if (month == null) { |
| | | continue; |
| | | } |
| | | categories.add(month.getMonth() + "月"); |
| | | electricity.add(month.getElectrovalence() == null ? BigDecimal.ZERO : month.getElectrovalence()); |
| | | service.add(month.getServiceCharge() == null ? BigDecimal.ZERO : month.getServiceCharge()); |
| | | } |
| | | Map<String, Object> chart = new LinkedHashMap<>(); chart.put("categories", categories); |
| | | Map<String, Object> electricitySeries = new LinkedHashMap<>(); electricitySeries.put("name", "充电费"); electricitySeries.put("data", electricity); |
| | | Map<String, Object> serviceSeries = new LinkedHashMap<>(); serviceSeries.put("name", "服务费"); serviceSeries.put("data", service); |
| | | chart.put("series", new ArrayList<>(Arrays.asList(electricitySeries, serviceSeries))); return chart; |
| | | Map<String, Object> chart = new LinkedHashMap<>(); |
| | | chart.put("categories", categories); |
| | | Map<String, Object> electricitySeries = new LinkedHashMap<>(); |
| | | electricitySeries.put("name", "充电费"); |
| | | electricitySeries.put("data", electricity); |
| | | Map<String, Object> serviceSeries = new LinkedHashMap<>(); |
| | | serviceSeries.put("name", "服务费"); |
| | | serviceSeries.put("data", service); |
| | | chart.put("series", new ArrayList<>(Arrays.asList(electricitySeries, serviceSeries))); |
| | | return chart; |
| | | } |
| | | |
| | | |
| | |
| | | |
| | | |
| | | @ResponseBody |
| | | @RequiresPermissions(value = {"/paymentOrder/refund", "/paymentOrder/refund/select"}, logical = Logical.OR) |
| | | @PostMapping(value = "/pay/order/refund") |
| | | @ApiOperation(value = "退款", tags = {"管理后台-支付订单-订单信息"}) |
| | | public R refund(@RequestBody PayOrderRefundDto payOrderQueryDto) { |
| | |
| | | |
| | | |
| | | @ResponseBody |
| | | @RequiresPermissions(value = {"/paymentOrder/refund", "/paymentOrder/refund/select"}, logical = Logical.OR) |
| | | @GetMapping(value = "/pay/order/refund/detail") |
| | | @ApiOperation(value = "退款信息", tags = {"管理后台-支付订单-订单信息"}) |
| | | public R refundDetail(Long orderId, Integer type) { |
| | |
| | | } |
| | | |
| | | @ResponseBody |
| | | @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR) |
| | | @GetMapping(value = "/pay/order/charging") |
| | | @ApiOperation(value = "充电信息", tags = {"管理后台-支付订单-订单信息"}) |
| | | public R<PayOrderChargingInfo> refundDetail(Long orderId) { |
| | |
| | | } |
| | | |
| | | @ResponseBody |
| | | @RequiresPermissions(value = {"/paymentOrder/order"}, logical = Logical.OR) |
| | | @GetMapping(value = "/pay/order/charging/details") |
| | | @ApiOperation(value = "充电明细", tags = {"管理后台-支付订单-订单信息"}) |
| | | public R<List<TChargingOrderAccountingStrategy>> chargingDetail(Long orderId) { |
| | |
| | | chargingOrderInfoVO.setCdVoltage(byId.getVoltage()!=null?byId.getVoltage().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":""); |
| | | chargingOrderInfoVO.setSurplus(byId.getTotalElectricity()!=null?byId.getTotalElectricity().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":""); |
| | | chargingOrderInfoVO.setTotalPower(byId.getPower()!=null?byId.getPower().setScale(2, BigDecimal.ROUND_HALF_DOWN)+"":""); |
| | | chargingOrderInfoVO.setVin(byId.getActualVin()); |
| | | chargingOrderInfoVO.setActualVin(byId.getActualVin()); |
| | | if (byId.getAppUserCarId()!=null){ |
| | | TAppUserCar data = appUserCarClient.getCarById(byId.getAppUserCarId()+"").getData(); |
| | | if (data!=null){ |
| | |
| | | } |
| | | |
| | | /** |
| | | * 远程启动充电应答 |
| | | * 远程启动充电应答(按订单号前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单) |
| | | * @param message |
| | | */ |
| | | @ResponseBody |
| | | @PostMapping(value = "/startChargeSuccessfully") |
| | | public void startChargeSuccessfully(@RequestBody PlatformStartChargingReplyMessageVO message){ |
| | | log.info("-------------------远程启动充电请求应答-------------------:" + message); |
| | | chargingOrderService.startChargeSuccessfully(message); |
| | | String orderCode = message == null ? null : message.getTransaction_serial_number(); |
| | | if (isCardOrder(orderCode)) { |
| | | cardChargingOrderService.cardStartChargeSuccessfully(message); |
| | | } else if (isVinOrder(orderCode)) { |
| | | vinChargingOrderService.vinStartChargeSuccessfully(message); |
| | | } else { |
| | | chargingOrderService.startChargeSuccessfully(message); |
| | | } |
| | | } |
| | | |
| | | |
| | |
| | | |
| | | |
| | | |
| | | /** |
| | | * 安全检测等待窗口(秒):设备在此时长内未上报有效安全检测时,前端按「未插枪」提示用户, |
| | | * 超时订单由启动超时兜底任务自动取消,避免订单永久停留在启动中状态。 |
| | | */ |
| | | private static final long STARTUP_WAIT_SECONDS = 90L; |
| | | |
| | | @ResponseBody |
| | | @GetMapping(value = "/preChargeCheck/{id}") |
| | | @ApiOperation(value = "获取安全检测数据", tags = {"小程序-扫一扫"}) |
| | |
| | | public AjaxResult<PreChargeCheck> preChargeCheck(@PathVariable Integer id) { |
| | | String key = "AQJC_" + id; |
| | | PreChargeCheck cacheObject = redisService.getCacheObject(key); |
| | | if(null != cacheObject){ |
| | | if(LocalDateTime.now().minusMinutes(1).isAfter(cacheObject.getAddTime())){ |
| | | redisService.deleteObject(key); |
| | | cacheObject = null; |
| | | if (null != cacheObject) { |
| | | LocalDateTime addTime = cacheObject.getAddTime(); |
| | | // 等待安全检测超出窗口且启动指令尚未下发时,按「未插枪」提示前端; |
| | | // 缓存必须保留:设备安全检测上报依赖该缓存推进启动,删除会导致订单永久卡在启动中 |
| | | if (Integer.valueOf(1).equals(cacheObject.getStartupSuccess()) |
| | | && !Boolean.TRUE.equals(cacheObject.getStartCommandSent()) |
| | | && null != addTime |
| | | && LocalDateTime.now().isAfter(addTime.plusSeconds(STARTUP_WAIT_SECONDS))) { |
| | | cacheObject.setStartupSuccess(3); |
| | | cacheObject.setFailureCause(5); |
| | | redisService.setCacheObject(key, cacheObject, 24L, TimeUnit.HOURS); |
| | | } |
| | | } |
| | | return AjaxResult.success(cacheObject); |
| | |
| | | }) |
| | | public AjaxResult stopCharging(@PathVariable String id) { |
| | | log.info("小程序主动发起停止充电,订单ID:{}", id); |
| | | // VIN 码充电订单路由:VD 订单存于 t_vin_charging_order,不在 t_charging_order; |
| | | // VD 表存在该 ID 订单时优先走 VIN 停充(内部按状态返回准确的“不能重复操作/还未开始充电”), |
| | | // 其余情况回落普通停充。雪花 ID 两表同源生成,撞号概率可忽略 |
| | | TVinChargingOrder vinOrder = null; |
| | | try { |
| | | vinOrder = vinChargingOrderService.getById(Long.valueOf(id)); |
| | | } catch (NumberFormatException ignored) { |
| | | // 非数字订单ID,按普通停充处理 |
| | | } |
| | | if (vinOrder != null) { |
| | | return vinChargingOrderService.stopChargingByApplet(id); |
| | | } |
| | | return chargingOrderService.stopCharging(id); |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 停止充电应答处理逻辑 |
| | | * 停止充电应答处理逻辑(普通订单原逻辑 + VIN订单按枪兜底确认) |
| | | * @param platformStopChargingReply |
| | | */ |
| | | @PostMapping("/terminateSuccessfulResponse") |
| | | public void terminateSuccessfulResponse(@RequestBody PlatformStopChargingReplyVO platformStopChargingReply){ |
| | | log.info("-------------------远程停止充电请求应答-------------------:" + platformStopChargingReply); |
| | | // VIN订单平台停止应答兜底(按枪定位停止中订单,内部自带空判断,不影响普通订单处理) |
| | | try { |
| | | vinChargingOrderService.vinTerminateStopByReply(platformStopChargingReply); |
| | | } catch (Exception ex) { |
| | | log.error("VIN订单停止应答处理异常:", ex); |
| | | } |
| | | chargingOrderService.terminateSuccessfulResponse(platformStopChargingReply); |
| | | } |
| | | |
| | | |
| | | |
| | | |
| | | /** |
| | | * 停止充电返回账单后计算费用 |
| | | * 停止充电返回账单后计算费用(按订单号前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单) |
| | | * @param vo |
| | | */ |
| | | @PostMapping("/endChargeBillingCharge") |
| | | public R endChargeBillingCharge(@RequestBody TransactionRecordMessageVO vo){ |
| | | log.info("-------------------停止充电返回账单后计算费用及修改业务状态-------------------:" + vo); |
| | | String orderCode = vo == null ? null : vo.getTransaction_serial_number(); |
| | | if (isCardOrder(orderCode)) { |
| | | return cardChargingOrderService.cardEndChargeBillingCharge(vo); |
| | | } |
| | | if (isVinOrder(orderCode)) { |
| | | return vinChargingOrderService.vinEndChargeBillingCharge(vo); |
| | | } |
| | | return chargingOrderService.endChargeBillingCharge(vo); |
| | | } |
| | | |
| | |
| | | public R<List<SixChargingDto>> charge(Integer siteId, Integer partnerId) { |
| | | Long userId = tokenService.getLoginUser().getUserid(); |
| | | SysUser sysUser = sysUserClient.getSysUser(userId).getData(); |
| | | boolean partnerView = isPartnerView(sysUser); |
| | | List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId); |
| | | LocalDate sixBefore = PreviousSixMonths.get(); |
| | | //通过siteIds进行sql查询统计 |
| | | List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, false); |
| | | return R.ok(buildLastSixMonths(siteIds, false)); |
| | | } |
| | | |
| | | /** |
| | | * 近6月+当月电站收入:历史月读结算账单、当月补原始订单。 |
| | | * 与「电站收入分析」图表、底部数据分类及加盟商收支同口径。 |
| | | */ |
| | | private List<SixChargingDto> buildLastSixMonths(List<Integer> siteIds, boolean partnerView) { |
| | | LocalDate sixBefore = PreviousSixMonths.get(); |
| | | List<SixChargingDto> chargingDtos = chargingOrderService.charge(sixBefore, siteIds, partnerView); |
| | | LocalDate statisticsEndMonth = resolveStatisticsEndMonth(LocalDate.now(), chargingDtos); |
| | | List<SixChargingDto> sixChargingDtos = generateLastSixMonths(statisticsEndMonth); |
| | | for (SixChargingDto sixChargingDto : sixChargingDtos) { |
| | |
| | | } |
| | | |
| | | } |
| | | |
| | | return R.ok(sixChargingDtos); |
| | | |
| | | return sixChargingDtos; |
| | | } |
| | | |
| | | |
| | |
| | | SysUser sysUser = sysUserClient.getSysUser(userId).getData(); |
| | | boolean partnerView = isPartnerView(sysUser); |
| | | List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId); |
| | | Map<String,Object> map = chargingOrderService.countAll(siteIds, false); |
| | | if (map == null) { |
| | | map = new HashMap<String,Object>(); |
| | | } |
| | | LocalDate sixBefore = PreviousSixMonths.get(); |
| | | Map<String,Object> map = new HashMap<String,Object>(); |
| | | // 电费/服务费与上方「电站收入分析」图表同口径:近6月结算账单 + 当月原始订单,保证底部合计=图表6个月相加 |
| | | List<SixChargingDto> sixChargingDtos = buildLastSixMonths(siteIds, false); |
| | | map.put("electrovalence", sixChargingDtos.stream() |
| | | .filter(Objects::nonNull) |
| | | .map(SixChargingDto::getElectrovalence) |
| | | .filter(Objects::nonNull) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add)); |
| | | map.put("service_charge", sixChargingDtos.stream() |
| | | .filter(Objects::nonNull) |
| | | .map(SixChargingDto::getServiceCharge) |
| | | .filter(Objects::nonNull) |
| | | .reduce(BigDecimal.ZERO, BigDecimal::add)); |
| | | // 合作商分成/三方平台分佣按近6月结算口径统计(与图表月份窗口一致) |
| | | Map<String,Object> sub = chargingOrderService.countAll(siteIds, false, sixBefore); |
| | | map.put("commission_amount", sub == null ? BigDecimal.ZERO : sub.get("commission_amount")); |
| | | map.put("sharing_amount", sub == null ? BigDecimal.ZERO : sub.get("sharing_amount")); |
| | | boolean platformVisible = !partnerView; |
| | | if(platformVisible){ |
| | | R<BigDecimal> parkingAmountResult = parkingLotClient.getRecordAmount(siteIds); |
| | | R<BigDecimal> parkingAmountResult = parkingLotClient.getRecordAmount(siteIds, sixBefore.toString()); |
| | | BigDecimal data = parkingAmountResult == null || parkingAmountResult.getData() == null |
| | | ? BigDecimal.ZERO : parkingAmountResult.getData(); |
| | | map.put("parkingAmount",data); |
| | | BigDecimal data1 = shoppingOrderService.getSumAmount(); |
| | | BigDecimal data1 = shoppingOrderService.getSumAmount(sixBefore); |
| | | map.put("shopAmount",data1); |
| | | BigDecimal data2 = vipOrderService.getSumAmout(); |
| | | BigDecimal data2 = vipOrderService.getSumAmout(sixBefore); |
| | | map.put("vipAmount",data2); |
| | | }else{ |
| | | map.put("parkingAmount",0); |
| | |
| | | boolean partnerView = isPartnerView(sysUser); |
| | | List<Integer> siteIds = resolvePlatformRevenueSiteIds(userId, sysUser, siteId, partnerId); |
| | | LocalDate sixBefore = PreviousSixMonths.get(); |
| | | return R.ok(chargingOrderService.payTypeCircle(sixBefore, siteIds, false)); |
| | | return R.ok(chargingOrderService.payTypeCircle(sixBefore, siteIds, partnerView)); |
| | | } |
| | | |
| | | private boolean isPartnerView(SysUser sysUser) { |
| | |
| | | } |
| | | |
| | | /** |
| | | * 处理充电订单实时监控数据相关的业务逻辑 |
| | | * 处理充电订单实时监控数据相关的业务逻辑(按订单号前缀路由) |
| | | * @param query |
| | | */ |
| | | @PostMapping("/chargeMonitoring") |
| | | public void chargeMonitoring(@RequestBody UploadRealTimeMonitoringDataQuery query){ |
| | | chargingOrderService.chargeMonitoring(query); |
| | | String orderCode = query == null ? null : query.getTransaction_serial_number(); |
| | | if (isCardOrder(orderCode)) { |
| | | cardChargingOrderService.cardChargeMonitoring(query); |
| | | } else if (isVinOrder(orderCode)) { |
| | | vinChargingOrderService.vinChargeMonitoring(query); |
| | | } else { |
| | | chargingOrderService.chargeMonitoring(query); |
| | | } |
| | | } |
| | | /** |
| | | * 通过流水号查询订单 |
| | | * 通过流水号查询订单(统一前缀路由:SD=刷卡订单,VD=VIN订单,其余=普通订单) |
| | | * <p>设备链路(实时监控/BMS需求/交易记录确认等)统一经此按订单号前缀取三类订单, |
| | | * SD/VD 订单实体继承自 TChargingOrder,字段兼容直接返回。</p> |
| | | * @param code |
| | | * @return |
| | | */ |
| | | @PostMapping(value = "/getOrderByCode/{code}") |
| | | public R<TChargingOrder> getOrderByCode(@PathVariable("code") String code){ |
| | | TChargingOrder one = chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class) |
| | | .eq(TChargingOrder::getCode, code)); |
| | | TChargingOrder one; |
| | | if (isCardOrder(code)) { |
| | | one = cardChargingOrderService.getCardOrderByCode(code); |
| | | } else if (isVinOrder(code)) { |
| | | one = vinChargingOrderService.getVinOrderByCode(code); |
| | | } else { |
| | | one = chargingOrderService.getOne(Wrappers.lambdaQuery(TChargingOrder.class) |
| | | .eq(TChargingOrder::getCode, code)); |
| | | } |
| | | if (one == null) { |
| | | return R.ok(null); |
| | | } |
| | | one.setIdStr(one.getId().toString()); |
| | | return R.ok(one); |
| | | } |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | @PostMapping("/updateHandshakeVin") |
| | | public R<Boolean> updateHandshakeVin(@RequestParam("orderCode") String orderCode, |
| | | @RequestParam("vin") String vin) { |
| | | if (StringUtils.isEmpty(orderCode)) { |
| | | return R.ok(false); |
| | | } |
| | | boolean updated; |
| | | if (orderCode.startsWith("CD")) { |
| | | updated = StringUtils.isNotEmpty(vin) && chargingOrderService.update(Wrappers.<TChargingOrder>lambdaUpdate() |
| | | .eq(TChargingOrder::getCode, orderCode) |
| | | .set(TChargingOrder::getActualVin, vin)); |
| | | } else if (orderCode.startsWith("SD")) { |
| | | // SD/VD:VIN 为空也进入握手处理(状态推进必达);服务内部仅非空回写 VIN,且仅状态=启动中(2)才推进 |
| | | updated = cardChargingOrderService.handleHandshakeVin(orderCode, vin); |
| | | } else if (orderCode.startsWith("VD")) { |
| | | updated = vinChargingOrderService.handleHandshakeVin(orderCode, vin); |
| | | } else { |
| | | log.warn("握手VIN回写失败,未知订单类型:{}", orderCode); |
| | | return R.ok(false); |
| | | } |
| | | return R.ok(updated); |
| | | } |
| | | |
| | | /** |
| | | * 设备链路订单号前缀判断:SD=刷卡充电订单 |
| | | */ |
| | | private boolean isCardOrder(String orderCode) { |
| | | return orderCode != null && orderCode.startsWith("SD"); |
| | | } |
| | | |
| | | /** |
| | | * 设备链路订单号前缀判断:VD=VIN码充电订单 |
| | | */ |
| | | private boolean isVinOrder(String orderCode) { |
| | | return orderCode != null && orderCode.startsWith("VD"); |
| | | } |
| | | |
| | | /** |
| | | * 设备主动发起充电(刷卡/VIN码)鉴权建单统一入口。 |
| | | * <p>协议 start_method:1=刷卡(创建SD订单),2=账号启动(暂不支持),3=VIN码(创建VD订单)。</p> |
| | | */ |
| | | @PostMapping("/inner/device-start-charging") |
| | | public R<DeviceStartChargingVO> deviceStartCharging(@RequestBody DeviceStartChargingDTO dto) { |
| | | if (dto == null || dto.getStartMethod() == null) { |
| | | log.warn("[设备启动] 缺少启动方式,拒绝建单 dto={}", dto); |
| | | return R.ok(DeviceStartChargingVO.fail(null)); |
| | | } |
| | | DeviceStartChargingVO result; |
| | | switch (dto.getStartMethod()) { |
| | | case 1: |
| | | result = cardChargingOrderService.startCardCharging(dto); |
| | | break; |
| | | case 3: |
| | | result = vinChargingOrderService.startVinCharging(dto); |
| | | break; |
| | | case 2: |
| | | // 账号启动暂不支持(协议无对应失败码,按最接近的“账户不存在”返回) |
| | | log.warn("[设备启动] 账号启动方式暂不支持 pile={} account={}", dto.getChargingPileCode(), dto.getAccount()); |
| | | result = DeviceStartChargingVO.fail(1); |
| | | break; |
| | | default: |
| | | log.warn("[设备启动] 未知启动方式 startMethod={} pile={} gun={}", |
| | | dto.getStartMethod(), dto.getChargingPileCode(), dto.getChargingGunCode()); |
| | | result = DeviceStartChargingVO.fail(null); |
| | | break; |
| | | } |
| | | return R.ok(result); |
| | | } |
| | | |
| | | /** |
| | | * 内部接口:统计公司名下进行中充电订单数(三表合计,状态 2=启动中/3=充电中/4=停止中, |
| | | * 账户模式切换:分配→共享 前校验使用) |
| | | */ |
| | | @PostMapping("/inner/count-active-by-company") |
| | | public R<Integer> countActiveByCompany(@RequestParam("companyId") Integer companyId) { |
| | | if (companyId == null) { |
| | | return R.ok(0); |
| | | } |
| | | try { |
| | | List<Integer> activeStatuses = Arrays.asList(2, 3, 4); |
| | | long count = 0L; |
| | | count += chargingOrderService.lambdaQuery() |
| | | .eq(TChargingOrder::getCompanyId, companyId) |
| | | .in(TChargingOrder::getStatus, activeStatuses) |
| | | .count(); |
| | | count += cardChargingOrderService.lambdaQuery() |
| | | .eq(TCardChargingOrder::getCompanyId, companyId) |
| | | .in(TCardChargingOrder::getStatus, activeStatuses) |
| | | .count(); |
| | | count += vinChargingOrderService.lambdaQuery() |
| | | .eq(TVinChargingOrder::getCompanyId, companyId) |
| | | .in(TVinChargingOrder::getStatus, activeStatuses) |
| | | .count(); |
| | | return R.ok((int) count); |
| | | } catch (RuntimeException ex) { |
| | | log.error("统计公司进行中充电订单失败:companyId={}", companyId, ex); |
| | | return R.fail("统计公司进行中充电订单失败:" + ex.getMessage()); |
| | | } |
| | | } |
| | | |
| | | @RequiresPermissions(value = {"/chargingOperationAnalysis"}, logical = Logical.OR) |
| | | @ResponseBody |
| | | @PostMapping(value = "/charging/statistics") |
| | |
| | | |
| | | |
| | | /** |
| | | * 硬件充电结束后的处理逻辑 |
| | | * 硬件充电结束后的处理逻辑(按订单号前缀路由,结束方式2=设备自动结束) |
| | | * @param code |
| | | */ |
| | | @PostMapping("/endCharge") |
| | | public void endCharge(@RequestParam("code") String code){ |
| | | log.info(code + ":-------------------充电桩自动结束充电-------------------"); |
| | | chargingOrderService.endCharge(code, 2); |
| | | if (isCardOrder(code)) { |
| | | cardChargingOrderService.cardEndCharge(code, 2); |
| | | } else if (isVinOrder(code)) { |
| | | vinChargingOrderService.vinEndCharge(code, 2); |
| | | } else { |
| | | chargingOrderService.endCharge(code, 2); |
| | | } |
| | | } |
| | | |
| | | |
| | | |
| | | /** |
| | | * 硬件异常结束充电后的处理逻辑 |
| | | * 硬件异常结束充电后的处理逻辑(按订单号前缀路由,结束方式0=异常终止) |
| | | * @param code |
| | | */ |
| | | @PostMapping("/excelEndCharge") |
| | | public void excelEndCharge(@RequestParam("code") String code){ |
| | | log.info(code + ":-------------------充电异常,停止充电-------------------"); |
| | | chargingOrderService.excelEndCharge(code); |
| | | if (isCardOrder(code)) { |
| | | cardChargingOrderService.cardEndCharge(code, 0); |
| | | } else if (isVinOrder(code)) { |
| | | vinChargingOrderService.vinEndCharge(code, 0); |
| | | } else { |
| | | chargingOrderService.excelEndCharge(code); |
| | | } |
| | | } |
| | | |
| | | |