mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 07:09:20 +08:00
feat: 新增拼多多店铺授权
This commit is contained in:
+1
@@ -46,6 +46,7 @@ public class SecurityConfig {
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/auth/login", "/auth/register", "/auth/refresh").permitAll()
|
||||
.requestMatchers("/ec/pdd/auth/callback").permitAll()
|
||||
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
|
||||
.requestMatchers("/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-resources/**",
|
||||
"/swagger-ui/**", "/swagger-ui.html")
|
||||
|
||||
+4
-1
@@ -29,7 +29,10 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
@Override
|
||||
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
return uri != null && uri.startsWith("/open/");
|
||||
if (uri == null) {
|
||||
return false;
|
||||
}
|
||||
return uri.startsWith("/open/") || uri.startsWith("/ec/pdd/auth/callback");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 拼多多 OAuth 配置
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "pdd.oauth")
|
||||
public class PddOAuthProperties {
|
||||
|
||||
/** 应用 client_id */
|
||||
private String clientId = "";
|
||||
|
||||
/** 应用 client_secret */
|
||||
private String clientSecret = "";
|
||||
|
||||
/** 回调地址(须与开放平台应用配置一致,指向后端 /ec/pdd/auth/callback) */
|
||||
private String redirectUri = "";
|
||||
|
||||
/** 店铺 WEB 授权页 */
|
||||
private String authorizeUrl = "https://fuwu.pinduoduo.com/service-market/auth";
|
||||
|
||||
/** state 在 Redis 中的有效期(秒) */
|
||||
private long stateTtlSeconds = 600;
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddAuthService;
|
||||
|
||||
/**
|
||||
* 拼多多 OAuth 授权
|
||||
*/
|
||||
@Tag(name = "拼多多-授权", description = "拼多多店铺 OAuth 授权跳转与回调")
|
||||
@RestController
|
||||
@RequestMapping("/ec/pdd/auth")
|
||||
public class PddAuthController {
|
||||
|
||||
private final PddAuthService pddAuthService;
|
||||
|
||||
public PddAuthController(PddAuthService pddAuthService) {
|
||||
this.pddAuthService = pddAuthService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取授权跳转 URL", description = "为指定内部店铺生成拼多多授权页链接,前端新窗口打开后引导商家授权")
|
||||
@GetMapping("/authorize-url")
|
||||
@RequirePermission(value = "biz:pdd:auth:manage", description = "拼多多授权管理", allowSuper = true)
|
||||
public ApiResponse<PddAuthorizeUrlVO> authorizeUrl(
|
||||
@Parameter(description = "内部店铺 ID(ec_shop.id)", required = true)
|
||||
@RequestParam("shopId") Long shopId) {
|
||||
return ApiResponse.success(pddAuthService.buildAuthorizeUrl(shopId));
|
||||
}
|
||||
|
||||
@Operation(summary = "授权回调", description = "拼多多回调入口:接收 code 换取 token、绑定内部店铺,返回提示 HTML(3 秒后关闭)")
|
||||
@GetMapping(value = "/callback", produces = MediaType.TEXT_HTML_VALUE)
|
||||
public ResponseEntity<String> callback(
|
||||
@Parameter(description = "授权码") @RequestParam(value = "code", required = false) String code,
|
||||
@Parameter(description = "自定义 state") @RequestParam(value = "state", required = false) String state) {
|
||||
String html = pddAuthService.handleCallback(code, state);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.TEXT_HTML)
|
||||
.body(html);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
|
||||
|
||||
@Mapper
|
||||
public interface PddAuthMapper extends BaseMapper<PddAuthPO> {
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 拼多多 OAuth 授权凭证
|
||||
*/
|
||||
@Data
|
||||
@TableName("ec_pdd_auth")
|
||||
public class PddAuthPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
/** 拼多多授权主体 ID(等同 mall_id) */
|
||||
@TableField("owner_id")
|
||||
private String ownerId;
|
||||
|
||||
@TableField("access_token")
|
||||
private String accessToken;
|
||||
|
||||
@TableField("refresh_token")
|
||||
private String refreshToken;
|
||||
|
||||
@TableField("expires_at")
|
||||
private LocalDateTime expiresAt;
|
||||
|
||||
@TableField("refresh_token_expires_at")
|
||||
private LocalDateTime refreshTokenExpiresAt;
|
||||
|
||||
/** scope JSON 数组字符串 */
|
||||
@TableField("scope")
|
||||
private String scope;
|
||||
|
||||
/** 最近一次授权完整响应 JSON */
|
||||
@TableField("raw_response")
|
||||
private String rawResponse;
|
||||
|
||||
/** 状态:0=失效 1=正常 2=已撤销 */
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@Schema(description = "拼多多授权跳转信息")
|
||||
public class PddAuthorizeUrlVO {
|
||||
|
||||
@Schema(description = "拼多多授权页完整 URL,前端直接打开")
|
||||
private String authorizeUrl;
|
||||
|
||||
@Schema(description = "本次授权 state(调试用;回调时拼多多会原样带回)")
|
||||
private String state;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
|
||||
|
||||
/**
|
||||
* 拼多多 OAuth 授权服务
|
||||
*/
|
||||
public interface PddAuthService {
|
||||
|
||||
/**
|
||||
* 生成授权跳转 URL(需登录;绑定指定内部店铺)
|
||||
*
|
||||
* @param shopId 内部店铺 ID(ec_shop.id)
|
||||
*/
|
||||
PddAuthorizeUrlVO buildAuthorizeUrl(Long shopId);
|
||||
|
||||
/**
|
||||
* 处理授权回调:用 code 换 token、同步 PDD 店铺,并将外部店绑定到 state 中的内部店铺
|
||||
*
|
||||
* @return 提示用 HTML 页面(3 秒后尝试关闭窗口)
|
||||
*/
|
||||
String handleCallback(String code, String state);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service;
|
||||
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.PopHttpClient;
|
||||
import com.pdd.pop.sdk.http.PopAccessTokenClient;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
|
||||
|
||||
/**
|
||||
* 拼多多 POP SDK 客户端工厂
|
||||
*/
|
||||
@Component
|
||||
public class PddPopClientFactory {
|
||||
|
||||
private final PddOAuthProperties properties;
|
||||
|
||||
public PddPopClientFactory(PddOAuthProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public PopAccessTokenClient createAccessTokenClient() {
|
||||
assertConfigured();
|
||||
return new PopAccessTokenClient(properties.getClientId(), properties.getClientSecret());
|
||||
}
|
||||
|
||||
public PopClient createHttpClient() {
|
||||
assertConfigured();
|
||||
return new PopHttpClient(properties.getClientId(), properties.getClientSecret());
|
||||
}
|
||||
|
||||
private void assertConfigured() {
|
||||
if (!StringUtils.hasText(properties.getClientId())
|
||||
|| !StringUtils.hasText(properties.getClientSecret())) {
|
||||
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
|
||||
}
|
||||
}
|
||||
}
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.pdd.pop.sdk.http.PopAccessTokenClient;
|
||||
import com.pdd.pop.sdk.http.PopClient;
|
||||
import com.pdd.pop.sdk.http.api.pop.request.PddMallInfoGetRequest;
|
||||
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
|
||||
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.config.PddOAuthProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.mapper.PddAuthMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.po.PddAuthPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.model.vo.PddAuthorizeUrlVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddAuthService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.auth.service.PddPopClientFactory;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 拼多多 OAuth 授权服务实现:生成授权链接、处理回调换票、同步外部店并绑定内部店。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PddAuthServiceImpl implements PddAuthService {
|
||||
|
||||
private static final String STATE_KEY_PREFIX = "pdd:oauth:state:";
|
||||
private static final String PLATFORM_CODE_PDD = "pdd";
|
||||
|
||||
private final PddOAuthProperties properties;
|
||||
private final PddPopClientFactory popClientFactory;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PddAuthMapper pddAuthMapper;
|
||||
private final PddShopMapper pddShopMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final PlatformMapper platformMapper;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PddAuthServiceImpl(PddOAuthProperties properties,
|
||||
PddPopClientFactory popClientFactory,
|
||||
StringRedisTemplate stringRedisTemplate,
|
||||
CurrentUserContext currentUserContext,
|
||||
PddAuthMapper pddAuthMapper,
|
||||
PddShopMapper pddShopMapper,
|
||||
ShopMapper shopMapper,
|
||||
PlatformMapper platformMapper,
|
||||
ObjectMapper objectMapper) {
|
||||
this.properties = properties;
|
||||
this.popClientFactory = popClientFactory;
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.pddAuthMapper = pddAuthMapper;
|
||||
this.pddShopMapper = pddShopMapper;
|
||||
this.shopMapper = shopMapper;
|
||||
this.platformMapper = platformMapper;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为指定内部店铺生成拼多多授权跳转 URL,并将 companyId/userId/shopId 写入 Redis state。
|
||||
*/
|
||||
@Override
|
||||
public PddAuthorizeUrlVO buildAuthorizeUrl(Long shopId) {
|
||||
assertOAuthConfigured();
|
||||
if (!StringUtils.hasText(properties.getRedirectUri())) {
|
||||
throw new BusinessException("拼多多 OAuth 未配置 redirect-uri");
|
||||
}
|
||||
if (shopId == null) {
|
||||
throw new BusinessException("请指定要授权绑定的内部店铺");
|
||||
}
|
||||
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
validateInternalShopForAuth(companyId, shopId);
|
||||
|
||||
String state = UUID.randomUUID().toString().replace("-", "");
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("companyId", companyId);
|
||||
payload.put("userId", userId);
|
||||
payload.put("shopId", shopId);
|
||||
try {
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
STATE_KEY_PREFIX + state,
|
||||
objectMapper.writeValueAsString(payload),
|
||||
properties.getStateTtlSeconds(),
|
||||
TimeUnit.SECONDS);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new BusinessException("写入授权 state 失败");
|
||||
}
|
||||
|
||||
String authorizeUrl = UriComponentsBuilder
|
||||
.fromHttpUrl(properties.getAuthorizeUrl())
|
||||
.queryParam("response_type", "code")
|
||||
.queryParam("client_id", properties.getClientId())
|
||||
.queryParam("redirect_uri", properties.getRedirectUri())
|
||||
.queryParam("state", state)
|
||||
.encode()
|
||||
.build()
|
||||
.toUriString();
|
||||
|
||||
return PddAuthorizeUrlVO.builder()
|
||||
.authorizeUrl(authorizeUrl)
|
||||
.state(state)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理拼多多授权回调:校验并消费 state → code 换 token → 落库授权与外部店 → 绑定内部店 → 返回提示 HTML。
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public String handleCallback(String code, String state) {
|
||||
try {
|
||||
if (!StringUtils.hasText(code)) {
|
||||
return buildResultHtml(false, "缺少授权码 code");
|
||||
}
|
||||
if (!StringUtils.hasText(state)) {
|
||||
return buildResultHtml(false, "缺少 state");
|
||||
}
|
||||
|
||||
String stateKey = STATE_KEY_PREFIX + state;
|
||||
String stateJson = stringRedisTemplate.opsForValue().get(stateKey);
|
||||
if (!StringUtils.hasText(stateJson)) {
|
||||
return buildResultHtml(false, "授权状态无效或已过期,请重新发起授权");
|
||||
}
|
||||
stringRedisTemplate.delete(stateKey);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> statePayload = objectMapper.readValue(stateJson, Map.class);
|
||||
Long companyId = toLong(statePayload.get("companyId"));
|
||||
Long userId = toLong(statePayload.get("userId"));
|
||||
Long shopId = toLong(statePayload.get("shopId"));
|
||||
if (companyId == null || userId == null || shopId == null) {
|
||||
return buildResultHtml(false, "授权状态数据不完整,请重新发起授权");
|
||||
}
|
||||
|
||||
AccessTokenResponse tokenResponse = exchangeCode(code);
|
||||
if (tokenResponse == null || !StringUtils.hasText(tokenResponse.getAccessToken())) {
|
||||
return buildResultHtml(false, "换取 access_token 失败");
|
||||
}
|
||||
if (tokenResponse.getErrorResponse() != null) {
|
||||
String msg = tokenResponse.getErrorResponse().getErrorMsg();
|
||||
log.warn("拼多多换票失败: {}", msg);
|
||||
return buildResultHtml(false, "换取 access_token 失败" + (StringUtils.hasText(msg) ? ":" + msg : ""));
|
||||
}
|
||||
if (!StringUtils.hasText(tokenResponse.getOwnerId())) {
|
||||
return buildResultHtml(false, "授权响应缺少店铺 owner_id");
|
||||
}
|
||||
|
||||
PddAuthPO auth = upsertAuth(companyId, tokenResponse);
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo = fetchMallInfo(tokenResponse.getAccessToken());
|
||||
Long mallId = resolveMallId(tokenResponse.getOwnerId(), mallInfo);
|
||||
if (mallId == null) {
|
||||
return buildResultHtml(false, "无法解析拼多多店铺 mall_id");
|
||||
}
|
||||
|
||||
upsertPddShop(companyId, auth.getId(), mallId, mallInfo, tokenResponse.getOwnerName());
|
||||
bindInternalShop(companyId, userId, shopId, mallId, mallInfo, tokenResponse.getOwnerName());
|
||||
|
||||
String shopName = firstNonBlank(
|
||||
mallInfo != null ? mallInfo.getMallName() : null,
|
||||
tokenResponse.getOwnerName(),
|
||||
"PDD-" + mallId);
|
||||
return buildResultHtml(true, "授权成功,已绑定店铺「" + shopName + "」(mall_id=" + mallId + ")");
|
||||
} catch (BusinessException e) {
|
||||
log.warn("拼多多授权回调业务失败: {}", e.getMessage());
|
||||
return buildResultHtml(false, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("拼多多授权回调异常", e);
|
||||
return buildResultHtml(false, "授权处理异常,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验内部店铺存在、属于当前公司,且平台为拼多多。
|
||||
*/
|
||||
private void validateInternalShopForAuth(Long companyId, Long shopId) {
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
throw new BusinessException("内部店铺不存在或不属于当前公司");
|
||||
}
|
||||
PlatformPO platform = platformMapper.selectById(shop.getPlatformId());
|
||||
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
|
||||
throw new BusinessException("仅支持对拼多多平台的内部店铺发起授权");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用授权码向拼多多换取 access_token。
|
||||
*/
|
||||
private AccessTokenResponse exchangeCode(String code) throws Exception {
|
||||
PopAccessTokenClient client = popClientFactory.createAccessTokenClient();
|
||||
try {
|
||||
return client.generate(code);
|
||||
} finally {
|
||||
try {
|
||||
client.destroy();
|
||||
} catch (Exception ignored) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 company_id + owner_id 新增或覆盖写入 ec_pdd_auth(重复授权会使旧 token 失效)。
|
||||
*/
|
||||
private PddAuthPO upsertAuth(Long companyId, AccessTokenResponse token) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
LocalDateTime expiresAt = plusSeconds(now, token.getExpiresIn());
|
||||
// AccessTokenResponse 无 refresh 过期秒数时,与 access 同 TTL 兜底
|
||||
LocalDateTime refreshExpiresAt = plusSeconds(now, token.getExpiresIn());
|
||||
|
||||
LambdaQueryWrapper<PddAuthPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(PddAuthPO::getCompanyId, companyId)
|
||||
.eq(PddAuthPO::getOwnerId, token.getOwnerId());
|
||||
PddAuthPO existing = pddAuthMapper.selectOne(wrapper);
|
||||
|
||||
PddAuthPO auth = existing != null ? existing : new PddAuthPO();
|
||||
auth.setCompanyId(companyId);
|
||||
auth.setOwnerId(token.getOwnerId());
|
||||
auth.setAccessToken(token.getAccessToken());
|
||||
auth.setRefreshToken(token.getRefreshToken());
|
||||
auth.setExpiresAt(expiresAt);
|
||||
auth.setRefreshTokenExpiresAt(refreshExpiresAt);
|
||||
auth.setScope(writeJson(token.getScope()));
|
||||
auth.setRawResponse(writeJson(token));
|
||||
auth.setStatus(1);
|
||||
|
||||
if (existing == null) {
|
||||
pddAuthMapper.insert(auth);
|
||||
} else {
|
||||
pddAuthMapper.updateById(auth);
|
||||
}
|
||||
return auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用 pdd.mall.info.get 拉取拼多多店铺详情;失败时返回 null(由调用方用 owner 信息兜底)。
|
||||
*/
|
||||
private PddMallInfoGetResponse.MallInfoGetResponse fetchMallInfo(String accessToken) {
|
||||
try {
|
||||
PopClient client = popClientFactory.createHttpClient();
|
||||
PddMallInfoGetResponse response = client.syncInvoke(new PddMallInfoGetRequest(), accessToken);
|
||||
if (response == null) {
|
||||
return null;
|
||||
}
|
||||
if (response.getErrorResponse() != null) {
|
||||
log.warn("pdd.mall.info.get 失败: {}", response.getErrorResponse().getErrorMsg());
|
||||
return null;
|
||||
}
|
||||
return response.getMallInfoGetResponse();
|
||||
} catch (Exception e) {
|
||||
log.warn("调用 pdd.mall.info.get 异常: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 mall_id:优先使用 mall.info 返回值,否则将 owner_id 解析为 Long。
|
||||
*/
|
||||
private Long resolveMallId(String ownerId, PddMallInfoGetResponse.MallInfoGetResponse mallInfo) {
|
||||
if (mallInfo != null && mallInfo.getMallId() != null) {
|
||||
return mallInfo.getMallId();
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(ownerId.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 company_id + mall_id 新增或更新 ec_pdd_shop,并绑定 pdd_auth_id。
|
||||
*/
|
||||
private void upsertPddShop(Long companyId,
|
||||
Long authId,
|
||||
Long mallId,
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
|
||||
String ownerName) {
|
||||
LambdaQueryWrapper<PddShopPO> byMall = new LambdaQueryWrapper<>();
|
||||
byMall.eq(PddShopPO::getCompanyId, companyId).eq(PddShopPO::getMallId, mallId);
|
||||
PddShopPO shop = pddShopMapper.selectOne(byMall);
|
||||
|
||||
// 若该授权已绑其他店铺,先解绑(uk_ec_pdd_shop_auth)
|
||||
LambdaQueryWrapper<PddShopPO> byAuth = new LambdaQueryWrapper<>();
|
||||
byAuth.eq(PddShopPO::getPddAuthId, authId);
|
||||
PddShopPO authBound = pddShopMapper.selectOne(byAuth);
|
||||
if (authBound != null && (shop == null || !authBound.getId().equals(shop.getId()))) {
|
||||
authBound.setPddAuthId(null);
|
||||
pddShopMapper.updateById(authBound);
|
||||
}
|
||||
|
||||
if (shop == null) {
|
||||
shop = new PddShopPO();
|
||||
shop.setCompanyId(companyId);
|
||||
shop.setMallId(mallId);
|
||||
}
|
||||
shop.setPddAuthId(authId);
|
||||
shop.setMallName(firstNonBlank(
|
||||
mallInfo != null ? mallInfo.getMallName() : null,
|
||||
ownerName,
|
||||
"PDD-" + mallId));
|
||||
if (mallInfo != null) {
|
||||
shop.setLogo(mallInfo.getLogo());
|
||||
shop.setMallDesc(mallInfo.getMallDesc());
|
||||
if (mallInfo.getMerchantType() != null) {
|
||||
shop.setMerchantType(mallInfo.getMerchantType());
|
||||
}
|
||||
if (mallInfo.getMallCharacter() != null) {
|
||||
shop.setMallCharacter(mallInfo.getMallCharacter());
|
||||
}
|
||||
}
|
||||
if (shop.getMerchantType() == null) {
|
||||
shop.setMerchantType(6);
|
||||
}
|
||||
if (shop.getMallCharacter() == null) {
|
||||
shop.setMallCharacter(2);
|
||||
}
|
||||
shop.setLastSyncTime(LocalDateTime.now());
|
||||
|
||||
if (shop.getId() == null) {
|
||||
pddShopMapper.insert(shop);
|
||||
} else {
|
||||
pddShopMapper.updateById(shop);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将拼多多 mall_id 写入指定内部店铺的 external_shop_id;若已被其他内部店占用则先解绑再改绑。
|
||||
*/
|
||||
private void bindInternalShop(Long companyId,
|
||||
Long userId,
|
||||
Long shopId,
|
||||
Long mallId,
|
||||
PddMallInfoGetResponse.MallInfoGetResponse mallInfo,
|
||||
String ownerName) {
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
throw new BusinessException("授权关联的内部店铺不存在或不属于当前公司");
|
||||
}
|
||||
|
||||
PlatformPO platform = platformMapper.selectById(shop.getPlatformId());
|
||||
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
|
||||
throw new BusinessException("内部店铺不是拼多多平台,无法绑定");
|
||||
}
|
||||
|
||||
String externalShopId = String.valueOf(mallId);
|
||||
|
||||
// 同一公司+平台下外部店 ID 唯一:若已被其他内部店占用则解绑
|
||||
ShopPO occupied = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.eq(ShopPO::getPlatformId, shop.getPlatformId())
|
||||
.eq(ShopPO::getExternalShopId, externalShopId)
|
||||
.ne(ShopPO::getId, shopId)
|
||||
.last("LIMIT 1"));
|
||||
if (occupied != null) {
|
||||
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
|
||||
.eq(ShopPO::getId, occupied.getId())
|
||||
.set(ShopPO::getExternalShopId, null)
|
||||
.set(ShopPO::getUpdateBy, userId));
|
||||
log.info("拼多多外部店 {} 从内部店 {} 解绑,改绑至 {}", externalShopId, occupied.getId(), shopId);
|
||||
}
|
||||
|
||||
shop.setExternalShopId(externalShopId);
|
||||
String mallName = firstNonBlank(
|
||||
mallInfo != null ? mallInfo.getMallName() : null,
|
||||
ownerName);
|
||||
if (StringUtils.hasText(mallName)) {
|
||||
shop.setName(mallName);
|
||||
}
|
||||
shop.setUpdateBy(userId);
|
||||
shopMapper.updateById(shop);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 OAuth client-id / client-secret 已配置。
|
||||
*/
|
||||
private void assertOAuthConfigured() {
|
||||
if (!StringUtils.hasText(properties.getClientId())
|
||||
|| !StringUtils.hasText(properties.getClientSecret())) {
|
||||
throw new BusinessException("拼多多 OAuth 未配置 client-id / client-secret");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造授权结果提示页 HTML(成功/失败),3 秒后尝试关闭窗口。
|
||||
*/
|
||||
private static String buildResultHtml(boolean success, String message) {
|
||||
String title = success ? "授权成功" : "授权失败";
|
||||
String color = success ? "#067d3f" : "#b42318";
|
||||
String safeMessage = HtmlUtils.htmlEscape(message == null ? "" : message);
|
||||
return """
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>%s</title>
|
||||
<style>
|
||||
body{font-family:system-ui,-apple-system,sans-serif;display:flex;align-items:center;justify-content:center;
|
||||
min-height:100vh;margin:0;background:#f6f7f9;color:#1f2937}
|
||||
.box{text-align:center;padding:28px 32px;background:#fff;border-radius:12px;
|
||||
box-shadow:0 8px 24px rgba(15,23,42,.08);max-width:420px}
|
||||
h1{margin:0 0 12px;font-size:22px;color:%s}
|
||||
p{margin:0;line-height:1.6;color:#4b5563}
|
||||
.hint{margin-top:16px;font-size:13px;color:#9ca3af}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="box">
|
||||
<h1>%s</h1>
|
||||
<p>%s</p>
|
||||
<p class="hint">本页将在 3 秒后自动关闭,若未关闭请手动关闭</p>
|
||||
</div>
|
||||
<script>setTimeout(function(){window.close();},3000);</script>
|
||||
</body>
|
||||
</html>
|
||||
""".formatted(title, color, title, safeMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以当前时刻为基准加上 expires_in 秒,得到过期时间;非法值时默认 24 小时。
|
||||
*/
|
||||
private static LocalDateTime plusSeconds(LocalDateTime base, Integer seconds) {
|
||||
if (seconds == null || seconds <= 0) {
|
||||
return base.plusHours(24);
|
||||
}
|
||||
return LocalDateTime.ofInstant(
|
||||
Instant.now().plusSeconds(seconds),
|
||||
ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象序列化为 JSON 字符串;失败时返回 null。
|
||||
*/
|
||||
private String writeJson(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.warn("序列化 JSON 失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Redis/JSON 中的数值或字符串安全转为 Long。
|
||||
*/
|
||||
private static Long toLong(Object value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(String.valueOf(value));
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回参数中第一个非空白字符串。
|
||||
*/
|
||||
private static String firstNonBlank(String... values) {
|
||||
if (values == null) {
|
||||
return null;
|
||||
}
|
||||
for (String v : values) {
|
||||
if (StringUtils.hasText(v)) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+1
-4
@@ -11,10 +11,7 @@ import java.time.LocalDateTime;
|
||||
@Schema(description = "创建拼多多店铺DTO")
|
||||
public class CreatePddShopDTO {
|
||||
|
||||
@Schema(description = "内部店铺ID(ec_shop.id)")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
|
||||
@Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
|
||||
private Long pddAuthId;
|
||||
|
||||
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
|
||||
-3
@@ -16,9 +16,6 @@ public class PddShopFilterDTO {
|
||||
@Schema(description = "店铺身份")
|
||||
private Integer mallCharacter;
|
||||
|
||||
@Schema(description = "内部店铺ID")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "拼多多授权ID")
|
||||
private Long pddAuthId;
|
||||
}
|
||||
|
||||
+1
-4
@@ -11,10 +11,7 @@ import java.time.LocalDateTime;
|
||||
@Schema(description = "更新拼多多店铺DTO")
|
||||
public class UpdatePddShopDTO {
|
||||
|
||||
@Schema(description = "内部店铺ID(ec_shop.id)")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
|
||||
@Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
|
||||
private Long pddAuthId;
|
||||
|
||||
@Schema(description = "拼多多店铺ID(mall_id)", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
|
||||
+5
-4
@@ -1,6 +1,10 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
@@ -15,9 +19,6 @@ public class PddShopPO {
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("pdd_auth_id")
|
||||
private Long pddAuthId;
|
||||
|
||||
|
||||
+1
-4
@@ -15,10 +15,7 @@ public class PddShopVO {
|
||||
@Schema(description = "公司ID")
|
||||
private Long companyId;
|
||||
|
||||
@Schema(description = "内部店铺ID(ec_shop.id)")
|
||||
private Long shopId;
|
||||
|
||||
@Schema(description = "拼多多授权ID(open_pdd_auth.id)")
|
||||
@Schema(description = "拼多多授权ID(ec_pdd_auth.id)")
|
||||
private Long pddAuthId;
|
||||
|
||||
@Schema(description = "拼多多店铺ID(mall_id)")
|
||||
|
||||
-3
@@ -126,9 +126,6 @@ public class PddShopServiceImpl extends ServiceImpl<PddShopMapper, PddShopPO> im
|
||||
if (filter.getMallCharacter() != null) {
|
||||
wrapper.eq(PddShopPO::getMallCharacter, filter.getMallCharacter());
|
||||
}
|
||||
if (filter.getShopId() != null) {
|
||||
wrapper.eq(PddShopPO::getShopId, filter.getShopId());
|
||||
}
|
||||
if (filter.getPddAuthId() != null) {
|
||||
wrapper.eq(PddShopPO::getPddAuthId, filter.getPddAuthId());
|
||||
}
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ public class ShopController {
|
||||
return ApiResponse.success("店铺删除成功");
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取店铺列表", description = "分页获取店铺列表,支持条件过滤")
|
||||
@Operation(summary = "分页获取店铺列表", description = "分页获取店铺列表,支持条件过滤;已绑定外部店时附带对应外部店铺 VO(如 pddShop)")
|
||||
@PostMapping("/list")
|
||||
@RequirePermission(value = "ecom:shop:read", description = "查询店铺列表", allowSuper = true)
|
||||
public ApiResponse<PageResultVO<ShopVO>> getShopPage(
|
||||
|
||||
+6
@@ -29,4 +29,10 @@ public class CreateShopDTO {
|
||||
*/
|
||||
@Schema(description = "平台ID", example = "1")
|
||||
private Long platformId;
|
||||
|
||||
/**
|
||||
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
|
||||
*/
|
||||
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
|
||||
private String externalShopId;
|
||||
}
|
||||
|
||||
+6
@@ -29,4 +29,10 @@ public class UpdateShopDTO {
|
||||
*/
|
||||
@Schema(description = "平台ID", example = "1")
|
||||
private Long platformId;
|
||||
|
||||
/**
|
||||
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
|
||||
*/
|
||||
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
|
||||
private String externalShopId;
|
||||
}
|
||||
|
||||
+6
@@ -44,6 +44,12 @@ public class ShopPO {
|
||||
@TableField("platform_id")
|
||||
private Long platformId;
|
||||
|
||||
/**
|
||||
* 外部店铺ID(如拼多多 mall_id;与 platform_id 组合关联平台店铺)
|
||||
*/
|
||||
@TableField("external_shop_id")
|
||||
private String externalShopId;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
|
||||
+13
@@ -2,6 +2,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.vo.PddShopVO;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@@ -42,6 +43,18 @@ public class ShopVO {
|
||||
@Schema(description = "平台ID", example = "1")
|
||||
private Long platformId;
|
||||
|
||||
/**
|
||||
* 外部店铺ID(平台侧店铺标识,如拼多多 mall_id)
|
||||
*/
|
||||
@Schema(description = "外部店铺ID(平台侧店铺标识,如拼多多 mall_id)", example = "123456789")
|
||||
private String externalShopId;
|
||||
|
||||
/**
|
||||
* 关联的拼多多外部店铺(仅 platform=pdd 且已绑定 externalShopId 时有值)
|
||||
*/
|
||||
@Schema(description = "关联的拼多多外部店铺(已授权绑定时返回)")
|
||||
private PddShopVO pddShop;
|
||||
|
||||
/**
|
||||
* 平台名称
|
||||
*/
|
||||
|
||||
+125
-18
@@ -15,6 +15,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.mapper.PddShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.po.PddShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.pdd.shop.model.vo.PddShopVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.mapper.PlatformMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
@@ -48,7 +51,12 @@ import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -57,6 +65,8 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements ShopService {
|
||||
|
||||
private static final String PLATFORM_CODE_PDD = "pdd";
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final SysFileService sysFileService;
|
||||
private final OrderMapper orderMapper;
|
||||
@@ -65,6 +75,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
private final ShopProductRelationMapper shopProductRelationMapper;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final PlatformMapper platformMapper;
|
||||
private final PddShopMapper pddShopMapper;
|
||||
private final BrushOrderMapper brushOrderMapper;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
|
||||
@@ -72,7 +83,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
OrderMapper orderMapper, PromotionFeeMapper promotionFeeMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopProductRelationMapper shopProductRelationMapper, ProductSpecService productSpecService,
|
||||
PlatformMapper platformMapper,
|
||||
PlatformMapper platformMapper, PddShopMapper pddShopMapper,
|
||||
BrushOrderMapper brushOrderMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileService = sysFileService;
|
||||
@@ -82,6 +93,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
this.shopProductRelationMapper = shopProductRelationMapper;
|
||||
this.productSpecService = productSpecService;
|
||||
this.platformMapper = platformMapper;
|
||||
this.pddShopMapper = pddShopMapper;
|
||||
this.brushOrderMapper = brushOrderMapper;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
}
|
||||
@@ -218,11 +230,15 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
|
||||
// 执行分页查询
|
||||
IPage<ShopPO> pageResult = this.page(page, wrapper);
|
||||
List<ShopPO> records = pageResult.getRecords();
|
||||
|
||||
// 转换为VO
|
||||
List<ShopVO> voList = pageResult.getRecords().stream()
|
||||
.map(this::convertToVO)
|
||||
// 批量加载平台,避免 N+1
|
||||
Map<Long, PlatformPO> platformMap = loadPlatformMap(companyId, records);
|
||||
|
||||
List<ShopVO> voList = records.stream()
|
||||
.map(shop -> convertToVO(shop, platformMap.get(shop.getPlatformId())))
|
||||
.collect(Collectors.toList());
|
||||
fillExternalShops(voList, records, companyId, platformMap);
|
||||
|
||||
// 构建分页结果
|
||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
||||
@@ -244,29 +260,120 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopPO> implements
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为VO
|
||||
* 转换为VO(单条;创建/更新等场景)
|
||||
*/
|
||||
private ShopVO convertToVO(ShopPO shop) {
|
||||
PlatformPO platform = null;
|
||||
if (shop.getPlatformId() != null) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
platform = platformMapper.selectOne(new LambdaQueryWrapper<PlatformPO>()
|
||||
.eq(PlatformPO::getId, shop.getPlatformId())
|
||||
.eq(PlatformPO::getCompanyId, companyId));
|
||||
}
|
||||
ShopVO shopVO = convertToVO(shop, platform);
|
||||
if (platform != null && PLATFORM_CODE_PDD.equals(platform.getPlatformCode())
|
||||
&& shop.getExternalShopId() != null && !shop.getExternalShopId().isBlank()) {
|
||||
Long mallId = parseMallId(shop.getExternalShopId());
|
||||
if (mallId != null) {
|
||||
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
|
||||
.eq(PddShopPO::getCompanyId, shop.getCompanyId())
|
||||
.eq(PddShopPO::getMallId, mallId)
|
||||
.last("LIMIT 1"));
|
||||
if (pddShop != null) {
|
||||
shopVO.setPddShop(convertPddShopToVO(pddShop));
|
||||
}
|
||||
}
|
||||
}
|
||||
return shopVO;
|
||||
}
|
||||
|
||||
private ShopVO convertToVO(ShopPO shop, PlatformPO platform) {
|
||||
ShopVO shopVO = new ShopVO();
|
||||
BeanCopyUtils.copyProperties(shop, shopVO);
|
||||
|
||||
|
||||
if (shop.getLogoImageId() != null) {
|
||||
shopVO.setLogo(sysFileService.getFileAccessUrl(shop.getLogoImageId()));
|
||||
}
|
||||
|
||||
// 获取平台名称
|
||||
if (shop.getPlatformId() != null) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
LambdaQueryWrapper<PlatformPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(PlatformPO::getId, shop.getPlatformId())
|
||||
.eq(PlatformPO::getCompanyId, companyId);
|
||||
PlatformPO platform = platformMapper.selectOne(wrapper);
|
||||
if (platform != null) {
|
||||
shopVO.setPlatformName(platform.getPlatformName());
|
||||
if (platform != null) {
|
||||
shopVO.setPlatformName(platform.getPlatformName());
|
||||
}
|
||||
return shopVO;
|
||||
}
|
||||
|
||||
private Map<Long, PlatformPO> loadPlatformMap(Long companyId, List<ShopPO> shops) {
|
||||
Set<Long> platformIds = shops.stream()
|
||||
.map(ShopPO::getPlatformId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
if (platformIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
List<PlatformPO> platforms = platformMapper.selectList(new LambdaQueryWrapper<PlatformPO>()
|
||||
.eq(PlatformPO::getCompanyId, companyId)
|
||||
.in(PlatformPO::getId, platformIds));
|
||||
return platforms.stream().collect(Collectors.toMap(PlatformPO::getId, Function.identity(), (a, b) -> a));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量填充已绑定的外部店铺 VO(当前支持拼多多)
|
||||
*/
|
||||
private void fillExternalShops(List<ShopVO> voList,
|
||||
List<ShopPO> shops,
|
||||
Long companyId,
|
||||
Map<Long, PlatformPO> platformMap) {
|
||||
if (voList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<Long, ShopVO> voById = voList.stream()
|
||||
.filter(v -> v.getId() != null)
|
||||
.collect(Collectors.toMap(ShopVO::getId, Function.identity(), (a, b) -> a));
|
||||
|
||||
Map<Long, Long> shopIdToMallId = new HashMap<>();
|
||||
for (ShopPO shop : shops) {
|
||||
if (shop.getExternalShopId() == null || shop.getExternalShopId().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
PlatformPO platform = platformMap.get(shop.getPlatformId());
|
||||
if (platform == null || !PLATFORM_CODE_PDD.equals(platform.getPlatformCode())) {
|
||||
continue;
|
||||
}
|
||||
Long mallId = parseMallId(shop.getExternalShopId());
|
||||
if (mallId != null) {
|
||||
shopIdToMallId.put(shop.getId(), mallId);
|
||||
}
|
||||
}
|
||||
|
||||
return shopVO;
|
||||
if (shopIdToMallId.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<PddShopPO> pddShops = pddShopMapper.selectList(new LambdaQueryWrapper<PddShopPO>()
|
||||
.eq(PddShopPO::getCompanyId, companyId)
|
||||
.in(PddShopPO::getMallId, shopIdToMallId.values()));
|
||||
Map<Long, PddShopVO> pddByMallId = pddShops.stream()
|
||||
.collect(Collectors.toMap(PddShopPO::getMallId, this::convertPddShopToVO, (a, b) -> a));
|
||||
|
||||
shopIdToMallId.forEach((shopId, mallId) -> {
|
||||
ShopVO vo = voById.get(shopId);
|
||||
PddShopVO pddShop = pddByMallId.get(mallId);
|
||||
if (vo != null && pddShop != null) {
|
||||
vo.setPddShop(pddShop);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static Long parseMallId(String externalShopId) {
|
||||
try {
|
||||
return Long.parseLong(externalShopId.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private PddShopVO convertPddShopToVO(PddShopPO pddShop) {
|
||||
PddShopVO vo = new PddShopVO();
|
||||
BeanCopyUtils.copyProperties(pddShop, vo);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,9 +5,9 @@ server:
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://192.168.3.100:3306/ecom_dmb_test?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: ecom_dmb_test
|
||||
password: ecom_dmb_test
|
||||
url: jdbc:mysql://192.168.3.100:3306/ecom_dmb_dev?characterEncoding=utf-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
|
||||
username: ecom_dmb_dev
|
||||
password: ecom_dmb_dev
|
||||
data:
|
||||
redis:
|
||||
host: 192.168.3.100
|
||||
|
||||
@@ -125,6 +125,15 @@ oss:
|
||||
endpoint: https://oss-cn-guangzhou.aliyuncs.com
|
||||
bucket-name: xyquan
|
||||
|
||||
# 拼多多开放平台 OAuth
|
||||
pdd:
|
||||
oauth:
|
||||
client-id: 9b71d887c8dc4b46998dedfdeca9b866
|
||||
client-secret: c626f640a6fd5f56b2c8c009a5eb2d5683e6b955
|
||||
redirect-uri: https://ecbi.newloop.top/api-dev/ec/pdd/auth/callback
|
||||
authorize-url: https://fuwu.pinduoduo.com/service-market/auth
|
||||
state-ttl-seconds: 600
|
||||
|
||||
# License 授权(开关与公钥见 LicenseEnforcement 源码硬编码)
|
||||
ecom:
|
||||
license:
|
||||
|
||||
@@ -109,6 +109,22 @@ INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status
|
||||
SELECT 3400, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1), 'ecom:platform', '平台管理', 'module', 1, '', 330
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'ecom:platform');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3600, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:ecom' LIMIT 1), 'biz:pdd', '拼多多', 'module', 1, '拼多多对接', 360
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3601, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:auth:manage', '拼多多授权管理', 'api', 1, '生成授权链接/管理授权', 361
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:auth:manage');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3602, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:shop:read', '拼多多店铺查看', 'api', 1, '', 362
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:read');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 3603, (SELECT id FROM `sys_permission` WHERE `code` = 'biz:pdd' LIMIT 1), 'biz:pdd:shop:manage', '拼多多店铺管理', 'api', 1, '', 363
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'biz:pdd:shop:manage');
|
||||
|
||||
INSERT INTO `sys_permission` (`id`, `parent_id`, `code`, `name`, `type`, `status`, `remark`, `sort_order`)
|
||||
SELECT 4100, (SELECT id FROM `sys_permission` WHERE `code` = 'MODULE:data' LIMIT 1), 'data:import-group', '数据导入', 'module', 1, '', 400
|
||||
FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM `sys_permission` WHERE `code` = 'data:import-group');
|
||||
|
||||
Reference in New Issue
Block a user