Commit 3471d76d authored by xiaosl's avatar xiaosl
parents 0743b1ed 80223556
......@@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
......@@ -21,6 +22,10 @@ import java.util.Map;
*/
@Slf4j
public class CommonBaseController {
@Autowired
HttpServletResponse response;
@Autowired
public HttpServletRequest request;
......@@ -28,6 +33,10 @@ public class CommonBaseController {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public String getCurrentUserName(){
return BaseContextHandler.getUsername();
}
......
package com.github.wxiaoqi.security.common.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.mockito.internal.util.collections.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_JSON_TRUE;
@Slf4j
public class AssertUtils {
public static<T> T isBlank(T object, BaseException baseException, String name) throws BaseException {
log.info(" AssertUtils.isBlank : {}", object);
if(object instanceof Collection) {
if (CollUtil.isEmpty((List)object)) {
throwException(baseException, name);
}
}else if (object == null) {
throwException(baseException, name);
}
return object;
}
public static<T> T isNotBlank(T object, BaseException baseException, String name) throws BaseException {
log.info(" AssertUtils.isNotBlank : {}", object);
if (object != null ) {
//如果是集合 并且 为空 着不抛异常
if (object instanceof Collection && CollUtil.isEmpty((List)object)) {
return object;
}else {
throwException(baseException, name);
}
}
return object;
}
public static<T> T isBlank(T object, BaseException baseException) throws BaseException {
return isBlank(object, baseException, null);
}
public static<T> T isNotBlank(T object, BaseException baseException) throws BaseException {
return isNotBlank(object, baseException, null);
}
public static void isBlankMulti(Object... objects) throws BaseException {
log.info(" AssertUtils.isBlank : {}", objects);
isBlank(objects);
for (Object object : objects) {
isBlank(object);
}
}
// public static void isEqual(Object a, Object b, BaseException bex) throws BaseException {
// log.info(" AssertUtils.isEqual : {} {}", a, b);
// if(a.equals(b)) {
// if(null != bex) {
// throw new BaseException(ResultCode.DB_OPERATION_FAIL_CODE);
// }else {
// throw bex;
// }
// }
// }
public static<T> T isBlank(T object) throws BaseException {
return isBlank(object, null, null);
}
public static<T> T isBlankBean(T object) throws BaseException {
Map<String, Object> beanMap = BeanUtil.beanToMap(object);
isBlank(object);
for(String key : beanMap.keySet()) {
isBlank(beanMap.get(key), null, null);
}
return object;
}
public static<T> T isBlank(T object, String attrName) throws BaseException {
return isBlank(object, null, attrName);
}
public static Integer isDBSucc(Integer flag, BaseException baseException) throws BaseException {
log.info(" AssertUtils.isDBSucc : {}", flag);
if(SYS_FALSE.equals(flag)) {
throwDBException(baseException);
}
return flag;
}
public static Integer isDBSucc(Integer flag) throws BaseException {
return isDBSucc(flag, null);
}
public static<T> ObjectRestResponse<T> isFeignSucc(ObjectRestResponse<T> orr) throws BaseException {
log.info(" AssertUtils.isFeignSucc : {}", orr);
if(!SYS_JSON_TRUE.equals(orr.getStatus())) {
throw new BaseException(orr.getMessage(), orr.getStatus());
}
return orr;
}
public static<T,E> ObjectRestResponse<T> isFeignSuccGetObj(E dto, Function<Map, ObjectRestResponse<T>> function) throws BaseException {
log.info(" AssertUtils.isFeignSucc : {}", dto);
ObjectRestResponse<T> orr = function.apply(DepthBeanToMap.objectToMap(dto));
//ObjectRestResponse<T> orr = function.apply( BeanUtil.beanToMap(dto, false, false));
if(!SYS_JSON_TRUE.equals(orr.getStatus())) {
throw new BaseException(orr.getMessage(), orr.getStatus());
}
return orr;
}
public static<T,E> List<T> isFeignSuccGetDataList(E dto, Function<Map, ObjectRestResponse<List<T>>> function, Class<T> tClass) throws BaseException {
log.info(" AssertUtils.isFeignSucc : {}", dto);
ObjectRestResponse<List<T>> orr = function.apply(DepthBeanToMap.objectToMap(dto));
//ObjectRestResponse<List<T>> orr = function.apply(BeanUtil.beanToMap(dto, false, false));
if(!SYS_JSON_TRUE.equals(orr.getStatus())) {
throw new BaseException(orr.getMessage(), orr.getStatus());
}
orr.setData(orr.getData().parallelStream().map(t -> BeanUtil.toBean(t, tClass)).collect(Collectors.toList()));
return orr.getData();
}
public static<T,E> T isFeignSuccGetData(E dto, Function<Map, ObjectRestResponse<T>> function) throws BaseException {
return isFeignSuccGetObj(dto, function).getData();
}
private static void throwException(BaseException baseException, String name) {
if(null != baseException) {
throw baseException;
}else {
throw new BaseException(ResultCode.NOTEXIST_CODE, Sets.newSet(name));
}
}
private static void throwDBException(BaseException baseException) {
if(null != baseException) {
throw baseException;
}else {
throw new BaseException(ResultCode.DB_OPERATION_FAIL_CODE);
}
}
}
\ No newline at end of file
package com.github.wxiaoqi.security.common.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class DepthBeanToMap {
public static Map objectToMap(Object obj){
try{
Class type = obj.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i< propertyDescriptors.length; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!propertyName.equals("class")) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(obj, new Object[0]);
if(result == null){
continue;
}
//判断是否为 基础类型 String,Boolean,Byte,Short,Integer,Long,Float,Double
//判断是否集合类,COLLECTION,MAP
if(result instanceof String
|| result instanceof Boolean
|| result instanceof Byte
|| result instanceof Short
|| result instanceof Integer
|| result instanceof Long
|| result instanceof Float
|| result instanceof Double
|| result instanceof Enum
){
if (result != null) {
returnMap.put(propertyName, result);
}
}else if(result instanceof Collection){
Collection<?> lstObj = arrayToMap((Collection<?>)result);
returnMap.put(propertyName, lstObj);
}else if(result instanceof Map){
Map<Object,Object> lstObj = mapToMap((Map<Object,Object>)result);
returnMap.put(propertyName, lstObj);
} else {
Map mapResult = objectToMap(result);
returnMap.put(propertyName, mapResult);
}
}
}
return returnMap;
}catch(Exception e){
throw new RuntimeException(e);
}
}
private static Map<Object, Object> mapToMap(Map<Object, Object> orignMap) {
Map<Object,Object> resultMap = new HashMap<Object,Object>();
for(Map.Entry<Object, Object> entry:orignMap.entrySet()){
Object key = entry.getKey();
Object resultKey = null;
if(key instanceof Collection){
resultKey = arrayToMap((Collection)key);
}else if(key instanceof Map){
resultKey = mapToMap((Map)key);
}
else{
if(key instanceof String
|| key instanceof Boolean
|| key instanceof Byte
|| key instanceof Short
|| key instanceof Integer
|| key instanceof Long
|| key instanceof Float
|| key instanceof Double
|| key instanceof Enum
){
if (key != null) {
resultKey = key;
}
}else{
resultKey = objectToMap(key);
}
}
Object value = entry.getValue();
Object resultValue = null;
if(value instanceof Collection){
resultValue = arrayToMap((Collection)value);
}else if(value instanceof Map){
resultValue = mapToMap((Map)value);
}
else{
if(value instanceof String
|| value instanceof Boolean
|| value instanceof Byte
|| value instanceof Short
|| value instanceof Integer
|| value instanceof Long
|| value instanceof Float
|| value instanceof Double
|| value instanceof Enum
){
if (value != null) {
resultValue = value;
}
}else{
resultValue = objectToMap(value);
}
}
resultMap.put(resultKey, resultValue);
}
return resultMap;
}
private static Collection arrayToMap(Collection lstObj){
ArrayList arrayList = new ArrayList();
for (Object t : lstObj) {
if(t instanceof Collection){
Collection result = arrayToMap((Collection)t);
arrayList.add(result);
}else if(t instanceof Map){
Map result = mapToMap((Map)t);
arrayList.add(result);
} else {
if(t instanceof String
|| t instanceof Boolean
|| t instanceof Byte
|| t instanceof Short
|| t instanceof Integer
|| t instanceof Long
|| t instanceof Float
|| t instanceof Double
|| t instanceof Enum
){
if (t != null) {
arrayList.add(t);
}
}else{
Object result = objectToMap(t);
arrayList.add(result);
}
}
}
return arrayList;
}
}
\ No newline at end of file
......@@ -749,6 +749,23 @@ public class GtDataRestClient {
return open(path, defaultSign, defaultTime);
}
/**
*
* Description:根据路径读取文件内容的请求地址 如果出现内存溢出,请使用openLarge(只能在Linux环境使用)
*
* @see #openLarge(String, String)
*
* @param path
* @return url
*
*/
public String openUrl(String path) {
String resourceUrl = MessageFormat
.format("{0}{1}?op=OPEN&sign={2}&time={3}", gtDataUrl, path,
defaultSign, defaultTime);
return resourceUrl;
}
/**
*
* Description:根据路径读取文件内容(小文件,1G以内的) 如果出现内存溢出,请使用openLarge(只能在Linux环境使用)
......
......@@ -166,10 +166,10 @@ public class AppPermissionService {
if (rsUserLogin != null) {
return JsonResultUtil.createFailedResult(ResultCode.EXIST_CODE, "用户已存在");
}
ObjectRestResponse<Boolean> objectRestResponse = thirdFeign.verify(phone, pointList);
if (objectRestResponse.getData() == null || objectRestResponse.getData() == false) {
return JsonResultUtil.createFailedResult(ResultCode.FAILED_CODE, "图片验证码验证失败");
}
// ObjectRestResponse<Boolean> objectRestResponse = thirdFeign.verify(phone, pointList);
// if (objectRestResponse.getData() == null || objectRestResponse.getData() == false) {
// return JsonResultUtil.createFailedResult(ResultCode.FAILED_CODE, "图片验证码验证失败");
// }
} else if (type == 1) {
AppUserLogin rsUserLogin = appUserLoginBiz.checkeUserLogin(phone);
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ace-sidecar</artifactId>
<groupId>com.github.wxiaoqi</groupId>
<version>2.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ace-sidecar-client-demo</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>
<!--暴露各种指标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-consul-all</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
Python服务端示例:
https://gitee.com/superjery/tornado_boilerplate
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
需以下根文件:
__init__.py
application.py
server.py
urls.py
需以下根文件夹:
handlers
model
static
templates
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python 安装 3.5
tornado 安装 4.5
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
运行python server.py即可启动Web
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
两种访问接口方式:
http://localhost:5689/ace-sidecar-client-demo/test/test
http://localhost:5689/ace-sidecar-client-demo/message/123
package com.github.wxiaoqi.security.sidecarclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* ${DESCRIPTION}
*
* @author yangyongjie
* @create 2017-10-22 20:30
*/
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class PythonServerBootstrap {
public static void main(String[] args) {
SpringApplication.run(PythonServerBootstrap.class, args);
}
}
package com.github.wxiaoqi.security.sidecarclient.client;
import com.github.wxiaoqi.security.sidecarclient.entity.Message;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author yangyongjie
* @create 2017-10-22 20:30
*/
@FeignClient(name = "ace-sidecar-server")
public interface PythonFeignClient {
//parse param like /message?id=12
@RequestMapping("/message/{id}")
List<Message> getMsg(@RequestParam("id") Long id);
//parse url like /test
@RequestMapping("/test")
String getTest();
}
\ No newline at end of file
package com.github.wxiaoqi.security.sidecarclient.entity;
/**
* ${DESCRIPTION}
*
* @author yangyongjie
* @create 2017-10-22 20:30
*/
public class Message {
private Long id;
private String msg;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
\ No newline at end of file
package com.github.wxiaoqi.security.sidecarclient.rest;
import com.github.wxiaoqi.security.sidecarclient.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import com.github.wxiaoqi.security.sidecarclient.client.PythonFeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* ${DESCRIPTION}
*
* @author yangyongjie
* @create 2017-10-22 20:30
*/
@RestController
@RequestMapping("test")
public class PythonController {
@Autowired
private PythonFeignClient pythonFeignClient;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String getTest() {
return pythonFeignClient.getTest();
}
@RequestMapping(value = "/message/{id}", method = RequestMethod.GET)
public List<Message> getMsg(@PathVariable Long id) {
return pythonFeignClient.getMsg(id);
}
}
\ No newline at end of file
server:
port: 5689 #启动端口
spring:
application:
name: ace-sidecar-client-demo
eureka:
instance:
statusPageUrlPath: /info
healthCheckUrlPath: /health
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
\ No newline at end of file
server:
port: 5689 #启动端口
spring:
application:
name: ace-sidecar-client-demo
eureka:
instance:
statusPageUrlPath: /info
healthCheckUrlPath: /health
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ace-sidecar</artifactId>
<groupId>com.github.wxiaoqi</groupId>
<version>2.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ace-sidecar-server</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--表示为web工程-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-sidecar</artifactId>
</dependency>
<!--暴露各种指标-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
使用Sidecar代理远程Python服务,端口为Python的Web端口
当然,换成Node的Web端口,即可代理Node的远程服务
远程服务需要实现一个接口,返回
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Node:
app.get('/health', (req, res) => {
res.json({
status: 'UP'
})
})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python:
class HealthHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("content-type", "application/json")
self.render('health')
health:
{"status":"UP"}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
切记,通过此代理访问不到远程Python提供的服务,
需通过ace-sidecar-client-demo封装后才可访问到。
\ No newline at end of file
package com.github.wxiaoqi.security.sidecar;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.sidecar.EnableSidecar;
/**
* Created by ace on 2017/7/29.
*/
@EnableSidecar
@SpringBootApplication
public class SidercarBootstrap {
public static void main(String[] args) {
SpringApplication.run(SidercarBootstrap.class, args);
}
}
server:
port: 5688 #启动端口
spring:
application:
name: ace-sidecar-server
cloud:
consul:
enabled: true
host: 127.0.0.1
port: 8500
discovery:
healthCheckPath: /actuator/health
healthCheckInterval: 5s
instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
register: true
enabled: true
sidecar:
port: 5680 #python接口
health:
uri: http://localhost:${sidecar.port}/health
eureka:
instance:
statusPageUrlPath: /info
healthCheckUrlPath: /health
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
\ No newline at end of file
server:
port: 5688 #启动端口
spring:
application:
name: ace-sidecar-server
cloud:
consul:
enabled: true
host: 127.0.0.1
port: 8500
discovery:
healthCheckPath: /actuator/health
healthCheckInterval: 5s
instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
register: true
enabled: true
sidecar:
port: 5680 #python接口
health:
uri: http://localhost:${sidecar.port}/health
eureka:
instance:
statusPageUrlPath: /info
healthCheckUrlPath: /health
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ace-security</artifactId>
<groupId>com.github.wxiaoqi</groupId>
<version>2.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ace-sidecar</artifactId>
<packaging>pom</packaging>
<modules>
<module>ace-sidecar-server</module>
<module>ace-sidecar-client-demo</module>
</modules>
</project>
\ No newline at end of file
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = config_info */
/******************************************/
CREATE TABLE `config_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`data_id` varchar(255) NOT NULL COMMENT 'data_id',
`group_id` varchar(255) DEFAULT NULL,
`content` longtext NOT NULL COMMENT 'content',
`md5` varchar(32) DEFAULT NULL COMMENT 'md5',
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '修改时间',
`src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip',
`app_name` varchar(128) DEFAULT NULL,
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
`c_desc` varchar(256) DEFAULT NULL,
`c_use` varchar(64) DEFAULT NULL,
`effect` varchar(64) DEFAULT NULL,
`type` varchar(64) DEFAULT NULL,
`c_schema` text,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = config_info_aggr */
/******************************************/
CREATE TABLE `config_info_aggr` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`data_id` varchar(255) NOT NULL COMMENT 'data_id',
`group_id` varchar(255) NOT NULL COMMENT 'group_id',
`datum_id` varchar(255) NOT NULL COMMENT 'datum_id',
`content` longtext NOT NULL COMMENT '内容',
`gmt_modified` datetime NOT NULL COMMENT '修改时间',
`app_name` varchar(128) DEFAULT NULL,
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = config_info_beta */
/******************************************/
CREATE TABLE `config_info_beta` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`data_id` varchar(255) NOT NULL COMMENT 'data_id',
`group_id` varchar(128) NOT NULL COMMENT 'group_id',
`app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
`content` longtext NOT NULL COMMENT 'content',
`beta_ips` varchar(1024) DEFAULT NULL COMMENT 'betaIps',
`md5` varchar(32) DEFAULT NULL COMMENT 'md5',
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '修改时间',
`src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip',
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = config_info_tag */
/******************************************/
CREATE TABLE `config_info_tag` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`data_id` varchar(255) NOT NULL COMMENT 'data_id',
`group_id` varchar(128) NOT NULL COMMENT 'group_id',
`tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
`tag_id` varchar(128) NOT NULL COMMENT 'tag_id',
`app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
`content` longtext NOT NULL COMMENT 'content',
`md5` varchar(32) DEFAULT NULL COMMENT 'md5',
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '修改时间',
`src_user` text COMMENT 'source user',
`src_ip` varchar(20) DEFAULT NULL COMMENT 'source ip',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = config_tags_relation */
/******************************************/
CREATE TABLE `config_tags_relation` (
`id` bigint(20) NOT NULL COMMENT 'id',
`tag_name` varchar(128) NOT NULL COMMENT 'tag_name',
`tag_type` varchar(64) DEFAULT NULL COMMENT 'tag_type',
`data_id` varchar(255) NOT NULL COMMENT 'data_id',
`group_id` varchar(128) NOT NULL COMMENT 'group_id',
`tenant_id` varchar(128) DEFAULT '' COMMENT 'tenant_id',
`nid` bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`nid`),
UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = group_capacity */
/******************************************/
CREATE TABLE `group_capacity` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`group_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
`quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
`usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
`max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
`max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
`max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
`max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_group_id` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = his_config_info */
/******************************************/
CREATE TABLE `his_config_info` (
`id` bigint(64) unsigned NOT NULL,
`nid` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`data_id` varchar(255) NOT NULL,
`group_id` varchar(128) NOT NULL,
`app_name` varchar(128) DEFAULT NULL COMMENT 'app_name',
`content` longtext NOT NULL,
`md5` varchar(32) DEFAULT NULL,
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',
`src_user` text,
`src_ip` varchar(20) DEFAULT NULL,
`op_type` char(10) DEFAULT NULL,
`tenant_id` varchar(128) DEFAULT '' COMMENT '租户字段',
PRIMARY KEY (`nid`),
KEY `idx_gmt_create` (`gmt_create`),
KEY `idx_gmt_modified` (`gmt_modified`),
KEY `idx_did` (`data_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';
/******************************************/
/* 数据库全名 = nacos_config */
/* 表名称 = tenant_capacity */
/******************************************/
CREATE TABLE `tenant_capacity` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`tenant_id` varchar(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
`quota` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
`usage` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '使用量',
`max_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
`max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
`max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
`max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '创建时间',
`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00' COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';
CREATE TABLE `tenant_info` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`kp` varchar(128) NOT NULL COMMENT 'kp',
`tenant_id` varchar(128) default '' COMMENT 'tenant_id',
`tenant_name` varchar(128) default '' COMMENT 'tenant_name',
`tenant_desc` varchar(256) DEFAULT NULL COMMENT 'tenant_desc',
`create_source` varchar(32) DEFAULT NULL COMMENT 'create_source',
`gmt_create` bigint(20) NOT NULL COMMENT '创建时间',
`gmt_modified` bigint(20) NOT NULL COMMENT '修改时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';
......@@ -57,26 +57,6 @@
<scope>provided</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>oss</id>
<name>oss</name>
<url>https://oss.sonatype.org/content/groups/public</url>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype Nexus Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
</repositories>
<!--依赖管理,用于管理spring-cloud的依赖,其中Camden.SR3是版本号-->
<dependencyManagement>
<dependencies>
......
......@@ -9,6 +9,7 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.upyuns.platform.rs</groupId>
<artifactId>rs-datacenter-api</artifactId>
<version>2.0-rscp-SNAPSHOT</version>
......
......@@ -20,7 +20,11 @@ public class RscpResolution implements java.io.Serializable {
private String id;
/** resolutionName */
@ApiModelProperty(value = "")
@ApiModelProperty(value = "分辨率标识")
private String resolution;
/** resolutionName */
@ApiModelProperty(value = "分辨率展示")
private String resolutionName;
/** sensorName */
......@@ -32,7 +36,7 @@ public class RscpResolution implements java.io.Serializable {
private Integer status;
/** sort */
@ApiModelProperty(value = "")
@ApiModelProperty(value = "排序")
private Integer sort;
/** 首页排序 */
......
package com.upyuns.platform.rs.datacenter.fegin;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaInfo;
import com.upyuns.platform.rs.datacenter.entity.RscpImageDataTotal;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* ${DESCRIPTION}
*
* @author wanghaobin
* @create 2017-06-21 8:11
*/
@FeignClient(value = "rs-datacenter", contextId = "datacenter-base")
public interface DatacenterFeign {
@RequestMapping(value = "/web/areaInfo/app/unauth/Fegin/queryByCodeFegin", method = RequestMethod.GET)
public ObjectRestResponse<RscpAreaInfo> queryByCode(String areaCode);
@RequestMapping(value = "/web/imageData/app/unauth/Fegin/queryById", method = RequestMethod.GET)
public ObjectRestResponse<RscpImageDataTotal> queryById(String id);
}
......@@ -9,11 +9,12 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.upyuns.platform.rs</groupId>
<artifactId>rs-datacenter-server</artifactId>
<dependencies>
<dependency>
<groupId>com.upyuns.common</groupId>
<groupId>com.upyuns.platform.rs</groupId>
<artifactId>rs-datacenter-api</artifactId>
<version>2.0-rscp-SNAPSHOT</version>
<scope>compile</scope>
......
package com.upyuns.platform.rs.datacenter.biz;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaImageTotal;
import com.upyuns.platform.rs.datacenter.entity.RscpImageDataTotal;
import com.upyuns.platform.rs.datacenter.mapper.RscpImageDataTotalMapper;
import com.upyuns.platform.rs.datacenter.rest.RscpImageDataTotalController;
......@@ -16,5 +19,18 @@ public class RscpImageDataTotalBiz extends BaseBiz<RscpImageDataTotalMapper, Rsc
return mapper.queryDataList(dto);
}
public List<RscpAreaImageTotal> queryDataAreaList(RscpImageDataTotalController.QueryDTO dto) {
List<RscpImageDataTotal> list = mapper.queryDataList(dto);
List<RscpAreaImageTotal> list2 = CollUtil.newArrayList();
if(CollUtil.isNotEmpty(list)) {
for(RscpImageDataTotal ridt : list) {
RscpAreaImageTotal rait = BeanUtil.toBean(ridt, RscpAreaImageTotal.class);
rait.setBeginTime(ridt.getImageTakeTime());
list2.add(rait);
}
}
return list2;
}
}
package com.upyuns.platform.rs.datacenter.rest;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.rest.CommonBaseController;
import com.upyuns.platform.rs.datacenter.entity.RscpAreaInfo;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
@RestController
@Slf4j
@RequestMapping("/web/gtdata/")
public class GtdataController extends CommonBaseController {
@Autowired
GtDataRestClient gtDataRestClient;
@RequestMapping(value = "/app/unauth/image/**", method = RequestMethod.GET)
@IgnoreUserToken
public void queryAreaInfoByAreaId() throws Exception {
String url = request.getRequestURI();
String fileName = url.substring(url.lastIndexOf("/")+1);
// String filePath = "/obt/thumbnail/"+ url.substring(url.lastIndexOf("/app/unauth/image/")+18);
String filePath = "/obt/thumbnail/data/VDM2/20200613/VDM2_20200525232637_0015_L1_MSS_CMOS5/VDM2_20200525232637_0015_L1_MSS_CMOS5_98_98.jpg";
filePath = gtDataRestClient.openUrl(filePath);
downloadVideoById(fileName, filePath, getResponse());
return;
}
public void downloadVideoById(String fileName, String filePath, HttpServletResponse response) throws Exception {
log.info("下载请求start>>");
try {
if (StrUtil.isEmpty(fileName) || StrUtil.isEmpty(filePath)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("参数错误,请联系管理员!");
response.flushBuffer();
return;
}
URL pathUrl = new URL(filePath);
HttpURLConnection urlcon = (HttpURLConnection) pathUrl.openConnection();
if(urlcon.getResponseCode()>=400){
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("文件不存在,请联系管理员!");
response.flushBuffer();
return;
}
//获取输入流对象(用于读文件) 网络流
InputStream inputStream = new URL(filePath).openStream();
//本地流文件
// FileInputStream fis = new FileInputStream(new File(filePath));
//动态设置响应类型,根据前台传递文件类型设置响应类型
response.setContentType("image/" + fileName.substring(fileName.lastIndexOf(".")+1));
//设置响应头,attachment表示以附件的形式下载,inline表示在线打开
response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));//下载时浏览器显示的名称
//获取输出流对象(用于写文件)
ServletOutputStream os = response.getOutputStream();
//下载文件,使用spring框架中的FileCopyUtils工具
FileCopyUtils.copy(inputStream, os);
} catch (Exception e) {
log.error("下载失败 start >>",e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print("下载失败,请联系管理员!");
response.flushBuffer();
}
}
}
......@@ -2,6 +2,7 @@ package com.upyuns.platform.rs.datacenter.rest;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.datacenter.biz.RscpAreaInfoBiz;
......@@ -18,10 +19,11 @@ import java.util.stream.Collectors;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
@RestController
@RequestMapping("areaInfo")
@RequestMapping("/web/areaInfo")
public class RscpAreaInfoController extends BaseController<RscpAreaInfoBiz, RscpAreaInfo> {
@RequestMapping(value = "/app/unauth/getAreaList", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse<List<RscpAreaInfo>> getAreaList(String parentId) {
if(StrUtil.isBlank(parentId)) {
parentId = "000000";
......@@ -30,7 +32,14 @@ public class RscpAreaInfoController extends BaseController<RscpAreaInfoBiz, Rscp
}
@RequestMapping(value = "/app/unauth/queryAreaInfoByAreaId", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse<RscpAreaInfo> queryAreaInfoByAreaId(String areaCode) {
return ObjectRestResponse.succ( baseBiz.queryAreaInfoByAreaId(areaCode));
}
@RequestMapping(value = "/app/unauth/Fegin/queryByCodeFegin", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse<RscpAreaInfo> queryByCode(String areaCode) {
return ObjectRestResponse.succ( baseBiz.queryAreaInfoByAreaId(areaCode));
}
}
\ No newline at end of file
......@@ -4,6 +4,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.Query;
......@@ -27,13 +28,14 @@ import java.util.Collections;
import java.util.List;
@RestController
@RequestMapping("imageData")
@RequestMapping("/web/imageData")
public class RscpImageDataTotalController extends BaseController<RscpImageDataTotalBiz, RscpImageDataTotal> {
@Autowired
RscpAreaImageTotalBiz rscpAreaImageTotalBiz;
@RequestMapping(value = "/app/unauth/query", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse unauthQuery(PageParam pageParam) {
return ObjectRestResponse.succ(baseBiz.selectByQuery(new Query(pageParam)));
}
......@@ -67,14 +69,20 @@ public class RscpImageDataTotalController extends BaseController<RscpImageDataTo
// 分辨率id
@RequestMapping(value = "/app/unauth/queryDataList", method = RequestMethod.POST)
@IgnoreUserToken
public ObjectRestResponse queryDataList(@RequestBody QueryDTO dto) {
if(RscpImageDataTotalController.QueryDTO.TYPE_AREA == dto.getType()) {
return ObjectRestResponse.succ(rscpAreaImageTotalBiz.queryDataList(dto));
}else {
return ObjectRestResponse.succ(baseBiz.queryDataList(dto));
return ObjectRestResponse.succ(baseBiz.queryDataAreaList(dto));
}
}
@RequestMapping(value = "/web/imageData/app/unauth/Fegin/queryByIds", method = RequestMethod.GET)
public ObjectRestResponse<List<RscpImageDataTotal>> queryById(String ids){
return ObjectRestResponse.succ(baseBiz.selectByAttrs(RscpImageDataTotal::getId, CollUtil.toList(ids.split(","))));
}
@Data
static public class QueryDTO {
......@@ -83,6 +91,7 @@ public class RscpImageDataTotalController extends BaseController<RscpImageDataTo
Integer type;
String startDate;
String endDate;
BigDecimal resolution;
String startDateTime;
String endDateTime;
String geom;
......
package com.upyuns.platform.rs.datacenter.rest;
import cn.hutool.core.collection.CollUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.Query;
......@@ -21,10 +22,11 @@ import java.util.stream.Collectors;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
@RestController
@RequestMapping("imagePrice")
@RequestMapping("/web/imagePrice")
public class RscpImagePriceController extends BaseController<RscpImagePriceBiz, RscpImagePrice> {
@RequestMapping(value = "/app/unauth/all", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse unauthQuery() {
List<RscpImagePrice> list = baseBiz.selectByWeekend(w -> {
......@@ -34,7 +36,7 @@ public class RscpImagePriceController extends BaseController<RscpImagePriceBiz,
List<ImagePriceVO> imagePriceVOS = CollUtil.newArrayList();
String key = "";
List<String> satelliteTypes = list.parallelStream().map(RscpImagePrice::getImageSatelliteType).collect(Collectors.toList());
List<String> satelliteTypes = list.parallelStream().map(RscpImagePrice::getImageSatelliteType).distinct().collect(Collectors.toList());
for(String satelliteType : satelliteTypes) {
List<RscpImagePrice> imagePriceList = list.parallelStream().filter(rscpImagePrice -> satelliteType.equals(rscpImagePrice.getImageSatelliteType())).collect(Collectors.toList());
imagePriceVOS.add(new ImagePriceVO(){{
......
package com.upyuns.platform.rs.datacenter.rest;
import cn.hutool.core.collection.CollUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.datacenter.biz.RscpImagePriceBiz;
......@@ -20,11 +21,12 @@ import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FA
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
@RestController
@RequestMapping("resolution")
@RequestMapping("/web/resolution")
public class RscpResolutionController extends BaseController<RscpResolutionBiz, RscpResolution> {
@RequestMapping(value = "/app/unauth/all", method = RequestMethod.GET)
@IgnoreUserToken
public ObjectRestResponse unauthQuery() {
List<RscpResolution> list = baseBiz.selectByWeekend(w -> {
......
......@@ -63,6 +63,9 @@
</if>
</foreach>
</if>
<if test="resolution != null">
and #{resolution} = any(image_resolution)
</if>
<if test="startDateTime != null">
and begin_time &gt;= #{startDateTime}
</if>
......
......@@ -112,6 +112,9 @@
</if>
</foreach>
</if>
<if test="resolution != null">
and #{resolution} = any(image_resolution)
</if>
<if test="startDateTime != null">
and image_take_time &gt;= #{startDateTime}
</if>
......
......@@ -89,4 +89,9 @@ public class DictionaryKey {
* 取消时间缓冲(分钟)
*/
public static final String CANCEL_TIME_BUFFER = "CANCEL_TIME_BUFFER";
/**
* 运费
*/
public static final String SEND_FEE = "SEND_FEE";
}
......@@ -54,634 +54,666 @@ import static com.upyuns.platform.rs.universal.constant.DictionaryKey.UNIVERSAL_
*/
@Service
@Slf4j
public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay>{
@Autowired
DictionaryBiz dictionaryBiz;
@Autowired
HttpServletRequest request;
@Autowired
MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}")
String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
private static final String SUCCESS = "SUCCESS";
public JSONObject preparepay(OrderPayVo orderPayVo) {
if (null == orderPayVo) {
log.error("-----参数为空-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
}
if (orderPayVo.getAmount() == null || orderPayVo.getAmount() == 0) {
log.error("-----金额不为为0-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "金额不为为0");
}
if (StringUtils.isBlank(orderPayVo.getOrderNo())) {
log.error("-----订单不能为空-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "订单不能为空");
}
log.info("订单支付参数:orderVo = {}", orderPayVo.toString());
String trade_no = OrderUtil.GetOrderNumber("");
orderPayVo.setTradeNo(trade_no);
String order_no = orderPayVo.getOrderNo();
Integer amount = orderPayVo.getAmount();
log.error("---下单---order_no=====" + order_no + "--支付订单号--trade_no====" + trade_no + "--金额---amount====" + amount);
//报名费回调路径
//临时处理
Map<String, Dictionary> dictionaryMap = dictionaryBiz.getAll4Map();
Integer demotion = Integer.valueOf(dictionaryMap.get(UNIVERSAL_PAY + "_" + PAY_DEMOTION).getDetail());
amount = amount / demotion;
if (amount <= 0) {
amount = 1;
}
Integer type = orderPayVo.getType() == null ? 1 : orderPayVo.getType();
String jsParam = "";
String notify_url = weixinHost + "/api/universal/pay/app/unauth/notify";
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
log.info("报名费回调路径notify_url:" + notify_url);
Integer payWay = orderPayVo.getPayWay() == null ? 1 : orderPayVo.getPayWay();
String sellerAccount = null;
if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(), null);
} else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID;
orderPayVo.setPayType(2);
jsParam = generateAliPayment(orderPayVo, notifyUrl);
} else if (type == 3 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(), wy_appid);
}
log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) {
try {
OrderPay orderPay = new OrderPay();
BeanUtils.copyProperties(orderPay, orderPayVo);
orderPay.setSellerAccount(sellerAccount);
insertSelective(orderPay);
log.error("---下单---order_no=====" + order_no + "----成功");
} catch (Exception e) {
log.error(e.getMessage(), e);;
log.error("---下单---order_no=====" + order_no + "----异常---msg===" + e.getMessage());
return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
}
if (payWay == 1) {
JSONObject temp = JSON.parseObject(jsParam);
return JsonResultUtil.createSuccessResultWithObj(temp);
} else {
return JsonResultUtil.createSuccessResultWithObj(jsParam);
}
} else {
return JsonResultUtil.createDefaultFail();
}
}
//支付回调
public void notice(String orderNo, String serialNumber) {
log.error("---支付回调---trade_no=====" + orderNo + "----开始处理");
Example example = new Example(OrderPay.class);
example.createCriteria().andEqualTo("tradeNo", orderNo).andEqualTo("isDel", 0).andEqualTo("status", 0);
List<OrderPay> list = mapper.selectByExample(example);
if (list.size() == 0) {
log.error("---支付回调---trade_no=====" + orderNo + "----订单不存在或已处理");
return;
}
example.clear();
example.createCriteria().andEqualTo("tradeNo", orderNo);
OrderPay orderPay = new OrderPay();
orderPay.setFinishTime(System.currentTimeMillis());
orderPay.setStatus(1);
orderPay.setSerialNumber(serialNumber);
int num = mapper.updateByExampleSelective(orderPay, example);
log.error("---支付回调处理---num=====" + num + "----orderNo=======" + orderNo);
if (num > 0) {
//支付成功,添加积分
OrderPay pay = list.get(0);
OrderPay newValue = mapper.selectOne(orderPay);
log.info("支付回调信息:newValue = {}", newValue);
if (newValue.getStatus() == 1) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", newValue.getUserId());
jsonObject.put("amount", newValue.getAmount());
jsonObject.put("channelId", newValue.getOrderNo());
if (newValue.getChannel() == 1) {//租车
jsonObject.put("integralRuleCode", "RENTRV");
} else if (newValue.getChannel() == 2) { //旅游
jsonObject.put("integralRuleCode", "BUYROUT");
} else if (newValue.getChannel() == 3) { //会员
jsonObject.put("integralRuleCode", "BUYMEMBER");
}
log.info("支付订单号:orderNo = {}, orderType = {}", newValue.getOrderNo(), newValue.getChannel());
log.info("支付成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
mqServiceBiZ.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
}
if (StringUtils.isNotBlank(pay.getNotifyUrl())) {
String url = pay.getNotifyUrl();
Integer type = pay.getType() == null ? 1 : pay.getType();
Integer payWay = pay.getPayWay();
url += "&tradeNo=" + orderNo + "&type=" + type+"&payWay="+payWay;
log.error("---支付回调处理---orderNo=======" + orderNo + "----notifyUrl====" + url);
String result = "";
if (url.contains("https") || url.contains("HTTPS")) {
result = HTTPSUtils.httpRequest(url, "GET", null);
} else {
result = HTTPUtils.doGet(url);
}
log.error("---支付回调处理---orderNo=======" + orderNo + "---result===" + result);
}
}
}
public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
@Autowired
DictionaryBiz dictionaryBiz;
@Autowired
HttpServletRequest request;
@Autowired
MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}")
String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
private static final String SUCCESS = "SUCCESS";
public JSONObject preparepay(OrderPayVo orderPayVo) {
if (null == orderPayVo) {
log.error("-----参数为空-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
}
if (orderPayVo.getAmount() == null || orderPayVo.getAmount() == 0) {
log.error("-----金额不为为0-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "金额不为为0");
}
if (StringUtils.isBlank(orderPayVo.getOrderNo())) {
log.error("-----订单不能为空-----------");
return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "订单不能为空");
}
log.info("订单支付参数:orderVo = {}", orderPayVo.toString());
String trade_no = OrderUtil.GetOrderNumber("");
orderPayVo.setTradeNo(trade_no);
String order_no = orderPayVo.getOrderNo();
Integer amount = orderPayVo.getAmount();
log.error("---下单---order_no=====" + order_no + "--支付订单号--trade_no====" + trade_no + "--金额---amount====" + amount);
//报名费回调路径
//临时处理
Map<String, Dictionary> dictionaryMap = dictionaryBiz.getAll4Map();
Integer demotion = Integer.valueOf(dictionaryMap.get(UNIVERSAL_PAY + "_" + PAY_DEMOTION).getDetail());
amount = amount / demotion;
if (amount <= 0) {
amount = 1;
}
Integer type = orderPayVo.getType() == null ? 1 : orderPayVo.getType();
String jsParam = "";
String notify_url = weixinHost + "/api/universal/pay/app/unauth/notify";
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
log.info("报名费回调路径notify_url:" + notify_url);
Integer payWay = orderPayVo.getPayWay() == null ? 1 : orderPayVo.getPayWay();
String sellerAccount = null;
if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(), null);
} else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID;
orderPayVo.setPayType(2);
jsParam = generateAliPayment(orderPayVo, notifyUrl);
} else if (type == 3 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(), wy_appid);
}
log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) {
try {
OrderPay orderPay = new OrderPay();
BeanUtils.copyProperties(orderPay, orderPayVo);
orderPay.setSellerAccount(sellerAccount);
insertSelective(orderPay);
log.error("---下单---order_no=====" + order_no + "----成功");
} catch (Exception e) {
log.error(e.getMessage(), e);
;
log.error("---下单---order_no=====" + order_no + "----异常---msg===" + e.getMessage());
return JsonResultUtil.createFailedResult(ResultCode.EXCEPTION_CODE, "出现异常");
}
if (payWay == 1) {
JSONObject temp = JSON.parseObject(jsParam);
return JsonResultUtil.createSuccessResultWithObj(temp);
} else {
return JsonResultUtil.createSuccessResultWithObj(jsParam);
}
} else {
return JsonResultUtil.createDefaultFail();
}
}
//支付回调
public void notice(String orderNo, String serialNumber) {
log.error("---支付回调---trade_no=====" + orderNo + "----开始处理");
Example example = new Example(OrderPay.class);
example.createCriteria().andEqualTo("tradeNo", orderNo).andEqualTo("isDel", 0).andEqualTo("status", 0);
List<OrderPay> list = mapper.selectByExample(example);
if (list.size() == 0) {
log.error("---支付回调---trade_no=====" + orderNo + "----订单不存在或已处理");
return;
}
example.clear();
example.createCriteria().andEqualTo("tradeNo", orderNo);
OrderPay orderPay = new OrderPay();
orderPay.setFinishTime(System.currentTimeMillis());
orderPay.setStatus(1);
orderPay.setSerialNumber(serialNumber);
int num = mapper.updateByExampleSelective(orderPay, example);
log.error("---支付回调处理---num=====" + num + "----orderNo=======" + orderNo);
if (num > 0) {
//支付成功,添加积分
OrderPay pay = list.get(0);
OrderPay newValue = mapper.selectOne(orderPay);
log.info("支付回调信息:newValue = {}", newValue);
if (newValue.getStatus() == 1) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", newValue.getUserId());
jsonObject.put("amount", newValue.getAmount());
jsonObject.put("channelId", newValue.getOrderNo());
if (newValue.getChannel() == 1) {//租车
jsonObject.put("integralRuleCode", "RENTRV");
} else if (newValue.getChannel() == 2) { //旅游
jsonObject.put("integralRuleCode", "BUYROUT");
} else if (newValue.getChannel() == 3) { //会员
jsonObject.put("integralRuleCode", "BUYMEMBER");
}
log.info("支付订单号:orderNo = {}, orderType = {}", newValue.getOrderNo(), newValue.getChannel());
log.info("支付成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
mqServiceBiZ.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
}
if (StringUtils.isNotBlank(pay.getNotifyUrl())) {
String url = pay.getNotifyUrl();
Integer type = pay.getType() == null ? 1 : pay.getType();
Integer payWay = pay.getPayWay();
url += "&tradeNo=" + orderNo + "&type=" + type + "&payWay=" + payWay;
log.error("---支付回调处理---orderNo=======" + orderNo + "----notifyUrl====" + url);
String result = "";
if (url.contains("https") || url.contains("HTTPS")) {
result = HTTPSUtils.httpRequest(url, "GET", null);
} else {
result = HTTPUtils.doGet(url);
}
log.error("---支付回调处理---orderNo=======" + orderNo + "---result===" + result);
/**
* 支付宝回调接口
*
* @return
*/
public String alipayNotify() {
//获取支付宝POST过来反馈信息
Map<String, String> params = new HashMap<>();
Map requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
params.put(name, valueStr);
}
String msg = JSONObject.toJSONString(params);
log.info("alipay notify message={}", msg);
//支付宝回调验签
try {
boolean flag = AlipaySignature.rsaCheckV1(params, SystemConfig.ALIPAY_PUBLIC_KEY, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
if (!flag) {
log.info("alipay order rsaCheckV1 fail, result={}", msg);
return ObjectRestResponse.createDefaultFail().getMessage();
}
String rsTradeStatus = params.get("trade_status");
if (StringUtils.isBlank(rsTradeStatus)) { //订单预授权支付回调
}
}
}
/**
* 支付宝回调接口
*
* @return
*/
public String alipayNotify() {
//获取支付宝POST过来反馈信息
Map<String, String> params = new HashMap<>();
Map requestParams = request.getParameterMap();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i]
: valueStr + values[i] + ",";
}
params.put(name, valueStr);
}
String msg = JSONObject.toJSONString(params);
log.info("alipay notify message={}", msg);
//支付宝回调验签
try {
boolean flag = AlipaySignature.rsaCheckV1(params, SystemConfig.ALIPAY_PUBLIC_KEY, AlipayConstants.CHARSET_UTF8, AlipayConstants.SIGN_TYPE_RSA2);
if (!flag) {
log.info("alipay order rsaCheckV1 fail, result={}", msg);
return ObjectRestResponse.createDefaultFail().getMessage();
}
String rsTradeStatus = params.get("trade_status");
if (StringUtils.isBlank(rsTradeStatus)) { //订单预授权支付回调
String status = params.get("status");
if (!status.equals("SUCCESS")) {
log.info("alipay order trade_status has problem, result={}", msg);
return ObjectRestResponse.createDefaultFail().getMessage();
}
//订单APP支付回调
//订单APP支付回调
} else if (!SystemConfig.ALIPAY_TRADE_FINISHED.equals(rsTradeStatus) && !SystemConfig.ALIPAY_TRADE_SUCCESS.equals(rsTradeStatus)) {
log.info("alipay order trade_status has problem, result={}", msg);
return ObjectRestResponse.createDefaultFail().getMessage();
}
log.info("alipay order trade_status has problem, result={}", msg);
return ObjectRestResponse.createDefaultFail().getMessage();
}
String tradeNo = params.get("out_trade_no");
String tradeNo = params.get("out_trade_no");
if (StringUtils.isBlank(tradeNo)) {
tradeNo = params.get("out_request_no");
}
String operationId = params.get("trade_no");
if (StringUtils.isBlank(operationId)) {
operationId = params.get("auth_no");
String operationId = params.get("trade_no");
if (StringUtils.isBlank(operationId)) {
operationId = params.get("auth_no");
}
notice(tradeNo, operationId);
return ObjectRestResponse.succ().getMessage();
} catch (AlipayApiException e) {
log.error("", e);
}
return ObjectRestResponse.createDefaultFail().getMessage();
}
/**
* 支付宝生成支付信息
*
* @return
*/
@SuppressWarnings("rawtypes")
private String generateAliPayment(OrderPayVo orderPayVo, String notifyUrl) {
//实例化客户端
AlipayClient alipayClient = getAlipayClient();
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
try {
return fundAuthOrderAppFreeze(alipayClient, orderPayVo, notifyUrl);
} catch (Exception e) {
log.error(e.getMessage(), e);;
}
return null;
}
private AlipayClient getAlipayClient() {
AlipayClient alipayClient = new DefaultAlipayClient(SystemConfig.ALIPAY_PAY_BASE_URL + "/gateway.do",
SystemConfig.ALIPAY_APPID, SystemConfig.ALIPAY_PRIVATE_KEY, AlipayConstants.FORMAT_JSON,
"utf-8", SystemConfig.ALIPAY_PUBLIC_KEY, AlipayConstants.SIGN_TYPE_RSA2);
return alipayClient;
}
//balance 余额
//moneyFund 余额宝
//coupon 红包
//pcredit 花呗
//pcreditpayInstallment 花呗分期
//creditCard 信用卡
//creditCardExpress 信用卡快捷
//creditCardCartoon 信用卡卡通
//credit_group 信用支付类型(包含信用卡卡通、信用卡快捷、花呗、花呗分期)
//debitCardExpress 借记卡快捷
//mcard 商户预存卡
//pcard 个人预存卡
//promotion 优惠(包含实时优惠+商户优惠)
//voucher 营销券
//point 积分
//mdiscount 商户优惠
//bankPay
//支付宝APP支付方法
private String appOrderPay(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) {
notice(tradeNo, operationId);
return ObjectRestResponse.succ().getMessage();
} catch (AlipayApiException e) {
log.error("", e);
}
return ObjectRestResponse.createDefaultFail().getMessage();
}
/**
* 支付宝生成支付信息
*
* @return
*/
@SuppressWarnings("rawtypes")
private String generateAliPayment(OrderPayVo orderPayVo, String notifyUrl) {
//实例化客户端
AlipayClient alipayClient = getAlipayClient();
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
try {
return preCreate(alipayClient, orderPayVo, notifyUrl);
} catch (Exception e) {
log.error(e.getMessage(), e);
;
}
return null;
}
private AlipayClient getAlipayClient() {
AlipayClient alipayClient = new DefaultAlipayClient(SystemConfig.ALIPAY_PAY_BASE_URL + "/gateway.do",
SystemConfig.ALIPAY_APPID, SystemConfig.ALIPAY_PRIVATE_KEY, AlipayConstants.FORMAT_JSON,
"utf-8", SystemConfig.ALIPAY_PUBLIC_KEY, AlipayConstants.SIGN_TYPE_RSA2);
return alipayClient;
}
//balance 余额
//moneyFund 余额宝
//coupon 红包
//pcredit 花呗
//pcreditpayInstallment 花呗分期
//creditCard 信用卡
//creditCardExpress 信用卡快捷
//creditCardCartoon 信用卡卡通
//credit_group 信用支付类型(包含信用卡卡通、信用卡快捷、花呗、花呗分期)
//debitCardExpress 借记卡快捷
//mcard 商户预存卡
//pcard 个人预存卡
//promotion 优惠(包含实时优惠+商户优惠)
//voucher 营销券
//point 积分
//mdiscount 商户优惠
//bankPay
//支付宝APP支付方法
private String appOrderPay(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) {
BigDecimal realAmount = new BigDecimal(orderPayVo.getAmount().toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
request.setBizContent("{" +
"\"total_amount\":\"" + realAmount + "\"," +
"\"subject\":\"" + orderPayVo.getSubject() + "\"," +
"\"enable_pay_channels\":\"balance,coupon,creditCard,creditCardExpress,creditCardCartoon,pcredit,credit_group,moneyFund,debitCardExpress\"," +
"\"out_trade_no\":\"" + orderPayVo.getTradeNo() + "\"" +
" }");
request.setNotifyUrl(notifyUrl);
try {
//这里和普通的接口调用不同,使用的是sdkExecute
AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
log.info(response.getBody());//就是orderString 可以直接给客户端请求,无需再做处理。
return response.getBody();
} catch (AlipayApiException e) {
log.error(e.getMessage(), e);
}
return null;
}
/**
* 扫码支付
*
* @return
*/
private String preCreate(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) {
BigDecimal realAmount = new BigDecimal(orderPayVo.getAmount().toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
request.setBizContent("{" +
"\"total_amount\":\"" + realAmount + "\"," +
"\"subject\":\"" + orderPayVo.getSubject() + "\"," +
"\"enable_pay_channels\":\"balance,coupon,creditCard,creditCardExpress,creditCardCartoon,pcredit,credit_group,moneyFund,debitCardExpress\"," +
"\"out_trade_no\":\"" + orderPayVo.getTradeNo() + "\"" +
" }");
request.setNotifyUrl(notifyUrl);
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); //创建API对应的request类
request.setBizContent("{" +
"\"out_trade_no\":\"" + orderPayVo.getTradeNo() + "\"," + //商户订单号
"\"total_amount\":\""+realAmount+"\"," +
"\"subject\":\"" + orderPayVo.getSubject() + "\"," +
"\"timeout_express\":\"30m\"}"); //订单允许的最晚付款时间
try {
//这里和普通的接口调用不同,使用的是sdkExecute
AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
AlipayTradePrecreateResponse response = alipayClient.execute(request);
log.info(response.getBody());//就是orderString 可以直接给客户端请求,无需再做处理。
return response.getBody();
} catch (AlipayApiException e) {
log.error(e.getMessage(), e);;
log.error(e.getMessage(), e);
}
return null;
}
//预授权冻结
public String fundAuthOrderAppFreeze(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) throws AlipayApiException {
AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
BigDecimal realAmount = new BigDecimal(orderPayVo.getAmount().toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
request.setBizContent("{" +
"\"out_order_no\":\"" + orderPayVo.getTradeNo() + "\"," +
"\"out_request_no\":\"" + orderPayVo.getTradeNo() + "\"," +
"\"order_title\":\"" + orderPayVo.getSubject() + "\"," +
"\"product_code\":\"PRE_AUTH_ONLINE\"," +
"\"pay_timeout\":\"1d\"," +
"\"amount\": \"" + realAmount.toString() + "\" }");
request.setNotifyUrl(notifyUrl);//异步通知地址,必填,该接口只通过该参数进行异步通知
AlipayFundAuthOrderAppFreezeResponse response = alipayClient.sdkExecute(request);//注意这里是sdkExecute,可以获取签名参数
log.info("response: {}" + response.getBody());//签名后的参数,直接入参到
if (response.isSuccess()) {
log.info("预授权冻结调用成功");
return response.getBody();
} else {
log.info("预授权冻结调用失败");
return null;
}
}
/**
* 转账功能 微信 | 支付宝
*
* @param fundPayVo
* @return
* @throws Exception
*/
public String fundTrans(FundPayVo fundPayVo) throws BaseException {
String cono = OrderUtil.GetOrderNumber("");
fundPayVo.setOutBizNo(cono);
if (fundPayVo.getType() == PayWay.WX_PAY.getCode()) {
//微信
fundPayVo.setCheckName("NO_CHECK");
return wxpayfundTrans(fundPayVo);
}
if (fundPayVo.getType() == PayWay.ALI_PAY.getCode()) {
//支付宝
return alipayfundTrans(getAlipayClient(), fundPayVo);
}
throw new BaseException("提现方式不对");
}
/**
* 支付宝转账功能 单笔最小转账0.1 最大小数点位数前支持13位,实际限额和签约一致
*
* @param alipayClient
* @throws AlipayApiException
*/
public String alipayfundTrans(AlipayClient alipayClient, FundPayVo fundPayVo){
AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
request.setBizContent("{" +
"\"out_biz_no\":\"" + fundPayVo.getOutBizNo() + "\"," +
"\"payee_type\":\"ALIPAY_USERID\"," +
"\"payee_account\":\"" + fundPayVo.getPayeeAccount() + "\"," +
"\"amount\":\"" + fundPayVo.getAmount() + "\"," +
"\"payer_show_name\":\"" + fundPayVo.getPayerShowName() + "\"," +
"\"remark\":\"" + fundPayVo.getRemark() + "\"" +
" }");
AlipayFundTransToaccountTransferResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
throw new BaseException("支付宝转账api调用错误",e);
}
if (response.isSuccess()) {
return fundPayVo.getOutBizNo();
} else {
throw new BaseException(response.getSubMsg(),response.getSubCode());
}
}
public String wxpayfundTrans(FundPayVo fundPayVo) {
Map<String, String> map = WXSuppToUserPay.WeiXinTiXian(fundPayVo.getPayeeAccount(),fundPayVo.getOutBizNo(),fundPayVo.getCheckName(), fundPayVo.getAmount(), fundPayVo.getRemark(), fundPayVo.getCreatIp());
if (SUCCESS.equals(map.get(WxResponseProperties.RETURN_CODE)) && SUCCESS.equals(map.get(WxResponseProperties.RESULT_CODE))) {
return map.get(WxResponseProperties.PARTNER_TRADE_NO);
}
throw new BaseException(map.get(WxResponseProperties.ERR_CODE_DES),map.get(WxResponseProperties.ERROR_CODE));
}
/**
* 支付宝授权获取用户信息
* @param code
* @return
* @throws AlipayApiException
*/
public String getAlipayToken(String code) throws AlipayApiException{
AlipayClient alipayClient = getAlipayClient();
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(code);
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
log.info("获取用户token调用成功,获取用户信息 {}", response.getBody());
if(response.isSuccess()){
log.info("获取用户token调用成功,获取用户信息 {}", response.getBody());
if(response.getAccessToken() != null) {
AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest,response.getAccessToken());
if(alipayUserInfoShareResponse.isSuccess()){
log.info("获取用户支付宝信息调用成功, {}", alipayUserInfoShareResponse.getBody());
return alipayUserInfoShareResponse.getBody();
} else {
log.info("获取用户支付宝信息调用失败, {}", alipayUserInfoShareResponse.getBody());
}
}
} else {
log.info("获取用户token调用失败, {}", response.getBody());
}
return response.getBody();
}
public String generateAliPayInfo(String apiName, String appName) {
//apiname=com.alipay.account.auth&app_id=xxxxx&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=xxxxx&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA2&target_id=20141225xxxx&sign=fMcp4GtiM6rxSIeFnJCVePJKV43eXrUP86CQgiLhDHH2u%2FdN75eEvmywc2ulkm7qKRetkU9fbVZtJIqFdMJcJ9Yp%2BJI%2FF%2FpESafFR6rB2fRjiQQLGXvxmDGVMjPSxHxVtIqpZy5FDoKUSjQ2%2FILDKpu3%2F%2BtAtm2jRw1rUoMhgt0%3D
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("apiname=");
stringBuilder.append("com.alipay.account.auth");
stringBuilder.append("&app_id=");
stringBuilder.append(SystemConfig.ALIPAY_APPID);
stringBuilder.append("&app_name=");
stringBuilder.append("mc");
stringBuilder.append("&auth_type=AUTHACCOUNT");
stringBuilder.append("&biz_type=openservice");
stringBuilder.append("&method=alipay.open.auth.sdk.code.get");
stringBuilder.append("&pid=");
stringBuilder.append(SystemConfig.ALIPAY_PID);
stringBuilder.append("&product_id=APP_FAST_LOGIN");
stringBuilder.append("&scope=kuaijie");
stringBuilder.append("&sign_type=RSA2");
stringBuilder.append("&target_id=");
stringBuilder.append(UUIDUtils.generateShortUuid());
String sign = SignUtils.sign(stringBuilder.toString(), SystemConfig.ALIPAY_PRIVATE_KEY, true);
stringBuilder.append("&sign=");
stringBuilder.append(sign);
return stringBuilder.toString();
}
public String alipayUserAuth() throws AlipayApiException {
AlipayClient alipayClient = getAlipayClient();
AlipayUserInfoAuthRequest request = new AlipayUserInfoAuthRequest();
request.setBizContent("{" +
" \"scopes\":[" +
" \"auth_base\"" +
" ]," +
"\"state\":\"init\"," +
"\"is_mobile\":\"true\"" +
" }");
AlipayUserInfoAuthResponse response = alipayClient.execute(request);
log.info("解冻预授权response: {}" + response.getBody());
log.info(response.toString());
if(response.isSuccess()){
log.info("用户授权调用成功");
} else {
log.info("用户授权调用失败");
}
return response.getBody();
}
//解冻预授权
public boolean fundAuthOrderUnFreeze(String outTradeNo, String serialNumber, Integer refundAmount, String refundReason) throws AlipayApiException {
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayClient alipayClient = getAlipayClient();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
AlipayFundAuthOrderUnfreezeModel model = new AlipayFundAuthOrderUnfreezeModel();
model.setAuthNo(serialNumber); // 支付宝资金授权订单号,在授权冻结成功时返回需要入库保存
model.setOutRequestNo(outTradeNo);//同一商户每次不同的资金操作请求,商户请求流水号不能重复,且与冻结流水号不同
model.setAmount(realAmount.toString()); // 本次操作解冻的金额,单位为:元(人民币),精确到小数点后两位
model.setRemark(refundReason); // 商户对本次解冻操作的附言描述,长度不超过100个字母或50个汉字
//选填字段,信用授权订单,针对信用全免订单,传入该值完结信用订单,形成芝麻履约记录
// model.setExtraParam("{\"unfreezeBizInfo\":\"{\\\"bizComplete\\\":\\\"true\\\"}\"}");
request.setBizModel(model);
//预授权冻结
public String fundAuthOrderAppFreeze(AlipayClient alipayClient, OrderPayVo orderPayVo, String notifyUrl) throws AlipayApiException {
AlipayFundAuthOrderAppFreezeRequest request = new AlipayFundAuthOrderAppFreezeRequest();
BigDecimal realAmount = new BigDecimal(orderPayVo.getAmount().toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
request.setBizContent("{" +
"\"out_order_no\":\"" + orderPayVo.getTradeNo() + "\"," +
"\"out_request_no\":\"" + orderPayVo.getTradeNo() + "\"," +
"\"order_title\":\"" + orderPayVo.getSubject() + "\"," +
"\"product_code\":\"PRE_AUTH_ONLINE\"," +
"\"pay_timeout\":\"1d\"," +
"\"amount\": \"" + realAmount.toString() + "\" }");
request.setNotifyUrl(notifyUrl);//异步通知地址,必填,该接口只通过该参数进行异步通知
AlipayFundAuthOrderAppFreezeResponse response = alipayClient.sdkExecute(request);//注意这里是sdkExecute,可以获取签名参数
log.info("response: {}" + response.getBody());//签名后的参数,直接入参到
if (response.isSuccess()) {
log.info("预授权冻结调用成功");
return response.getBody();
} else {
log.info("预授权冻结调用失败");
return null;
}
}
/**
* 转账功能 微信 | 支付宝
*
* @param fundPayVo
* @return
* @throws Exception
*/
public String fundTrans(FundPayVo fundPayVo) throws BaseException {
String cono = OrderUtil.GetOrderNumber("");
fundPayVo.setOutBizNo(cono);
if (fundPayVo.getType() == PayWay.WX_PAY.getCode()) {
//微信
fundPayVo.setCheckName("NO_CHECK");
return wxpayfundTrans(fundPayVo);
}
if (fundPayVo.getType() == PayWay.ALI_PAY.getCode()) {
//支付宝
return alipayfundTrans(getAlipayClient(), fundPayVo);
}
throw new BaseException("提现方式不对");
}
/**
* 支付宝转账功能 单笔最小转账0.1 最大小数点位数前支持13位,实际限额和签约一致
*
* @param alipayClient
* @throws AlipayApiException
*/
public String alipayfundTrans(AlipayClient alipayClient, FundPayVo fundPayVo) {
AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
request.setBizContent("{" +
"\"out_biz_no\":\"" + fundPayVo.getOutBizNo() + "\"," +
"\"payee_type\":\"ALIPAY_USERID\"," +
"\"payee_account\":\"" + fundPayVo.getPayeeAccount() + "\"," +
"\"amount\":\"" + fundPayVo.getAmount() + "\"," +
"\"payer_show_name\":\"" + fundPayVo.getPayerShowName() + "\"," +
"\"remark\":\"" + fundPayVo.getRemark() + "\"" +
" }");
AlipayFundTransToaccountTransferResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
throw new BaseException("支付宝转账api调用错误", e);
}
if (response.isSuccess()) {
return fundPayVo.getOutBizNo();
} else {
throw new BaseException(response.getSubMsg(), response.getSubCode());
}
}
public String wxpayfundTrans(FundPayVo fundPayVo) {
Map<String, String> map = WXSuppToUserPay.WeiXinTiXian(fundPayVo.getPayeeAccount(), fundPayVo.getOutBizNo(), fundPayVo.getCheckName(), fundPayVo.getAmount(), fundPayVo.getRemark(), fundPayVo.getCreatIp());
if (SUCCESS.equals(map.get(WxResponseProperties.RETURN_CODE)) && SUCCESS.equals(map.get(WxResponseProperties.RESULT_CODE))) {
return map.get(WxResponseProperties.PARTNER_TRADE_NO);
}
throw new BaseException(map.get(WxResponseProperties.ERR_CODE_DES), map.get(WxResponseProperties.ERROR_CODE));
}
/**
* 支付宝授权获取用户信息
*
* @param code
* @return
* @throws AlipayApiException
*/
public String getAlipayToken(String code) throws AlipayApiException {
AlipayClient alipayClient = getAlipayClient();
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(code);
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
log.info("获取用户token调用成功,获取用户信息 {}", response.getBody());
if (response.isSuccess()) {
log.info("获取用户token调用成功,获取用户信息 {}", response.getBody());
if (response.getAccessToken() != null) {
AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest, response.getAccessToken());
if (alipayUserInfoShareResponse.isSuccess()) {
log.info("获取用户支付宝信息调用成功, {}", alipayUserInfoShareResponse.getBody());
return alipayUserInfoShareResponse.getBody();
} else {
log.info("获取用户支付宝信息调用失败, {}", alipayUserInfoShareResponse.getBody());
}
}
} else {
log.info("获取用户token调用失败, {}", response.getBody());
}
return response.getBody();
}
public String generateAliPayInfo(String apiName, String appName) {
//apiname=com.alipay.account.auth&app_id=xxxxx&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=xxxxx&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA2&target_id=20141225xxxx&sign=fMcp4GtiM6rxSIeFnJCVePJKV43eXrUP86CQgiLhDHH2u%2FdN75eEvmywc2ulkm7qKRetkU9fbVZtJIqFdMJcJ9Yp%2BJI%2FF%2FpESafFR6rB2fRjiQQLGXvxmDGVMjPSxHxVtIqpZy5FDoKUSjQ2%2FILDKpu3%2F%2BtAtm2jRw1rUoMhgt0%3D
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("apiname=");
stringBuilder.append("com.alipay.account.auth");
stringBuilder.append("&app_id=");
stringBuilder.append(SystemConfig.ALIPAY_APPID);
stringBuilder.append("&app_name=");
stringBuilder.append("mc");
stringBuilder.append("&auth_type=AUTHACCOUNT");
stringBuilder.append("&biz_type=openservice");
stringBuilder.append("&method=alipay.open.auth.sdk.code.get");
stringBuilder.append("&pid=");
stringBuilder.append(SystemConfig.ALIPAY_PID);
stringBuilder.append("&product_id=APP_FAST_LOGIN");
stringBuilder.append("&scope=kuaijie");
stringBuilder.append("&sign_type=RSA2");
stringBuilder.append("&target_id=");
stringBuilder.append(UUIDUtils.generateShortUuid());
String sign = SignUtils.sign(stringBuilder.toString(), SystemConfig.ALIPAY_PRIVATE_KEY, true);
stringBuilder.append("&sign=");
stringBuilder.append(sign);
return stringBuilder.toString();
}
public String alipayUserAuth() throws AlipayApiException {
AlipayClient alipayClient = getAlipayClient();
AlipayUserInfoAuthRequest request = new AlipayUserInfoAuthRequest();
request.setBizContent("{" +
" \"scopes\":[" +
" \"auth_base\"" +
" ]," +
"\"state\":\"init\"," +
"\"is_mobile\":\"true\"" +
" }");
AlipayUserInfoAuthResponse response = alipayClient.execute(request);
log.info("解冻预授权response: {}" + response.getBody());
log.info(response.toString());
if (response.isSuccess()) {
log.info("用户授权调用成功");
} else {
log.info("用户授权调用失败");
}
return response.getBody();
}
//解冻预授权
public boolean fundAuthOrderUnFreeze(String outTradeNo, String serialNumber, Integer refundAmount, String refundReason) throws AlipayApiException {
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayClient alipayClient = getAlipayClient();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();
AlipayFundAuthOrderUnfreezeModel model = new AlipayFundAuthOrderUnfreezeModel();
model.setAuthNo(serialNumber); // 支付宝资金授权订单号,在授权冻结成功时返回需要入库保存
model.setOutRequestNo(outTradeNo);//同一商户每次不同的资金操作请求,商户请求流水号不能重复,且与冻结流水号不同
model.setAmount(realAmount.toString()); // 本次操作解冻的金额,单位为:元(人民币),精确到小数点后两位
model.setRemark(refundReason); // 商户对本次解冻操作的附言描述,长度不超过100个字母或50个汉字
//选填字段,信用授权订单,针对信用全免订单,传入该值完结信用订单,形成芝麻履约记录
// model.setExtraParam("{\"unfreezeBizInfo\":\"{\\\"bizComplete\\\":\\\"true\\\"}\"}");
request.setBizModel(model);
// request.setNotifyUrl(notifyUrl);//异步通知地址,必填,该接口只通过该参数进行异步通知
AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);
log.info("解冻预授权response: {}" + response.getBody());
if (response.isSuccess()) {
log.info("解冻预授权调用成功");
return true;
} else {
log.info("解冻预授权调用失败");
return false;
}
}
//取消预授权
public String fundAuthCancel(String outTradeNo, String serialNumber, String refundReason) throws AlipayApiException {
AlipayClient alipayClient = getAlipayClient();
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayFundAuthOperationCancelRequest request = new AlipayFundAuthOperationCancelRequest();
AlipayFundAuthOperationCancelModel model = new AlipayFundAuthOperationCancelModel();
model.setAuthNo(outTradeNo); // 支付宝资金授权订单号,在授权冻结成功时返回参数中获得
//model.setOutOrderNo(orderPayVo.getOrderNo()); //商户的授权资金订单号,与支付宝的授权资金订单号不能同时为空
//model.setOperationId("20171201317348823902"); //支付宝的授权资金操作流水号
model.setOutRequestNo(serialNumber);//与支付宝的授权资金操作流水号不能同时为空,与冻结流水号相同
model.setRemark(refundReason); // 商户对本次撤销操作的附言描述,长度不超过100个字母或50个汉字
request.setBizModel(model);
AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);
log.info("解冻预授权response: {}" + response.getBody());
if (response.isSuccess()) {
log.info("解冻预授权调用成功");
return true;
} else {
log.info("解冻预授权调用失败");
return false;
}
}
//取消预授权
public String fundAuthCancel(String outTradeNo, String serialNumber, String refundReason) throws AlipayApiException {
AlipayClient alipayClient = getAlipayClient();
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayFundAuthOperationCancelRequest request = new AlipayFundAuthOperationCancelRequest();
AlipayFundAuthOperationCancelModel model = new AlipayFundAuthOperationCancelModel();
model.setAuthNo(outTradeNo); // 支付宝资金授权订单号,在授权冻结成功时返回参数中获得
//model.setOutOrderNo(orderPayVo.getOrderNo()); //商户的授权资金订单号,与支付宝的授权资金订单号不能同时为空
//model.setOperationId("20171201317348823902"); //支付宝的授权资金操作流水号
model.setOutRequestNo(serialNumber);//与支付宝的授权资金操作流水号不能同时为空,与冻结流水号相同
model.setRemark(refundReason); // 商户对本次撤销操作的附言描述,长度不超过100个字母或50个汉字
request.setBizModel(model);
// request.setNotifyUrl(notifyUrl);//异步通知地址,必填,该接口只通过该参数进行异步通知
AlipayFundAuthOperationCancelResponse response = alipayClient.execute(request);
log.info("取消预授权response: {}" + response.getBody());
if (response.isSuccess()) {
log.info("取消预授权调用成功");
return response.getBody();
} else {
log.info("取消预授权调用失败");
return null;
}
}
//预授权转支付
public boolean tradePay(String outTradeNo, String serialNumber, Integer refundAmount, String refundReason, String subject) throws AlipayApiException {
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayClient alipayClient = getAlipayClient();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayTradePayRequest request = new AlipayTradePayRequest();
AlipayTradePayModel model = new AlipayTradePayModel();
model.setOutTradeNo(outTradeNo); // 预授权转支付商户订单号,为新的商户交易流水号;如果重试发起扣款,商户订单号不要变;
model.setProductCode("PRE_AUTH_ONLINE"); // 固定值PRE_AUTH_ONLINE
model.setAuthNo(serialNumber); // 填写预授权冻结交易号
if (StringUtils.isNotBlank(subject)) {
model.setSubject(subject); // 解冻转支付标题,用于展示在支付宝账单中
} else {
model.setSubject("订单费用");
}
model.setTotalAmount(realAmount.toString()); // 结算支付金额
model.setSellerId(SystemConfig.ALIPAY_PID); // 填写卖家支付宝账户pid
model.setBuyerId(SystemConfig.ALIPAY_APPID); // 填写预授权用户uid,通过预授权冻结接口返回的payer_user_id字段获取
if (StringUtils.isNotBlank(refundReason)) {
model.setBody(refundReason); // 可填写备注信息
} else {
model.setBody("订单费用");
}
//如果需要从一笔授权中完成多笔订单支付,保持auth_no不变,不同订单根据outTradeNo进行标识,此时auth_confirm_mode不传或者传入NOT_COMPLETE;进行到最后一笔转支付时,auth_confirm_mode传入COMPLETE由支付宝完成剩余金额自动解冻,或者商户自行调用解冻接口将剩余金额解冻。
model.setAuthConfirmMode("NOT_COMPLETE");//传入该值用户剩余金额不会自动解冻
request.setBizModel(model);
AlipayFundAuthOperationCancelResponse response = alipayClient.execute(request);
log.info("取消预授权response: {}" + response.getBody());
if (response.isSuccess()) {
log.info("取消预授权调用成功");
return response.getBody();
} else {
log.info("取消预授权调用失败");
return null;
}
}
//预授权转支付
public boolean tradePay(String outTradeNo, String serialNumber, Integer refundAmount, String refundReason, String subject) throws AlipayApiException {
String notifyUrl = weixinHost + "/api/universal/pay/app/unauth/notify/alipay";
AlipayClient alipayClient = getAlipayClient();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
AlipayTradePayRequest request = new AlipayTradePayRequest();
AlipayTradePayModel model = new AlipayTradePayModel();
model.setOutTradeNo(outTradeNo); // 预授权转支付商户订单号,为新的商户交易流水号;如果重试发起扣款,商户订单号不要变;
model.setProductCode("PRE_AUTH_ONLINE"); // 固定值PRE_AUTH_ONLINE
model.setAuthNo(serialNumber); // 填写预授权冻结交易号
if (StringUtils.isNotBlank(subject)) {
model.setSubject(subject); // 解冻转支付标题,用于展示在支付宝账单中
} else {
model.setSubject("订单费用");
}
model.setTotalAmount(realAmount.toString()); // 结算支付金额
model.setSellerId(SystemConfig.ALIPAY_PID); // 填写卖家支付宝账户pid
model.setBuyerId(SystemConfig.ALIPAY_APPID); // 填写预授权用户uid,通过预授权冻结接口返回的payer_user_id字段获取
if (StringUtils.isNotBlank(refundReason)) {
model.setBody(refundReason); // 可填写备注信息
} else {
model.setBody("订单费用");
}
//如果需要从一笔授权中完成多笔订单支付,保持auth_no不变,不同订单根据outTradeNo进行标识,此时auth_confirm_mode不传或者传入NOT_COMPLETE;进行到最后一笔转支付时,auth_confirm_mode传入COMPLETE由支付宝完成剩余金额自动解冻,或者商户自行调用解冻接口将剩余金额解冻。
model.setAuthConfirmMode("NOT_COMPLETE");//传入该值用户剩余金额不会自动解冻
request.setBizModel(model);
// request.setNotifyUrl(notifyUrl);//异步通知地址,必填,该接口只通过该参数进行异步通知
AlipayTradePayResponse response = alipayClient.execute(request);
log.info("预授权转支付response: {}" + response.getBody());
if (response.isSuccess()) {
return true;
} else {
log.info("预授权转支付调用失败");
return false;
}
}
/**
* APP支付退款
*
* @param
* @param outTradeNo 订单号
* @param tradNo 流水号
* @param refundAmount 退款金额
* @param refundReason 退款原因
* outRequestNo 退款请求标示 用于分批退款,每笔退款标示不一样,同样标示不会重复退款
* @return
*/
public boolean alipayOrderRefund(String outTradeNo, String tradNo, Integer refundAmount, String
refundReason, String outRequestNo) {
AlipayClient alipayClient = getAlipayClient();
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
request.setBizContent("{" +
"\"out_trade_no\":\"" + outTradeNo + "\"," +
"\"trade_no\":\"" + tradNo + "\"," +
"\"refund_amount\":" + realAmount + "," +
"\"refund_reason\":\"" + refundReason + "\"," +
"\"out_request_no\":\"" + outRequestNo + "\"" +
" }");
try {
log.info("支付宝退款中:outTradeNo = {}, tradNo = {}, refundAmount = {}, refundReason = {}", outTradeNo, tradNo, refundAmount, refundReason);
AlipayTradeRefundResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
return true;
} else {
log.info(response.getBody());
return false;
}
} catch (Exception e) {
log.error(e.getMessage(), e);;
log.info("退款失败请重试");
}
return false;
}
/**
* 查询预授权订单
* @param tradNo
* @throws AlipayApiException
*/
public ObjectRestResponse fundAuthQuery(String tradNo){
AlipayClient alipayClient = getAlipayClient();
AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
//model.setAuthNo("2017120110002001390206804295"); // 支付宝资金授权订单号,在授权冻结成功时返回参数中获得
model.setOutOrderNo(tradNo); //商户的授权资金订单号,与支付宝的授权资金订单号不能同时为空
//model.setOperationId("20171201317348823902"); //支付宝的授权资金操作流水号,冻结成功同步返回
model.setOutRequestNo(tradNo);//商户的授权资金操作流水号,与支付宝的授权资金操作流水号不能同时为空,该值为冻结或解冻是的outRequestNo
request.setBizModel(model);
AlipayFundAuthOperationDetailQueryResponse response = null;
try {
response = alipayClient.execute(request);
log.info("response: {}"+response.getBody());
} catch (AlipayApiException e) {
e.printStackTrace();
}
return ObjectRestResponse.succ(response.getBody());
}
/**
* 预授权转支付退款
* @param tradNo 预授权转支付商户订单号
* @param refundAmount 退款金额
* @param refundReason 退款原因
* @param outRequestNo 退款标志号
*/
public AlipayTradeRefundResponse testTradeRefund(String tradNo, Integer refundAmount, String refundReason, String outRequestNo) {
AlipayClient alipayClient = getAlipayClient();
AlipayTradeRefundModel model = new AlipayTradeRefundModel();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
model.setOutTradeNo(tradNo); //与预授权转支付商户订单号相同,代表对该笔交易退款
model.setRefundAmount(realAmount.toString());
model.setRefundReason(refundReason);
model.setOutRequestNo(outRequestNo);//标识一次退款请求,同一笔交易多次退款需要保证唯一,如部分退款则此参数必传。
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
request.setBizModel(model);
AlipayTradeRefundResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
e.printStackTrace();
}
log.info("response: {}"+response.getBody());
return response;
}
public static void main(String[] args) throws AlipayApiException {
OrderPayBiz orderPayBiz = new OrderPayBiz();
OrderPayVo orderPayVo = new OrderPayVo();
orderPayVo.setOrderNo("20191024153859000003");
orderPayVo.setTradeNo("2019102410002001530572359246");
orderPayVo.setSerialNumber("2019102410002001530572351411");
orderPayVo.setAmount(3);
orderPayVo.setBody("扣除租车订单费用");
orderPayVo.setSubject("租车订单交易费用");
//orderPayBiz.testTradeRefund("222522054304468992", 180000, "退还违约金1800元", "222522054304461800");
//orderPayBiz.fundAuthOrderUnFreeze(orderPayVo, "");
//orderPayBiz.alipayOrderRefund("20191024153859000003","2019102422001421530513773694", 2, "xxxx", "");
//orderPayBiz.tradePay(orderPayVo, "");
//orderPayBiz.fundAuthCancel(orderPayVo, "");
//orderPayBiz.tradePay("20191114182254000019", "2019111410002001530505959461", 1,"扣除违约金", "扣除违约金");
//orderPayBiz.fundAuthQuery("20191031172653000026");
}
AlipayTradePayResponse response = alipayClient.execute(request);
log.info("预授权转支付response: {}" + response.getBody());
if (response.isSuccess()) {
return true;
} else {
log.info("预授权转支付调用失败");
return false;
}
}
/**
* APP支付退款
*
* @param
* @param outTradeNo 订单号
* @param tradNo 流水号
* @param refundAmount 退款金额
* @param refundReason 退款原因
* outRequestNo 退款请求标示 用于分批退款,每笔退款标示不一样,同样标示不会重复退款
* @return
*/
public boolean alipayOrderRefund(String outTradeNo, String tradNo, Integer refundAmount, String
refundReason, String outRequestNo) {
AlipayClient alipayClient = getAlipayClient();
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
request.setBizContent("{" +
"\"out_trade_no\":\"" + outTradeNo + "\"," +
"\"trade_no\":\"" + tradNo + "\"," +
"\"refund_amount\":" + realAmount + "," +
"\"refund_reason\":\"" + refundReason + "\"," +
"\"out_request_no\":\"" + outRequestNo + "\"" +
" }");
try {
log.info("支付宝退款中:outTradeNo = {}, tradNo = {}, refundAmount = {}, refundReason = {}", outTradeNo, tradNo, refundAmount, refundReason);
AlipayTradeRefundResponse response = alipayClient.execute(request);
if (response.isSuccess()) {
return true;
} else {
log.info(response.getBody());
return false;
}
} catch (Exception e) {
log.error(e.getMessage(), e);
;
log.info("退款失败请重试");
}
return false;
}
/**
* 查询预授权订单
*
* @param tradNo
* @throws AlipayApiException
*/
public ObjectRestResponse fundAuthQuery(String tradNo) {
AlipayClient alipayClient = getAlipayClient();
AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
AlipayFundAuthOperationDetailQueryModel model = new AlipayFundAuthOperationDetailQueryModel();
//model.setAuthNo("2017120110002001390206804295"); // 支付宝资金授权订单号,在授权冻结成功时返回参数中获得
model.setOutOrderNo(tradNo); //商户的授权资金订单号,与支付宝的授权资金订单号不能同时为空
//model.setOperationId("20171201317348823902"); //支付宝的授权资金操作流水号,冻结成功同步返回
model.setOutRequestNo(tradNo);//商户的授权资金操作流水号,与支付宝的授权资金操作流水号不能同时为空,该值为冻结或解冻是的outRequestNo
request.setBizModel(model);
AlipayFundAuthOperationDetailQueryResponse response = null;
try {
response = alipayClient.execute(request);
log.info("response: {}" + response.getBody());
} catch (AlipayApiException e) {
e.printStackTrace();
}
return ObjectRestResponse.succ(response.getBody());
}
/**
* 预授权转支付退款
*
* @param tradNo 预授权转支付商户订单号
* @param refundAmount 退款金额
* @param refundReason 退款原因
* @param outRequestNo 退款标志号
*/
public AlipayTradeRefundResponse testTradeRefund(String tradNo, Integer refundAmount, String refundReason, String outRequestNo) {
AlipayClient alipayClient = getAlipayClient();
AlipayTradeRefundModel model = new AlipayTradeRefundModel();
BigDecimal realAmount = new BigDecimal(refundAmount.toString()).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_UP);
model.setOutTradeNo(tradNo); //与预授权转支付商户订单号相同,代表对该笔交易退款
model.setRefundAmount(realAmount.toString());
model.setRefundReason(refundReason);
model.setOutRequestNo(outRequestNo);//标识一次退款请求,同一笔交易多次退款需要保证唯一,如部分退款则此参数必传。
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
request.setBizModel(model);
AlipayTradeRefundResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
e.printStackTrace();
}
log.info("response: {}" + response.getBody());
return response;
}
public static void main(String[] args) throws AlipayApiException {
OrderPayBiz orderPayBiz = new OrderPayBiz();
OrderPayVo orderPayVo = new OrderPayVo();
orderPayVo.setOrderNo("20191024153859000003");
orderPayVo.setTradeNo("2019102410002001530572359246");
orderPayVo.setSerialNumber("2019102410002001530572351411");
orderPayVo.setAmount(3);
orderPayVo.setBody("扣除租车订单费用");
orderPayVo.setSubject("租车订单交易费用");
//orderPayBiz.testTradeRefund("222522054304468992", 180000, "退还违约金1800元", "222522054304461800");
//orderPayBiz.fundAuthOrderUnFreeze(orderPayVo, "");
//orderPayBiz.alipayOrderRefund("20191024153859000003","2019102422001421530513773694", 2, "xxxx", "");
//orderPayBiz.tradePay(orderPayVo, "");
//orderPayBiz.fundAuthCancel(orderPayVo, "");
//orderPayBiz.tradePay("20191114182254000019", "2019111410002001530505959461", 1,"扣除违约金", "扣除违约金");
//orderPayBiz.fundAuthQuery("20191031172653000026");
}
}
package com.upyuns.platform.rs.website.dto;
import lombok.Data;
/**
* @ClassName : CartOrderDto
* @Description : 购物车订单参数
* @Author : jiaoruizhen
* @Date: 2020-12-04 11:02
*/
@Data
public class CartOrderDto {
String ids;
//收货地址信息
String address;
//收货人姓名
String name;
//收货电话
String phone;
//配送方式:1、线上配送,2、快递配送
Integer sendType;
}
package com.upyuns.platform.rs.website.dto;
import lombok.Data;
import java.util.List;
/**
* @ClassName : ConfirmOrderDto
* @Description : 确认订单
* @Author : jiaoruizhen
* @Date: 2020-12-16 14:51
*/
@Data
public class ConfirmOrderDto {
List<ItemInfoDto> itemInfoDtoList;
}
package com.upyuns.platform.rs.website.dto;
import lombok.Data;
/**
* @ClassName : itemInfoDto
* @Description : 商品信息
* @Author : jiaoruizhen
* @Date: 2020-12-16 16:56
*/
@Data
public class ItemInfoDto {
Integer id;
Integer number;
/**
* 类型: 1、标准数据,2、影像图库,3、行业应用信息, 4、购物车确认订单
*/
private Integer type;
}
package com.upyuns.platform.rs.website.dto;
import com.github.wxiaoqi.security.common.vo.PageParam;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* @ClassName : OrderInfoDto
* @Description : 添加订单信息
* @Author : jiaoruizhen
* @Date: 2020-12-12 17:09
*/
@Data
public class OrderInfoDto extends PageParam {
/**
* 订单备注
*/
@ApiModelProperty(value = "订单备注")
private String remark;
/**
* 配送方式:1、线上配送,2、快递配送
*/
@ApiModelProperty(value = "配送方式:1、线上配送,2、快递配送")
private Integer sendType;
/**
* 地址ID
*/
private Integer userAddressId;
/**
* 发票ID
*/
private Integer userInvoiceId;
/**
* 商品信息ID
*/
private List<ItemInfoDto> itemInfoDtoList;
//详情ID
Integer detailId;
//1、标准数据,2、影像图库,3、行业应用信息
Integer type;
//数量
Integer number;
//单价
BigDecimal price;
//文件地址
String filePath;
}
......@@ -89,6 +89,9 @@ public class CommonInfo implements Serializable {
@Column(name = "rank")
@ApiModelProperty(value = "排序")
private Integer rank;
/**
* 图标
*/
private String icon;
}
......@@ -166,6 +166,26 @@ public class CustomForm implements Serializable {
@Column(name = "is_del")
@ApiModelProperty(value = "是否删除:0、否, 1、是")
private Integer isDel;
/**
* 省名称
*/
@Column(name = "province_name")
@ApiModelProperty(value = "省名称")
private String provinceName;
/**
* 市名称
*/
@Column(name = "city_name")
@ApiModelProperty(value = "市名称")
private String cityName;
/**
* 区名称
*/
@Column(name = "area_name")
@ApiModelProperty(value = "区名称")
private String areaName;
}
package com.upyuns.platform.rs.website.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
......@@ -143,6 +144,11 @@ public class IndustryApplicationInfo implements Serializable {
*/
private Integer customized;
/**
* 价格信息
*/
private BigDecimal price;
@Transient
private String firstTitle;
......
......@@ -177,7 +177,7 @@ public class OrderInfo implements Serializable {
*
*/
@Column(name = "type")
@ApiModelProperty(value = "")
@ApiModelProperty(value = "1、普通订单,2、定制订单")
private Integer type;
......
......@@ -147,4 +147,18 @@ public class ShoppingCartInfo implements Serializable {
@ApiModelProperty(value = "")
private BigDecimal totalAmount;
public static OrderItem convertToOrderItem(ShoppingCartInfo shoppingCartInfo) {
OrderItem orderItem = new OrderItem();
orderItem.setDetailId(shoppingCartInfo.getDetailId());
orderItem.setDetailJson(shoppingCartInfo.getDetailJson());
orderItem.setFilePath(shoppingCartInfo.getFilePath());
orderItem.setItemPic(shoppingCartInfo.getItemPic());
orderItem.setName(shoppingCartInfo.getName());
orderItem.setNumber(shoppingCartInfo.getNumber());
orderItem.setPrice(shoppingCartInfo.getPrice());
orderItem.setTotalAmount(shoppingCartInfo.getTotalAmount());
orderItem.setType(shoppingCartInfo.getType());
return orderItem;
}
}
......@@ -24,7 +24,7 @@ public class UserAddress implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty("订单收获地址id")
private Long id;
private Integer id;
/**
* 收获人姓名
......@@ -92,10 +92,21 @@ public class UserAddress implements Serializable {
@Column(name = "user_id")
@ApiModelProperty(value = "用户ID")
private Long userId;
private Integer userId;
/**
* 是否删除: 0、否,1、是
*/
private Integer isDel;
/**
* 是否是默认值: 0、否,1、是
*/
private Integer isDefault;
/**
* 标签
*/
private String label;
}
......@@ -113,4 +113,36 @@ public class UserInvoice implements Serializable {
private Integer isDel;
/**
* 发票类型: 1、普通发票,2、专票
*/
private Integer type;
/**
* 是否是默认值: 0、否,1、是
*/
private Integer isDefault;
/**
* 省份
*/
@Column(name = "province")
@ApiModelProperty(value = "省份")
private String province;
/**
* 市
*/
@Column(name = "city")
@ApiModelProperty(value = "市")
private String city;
/**
* 乡镇/街道
*/
@Column(name = "town")
@ApiModelProperty(value = "乡镇/街道")
private String town;
}
package com.upyuns.platform.rs.website.type;
/**
* @ClassName : OrderTypeEnum
* @Description : 订单类型
* @Author : jiaoruizhen
* @Date: 2020-12-12 16:50
*/
public enum OrderTypeEnum {
STANDARD_DATA(1, "标准数据"),
INDUSTRY_INFO(3, "行业应用"),
IMAGE_STORAGE(2, "影像图库"),
SHOPPING_CART_INFO(4, "购物车下单");
private Integer type;
private String msg;
OrderTypeEnum(Integer type, String msg) {
this.type = type;
this.msg = msg;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static <T extends OrderTypeEnum> String getType(Integer code, Class<T> t) {
for (T item : t.getEnumConstants()) {
if (item.getType().equals(code)) {
return item.getMsg();
}
}
return "";
}
public static OrderTypeEnum getByCode(Integer code) {
for (OrderTypeEnum v : values()) {
if (v.getType() == code) {
return v;
}
}
return null;
}
public static String getProductStatusEnum(Integer code) {
return getType(code, OrderTypeEnum.class);
}
}
package com.upyuns.platform.rs.website.vo;
import com.upyuns.platform.rs.website.entity.*;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* @ClassName : ConfirmOrderInfoVo
* @Description : 确认订单
* @Author : jiaoruizhen
* @Date: 2020-12-16 14:57
*/
@Data
public class ConfirmOrderInfoVo {
/**
* 配送方式:1、线上配送,2、快递配送
*/
private Integer sendType;
/**
* 用户地址列表
*/
private List<UserAddress> userAddressList;
/**
* 用户发票列表
*/
private List<UserInvoice> userInvoiceList;
/**
* 订单商品数量
*/
private Integer number;
/**
* 总金额
*/
private BigDecimal totalAmount;
/**
* 实付金额
*/
private BigDecimal actAmount;
/**
* 运费
*/
private BigDecimal fee;
private List<ItemInfoVo> itemInfoVoList;
}
package com.upyuns.platform.rs.website.vo;
import lombok.Data;
import java.math.BigDecimal;
/**
* @ClassName : ItemInfoVo
* @Description : 商品信息
* @Author : jiaoruizhen
* @Date: 2020-12-16 16:59
*/
@Data
public class ItemInfoVo {
private Integer id;
private String detailJson;
private Integer number;
private BigDecimal price;
private Integer type;
private String img;
}
......@@ -24,6 +24,13 @@
<version>2.0-rscp-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.upyuns.platform.rs</groupId>
<artifactId>rs-datacenter-api</artifactId>
<version>2.0-rscp-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
......
......@@ -56,6 +56,7 @@ public class CommonInfoBiz extends BaseBiz<CommonInfoMapper,CommonInfo> {
public List<CommonInfo> getByType(Integer type) {
Example example = new Example(CommonInfo.class);
example.createCriteria().andEqualTo("type", type).andEqualTo("isDel", 0);
example.orderBy("rank");
return mapper.selectByExample(example);
}
......
......@@ -17,7 +17,9 @@ import com.upyuns.platform.rs.website.mapper.ImageImgStorageMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* 影像图库
......@@ -118,7 +120,7 @@ public class ImageImgStorageBiz extends BaseBiz<ImageImgStorageMapper,ImageImgSt
* @param id
* @return
*/
public ObjectRestResponse getDetail(Integer id) {
public ObjectRestResponse<ImageImgStorage> getDetail(Integer id) {
if (id == null) {
return ObjectRestResponse.paramIsEmpty();
}
......@@ -147,4 +149,14 @@ public class ImageImgStorageBiz extends BaseBiz<ImageImgStorageMapper,ImageImgSt
return ObjectRestResponse.succ(mapper.selectByExample(example));
}
/**
* 根据ID List 获取所有图库信息
* @param idList
* @return
*/
public List<ImageImgStorage> getAllByIds(Set<Integer> idList) {
Example example = new Example(ImageImgStorage.class);
example.createCriteria().andIn("id", idList);
return mapper.selectByExample(example);
}
}
\ No newline at end of file
......@@ -21,6 +21,7 @@ import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
......@@ -109,4 +110,16 @@ public class IndustryApplicationInfoBiz extends BaseBiz<IndustryApplicationInfoM
}
return ObjectRestResponse.succ(list);
}
/**
* 根据ID List获取行业应用信息
* @param idList
* @return
*/
public List<IndustryApplicationInfo> getAllByIds(Set<Integer> idList) {
Example example = new Example(IndustryApplicationInfo.class);
example.createCriteria().andIn("id", idList);
return mapper.selectByExample(example);
}
}
\ No newline at end of file
......@@ -2,23 +2,35 @@ package com.upyuns.platform.rs.website.biz;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.upyuns.platform.rs.universal.constant.DictionaryKey;
import com.upyuns.platform.rs.universal.entity.Dictionary;
import com.upyuns.platform.rs.universal.feign.ThirdFeign;
import com.upyuns.platform.rs.website.dto.ItemInfoDto;
import com.upyuns.platform.rs.website.dto.OrderInfoDto;
import com.upyuns.platform.rs.website.dto.UserOrderDto;
import com.upyuns.platform.rs.website.entity.OrderItem;
import com.upyuns.platform.rs.website.entity.ShoppingCartInfo;
import com.upyuns.platform.rs.website.entity.*;
import com.upyuns.platform.rs.website.mapper.OrderItemMapper;
import com.upyuns.platform.rs.website.type.OrderTypeEnum;
import com.upyuns.platform.rs.website.vo.ItemInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.upyuns.platform.rs.website.entity.OrderInfo;
import com.upyuns.platform.rs.website.mapper.OrderInfoMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* 订单信息
......@@ -31,7 +43,36 @@ import java.util.List;
public class OrderInfoBiz extends BaseBiz<OrderInfoMapper, OrderInfo> {
@Autowired
OrderItemMapper orderItemMapper;
OrderItemBiz orderItemBiz;
@Autowired
IndustryApplicationInfoBiz industryApplicationInfoBiz;
@Autowired
ImageImgStorageBiz imageImgStorageBiz;
@Autowired
ShoppingCartInfoBiz shoppingCartInfoBiz;
@Autowired
ImageInfoRelationBiz imageInfoRelationBiz;
@Autowired
ThirdFeign thirdFeign;
@Autowired
UserFeign userFeign;
@Autowired
HttpServletRequest request;
@Autowired
UserAddressBiz userAddressBiz;
@Autowired
OrderEInvoiceBiz orderEInvoiceBiz;
@Autowired
UserInvoiceBiz userInvoiceBiz;
/**
* 添加订单
......@@ -79,7 +120,7 @@ public class OrderInfoBiz extends BaseBiz<OrderInfoMapper, OrderInfo> {
*/
public OrderInfo getOneByOrderNo(String orderNo) {
Example example = new Example(OrderInfo.class);
example.createCriteria().andEqualTo("orderNo", orderNo).andNotEqualTo("status", -1).andEqualTo("status", -2);
example.createCriteria().andEqualTo("orderNo", orderNo).andNotEqualTo("status", -1).andNotEqualTo("status", -2);
return mapper.selectOneByExample(example);
}
......@@ -105,16 +146,168 @@ public class OrderInfoBiz extends BaseBiz<OrderInfoMapper, OrderInfo> {
if (StringUtils.isNotBlank(userOrderDto.getName())) {
orderItemCriteria.andLike("name", "%"+ userOrderDto.getName() +"%");
}
orderInfoCriteria.andNotEqualTo("status", -1);
example.orderBy("updTime").desc();
List<OrderInfo> orderInfoList = mapper.selectByExample(example);
if (orderInfoList != null) {
}
return new ArrayList<>();
}
/**
* 提交订单
* @param orderInfoDto
* @return
*/
public ObjectRestResponse submitOrder(OrderInfoDto orderInfoDto) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (orderInfoDto == null || orderInfoDto.getItemInfoDtoList() == null) {
return ObjectRestResponse.paramIsEmpty();
}
List<ItemInfoDto> itemInfoDtoList = orderInfoDto.getItemInfoDtoList();
List<OrderItem> orderItemList = new ArrayList<>();
AtomicReference<Integer> number = new AtomicReference<>(0);
AtomicReference<Double> amount = new AtomicReference<>((double) 0);
itemInfoDtoList.parallelStream().forEach(itemInfoDto -> {
switch (OrderTypeEnum.getByCode(itemInfoDto.getType())) {
//标准数据
case STANDARD_DATA:
break;
//行业应用
case INDUSTRY_INFO:
IndustryApplicationInfo industryApplicationInfo = industryApplicationInfoBiz.getOneById(itemInfoDto.getId()).getData();
if (industryApplicationInfo != null) {
OrderItem orderItem = new OrderItem();
orderItem.setType(itemInfoDto.getType());
orderItem.setTotalAmount(industryApplicationInfo.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber())));
orderItem.setPrice(industryApplicationInfo.getPrice());
orderItem.setNumber(itemInfoDto.getNumber());
orderItem.setName(industryApplicationInfo.getTitle());
orderItem.setItemPic(industryApplicationInfo.getCoverImg());
orderItem.setDetailJson(JSONObject.toJSONString(industryApplicationInfo));
orderItem.setDetailId(industryApplicationInfo.getId());
orderItemList.add(orderItem);
//总数量
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = industryApplicationInfo.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber()));
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
break;
//影像图库
case IMAGE_STORAGE:
ImageInfoRelation imageInfoRelation = imageInfoRelationBiz.selectById(itemInfoDto.getId());
if (imageInfoRelation != null ) {
ImageImgStorage imageImgStorage = imageImgStorageBiz.getDetail(itemInfoDto.getId()).getData();
if (imageImgStorage != null) {
List<ImageInfoRelation> imageInfoRelationList = new ArrayList<>();
imageInfoRelationList.add(imageInfoRelation);
imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
OrderItem orderItem = new OrderItem();
orderItem.setType(itemInfoDto.getType());
orderItem.setTotalAmount(imageInfoRelation.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber())));
orderItem.setPrice(imageInfoRelation.getPrice());
orderItem.setNumber(itemInfoDto.getNumber());
orderItem.setName(imageImgStorage.getName());
orderItem.setItemPic(imageImgStorage.getCoverImg());
orderItem.setDetailJson(JSONObject.toJSONString(imageImgStorage));
orderItem.setDetailId(imageImgStorage.getId());
orderItemList.add(orderItem);
//总数量
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = imageInfoRelation.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber()));
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
}
break;
//购物车
case SHOPPING_CART_INFO:
ShoppingCartInfo shoppingCartInfo = shoppingCartInfoBiz.selectById(itemInfoDto.getId());
if (shoppingCartInfo != null) {
OrderItem orderItem = new OrderItem();
orderItem.setType(itemInfoDto.getType());
orderItem.setTotalAmount(shoppingCartInfo.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber())));
orderItem.setPrice(shoppingCartInfo.getPrice());
orderItem.setNumber(itemInfoDto.getNumber());
orderItem.setName(shoppingCartInfo.getName());
orderItem.setItemPic(shoppingCartInfo.getItemPic());
orderItem.setDetailJson(shoppingCartInfo.getDetailJson());
orderItem.setDetailId(shoppingCartInfo.getDetailId());
orderItemList.add(orderItem);
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = shoppingCartInfo.getTotalAmount();
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
break;
default:
break;
}
});
OrderInfo orderInfo = new OrderInfo();
orderInfo.setRealName(appUserDTO.getRealname());
orderInfo.setUserId(appUserDTO.getUserid());
orderInfo.setPhone(appUserDTO.getUsername());
orderInfo.setNickname(appUserDTO.getNickname());
orderInfo.setHeadImg(appUserDTO.getHeadimgurl());
if (orderInfoDto.getUserAddressId() != null) {
UserAddress userAddress = userAddressBiz.selectById(orderInfoDto.getUserAddressId());
if (userAddress != null) {
orderInfo.setReceiveName(userAddress.getConsigneeName());
orderInfo.setReceivePhone(userAddress.getConsigneePhone());
orderInfo.setReceiveAddress(userAddress.getProvince() + userAddress.getCity() + userAddress.getTown() + userAddress.getConsigneeAddress());
}
}
orderInfo.setRemark(orderInfoDto.getRemark());
orderInfo.setAmount(new BigDecimal(amount.get()));
Dictionary dictionary = thirdFeign.findDictionaryByTypeAndCode(DictionaryKey.APP_ORDER, DictionaryKey.SEND_FEE);
if (dictionary != null && StringUtils.isNotBlank(dictionary.getDetail())) {
orderInfo.setFee(new BigDecimal(dictionary.getDetail()));
}
if (orderInfo.getFee() != null) {
orderInfo.setTotalAmount(orderInfo.getAmount().add(orderInfo.getFee()));
}
orderInfo.setSendType(orderInfoDto.getSendType());
orderInfo.setType(1);
/**
* 新增订单
*/
orderInfo.setOrderNo(OrderUtil.GetOrderNumber("", OrderUtil.APP_MID));
generateOrder(orderInfo);
orderItemList.parallelStream().forEach(orderItem -> {
if (orderItem != null) {
orderItem.setOrderId(orderInfo.getOrderId());
orderItemBiz.insertSelective(orderItem);
}
});
//订单发票信息
if (orderInfoDto.getUserInvoiceId() != null) {
UserInvoice userInvoice = userInvoiceBiz.selectById(orderInfoDto.getUserInvoiceId());
if (userInvoice != null) {
OrderEInvoice orderEInvoice = new OrderEInvoice();
orderEInvoice.setAmount(orderInfo.getAmount());
orderEInvoice.setType(1);
orderEInvoice.setOrderIds(orderInfo.getOrderId() + "");
orderEInvoice.setTitleType(userInvoice.getTitleType());
orderEInvoice.setTitleName(userInvoice.getTitleName());
orderEInvoice.setTaxCode(userInvoice.getTaxCode());
orderEInvoice.setContentRemark(orderInfoDto.getRemark());
orderEInvoice.setContentAccount(userInvoice.getOpenBank() + " " + userInvoice.getAccount());
orderEInvoice.setContentContact(orderInfo.getReceiveAddress() + " " + orderInfo.getReceiveName() + " " + orderInfo.getReceivePhone());
//发票内容
orderEInvoice.setContentTitle("");
orderEInvoiceBiz.addUpdate(orderEInvoice);
}
}
return ObjectRestResponse.succ();
}
}
\ No newline at end of file
......@@ -15,4 +15,5 @@ import com.github.wxiaoqi.security.common.biz.BaseBiz;
*/
@Service
public class OrderItemBiz extends BaseBiz<OrderItemMapper,OrderItem> {
}
\ No newline at end of file
......@@ -2,24 +2,31 @@ package com.upyuns.platform.rs.website.biz;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.upyuns.platform.rs.website.entity.OrderEInvoice;
import com.upyuns.platform.rs.website.entity.OrderInfo;
import com.upyuns.platform.rs.website.entity.OrderItem;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.website.dto.CartOrderDto;
import com.upyuns.platform.rs.website.dto.OrderInfoDto;
import com.upyuns.platform.rs.website.entity.*;
import com.upyuns.platform.rs.website.type.OrderTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.upyuns.platform.rs.website.entity.ShoppingCartInfo;
import com.upyuns.platform.rs.website.mapper.ShoppingCartInfoMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* 购物车
......@@ -29,7 +36,7 @@ import java.util.List;
* @date 2020-12-03 13:29:23
*/
@Service
public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper,ShoppingCartInfo> {
public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper, ShoppingCartInfo> {
@Autowired
OrderInfoBiz orderInfoBiz;
......@@ -37,8 +44,21 @@ public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper,Shopping
@Autowired
OrderItemBiz orderItemBiz;
@Autowired
IndustryApplicationInfoBiz industryApplicationInfoBiz;
@Autowired
ImageImgStorageBiz imageImgStorageBiz;
@Autowired
UserFeign userFeign;
@Autowired
HttpServletRequest request;
/**
* 添加购物车
*
* @param shoppingCartInfo
* @return
*/
......@@ -58,34 +78,141 @@ public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper,Shopping
/**
* 获取用户所有购物车商品
* @param userId
*
* @param orderInfoDto
* @return
*/
public ObjectRestResponse getUserAllCart(Integer userId) {
public ObjectRestResponse getUserAllCart(OrderInfoDto orderInfoDto) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
Example example = new Example(ShoppingCartInfo.class);
example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0);
example.createCriteria().andEqualTo("userId", appUserDTO.getUserid()).andEqualTo("isDel", 0);
example.orderBy("updTime").desc();
return ObjectRestResponse.succ(mapper.selectByExample(example));
Query query = new Query(orderInfoDto);
PageDataVO<ShoppingCartInfo> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
return ObjectRestResponse.succ(pageDataVO);
}
/**
* 前端用户添加购物车
*
* @param orderInfoDto 商品详情ID
* @return
*/
public ObjectRestResponse addShoppingCart(OrderInfoDto orderInfoDto) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (orderInfoDto.getType() == null || orderInfoDto.getType() == null) {
return ObjectRestResponse.paramIsEmpty();
}
//标准数据
if (OrderTypeEnum.STANDARD_DATA.getType().equals(orderInfoDto.getType())) {
}
//影像图库
if (OrderTypeEnum.IMAGE_STORAGE.getType().equals(orderInfoDto.getType())) {
ImageImgStorage imageImgStorage = imageImgStorageBiz.selectById(orderInfoDto.getDetailId());
if (imageImgStorage != null) {
ShoppingCartInfo old = selectByUser(appUserDTO.getUserid(), imageImgStorage.getId());
if (old != null) {
old.setNumber(old.getNumber() + orderInfoDto.getNumber());
old.setTotalAmount(old.getPrice().multiply(new BigDecimal(old.getNumber())));
updateSelectiveByIdRe(old);
} else {
ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
shoppingCartInfo.setDetailId(imageImgStorage.getId());
shoppingCartInfo.setDetailJson(JSONObject.toJSONString(imageImgStorage));
shoppingCartInfo.setPrice(orderInfoDto.getPrice());
shoppingCartInfo.setFilePath(orderInfoDto.getFilePath());
shoppingCartInfo.setNumber(orderInfoDto.getNumber());
shoppingCartInfo.setItemPic(imageImgStorage.getCoverImg());
shoppingCartInfo.setName(imageImgStorage.getName());
shoppingCartInfo.setTotalAmount(orderInfoDto.getPrice().multiply(new BigDecimal(orderInfoDto.getNumber())));
shoppingCartInfo.setType(orderInfoDto.getType());
//添加用户信息
shoppingCartInfo.setRealName(appUserDTO.getRealname());
shoppingCartInfo.setNickname(appUserDTO.getNickname());
shoppingCartInfo.setHeadImg(appUserDTO.getHeadimgurl());
shoppingCartInfo.setPhone(appUserDTO.getUsername());
shoppingCartInfo.setUserId(appUserDTO.getUserid());
addUpdate(shoppingCartInfo);
}
} else {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
}
//行业应用信息
if (OrderTypeEnum.INDUSTRY_INFO.getType().equals(orderInfoDto.getType())) {
IndustryApplicationInfo industryApplicationInfo = industryApplicationInfoBiz.selectById(orderInfoDto.getDetailId());
if (industryApplicationInfo != null) {
ShoppingCartInfo old = selectByUser(appUserDTO.getUserid(), industryApplicationInfo.getId());
if (old != null) {
old.setNumber(old.getNumber() + orderInfoDto.getNumber());
old.setTotalAmount(old.getPrice().multiply(new BigDecimal(old.getNumber())));
updateSelectiveByIdRe(old);
} else {
ShoppingCartInfo shoppingCartInfo = new ShoppingCartInfo();
shoppingCartInfo.setDetailId(industryApplicationInfo.getId());
shoppingCartInfo.setDetailJson(JSONObject.toJSONString(industryApplicationInfo));
shoppingCartInfo.setPrice(orderInfoDto.getPrice());
shoppingCartInfo.setFilePath(orderInfoDto.getFilePath());
shoppingCartInfo.setNumber(orderInfoDto.getNumber());
shoppingCartInfo.setItemPic(industryApplicationInfo.getCoverImg());
shoppingCartInfo.setName(industryApplicationInfo.getTitle());
shoppingCartInfo.setTotalAmount(orderInfoDto.getPrice().multiply(new BigDecimal(orderInfoDto.getNumber())));
shoppingCartInfo.setType(orderInfoDto.getType());
//添加用户信息
shoppingCartInfo.setRealName(appUserDTO.getRealname());
shoppingCartInfo.setNickname(appUserDTO.getNickname());
shoppingCartInfo.setHeadImg(appUserDTO.getHeadimgurl());
shoppingCartInfo.setPhone(appUserDTO.getUsername());
shoppingCartInfo.setUserId(appUserDTO.getUserid());
addUpdate(shoppingCartInfo);
}
} else {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
}
return ObjectRestResponse.succ();
}
public ShoppingCartInfo selectByUser(Integer userId, Integer detailId) {
Example example = new Example(ShoppingCartInfo.class);
example.createCriteria().andEqualTo("detailId", detailId).andEqualTo("userId", userId);
return mapper.selectOneByExample(example);
}
/**
* 购物车转为订单
* @param ids
*
* @param cartOrderDto
* @return
*/
public ObjectRestResponse convertShopCartToOrderInfo(String ids) {
if (StringUtils.isBlank(ids)) {
public ObjectRestResponse convertShopCartToOrderInfo(CartOrderDto cartOrderDto) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (cartOrderDto == null || StringUtils.isBlank(cartOrderDto.getIds())) {
return ObjectRestResponse.paramIsEmpty();
}
String[] cartIds = ids.split(",");
if (cartIds == null || ids.length() <= 0) {
String[] cartIds = cartOrderDto.getIds().split(",");
if (cartIds == null || cartIds.length <= 0) {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
Example example = new Example(ShoppingCartInfo.class);
example.createCriteria().andIn("cartId", Arrays.asList(cartIds)).andEqualTo("isDel", 0);
List<ShoppingCartInfo> cartInfoList = mapper.selectByExample(example);
if (cartInfoList != null && cartInfoList.size() > 0) {
convertToOrderInfo(cartInfoList);
convertToOrderInfo(cartInfoList, cartOrderDto, appUserDTO);
return ObjectRestResponse.succ();
}
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
......@@ -93,18 +220,88 @@ public class ShoppingCartInfoBiz extends BaseBiz<ShoppingCartInfoMapper,Shopping
/**
* 购物车转订单实现
*
* @param cartInfoList
*/
private void convertToOrderInfo(List<ShoppingCartInfo> cartInfoList) {
List<OrderItem> orderItemList = new ArrayList<>();
private void convertToOrderInfo(List<ShoppingCartInfo> cartInfoList, CartOrderDto cartOrderDto, AppUserDTO appUserDTO) {
//总金额
double amount = cartInfoList.parallelStream().mapToDouble(shoppingCartInfo ->shoppingCartInfo.getTotalAmount().doubleValue()).sum();
double amount = cartInfoList.parallelStream().mapToDouble(shoppingCartInfo -> shoppingCartInfo.getTotalAmount().doubleValue()).sum();
//总数量
Integer totalNumber = cartInfoList.parallelStream().mapToInt(ShoppingCartInfo::getNumber).sum();
OrderInfo orderInfo = new OrderInfo();
orderInfo.setAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
orderInfo.setNumber(totalNumber);
orderInfoBiz.generateOrder(orderInfo);
cartInfoList.parallelStream().forEach(shoppingCartInfo -> {
OrderItem orderItem = ShoppingCartInfo.convertToOrderItem(shoppingCartInfo);
orderItem.setOrderId(orderInfo.getOrderId());
orderItemBiz.insertSelectiveRe(orderItem);
});
//收货信息
orderInfo.setReceiveName(cartOrderDto.getName());
orderInfo.setReceivePhone(cartOrderDto.getPhone());
orderInfo.setReceiveAddress(cartOrderDto.getAddress());
//用户信息
orderInfo.setHeadImg(appUserDTO.getHeadimgurl());
orderInfo.setNickname(appUserDTO.getNickname());
orderInfo.setPhone(appUserDTO.getUsername());
orderInfo.setUserId(appUserDTO.getUserid());
orderInfo.setRealName(appUserDTO.getRealname());
orderInfoBiz.updateSelectiveByIdRe(orderInfo);
}
/**
* 删除购物车
*
* @param id
* @return
*/
public ObjectRestResponse deleteOne(Integer id) {
if (id == null) {
return ObjectRestResponse.paramIsEmpty();
}
ShoppingCartInfo shoppingCartInfo = selectById(id);
if (shoppingCartInfo == null || shoppingCartInfo.getIsDel() == 1) {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
shoppingCartInfo.setIsDel(1);
updateSelectiveByIdRe(shoppingCartInfo);
return ObjectRestResponse.succ();
}
/**
* 批量删除
*
* @param ids
* @return
*/
public ObjectRestResponse deleteBatch(String ids) {
if (StringUtils.isBlank(ids)) {
return ObjectRestResponse.paramIsEmpty();
}
String[] idArr = ids.split(",");
if (idArr == null) {
return ObjectRestResponse.paramIsEmpty();
}
for (String id : idArr) {
if (StringUtils.isNotBlank(id)) {
deleteOne(Integer.parseInt(id));
}
}
return ObjectRestResponse.succ();
}
/**
* 根据ID List 查询所有购物车信息
* @param idList
* @return
*/
public List<ShoppingCartInfo> getAllByIds(Set<Integer> idList) {
Example example = new Example(ShoppingCartInfo.class);
example.createCriteria().andIn("id", idList);
return mapper.selectByExample(example);
}
}
\ No newline at end of file
......@@ -4,7 +4,6 @@ import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
......@@ -74,6 +73,7 @@ public class UserAddressBiz extends BaseBiz<UserAddressMapper, UserAddress> {
if (userAddress == null) {
return ObjectRestResponse.paramIsEmpty();
}
userAddress.setUserId(appUserVo.getUserid());
if (userAddress.getId() != null) {
UserAddress old = selectById(userAddress.getId());
if (old != null && old.getIsDel() != 1) {
......@@ -93,13 +93,54 @@ public class UserAddressBiz extends BaseBiz<UserAddressMapper, UserAddress> {
*
* @return
*/
public List<UserAddress> getUserAddress() {
public ObjectRestResponse<PageDataVO<UserAddress>> getUserAddress(UserAddressDto userAddressDto) {
AppUserDTO appUserVo = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserVo == null) {
return new ArrayList<>();
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
Query query = new Query(userAddressDto);
Example example = new Example(UserAddress.class);
example.createCriteria().andEqualTo("userId", appUserVo.getUserid()).andEqualTo("isDel", 0);
return mapper.selectByExample(example);
example.orderBy("isDefault").desc();
PageDataVO<UserAddress> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
return ObjectRestResponse.succ(pageDataVO);
}
/**
* 设置地址为默认值
* @param id
* @return
*/
public ObjectRestResponse setDefault(Integer id) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (id == null) {
return ObjectRestResponse.paramIsEmpty();
}
UserAddress userAddress = selectById(id);
if (userAddress == null || userAddress.getIsDel() == 1) {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
generateDefault(appUserDTO.getUserid());
userAddress.setIsDefault(1);
updateSelectiveByIdRe(userAddress);
return ObjectRestResponse.succ();
}
private void generateDefault(Integer userId) {
Example example = new Example(UserAddress.class);
example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0).andEqualTo("isDefault", 1);
List<UserAddress> list = mapper.selectByExample(example);
if (list != null && list.size() > 0) {
list.parallelStream().forEach(userAddress -> {
userAddress.setIsDefault(0);
updateSelectiveByIdRe(userAddress);
});
}
}
}
\ No newline at end of file
......@@ -2,12 +2,16 @@ package com.upyuns.platform.rs.website.biz;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.website.dto.UserInvoiceDto;
import com.upyuns.platform.rs.website.entity.OrderEInvoice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.upyuns.platform.rs.website.entity.UserInvoice;
......@@ -15,6 +19,9 @@ import com.upyuns.platform.rs.website.mapper.UserInvoiceMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 用户发票信息
*
......@@ -25,6 +32,10 @@ import tk.mybatis.mapper.entity.Example;
@Service
public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
@Autowired
UserFeign userFeign;
@Autowired
HttpServletRequest request;
/**
* 添加用户发票
* @param userInvoice
......@@ -48,6 +59,34 @@ public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
return ObjectRestResponse.succ();
}
/**
* 添加用户发票
* @param userInvoice
* @return
*/
public ObjectRestResponse userAddUpdate(UserInvoice userInvoice) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (userInvoice == null) {
return ObjectRestResponse.paramIsEmpty();
}
userInvoice.setUserId(appUserDTO.getUserid());
if (userInvoice.getId() == null) {
UserInvoice old = getOneByTax(userInvoice.getTaxCode(), userInvoice.getUserId());
if (old != null && StringUtils.isNotBlank(userInvoice.getTaxCode())) {
userInvoice.setId(old.getId());
updateData(userInvoice);
} else {
insertSelectiveRe(userInvoice);
}
} else {
updateData(userInvoice);
}
return ObjectRestResponse.succ();
}
/**
* 查询发票信息
* @param tax
......@@ -65,7 +104,7 @@ public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
* @param userInvoiceDto
* @return
*/
public ObjectRestResponse getList(UserInvoiceDto userInvoiceDto) {
public ObjectRestResponse<PageDataVO<UserInvoice>> getList(UserInvoiceDto userInvoiceDto) {
Example example = new Example(UserInvoice.class);
Example.Criteria criteria = example.createCriteria();
if (userInvoiceDto.getUserId() != null) {
......@@ -81,7 +120,7 @@ public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
criteria.andEqualTo("taxCode", "%" + userInvoiceDto.getTaxCode() + "%");
}
criteria.andEqualTo("isDel", 0);
example.orderBy("updTime").desc();
example.orderBy("isDefault").desc();
Query query = new Query(userInvoiceDto);
PageDataVO<UserInvoice> pageDataVO = PageDataVO.pageInfo(query, () -> mapper.selectByExample(example));
return ObjectRestResponse.succ(pageDataVO);
......@@ -92,7 +131,12 @@ public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
* @param userInvoiceDto
* @return
*/
public ObjectRestResponse getUserInvoiceInfo(UserInvoiceDto userInvoiceDto) {
public ObjectRestResponse<PageDataVO<UserInvoice>> getUserInvoiceInfo(UserInvoiceDto userInvoiceDto) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
userInvoiceDto.setUserId(appUserDTO.getUserid());
return getList(userInvoiceDto);
}
......@@ -108,4 +152,41 @@ public class UserInvoiceBiz extends BaseBiz<UserInvoiceMapper,UserInvoice> {
return ObjectRestResponse.succ();
}
/**
* 设置发票为默认值
* @param id
* @return
*/
public ObjectRestResponse setDefault(Integer id) {
AppUserDTO appUserDTO = userFeign.userDetailByToken(request.getHeader("Authorization")).getData();
if (appUserDTO == null) {
return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
}
if (id == null) {
return ObjectRestResponse.paramIsEmpty();
}
UserInvoice userInvoice = selectById(id);
if (userInvoice == null || userInvoice.getIsDel() == 1) {
return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, ResultCode.getMsg(ResultCode.NOTEXIST_CODE));
}
generateDefault(appUserDTO.getUserid());
userInvoice.setIsDefault(1);
updateSelectiveByIdRe(userInvoice);
return ObjectRestResponse.succ();
}
private void generateDefault(Integer userId) {
Example example = new Example(UserInvoice.class);
example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel", 0).andEqualTo("isDefault", 1);
List<UserInvoice> list = mapper.selectByExample(example);
if (list != null && list.size() > 0) {
list.parallelStream().forEach(userInvoice -> {
userInvoice.setIsDefault(0);
updateSelectiveByIdRe(userInvoice);
});
}
}
}
\ No newline at end of file
......@@ -58,7 +58,9 @@ public class WebConfiguration implements WebMvcConfigurer {
"/industryApplicationInfo/**",
"/industryApplicationType/**",
"/newsInfo/**",
"/newsType/**"
"/newsType/**",
"/customForm/**",
"/shoppingCartInfo/**"
};
Collections.addAll(list, urls);
return list;
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.BannerBiz;
......@@ -22,6 +23,7 @@ public class BannerController extends BaseController<BannerBiz, Banner> {
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll() {
return baseBiz.getAll(1);
}
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.ImageInformationBiz;
......@@ -24,6 +25,7 @@ public class ImageInformationController extends BaseController<ImageInformationB
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(ImageInformationDto imageInformationDto) {
return ObjectRestResponse.succ(baseBiz.selectList(imageInformationDto));
}
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.IndustryApplicationInfoBiz;
......@@ -22,11 +23,13 @@ public class IndustryApplicationInfoController extends BaseController<IndustryAp
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll() {
return baseBiz.getAllIndexShow();
}
@GetMapping(value = "/app/unauth/detail")
@IgnoreUserToken
public ObjectRestResponse detail(Integer id) {
return ObjectRestResponse.succ(baseBiz.selectById(id));
}
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.IndustryApplicationTypeBiz;
......@@ -22,12 +23,14 @@ public class IndustryApplicationTypeController extends BaseController<IndustryAp
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(Integer indexShow) {
return baseBiz.getAll(indexShow);
}
@GetMapping(value = "/app/unauth/getDetail")
@IgnoreUserToken
public ObjectRestResponse getDetail(Integer id) {
return baseBiz.getDetail(id);
}
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.NewsInfoBiz;
......@@ -22,16 +23,19 @@ public class NewsInfoController extends BaseController<NewsInfoBiz, NewsInfo> {
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(NewsInfoDto newsInfoDto) {
return baseBiz.selectList(newsInfoDto);
}
@GetMapping(value = "/app/unauth/getHot")
@IgnoreUserToken
public ObjectRestResponse getHotMsg() {
return baseBiz.getHotMsg();
}
@GetMapping(value = "/app/unauth/detail")
@IgnoreUserToken
public ObjectRestResponse detail(Integer id) {
return ObjectRestResponse.succ(baseBiz.selectById(id));
}
......
package com.upyuns.platform.rs.website.controller;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.NewsTypeBiz;
......@@ -17,6 +18,7 @@ public class NewsTypeController extends BaseController<NewsTypeBiz, NewsType> {
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll() {
return baseBiz.getAll();
}
......
......@@ -21,8 +21,4 @@ public class UserAddressController extends BaseController<UserAddressBiz,UserAdd
return baseBiz.addUpdate(userAddress);
}
@GetMapping(value = "getUserAddress")
public ObjectRestResponse getUserAddress() {
return ObjectRestResponse.succ(baseBiz.getUserAddress());
}
}
\ No newline at end of file
......@@ -8,7 +8,7 @@ import com.upyuns.platform.rs.website.entity.UserInvoice;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/userInvoice/back")
@RequestMapping("/userInvoice")
public class UserInvoiceController extends BaseController<UserInvoiceBiz,UserInvoice> {
@GetMapping(value = "getList")
......@@ -16,4 +16,9 @@ public class UserInvoiceController extends BaseController<UserInvoiceBiz,UserInv
return baseBiz.getList(userInvoiceDto);
}
@PostMapping(value = "addUpdate")
public ObjectRestResponse addUpdate(@RequestBody UserInvoice userInvoice) {
return baseBiz.addUpdate(userInvoice);
}
}
\ No newline at end of file
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.CommonInfoBiz;
......@@ -12,6 +13,7 @@ import org.springframework.web.bind.annotation.*;
public class CommonInfoWebController extends BaseController<CommonInfoBiz,CommonInfo> {
@GetMapping(value = "/app/unauth/getByType")
@IgnoreUserToken
public ObjectRestResponse getByType(Integer type) {
return ObjectRestResponse.succ(baseBiz.getByType(type));
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.CompanyInfoBiz;
......@@ -13,6 +14,7 @@ import org.springframework.web.bind.annotation.RestController;
public class CompanyInfoWebController extends BaseController<CompanyInfoBiz,CompanyInfo> {
@GetMapping(value = "/app/unauth/detail")
@IgnoreUserToken
public ObjectRestResponse getOne() {
return baseBiz.getIndexShow();
}
......
package com.upyuns.platform.rs.website.controller.web;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.AssertUtils;
import com.upyuns.platform.rs.datacenter.fegin.DatacenterFeign;
import com.upyuns.platform.rs.website.biz.CustomFormBiz;
import com.upyuns.platform.rs.website.entity.CustomForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
......@@ -12,20 +17,26 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("customForm/web")
public class CustomFormWebController extends BaseController<CustomFormBiz,CustomForm> {
@Autowired
DatacenterFeign datacenterFegin;
@RequestMapping(value = "customIndustry",method = RequestMethod.POST)
public ObjectRestResponse customIndustry(CustomForm entity) {
public ObjectRestResponse customIndustry(@RequestBody CustomForm entity) {
// if(StrUtil.isNotBlank(entity.getProvinceCode())) {
// entity.setProvinceName(AssertUtils.isFeignSucc(datacenterFegin.queryByCode(entity.getProvinceCode()).getData());
// }
baseBiz.insertSelective(entity);
return ObjectRestResponse.succ();
}
@RequestMapping(value = "customImgStorage",method = RequestMethod.POST)
public ObjectRestResponse customImgStorage(CustomForm entity) {
public ObjectRestResponse customImgStorage(@RequestBody CustomForm entity) {
baseBiz.insertSelective(entity);
return ObjectRestResponse.succ();
}
@RequestMapping(value = "customImageData",method = RequestMethod.POST)
public ObjectRestResponse customImageData(CustomForm entity) {
public ObjectRestResponse customImageData(@RequestBody CustomForm entity) {
baseBiz.insertSelective(entity);
return ObjectRestResponse.succ();
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.ImageImgStorageBiz;
......@@ -12,16 +13,19 @@ import org.springframework.web.bind.annotation.*;
public class ImageImgStorageWebController extends BaseController<ImageImgStorageBiz,ImageImgStorage> {
@GetMapping(value = "/app/unauth/getDetail/{id}")
@IgnoreUserToken
public ObjectRestResponse getDetail(@PathVariable Integer id) {
return baseBiz.getDetail(id);
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(Integer type) {
return baseBiz.getAll(type);
}
@GetMapping(value = "/app/unauth/getList")
@IgnoreUserToken
public ObjectRestResponse getList(ImageInformationStorageDto imageInformationStorageDto) {
return baseBiz.selectList(imageInformationStorageDto, 2);
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.ImageInformationBiz;
......@@ -12,11 +13,13 @@ import org.springframework.web.bind.annotation.*;
public class ImageInformationWebController extends BaseController<ImageInformationBiz,ImageInformation> {
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(ImageInformationDto imageInformationDto) {
return ObjectRestResponse.succ(baseBiz.selectList(imageInformationDto));
}
@GetMapping(value = "/app/unauth/getDetail/{id}")
@IgnoreUserToken
public ObjectRestResponse getDetail(@PathVariable Integer id) {
return ObjectRestResponse.succ(baseBiz.selectById(id));
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.IndustryApplicationInfoBiz;
......@@ -12,6 +13,7 @@ import org.springframework.web.bind.annotation.*;
public class IndustryApplicationWebInfoController extends BaseController<IndustryApplicationInfoBiz, IndustryApplicationInfo> {
@GetMapping(value = "/app/unauth/getList")
@IgnoreUserToken
public ObjectRestResponse getList(IndustryApplicationInfoDto industryApplicationInfoDto) {
industryApplicationInfoDto.setSortType(1);
industryApplicationInfoDto.setStatus(1);
......@@ -19,11 +21,13 @@ public class IndustryApplicationWebInfoController extends BaseController<Industr
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll() {
return baseBiz.getAllIndexShow();
}
@GetMapping(value = "/app/unauth/detail")
@IgnoreUserToken
public ObjectRestResponse detail(Integer id) {
return ObjectRestResponse.succ(baseBiz.selectById(id));
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.NewsInfoBiz;
......@@ -12,6 +13,7 @@ import org.springframework.web.bind.annotation.*;
public class NewsInfoWebController extends BaseController<NewsInfoBiz, NewsInfo> {
@GetMapping(value = "/app/unauth/getList")
@IgnoreUserToken
public ObjectRestResponse getList(NewsInfoDto newsInfoDto) {
newsInfoDto.setStatus(1);
newsInfoDto.setSortType(1);
......@@ -19,11 +21,13 @@ public class NewsInfoWebController extends BaseController<NewsInfoBiz, NewsInfo>
}
@GetMapping(value = "/app/unauth/getAll")
@IgnoreUserToken
public ObjectRestResponse getAll(NewsInfoDto newsInfoDto) {
return baseBiz.selectList(newsInfoDto);
}
@GetMapping(value = "/app/unauth/detail")
@IgnoreUserToken
public ObjectRestResponse detail(Integer id) {
return ObjectRestResponse.succ(baseBiz.selectById(id));
}
......
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.OrderInfoBiz;
import com.upyuns.platform.rs.website.dto.ConfirmOrderDto;
import com.upyuns.platform.rs.website.dto.OrderInfoDto;
import com.upyuns.platform.rs.website.entity.OrderInfo;
import com.upyuns.platform.rs.website.service.ConfirmOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -10,4 +17,16 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("orderInfo/web")
public class OrderInfoWebController extends BaseController<OrderInfoBiz,OrderInfo> {
@Autowired
ConfirmOrderService confirmOrderService;
@PostMapping(value = "confirmOrder")
public ObjectRestResponse confirmOrder(@RequestBody ConfirmOrderDto confirmOrderDto) {
return confirmOrderService.confirmOrderInfo(confirmOrderDto);
}
@PostMapping(value = "submitOrder")
public ObjectRestResponse submitOrder(@RequestBody OrderInfoDto orderInfoDto) {
return baseBiz.submitOrder(orderInfoDto);
}
}
\ No newline at end of file
package com.upyuns.platform.rs.website.controller.web;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.ShoppingCartInfoBiz;
import com.upyuns.platform.rs.website.dto.CartOrderDto;
import com.upyuns.platform.rs.website.dto.OrderInfoDto;
import com.upyuns.platform.rs.website.entity.ShoppingCartInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("shoppingCartInfo/web")
public class ShoppingCartInfoWebController extends BaseController<ShoppingCartInfoBiz,ShoppingCartInfo> {
@PostMapping(value = "addUpdate")
public ObjectRestResponse addUpdate(@RequestBody OrderInfoDto orderInfoDto) {
return baseBiz.addShoppingCart(orderInfoDto);
}
@GetMapping(value = "getUserShoppingCart")
public ObjectRestResponse getUserShoppingCart(OrderInfoDto orderInfoDto) {
return baseBiz.getUserAllCart(orderInfoDto);
}
@PostMapping(value = "convertToOrderInfo")
public ObjectRestResponse convertToOrderInfo(CartOrderDto cartOrderDto) {
return baseBiz.convertShopCartToOrderInfo(cartOrderDto);
}
@DeleteMapping(value = "deleteOne")
public ObjectRestResponse deleteOne(Integer id) {
return baseBiz.deleteOne(id);
}
@DeleteMapping(value = "deleteBatch")
public ObjectRestResponse deleteBatch(String ids) {
return baseBiz.deleteBatch(ids);
}
}
\ No newline at end of file
......@@ -5,24 +5,25 @@ import com.github.wxiaoqi.security.common.rest.BaseController;
import com.upyuns.platform.rs.website.biz.UserAddressBiz;
import com.upyuns.platform.rs.website.dto.UserAddressDto;
import com.upyuns.platform.rs.website.entity.UserAddress;
import com.upyuns.platform.rs.website.entity.UserInvoice;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("userAddress/web")
public class UserAddressWebController extends BaseController<UserAddressBiz,UserAddress>{
@GetMapping(value = "getList")
public ObjectRestResponse getList(UserAddressDto userAddressDto) {
return baseBiz.selectList(userAddressDto);
}
@PostMapping(value = "addUpdate")
public ObjectRestResponse addUpdate(@RequestBody UserAddress userAddress) {
return baseBiz.addUpdate(userAddress);
}
@GetMapping(value = "getUserAddress")
public ObjectRestResponse getUserAddress() {
return ObjectRestResponse.succ(baseBiz.getUserAddress());
public ObjectRestResponse getUserAddress(UserAddressDto userAddressDto) {
return baseBiz.getUserAddress(userAddressDto);
}
@PostMapping(value = "setDefault")
public ObjectRestResponse setDefault(@RequestBody UserAddress userAddress) {
return baseBiz.setDefault(userAddress.getId());
}
}
\ No newline at end of file
......@@ -13,10 +13,17 @@ public class UserInvoiceWebController extends BaseController<UserInvoiceBiz,User
@PostMapping(value = "addUpdate")
public ObjectRestResponse addUpdate(@RequestBody UserInvoice userInvoice) {
return baseBiz.addUpdate(userInvoice);
return baseBiz.userAddUpdate(userInvoice);
}
@GetMapping(value = "getUserList")
public ObjectRestResponse getUserList(UserInvoiceDto userInvoiceDto) {
return baseBiz.getUserInvoiceInfo(userInvoiceDto);
}
@PostMapping(value = "setDefault")
public ObjectRestResponse setDefault(@RequestBody UserInvoice userInvoice) {
return baseBiz.setDefault(userInvoice.getId());
}
}
\ No newline at end of file
package com.upyuns.platform.rs.website.service;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.upyuns.platform.rs.universal.constant.DictionaryKey;
import com.upyuns.platform.rs.universal.entity.Dictionary;
import com.upyuns.platform.rs.universal.feign.ThirdFeign;
import com.upyuns.platform.rs.website.biz.*;
import com.upyuns.platform.rs.website.dto.ConfirmOrderDto;
import com.upyuns.platform.rs.website.dto.ItemInfoDto;
import com.upyuns.platform.rs.website.entity.*;
import com.upyuns.platform.rs.website.type.OrderTypeEnum;
import com.upyuns.platform.rs.website.vo.ConfirmOrderInfoVo;
import com.upyuns.platform.rs.website.vo.ItemInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
/**
* @ClassName : ConfirmOrderService
* @Description : 确认订单信息
* @Author : jiaoruizhen
* @Date: 2020-12-16 14:50
*/
@Service
@Slf4j
public class ConfirmOrderService {
@Autowired
IndustryApplicationInfoBiz industryApplicationInfoBiz;
@Autowired
ImageImgStorageBiz imageImgStorageBiz;
@Autowired
ShoppingCartInfoBiz shoppingCartInfoBiz;
@Autowired
ImageInfoRelationBiz imageInfoRelationBiz;
@Autowired
ThirdFeign thirdFeign;
/**
* 确认订单
* @param confirmOrderDto
* @return
*/
public ObjectRestResponse confirmOrderInfo(ConfirmOrderDto confirmOrderDto) {
if (confirmOrderDto == null || confirmOrderDto.getItemInfoDtoList() == null) {
return ObjectRestResponse.paramIsEmpty();
}
ConfirmOrderInfoVo confirmOrderInfoVo = new ConfirmOrderInfoVo();
List<ItemInfoDto> itemInfoDtoList = confirmOrderDto.getItemInfoDtoList();
if (itemInfoDtoList != null && itemInfoDtoList.size() > 0) {
List<ItemInfoVo> itemInfoVoList = new ArrayList<>();
AtomicReference<Integer> number = new AtomicReference<>(0);
AtomicReference<Double> amount = new AtomicReference<>((double) 0);
itemInfoDtoList.parallelStream().forEach(itemInfoDto -> {
switch (OrderTypeEnum.getByCode(itemInfoDto.getType())) {
//标准数据
case STANDARD_DATA:
break;
//行业应用
case INDUSTRY_INFO:
IndustryApplicationInfo industryApplicationInfo = industryApplicationInfoBiz.getOneById(itemInfoDto.getId()).getData();
if (industryApplicationInfo != null) {
ItemInfoVo itemInfoVo = new ItemInfoVo();
itemInfoVo.setId(industryApplicationInfo.getId());
itemInfoVo.setDetailJson(JSONObject.toJSONString(industryApplicationInfo));
itemInfoVo.setImg(industryApplicationInfo.getCoverImg());
itemInfoVo.setNumber(itemInfoDto.getNumber());
itemInfoVo.setType(itemInfoDto.getType());
itemInfoVo.setPrice(industryApplicationInfo.getPrice());
itemInfoVoList.add(itemInfoVo);
//总数量
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = industryApplicationInfo.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber()));
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
break;
//影像图库
case IMAGE_STORAGE:
ImageInfoRelation imageInfoRelation = imageInfoRelationBiz.selectById(itemInfoDto.getId());
if (imageInfoRelation != null ) {
ImageImgStorage imageImgStorage = imageImgStorageBiz.getDetail(itemInfoDto.getId()).getData();
if (imageImgStorage != null) {
List<ImageInfoRelation> imageInfoRelationList = new ArrayList<>();
imageInfoRelationList.add(imageInfoRelation);
imageImgStorage.setImageInfoRelationList(imageInfoRelationList);
ItemInfoVo itemInfoVo = new ItemInfoVo();
itemInfoVo.setId(imageImgStorage.getId());
itemInfoVo.setPrice(imageInfoRelation.getPrice());
itemInfoVo.setType(itemInfoDto.getType());
itemInfoVo.setNumber(itemInfoDto.getNumber());
itemInfoVo.setImg(imageImgStorage.getCoverImg());
itemInfoVo.setDetailJson(JSONObject.toJSONString(imageImgStorage));
itemInfoVoList.add(itemInfoVo);
//总数量
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = imageInfoRelation.getPrice().multiply(new BigDecimal(itemInfoDto.getNumber()));
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
}
break;
//购物车
case SHOPPING_CART_INFO:
ShoppingCartInfo shoppingCartInfo = shoppingCartInfoBiz.selectById(itemInfoDto.getId());
if (shoppingCartInfo != null) {
ItemInfoVo itemInfoVo = new ItemInfoVo();
itemInfoVo.setId(shoppingCartInfo.getCartId().intValue());
itemInfoVo.setPrice(shoppingCartInfo.getPrice());
itemInfoVo.setType(shoppingCartInfo.getType());
itemInfoVo.setNumber(itemInfoDto.getNumber());
itemInfoVo.setImg(shoppingCartInfo.getItemPic());
itemInfoVo.setDetailJson(shoppingCartInfo.getDetailJson());
itemInfoVoList.add(itemInfoVo);
number.updateAndGet(v -> v + itemInfoDto.getNumber());
BigDecimal totalAmount = shoppingCartInfo.getTotalAmount();
amount.updateAndGet(v -> new Double((double) (v + totalAmount.doubleValue())));
}
break;
default:
break;
}
});
confirmOrderInfoVo.setTotalAmount(new BigDecimal(amount.get()));
confirmOrderInfoVo.setNumber(number.get());
confirmOrderInfoVo.setItemInfoVoList(itemInfoVoList);
}
Dictionary dictionary = thirdFeign.findDictionaryByTypeAndCode(DictionaryKey.APP_ORDER, DictionaryKey.SEND_FEE);
if (dictionary != null && StringUtils.isNotBlank(dictionary.getDetail())) {
confirmOrderInfoVo.setFee(new BigDecimal(dictionary.getDetail()));
}
if (confirmOrderInfoVo.getFee() != null) {
confirmOrderInfoVo.setActAmount(confirmOrderInfoVo.getTotalAmount().add(confirmOrderInfoVo.getFee()));
}
return ObjectRestResponse.succ(confirmOrderInfoVo);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment