feat:正元同步部门、身份、商户信息、自动创建并且绑定饭卡、正元id字典

This commit is contained in:
dzc committed 2025-03-04 22:43:36 +08:00
1 parent 54a46dd9ee
commit 4382c13d8a
30 files changed
+710 -171

No files matched your search

+24 -1
View File
@@ -27,4 +27,27 @@ CREATE TABLE `third_zy_log`
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci
ROW_FORMAT = DYNAMIC COMMENT ='正元日志表';
ROW_FORMAT = DYNAMIC COMMENT ='正元日志表';
-- ----------------------------
-- Table structure for third_zy_id_dict
-- ----------------------------
DROP TABLE IF EXISTS `third_zy_id_dict`;
CREATE TABLE `third_zy_id_dict`
(
`id` bigint NOT NULL COMMENT '主键',
`self_id` varchar(64) NOT NULL COMMENT '自己这边的id映射',
`zy_id` varchar(64) NOT NULL COMMENT '正元id映射',
`biz_type` tinytext(16) NOT NULL COMMENT '同步类型',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`create_by` varchar(32) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '创建人',
`update_by` varchar(32) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '更新人',
`del_flag` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '删除时间',
`tenant_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_general_ci
ROW_FORMAT = DYNAMIC COMMENT ='正元字典id对应 id + bizType 唯一';
@@ -138,6 +138,8 @@ public interface CacheConstants {
String THIRDPARTY_ZY_MER_TOKEN = "thirdparty:zy:mer_token";
String THIRDPARTY_ZY_REGION_TOKEN = "thirdparty:zy:region";
String THIRDPARTY_ZY_SELF_TOKEN = "thirdparty:zy:self_token:";
/* ************************************* end 第三方对接相关 end ************************************* */
@@ -138,6 +138,12 @@
<version>5.7.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.bsd</groupId>
<artifactId>pjcloud-wallet-biz</artifactId>
<version>5.7.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
<profile>
@@ -49,15 +49,6 @@ public class HardOrderTotalController {
/* ************************************* start 远程调用 start ************************************* */
@PostMapping("/zy-card-sync")
@Operation(summary = "正元本地一卡通交易数据同步")
public R<HardZyCardSyncVo> zyCardSync() {
HardOrderDto dto = new HardOrderDto();
dto.setOrderStatusCodes(HardOrderStatusEnum.getPayPrice());
dto.setOrderTypeCodes(HardOrderTypeEnum.getExternalCodes());
return R.ok(HardOrderTotalService.totalYearMonthDay(dto));
}
/* ************************************* end 远程调用 end ************************************* */
@PostMapping("/page-list-sb")
@@ -0,0 +1,31 @@
package com.bsd.pjcloud.hard.controller.third;
import com.bsd.pjcloud.common.core.util.R;
import com.bsd.pjcloud.hard.service.HardThirdZyService;
import com.bsd.pjcloud.wallet.api.vo.MchManageVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/hard-third-zy")
@Tag(description = "hard-third-zy", name = "正元同步")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HardThirdZyController {
private final HardThirdZyService hardThirdZyService;
@GetMapping("/sync-native-card-trade")
@Operation(summary = "交易数据同步")
public R<MchManageVo> syncNativeCardTrade() {
hardThirdZyService.syncNativeCardTradeInfo();
return R.ok();
}
}
@@ -0,0 +1,10 @@
package com.bsd.pjcloud.hard.service;
public interface HardThirdZyService {
/**
* 交易数据同步
*/
void syncNativeCardTradeInfo();
}
@@ -0,0 +1,69 @@
package com.bsd.pjcloud.hard.service.impl.third;
import cn.hutool.core.util.ObjectUtil;
import com.bsd.pjcloud.hard.api.constant.order.HardOrderStatusEnum;
import com.bsd.pjcloud.hard.api.constant.order.HardOrderTypeEnum;
import com.bsd.pjcloud.hard.api.dto.order.HardOrderDto;
import com.bsd.pjcloud.hard.api.vo.order.HardZyCardSyncVo;
import com.bsd.pjcloud.hard.service.HardOrderTotalService;
import com.bsd.pjcloud.hard.service.HardThirdZyService;
import com.bsd.pjcloud.thirdparty.api.feign.RemoterThirdZyService;
import com.bsd.pjcloud.thirdparty.dto.zy.foreign.ZyForeignSyncNativeCardTradeInfoDto;
import com.bsd.pjcloud.thirdparty.vo.zy.foreign.ZyForeignSyncNativeCardTradeInfoVo;
import com.bsd.pjcloud.wallet.service.MchThirdZyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Validated
@Slf4j
@RequiredArgsConstructor
@Service
public class HardThirdZyServiceImpl implements HardThirdZyService {
private static final String TAG = "硬件模块同步到正元信息";
private final RemoterThirdZyService thirdZyService;
private final HardOrderTotalService hardOrderTotalService;
/**
* 交易数据同步
*/
@Override
public void syncNativeCardTradeInfo() {
// 查询统计数据
HardOrderDto dto = new HardOrderDto();
dto.setOrderStatusCodes(HardOrderStatusEnum.getPayPrice());
dto.setOrderTypeCodes(HardOrderTypeEnum.getExternalCodes());
HardZyCardSyncVo total = hardOrderTotalService.totalYearMonthDay(dto);
if (ObjectUtil.isEmpty(total)) {
log.info("|{}|syncNativeCardTradeInfo交易数据同步到正元全部统计信息错误total为空", TAG);
return;
}
ZyForeignSyncNativeCardTradeInfoDto sync = new ZyForeignSyncNativeCardTradeInfoDto();
sync.setTotalMoney(parseMoney(total.getTotalMoney()));
sync.setTotalNum(total.getTotalNum());
sync.setTotalMoneyYear(parseMoney(total.getTotalMoneyYear()));
sync.setTotalNumYear(total.getTotalNumYear());
sync.setTotalMoneyMonth(parseMoney(total.getTotalMoneyMonth()));
sync.setTotalNumMonth(total.getTotalNumMonth());
sync.setTotalMoneyDay(parseMoney(total.getTotalMoneyDay()));
sync.setTotalNumDay(total.getTotalNumDay());
try {
ZyForeignSyncNativeCardTradeInfoVo res = thirdZyService.syncNativeCardTradeInfoApi(sync).getData();
if (ObjectUtil.isEmpty(res)) return;
} catch (Exception e) {
log.error("|{}syncNativeCardTradeInfo调用第三方接口错误|", TAG);
}
}
private BigDecimal parseMoney(Long money) {
if (ObjectUtil.isEmpty(money)) return BigDecimal.ZERO;
return BigDecimal.valueOf(money).divide(BigDecimal.valueOf(100)).setScale(2, RoundingMode.HALF_UP);
}
}
@@ -21,6 +21,7 @@ import com.bsd.pjcloud.thirdparty.vo.zy.stride.ZyStrideConsumptionVo;
import com.bsd.pjcloud.thirdparty.vo.zy.stride.ZyStrideCorrectVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@@ -34,7 +35,7 @@ public interface RemoterThirdZyService {
* 本地一卡通交易数据同步
*/
@NoToken
@GetMapping("/third-zy-foreign/sync-native-card")
@PostMapping("/third-zy-foreign/sync-native-card")
R<ZyForeignSyncNativeCardTradeInfoVo> syncNativeCardTradeInfoApi(@RequestBody ZyForeignSyncNativeCardTradeInfoDto dto);
/* ************************************* end 正元本地一卡通交易数据同步 end ************************************* */
@@ -46,28 +47,28 @@ public interface RemoterThirdZyService {
* 商户信息同步
*/
@NoToken
@GetMapping("/third-zy-mer/sync-dealer-info")
@PostMapping("/third-zy-mer/sync-dealer-info")
R<ZyMerSyncDealerInfoVo> syncDealerInfo(@RequestBody List<ZyMerSyncDealerInfoDto> dto);
/**
* 记账单位同步
*/
@NoToken
@GetMapping("/third-zy-mer/sync-enterprise-info")
@PostMapping("/third-zy-mer/sync-enterprise-info")
R<ZyMerSyncEnterpriseInfoVo> syncEnterpriseInfoApi(@RequestBody List<ZyMerSyncEnterpriseInfoDto> dto);
/**
* 账户信息同步
*/
@NoToken
@GetMapping("/third-zy-mer/sync-account-info")
@PostMapping("/third-zy-mer/sync-account-info")
R<ZyMerSyncAccountInfoVo> syncAccountInfoApi(@RequestBody List<ZyMerSyncAccountInfoDto> dto);
/**
* 身份信息同步
*/
@NoToken
@GetMapping("/third-zy-mer/sync-acc-class-info")
@PostMapping("/third-zy-mer/sync-acc-class-info")
R<ZyMerSyncAccClassInfoVo> syncAccClassInfoApi(@RequestBody List<ZyMerSyncAccClassInfoDto> dto);
/* ************************************* end 数据同步 end ************************************* */
@@ -78,21 +79,21 @@ public interface RemoterThirdZyService {
* 统一身份验证功能
*/
@NoToken
@GetMapping("/third-zy-stride/authentication")
@PostMapping("/third-zy-stride/authentication")
R<ZyStrideAuthenticationVo> authenticationApi(@RequestBody ZyStrideAuthenticationDto dto);
/**
* 智慧园区通刷平台提供消费接口
*/
@NoToken
@GetMapping("/third-zy-stride/consumption")
@PostMapping("/third-zy-stride/consumption")
R<ZyStrideConsumptionVo> consumptionApi(@RequestBody ZyStrideConsumptionDto dto);
/**
* 智慧园区通刷平台提供冲正接口
*/
@NoToken
@GetMapping("/third-zy-stride/correct")
@PostMapping("/third-zy-stride/correct")
R<ZyStrideCorrectVo> correctApi(@RequestBody ZyStrideCorrectDto dto);
/* ************************************* end 数据同步 end ************************************* */
@@ -24,17 +24,17 @@ public class ZyForeignSyncNativeCardTradeInfoDto {
/**
* 就餐总人数,从推广公务餐之日起,即总人数
*/
private Long totalNum;
private Long totalNum = 0L;
/**
* 就餐总金额,从推广公务餐之日起,即总金额
* 就餐总金额,从推广公务餐之日起,即总金额
*/
private BigDecimal totalMoney;
/**
* 当年就餐总人数,从当年1月1日开始
*/
private Long totalNumYear;
private Long totalNumYear = 0L;
/**
* 当年就餐总金额,从当年1月1日开始
@@ -44,7 +44,7 @@ public class ZyForeignSyncNativeCardTradeInfoDto {
/**
* 当月就餐总人数,从当月1日开始
*/
private Long totalNumMonth;
private Long totalNumMonth = 0L;
/**
* 当月就餐总金额,从当月1日开始
@@ -54,7 +54,7 @@ public class ZyForeignSyncNativeCardTradeInfoDto {
/**
* 当日就餐总人数
*/
private Long totalNumDay;
private Long totalNumDay = 0L;
/**
* 当日就餐总金额
@@ -0,0 +1,92 @@
package com.bsd.pjcloud.thirdparty.entity.zy;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import com.bsd.pjcloud.common.core.util.TenantTable;
import java.time.LocalDateTime;
/**
* 正元字典id对应 id + bizType 唯一
*
* @author third
* @date 2025-03-04 19:11:02
*/
@Data
@TenantTable
@TableName("third_zy_id_dict")
@EqualsAndHashCode(callSuper = true)
@Schema(description = "正元字典id对应 id + bizType 唯一")
public class ThirdZyIdDictEntity extends Model<ThirdZyIdDictEntity> {
/**
* 主键
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "主键")
private Long id;
/**
* 自己这边的id映射
*/
@Schema(description = "自己这边的id映射")
private String selfId;
/**
* 正元id映射
*/
@Schema(description = "正元id映射")
private String zyId;
/**
* 同步类型
*/
@Schema(description = "同步类型")
private String bizType;
/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建人")
private String createBy;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
@Schema(description = "创建时间")
private LocalDateTime createTime;
/**
* 更新人
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新人")
private String updateBy;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@Schema(description = "更新时间")
private LocalDateTime updateTime;
/**
* 删除时间
*/
@TableLogic
@TableField(fill = FieldFill.INSERT)
@Schema(description = "删除时间")
private String delFlag;
/**
* tenantId
*/
@Schema(description = "tenantId")
private Long tenantId;
}
@@ -18,10 +18,7 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -38,28 +35,28 @@ public class ThirdZyMerController {
@Inner
@Operation(summary = "商户信息同步")
@GetMapping("/sync-dealer-info")
@PostMapping("/sync-dealer-info")
public R<ZyMerSyncDealerInfoVo> syncDealerInfo(@RequestBody List<ZyMerSyncDealerInfoDto> dto) {
return R.ok(thirdZyMerService.syncDealerInfoApi(dto));
}
@Inner
@Operation(summary = "记账单位同步")
@GetMapping("/sync-enterprise-info")
@PostMapping("/sync-enterprise-info")
public R<ZyMerSyncEnterpriseInfoVo> syncEnterpriseInfoApi(@RequestBody List<ZyMerSyncEnterpriseInfoDto> dto) {
return R.ok(thirdZyMerService.syncEnterpriseInfoApi(dto));
}
@Inner
@Operation(summary = "账户信息同步")
@GetMapping("/sync-account-info")
@PostMapping("/sync-account-info")
public R<ZyMerSyncAccountInfoVo> syncAccountInfoApi(@RequestBody List<ZyMerSyncAccountInfoDto> dto) {
return R.ok(thirdZyMerService.syncAccountInfoApi(dto));
}
@Inner
@Operation(summary = "身份信息同步")
@GetMapping("/sync-acc-class-info")
@PostMapping("/sync-acc-class-info")
public R<ZyMerSyncAccClassInfoVo> syncAccClassInfoApi(@RequestBody List<ZyMerSyncAccClassInfoDto> dto) {
return R.ok(thirdZyMerService.syncAccClassInfoApi(dto));
}
@@ -0,0 +1,31 @@
package com.bsd.pjcloud.thirdparty.mapper.zy;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bsd.pjcloud.common.data.datascope.PjcloudBaseMapper;
import com.bsd.pjcloud.thirdparty.constant.ThirdZyBizEnumType;
import com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyIdDictEntity;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ThirdZyIdDictMapper extends PjcloudBaseMapper<ThirdZyIdDictEntity> {
default List<ThirdZyIdDictEntity> getBySelfIds(ThirdZyBizEnumType type, List<String> selfIds) {
if (ObjectUtil.isEmpty(type)) return null;
LambdaQueryWrapper<ThirdZyIdDictEntity> wrapper = new LambdaQueryWrapper<ThirdZyIdDictEntity>()
.in(ObjectUtil.isNotEmpty(selfIds), ThirdZyIdDictEntity::getSelfId, selfIds)
.eq(ThirdZyIdDictEntity::getBizType, type.getType());
return selectList(wrapper);
}
default List<ThirdZyIdDictEntity> getByZyIds(ThirdZyBizEnumType type, List<String> zyIds) {
if (ObjectUtil.isEmpty(type)) return null;
LambdaQueryWrapper<ThirdZyIdDictEntity> wrapper = new LambdaQueryWrapper<ThirdZyIdDictEntity>()
.in(ObjectUtil.isNotEmpty(zyIds), ThirdZyIdDictEntity::getZyId, zyIds)
.eq(ThirdZyIdDictEntity::getBizType, type.getType());
return selectList(wrapper);
}
}
@@ -0,0 +1,8 @@
package com.bsd.pjcloud.thirdparty.service.impl;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyIdDictEntity;
public interface ThirdZyIdDictService extends IService<ThirdZyIdDictEntity> {
}
@@ -4,6 +4,7 @@ import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.bsd.pjcloud.common.core.constant.CacheConstants;
import com.bsd.pjcloud.thirdparty.config.ZyConfig;
import com.bsd.pjcloud.thirdparty.dto.zy.foreign.ZyForeignSyncNativeCardTradeInfoDto;
import com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyLogEntity;
@@ -15,12 +16,14 @@ import com.bsd.pjcloud.thirdparty.vo.zy.foreign.ZyForeignGetRegionIdByTokenVo;
import com.bsd.pjcloud.thirdparty.vo.zy.foreign.ZyForeignSyncNativeCardTradeInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@Validated
@@ -34,8 +37,11 @@ public class ThirdZyForeignServiceImpl implements ThirdZyForeignService {
private final ZyApiTool zyApiTool;
private final StringRedisTemplate redisTemplate;
private final ThirdZyLogServiceImpl thirdZyLogService;
/**
* 本地一卡通交易数据同步
*/
@@ -45,6 +51,13 @@ public class ThirdZyForeignServiceImpl implements ThirdZyForeignService {
long startTime = System.currentTimeMillis();
String url = zyConfig.getBaseUrl() + ZyApi.Foreign.SYNC_NATIVE_CARD_TRADE_INFO;
try {
if (ObjectUtil.isEmpty(dto.getRegionCode())) {
ZyForeignGetRegionIdByTokenVo.VoData regionInfo = getRegionInfo();
if (ObjectUtil.isEmpty(regionInfo)) {
throw new RuntimeException("获取区域信息错误无法进行");
}
dto.setRegionCode(regionInfo.getRegionCode());
}
url = String.format(url, zyApiTool.getToken());
Map<String, Object> encryptionBody = new HashMap<>();
encryptionBody.put("regionCode", dto);
@@ -52,10 +65,7 @@ public class ThirdZyForeignServiceImpl implements ThirdZyForeignService {
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.form(body)
.execute()
.body();
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -116,4 +126,21 @@ public class ThirdZyForeignServiceImpl implements ThirdZyForeignService {
}
return null;
}
// 获取区域信息
private ZyForeignGetRegionIdByTokenVo.VoData getRegionInfo() {
String redisKey = CacheConstants.THIRDPARTY_ZY_REGION_TOKEN;
String regionJson = redisTemplate.opsForValue().get(redisKey);
if (ObjectUtil.isNotEmpty(regionJson)) {
return JSONUtil.toBean(regionJson, ZyForeignGetRegionIdByTokenVo.VoData.class);
}
try {
ZyForeignGetRegionIdByTokenVo.VoData regionInfo = getRegionIdByToken();
redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(regionInfo));
return regionInfo;
} catch (Exception e) {
log.error("|{}|获取区域信息错误无法进行,意外的错误error|{}|stack|{}|", TAG, e.getMessage(), e.getStackTrace());
return null;
}
}
}
@@ -0,0 +1,26 @@
package com.bsd.pjcloud.thirdparty.service.impl.zy;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyIdDictEntity;
import com.bsd.pjcloud.thirdparty.mapper.zy.ThirdZyIdDictMapper;
import com.bsd.pjcloud.thirdparty.service.impl.ThirdZyIdDictService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
/**
* 正元字典id对应 id + bizType 唯一
*
* @author third
* @date 2025-03-04 19:11:02
*/
@Service
@Validated
@Slf4j
@RequiredArgsConstructor
public class ThirdZyIdDictServiceImpl extends ServiceImpl<ThirdZyIdDictMapper, ThirdZyIdDictEntity> implements ThirdZyIdDictService {
}
@@ -41,14 +41,23 @@ public class ThirdZyMerServiceImpl implements ThirdZyMerService {
*/
@Override
public ZyMerSyncDealerInfoVo syncDealerInfoApi(List<ZyMerSyncDealerInfoDto> dto) {
ThirdZyBizEnumType bizTYpe = ThirdZyBizEnumType.SYNC_DEALER_INFO;
ThirdZyLogEntity entity = new ThirdZyLogEntity();
entity.setBizType(ThirdZyBizEnumType.SYNC_DEALER_INFO.getType());
entity.setBizType(bizTYpe.getType());
long startTime = System.currentTimeMillis();
if (ObjectUtil.isEmpty(dto)) {
return null;
}
// 转换部门id
List<String> deptList = dto.stream().map(ZyMerSyncDealerInfoDto::getEPID).distinct().toList();
Map<String, String> deptDdDict = zyApiTool.generateZyId(ThirdZyBizEnumType.SYNC_ENTERPRISE_INFO, deptList);
// 转换商户id
List<String> mchList = dto.stream().map(ZyMerSyncDealerInfoDto::getDealerKeyObj).distinct().toList();
Map<String, String> mchIdDict = zyApiTool.generateZyId(bizTYpe, mchList);
List<Map<String, Object>> listMap = new ArrayList<>();
for (ZyMerSyncDealerInfoDto v : dto) {
v.setEPID(deptDdDict.get(v.getEPID()));
v.setDealerKeyObj(mchIdDict.get(v.getDealerKeyObj()));
Map<String, Object> map = zyApiTool.removeEmptyMap(BeanUtil.beanToMap(v));
listMap.add(map);
}
@@ -89,23 +98,29 @@ public class ThirdZyMerServiceImpl implements ThirdZyMerService {
*/
@Override
public ZyMerSyncEnterpriseInfoVo syncEnterpriseInfoApi(List<ZyMerSyncEnterpriseInfoDto> dto) {
ThirdZyBizEnumType bizType = ThirdZyBizEnumType.SYNC_ENTERPRISE_INFO;
ThirdZyLogEntity entity = new ThirdZyLogEntity();
entity.setBizType(ThirdZyBizEnumType.SYNC_ENTERPRISE_INFO.getType());
entity.setBizType(bizType.getType());
long startTime = System.currentTimeMillis();
List<Map<String, Object>> listMap = new ArrayList<>();
// 转换zyId
List<String> list = dto.stream().map(ZyMerSyncEnterpriseInfoDto::getEPID).distinct().toList();
Map<String, String> idDict = zyApiTool.generateZyId(bizType, list);
for (ZyMerSyncEnterpriseInfoDto v : dto) {
v.setEPID(idDict.get(v.getEPID()));
Map<String, Object> map = zyApiTool.removeEmptyMap(BeanUtil.beanToMap(v));
listMap.add(map);
}
String url = zyConfig.getBaseUrl() + ZyApi.Mer.SYNC_ENTERPRISE_INFO;
try {
url = String.format(url, zyApiTool.getToken());
Map<String, Object> encryptionBody = new HashMap<>();
encryptionBody.put("enterprises", dto);
encryptionBody.put("enterprises", listMap);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.contentType("application/x-www-form-urlencoded")
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -142,12 +157,9 @@ public class ThirdZyMerServiceImpl implements ThirdZyMerService {
encryptionBody.put("accounts", dto);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -175,21 +187,29 @@ public class ThirdZyMerServiceImpl implements ThirdZyMerService {
*/
@Override
public ZyMerSyncAccClassInfoVo syncAccClassInfoApi(List<ZyMerSyncAccClassInfoDto> dto) {
ThirdZyBizEnumType bizType = ThirdZyBizEnumType.SYNC_ACC_CLASS_INFO;
ThirdZyLogEntity entity = new ThirdZyLogEntity();
entity.setBizType(bizType.getType());
long startTime = System.currentTimeMillis();
String url = zyConfig.getBaseUrl() + ZyApi.Mer.SYNC_ACC_CLASS_INFO;
try {
List<Map<String, Object>> listMap = new ArrayList<>();
// 转换zyId
List<String> roleList = dto.stream().map(ZyMerSyncAccClassInfoDto::getEPID).distinct().toList();
Map<String, String> roleIdDict = zyApiTool.generateZyId(bizType, roleList);
for (ZyMerSyncAccClassInfoDto v : dto) {
v.setEPID(roleIdDict.get(v.getEPID()));
Map<String, Object> map = zyApiTool.removeEmptyMap(BeanUtil.beanToMap(v));
listMap.add(map);
}
url = String.format(url, zyApiTool.getToken());
Map<String, Object> encryptionBody = new HashMap<>();
encryptionBody.put("accClasses", dto);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -51,12 +51,9 @@ public class ThirdZyStrideServiceImpl implements ThirdZyStrideService {
encryptionBody.put("dealers", dto);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -93,12 +90,9 @@ public class ThirdZyStrideServiceImpl implements ThirdZyStrideService {
encryptionBody.put("dealers", dto);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -135,12 +129,9 @@ public class ThirdZyStrideServiceImpl implements ThirdZyStrideService {
encryptionBody.put("dealers", dto);
entity.setApiUrl(url);
entity.setOrgReq(JSONUtil.toJsonStr(encryptionBody));
String body = zyApiTool.getEncryptionDto(encryptionBody);
entity.setEncipherReq(body);
String res = HttpRequest.post(url)
.body(body)
.execute()
.body();
Map<String, Object> body = zyApiTool.getEncryptionMap(encryptionBody);
entity.setEncipherReq(JSONUtil.toJsonStr(body));
String res = HttpRequest.post(url).form(body).execute().body();
if (ObjectUtil.isEmpty(res)) {
throw new RuntimeException("response is empty");
}
@@ -3,6 +3,7 @@ package com.bsd.pjcloud.thirdparty.utils.zy.api;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
@@ -10,6 +11,9 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bsd.pjcloud.common.core.constant.CacheConstants;
import com.bsd.pjcloud.thirdparty.config.ZyConfig;
import com.bsd.pjcloud.thirdparty.constant.ThirdZyBizEnumType;
import com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyIdDictEntity;
import com.bsd.pjcloud.thirdparty.mapper.zy.ThirdZyIdDictMapper;
import com.bsd.pjcloud.thirdparty.vo.zy.mer.ZyMerGetTokenVo;
import io.undertow.security.idm.DigestAlgorithm;
import lombok.RequiredArgsConstructor;
@@ -19,10 +23,10 @@ import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
@@ -37,6 +41,8 @@ public class ZyApiTool {
private final StringRedisTemplate redisTemplate;
private final ThirdZyIdDictMapper thirdZyIdDictMapper;
public ZyMerGetTokenVo getTokenApi() throws Exception {
String url = zyConfig.getBaseUrl() + ZyApi.Mer.GET_TOKEN;
url = String.format(url, zyConfig.getAppId(), zyConfig.getAppSecret());
@@ -63,24 +69,22 @@ public class ZyApiTool {
try {
String redisKey = CacheConstants.THIRDPARTY_ZY_MER_TOKEN;
String token = redisTemplate.opsForValue().get(redisKey);
if (ObjectUtil.isEmpty(token)) {
ZyMerGetTokenVo vo = getTokenApi();
if (ObjectUtil.isNotEmpty(vo)) {
String accessToken = vo.getAccess_token();
String expiresIn = vo.getExpires_in();
redisTemplate.opsForValue().set(redisKey, accessToken);
try {
long expiresInNum = Long.parseLong(expiresIn);
if (ObjectUtil.isNotEmpty(expiresInNum) && expiresInNum > 100) {
redisTemplate.expire(redisKey, expiresInNum - 100, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.error("|{}|意外的错误error|{}|stack|{}|", TAG, e.getMessage(), e.getStackTrace());
if (ObjectUtil.isNotEmpty(token)) return token;
ZyMerGetTokenVo vo = getTokenApi();
if (ObjectUtil.isNotEmpty(vo)) {
String accessToken = vo.getAccess_token();
String expiresIn = vo.getExpires_in();
redisTemplate.opsForValue().set(redisKey, accessToken);
try {
long expiresInNum = Long.parseLong(expiresIn);
if (ObjectUtil.isNotEmpty(expiresInNum) && expiresInNum > 100) {
redisTemplate.expire(redisKey, expiresInNum - 100, TimeUnit.SECONDS);
}
return accessToken;
} catch (Exception e) {
log.error("|{}|意外的错误error|{}|stack|{}|", TAG, e.getMessage(), e.getStackTrace());
}
return accessToken;
}
return token;
} catch (Exception e) {
log.error("|{}|token获取错误无法进行,意外的错误error|{}|", TAG, e.getMessage());
}
@@ -96,6 +100,51 @@ public class ZyApiTool {
return jsonString;
}
public Map<String, String> generateZyId(ThirdZyBizEnumType type, List<String> selfIds) {
if (!ObjectUtil.isAllNotEmpty(type, selfIds)) return null;
List<ThirdZyIdDictEntity> bySelfIdList = thirdZyIdDictMapper.getBySelfIds(type, selfIds);
if (ObjectUtil.isEmpty(bySelfIdList)) bySelfIdList = new ArrayList<>();
Map<String, String> result = new HashMap<>();
List<ThirdZyIdDictEntity> list = new ArrayList<>();
boolean hasDuplicate;
do {
// 标识是否有重复
hasDuplicate = false;
list.clear();
result.clear();
for (String v : selfIds) {
Optional<ThirdZyIdDictEntity> first = bySelfIdList.stream().filter(i -> ObjectUtil.equals(v, i.getSelfId()) && ObjectUtil.equals(type.getType(), i.getBizType())).findFirst();
if (first.isPresent()) {
result.put(v, first.get().getZyId());
continue;
}
ThirdZyIdDictEntity item = new ThirdZyIdDictEntity();
item.setSelfId(v);
item.setBizType(type.getType());
String randomNumber = RandomUtil.randomNumbers(3);
long epochMillis = Instant.now().toEpochMilli();
String zyId = epochMillis + randomNumber;
item.setZyId(zyId);
list.add(item);
result.put(v, zyId);
}
List<String> zyIds = list.stream().map(ThirdZyIdDictEntity::getZyId).toList();
if (zyIds.isEmpty()) {
hasDuplicate = true;
break;
}
List<ThirdZyIdDictEntity> repetitionList = thirdZyIdDictMapper.getByZyIds(type, zyIds);
if (ObjectUtil.isNotEmpty(repetitionList)) {
hasDuplicate = true;
break;
}
} while (hasDuplicate);
if (ObjectUtil.isNotEmpty(list)) {
thirdZyIdDictMapper.insert(list);
}
return result;
}
public Map<String, Object> getEncryptionMap(Map<String, Object> params) {
Map<String, Object> body = new HashMap<>();
body.put("data", params);
@@ -127,7 +176,7 @@ public class ZyApiTool {
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String) {
entry.setValue(Base64.encode((String) value).replaceAll("\\s+", ""));
entry.setValue(Base64.encode((String) value));
} else {
entry.setValue(Base64.encode(value.toString()));
}
@@ -0,0 +1,18 @@
<?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.bsd.pjcloud.thirdparty.mapper.zy.ThirdZyIdDictMapper">
<resultMap id="thirdZyIdDictMap" type="com.bsd.pjcloud.thirdparty.entity.zy.ThirdZyIdDictEntity">
<id property="id" column="id"/>
<result property="selfId" column="self_id"/>
<result property="zyId" column="zy_id"/>
<result property="bizType" column="biz_type"/>
<result property="createBy" column="create_by"/>
<result property="createTime" column="create_time"/>
<result property="updateBy" column="update_by"/>
<result property="updateTime" column="update_time"/>
<result property="delFlag" column="del_flag"/>
<result property="tenantId" column="tenant_id"/>
</resultMap>
</mapper>
@@ -78,7 +78,7 @@ public class ZyTest {
@Test
public void merSyncEnterpriseInfo() {
ZyMerSyncEnterpriseInfoDto dto = new ZyMerSyncEnterpriseInfoDto();
dto.setEPID("1");
dto.setEPID("0123456789012");
dto.setEPName("测试部门");
dto.setIsValid(1);
dto.setFixId("20190920100101");
@@ -22,8 +22,10 @@ package com.bsd.pjcloud.admin.api.feign;
import com.bsd.pjcloud.admin.api.entity.SysRole;
import com.bsd.pjcloud.common.core.constant.ServiceNameConstants;
import com.bsd.pjcloud.common.core.util.R;
import com.bsd.pjcloud.common.feign.annotation.NoToken;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@@ -46,7 +48,8 @@ public interface RemoteRoleService {
/**
*
*/
@GetMapping("/role/by-codes")
@NoToken
@PostMapping("/role/by-codes")
R<List<SysRole>> findRolesByCodes(@RequestBody List<String> codes);
}
@@ -74,7 +74,7 @@ public class WalletActiveController {
@PostMapping("/app/bind-card")
@SysLog("app绑定饭卡")
@Operation(summary = "app绑定饭卡")
public R<Boolean> appBindCard(@Validated(Group.APP.class) @RequestBody WalletActiveBindCardDto dto) {
public R<WalletActiveEntity> appBindCard(@Validated(Group.APP.class) @RequestBody WalletActiveBindCardDto dto) {
PjcloudUser user = SecurityUtils.getUser();
dto.setUserId(user.getId());
return R.ok(walletActiveService.bindCard(dto));
@@ -95,7 +95,7 @@ public class WalletActiveController {
@SysLog("admin管理员绑定饭卡")
@Idempotent(info = "正在处理中,请勿重复提交")
@PreAuthorize("@pms.hasPermission('wallet_walletActive_bind_card')")
public R<Boolean> adminBindCard(@Validated(Group.ADMIN.class) @RequestBody WalletActiveBindCardDto dto) {
public R<WalletActiveEntity> adminBindCard(@Validated(Group.ADMIN.class) @RequestBody WalletActiveBindCardDto dto) {
return R.ok(walletActiveService.adminBindCard(dto));
}
@@ -1,7 +1,5 @@
package com.bsd.pjcloud.wallet.controller.third;
import cn.hutool.core.util.ObjectUtil;
import com.bsd.pjcloud.common.core.util.R;
import com.bsd.pjcloud.wallet.api.vo.MchManageVo;
import com.bsd.pjcloud.wallet.service.MchThirdZyService;
@@ -13,13 +11,12 @@ import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/mch-third-zy")
@Tag(description = "wallet-active", name = "钱包开卡管理")
@Tag(description = "mch-third-zy", name = "正元同步")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Validated
public class MchThirdZyController {
@@ -28,15 +25,29 @@ public class MchThirdZyController {
@GetMapping("/sync-all-mch")
@Operation(summary = "同步全部商户")
public R<MchManageVo> syncAllMch(@RequestParam Long id) {
mchThirdZyService.syncAllMch();
public R<MchManageVo> syncAllMch() {
mchThirdZyService.syncAllMch(null);
return R.ok();
}
@GetMapping("/sync-all-dept")
@Operation(summary = "同步全部商户部门")
public R<MchManageVo> syncAllDept() {
mchThirdZyService.syncAllDept();
mchThirdZyService.syncAllDept(null);
return R.ok();
}
@GetMapping("/sync-all-role")
@Operation(summary = "同步全部身份")
public R<MchManageVo> syncAllRole() {
mchThirdZyService.syncAllRole();
return R.ok();
}
@GetMapping("/sync-all-user")
@Operation(summary = "同步全部用户")
public R<MchManageVo> syncAllUser() {
mchThirdZyService.syncAllUser(null);
return R.ok();
}
@@ -39,6 +39,7 @@ public interface MchManageMapper extends PjcloudBaseMapper<MchManageEntity> {
default List<MchManageVo> list(MchManageDto dto) {
MPJLambdaQueryWrapper<MchManageEntity> wrapper = new MPJLambdaQueryWrapper<MchManageEntity>()
.selectAll(MchManageEntity.class)
.eq(ObjectUtil.isNotEmpty(dto.getId()), MchManageEntity::getId, dto.getId())
.likeIfExists(MchManageEntity::getName, dto.getName())
.in(ObjectUtil.isNotEmpty(dto.getDeptIds()), MchManageEntity::getDeptId, dto.getDeptIds())
.in(ObjectUtil.isNotEmpty(dto.getIds()), MchManageEntity::getId, dto.getIds())
@@ -31,7 +31,7 @@ public interface WalletActiveMapper extends PjcloudBaseMapper<WalletActiveEntity
.like(ObjectUtil.isNotEmpty(dto.getCardNumber()), WalletActiveEntity::getCardNumber, dto.getCardNumber())
.eq(ObjectUtil.isNotEmpty(dto.getIsActiveHardware()), WalletActiveEntity::getIsActiveHardware, dto.getIsActiveHardware())
.eq(ObjectUtil.isNotEmpty(dto.getDeptId()), WalletActiveEntity::getDeptId, dto.getDeptId())
.in(ObjectUtil.isNotEmpty(dto.getUserIds()), WalletActiveEntity::getId, dto.getUserIds())
.in(ObjectUtil.isNotEmpty(dto.getUserIds()), WalletActiveEntity::getUserId, dto.getUserIds())
.orderByDesc(WalletActiveEntity::getCardSort);
Page list = selectPageByScope(page, wrapper, DataScope.of());
list.setRecords(BeanUtils.toBean(list.getRecords(), WalletActiveVo.class));
@@ -5,17 +5,17 @@ public interface MchThirdZyService {
/**
* 同步全部商户
*/
void syncAllMch();
void syncAllMch(Long mchId);
/**
* 同步全部商户部门
*/
void syncAllDept();
void syncAllDept(Long deptId);
/**
* 同步到正元全部身份信息
* 同步到正元全部账户信息
*/
void syncAllUser();
void syncAllUser(Long userId);
/**
* 同步到正元全部身份信息
@@ -2,10 +2,10 @@ package com.bsd.pjcloud.wallet.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bsd.pjcloud.common.security.service.PjcloudUser;
import com.bsd.pjcloud.wallet.api.dto.WalletActiveBindCardDto;
import com.bsd.pjcloud.wallet.api.dto.WalletActiveDto;
import com.bsd.pjcloud.wallet.api.entity.WalletActiveEntity;
import com.bsd.pjcloud.wallet.api.entity.WalletManageEntity;
import com.bsd.pjcloud.wallet.api.vo.WalletActiveVo;
import jakarta.validation.constraints.NotEmpty;
@@ -37,9 +37,11 @@ public interface WalletActiveService extends IService<WalletActiveEntity> {
* @param dto
* @return
*/
Boolean bindCard(WalletActiveBindCardDto dto);
WalletActiveEntity bindCard(WalletActiveBindCardDto dto);
Boolean adminBindCard(WalletActiveBindCardDto dto);
WalletActiveEntity adminBindCard(WalletActiveBindCardDto dto);
void createAndActiveCard(WalletManageEntity dto);
/**
* 取消绑定饭卡
@@ -122,7 +122,7 @@ public class WalletActiveServiceImpl extends ServiceImpl<WalletActiveMapper, Wal
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean bindCard(WalletActiveBindCardDto dto) {
public WalletActiveEntity bindCard(WalletActiveBindCardDto dto) {
WalletActiveEntity walletActive = getByCardNumber(dto.getCardNumber());
if (ObjectUtil.isEmpty(walletActive)) {
throw new RuntimeException("卡号不存在");
@@ -141,11 +141,11 @@ public class WalletActiveServiceImpl extends ServiceImpl<WalletActiveMapper, Wal
// 更新用户钱包
WalletManageEntity walletObj = WalletManageEntity.builder().id(selfWallet.getId()).cardNumber(walletActive.getCardNumber()).activeBindStatus(YesNoEnum.YES.getCode()).activeBindTime(LocalDateTime.now()).build();
walletManageService.updateById(walletObj);
return true;
return baseMapper.selectById(walletActiveObj.getId());
}
@Override
public Boolean adminBindCard(WalletActiveBindCardDto dto) {
public WalletActiveEntity adminBindCard(WalletActiveBindCardDto dto) {
// 查询饭卡钱包
WalletManageEntity wallet = walletManageService.getWallet(dto.getUserId(), WalletTypeEnum.EAT);
if (ObjectUtil.isEmpty(wallet)) {
@@ -155,6 +155,37 @@ public class WalletActiveServiceImpl extends ServiceImpl<WalletActiveMapper, Wal
return getSelf().bindCard(dto);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void createAndActiveCard(WalletManageEntity wallet) {
if (ObjectUtil.isEmpty(wallet) || ObjectUtil.isNotEmpty(wallet.getCardNumber())) return;
// 查询用户所属于的商户
MchManageVo mch = mchManageService.getFirstMchByDeptId(wallet.getDeptId());
if (ObjectUtil.isEmpty(mch)) return;
LambdaQueryWrapper<WalletActiveEntity> wrapper = new LambdaQueryWrapper<WalletActiveEntity>()
.isNull(WalletActiveEntity::getUserId)
.isNull(WalletActiveEntity::getWalletId)
.eq(WalletActiveEntity::getMerchantId, mch.getId())
.eq(WalletActiveEntity::getIsActiveHardware, YesNoEnum.NO.getCode());
Long count = baseMapper.selectCount(wrapper);
if (count <= 1) {
WalletActiveDto createCardDto = new WalletActiveDto();
createCardDto.setCount(20L);
createCardDto.setMerchantId(mch.getId());
getSelf().fastCreateCard(createCardDto);
}
LambdaQueryWrapper<WalletActiveEntity> selectOneWrapper = wrapper.clone().orderByAsc(WalletActiveEntity::getCardSort).last("limit 1");
WalletActiveEntity walletActive = baseMapper.selectOne(selectOneWrapper);
if (ObjectUtil.isNotEmpty(walletActive)) {
// 绑定饭卡
WalletActiveBindCardDto walletActiveDto = new WalletActiveBindCardDto();
walletActiveDto.setUserId(wallet.getUserId());
walletActiveDto.setWalletId(wallet.getId());
walletActiveDto.setCardNumber(walletActive.getCardNumber());
getSelf().bindCard(walletActiveDto);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean cancelAdminBindCard(Long activeId) {
@@ -43,6 +43,7 @@ import com.bsd.pjcloud.wallet.api.vo.WalletManageVo;
import com.bsd.pjcloud.wallet.api.vo.WalletSettingVo;
import com.bsd.pjcloud.wallet.mapper.WalletManageMapper;
import com.bsd.pjcloud.wallet.mapper.WalletTypeMapper;
import com.bsd.pjcloud.wallet.service.WalletActiveService;
import com.bsd.pjcloud.wallet.service.WalletManageService;
import com.bsd.pjcloud.wallet.service.WalletSettingService;
import com.bsd.pjcloud.wallet.service.WalletTypeService;
@@ -50,6 +51,7 @@ import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -80,6 +82,8 @@ public class WalletManageServiceImpl extends ServiceImpl<WalletManageMapper, Wal
private final WalletTypeService walletTypeService;
private final WalletSettingService walletSettingService;
@Lazy
private final WalletActiveService walletActiveService;
private final RemoteUserService userService;
private final RemoteDeptService deptService;
@@ -116,12 +120,18 @@ public class WalletManageServiceImpl extends ServiceImpl<WalletManageMapper, Wal
.eq(WalletManageEntity::getUserId, userId)
.eq(WalletManageEntity::getWalletTypeId, v.getId())
);
if (ObjectUtil.isNotEmpty(wallet)) continue;
// 创建钱包
WalletManageEntity insertObj = new WalletManageEntity();
insertObj.setUserId(userId);
insertObj.setWalletTypeId(v.getId());
insertObj.setDeptId(user.getSysUser().getDeptId());
baseMapper.insert(insertObj);
if (ObjectUtil.isEmpty(wallet)) {
insertObj.setUserId(userId);
insertObj.setWalletTypeId(v.getId());
insertObj.setDeptId(user.getSysUser().getDeptId());
baseMapper.insert(insertObj);
}
// 默认创建饭卡并绑定饭卡钱包
if (ObjectUtil.equals(v.getUniqueCode(), WalletTypeEnum.EAT.getCode())) {
walletActiveService.createAndActiveCard(wallet);
}
}
}
@@ -1,11 +1,17 @@
package com.bsd.pjcloud.wallet.service.impl.thrid;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsd.pjcloud.admin.api.dto.UserInfo;
import com.bsd.pjcloud.admin.api.entity.SysDept;
import com.bsd.pjcloud.admin.api.entity.SysRole;
import com.bsd.pjcloud.admin.api.feign.RemoteDeptService;
import com.bsd.pjcloud.admin.api.feign.RemoteRoleService;
import com.bsd.pjcloud.admin.api.feign.RemoteUserService;
import com.bsd.pjcloud.common.data.datascope.DataScope;
import com.bsd.pjcloud.common.data.datascope.DataScopeFuncEnum;
import com.bsd.pjcloud.thirdparty.api.feign.RemoterThirdZyService;
@@ -17,14 +23,18 @@ import com.bsd.pjcloud.thirdparty.vo.zy.mer.ZyMerSyncAccClassInfoVo;
import com.bsd.pjcloud.thirdparty.vo.zy.mer.ZyMerSyncAccountInfoVo;
import com.bsd.pjcloud.thirdparty.vo.zy.mer.ZyMerSyncDealerInfoVo;
import com.bsd.pjcloud.thirdparty.vo.zy.mer.ZyMerSyncEnterpriseInfoVo;
import com.bsd.pjcloud.wallet.api.constant.WalletTypeEnum;
import com.bsd.pjcloud.wallet.api.dto.MchManageDto;
import com.bsd.pjcloud.wallet.api.dto.WalletManageDto;
import com.bsd.pjcloud.wallet.api.entity.MchManageEntity;
import com.bsd.pjcloud.wallet.api.entity.WalletManageEntity;
import com.bsd.pjcloud.wallet.api.entity.WalletTypeEntity;
import com.bsd.pjcloud.wallet.api.vo.MchManageVo;
import com.bsd.pjcloud.wallet.api.vo.WalletManageVo;
import com.bsd.pjcloud.wallet.service.MchManageService;
import com.bsd.pjcloud.wallet.service.MchThirdZyService;
import com.bsd.pjcloud.wallet.service.WalletManageService;
import com.bsd.pjcloud.wallet.service.WalletTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -32,6 +42,7 @@ import org.springframework.validation.annotation.Validated;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Validated
@Slf4j
@@ -41,61 +52,75 @@ public class MchThirdZyServiceImpl implements MchThirdZyService {
private static final String TAG = "用户模块同步到正元信息";
private static final String DEFAULT_USER_ROLE_CODE = "GENERAL_USER";
private final RemoterThirdZyService thirdZyService;
private final RemoteDeptService remoteDeptService;
private final RemoteRoleService remoteRoleService;
private final RemoteUserService remoteUserService;
private final MchManageService mchManageService;
private final WalletManageService walletManageService;
private final WalletTypeService walletTypeService;
/**
* 同步全部商户
*/
@Override
public void syncAllMch() {
List<MchManageEntity> mchList = mchManageService.list();
public void syncAllMch(Long mchId) {
MchManageDto dto = new MchManageDto();
dto.setId(mchId);
List<MchManageVo> mchList = mchManageService.list(dto);
if (ObjectUtil.isEmpty(mchList)) {
log.info("|{}|同步到正元全部商户信息错误mchList为空", TAG);
return;
}
List<ZyMerSyncDealerInfoDto> syncList = new ArrayList<>();
for (MchManageEntity v : mchList) {
for (MchManageVo v : mchList) {
ZyMerSyncDealerInfoDto entity = new ZyMerSyncDealerInfoDto();
entity.setDealerKeyObj(v.getId().toString());
entity.setDealerName(v.getName());
entity.setIsValid(1);
entity.setEPID("");
entity.setEPID(v.getDeptId().toString());
entity.setFixId(getSyncAllMchVersion());
syncList.add(entity);
}
ZyMerSyncDealerInfoVo res = thirdZyService.syncDealerInfo(syncList).getData();
try {
ZyMerSyncDealerInfoVo res = thirdZyService.syncDealerInfo(syncList).getData();
if (ObjectUtil.isEmpty(res)) return;
} catch (Exception e) {
log.error("|{}syncAllMch 调用第三方接口错误|", TAG);
}
}
/**
* 同步全部商户部门
*/
@Override
public void syncAllDept() {
List<SysDept> mchList = remoteDeptService.getAllDept(null).getData();
public void syncAllDept(Long mchId) {
// List<SysDept> mchList = remoteDeptService.getAllDept(null).getData();
MchManageDto dto = new MchManageDto();
dto.setId(mchId);
List<MchManageVo> mchList = mchManageService.list(dto);
if (ObjectUtil.isEmpty(mchList)) {
log.info("|{}|同步到正元全部商户部门信息错误mchList为空", TAG);
return;
}
List<ZyMerSyncEnterpriseInfoDto> syncList = new ArrayList<>();
for (SysDept v : mchList) {
String syncAllMchVersion = getSyncAllMchVersion();
for (MchManageVo v : mchList) {
ZyMerSyncEnterpriseInfoDto entity = new ZyMerSyncEnterpriseInfoDto();
entity.setEPID(v.getDeptId().toString());
entity.setEPName(v.getName());
entity.setEPName(v.getDeptName());
entity.setIsValid(1);
entity.setFixId(getSyncAllMchVersion());
entity.setFixId(syncAllMchVersion);
syncList.add(entity);
}
ZyMerSyncEnterpriseInfoVo res = thirdZyService.syncEnterpriseInfoApi(syncList).getData();
}
@Override
public void syncAllUser() {
Page page = new Page();
page.setCurrent(1);
page.setSize(500);
boolean isResidue = true;
while (isResidue) {
isResidue = syncAllUserGroup(page);
if (!isResidue) break;
try {
ZyMerSyncEnterpriseInfoVo res = thirdZyService.syncEnterpriseInfoApi(syncList).getData();
if (ObjectUtil.isEmpty(res)) return;
} catch (Exception e) {
log.error("|{}syncAllDept 调用第三方接口错误|", TAG);
}
}
@@ -105,72 +130,136 @@ public class MchThirdZyServiceImpl implements MchThirdZyService {
@Override
public void syncAllRole() {
// 查询需要同步的身份信息
List<SysRole> roleList = remoteRoleService.findRolesByCodes(List.of("GENERAL_USER")).getData();
List<SysRole> roleList = remoteRoleService.findRolesByCodes(List.of(DEFAULT_USER_ROLE_CODE)).getData();
if (ObjectUtil.isEmpty(roleList)) {
log.info("|{}|同步到正元全部身份信息错误roleList为空", TAG);
return;
}
List<ZyMerSyncAccClassInfoDto> syncList = new ArrayList<>();
String syncAllMchVersion = getSyncAllMchVersion();
for (SysRole v : roleList) {
ZyMerSyncAccClassInfoDto entity = new ZyMerSyncAccClassInfoDto();
entity.setAccClassID(v.getRoleId().toString());
entity.setAccClassName(v.getRoleName());
entity.setEPID("1");
entity.setFixId(getSyncAllRoleVersion());
entity.setFixId(syncAllMchVersion);
syncList.add(entity);
}
ZyMerSyncAccClassInfoVo res = thirdZyService.syncAccClassInfoApi(syncList).getData();
try {
ZyMerSyncAccClassInfoVo res = thirdZyService.syncAccClassInfoApi(syncList).getData();
if (ObjectUtil.isEmpty(res)) return;
} catch (Exception e) {
log.error("|{}syncAllRole 调用第三方接口错误|", TAG);
}
}
private boolean syncAllUserGroup(Page page) {
/**
* 同步到正元全部账户信息
*/
@Override
public void syncAllUser(Long userId) {
Page page = new Page();
page.setCurrent(1);
page.setSize(100);
// 查询身份信息
List<SysRole> roleList = remoteRoleService.findRolesByCodes(List.of(DEFAULT_USER_ROLE_CODE)).getData();
if (ObjectUtil.isEmpty(roleList)) {
log.error("|{}|syncAllUser 同步到正元全部身份信息错误roleList为空", TAG);
return;
}
Optional<SysRole> defaultUserRole = roleList.stream().filter(v -> ObjectUtil.equals(v.getRoleCode(), DEFAULT_USER_ROLE_CODE)).findFirst();
if (defaultUserRole.isEmpty()) {
log.error("|{}|syncAllUser 同步到正元全部身份信息错误defaultUserRole为空", TAG);
return;
}
// 查询饭卡钱包信息
WalletTypeEntity walletType = walletTypeService.getByUniqueCode(WalletTypeEnum.EAT);
if (ObjectUtil.isEmpty(walletType)) {
log.error("|{}|syncAllUser 同步到正元全部身份信息错误walletType为空", TAG);
return;
}
while (true) {
boolean isNotEmpty = syncAllUserGroup(page, userId, defaultUserRole.get().getRoleId(), walletType.getId());
if (!isNotEmpty) break;
}
}
private boolean syncAllUserGroup(Page page, Long userId, Long roleId, Long walletTypeId) {
WalletManageDto query = new WalletManageDto();
query.setWalletTypeId(walletTypeId);
if (ObjectUtil.isNotEmpty(userId)) query.setUserId(userId);
DataScope dataScope = DataScope.of();
dataScope.func(DataScopeFuncEnum.ALL);
Page<WalletManageVo> userPage = walletManageService.scopePageList(page, query, dataScope);
if (ObjectUtil.isEmpty(userPage.getRecords())) return false;
List<ZyMerSyncAccountInfoDto> syncList = new ArrayList<>();
String syncAllMchVersion = getSyncAllMchVersion();
for (WalletManageVo v : userPage.getRecords()) {
// 查询用户
UserInfo user = remoteUserService.getByUserId(v.getUserId()).getData();
if (ObjectUtil.isEmpty(user)) {
log.error("|{}|syncAllUserGroup用户不存在为空WalletManageVo|{}|", TAG, JSONUtil.toJsonStr(v));
continue;
}
MchManageVo mch = mchManageService.getFirstMchByDeptId(user.getSysUser().getDeptId());
if (ObjectUtil.isEmpty(mch)) {
log.error("|{}|syncAllUserGroup用户部门商户id为空WalletManageVo|{}|", TAG, JSONUtil.toJsonStr(v));
continue;
}
if (ObjectUtil.isEmpty(v.getCardNumber())) {
walletManageService.createWallet(v.getUserId());
WalletManageEntity wallet = walletManageService.getWallet(v.getId());
if (ObjectUtil.isNotEmpty(wallet)) {
v.setCardNumber(wallet.getCardNumber());
}
}
ZyMerSyncAccountInfoDto item = new ZyMerSyncAccountInfoDto();
item.setAccName(v.getUsername());
item.setAccNum(v.getUserId().toString());
item.setCardAccNum(v.getId());
item.setCardSID(v.getCardNumber());
item.setCardStatus(getCardStatus(v.getCardNumber()));
item.setEPID("");
item.setAccClassID("");
item.setCardStatus(getCardStatus(v.getUserId(), v.getCardNumber()));
item.setEPID(mch.getDeptId().toString());
item.setAccClassID(roleId.toString());
item.setPhoneNo(v.getUserMobile());
item.setFixId(getSyncAllUserVersion());
item.setFixId(syncAllMchVersion);
syncList.add(item);
}
ZyMerSyncAccountInfoVo res = thirdZyService.syncAccountInfoApi(syncList).getData();
// try {
// ZyMerSyncAccountInfoVo res = thirdZyService.syncAccountInfoApi(syncList).getData();
// if (ObjectUtil.isEmpty(res)) return false;
// } catch (Exception e) {
// log.error("|{}syncAllUserGroup 调用第三方接口错误|", TAG);
// return false;
// }
return userPage.getTotal() > 0;
}
/* ************************************* start 版本号 start ************************************* */
/* ************************************* start 工具类 start ************************************* */
private String getSyncAllMchVersion() {
return String.format("%014d", 2);
return LocalDateTimeUtil.format(LocalDateTimeUtil.now(), DatePattern.PURE_DATETIME_PATTERN);
}
private String getSyncAllDeptVersion() {
return String.format("%014d", 2);
}
private String getSyncAllUserVersion() {
return String.format("%014d", 1);
}
private String getSyncAllRoleVersion() {
return String.format("%014d", 1);
}
/* ************************************* end 版本号 end ************************************* */
// 卡片状态,0销卡;1有效;2挂失;3冻结;4预销卡;5锁卡,默认1
private Integer getCardStatus(String cardNumber) {
return 0;
private Integer getCardStatus(Long userId, String cardNumber) {
if (!ObjectUtil.isAllNotEmpty(userId, cardNumber)) {
throw new RuntimeException();
}
try {
// 创建并绑定钱包
walletManageService.createWallet(userId);
return 1;
} catch (Exception e) {
String msg = String.format("|{}|getCardStatus意外的错误", TAG);
log.error(msg, e);
throw new RuntimeException(msg, e);
}
}
/* ************************************* end 工具类 end ************************************* */
}