项目初始化

parents
File added
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/agent.iml" filepath="$PROJECT_DIR$/.idea/agent.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="e3e559cc-848f-4a95-8e0a-a8ecfbd8fa3c" name="Default Changelist" comment="" />
<ignored path="$PROJECT_DIR$/out/" />
<ignored path="$PROJECT_DIR$/target/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf />
</component>
<component name="MavenImportPreferences">
<option name="generalSettings">
<MavenGeneralSettings>
<option name="localRepository" value="$PROJECT_DIR$/../../../SDK/repository" />
<option name="mavenHome" value="$PROJECT_DIR$/../../../SDK/apache-maven-3.5.0" />
<option name="userSettingsFile" value="$PROJECT_DIR$/../../../SDK/apache-maven-3.5.0/conf/settings.xml" />
</MavenGeneralSettings>
</option>
</component>
<component name="ProjectFrameBounds">
<option name="x" value="141" />
<option name="y" value="-1361" />
<option name="width" value="2016" />
<option name="height" value="1205" />
</component>
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scope" />
<pane id="PackagesPane" />
<pane id="ProjectPane" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="go.gopath.indexing.explicitly.defined" value="true" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
<property name="settings.editor.selected.configurable" value="MavenSettings" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="e3e559cc-848f-4a95-8e0a-a8ecfbd8fa3c" name="Default Changelist" comment="" />
<created>1621388580896</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1621388580896</updated>
<workItem from="1621388588556" duration="599000" />
<workItem from="1621499313858" duration="593000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="1192000" />
</component>
<component name="ToolWindowManager">
<frame x="141" y="-1361" width="2016" height="1205" extended-state="0" />
<editor active="true" />
<layout>
<window_info active="true" content_ui="combo" id="Project" order="0" visible="true" weight="0.25227964" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info id="Designer" order="2" />
<window_info id="Image Layers" order="3" />
<window_info id="Capture Tool" order="4" />
<window_info id="UI Designer" order="5" />
<window_info id="Favorites" order="6" side_tool="true" />
<window_info id="Learn" order="7" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" />
<window_info anchor="bottom" id="Run" order="2" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="thief-book" order="7" />
<window_info anchor="bottom" id="Terminal" order="8" />
<window_info anchor="bottom" id="Docker" order="9" show_stripe_button="false" />
<window_info anchor="bottom" id="Event Log" order="10" side_tool="true" />
<window_info anchor="bottom" id="Messages" order="11" visible="true" weight="0.32973945" />
<window_info anchor="bottom" id="Database Changes" order="12" />
<window_info anchor="bottom" id="Version Control" order="13" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="right" id="Maven" order="3" />
<window_info anchor="right" id="Palette" order="4" />
<window_info anchor="right" id="Capture Analysis" order="5" />
<window_info anchor="right" id="SciView" order="6" />
<window_info anchor="right" id="Database" order="7" />
<window_info anchor="right" id="Palette&#9;" order="8" />
<window_info anchor="right" id="Theme Preview" order="9" />
<window_info anchor="right" id="RestServices" order="10" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/pom.xml">
<provider selected="true" editor-type-id="text-editor" />
<provider editor-type-id="MavenHelperPluginDependencyAnalyzer" />
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
\ No newline at end of file
spring.application.name=resources-admin
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
eureka.client.enabled=false
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.client.eureka-server-connect-timeout-seconds=5
eureka.client.eureka-server-read-timeout-second = 8
eureka.client.register-with-eureka=false
eureka.instance.preferIpAddress=true
eureka.client.fetch-registry=false
app.id=resources
apollo.meta=http://localhost:8280
apollo.bootstrap.enabled = true
apollo.bootstrap.namespaces = application,admin
apollo.cacheDir=/data/deploy/cache
shell.python.path=/usr/local/bin/python3
server.port=9070
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/opt/logs/resources-admin.log</file>
<append>true</append>
<encoder>
<pattern>%date [%thread] %level %logger{100}[%line] %msg%n</pattern>
</encoder>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>/opt/logs/resources-admin.%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>50MB</maxFileSize>
<maxHistory>60</maxHistory>
<totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>
</appender>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date [%thread] %level %logger{100}[%line] %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.springframework.data" level="DEBUG" />
<logger name="org.springframework.cloud" level="INFO" />
<logger name="cn.benewtech.resources" level="DEBUG" />
<logger name="cn.benewtech.tower" level="DEBUG" />
<logger name="org.springframework.amqp" level="INFO" />
</configuration>
<?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>agent</artifactId>
<groupId>cn.benewtech</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-admin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<exclusions>
<exclusion>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
</dependency>
<dependency>
<groupId>cn.benewtech</groupId>
<artifactId>tower-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.benewtech</groupId>
<artifactId>job-helper</artifactId>
</dependency>
<dependency>
<groupId>cn.benewtech</groupId>
<artifactId>agent-repository</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
<resource>
<directory>config/${env}</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.benewtech.agent.admin.AgentAdminApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
package cn.benewtech.agent.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication(scanBasePackages = "cn.benewtech.agent")
@EnableAutoConfiguration(exclude = { ErrorMvcAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class,
DataSourceAutoConfiguration.class })
@EnableAspectJAutoProxy(exposeProxy = true)
@EnableAsync
public class AgentAdminApplication {
public static void main(String[] args) {
SpringApplication.run(AgentAdminApplication.class, args);
}
}
package cn.benewtech.agent.admin;
import cn.benewtech.tower.provider.annotation.EnableAliConfig;
import cn.benewtech.tower.provider.annotation.EnableQiniuConfig;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableQiniuConfig
@EnableAliConfig
public class CdnConfiguration {
}
package cn.benewtech.agent.admin;
import cn.benewtech.tower.core.repositories.ExtendMongoRepositoryImpl;
import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
@Configuration
@ComponentScan
@EnableMongoRepositories(basePackages = "cn.benewtech.agent.repository.primary", repositoryBaseClass = ExtendMongoRepositoryImpl.class)
public class MongoDbConfiguration {
@Value("${mongodb.primary.connectUrl}")
private String primaryUri;
@Primary
@Bean(name = "mongoTemplate")
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory());
}
@Bean
@Primary
public MongoDbFactory primaryFactory() throws Exception {
MongoDbFactory factory = new SimpleMongoDbFactory(new MongoClientURI(primaryUri));
return factory;
}
@Bean
MongoTransactionManager transactionManager() throws Exception {
return new MongoTransactionManager(primaryFactory());
}
}
package cn.benewtech.agent.admin;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;
@Configuration
public class RabbitmqConfiguration {
@Value("${rabbitmq.hosts}")
private String hosts;
@Value("${rabbitmq.task.username}")
private String taskUsername;
@Value("${rabbitmq.task.password}")
private String taskPasswd;
@Value("${rabbitmq.task.vhost}")
private String taskVhost;
@Bean
@Primary
public ConnectionFactory taskConnectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setAddresses(hosts);
connectionFactory.setUsername(taskUsername);
connectionFactory.setPassword(taskPasswd);
connectionFactory.setVirtualHost(taskVhost);
connectionFactory.setPublisherConfirms(true);
return connectionFactory;
}
@Bean("taskAdmin")
@Primary
public RabbitAdmin taskAdmin() {
return new RabbitAdmin(taskConnectionFactory());
}
@Bean("taskRabbitTemplate")
@Primary
public RabbitTemplate taskRabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
RetryTemplate retryTemplate = new RetryTemplate();
ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(500);
backOffPolicy.setMultiplier(10.0);
backOffPolicy.setMaxInterval(10000);
retryTemplate.setBackOffPolicy(backOffPolicy);
rabbitTemplate.setRetryTemplate(retryTemplate);
return rabbitTemplate;
}
@Bean("taskRabbitListener")
public SimpleRabbitListenerContainerFactory taskRabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(taskConnectionFactory());
factory.setMaxConcurrentConsumers(3);
factory.setChannelTransacted(false);
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
return factory;
}
@Bean("limitTaskRabbitListener")
public SimpleRabbitListenerContainerFactory limitTaskRabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(taskConnectionFactory());
factory.setMaxConcurrentConsumers(3);
factory.setChannelTransacted(false);
factory.setPrefetchCount(6);
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
return factory;
}
}
package cn.benewtech.agent.admin;
import cn.benewtech.tower.provider.middleware.RedisMessageListenerAdapter;
import cn.benewtech.tower.provider.middleware.RedisProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.util.List;
@Configuration
public class RedisConfiguration {
@Value("${redis.hostname}")
private String hostname;
@Value("${redis.port}")
private int port;
@Value("${redis.password}")
private String password;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(hostname);
config.setPort(port);
config.setPassword(password);
return new JedisConnectionFactory(config);
}
@Bean
public <T> RedisTemplate<String, T> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, T> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
Jackson2JsonRedisSerializer<?> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer(List<RedisMessageListenerAdapter> listeners) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(jedisConnectionFactory());
for(RedisMessageListenerAdapter listener: listeners) {
container.addMessageListener(listener, listener.topics());
}
return container;
}
@Bean
public RedisProvider redisProvider(RedisTemplate<String, Object> redisTemplate) {
return new RedisProvider(redisTemplate);
}
}
package cn.benewtech.agent.admin;
import cn.benewtech.tower.core.GlobalExceptionHandler;
import cn.benewtech.tower.core.annotation.support.AdminAuthenticateRequestInterceptor;
import cn.benewtech.tower.core.annotation.support.RetryAspect;
import cn.benewtech.tower.core.annotation.support.UserContextHandlerMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
/*@Value("${spring.application.name}")
private String moduleCode;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new UserContextHandlerMethodArgumentResolver());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AdminAuthenticateRequestInterceptor());
}
@Bean
public RetryAspect retryAspect() {
return new RetryAspect();
}
@Bean
public ApplicationEventMulticaster applicationEventMulticaster() {
SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
eventMulticaster.setTaskExecutor(defaultThreadPool());
return eventMulticaster;
}
@Bean
@Qualifier("defaultThreadPool")
public ThreadPoolExecutor defaultThreadPool() {
return new ThreadPoolExecutor(5, 20,
5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(5000),
new ThreadPoolExecutor.CallerRunsPolicy());
}
@Bean
public GlobalExceptionHandler globalExceptionHandler() {
return new GlobalExceptionHandler();
}*/
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.AgentDTO;
import cn.benewtech.agent.admin.input.AgentEvaluationFormInput;
import cn.benewtech.agent.admin.input.AgentDetailFormInput;
import cn.benewtech.agent.admin.input.AgentFormInput;
import cn.benewtech.agent.admin.servie.AgentEvaluationService;
import cn.benewtech.agent.admin.servie.AgentDetailService;
import cn.benewtech.agent.admin.servie.AgentService;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryOperator;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.annotation.QueryOperand;
import cn.benewtech.tower.core.HttpResult;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/agent")
public class AgentController {
@Autowired
private AgentService agentService;
@Autowired
private AgentDetailService detailService;
@Autowired
private AgentEvaluationService agentEvaluationService;
@PostMapping("/page")
public HttpResult<SimplePage<AgentDTO>> page(@RequestBody AgentQueryParams params, PageAdapter page) {
return HttpResult.of(agentService.pageQuery(params, page));
}
@GetMapping("/{uid}")
public HttpResult<AgentDTO> getAgent(@PathVariable Long uid) {
return HttpResult.of(agentService.get(uid));
}
@PostMapping("/{uid}/edit")
public HttpResult<Void> edit(@PathVariable Long uid, @RequestBody AgentFormInput input) {
agentService.edit(uid, input);
return HttpResult.of(null);
}
@GetMapping("/{uid}/approve")
public HttpResult<Void> approve(@PathVariable Long uid, @RequestParam ApproveStatusEnum status) {
agentService.updateApproveStatus(uid, status);
return HttpResult.of(null);
}
@PostMapping("/{uid}/detail/edit")
public HttpResult<Void> editDetail(@PathVariable Long uid, @RequestBody AgentDetailFormInput input) {
detailService.edit(uid, input);
return HttpResult.of(null);
}
@PostMapping("/{uid}/comment")
public HttpResult<Void> monthlyComment(@PathVariable Long uid, @RequestBody AgentEvaluationFormInput input) {
agentEvaluationService.add(uid, input);
return HttpResult.of(null);
}
//todo 邀请注册
@GetMapping("/invite")
public HttpResult<String> invite() {
return HttpResult.of(null);
}
@Data
public static class AgentQueryParams extends QueryParams {
@QueryOperand(QueryOperator.EQ)
private Long uid;
@QueryOperand(QueryOperator.LIKE)
private String name;
@QueryOperand(QueryOperator.LIKE)
private String salesman;
@QueryOperand(QueryOperator.LIKE)
private CooperationTypeEnum cooperationMode;
@QueryOperand(QueryOperator.EQ)
private ApproveStatusEnum approveStatus;
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.ArticleDTO;
import cn.benewtech.agent.admin.servie.ArticleService;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.tower.core.HttpResult;
import cn.benewtech.tower.utils.common.StringHelper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@PostMapping("/page")
public HttpResult<SimplePage<ArticleDTO>> page(@RequestBody ArticleQueryParam param, PageAdapter page) {
if (StringHelper.isBlank(page.getOrder())) {
page.setOrder("-order");
}
return HttpResult.of(articleService.pageQuery(param, page));
}
@GetMapping("/{uid}/detail")
public HttpResult<ArticleDTO> detail(@PathVariable Long uid) {
return HttpResult.of(articleService.getDetail(uid));
}
@GetMapping("/{uid}/delete")
public HttpResult<Void> delete(@PathVariable Long uid) {
articleService.delete(uid);
return HttpResult.of(null);
}
@Data
public static class ArticleQueryParam extends QueryParams {
private String title;
private Long uid;
private AccessEnum status;
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.tower.core.HttpResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/helloWorld")
public HttpResult<String> helloWorld(){
return HttpResult.of("hello world");
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.FeedbackDTO;
import cn.benewtech.agent.admin.servie.FeedbackService;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryOperator;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.annotation.QueryOperand;
import cn.benewtech.tower.core.HttpResult;
import cn.benewtech.agent.enums.SellChannelEnum;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* 投诉/反馈
*/
@RestController
@RequestMapping("/feedback")
public class FeedbackController {
@Autowired
private FeedbackService feedbackService;
@PostMapping("/page")
public HttpResult<SimplePage<FeedbackDTO>> page(@RequestBody FeedbackQueryParam params, PageAdapter page) {
return HttpResult.of(feedbackService.pageQuery(params, page));
}
@GetMapping("/{uid}/detail")
public HttpResult<FeedbackDTO> detail(@PathVariable Long uid){
return HttpResult.of(feedbackService.getDetail(uid));
}
@Data
public static class FeedbackQueryParam extends QueryParams {
@QueryOperand(QueryOperator.LIKE)
private String username;
@QueryOperand(QueryOperator.EQ)
private SellChannelEnum channel;
@QueryOperand(QueryOperator.EQ)
private String productCode;
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.ProductDTO;
import cn.benewtech.agent.admin.input.ProductFormInput;
import cn.benewtech.agent.admin.servie.ProductService;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryOperator;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.annotation.QueryOperand;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.tower.core.HttpResult;
import cn.benewtech.agent.enums.ProductTypeEnum;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@PostMapping("/page")
public HttpResult<SimplePage<ProductDTO>> page(@RequestBody ProductQueryParam param, PageAdapter page) {
SimplePage<ProductDTO> result = productService.pageQuery(param, page);
return HttpResult.of(result);
}
@PostMapping("/add")
public HttpResult<Void> add(@RequestBody ProductFormInput input) {
productService.add(input);
return HttpResult.of(null);
}
@PostMapping("/{uid}/edit")
public HttpResult<ProductDTO> edit(@PathVariable Long uid, @RequestBody ProductFormInput input) {
return HttpResult.of(productService.edit(uid, input));
}
@Data
public static class ProductQueryParam extends QueryParams {
@QueryOperand(QueryOperator.EQ)
private Long uid;
@QueryOperand(QueryOperator.LIKE)
private String name;
@QueryOperand(QueryOperator.EQ)
private String code;
@QueryOperand(QueryOperator.EQ)
private ProductTypeEnum productType;
@QueryOperand(QueryOperator.EQ)
private AccessEnum status;
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.RebateConfigDTO;
import cn.benewtech.agent.admin.input.RebateConfigFormInput;
import cn.benewtech.agent.admin.servie.RebateConfigService;
import cn.benewtech.agent.enums.RebateTypeEnum;
import cn.benewtech.tower.core.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/rebate/config")
public class RebateConfigController {
@Autowired
private RebateConfigService rebateConfigService;
@PostMapping("/edit")
public HttpResult<Void> edit(@RequestBody RebateConfigFormInput input) {
rebateConfigService.createOrUpdate(input);
return HttpResult.of(null);
}
@GetMapping("/{type}/detail")
public HttpResult<RebateConfigDTO> detail(@PathVariable RebateTypeEnum type) {
return HttpResult.of(rebateConfigService.getDetail(type));
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.RebateRecordDTO;
import cn.benewtech.agent.admin.input.RebateRecordFormInput;
import cn.benewtech.agent.admin.servie.RebateRecordService;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryOperator;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.annotation.QueryOperand;
import cn.benewtech.tower.core.HttpResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/rebateRecord")
public class RebateRecordController {
@Autowired
private RebateRecordService rebateRecordService;
@PostMapping("/page")
public HttpResult<SimplePage<RebateRecordDTO>> page(@RequestBody RebateRecordQueryParam param, PageAdapter page) {
SimplePage<RebateRecordDTO> result = rebateRecordService.pageQuery(param, page);
return HttpResult.of(result);
}
@PostMapping("/{uid}/update")
public HttpResult<Void> update(@PathVariable Long uid, @RequestBody RebateRecordFormInput input) {
rebateRecordService.update(uid, input);
return HttpResult.of(null);
}
@GetMapping("/{uid}/approve")
public HttpResult<Void> approve(@PathVariable Long uid) {
rebateRecordService.approve(uid);
return HttpResult.of(null);
}
/**
* 生成返利
*
* @return
*/
@GetMapping("/generate")
public HttpResult<Void> generate() {
//todo 生成上季度所有代理商的返利数据
return HttpResult.of(null);
}
@Data
public static class RebateRecordQueryParam extends QueryParams {
@QueryOperand(QueryOperator.EQ)
private Long agentId;
@QueryOperand(QueryOperator.EQ)
private Integer rebateCycle;
@QueryOperand(QueryOperator.EQ)
private ApproveStatusEnum status;
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.RechargeConfigDTO;
import cn.benewtech.agent.admin.input.RechargeConfigFormInput;
import cn.benewtech.agent.admin.servie.RechargeConfigService;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.core.HttpResult;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/recharge/config")
@RestController
@Slf4j
public class RechargeConfigController {
@Autowired
private RechargeConfigService rechargeConfigService;
@GetMapping("/page")
public HttpResult<SimplePage<RechargeConfigDTO>> page(PageAdapter page) {
return HttpResult.of(rechargeConfigService.pageQuery(page));
}
@PostMapping("/add")
public HttpResult<Void> add(@RequestBody RechargeConfigFormInput input) {
rechargeConfigService.checkConfigExistByType(input.getFeeType());
rechargeConfigService.add(input);
return HttpResult.of(null);
}
@PostMapping("/{uid}/edit")
public HttpResult<Void> edit(@PathVariable Long uid, @RequestBody RechargeConfigFormInput input) {
rechargeConfigService.createNewVersion(uid, input);
return HttpResult.of(null);
}
}
package cn.benewtech.agent.admin.controller;
import cn.benewtech.agent.admin.dto.RechargeRecordDTO;
import cn.benewtech.agent.admin.input.ApproveInput;
import cn.benewtech.agent.admin.servie.RechargeService;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.QueryOperator;
import cn.benewtech.tower.beans.QueryParams;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.annotation.QueryOperand;
import cn.benewtech.tower.core.HttpResult;
import cn.benewtech.tower.core.SessionContext;
import cn.benewtech.tower.core.annotation.LoginInfo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
@RestController
@RequestMapping("/recharge/record")
public class RechargeController {
@Autowired
private RechargeService rechargeService;
@GetMapping("/{uid}/detail")
public HttpResult<Map> detail(@PathVariable Long uid) {
RechargeRecordDTO result = rechargeService.getDetail(uid);
return HttpResult.of(null);
}
@PostMapping("/page")
public HttpResult<SimplePage<RechargeRecordDTO>> page(RechargeRecordQueryParam param, PageAdapter page) {
SimplePage<RechargeRecordDTO> result = rechargeService.pageQuery(param, page);
return HttpResult.of(result);
}
@PostMapping("/{uid}/approve")
public HttpResult<Void> approve(@PathVariable Long uid, @RequestBody ApproveInput approveInput,
@LoginInfo SessionContext sessionCtx) {
rechargeService.approve(uid, approveInput, sessionCtx.userId);
return HttpResult.of(null);
}
@Data
public static class RechargeRecordQueryParam extends QueryParams {
@QueryOperand(QueryOperator.EQ)
private String orderNo;
@QueryOperand(value = QueryOperator.GTE, field = "created")
private Date beginDate;
@QueryOperand(value = QueryOperator.LTE, field = "created")
private Date endDate;
@QueryOperand(QueryOperator.EQ)
private FeeTypeEnum feeType;
}
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import lombok.Data;
import java.util.Date;
@Data
public class AgentDTO {
private Long uid;
private String name;
private String erpCode;
private CooperationTypeEnum cooperationMode;
private String salesman;
private ApproveStatusEnum approveStatus;
private AgentDetailDTO agentDetail;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
import lombok.Data;
import java.util.Date;
@Data
public class AgentDetailDTO {
private Long agentUid;
private String companyName;
private String contracts;
private String duty;
private String tel;
private String mail;
private String address;
private Date registerTime;
private Double companyArea;
private String identityFront;
private String identityReverse;
private String businessLicense;
private String taxCertify;
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.tower.beans.enums.AccessEnum;
import java.util.Date;
public class ArticleDTO {
private Long uid;
private String title;
private String type;
private Integer order;
private String content;
private String link;
private AccessEnum status;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.agent.enums.FeedbackTypeEnum;
import cn.benewtech.agent.enums.SellChannelEnum;
import lombok.Data;
import java.util.Date;
@Data
public class FeedbackDTO {
private Long uid;
private FeedbackTypeEnum type;
private String phone;
private SellChannelEnum channel;
private String store;
private String productCode;
private String product;
private String link;
private String content;
private String picture;
private String username;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import cn.benewtech.agent.enums.ProductTypeEnum;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class ProductDTO {
private Long uid;
private String name;
private String code;
private ProductTypeEnum productType;
private String cover;
private BigDecimal price;
private BigDecimal expressFee;
private CooperationTypeEnum cooperationType;
private AccessEnum status;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
public class RebateConfigDTO {
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import cn.benewtech.agent.enums.EvaluateEnum;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class RebateRecordDTO {
private Long uid;
private Long agentUid;
private BigDecimal sale;
private BigDecimal saleTarget;
/**
* 销售额返利百分比
*/
private Double saleRebate;
/**
* 激活量
*/
private Integer activationCnt;
/**
* 激活量排名
*/
private Integer activationRank;
/**
* 激活量排名返利
*/
private Double activationCntRebate;
/**
* 激活量增速排名
*/
private Integer activationIncrRank;
/**
* 激活量增速返利
*/
private Double activationIncrRebate;
private CooperationTypeEnum cooperationType;
private Double cooperationRebate;
/**
* 市场协作/评价
*/
private EvaluateEnum evaluate;
private Double evaluateRebate;
private BigDecimal rebateFee;
private Date expireDate;
private Integer rebateCycle;
private ApproveStatusEnum status;
private Double totalRebate;
private String salesman;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.enums.StatusEnum;
import lombok.Data;
import java.util.Date;
@Data
public class RechargeConfigDTO {
private Long uid;
private FeeTypeEnum feeType;
private Double goodsRebateRate = 0d;
private Double partsRebateRate = 0d;
private Double expressRebateRate = 0d;
private StatusEnum status = StatusEnum.NORMAL;
private Integer version;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.dto;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Data
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class RechargeRecordDTO {
private Long uid;
private Long agentUid;
private String orderNo;
private BigDecimal fee;
private FeeTypeEnum feeType;
private BigDecimal fittingRebate;
private BigDecimal expressRebate;
private String remark;
private String snapshot;
private ApproveStatusEnum status;
private List<AccountSnapshot> accountSnapshot;
private Date created;
private Date updated;
@Data
public static class AccountSnapshot {
/**
* 钱包余额
*/
private BigDecimal beforeFee;
/**
* 返利余额(指未激活的返利)
*/
private BigDecimal beforeRebate;
/**
* 充值金额
*/
private BigDecimal rechargeFee;
/**
* 返利金额
*/
private BigDecimal rebateFee;
private FeeTypeEnum feeType;
}
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.tower.beans.FormInput;
import lombok.Data;
import java.util.Date;
@Data
public class AgentDetailFormInput implements FormInput {
private String companyName;
private String contracts;
private String duty;
private String tel;
private String mail;
private String address;
private Date registerTime;
private Double companyArea;
private String identityFront;
private String identityReverse;
private String businessLicense;
private String taxCertify;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import lombok.Data;
import java.util.Date;
@Data
public class AgentEvaluationFormInput {
private Integer score;
private Integer commentYear;
private Integer commentMonth;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.tower.beans.FormInput;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import lombok.Data;
import java.util.Date;
@Data
public class AgentFormInput implements FormInput {
private String name;
private String erpCode;
private CooperationTypeEnum cooperationMode;
private String salesman;
private ApproveStatusEnum approveStatus;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import lombok.Data;
@Data
public class ApproveInput {
private String remark;
private ApproveStatusEnum approveStatus;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.tower.beans.FormInput;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import cn.benewtech.agent.enums.ProductTypeEnum;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class ProductFormInput implements FormInput {
private String name;
private String code;
private ProductTypeEnum productType;
private String coverKey;
private BigDecimal price;
private BigDecimal expressFee;
private CooperationTypeEnum cooperationType;
private AccessEnum status;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.tower.beans.FormInput;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.agent.domain.RebateConfig;
import cn.benewtech.agent.enums.RebateTypeEnum;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
public class RebateConfigFormInput implements FormInput {
private Long uid;
/**
* 销售额返利
*/
private List<RebateConfig.SaleRebate> saleRebates;
/**
* 激活量增速
*/
private List<RebateConfig.ActivationRebate> activationIncrRebates;
/**
* 合作方式返利
*/
private List<RebateConfig.CooperationRebate> cooperationRebates;
/**
* 激活量
*/
private List<RebateConfig.ActivationRebate> activationRebates;
private RebateTypeEnum rebateType;
private AccessEnum status;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.CooperationTypeEnum;
import cn.benewtech.agent.enums.EvaluateEnum;
import cn.benewtech.tower.beans.FormInput;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class RebateRecordFormInput implements FormInput {
private Long uid;
private Long agentUid;
private BigDecimal sale;
private BigDecimal saleTarget;
/**
* 销售额返利百分比
*/
private Double saleRebate;
/**
* 激活量
*/
private Integer activationCnt;
/**
* 激活量排名
*/
private Integer activationRank;
/**
* 激活量排名返利
*/
private Double activationCntRebate;
/**
* 激活量增速排名
*/
private Integer activationIncrRank;
/**
* 激活量增速返利
*/
private Double activationIncrRebate;
private CooperationTypeEnum cooperationType;
private Double cooperationRebate;
/**
* 市场协作/评价
*/
private EvaluateEnum evaluate;
private Double evaluateRebate;
private BigDecimal rebateFee;
private Date expireDate;
private Integer rebateCycle;
private Date created;
private Date updated;
}
package cn.benewtech.agent.admin.input;
import cn.benewtech.tower.beans.FormInput;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.enums.StatusEnum;
import lombok.Data;
@Data
public class RechargeConfigFormInput implements FormInput {
private Long uid;
private FeeTypeEnum feeType;
private Double goodsRebateRate;
private Double partsRebateRate;
private Double expressRebateRate;
private StatusEnum status;
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.domain.AccountLog;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.enums.FeeItemTypeEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.repository.primary.AccountLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
@Service
public class AccountLogService {
@Autowired
private AccountLogRepository accountLogRepo;
public void recordDealLog(Long agentUid, BigDecimal fee, FeeTypeEnum feeType,
FeeItemTypeEnum feeItemType, Long businessUid, BusTypeEnum busType) {
Date now = new Date();
AccountLog accountLog = new AccountLog();
accountLog.setUid(accountLogRepo.nextLongUid());
accountLog.setAgentUid(agentUid);
accountLog.setFee(fee);
accountLog.setFeeType(feeType);
accountLog.setFeeItemType(feeItemType);
accountLog.setRefUid(businessUid);
accountLog.setBusTypeEnum(busType);
accountLog.setCreated(now);
accountLogRepo.insert(accountLog);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.domain.Account;
import cn.benewtech.agent.domain.QAccount;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.enums.FeeItemTypeEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.repository.primary.AccountRepository;
import cn.benewtech.tower.beans.exception.BizException;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.CollectionHelper;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class AccountService {
@Autowired
private AccountRepository accountRepo;
@Autowired
private AccountLogService accountLogService;
public Map<FeeTypeEnum, Account> mapByFeeType(Long agentUid) {
List<Account> accounts = getAccounts(agentUid);
return CollectionHelper.toMap(accounts, Account::getFeeType);
}
private List<Account> getAccounts(Long agentUid) {
QAccount qb = QAccount.account;
BooleanExpression expression = qb.agentUid.eq(agentUid);
return accountRepo.listQuery(expression);
}
/**
* 钱包扣费/充值
* 注意: 钱包一定要在初始化账号的时候建好
*
* @param agentUid
* @param fee
* @param feeType
* @param recharge
*/
@Transactional
public void deduct(Long agentUid, BigDecimal fee, FeeTypeEnum feeType,
FeeItemTypeEnum feeItemType, Long businessUid, BusTypeEnum recharge) {
if (BigDecimal.ZERO.compareTo(fee) == 0) {
return;
}
Account account = getAccount(agentUid, feeType);
updateAccountFee(fee, feeItemType, account);
accountLogService.recordDealLog(agentUid, fee, feeType, feeItemType, businessUid, recharge);
}
private void updateAccountFee(BigDecimal fee, FeeItemTypeEnum feeItemType, Account account) {
QAccount qb = QAccount.account;
BooleanExpression expression = qb.id.eq(account.getId())
.and(qb.v.eq(account.getV()));
String updateField = chooseUpdateFeeField(feeItemType);
Update update = new Update();
update.inc(updateField, fee);
update.set("updated", new Date());
long updateCnt = accountRepo.update(expression, update);
AssertHelper.isTrue(updateCnt == 1, "账户扣款失败");
}
private String chooseUpdateFeeField(FeeItemTypeEnum feeItemType) {
String updateField;
switch (feeItemType) {
case ACTUAL:
updateField = "fee";
break;
case REBATE:
updateField = "rebateFee";
break;
default:
throw new RuntimeException("实际费用类型错误");
}
return updateField;
}
private Account getAccount(Long agentUid, FeeTypeEnum feeType) {
QAccount qb = QAccount.account;
BooleanExpression expression = qb.agentUid.eq(agentUid)
.and(qb.feeType.eq(feeType));
return accountRepo.findOne(expression)
.orElseThrow(() -> new BizException("账号不存在"));
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.input.AgentDetailFormInput;
import com.querydsl.core.types.dsl.BooleanExpression;
import cn.benewtech.agent.domain.QAgentDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.AgentDetailRepository;
import java.util.Date;
@Service
public class AgentDetailService {
@Autowired
private AgentDetailRepository detailRepo;
public void edit(Long uid, AgentDetailFormInput input) {
QAgentDetail qb = QAgentDetail.agentDetail;
BooleanExpression eq = qb.agentUid.eq(uid);
input.setUpdated(new Date());
detailRepo.update(eq, input);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.input.AgentEvaluationFormInput;
import cn.benewtech.agent.domain.Agent;
import cn.benewtech.agent.domain.AgentEvaluation;
import cn.benewtech.agent.domain.QAgentEvaluation;
import cn.benewtech.agent.repository.primary.AgentEvaluationRepository;
import cn.benewtech.agent.repository.primary.AgentRepository;
import cn.benewtech.tower.utils.common.AssertHelper;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Optional;
@Service
public class AgentEvaluationService {
@Autowired
private AgentRepository agentRepo;
@Autowired
private AgentEvaluationRepository evaluationRepo;
public void add(Long uid, AgentEvaluationFormInput input) {
Optional<Agent> agentOptional = agentRepo.getByUid(uid);
AssertHelper.isTrue(agentOptional.isPresent(), "代理商不存在");
Integer commentYear = input.getCommentYear();
Integer commentMonth = input.getCommentMonth();
QAgentEvaluation qb = QAgentEvaluation.agentEvaluation;
BooleanExpression eq = qb.agentUid.eq(uid)
.and(qb.month.eq(commentMonth))
.and(qb.year.eq(commentYear));
long existCount = evaluationRepo.count(eq);
AssertHelper.isTrue(existCount <= 0,
String.format("代理商%s,%s年%s月已存在点评",
agentOptional.get().getName(), commentYear, commentMonth));
AgentEvaluation agentEvaluation = new AgentEvaluation();
BeanUtils.copyProperties(input, agentEvaluation);
agentEvaluation.setAgentUid(uid);
agentEvaluation.setCreated(new Date());
evaluationRepo.save(agentEvaluation);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.AgentController;
import cn.benewtech.agent.admin.dto.AgentDTO;
import cn.benewtech.agent.admin.dto.AgentDetailDTO;
import cn.benewtech.agent.admin.input.AgentFormInput;
import cn.benewtech.agent.domain.*;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.repository.primary.AgentDetailRepository;
import cn.benewtech.agent.repository.primary.AgentRepository;
import cn.benewtech.agent.repository.primary.ApprovalLogRepository;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.CollectionHelper;
import com.google.common.collect.Lists;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
public class AgentService {
@Autowired
private AgentRepository agentRepo;
@Autowired
private AgentDetailRepository agentDetailRepo;
@Autowired
private ApprovalLogRepository approvalLogRepo;
public SimplePage<AgentDTO> pageQuery(AgentController.AgentQueryParams params, PageAdapter page) {
SimplePage<Agent> simplePage = agentRepo.pageQuery(params, page);
List<Agent> agents = simplePage.getDatas();
List<AgentDTO> dtos = Lists.newArrayList();
agents.forEach(agent -> {
AgentDTO dto = new AgentDTO();
BeanUtils.copyProperties(agent, dto);
dtos.add(dto);
});
return SimplePage.valueOf(simplePage.getCount(), dtos);
}
public AgentDTO get(Long uid) {
Optional<Agent> agentOptional = agentRepo.getByUid(uid);
AssertHelper.isTrue(agentOptional.isPresent(), "代理商不存在");
Agent agent = agentOptional.get();
AgentDTO agentDto = new AgentDTO();
BeanUtils.copyProperties(agent, agentDto);
QAgentDetail qAgentDetail = QAgentDetail.agentDetail;
BooleanExpression eq = qAgentDetail.agentUid.eq(uid);
Optional<AgentDetail> detailOptional = agentDetailRepo.findOne(eq);
if (detailOptional.isPresent()) {
AgentDetail detail = detailOptional.get();
AgentDetailDTO detailDto = new AgentDetailDTO();
BeanUtils.copyProperties(detail, detailDto);
agentDto.setAgentDetail(detailDto);
}
return agentDto;
}
public void edit(Long uid, AgentFormInput input) {
QAgent qb = QAgent.agent;
BooleanExpression eq = qb.uid.eq(uid);
input.setUpdated(new Date());
agentRepo.update(eq, input);
}
@Transactional
public void updateApproveStatus(Long uid, ApproveStatusEnum status) {
Date now = new Date();
Update update = new Update();
update.set("approveStatus", status);
update.set("updated", now);
QAgent qb = QAgent.agent;
BooleanExpression eq = qb.uid.eq(uid);
agentRepo.update(eq, update);
ApprovalLog approvalLog = new ApprovalLog();
approvalLog.setRefUid(uid);
approvalLog.setBusType(BusTypeEnum.AGENT_REGIST);
approvalLog.setStatus(status);
approvalLog.setCreated(now);
approvalLogRepo.save(approvalLog);
}
public Map<Long, Agent> mapByUids(List<Long> uids) {
List<Agent> agents = listByUids(uids);
return CollectionHelper.toMap(agents, Agent::getUid);
}
public List<Agent> listByUids(List<Long> uids) {
QAgent qb = QAgent.agent;
BooleanExpression eq = qb.uid.in(uids);
return agentRepo.listQuery(eq);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.input.ApproveInput;
import cn.benewtech.agent.domain.ApprovalLog;
import cn.benewtech.agent.domain.RechargeRecord;
import cn.benewtech.agent.repository.primary.ApprovalLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class ApprovalLogService {
@Autowired
private ApprovalLogRepository approvalLogRepo;
public void saveLog(ApproveInput approveInput, Long userId, RechargeRecord record) {
ApprovalLog approvalLog = new ApprovalLog();
approvalLog.setUid(approvalLogRepo.nextLongUid());
approvalLog.setRefUid(record.getUid());
approvalLog.setAgentUid(record.getAgentUid());
approvalLog.setRemark(approveInput.getRemark());
approvalLog.setOperId(userId);
approvalLog.setStatus(approveInput.getApproveStatus());
approvalLog.setCreated(new Date());
approvalLogRepo.insert(approvalLog);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.ArticleController;
import cn.benewtech.agent.admin.dto.ArticleDTO;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.beans.enums.AccessEnum;
import cn.benewtech.tower.utils.common.AssertHelper;
import com.google.common.collect.Lists;
import com.querydsl.core.types.dsl.BooleanExpression;
import cn.benewtech.agent.domain.Article;
import cn.benewtech.agent.domain.QArticle;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.ArticleRepository;
import java.util.List;
import java.util.Optional;
@Service
public class ArticleService {
@Autowired
private ArticleRepository articleRepo;
public SimplePage<ArticleDTO> pageQuery(ArticleController.ArticleQueryParam param, PageAdapter page) {
SimplePage<Article> pageResult = articleRepo.pageQuery(param, page);
List<Article> datas = pageResult.getDatas();
List<ArticleDTO> dtos = Lists.newArrayList();
for (Article data : datas) {
ArticleDTO dto = new ArticleDTO();
BeanUtils.copyProperties(data, dto);
dtos.add(dto);
}
return SimplePage.valueOf(pageResult.getCount(), dtos);
}
public ArticleDTO getDetail(Long uid) {
Optional<Article> articleOptional = articleRepo.getByUid(uid);
AssertHelper.isTrue(articleOptional.isPresent(), "文章不存在");
Article article = articleOptional.get();
ArticleDTO dto = new ArticleDTO();
BeanUtils.copyProperties(article, dto);
return dto;
}
public void delete(Long uid) {
QArticle qb = QArticle.article;
BooleanExpression expression = qb.uid.eq(uid);
Update update = new Update();
update.set("access", AccessEnum.DELETED);
articleRepo.update(expression, update);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.FeedbackController;
import cn.benewtech.agent.admin.dto.FeedbackDTO;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.provider.cdn.QiniuCdnProvider;
import cn.benewtech.tower.provider.cdn.ResourceTypeEnum;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.StringHelper;
import com.google.common.collect.Lists;
import cn.benewtech.agent.domain.Feedback;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.FeedbackRepository;
import java.util.List;
import java.util.Optional;
@Service
public class FeedbackService {
@Autowired
private FeedbackRepository feedbackRepo;
@Autowired
private QiniuCdnProvider qiniuProvider;
public SimplePage<FeedbackDTO> pageQuery(FeedbackController.FeedbackQueryParam params, PageAdapter page) {
SimplePage<Feedback> simplePage = feedbackRepo.pageQuery(params, page);
List<Feedback> feedbacks = simplePage.getDatas();
List<FeedbackDTO> dtos = Lists.newArrayList();
for (Feedback feedback : feedbacks) {
FeedbackDTO dto = converDto(feedback);
dtos.add(dto);
}
return SimplePage.valueOf(simplePage.getCount(), dtos);
}
private FeedbackDTO converDto(Feedback feedback) {
FeedbackDTO dto = new FeedbackDTO();
BeanUtils.copyProperties(feedback, dto);
dto.setPicture(getPicture(feedback.getPicture()));
return dto;
}
private String getPicture(String pictureKey) {
if (!StringHelper.isBlank(pictureKey)) {
// return qiniuProvider.getResourceUrl(ResourceTypeEnum.IMGS, pictureKey);
}
return null;
}
public FeedbackDTO getDetail(Long uid) {
Optional<Feedback> feedbackOptional = feedbackRepo.getByUid(uid);
AssertHelper.isTrue(feedbackOptional.isPresent(), "记录不存在");
return converDto(feedbackOptional.get());
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.ProductController;
import cn.benewtech.agent.admin.dto.ProductDTO;
import cn.benewtech.agent.admin.input.ProductFormInput;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.provider.cdn.QiniuCdnProvider;
import cn.benewtech.tower.provider.cdn.ResourceTypeEnum;
import cn.benewtech.tower.utils.common.AssertHelper;
import com.google.common.collect.Lists;
import com.querydsl.core.types.dsl.BooleanExpression;
import cn.benewtech.agent.domain.Product;
import cn.benewtech.agent.domain.QProduct;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.ProductRepository;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepo;
/*@Autowired
private QiniuCdnProvider qiniuCdnProvider;*/
public SimplePage<ProductDTO> pageQuery(ProductController.ProductQueryParam param, PageAdapter page) {
SimplePage<Product> pageResult = productRepo.pageQuery(param, page);
List<Product> datas = pageResult.getDatas();
List<ProductDTO> dtos = Lists.newArrayList();
for (Product data : datas) {
ProductDTO dto = new ProductDTO();
BeanUtils.copyProperties(data, dto);
// dto.setCover(qiniuCdnProvider.getResourceUrl(ResourceTypeEnum.IMGS, data.getCoverKey()));
dtos.add(dto);
}
return SimplePage.valueOf(pageResult.getCount(), dtos);
}
public void add(ProductFormInput input) {
Product product = new Product();
BeanUtils.copyProperties(input, product);
product.setUid(productRepo.nextLongUid());
productRepo.insert(product);
}
public ProductDTO edit(Long uid, ProductFormInput input) {
input.setUpdated(new Date());
QProduct qb = QProduct.product;
BooleanExpression expression = qb.uid.eq(uid);
Optional<Product> productOptional = productRepo.findOne(expression);
AssertHelper.isTrue(productOptional.isPresent(), "产品不存在");
Product product = productOptional.get();
productRepo.update(product.getId(), input);
ProductDTO dto = new ProductDTO();
BeanUtils.copyProperties(input, dto);
return dto;
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.domain.RebateAccountLog;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.repository.primary.RebateAccountLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
@Service
public class RebateAccountLogService {
@Autowired
private RebateAccountLogRepository rebateAccountLogRepo;
public void recordLog(Long agentUid, BigDecimal rebateAmount, FeeTypeEnum feeType, Long businessUid, BusTypeEnum busType, Date now, Long rebateAccountUid) {
RebateAccountLog rebateAccountLog = new RebateAccountLog();
rebateAccountLog.setUid(rebateAccountLogRepo.nextLongUid());
rebateAccountLog.setAgentUid(agentUid);
rebateAccountLog.setFee(rebateAmount);
rebateAccountLog.setFeeType(feeType);
rebateAccountLog.setBusType(busType);
rebateAccountLog.setRefUid(businessUid);
rebateAccountLog.setRebateAccountUid(rebateAccountUid);
rebateAccountLog.setCreated(now);
rebateAccountLogRepo.insert(rebateAccountLog);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.domain.QRebateAccount;
import cn.benewtech.agent.domain.RebateAccount;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.repository.primary.RebateAccountRepository;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.DateHelper;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class RebateAccountService {
private static final int RECHARGE_EXPIRES_DAY = 30;
@Autowired
private RebateAccountRepository rebateAccountRepo;
@Autowired
private RebateAccountLogService rebateAccountLogService;
public Map<FeeTypeEnum, List<RebateAccount>> mapValidByFeeItem(Long agentUid) {
List<RebateAccount> rebateAccounts = listValidItems(agentUid);
return rebateAccounts.stream()
.collect(Collectors.groupingBy(RebateAccount::getFeeType));
}
public List<RebateAccount> listValidItems(Long agentUid) {
QRebateAccount qRebateAccount = QRebateAccount.rebateAccount;
BooleanExpression rebateAccountQb = qRebateAccount.agentUid.eq(agentUid)
.and(qRebateAccount.expires.gt(new Date()).or(qRebateAccount.expires.isNull()))
.and(qRebateAccount.unactivatedFee.gt(BigDecimal.ZERO));
return rebateAccountRepo.listQuery(rebateAccountQb);
}
public void increase(Long agentUid, BigDecimal rebateAmount, FeeTypeEnum feeType,
Long businessUid, BusTypeEnum busType) {
if (BigDecimal.ZERO.compareTo(rebateAmount) == 0) {
return;
}
Date now = new Date();
Date expires = DateHelper.plusDurationOfDate(now, Duration.ofDays(RECHARGE_EXPIRES_DAY));
RebateAccount rebateAccount = new RebateAccount();
Long rebateAccountUid = rebateAccountRepo.nextLongUid();
rebateAccount.setUid(rebateAccountUid);
rebateAccount.setAgentUid(agentUid);
rebateAccount.setFee(rebateAmount);
rebateAccount.setUnactivatedFee(FeeTypeEnum.FITTING.equals(feeType) ? rebateAmount : BigDecimal.ZERO);
rebateAccount.setFeeType(feeType);
rebateAccount.setExpires(FeeTypeEnum.FITTING.equals(feeType) ? expires : null);
rebateAccount.setRebateType(busType);
rebateAccount.setCreated(now);
rebateAccountRepo.insert(rebateAccount);
rebateAccountLogService.recordLog(agentUid, rebateAmount, feeType, businessUid, busType, now, rebateAccountUid);
}
public void activate(Long agentUid, BigDecimal amount, FeeTypeEnum feeType, Long uid, BusTypeEnum recharge) {
AssertHelper.isTrue(FeeTypeEnum.FITTING.equals(feeType), "只有配件返利才可以激活");
List<RebateAccount> rebateAccounts = listValidItems(agentUid);
rebateAccounts.sort(Comparator.comparing(RebateAccount::getExpires));
BigDecimal needActivateFee = new BigDecimal(amount.toString());
for (RebateAccount rebateAccount : rebateAccounts) {
BigDecimal unactivatedFee = rebateAccount.getUnactivatedFee();
if (unactivatedFee.compareTo(needActivateFee) <= 0) {
rebateAccount.setUnactivatedFee(BigDecimal.ZERO);
needActivateFee.subtract(unactivatedFee);
}
}
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.dto.RebateConfigDTO;
import cn.benewtech.agent.admin.input.RebateConfigFormInput;
import com.querydsl.core.types.dsl.BooleanExpression;
import cn.benewtech.agent.domain.QRebateConfig;
import cn.benewtech.agent.domain.RebateConfig;
import cn.benewtech.agent.enums.RebateTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.RebateConfigRepository;
import java.util.Date;
@Service
public class RebateConfigService {
@Autowired
private RebateConfigRepository rebateConfigRepo;
public void createOrUpdate(RebateConfigFormInput input) {
RebateTypeEnum rebateType = input.getRebateType();
RebateConfig newConfig = new RebateConfig();
BeanUtils.copyProperties(input, newConfig);
newConfig.setUid(rebateConfigRepo.nextLongUid());
newConfig.setCreated(new Date());
Integer version = getNextVersion(rebateType);
newConfig.setVersion(version);
rebateConfigRepo.insert(newConfig);
}
public RebateConfigDTO getDetail(RebateTypeEnum rebateType) {
RebateConfig config = getByRebateType(rebateType);
RebateConfigDTO dto = new RebateConfigDTO();
BeanUtils.copyProperties(config, dto);
return dto;
}
private Integer getNextVersion(RebateTypeEnum rebateType) {
RebateConfig existConfig = getByRebateType(rebateType);
if (existConfig != null) {
return existConfig.getVersion() + 1;
}
return 0;
}
private RebateConfig getByRebateType(RebateTypeEnum rebateType) {
QRebateConfig qb = QRebateConfig.rebateConfig;
BooleanExpression expression = qb.rebateType.eq(rebateType);
return rebateConfigRepo.findOne(expression).orElse(null);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.RebateRecordController;
import cn.benewtech.agent.admin.dto.RebateRecordDTO;
import cn.benewtech.agent.admin.input.RebateRecordFormInput;
import cn.benewtech.agent.domain.Agent;
import cn.benewtech.agent.domain.QRebateRecord;
import cn.benewtech.agent.domain.RebateRecord;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.repository.primary.RebateRecordRepository;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.CollectionHelper;
import com.google.common.collect.Lists;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class RebateRecordService {
@Autowired
private RebateRecordRepository rebateRecordRepo;
@Autowired
private AgentService agentService;
public SimplePage<RebateRecordDTO> pageQuery(RebateRecordController.RebateRecordQueryParam param, PageAdapter page) {
SimplePage<RebateRecord> pageResult = rebateRecordRepo.pageQuery(param, page);
List<RebateRecord> datas = pageResult.getDatas();
List<Long> agentUids = CollectionHelper.map(datas, RebateRecord::getAgentUid);
Map<Long, Agent> agentMap = agentService.mapByUids(agentUids);
List<RebateRecordDTO> dtos = Lists.newArrayList();
for (RebateRecord data : datas) {
RebateRecordDTO dto = new RebateRecordDTO();
BeanUtils.copyProperties(data, dto);
Agent agent = agentMap.get(data.getAgentUid());
dto.setSalesman(agent.getSalesman());
dto.setTotalRebate(totalRebate(data));
dtos.add(dto);
}
return SimplePage.valueOf(pageResult.getCount(), dtos);
}
private Double totalRebate(RebateRecord data) {
Double saleRebate = data.getSaleRebate();
Double activationCntRebate = data.getActivationCntRebate();
Double activationIncrRebate = data.getActivationIncrRebate();
Double cooperationRebate = data.getCooperationRebate();
Double evaluateRebate = data.getEvaluateRebate();
return (saleRebate + activationCntRebate +
activationIncrRebate + cooperationRebate + evaluateRebate);
}
public void update(Long uid, RebateRecordFormInput input) {
RebateRecord rebateRecord = getByUid(uid);
AssertHelper.isTrue(rebateRecord != null, "记录不存在");
rebateRecordRepo.update(rebateRecord.getId(), input);
}
public void approve(Long uid) {
RebateRecord rebateRecord = getByUid(uid);
AssertHelper.isTrue(rebateRecord != null, "记录不存在");
Update update = new Update();
update.set("status", ApproveStatusEnum.PASS);
update.set("updated", new Date());
rebateRecordRepo.update(rebateRecord.getId(), update);
//todo 返利到账,经销商钱包+
}
private RebateRecord getByUid(Long uid) {
QRebateRecord qb = QRebateRecord.rebateRecord;
BooleanExpression expression = qb.uid.eq(uid);
return rebateRecordRepo.findOne(expression).orElse(null);
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.dto.RechargeConfigDTO;
import cn.benewtech.agent.admin.input.RechargeConfigFormInput;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.utils.common.AssertHelper;
import com.google.common.collect.Lists;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import cn.benewtech.agent.domain.QRechargeConfig;
import cn.benewtech.agent.domain.RechargeConfig;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.enums.StatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.benewtech.agent.repository.primary.RechargeConfigRepository;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
@Slf4j
public class RechargeConfigService {
private static final Integer INITIAL_VERSION = 1;
@Autowired
private RechargeConfigRepository rechargeConfigRepo;
public void add(RechargeConfigFormInput input) {
Date now = new Date();
RechargeConfig rechargeConfig = new RechargeConfig();
BeanUtils.copyProperties(input, rechargeConfig);
rechargeConfig.setUid(rechargeConfigRepo.nextLongUid());
rechargeConfig.setVersion(INITIAL_VERSION);
rechargeConfig.setCreated(now);
rechargeConfigRepo.save(rechargeConfig);
}
public void createNewVersion(Long uid, RechargeConfigFormInput input) {
Optional<RechargeConfig> configOptional = rechargeConfigRepo.getByUid(uid);
RechargeConfig rechargeConfig = configOptional.get();
Date now = new Date();
RechargeConfig newConfig = new RechargeConfig();
BeanUtils.copyProperties(input, newConfig);
Integer newVersion = rechargeConfig.getVersion() + 1;
newConfig.setUid(rechargeConfigRepo.nextLongUid());
newConfig.setVersion(newVersion);
newConfig.setCreated(now);
newConfig.setUpdated(now);
rechargeConfigRepo.save(newConfig);
}
public SimplePage<RechargeConfigDTO> pageQuery(PageAdapter page) {
QRechargeConfig rechargeConfig = QRechargeConfig.rechargeConfig;
Predicate predicate = rechargeConfig.uid.gt(0l);
SimplePage<RechargeConfig> simplePage = rechargeConfigRepo.pageQuery(page, predicate);
List<RechargeConfig> configs = simplePage.getDatas();
List<RechargeConfigDTO> dtos = Lists.newArrayList();
configs.forEach(config -> {
RechargeConfigDTO dto = new RechargeConfigDTO();
BeanUtils.copyProperties(config, dto);
dtos.add(dto);
});
return SimplePage.valueOf(simplePage.getCount(), dtos);
}
public void checkConfigExistByType(FeeTypeEnum feeType) {
QRechargeConfig qRechargeConfig = QRechargeConfig.rechargeConfig;
BooleanExpression expression = qRechargeConfig.feeType.eq(feeType)
.and(qRechargeConfig.status.eq(StatusEnum.NORMAL));
long count = rechargeConfigRepo.count(expression);
AssertHelper.isTrue(count <= 0, String.format("%s类型设置已存在,请不要重复创建", feeType.getDesc()));
}
}
package cn.benewtech.agent.admin.servie;
import cn.benewtech.agent.admin.controller.RechargeController;
import cn.benewtech.agent.admin.dto.RechargeRecordDTO;
import cn.benewtech.agent.admin.input.ApproveInput;
import cn.benewtech.agent.domain.Account;
import cn.benewtech.agent.domain.RebateAccount;
import cn.benewtech.agent.domain.RechargeRecord;
import cn.benewtech.agent.enums.ApproveStatusEnum;
import cn.benewtech.agent.enums.BusTypeEnum;
import cn.benewtech.agent.enums.FeeItemTypeEnum;
import cn.benewtech.agent.enums.FeeTypeEnum;
import cn.benewtech.agent.repository.primary.RebateAccountRepository;
import cn.benewtech.agent.repository.primary.RechargeRecordRepository;
import cn.benewtech.tower.beans.PageAdapter;
import cn.benewtech.tower.beans.SimplePage;
import cn.benewtech.tower.provider.cdn.QiniuCdnProvider;
import cn.benewtech.tower.provider.cdn.ResourceTypeEnum;
import cn.benewtech.tower.utils.common.AssertHelper;
import cn.benewtech.tower.utils.common.CollectionHelper;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
public class RechargeService {
@Autowired
private RechargeRecordRepository rechargeRecordRepo;
@Autowired
private RebateAccountRepository rebateAccountRepo;
@Autowired
private AccountService accountService;
@Autowired
private RebateAccountService rebateAccountService;
@Autowired
private ApprovalLogService approvalLogService;
@Autowired
private QiniuCdnProvider qiniuProvider;
public SimplePage<RechargeRecordDTO> pageQuery(RechargeController.RechargeRecordQueryParam param,
PageAdapter page) {
SimplePage<RechargeRecord> pageResult = rechargeRecordRepo.pageQuery(param, page);
List<RechargeRecord> datas = pageResult.getDatas();
List<RechargeRecordDTO> dtos = Lists.newArrayList();
for (RechargeRecord data : datas) {
RechargeRecordDTO dto = convertDT0(data);
dtos.add(dto);
}
return SimplePage.valueOf(pageResult.getCount(), dtos);
}
public RechargeRecordDTO getDetail(Long uid) {
RechargeRecord rechargeRecord = getByUid(uid);
Long agentUid = rechargeRecord.getAgentUid();
RechargeRecordDTO dto = convertDT0(rechargeRecord);
List<RechargeRecordDTO.AccountSnapshot> accountDtos = calculateBalance(rechargeRecord, agentUid);
dto.setAccountSnapshot(accountDtos);
return dto;
}
private RechargeRecord getByUid(Long uid) {
Optional<RechargeRecord> rechargeRecordOptional = rechargeRecordRepo.getByUid(uid);
AssertHelper.isTrue(rechargeRecordOptional.isPresent(), "记录不存在");
return rechargeRecordOptional.get();
}
/**
* 计算余额
* @param rechargeRecord
* @param agentUid
* @return
*/
private List<RechargeRecordDTO.AccountSnapshot> calculateBalance(RechargeRecord rechargeRecord, Long agentUid) {
Map<FeeTypeEnum, Account> accountMap = accountService.mapByFeeType(agentUid);
Map<FeeTypeEnum, List<RebateAccount>> rebateAccountMap = rebateAccountService.mapValidByFeeItem(agentUid);
List<RechargeRecordDTO.AccountSnapshot> accountDtos = Lists.newArrayList();
for (FeeTypeEnum feeType : FeeTypeEnum.values()) {
RechargeRecordDTO.AccountSnapshot accountSnapshot = new RechargeRecordDTO.AccountSnapshot();
accountSnapshot.setFeeType(feeType);
accountSnapshot.setRechargeFee(rechargeRecord.getFee());
Account accountBalance = accountMap.get(feeType);
accountSnapshot.setBeforeFee(accountBalance.getFee());
if (FeeTypeEnum.FITTING.equals(feeType)) {
accountSnapshot.setRebateFee(rechargeRecord.getFittingRebate());
}
if (FeeTypeEnum.EXPRESS.equals(feeType)) {
accountSnapshot.setRebateFee(rechargeRecord.getExpressRebate());
}
List<RebateAccount> rebateBalances = rebateAccountMap.get(feeType);
if (!CollectionHelper.isEmpty(rebateBalances)) {
BigDecimal rebatBalance = BigDecimal.ZERO;
rebateBalances.stream()
.forEach(a -> rebatBalance.add(a.getUnactivatedFee()));
accountSnapshot.setBeforeRebate(rebatBalance);
}
accountDtos.add(accountSnapshot);
}
return accountDtos;
}
private RechargeRecordDTO convertDT0(RechargeRecord record) {
RechargeRecordDTO dto = new RechargeRecordDTO();
BeanUtils.copyProperties(record, dto);
dto.setSnapshot(qiniuProvider.getResourceUrl(ResourceTypeEnum.IMGS, record.getSnapshotKey()));
return dto;
}
@Transactional
public void approve(Long uid, ApproveInput approveInput, Long userId) {
RechargeRecord record = getByUid(uid);
proceedPay(record, approveInput.getApproveStatus());
Update update = new Update();
update.set("status", approveInput.getApproveStatus());
update.set("updated", new Date());
rechargeRecordRepo.update(record.getId(), record);
approvalLogService.saveLog(approveInput, userId, record);
}
private void proceedPay(RechargeRecord record, ApproveStatusEnum approveStatus) {
if (!ApproveStatusEnum.PASS.equals(approveStatus)) {
return;
}
Long agentUid = record.getAgentUid();
//审批通过,钱包余额+ 返利余额 + 审批记录 => 修改状态
FeeTypeEnum feeType = record.getFeeType();
BigDecimal fee = record.getFee(); //充值金额
accountService.deduct(agentUid, fee, feeType, FeeItemTypeEnum.ACTUAL, record.getUid(), BusTypeEnum.RECHARGE);
BigDecimal fittingRebate = record.getFittingRebate();
rebateAccountService.increase(agentUid, fittingRebate, FeeTypeEnum.FITTING, record.getUid(), BusTypeEnum.RECHARGE);
BigDecimal expressRebate = record.getExpressRebate();
rebateAccountService.increase(agentUid, expressRebate, FeeTypeEnum.EXPRESS, record.getUid(), BusTypeEnum.RECHARGE);
accountService.deduct(agentUid, expressRebate, FeeTypeEnum.EXPRESS, FeeItemTypeEnum.REBATE,
record.getUid(), BusTypeEnum.RECHARGE);
//todo 如果是货款充值,还要激活返利余额
if (FeeTypeEnum.FITTING.equals(feeType)) {
//todo 读取配置 3/7
BigDecimal canActivateRebate = getCanActivateRebate(fee);
//记录交易记录明细
//
}
}
private BigDecimal getCanActivateRebate(BigDecimal fee) {
//todo 后台设置返利激活比例?
return fee.multiply(new BigDecimal(0.3));
}
}
package cn.benewtech.rebate;
import cn.benewtech.agent.admin.AgentAdminApplication;
import cn.benewtech.agent.admin.servie.RebateAccountService;
import cn.benewtech.agent.domain.RebateAccount;
import cn.benewtech.agent.repository.primary.RebateAccountRepository;
import cn.benewtech.tower.utils.common.DateHelper;
import cn.benewtech.tower.utils.common.JsonHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AgentAdminApplication.class)
public class RebateAccountTest {
@Autowired
private RebateAccountRepository rebateAccountRepo;
@Autowired
private RebateAccountService rebateAccountService;
@Test
public void testAdd(){
RebateAccount rebateAccount = new RebateAccount();
rebateAccount.setUid(4l);
rebateAccount.setAgentUid(1l);
rebateAccount.setFee(new BigDecimal(100));
rebateAccount.setUnactivatedFee(new BigDecimal(19));
rebateAccount.setExpires(null);
rebateAccount.setCreated(new Date());
rebateAccountRepo.insert(rebateAccount);
}
@Test
public void testUpdate(){
Optional<RebateAccount> accountOptional = rebateAccountRepo.getByUid(1l);
RebateAccount rebateAccount = accountOptional.get();
rebateAccount.setExpires(new Date());
rebateAccountRepo.save(rebateAccount);
}
@Test
public void testQuery(){
List<RebateAccount> rebateAccounts = rebateAccountService.listValidItems(1l);
rebateAccounts.sort(Comparator.comparing(RebateAccount::getExpires));
for (RebateAccount rebateAccount : rebateAccounts) {
System.out.println(JsonHelper.writeValueAsString(rebateAccount));
}
System.out.println(rebateAccounts);
}
}
spring.application.name=resources-admin
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
eureka.client.enabled=false
eureka.client.serviceUrl.defaultZone=${EUREKA_URI:http://localhost:8761/eureka}
eureka.client.eureka-server-connect-timeout-seconds=5
eureka.client.eureka-server-read-timeout-second = 8
eureka.client.register-with-eureka=false
eureka.instance.preferIpAddress=true
eureka.client.fetch-registry=false
app.id=resources
apollo.meta=http://localhost:8280
apollo.bootstrap.enabled = true
apollo.bootstrap.namespaces = application,admin
apollo.cacheDir=/data/deploy/cache
shell.python.path=/usr/local/bin/python3
server.port=9070
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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