Compare commits

..

1 Commits

Author SHA1 Message Date
Shaun Chyxion
e85857702c
!3 merge 0.0.3 to master
Merge pull request !3 from Shaun Chyxion/feature/v0.0.3
2022-05-22 08:13:26 +00:00
359 changed files with 12316 additions and 6075 deletions

1
.gitignore vendored
View File

@ -30,6 +30,7 @@
!.gitkeep
*.iml
# ember-try
.node_modules.ember-try/
bower.json.ember-try

2
server/.gitignore vendored
View File

@ -7,6 +7,4 @@ target/
bin/
crm/src/main/resources/static/
crm/src/main/resources/application.properties
crm/src/main/resources/application.yml
crm/src/main/resources/log4j2.xml
crm/src/main/resources/logback.xml

View File

@ -6,11 +6,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>crm</artifactId>
<name>Ambition CRM</name>
<packaging>jar</packaging>
<parent>
<groupId>com.pudonghot.ambition</groupId>
<artifactId>lemo-crm</artifactId>
<version>${revision}</version>
<artifactId>ambition-crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<properties>
@ -29,23 +31,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-web-controller</artifactId>
</dependency>
<!-- Log -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>

View File

@ -1,35 +1,16 @@
package com.pudonghot.ambition.crm;
import lombok.val;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Mar 05, 2017 14:40:30
*/
@EnableAsync
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ImportResource("classpath*:spring/spring-*.xml")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class AmbitionCRM implements WebMvcConfigurer {
public class AmbitionCRM {
/**
* @param args start args
@ -37,28 +18,4 @@ public class AmbitionCRM implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(AmbitionCRM.class, args);
}
@Bean("exportTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
val threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(2);
threadPoolTaskExecutor.setMaxPoolSize(8);
threadPoolTaskExecutor.setKeepAliveSeconds(16);
threadPoolTaskExecutor.setQueueCapacity(64);
return threadPoolTaskExecutor;
}
/**
* {@inheritDoc}
*/
@Override
public void extendMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.forEach(converter -> {
if (converter instanceof MappingJackson2HttpMessageConverter) {
val supportedMediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
supportedMediaTypes.add(MediaType.valueOf("text/event-stream"));
((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(supportedMediaTypes);
}
});
}
}

View File

@ -2,14 +2,18 @@ package com.pudonghot.ambition.crm.auth;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.ViewModel;
import org.apache.shiro.subject.Subject;
import me.chyxion.tigon.shiro.AuthCallback;
import me.chyxion.tigon.shiro.model.AuthUser;
import javax.servlet.http.HttpServletRequest;
import me.chyxion.tigon.shiro.model.AuthInfo;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Service;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.AuthenticationException;
import com.pudonghot.ambition.crm.auth.model.Principal;
import com.pudonghot.ambition.crm.service.AuthLogService;
import com.pudonghot.ambition.crm.util.HttpServletRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -26,40 +30,40 @@ import com.pudonghot.ambition.crm.form.create.AuthFailedLogFormForCreate;
*/
@Slf4j
@Service
public class AuthCallbackSupport implements AuthCallback, SessionAbility {
public class AuthCallbackSupport implements AuthCallback {
@Autowired
private AuthLogService authLogService;
@Autowired
private AuthFailedLogService authLogFailedService;
@Autowired
private HttpServletRequest request;
/**
* {@inheritDoc}
*/
@Override
public void onSuccessfulLogin(final AuthenticationToken token,
final AuthenticationInfo info,
final Subject subject) {
public void onSuccessfulLogin(AuthenticationToken token,
AuthenticationInfo info, Subject subject) {
val principal = (Principal) subject.getPrincipal();
val ws = (WebSubject) subject;
val session = ws.getSession(false);
val request = (HttpServletRequest) ws.getServletRequest();
// val authUser = new AuthUser<ViewModel<User>>();
val authUser = new AuthUser<ViewModel<User>>();
val ip = HttpServletRequestUtils.getClientIP(request);
// authUser.setAttr("ip", ip);
authUser.setAttr("ip", ip);
val userAgent = request.getHeader("User-Agent");
// authUser.setAttr("userAgent", userAgent);
// val user = (ViewModel<User>) ((AuthInfo) info).getExtra();
val userId = principal.getUserId();
// authUser.setUserId(userId);
// authUser.setUser(user);
// log.info("Save Auth User [{}] To Session [{}].", user, session.getId());
// authUser.save(session);
authUser.setAttr("userAgent", userAgent);
val user = (ViewModel<User>) ((AuthInfo) info).getExtra();
val userId = user.getData().getId();
authUser.setUserId(userId);
authUser.setUser(user);
log.info("Save Auth User [{}] To Session [{}].", user, session.getId());
authUser.save(session);
val alForm = new AuthLogFormForCreate();
alForm.setUserId(principal.getEmployeeId());
alForm.setUserId(userId);
alForm.setIp(ip);
alForm.setUserAgent(userAgent);
alForm.unlock();
alForm.setCreatedBy(userId);
authLogService.create(alForm);
// HttpServletResponse response = (HttpServletResponse) ws.getServletResponse();
@ -70,14 +74,16 @@ public class AuthCallbackSupport implements AuthCallback, SessionAbility {
* {@inheritDoc}
*/
@Override
public void onFailedLogin(final AuthenticationToken token,
final AuthenticationException ae,
final Subject subject) {
public void onFailedLogin(AuthenticationToken token,
AuthenticationException ae,
Subject subject) {
val loginId = (String) token.getPrincipal();
val password = new String((char[]) token.getCredentials());
log.info("Login Id [{}] Password [{}] Login Failed.", loginId, password);
val ws = (WebSubject) subject;
val request = (HttpServletRequest) ws.getServletRequest();
val form = new AuthFailedLogFormForCreate();
form.setLoginId(loginId);
form.setPassword(password);
@ -91,7 +97,8 @@ public class AuthCallbackSupport implements AuthCallback, SessionAbility {
*/
@Override
public void beforeLogout(final Subject subject) {
val session = subject.getSession(false);
val ws = (WebSubject) subject;
val session = ws.getSession(false);
if (session != null) {
log.warn("Session [{}] Logout.", session);
}

View File

@ -1,8 +1,8 @@
package com.pudonghot.ambition.crm.auth;
import lombok.val;
import java.util.*;
import lombok.val;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.shiro.AuthRealm;
import org.apache.commons.lang3.ArrayUtils;
@ -10,7 +10,6 @@ import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.shiro.model.Credential;
import org.apache.shiro.authc.LockedAccountException;
import com.pudonghot.ambition.crm.auth.model.Principal;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
@ -22,7 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired;
* Apr 7, 2015 4:14:20 PM
*/
@Service
public class AuthRealmSupport implements AuthRealm<Principal, String> {
public class AuthRealmSupport extends AuthRealm {
@Autowired
private UserService userService;
@ -31,19 +30,18 @@ public class AuthRealmSupport implements AuthRealm<Principal, String> {
* {@inheritDoc}
*/
@Override
public Credential credential(final Principal principal) {
public Credential credential(Object principal) {
Credential credential = null;
val userViewModel =
userService.findViewModel(principal.getUserId());
userService.findViewModel(new Search(User.EMPLOYEE_ID, principal));
if (userViewModel != null) {
val admin = userViewModel.getData();
if (!admin.getEnabled()) {
throw new LockedAccountException("Account locked");
User admin = userViewModel.getData();
if (!admin.isEnabled()) {
throw new LockedAccountException("账户已禁用,请联系管理员");
}
credential = new Credential(
admin.getPassword(),
admin.getId());
credential.setExtra(userViewModel);
admin.getId()).setExtra(userViewModel);
}
return credential;
}
@ -52,23 +50,24 @@ public class AuthRealmSupport implements AuthRealm<Principal, String> {
* {@inheritDoc}
*/
@Override
public boolean credentialMatch(final String password, Credential credential) {
public boolean credentialMatch(Object password, Credential credential) {
return userService.validatePassword(
((ViewModel<User>) credential.getExtra()).getData().getId(), password);
((ViewModel<User>) credential.getExtra()).getData().getId(),
new String((char[])password));
}
/**
* {@inheritDoc}
*/
@Override
public Collection<String> roles(final Principal principal) {
val user = userService.find(principal.getUserId());
public Collection<String> roles(Object principal) {
val user = userService.find(new Search(User.EMPLOYEE_ID, principal));
val roles = new ArrayList<String>(4);
if (user.isAdmin()) {
roles.add(User.ROLE_ADMIN);
}
val account = user.getAccount();
if (ArrayUtils.contains(new String[] {User.ROLE_LELI, User.ROLE_DONGHUANG}, account)) {
if (ArrayUtils.contains(new String[] {User.ROLE_LELI, User.ROLE_CHYXION}, account)) {
roles.add(account);
}
return roles;

View File

@ -1,27 +0,0 @@
package com.pudonghot.ambition.crm.auth;
import javax.servlet.*;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.core.annotation.Order;
/**
* @author Donghuang <br>
* Nov 17, 2019 16:30:41
*/
@Order
@Slf4j
@Component
public class AuthRequestFilter implements Filter {
/**
* {@inheritDoc}
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.debug("Wrap HTTP servlet request as AUTH request.");
filterChain.doFilter(new AuthRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
}

View File

@ -1,63 +0,0 @@
package com.pudonghot.ambition.crm.auth;
import lombok.val;
import java.util.*;
import java.util.function.Function;
import com.pudonghot.ambition.crm.model.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author Donghuang <br>
* Nov 17, 2019 16:05:39
*/
public class AuthRequestWrapper extends HttpServletRequestWrapper implements SessionAbility {
private static Map<String, Function<SessionAbility, ?>> AUTH_ELS = new HashMap<>();
static {
AUTH_ELS.put(User.CREATED_BY, SessionAbility::getUserId);
AUTH_ELS.put(User.UPDATED_BY, SessionAbility::getUserId);
}
/**
* {@inheritDoc}
*/
public AuthRequestWrapper(final HttpServletRequest request) {
super(request);
}
/**
* {@inheritDoc}
*/
@Override
public Enumeration<String> getParameterNames() {
final Enumeration<String> paramNames = super.getParameterNames();
if (isAuthenticated()) {
val params = Collections.list(paramNames);
params.addAll(AUTH_ELS.keySet());
return Collections.enumeration(params);
}
return paramNames;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getParameterValues(final String name) {
val getter = AUTH_ELS.get(name);
return getter != null ? new String[] { getParam(getter) } : super.getParameterValues(name);
}
/**
* get params
* @param getter getter
* @return param string or null
*/
private String getParam(final Function<SessionAbility, ?> getter) {
val param = getter.apply(this);
return param != null ?
(param instanceof String ?
(String) param : String.valueOf(param)) : null;
}
}

View File

@ -1,88 +0,0 @@
package com.pudonghot.ambition.crm.auth;
import lombok.val;
import org.apache.shiro.SecurityUtils;
import me.chyxion.tigon.kit.json.JsonService;
import com.pudonghot.ambition.crm.auth.model.Principal;
/**
* @author Donghuang
* @date Aug 12, 2020 10:13:43
*/
public interface SessionAbility {
/**
* get session id
*
* @return session id
*/
default String getSessionId() {
return (String) SecurityUtils.getSubject().getSession(false).getId();
}
/**
* get user id
*
* @return user id
*/
default String getUserId() {
return getPrincipal().getUserId();
}
/**
* get user name
*
* @return user name
*/
default String getName() {
return getPrincipal().getName();
}
/**
* get auth account
*
* @return auth account
*/
default String getAuthAccount() {
return getPrincipal().getAccount();
}
/**
* get auth principal
*
* @return session
*/
default Principal getPrincipal() {
val principal = SecurityUtils.getSubject().getPrincipal();
if (principal instanceof Principal) {
return (Principal) principal;
}
if (principal != null) {
return JsonService.getInstance().convert(principal, Principal.class);
}
throw new IllegalStateException(
"No principal found in security subject");
}
/**
* return true if user is authenticated
*
* @return true if user is authenticated
*/
default boolean isAuthenticated() {
return SecurityUtils.getSubject().isAuthenticated();
}
/**
* return true if user is admin
*
* @return true if user is admin
*/
default boolean isAdmin() {
return getPrincipal().getAdmin();
}
}

View File

@ -1,44 +0,0 @@
package com.pudonghot.ambition.crm.auth.model;
import lombok.Getter;
import lombok.AllArgsConstructor;
import org.apache.shiro.authc.HostAuthenticationToken;
/**
* @author Donghuang
* @date Aug 12, 2020 20:52:03
*/
@Getter
@AllArgsConstructor
public class AuthToken implements HostAuthenticationToken {
private static final long serialVersionUID = 1L;
/**
* principal
*/
private final Principal principal;
/**
* password
*/
private final String password;
/**
* The location from where the login attempt occurs, or <code>null</code> if not known or explicitly
* omitted.
*/
private String host;
public AuthToken(final Principal principal, final String password) {
this(principal, password, null);
}
/**
* {@inheritDoc}
*/
@Override
public Object getCredentials() {
return password;
}
}

View File

@ -1,39 +0,0 @@
package com.pudonghot.ambition.crm.auth.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* @author Donghuang
* @date Aug 12, 2020 20:47:35
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
public class Principal implements Serializable {
private static final long serialVersionUID = 1L;
// Properties
private String userId;
private String account;
private String employeeId;
private String mobile;
private String email;
private String name;
private String enName;
private String gender;
private Boolean admin;
/**
* 扩展属性
*/
private Serializable attr;
public Principal(final String account) {
this.account = account;
}
}

View File

@ -1,42 +0,0 @@
package com.pudonghot.ambition.crm.common.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* May 17, 2016 2:49:31 PM
*/
@Slf4j
@Order(32)
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class BaseControllerAdvice {
private ByteArrayMultipartFileEditor bamfe =
new ByteArrayMultipartFileEditor() {
/**
* {@inheritDoc}
*/
@Override
public void setValue(Object value) {
super.setValue(value instanceof MultipartFile ||
value instanceof byte[] ? value : null);
}
};
@InitBinder
public void registerCustomEditors(WebDataBinder binder, ServletWebRequest request) {
// PropertyEditorSupport
binder.registerCustomEditor(byte[].class, bamfe);
}
}

View File

@ -1,21 +0,0 @@
package com.pudonghot.ambition.crm.common.request;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.web.controller2.request.BaseListCtrlrReqApi;
/**
* @author Donghuang
* @date Jun 18, 2022 13:27:22
*/
@Getter
@Setter
public class BaseListCtrlrReq implements BaseListCtrlrReqApi {
private static final long serialVersionUID = 1L;
private Integer start;
private Integer limit;
private String search;
private String filters;
private String orders;
}

View File

@ -5,19 +5,23 @@ import java.util.*;
import java.net.URLDecoder;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.M1;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.chyxion.tigon.mybatis.Search;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.util.TypeUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.CharEncoding;
import me.chyxion.tigon.kit.json.JsonService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
@ -31,9 +35,6 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
@Validated
public abstract class AbstractBaseController {
@Autowired
private JsonService jsonService;
/**
* build sql like value
* @param value
@ -176,10 +177,8 @@ public abstract class AbstractBaseController {
search.limit(limit);
}
if (StringUtils.isNotBlank(strSearch)) {
search.attr("hasSearch", true);
val orSearch = new Search();
for (val col : searchCols()) {
for (final String col : searchCols()) {
orSearch.or(new Search().like(col, decodeLike(strSearch)));
}
search.and(orSearch);
@ -198,7 +197,7 @@ public abstract class AbstractBaseController {
final List<Object[]> criteria;
try {
criteria = jsonService.parseArray(decodeParam(strCriteria), Object[].class);
criteria = JSON.parseArray(decodeParam(strCriteria), Object[].class);
}
catch (Exception e) {
throw new IllegalStateException(
@ -207,15 +206,14 @@ public abstract class AbstractBaseController {
for (val criterion : criteria) {
if (criterion.length == 3) {
val field = (String) criterion[0];
final String field = (String) criterion[0];
if (StringUtils.isNotBlank(field)) {
val colProp = criterionCol(field);
val col = colProp.getKey();
if (StringUtils.isNotBlank(col)) {
val op = (String) criterion[1];
val val = JsonService.getInstance().convert(criterion[2], colProp.getValue());
val val = TypeUtils.castToJavaBean(criterion[2], colProp.getValue());
if (StringUtils.isNotBlank(op) &&
val != null && val instanceof String ?
StringUtils.isNotBlank((String) val) : true) {
@ -260,9 +258,9 @@ public abstract class AbstractBaseController {
return search;
}
protected Map<String, Object> filters(String filters) {
protected JSONObject filters(String filters) {
try {
return jsonService.parse(decodeParam(filters), Map.class);
return JSON.parseObject(decodeParam(filters));
}
catch (Exception e) {
throw new IllegalStateException(
@ -277,10 +275,10 @@ public abstract class AbstractBaseController {
return defaultFilter(search);
}
val joFilters = filters(strFilters);
final JSONObject joFilters = filters(strFilters);
for (val filter : joFilters.entrySet()) {
val field = filter.getKey();
val colProp = filterCol(field);
val colProp = filterCol(filter.getKey());
if (colProp != null) {
val col = colProp.getKey();
val filterVal = filter.getValue();
@ -289,11 +287,9 @@ public abstract class AbstractBaseController {
continue;
}
// type convert
if (filterVal instanceof Collection) {
val values = jsonService.convert((Collection) filterVal, colProp.getValue());
if (!values.isEmpty()) {
search.in(col, values);
}
if (filterVal instanceof JSONArray) {
search.eq(col, joFilters.getObject(
field, Array.newInstance(colProp.getValue(), 0).getClass()));
}
else {
search.eq(col, filterVal);
@ -306,15 +302,22 @@ public abstract class AbstractBaseController {
protected Search order(final Search search, final String strOrders) {
if (StringUtils.isNotBlank(strOrders)) {
val jaOrders = jsonService.parseArray(decodeParam(strOrders));
for (val joSorter : jaOrders) {
final JSONArray jaOrders;
try {
jaOrders = JSON.parseArray(decodeParam(strOrders));
}
catch (JSONException e) {
throw new IllegalStateException(
"Invalid orders params [" + strOrders + "]", e);
}
for (val objOrder : jaOrders) {
val joSorter = (JSONObject) objOrder;
if (!joSorter.isEmpty()) {
val sortEntry =
joSorter.entrySet().iterator().next();
val col = orderCol(sortEntry.getKey());
if (StringUtils.isNotBlank(col)) {
val dir = (String) sortEntry.getValue();
final String dir = (String) sortEntry.getValue();
if ("asc".equalsIgnoreCase(dir)) {
search.asc(col);
}

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.crm.controller;
import lombok.val;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
@ -24,7 +23,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.crm.form.create.ApplicationFormForCreate;
import com.pudonghot.ambition.crm.form.update.ApplicationFormForUpdate;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import com.pudonghot.ambition.crm.form.create.ApplicationImageFormForCreate;
import com.pudonghot.ambition.crm.form.update.ApplicationImageFormForUpdate;
import com.pudonghot.ambition.crm.form.create.ApplicationAttachedFileFormForCreate;
@ -60,10 +58,9 @@ public class ApplicationController
@RequestParam(value = "search", required = false)
final String strSearch) {
val result =
final ListResult<ViewModel<Application>> result =
listViewModels(new Search().asc(Application.NAME),
start, limit, strSearch, null, filters, null);
result.setAttr("users", userService.listViewModels(
new Search().asc(User.EMPLOYEE_ID)));
result.setAttr("namePrefixes",
@ -96,7 +93,7 @@ public class ApplicationController
@RequestMapping(value = "/update", method = RequestMethod.POST)
public void update(
@Valid ApplicationFormForUpdate form) {
form.setAdmin(isAdmin());
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
((ApplicationService) queryService).update(form);
}
@ -106,7 +103,7 @@ public class ApplicationController
@Override
public ViewModel<Application> find(final String id) {
final ViewModel<Application> viewModel = queryService.findViewModel(id);
if (isAdmin()) {
if (getAuthUser().getUser().getData().isAdmin()) {
viewModel.setAttr("users", userService.listViewModels(
new Search().asc(User.EMPLOYEE_ID)));
}
@ -117,19 +114,19 @@ public class ApplicationController
public ViewModel<AttachedImage> addImage(
@Valid ApplicationImageFormForCreate form) {
Assert.state(!form.getImage().isEmpty(), "Image content is empty");
form.setAdmin(isAdmin());
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
return new ViewModel<>(((ApplicationService) queryService).addImage(form));
}
@RequestMapping(value = "/remove-image", method = RequestMethod.POST)
public void removeImage(@NotBlank @RequestParam("id") String id) {
val principal = getPrincipal();
((ApplicationService) queryService).removeImage(id, principal.getUserId(), principal.getAdmin());
final User user = getAuthUser().getUser().getData();
((ApplicationService) queryService).removeImage(id, user.getId(), user.isAdmin());
}
@RequestMapping(value = "/update-image", method = RequestMethod.POST)
public void updateImage(@Valid ApplicationImageFormForUpdate form) {
form.setAdmin(isAdmin());
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
((ApplicationService) queryService).updateImage(form);
}
@ -137,19 +134,19 @@ public class ApplicationController
public ViewModel<AttachedFile> addAttachment(
@Valid ApplicationAttachedFileFormForCreate form) {
Assert.state(!form.getAttachment().isEmpty(), "Image content is empty");
form.setAdmin(isAdmin());
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
return new ViewModel<>(((ApplicationService) queryService).addAttachment(form));
}
@RequestMapping(value = "/remove-attachment", method = RequestMethod.POST)
public void removeAttachment(@NotBlank @RequestParam("id") String id) {
val principal = getPrincipal();
((ApplicationService) queryService).removeAttachment(id, principal.getUserId(), principal.getAdmin());
final User user = getAuthUser().getUser().getData();
((ApplicationService) queryService).removeAttachment(id, user.getId(), user.isAdmin());
}
@RequestMapping(value = "/update-attachment", method = RequestMethod.POST)
public void updateImage(@Valid ApplicationAttachedFileFormForUpdate form) {
form.setAdmin(isAdmin());
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
((ApplicationService) queryService).updateAttachment(form);
}

View File

@ -1,19 +1,13 @@
package com.pudonghot.ambition.crm.controller;
import lombok.val;
import org.apache.shiro.SecurityUtils;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.util.Assert;
import org.apache.shiro.util.Assert;
import me.chyxion.tigon.model.ViewModel;
import com.pudonghot.ambition.crm.model.User;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.kit.bean.BeanService;
import org.springframework.stereotype.Controller;
import me.chyxion.tigon.shiro.service.AuthService;
import javax.validation.constraints.NotBlank;
import com.pudonghot.ambition.crm.service.UserService;
import com.pudonghot.ambition.crm.auth.SessionAbility;
import com.pudonghot.ambition.crm.auth.model.AuthToken;
import com.pudonghot.ambition.crm.auth.model.Principal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
@ -27,13 +21,11 @@ import org.springframework.beans.factory.annotation.Autowired;
*/
@Validated
@Controller
public class AuthController implements SessionAbility {
public class AuthController {
@Autowired
private UserService userService;
@Autowired
private AuthService authService;
@Autowired
private BeanService beanService;
@RequestMapping(value = "/auth/login", method = RequestMethod.POST)
public ViewModel<User> login(
@ -42,20 +34,13 @@ public class AuthController implements SessionAbility {
String loginId,
@NotBlank(message = "Param 'password' Could Not Be Blank")
@RequestParam("password")
String password) {
val user = findUser(loginId);
Assert.state(user != null, () -> "Incorrect account or password");
Assert.state(user.getEnabled(), "Account is disabled, please contact admin");
val principal = new Principal();
principal.setAccount(loginId);
principal.setUserId(user.getId());
beanService.assign(principal, user);
SecurityUtils.getSubject().login(new AuthToken(principal, password));
return userService.findViewModel(user.getId());
String password,
@RequestParam(value = "rememberMe", defaultValue = "false")
boolean rememberMe) {
final User user = userService.find(new Search(User.ACCOUNT, loginId));
Assert.state(user != null, "Unknown account");
return userService.findViewModel((String) authService.login(
user.getEmployeeId(), password, rememberMe).getUserId());
}
/**
@ -68,14 +53,6 @@ public class AuthController implements SessionAbility {
@RequestMapping("/auth/info")
public ViewModel<User> info() {
return userService.findViewModel(getUserId());
}
User findUser(final String loginId) {
val user = userService.find(new Search(User.ACCOUNT, loginId));
if (user != null) {
return user;
}
return userService.find(new Search(User.EMPLOYEE_ID, loginId));
return userService.findViewModel((String) authService.getAuthUser().getUserId());
}
}

View File

@ -1,11 +1,10 @@
package com.pudonghot.ambition.crm.common.controller;
package com.pudonghot.ambition.crm.controller;
import com.pudonghot.ambition.crm.controller.AbstractBaseController;
import com.pudonghot.ambition.crm.service.UserService;
import me.chyxion.tigon.model.ViewModel;
import com.pudonghot.ambition.crm.model.User;
import me.chyxion.tigon.shiro.model.AuthUser;
import me.chyxion.tigon.shiro.service.AuthService;
import com.pudonghot.ambition.crm.auth.SessionAbility;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -15,12 +14,28 @@ import org.springframework.beans.factory.annotation.Autowired;
* chyxion@163.com <br>
* Jun 2, 2016 12:52:10 PM
*/
public class BaseController extends AbstractBaseController implements SessionAbility {
public class BaseController extends AbstractBaseController {
@Autowired
protected AuthService authService;
@Autowired
private UserService userService;
/**
* get auth user id
* @return
*/
protected String getUserId() {
return (String) getAuthUser().getUserId();
}
/**
* get auth user
* @return
*/
protected AuthUser<ViewModel<User>> getAuthUser() {
return authService.getAuthUser();
}
/**
* @return
*/

View File

@ -0,0 +1,78 @@
package com.pudonghot.ambition.crm.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.form.FU2;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import me.chyxion.tigon.shiro.service.AuthService;
import java.lang.reflect.InvocationTargetException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* May 17, 2016 2:49:31 PM
*/
@Order(32)
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class BaseControllerAdvice {
private static final Logger log =
LoggerFactory.getLogger(BaseControllerAdvice.class);
@Autowired
private AuthService authService;
private ByteArrayMultipartFileEditor bamfe =
new ByteArrayMultipartFileEditor() {
/**
* {@inheritDoc}
*/
@Override
public void setValue(Object value) {
super.setValue(value instanceof MultipartFile ||
value instanceof byte[] ? value : null);
}
};
@InitBinder
public void registerCustomEditors(WebDataBinder binder, ServletWebRequest request)
throws IllegalAccessException, InvocationTargetException {
Object target = binder.getTarget();
String userId = getUserId();
if (target instanceof FC2) {
log.debug("Base form [{}] for create found, set created by [{}].", target, userId);
((FC2<String>) target).unlock();
((FC2<String>) target).setCreatedBy(userId);
}
else if (target instanceof FU2) {
log.debug("Base form [{}] for update found, set updated by [{}].", target, userId);
((FU2<String, String>) target).unlock();
((FU2<String, String>) target).setUpdatedBy(userId);
}
else if (target != null) {
log.debug("Set form [{}] created/updated by [{}].", target, userId);
BeanUtils.copyProperty(target, "createdBy", userId);
BeanUtils.copyProperty(target, "updatedBy", userId);
}
// PropertyEditorSupport
binder.registerCustomEditor(byte[].class, bamfe);
}
// --
// inner methods
String getUserId() {
return authService.isAuthenticated() ?
(String) authService.getAuthUser().getUserId() : null;
}
}

View File

@ -1,12 +1,13 @@
package com.pudonghot.ambition.crm.common.controller;
package com.pudonghot.ambition.crm.controller;
import javax.validation.Valid;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.form.FormUpdateApi;
import me.chyxion.tigon.form.BaseFormForUpdateApi;
import me.chyxion.tigon.service.BaseCrudByFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@ -19,9 +20,9 @@ import org.springframework.web.bind.annotation.RequestMethod;
* May 4, 2016 6:09:54 PM
*/
public class BaseCruController<
Model extends M0<String>,
Model extends BaseModel<String>,
FC extends FC2<String>,
FU extends FormUpdateApi<String>>
FU extends BaseFormForUpdateApi<String>>
extends BaseQueryController<Model> {
@Autowired

View File

@ -1,10 +1,11 @@
package com.pudonghot.ambition.crm.common.controller;
package com.pudonghot.ambition.crm.controller;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.form.FormUpdateApi;
import me.chyxion.tigon.model.BaseModel;
import javax.validation.constraints.NotNull;
import me.chyxion.tigon.form.BaseFormForUpdateApi;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
@ -16,9 +17,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
* May 4, 2016 6:09:54 PM
*/
public class BaseCrudController<
Model extends M0<String>,
Model extends BaseModel<String>,
FC extends FC2<String>,
FU extends FormUpdateApi<String>>
FU extends BaseFormForUpdateApi<String>>
extends BaseCruController<Model, FC, FU> {
@SuppressWarnings("unchecked")

View File

@ -1,7 +1,8 @@
package com.pudonghot.ambition.crm.common.controller;
package com.pudonghot.ambition.crm.controller;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import me.chyxion.tigon.service.BaseQueryService;
@ -18,7 +19,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
* May 10, 2016 4:50:58 PM
*/
@Slf4j
public class BaseQueryController<Model> extends BaseController {
public class BaseQueryController<Model extends BaseModel<String>>
extends BaseController {
@Autowired
protected BaseQueryService<String, Model> queryService;

View File

@ -4,34 +4,31 @@ import lombok.val;
import java.util.*;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONArray;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.ListResult;
import org.apache.commons.lang3.tuple.Pair;
import me.chyxion.tigon.webmvc.ResourceModel;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import com.pudonghot.ambition.crm.model.Customer;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.multipart.MultipartFile;
import com.pudonghot.ambition.crm.util.FileDownloadUtils;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import com.pudonghot.ambition.crm.service.CustomerService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.pudonghot.ambition.crm.service.ExportTaskService;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pudonghot.ambition.crm.model.CustomerYearToDateSale;
import com.pudonghot.ambition.crm.form.create.CustomerFormForCreate;
import com.pudonghot.ambition.crm.form.update.CustomerFormForUpdate;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
/**
* @author Donghuang <br>
@ -59,7 +56,7 @@ public class CustomerController
private static final Map<String, String> ORDER_COLS = new HashMap<>();
static {
ORDER_COLS.put(Customer.ID, "customer.id2");
ORDER_COLS.put(Customer.ID, "customer.id");
ORDER_COLS.put("dateAdded", "year(customer.date_added)");
ORDER_COLS.put(CustomerYearToDateSale.YEAR, CustomerYearToDateSale.YEAR);
ORDER_COLS.put("countryCode", "customer.country_code");
@ -110,9 +107,6 @@ public class CustomerController
Pair.of(CRITERION_COLS.get("issue"), Boolean.class));
}
@Autowired
private ExportTaskService exportTaskService;
@RequestMapping("/list")
public ListResult<ViewModel<Customer>> list(
@Min(0)
@ -133,10 +127,7 @@ public class CustomerController
val search = new Search();
val user = getUser().getData();
if (!user.isAdmin()) {
search.setAttr(User.ACCOUNT, user.getAccount());
}
search.setAttr(User.ACCOUNT, user.getAccount());
// search year
if (StringUtils.isNotBlank(strSearch)) {
@ -169,14 +160,10 @@ public class CustomerController
@RequiresRoles(User.ROLE_ADMIN)
@RequestMapping("/export")
public ResponseEntity<?> exportCSV() {
return FileDownloadUtils.toResponseEntity(((CustomerService) queryService).exportCSV(getUserId()), null);
}
@RequiresRoles(User.ROLE_ADMIN)
@RequestMapping("/async-export")
public void asyncExportCSV() {
exportTaskService.doExport(getUserId());
public ResourceModel exportCSV() {
return new ResourceModel(
((CustomerService) queryService).exportCSV(getUserId()),
"text/csv; charset=gbk", null);
}
@RequiresRoles(User.ROLE_ADMIN)
@ -221,17 +208,7 @@ public class CustomerController
*/
@Override
protected Search defaultFilter(final Search search) {
if (search.hasAttr("hasSearch")) {
return search;
}
// default status not NA
val statusCol = CRITERION_COLS.get("status");
return search.and(new Search()
.notNull(statusCol)
.ne(statusCol, CustomerProperty.STATUS_NA_ID)
.or(statusCol, null));
return search.ne(CRITERION_COLS.get("status"), CustomerProperty.STATUS_NA_ID);
}
/**
@ -244,8 +221,7 @@ public class CustomerController
CustomerYearToDateSale.YTD_SALE.equals(col)) {
search.setAttr("YTD_SALE", true);
}
if ("application".equals(col) && !((Collection<Object>) val).isEmpty()) {
if ("application".equals(col) && !((JSONArray) val).isEmpty()) {
search.setAttr("APPLICATIONS", val);
return true;
}

View File

@ -4,8 +4,6 @@ import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import me.chyxion.tigon.model.ViewModel;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.ListResult;

View File

@ -3,8 +3,7 @@ package com.pudonghot.ambition.crm.controller;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import com.alibaba.fastjson.JSONArray;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@ -12,9 +11,9 @@ import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import javax.validation.constraints.NotNull;
import com.pudonghot.ambition.crm.model.User;
import javax.validation.constraints.NotEmpty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.hibernate.validator.constraints.NotEmpty;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import org.springframework.web.bind.annotation.RequestParam;
@ -84,7 +83,7 @@ public class CustomerPropertyController
public void updateSort(
@NotEmpty
@RequestParam("ids")
final List<String> ids) {
JSONArray ids) {
((CustomerPropertyService) queryService).updateSort(getUserId(), ids);
}

View File

@ -1,8 +1,6 @@
package com.pudonghot.ambition.crm.controller;
import javax.validation.constraints.NotNull;
import com.pudonghot.ambition.crm.common.controller.BaseController;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

View File

@ -1,111 +0,0 @@
package com.pudonghot.ambition.crm.controller;
import lombok.val;
import java.io.File;
import java.util.Map;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.http.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import javax.validation.constraints.NotNull;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.http.ResponseEntity;
import me.chyxion.tigon.web.controller2.ArgQuery;
import org.springframework.stereotype.Controller;
import com.pudonghot.ambition.crm.model.ExportTask;
import com.pudonghot.ambition.crm.auth.SessionAbility;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.pudonghot.ambition.crm.util.FileDownloadUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import me.chyxion.tigon.web.controller2.BaseQueryController;
import org.springframework.web.bind.annotation.RequestParam;
import com.pudonghot.ambition.crm.service.ExportTaskService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.crm.ws.service.WebSocketService;
import me.chyxion.tigon.web.controller2.response.ListCtrlrResp;
import com.pudonghot.ambition.crm.common.request.BaseListCtrlrReq;
import com.pudonghot.ambition.crm.ws.model.ExportTaskUpdatedWsResp;
/**
* @author Donghuang
* @date Jun 18, 2022 09:47:30
*/
@Slf4j
@Controller
@RequestMapping("/export-task")
public class ExportTaskController
extends BaseQueryController<Long,
BaseListCtrlrReq,
ExportTask,
ExportTask>
implements SessionAbility {
/**
* {@inheritDoc}
*/
@Override
@RequiresRoles(User.ROLE_ADMIN)
public ListCtrlrResp<ExportTask> list(@Valid final BaseListCtrlrReq req) {
return list(req, new Search());
}
/**
* download file
* @param id id
* @return file
*/
@RequiresRoles(User.ROLE_ADMIN)
@RequestMapping("/download")
public ResponseEntity file(@NotNull @RequestParam("id") final Long id) {
val exportTask = service.find(id);
if (exportTask == null) {
return ResponseEntity.notFound().build();
}
val userId = getUserId();
if (!userId.equals(exportTask.getCreatedBy())) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
exportTask.setDownloaded(true);
exportTask.setUpdatedBy(userId);
((ExportTaskService) service).update(exportTask);
val location = exportTask.getLocation();
if (StringUtils.isNotBlank(location)) {
val file = new File(location);
if (file.exists() && file.isFile()) {
((ExportTaskService) service).notifyTaskUpdated(userId);
return FileDownloadUtils.toResponseEntity(file, file.getName());
}
}
return ResponseEntity.notFound().build();
}
/**
* {@inheritDoc}
*/
@Override
protected void before(final ArgQuery<?> arg) {
super.before(arg);
val search = arg.getSearch();
search.eq(ExportTask.CREATED_BY, getUserId());
if (arg.getType() == ArgQuery.Type.LIST) {
search.desc(ExportTask.DATE_CREATED);
}
}
@Autowired
private WebSocketService webSocketService;
@PostMapping("/test-push")
@RequiresRoles(User.ROLE_ADMIN)
public void testPush(@RequestBody Map<String, Object> resp) {
webSocketService.publish(getUserId(), resp);
}
}

View File

@ -1,21 +1,9 @@
package com.pudonghot.ambition.crm.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.pudonghot.ambition.crm.util.FileDownloadUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import me.chyxion.tigon.webmvc.ResourceModel;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import com.pudonghot.ambition.file.DiskFileApi;
@ -38,28 +26,23 @@ public class FileController {
private DiskFileApi fileApi;
@RequestMapping("/f/**")
public ResponseEntity file(HttpServletRequest request) {
val reqUri = request.getRequestURI();
public Object file(HttpServletRequest request) {
String reqUri = request.getRequestURI();
Assert.state(reqUri.length() > 3, "File name could not be blank");
val fileName = reqUri.substring(
final String fileName = reqUri.substring(
(request.getContextPath() + "/f/").length()).replaceAll("\\.\\w+$", "");
log.info("Get file [{}].", fileName);
val fileInfo = fileApi.findFileInfo(fileName);
final FileInfo fileInfo = fileApi.findFileInfo(fileName);
ResourceModel rm = null;
if (fileInfo != null) {
val file = fileApi.getFile(fileInfo);
return FileDownloadUtils.toResponseEntity(file, fileInfo.getDownloadName());
final File file = fileApi.getFile(fileInfo);
if (file.exists()) {
rm = new ResourceModel(file,
fileInfo.getContentType(), fileInfo.getDownloadName());
}
}
return ResponseEntity.notFound().build();
}
@SneakyThrows
String encode(final String downloadName) {
val name = URLEncoder.encode(downloadName, StandardCharsets.UTF_8.name());
return new StringBuilder("attachment; filename=\"")
.append(name)
.append("\"; filename*=utf-8''")
.append(name).toString();
return rm != null ?
rm : ResponseEntity.notFound().build();
}
}

View File

@ -1,8 +1,6 @@
package com.pudonghot.ambition.crm.controller;
import javax.validation.Valid;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import lombok.extern.slf4j.Slf4j;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

View File

@ -2,8 +2,6 @@ package com.pudonghot.ambition.crm.controller;
import java.util.List;
import java.util.Arrays;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.ViewModel;
import javax.validation.constraints.Max;
@ -32,7 +30,7 @@ public class ImportRecordController
"u.name",
"u.en_name",
"u.account",
"u.employee_id");
"u.employee_id" );
@RequestMapping("/list")
@RequiresRoles(User.ROLE_ADMIN)

View File

@ -3,9 +3,6 @@ package com.pudonghot.ambition.crm.controller;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import lombok.val;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
@ -72,14 +69,14 @@ public class LocalProductController
return result;
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/create", method = RequestMethod.POST)
public void create(
@Valid LocalProductFormForCreate form) {
((LocalProductService) queryService).create(form);
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/update", method = RequestMethod.POST)
public void update(
@Valid LocalProductFormForUpdate form) {
@ -91,15 +88,15 @@ public class LocalProductController
*/
@Override
public ViewModel<LocalProduct> find(final String id) {
val viewModel = queryService.findViewModel(id);
if (isAdmin()) {
final ViewModel<LocalProduct> viewModel = queryService.findViewModel(id);
if (getAuthUser().getUser().getData().isAdmin()) {
viewModel.setAttr("users", userService.listViewModels(
new Search().asc(User.EMPLOYEE_ID)));
}
return viewModel;
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/add-image", method = RequestMethod.POST)
public ViewModel<AttachedImage> addImage(
@Valid LocalProductImageFormForCreate form) {
@ -107,19 +104,19 @@ public class LocalProductController
return new ViewModel<>(((LocalProductService) queryService).addImage(form));
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/remove-image", method = RequestMethod.POST)
public void removeImage(@NotBlank @RequestParam("id") String id) {
((LocalProductService) queryService).removeImage(id);
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/update-image", method = RequestMethod.POST)
public void updateImage(@Valid LocalProductImageFormForUpdate form) {
((LocalProductService) queryService).updateImage(form);
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/add-attachment", method = RequestMethod.POST)
public ViewModel<AttachedFile> addAttachment(
@Valid LocalProductAttachedFileFormForCreate form) {
@ -132,13 +129,13 @@ public class LocalProductController
((LocalProductService) queryService).removeAttachment(id);
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/update-attachment", method = RequestMethod.POST)
public void updateImage(@Valid LocalProductAttachedFileFormForUpdate form) {
((LocalProductService) queryService).updateAttachment(form);
}
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_DONGHUANG, User.ROLE_ADMIN}, logical = Logical.OR)
@RequiresRoles(value = {User.ROLE_LELI, User.ROLE_CHYXION, User.ROLE_ADMIN}, logical = Logical.OR)
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public void delete(@NotBlank @RequestParam("id") String id) {
((LocalProductService) queryService).delete(id);

View File

@ -5,8 +5,6 @@ import java.util.List;
import java.util.Arrays;
import java.util.HashMap;
import javax.validation.Valid;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

View File

@ -1,18 +1,19 @@
package com.pudonghot.ambition.crm.controller;
import java.util.*;
import com.pudonghot.ambition.crm.common.controller.BaseQueryController;
import lombok.val;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import javax.validation.Valid;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import org.apache.commons.lang3.StringUtils;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import com.pudonghot.ambition.crm.model.WeekGoal;
@ -20,7 +21,6 @@ import com.pudonghot.ambition.crm.util.AmDateUtil;
import com.pudonghot.ambition.crm.service.WeekGoalService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pudonghot.ambition.crm.form.update.WeekGoalFormForUpdate;
@ -41,9 +41,6 @@ public class WeekGoalController
"u.account",
"u.employee_id");
@Autowired
private JsonService jsonService;
@RequestMapping("/list")
public ViewModel<List<ViewModel<WeekGoal>>> list(
@Min(0)
@ -70,7 +67,7 @@ public class WeekGoalController
((WeekGoalService) queryService).initWeekGoal(userId);
return addYearSum(listViewModels(mineFilters(new Search(WeekGoal.USER_ID, userId), filters)),
Arrays.asList(getPrincipal().getEmployeeId()));
Arrays.asList(getAuthUser().getUser().getData().getEmployeeId()));
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ -81,10 +78,11 @@ public class WeekGoalController
private List<String> employeeIdsFilter(final String strFilters) {
if (StringUtils.isNotBlank(strFilters)) {
Map<String, Object> joFilters = parseFilters(strFilters);
val employees = (List<String>) joFilters.get("user");
if (employees != null && !employees.isEmpty()) {
return employees;
final JSONObject joFilters = parseFilters(strFilters);
final String[] employees =
joFilters.getObject("user", String[].class);
if (employees != null && employees.length > 0) {
return Arrays.asList(employees);
}
}
return Collections.emptyList();
@ -105,10 +103,11 @@ public class WeekGoalController
return thisMonth(search);
}
Map<String, Object> joFilters = parseFilters(strFilters);
final JSONObject joFilters = parseFilters(strFilters);
val months = (List<Integer>)joFilters.get("month");
if (months != null && !months.isEmpty()) {
final Integer[] months =
joFilters.getObject("month", Integer[].class);
if (months != null && months.length > 0) {
search.and(new Search(WeekGoal.MONTH_START, months)
.or(WeekGoal.MONTH_END, months));
}
@ -153,9 +152,9 @@ public class WeekGoalController
return result;
}
private Map<String, Object> parseFilters(final String filters) {
private JSONObject parseFilters(final String filters) {
try {
return jsonService.parseObject(decodeParam(filters));
return JSON.parseObject(decodeParam(filters));
}
catch (Exception e) {
throw new IllegalStateException(

View File

@ -7,6 +7,7 @@ import org.springframework.stereotype.Service;
import org.springframework.core.annotation.Order;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.dao.DuplicateKeyException;
import me.chyxion.tigon.webmvc.exception.DefaultExceptionResolver;
/**
* @author Shaun Chyxion <br>
@ -15,7 +16,7 @@ import org.springframework.dao.DuplicateKeyException;
*/
@Service
@Order(16)
public class CRMExceptionResolver {
public class CRMExceptionResolver extends DefaultExceptionResolver {
private static final Map<Class<?>, Pair<Integer, String>>
EXCEPTIONS_MAP =
@ -38,4 +39,28 @@ public class CRMExceptionResolver {
return ImmutablePair.<Integer, String>of(code, msg);
}
};
/**
* {@inheritDoc}
*/
@Override
public boolean accept(Throwable ex) {
return EXCEPTIONS_MAP.containsKey(ex.getClass());
}
/**
* {@inheritDoc}
*/
@Override
protected Object getErrorCode(Throwable ex) {
return EXCEPTIONS_MAP.get(ex.getClass()).getKey();
}
/**
* {@inheritDoc}
*/
@Override
protected Object getErrorMessage(Throwable ex, Object code) {
return EXCEPTIONS_MAP.get(ex.getClass()).getValue();
}
}

View File

@ -3,6 +3,7 @@ package com.pudonghot.ambition.crm.exception;
import java.util.Map;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.webmvc.exception.ExceptionMessage;
/**
* @author Shaun Chyxion <br>
@ -10,7 +11,7 @@ import org.springframework.stereotype.Service;
* Jun 30, 2017 23:09:33
*/
@Service
public class ExceptionMessageSupport {
public class ExceptionMessageSupport implements ExceptionMessage {
private static final Map<Object, Object> map = new HashMap<Object, Object>() {
private static final long serialVersionUID = 1L;
{
@ -24,4 +25,12 @@ public class ExceptionMessageSupport {
put(5000, "Unknown error, please contact system admin");
}
};
/**
* {@inheritDoc}
*/
@Override
public Object get(Object code) {
return map.get(code);
}
}

View File

@ -1,15 +1,13 @@
package com.pudonghot.ambition.crm.service;
import com.alibaba.fastjson.JSONArray;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.NotEmpty;
import me.chyxion.tigon.service.BaseCrudByFormService;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import com.pudonghot.ambition.crm.form.create.CustomerPropertyFormForCreate;
import com.pudonghot.ambition.crm.form.update.CustomerPropertyFormForUpdate;
import java.util.List;
/**
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
@ -26,7 +24,7 @@ public interface CustomerPropertyService
* @param operator operator
* @param ids ids
*/
void updateSort(@NotBlank String operator, @NotEmpty List<String> ids);
void updateSort(@NotBlank String operator, @NotEmpty JSONArray ids);
/**
* init system status

View File

@ -1,38 +0,0 @@
package com.pudonghot.ambition.crm.service;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import com.pudonghot.ambition.crm.model.ExportTask;
import me.chyxion.tigon.service2.BaseQueryService;
import org.springframework.validation.annotation.Validated;
/**
* @author Donghuang
* @date May 29, 2022 21:24:42
*/
@Validated
public interface ExportTaskService extends BaseQueryService<Long, ExportTask> {
/**
* do export
*
* @param employeeKey employee key
*/
void doExport(@NotBlank String employeeKey);
/**
* notify task updated
*
* @param employeeKey employee key
*/
void notifyTaskUpdated(@NotBlank String employeeKey);
/**
* update task
*
* @param exportTask task
*/
void update(@NotNull ExportTask exportTask);
}

View File

@ -12,7 +12,7 @@ import com.pudonghot.ambition.crm.model.*;
import com.pudonghot.ambition.crm.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.kit.sequence.IdSequence;
import com.pudonghot.ambition.file.DiskFileApi;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.web.multipart.MultipartFile;
import com.pudonghot.ambition.crm.service.AttachmentService;
@ -44,6 +44,8 @@ public class ApplicationServiceSupport
@Autowired
private AttachedFileMapper attachmentMapper;
@Autowired
private DiskFileApi fileApi;
@Autowired
private CustomerMapper customerMapper;
@Autowired
private CustomerApplicationMapper customerApplicationMapper;
@ -53,8 +55,6 @@ public class ApplicationServiceSupport
private CustomerPermissionService customerPermissionService;
@Autowired
private AttachmentService attachmentService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
@ -223,13 +223,12 @@ public class ApplicationServiceSupport
*/
@Override
@Transactional(rollbackFor = Throwable.class)
public int delete(final String id) {
attachmentService.deleteOwner(id,
public Application delete(final String id) {
return attachmentService.deleteOwner(id,
mapper, application ->
Assert.state(customerApplicationMapper.count(
new Search(CustomerApplication.APPLICATION_ID, id)) == 0,
"Application [" + id + "] is in using"));
return 0;
}
private Application validatePerm(final String appId, final String userId, final boolean admin) {

View File

@ -1,23 +1,24 @@
package com.pudonghot.ambition.crm.service.support;
import lombok.val;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.model.M2;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.sequence.IdSequence;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.BaseMapper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.file.DiskFileApi;
import com.pudonghot.ambition.crm.model.FileInfo;
import com.pudonghot.ambition.crm.model.Attachment;
import com.pudonghot.ambition.crm.model.AttachedImage;
import org.springframework.web.multipart.MultipartFile;
@ -26,7 +27,6 @@ import com.pudonghot.ambition.crm.mapper.AttachedFileMapper;
import com.pudonghot.ambition.crm.mapper.AttachedImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.pudonghot.ambition.file.request.AmInputStreamUploadReq;
import com.pudonghot.ambition.crm.form.update.AttachmentFormForUpdate;
/**
@ -64,24 +64,19 @@ public class AttachmentServiceSupport
final Date now = new Date();
final String fileFolder = fileFolder(ownerId);
int i = 0;
for (val file : files) {
for (final MultipartFile file : files) {
if (!file.isEmpty()) {
val originalFilename = file.getOriginalFilename();
try (val ins = file.getInputStream()) {
val fileId = idSeq.get();
val appFile = constructor.get();
val req = new AmInputStreamUploadReq();
req.setInputStream(ins);
req.setContentLength(file.getSize());
req.setFolder(fileFolder);
req.setName(fileId);
req.setContentType(file.getContentType());
req.setFormat(FilenameUtils.getExtension(originalFilename));
req.setDownloadName(originalFilename);
val fileInfo = fileApi.upload(req);
final String originalFilename = file.getOriginalFilename();
try (final InputStream ins = file.getInputStream()) {
final String fileId = idSeq.get();
final T appFile = constructor.get();
final FileInfo fileInfo = fileApi.upload(ins,
file.getSize(),
fileFolder,
fileId,
file.getContentType(),
FilenameUtils.getExtension(originalFilename),
originalFilename);
appFile.setId(fileId);
appFile.setOwnerId(ownerId);
appFile.setFileId(fileInfo.getId());
@ -117,15 +112,15 @@ public class AttachmentServiceSupport
final Function<String, List<T>> listSort,
final Consumer<T> updater) {
val id = form.getId();
val appImage = finder.apply(id);
final String id = form.getId();
final T appImage = finder.apply(id);
Assert.state(appImage != null, "No local product file [" + id + "] found");
val ownerId = appImage.getOwnerId();
val updatedBy = form.getUpdatedBy();
final String ownerId = appImage.getOwnerId();
final String updatedBy = form.getUpdatedBy();
boolean sortUpdated = false;
val sort = form.getSort();
val sortOld = appImage.getSort();
final float sort = form.getSort();
final float sortOld = appImage.getSort();
if (sort < sortOld) {
sortUpdated = true;
appImage.setSort(sortOld - 1.5f);
@ -155,13 +150,12 @@ public class AttachmentServiceSupport
final Function<String, Integer> deleter,
final Function<String, Integer> sortUpdater,
final Consumer<T> validator) {
val attachment = finder.apply(id);
final T attachment = finder.apply(id);
Assert.state(attachment != null, "No file [" + id + "] found");
if (validator != null) {
validator.accept(attachment);
}
val ownerId = attachment.getOwnerId();
final String ownerId = attachment.getOwnerId();
fileApi.delete(fileFolder(ownerId) + "/" + id);
deleter.apply(id);
sortUpdater.apply(ownerId);
@ -176,15 +170,15 @@ public class AttachmentServiceSupport
final Consumer<M> validator) {
log.info("Delete attachment owner [{}].", ownerId);
val owner = mapper.find(ownerId);
final M owner = mapper.find(ownerId);
Assert.state(owner != null, "No attachment owner [" + ownerId + "] found");
Assert.state(!owner.getEnabled(), "Attachment owner [" + ownerId + "] is enabled");
Assert.state(!owner.isEnabled(), "Attachment owner [" + ownerId + "] is enabled");
if (validator != null) {
validator.accept(owner);
}
val search = new Search(AttachedImage.OWNER_ID, ownerId);
final Search search = new Search(AttachedImage.OWNER_ID, ownerId);
imageMapper.list(search).forEach(
image -> fileApi.deleteById(image.getFileId()));
imageMapper.delete(search);

View File

@ -40,7 +40,7 @@ public class CustomerIssueServiceSupport
final CustomerIssue issue = find(id);
Assert.state(issue != null, "No issue [" + id + "] found");
if (!issue.getIssue().equals(form.getIssue()) ||
form.getEnabled() != issue.getEnabled()) {
form.isEnabled() != issue.isEnabled()) {
return super.update(form);
}
log.info("Issue [{}] not changed", issue);

View File

@ -2,9 +2,7 @@ package com.pudonghot.ambition.crm.service.support;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.crm.model.CustomerPermission;
import me.chyxion.tigon.service.support.BaseCrudServiceSupport;
@ -24,9 +22,6 @@ public class CustomerPermissionServiceSupport
CustomerPermissionMapper>
implements CustomerPermissionService {
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
*/

View File

@ -1,8 +1,8 @@
package com.pudonghot.ambition.crm.service.support;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONArray;
import org.springframework.util.Assert;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.crm.model.CustomerProperty;
@ -39,7 +39,7 @@ public class CustomerPropertyServiceSupport
* {@inheritDoc}
*/
@Override
public void updateSort(String operator, List<String> ids) {
public void updateSort(String operator, JSONArray ids) {
int sort = 0;
final Date now = new Date();
for (final Object id : ids) {

View File

@ -4,7 +4,6 @@ import java.io.*;
import java.util.*;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
@ -62,8 +61,6 @@ public class CustomerServiceSupport
private CustomerApplicationMapper customerApplicationMapper;
@Autowired
private ApplicationMapper applicationMapper;
@Autowired
private IdSequence idSeq;
private static final String SPLITTER = new String(new int[]{0x1d}, 0, 1);
private static final CSVFormat EXPORT_FORMAT =
@ -182,7 +179,7 @@ public class CustomerServiceSupport
val application = applicationMapper.find(applicationId);
Assert.state(application != null,
"No application [" + applicationId + "] found");
Assert.state(application.getEnabled(),
Assert.state(application.isEnabled(),
"Application [" + application.getName() + "] is disabled");
val customerApplication = new CustomerApplication();
@ -473,6 +470,22 @@ public class CustomerServiceSupport
.asc(Customer.ID),
this::exportList,
this::exportCount, c -> {
// "Customer ID",
// "Name",
// "Sum Sales(3 Years)",
// "Sales",
// "Comment",
// "Application",
// "Status",
// "Year Added",
// "Year",
// "Country",
// "State",
// "City",
// "MS",
// "Region",
// "Sales Person");
try {
log.info("Export Customer [{}].", c);
printer.printRecord(c.getId2(),
@ -552,9 +565,10 @@ public class CustomerServiceSupport
* {@inheritDoc}
*/
@Override
public int delete(final String id) {
val rowDeleted = super.delete(id);
Assert.state(rowDeleted > 0, "No customer [" + id + "] found");
public Customer delete(final String id) {
val customer = super.delete(id);
Assert.state(customer != null,
"No customer [" + id + "] found");
customerPermissionMapper.delete(
new Search(CustomerPermission.CUSTOMER_ID, id));
customerIssueMapper.delete(
@ -564,6 +578,6 @@ public class CustomerServiceSupport
customerApplicationMapper.delete(
new Search(CustomerApplication.CUSTOMER_ID, id));
return 0;
return customer;
}
}

View File

@ -5,7 +5,6 @@ import java.util.Date;
import java.io.InputStream;
import java.text.ParseException;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
@ -47,8 +46,6 @@ public class CustomerYearToDateSaleServiceSupport
private ImportRecordMapper importRecordMapper;
@Autowired
private CustomerPropertyService customerPropertyService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
@ -105,22 +102,15 @@ public class CustomerYearToDateSaleServiceSupport
return;
}
val customers = customerMapper.list(
val customer = customerMapper.find(
new Search(Customer.ID2, customerId2)
.eq(Customer.NAME, customerName));
if (customers.isEmpty()) {
if (customer == null) {
log.warn("No customer [{}] found, ignore.", customerName);
return;
}
if (customers.size() > 1) {
log.warn("Duplicate customers [{}] found, error.", customers);
throw new IllegalStateException(
"Duplicate customer found, id [" + customerId2 + "] name [" + customerName + "]");
}
val customer = customers.iterator().next();
val customerId = customer.getId();
customerYtdSale.setCustomerId(customerId);
customerYtdSale.setYear(StringUtils.trim(record.get(3)));

View File

@ -1,127 +0,0 @@
package com.pudonghot.ambition.crm.service.support;
import lombok.val;
import java.io.File;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.mybatis.Search;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Service;
import java.util.concurrent.ConcurrentHashMap;
import com.pudonghot.ambition.crm.model.ExportTask;
import org.springframework.core.task.TaskExecutor;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import com.pudonghot.ambition.crm.mapper.ExportTaskMapper;
import com.pudonghot.ambition.crm.service.CustomerService;
import com.pudonghot.ambition.crm.service.ExportTaskService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.crm.ws.service.WebSocketService;
import me.chyxion.tigon.service.support2.BaseQueryServiceSupport;
import com.pudonghot.ambition.crm.enumeration.EnumExportTaskStatus;
import com.pudonghot.ambition.crm.ws.model.ExportTaskUpdatedWsResp;
import com.pudonghot.ambition.crm.ws.model.ExportTaskCompletedWsResp;
/**
* @author Donghuang
* @date May 29, 2022 21:29:06
*/
@Slf4j
@Service
public class ExportTaskServiceSupport
extends BaseQueryServiceSupport<Long, ExportTask, ExportTaskMapper, ExportTask>
implements ExportTaskService {
private final ConcurrentMap<String, Long> LOCK_MAP = new ConcurrentHashMap<>();
@Autowired
@Qualifier("exportTaskExecutor")
private TaskExecutor threadPoolTaskExecutor;
@Autowired
private CustomerService customerService;
@Value("${export.location:/data/program/export}")
private String exportLocation;
@Autowired
private WebSocketService webSocketService;
/**
* {@inheritDoc}
*/
@Override
public void doExport(final String employeeKey) {
val now = Long.valueOf(System.currentTimeMillis());
Assert.state(LOCK_MAP.putIfAbsent(employeeKey, now) == null,
"There is a running export task, please try again later!");
threadPoolTaskExecutor.execute(() ->{
try {
val exportTask = new ExportTask();
exportTask.setCreatedBy(employeeKey);
exportTask.setDateCreated(new Date());
exportTask.setStatus(EnumExportTaskStatus.RUNNING);
mapper.insert(exportTask);
try {
val exportFile = customerService.exportCSV(employeeKey);
val distDir = new File(new File(exportLocation),
DateFormatUtils.format(now, "yyyyMMdd"));
if (!distDir.exists()) {
distDir.mkdirs();
}
FileUtils.moveFileToDirectory(exportFile, distDir, true);
exportTask.setStatus(EnumExportTaskStatus.DONE);
exportTask.setLocation(new File(distDir, exportFile.getName()).getPath());
exportTask.setDateUpdated(new Date());
mapper.update(exportTask);
notifyTaskComplete(employeeKey, true, null);
}
catch (final Throwable e) {
log.error("Export file error caused.", e);
exportTask.setStatus(EnumExportTaskStatus.FAILED);
exportTask.setNote(ExceptionUtils.getStackTrace(e));
exportTask.setDateUpdated(new Date());
mapper.update(exportTask);
notifyTaskComplete(employeeKey, false, e.getMessage());
}
}
finally {
LOCK_MAP.remove(employeeKey);
}
});
}
void notifyTaskComplete(final String employeeKey, final boolean success, final String message) {
val resp = new ExportTaskCompletedWsResp(employeeKey,
mapper.count(new Search(ExportTask.CREATED_BY, employeeKey)
.isFalse(ExportTask.DOWNLOADED)));
resp.setSuccess(success);
resp.setMessage(message);
webSocketService.publish(resp);
}
/**
* {@inheritDoc}
*/
@Override
public void notifyTaskUpdated(final String employeeKey) {
webSocketService.publish(
new ExportTaskUpdatedWsResp(employeeKey,
mapper.count(new Search(ExportTask.CREATED_BY, employeeKey)
.eq(ExportTask.STATUS, EnumExportTaskStatus.DONE)
.isFalse(ExportTask.DOWNLOADED))));
}
/**
* {@inheritDoc}
*/
@Override
public void update(final ExportTask exportTask) {
mapper.update(exportTask);
}
}

View File

@ -4,7 +4,6 @@ import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.shiro.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
@ -37,7 +36,7 @@ public class HomePageServiceSupport
public void apply(final String id, final String operator) {
final HomePage homePage = find(id);
Assert.state(homePage != null, "No home page [" + id + "] found");
Assert.state(homePage.getEnabled(), "Home page [" + id + "] is not enabled");
Assert.state(homePage.isEnabled(), "Home page [" + id + "] is not enabled");
Assert.state(!homePage.isApplying(), "Home page [" + id + "] is applying");
final Date now = new Date();
toggleApplying(now, operator);
@ -61,10 +60,10 @@ public class HomePageServiceSupport
* {@inheritDoc}
*/
@Override
public int delete(final String id) {
val homePage = find(id);
public HomePage delete(final String id) {
final HomePage homePage = find(id);
Assert.state(homePage != null, "No home page [" + id + "] found");
Assert.state(!homePage.getEnabled(), "Home page [" + id + "] is enabled");
Assert.state(!homePage.isEnabled(), "Home page [" + id + "] is enabled");
return super.delete(id);
}

View File

@ -4,7 +4,6 @@ import java.util.Map;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.util.Assert;
import me.chyxion.tigon.model.ViewModel;
@ -41,8 +40,6 @@ public class LocalProductServiceSupport
private AttachedFileMapper attachmentMapper;
@Autowired
private AttachmentService attachmentService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
@ -169,9 +166,8 @@ public class LocalProductServiceSupport
*/
@Override
@Transactional(rollbackFor = Throwable.class)
public int delete(final String id) {
attachmentService.deleteOwner(id, mapper, null);
return 0;
public LocalProduct delete(final String id) {
return attachmentService.deleteOwner(id, mapper, null);
}
private String namePrefix(final String name) {

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.crm.service.support;
import lombok.val;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
@ -8,11 +7,10 @@ import me.chyxion.tigon.model.ViewModel;
import org.apache.commons.lang3.StringUtils;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.kit.sequence.IdSequence;
import com.pudonghot.ambition.crm.util.Sha512Utils;
import javax.validation.constraints.NotBlank;
import com.pudonghot.ambition.crm.mapper.UserMapper;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.crm.form.create.UserFormForCreate;
import com.pudonghot.ambition.crm.form.update.UserFormForUpdate;
import me.chyxion.tigon.service.support.BaseCrudByFormServiceSupport;
@ -32,15 +30,12 @@ public class UserServiceSupport
UserFormForCreate, UserFormForUpdate, UserMapper>
implements UserService {
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
*/
@Override
public ViewModel<User> update(final UserFormForUpdate form) {
val password = form.getPassword();
public ViewModel<User> update(UserFormForUpdate form) {
final String password = form.getPassword();
if (StringUtils.isNotBlank(password)) {
form.setPassword(hashPassword(form.getId(), password));
}
@ -51,10 +46,10 @@ public class UserServiceSupport
* {@inheritDoc}
*/
@Override
public int delete(final String id) {
final User user = find(id);
public User delete(final String id) {
User user = find(id);
Assert.state(user != null, "No user [" + id + "] found");
Assert.state(!user.getEnabled(), "User [" + id + "] is enabled");
Assert.state(!user.isEnabled(), "User [" + id + "] is enabled");
return super.delete(id);
}
@ -63,7 +58,7 @@ public class UserServiceSupport
*/
@Override
public boolean validatePassword(String userId, String password) {
val user = mapper.find(userId);
final User user = mapper.find(userId);
return hashPassword(user.getId(), password)
.equals((user.getPassword()));
}
@ -72,7 +67,7 @@ public class UserServiceSupport
* {@inheritDoc}
*/
@Override
public List<ViewModel<User>> listByCustomerId(final String customerId) {
public List<ViewModel<User>> listByCustomerId(@NotBlank String customerId) {
return toViewModel(mapper.listByCustomerId(customerId));
}
@ -84,7 +79,7 @@ public class UserServiceSupport
Assert.state(form.getPassword().equals(form.getConfirmPassword()),
"Repeat password does not match");
val user = mapper.find(userId);
final User user = mapper.find(userId);
Assert.state(user != null, "No user [" + userId + "] found");
Assert.state(hashPassword(userId, form.getOriginPassword())
.equals((user.getPassword())), "Incorrect origin password");
@ -98,7 +93,7 @@ public class UserServiceSupport
*/
@Override
public String findAccount(final String id) {
val user = find(id);
final User user = find(id);
Assert.state(user != null, "No user [" + id + "] found");
return user.getAccount();
}
@ -109,7 +104,6 @@ public class UserServiceSupport
@Override
protected void beforeInsert(final User model) {
super.beforeInsert(model);
model.setId(idSeq.get());
model.setPassword(hashPassword(model.getId(), model.getPassword()));
}

View File

@ -3,12 +3,9 @@ package com.pudonghot.ambition.crm.service.support;
import java.util.Map;
import java.util.Date;
import java.util.List;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.joda.time.*;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
@ -36,9 +33,6 @@ public class WeekGoalServiceSupport
extends BaseCrudServiceSupport<String, WeekGoal, WeekGoalMapper>
implements WeekGoalService {
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
*/

View File

@ -1,57 +0,0 @@
package com.pudonghot.ambition.crm.util;
import java.io.*;
import lombok.val;
import lombok.SneakyThrows;
import java.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import org.springframework.http.MediaType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.core.io.FileSystemResource;
/**
* @author Donghuang
* @date Jun 06, 2022 20:01:02
*/
@Slf4j
public class FileDownloadUtils {
/**
* file to response entity
*
* @param file file
* @return response entity
*/
public static ResponseEntity<?> toResponseEntity(final File file, final String downloadName) {
log.debug("Download file [{}].", file);
if (file.exists()) {
val headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
encode(StringUtils.defaultIfBlank(downloadName, file.getName())));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(file));
}
return ResponseEntity.notFound().build();
}
@SneakyThrows
static String encode(final String downloadName) {
val name = URLEncoder.encode(downloadName, StandardCharsets.UTF_8.name());
return new StringBuilder("attachment; filename=\"")
.append(name)
.append("\"; filename*=utf-8''")
.append(name).toString();
}
}

View File

@ -5,8 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import me.chyxion.tigon.sequence.IdSequence;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -22,7 +22,7 @@ public class RequestListener implements ServletRequestListener {
@Override
public void requestInitialized(final ServletRequestEvent sre) {
MDC.put("requestId", idSeq.uuid());
MDC.put("requestId", idSeq.get());
sre.getServletRequest().setAttribute("startTime", System.currentTimeMillis());
}

View File

@ -1,37 +0,0 @@
package com.pudonghot.ambition.crm.ws.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* @author Donghuang
* @date Oct 12, 2021 15:31:50
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* {@inheritDoc}
*/
@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes("/ws");
config.enableSimpleBroker("/topic");
}
/**
* {@inheritDoc}
*/
@Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/stomp")
.setAllowedOriginPatterns(
"http://localhost:[*]",
"http://127.0.0.1:[*]")
.withSockJS();
}
}

View File

@ -1,23 +0,0 @@
package com.pudonghot.ambition.crm.ws.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
/**
* @author Donghuang
* @date Jun 17, 2022 15:01:49
*/
@Getter
@Setter
@ToString
public class BaseWsResp implements Serializable {
private static final long serialVersionUID = 1L;
@NotBlank
private String employeeKey;
@NotBlank
private String type;
}

View File

@ -1,30 +0,0 @@
package com.pudonghot.ambition.crm.ws.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Donghuang
* @date Jun 17, 2022 15:01:49
*/
@Getter
@Setter
@ToString
public class ExportTaskCompletedWsResp extends BaseWsResp {
private static final long serialVersionUID = 1L;
private Integer countUndownloaded;
private Boolean success;
private String message;
public ExportTaskCompletedWsResp() {
setType("EXPORT_TASK_COMPLETED");
}
public ExportTaskCompletedWsResp(final String employeeKey, final Integer countUndownloaded) {
this();
this.countUndownloaded = countUndownloaded;
setEmployeeKey(employeeKey);
}
}

View File

@ -1,28 +0,0 @@
package com.pudonghot.ambition.crm.ws.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Donghuang
* @date Jun 17, 2022 15:01:49
*/
@Getter
@Setter
@ToString
public class ExportTaskUpdatedWsResp extends BaseWsResp {
private static final long serialVersionUID = 1L;
private Integer countUndownloaded;
public ExportTaskUpdatedWsResp() {
setType("EXPORT_TASK_UPDATED");
}
public ExportTaskUpdatedWsResp(final String employeeKey, final Integer countUndownloaded) {
this();
this.countUndownloaded = countUndownloaded;
setEmployeeKey(employeeKey);
}
}

View File

@ -1,32 +0,0 @@
package com.pudonghot.ambition.crm.ws.service;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotBlank;
import com.pudonghot.ambition.crm.ws.model.BaseWsResp;
import org.springframework.validation.annotation.Validated;
/**
* @author Donghuang
* @date May 30, 2022 15:56:24
*/
@Validated
public interface WebSocketService {
/**
* publish websocket message
*
* @param resp resp
*/
void publish(@NotNull @Valid BaseWsResp resp);
/**
* publish websocket message
*
* @param employeeKey employee key
* @param payload payload
*/
void publish(@NotBlank String employeeKey, @NotNull Object payload);
}

View File

@ -1,36 +0,0 @@
package com.pudonghot.ambition.crm.ws.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.crm.ws.model.BaseWsResp;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.crm.ws.service.WebSocketService;
import org.springframework.messaging.simp.SimpMessagingTemplate;
/**
* @author Donghuang
* @date May 30, 2022 19:07:22
*/
@Slf4j
@Service
public class WebSocketServiceImpl implements WebSocketService {
@Autowired
private SimpMessagingTemplate message;
/**
* {@inheritDoc}
*/
@Override
public void publish(final BaseWsResp resp) {
publish(resp.getEmployeeKey(), resp);
}
@Override
public void publish(final String employeeKey,
final Object payload) {
log.debug("Publish websocket message [{}] -> [{}].", employeeKey, payload);
message.convertAndSend("/topic/" + employeeKey, payload);
}
}

View File

@ -0,0 +1,23 @@
# Server
server.port=8088
# MySQL
datasource.host=127.0.0.1
datasource.port=63306
datasource.database-name=ambition_crm_test
datasource.username=root
datasource.password=696@2^~)oZ@^#*Q
database.backup-dir=/Users/chyxion/Workspaces/ambition-crm/database_backups
database.restore-shell=/data/program/mysql-backup/bin/mysql_restore.sh
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.servlet.multipart.max-file-size=512MB
spring.servlet.multipart.max-request-size=512MB
# File
file.base-path=http://127.0.0.1:1217/lm-f/
# file.base-dir=/Users/chyxion/Workspaces/ambition-crm/files/
file.base-dir=/Users/donghuang/Documents/Workspaces/ambition-crm/files/

View File

@ -1,46 +0,0 @@
server:
port: 8088
spring:
jackson:
default-property-inclusion: NON_NULL
time-zone: GMT+8
serialization:
write-dates-as-timestamps: true
fail-on-empty-beans: false
servlet:
multipart:
max-file-size: 512MB
max-request-size: 512MB
datasource:
database-name: ambition-crm
host: 172.16.4.6
password: MySQL2b||!2b
port: 3306
username: root
database:
backup-dir: d:/data/database_backups
restore-shell: /data/program/mysql-backup/bin/mysql_restore.sh
file:
base-dir: /Users/donghuang/Documents/Workspaces/ambition-crm/files/
base-path: http://127.0.0.1:1217/lm-f/
export:
location: d:/data/export
tigon:
shiro:
session:
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -0,0 +1,18 @@
# Server
server.port=8100
# MySQL
datasource.host=127.0.0.1
datasource.port=43306
datasource.database-name=ambition_crm
datasource.username=root
datasource.password=696@2^~)oZ@^#*Q
database.backup-dir=/data/program/mysql-backup/backup/ambition_crm
database.backup-shell=/data/program/mysql-backup/bin/mysql_restore.sh
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.http.multipart.max-file-size=1024MB
spring.http.multipart.max-request-size=1024MB

View File

@ -1,48 +0,0 @@
server:
port: 8100
spring:
http:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
jackson:
default-property-inclusion: NON_NULL
time-zone: GMT+8
serialization:
write-dates-as-timestamps: true
fail-on-empty-beans: false
servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
datasource:
database-name: ambition_crm
host: 127.0.0.1
password: 696@2^~)oZ@^#*Q
port: 3306
username: root
database:
backup-dir: /data/program/mysql-backup/backup/ambition_crm
restore-shell: /data/program/mysql-backup/bin/mysql-restore.sh
file:
base-dir: /data/program/lemo-crm/files
base-path: http://116.62.189.211/f/
tigon:
shiro:
session:
timeout: 21600000
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -0,0 +1,16 @@
# Server
server.port=80
# MySQL
datasource.host=127.0.0.1
datasource.port=3306
datasource.database-name=ambition_crm
datasource.username=root
datasource.password=696@2^~)oZ@^#*Q
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.http.multipart.max-file-size=1024MB
spring.http.multipart.max-request-size=1024MB

View File

@ -1,47 +0,0 @@
server:
port: 8100
spring:
http:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
jackson:
default-property-inclusion: NON_NULL
time-zone: GMT+8
serialization:
write-dates-as-timestamps: true
fail-on-empty-beans: false
servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
datasource:
database-name: ambition_crm
host: 127.0.0.1
password: 696@2^~)oZ@^#*Q
port: 3306
username: root
database:
backup-dir: /data/program/mysql-backup/backup/ambition_crm
restore-shell: /data/program/mysql-backup/bin/mysql-restore.sh
file:
base-dir: /data/program/lemo-crm/files
base-path: http://116.62.189.211/f/
shiro:
session:
timeout: 21600000
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -10,8 +10,8 @@
<PatternLayout pattern="%highlight{%-d{yyyy-MM-dd HH:mm:ss,SSS}}{FATAL=magenta, ERROR=magenta, WARN=magenta, INFO=magenta, DEBUG=magenta, TRACE=magenta} %highlight{%-5p}{FATAL=red blink, ERROR=red, WARN=yellow bold, INFO=black, DEBUG=green bold, TRACE=blue} [%t][%X{requestId}][%highlight{%c{1.}}{FATAL=cyan, ERROR=cyan, WARN=cyan, INFO=cyan, DEBUG=cyan, TRACE=cyan}] %m%n"/>
</Console>
<RollingFile name="File"
fileName="${log.dir}/app.log"
filePattern="${log.dir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
fileName="${log.dir}/${project.artifactId}.log"
filePattern="${log.dir}/$${date:yyyy-MM}/${project.artifactId}-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${pattern}" />
<Policies>
<TimeBasedTriggeringPolicy />
@ -21,6 +21,9 @@
</RollingFile>
</Appenders>
<Loggers>
<Logger name="org.springframework" level="INFO" additivity="false">
<AppenderRef ref="File" />
</Logger>
<Logger name="org.apache" level="WARN" additivity="false">
<AppenderRef ref="File" />
</Logger>

View File

@ -10,8 +10,8 @@
<PatternLayout pattern="${pattern}" />
</Console>
<RollingFile name="File"
fileName="${log.dir}/app.log"
filePattern="${log.dir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
fileName="${log.dir}/${project.artifactId}.log"
filePattern="${log.dir}/$${date:yyyy-MM}/${project.artifactId}-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${pattern}" />
<Policies>
<TimeBasedTriggeringPolicy />

View File

@ -10,12 +10,12 @@
<PatternLayout pattern="${pattern}" />
</Console>
<RollingFile name="File"
fileName="${log.dir}/app.log"
filePattern="${log.dir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
fileName="${log.dir}/${project.artifactId}.log"
filePattern="${log.dir}/$${date:yyyy-MM}/${project.artifactId}-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="${pattern}" />
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="64 MB" />
<SizeBasedTriggeringPolicy size="16 MB" />
</Policies>
<DefaultRolloverStrategy max="32" />
</RollingFile>

View File

@ -0,0 +1,6 @@
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--<bean class="com.alibaba.druid.pool.DruidDataSource"-->
<!--init-method="init" -->
<!--destroy-method="close" -->
<!--p:url="${db.url}"-->
<!--p:username="${db.user}" -->
<!--p:password="${db.password}" />-->
</beans>

View File

@ -1,148 +0,0 @@
package com.pudonghot.ambition.crm;
import com.pudonghot.ambition.crm.auth.model.Principal;
import lombok.SneakyThrows;
import lombok.val;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author Donghuang
* @date Jan 05, 2022 15:28:35
*/
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AmbitionCRM.class,
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public abstract class MockTestBase {
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected SecurityManager securityManager;
@Autowired
private JsonService jsonService;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
@Before
public void before() throws Exception {
SecurityUtils.setSecurityManager(securityManager);
request = new MockHttpServletRequest(webApplicationContext.getServletContext());
response = new MockHttpServletResponse();
val subject = new WebSubject.Builder(request, response).buildWebSubject();
if (subject instanceof DelegatingSubject) {
val delegatingSubject = (DelegatingSubject) subject;
val fieldPrincipals = DelegatingSubject.class.getDeclaredField("principals");
fieldPrincipals.setAccessible(true);
fieldPrincipals.set(delegatingSubject, new SimplePrincipalCollection(getPrincipal(), "realm"));
val fieldAuthenticated = DelegatingSubject.class.getDeclaredField("authenticated");
fieldAuthenticated.setAccessible(true);
fieldAuthenticated.set(delegatingSubject, true);
val fieldSession = DelegatingSubject.class.getDeclaredField("session");
fieldSession.setAccessible(true);
fieldSession.set(delegatingSubject, getSession());
ThreadContext.bind(delegatingSubject);
}
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* 子类改写
*
* @return principal
*/
protected abstract Principal getPrincipal();
/**
* 子类改写
*
* @return session
*/
protected Session getSession() {
return new SimpleSession();
}
protected String toJsonString(final Object obj) {
return jsonService.toJSONString(obj);
}
/**
* post json
*
* @param path path
* @param payload payload
* @return req builder
*/
protected MvcResult postJson(final String path, final Object payload) {
return perform(MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(toJsonString(payload))
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path) {
return perform(MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path, final Object params) {
val builder = MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON);
if (params != null) {
jsonService.toMap(params).forEach((key, value) -> builder.queryParam(key, String.valueOf(value)));
}
return perform(builder);
}
@SneakyThrows
MvcResult perform(final MockHttpServletRequestBuilder reqBuilder) {
return mockMvc.perform(reqBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
}

View File

@ -1,120 +0,0 @@
package com.pudonghot.ambition.crm;
import lombok.SneakyThrows;
import lombok.val;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.apache.shiro.web.subject.WebSubject;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author Donghuang
* @date Jan 05, 2022 15:28:35
*/
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AmbitionCRM.class,
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public abstract class TestBase {
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected SecurityManager securityManager;
@Autowired
private JsonService jsonService;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
@Before
public void before() throws Exception {
SecurityUtils.setSecurityManager(securityManager);
request = new MockHttpServletRequest(webApplicationContext.getServletContext());
request.addHeader("User-Agent", "Mock-Request");
response = new MockHttpServletResponse();
val subject = new WebSubject.Builder(request, response).buildWebSubject();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* 子类改写
*
* @return session
*/
protected Session getSession() {
return new SimpleSession();
}
protected String toJsonString(final Object obj) {
return jsonService.toJSONString(obj);
}
/**
* post json
*
* @param path path
* @param payload payload
* @return req builder
*/
protected MvcResult postJson(final String path, final Object payload) {
return perform(MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(toJsonString(payload))
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path) {
return perform(MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path, final Object params) {
val builder = MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON);
if (params != null) {
jsonService.toMap(params).forEach((key, value) -> builder.queryParam(key, String.valueOf(value)));
}
return perform(builder);
}
@SneakyThrows
MvcResult perform(final MockHttpServletRequestBuilder reqBuilder) {
return mockMvc.perform(reqBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
}

View File

@ -1,19 +1,27 @@
package com.pudonghot.ambition.crm.controller;
import com.pudonghot.ambition.crm.TestBase;
import lombok.val;
import me.chyxion.tigon.web.test.ControllerTestTool;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
import org.junit.Test;
import java.util.HashMap;
import org.junit.runner.RunWith;
import me.chyxion.tigon.webmvc.test.ControllerTestTool;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.pudonghot.ambition.crm.AmbitionCRM;
/**
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Mar 10, 2017 23:15:16
*/
public class SiteControllerTest extends TestBase {
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AmbitionCRM.class)
public class SiteControllerTest {
@Autowired
private ControllerTestTool t;
@ -34,10 +42,11 @@ public class SiteControllerTest extends TestBase {
}
@Test
public void testAuthLogin() {
val params = new HashMap<String, Object>();
params.put("loginId", "donghuang");
params.put("password", "2b||!2b");
t.print(t.post("/auth/login", params));
public void testPost() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", "id");
params.put("name", "Shaun Chyxion");
params.put("gender", "");
t.print(t.post("/post", params));
}
}

View File

@ -1,14 +1,12 @@
package com.pudonghot.ambition.crm.service;
import java.io.File;
import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import lombok.extern.slf4j.Slf4j;
import com.pudonghot.ambition.crm.AmbitionCRM;
import com.pudonghot.ambition.crm.model.FileInfo;
import com.pudonghot.ambition.file.AmbitionFileApi;
import com.pudonghot.ambition.file.request.AmFileUploadReq;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
@ -29,11 +27,8 @@ public class DiskFileStoreTest {
private AmbitionFileApi<FileInfo> fileApi;
@Test
public void testUpload() {
val req = new AmFileUploadReq();
req.setFile(new File("/Users/chyxion/Workspaces/FileController.java"));
req.setName("foobar");
final FileInfo foobar = fileApi.upload(req);
public void testUpload() throws Exception {
final FileInfo foobar = fileApi.upload(new File("/Users/chyxion/Workspaces//Eclipse/Default/bzush-schoolmate-api/src/main/java/cn/edu/bzu/schoolmate/controllers/FileController.java"), "foobar");
log.info("Upload result [{}].", foobar);
}
}

View File

@ -1,30 +0,0 @@
package com.pudonghot.ambition.crm.service;
import lombok.val;
import org.junit.Test;
import org.junit.runner.RunWith;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.mybatis.Search;
import com.pudonghot.ambition.crm.AmbitionCRM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Donghuang
* @date Sep 27, 2022 15:28:31
*/
@Slf4j
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AmbitionCRM.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testList() {
val users = userService.list(new Search().limit(1));
}
}

View File

@ -1,46 +0,0 @@
server:
port: 8088
spring:
jackson:
default-property-inclusion: NON_NULL
time-zone: GMT+8
serialization:
write-dates-as-timestamps: true
fail-on-empty-beans: false
servlet:
multipart:
max-file-size: 512MB
max-request-size: 512MB
datasource:
database-name: ambition-crm
host: 172.16.4.6
password: MySQL2b||!2b
port: 3306
username: root
database:
backup-dir: d:/data/database_backups
restore-shell: /data/program/mysql-backup/bin/mysql_restore.sh
file:
base-dir: /Users/donghuang/Documents/Workspaces/ambition-crm/files/
base-path: http://127.0.0.1:1217/lm-f/
export:
location: d:/data/export
tigon:
shiro:
session:
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -4,5 +4,5 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Scan Controllers -->
<bean class="me.chyxion.tigon.web.test.ControllerTestTool" />
<bean class="me.chyxion.tigon.webmvc.test.ControllerTestTool" />
</beans>

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.pudonghot.ambition</groupId>
<artifactId>lemo-crm</artifactId>
<version>${revision}</version>
<artifactId>ambition-crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
@ -26,7 +27,7 @@
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-kit</artifactId>
<artifactId>tigon-sequence</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>

View File

@ -3,12 +3,10 @@ package com.pudonghot.ambition.file;
import java.io.File;
import java.util.List;
import java.io.InputStream;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotBlank;
import com.pudonghot.ambition.file.request.AmFileUploadReq;
import org.springframework.validation.annotation.Validated;
import com.pudonghot.ambition.file.request.AmInputStreamUploadReq;
/**
* @version 0.0.4
@ -44,18 +42,67 @@ public interface AmbitionFileApi<UploadReturn> {
@NotBlank String getUrl(@NotBlank String name);
/**
* upload file
* @param req req
* @return result
* Upload File To OSS
* @param file File
* @param name File Name [optional], Such As "foobar.doc",
* A UUID Will Be The Name, If Name Not Specified,
* @return File Link [http://umsapp.oss-cn-hangzhou.aliyuncs.com/echat-dev/foobar.png]
*/
UploadReturn upload(@NotNull @Valid AmFileUploadReq req);
UploadReturn upload(@NotNull File file, String name);
/**
* Upload File
* @param file File
* @param folder Custom Folder
* @param name File Name
* @param contentType Content Type [Optional]
* @param format File Format [Optional]
* @return
*/
UploadReturn upload(@NotNull File file, String folder, String name, String contentType, String format);
/**
* upload file
* @param req req
* @return result
* Upload Stream
* @param ins Input Stream
* @param name File Name
* @return File Link [http://umsapp.oss-cn-hangzhou.aliyuncs.com/echat-dev/foobar.png]
*/
UploadReturn upload(@NotNull @Valid AmInputStreamUploadReq req);
UploadReturn upload(@NotNull InputStream ins, @Min(1) long contentLength, String name);
/**
* Upload Stream
* @param ins Input Stream
* @param folder Custom Folder
* @param name name
* @param contentType Content Type [Optional]
* @param format File Format [Optional]
*/
UploadReturn upload(@NotNull InputStream ins,
@Min(1) long contentLength,
String folder,
String name,
String contentType,
String format);
/**
* Upload Stream To OSS
* @param ins Input Stream
* @param contentLength
* @param folder Custom Folder
* @param name File Name [optional], Such As "foobar.doc",
* A UUID Will Be The Name, If Name Not Specified,
* @param contentType Content Type [Optional]
* @param format File Format [Optional]
* @param downloadName File Download Name [Optional]
* @return
*/
UploadReturn upload(@NotNull InputStream ins,
@Min(1) long contentLength,
String folder,
String name,
String contentType,
String format,
String downloadName);
/**
* Get File From OSS

View File

@ -1,51 +0,0 @@
package com.pudonghot.ambition.file.request;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.File;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
/**
* @author Donghuang
* @date May 29, 2022 12:14:35
*/
@Getter
@Setter
@ToString
public class AmFileUploadReq implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Upload file
*/
@NotNull
private File file;
/**
* custom folder
*/
private String folder;
/**
* optional file name, such as "some-file.doc"
* A UUID will be the name, if name not specified
*/
private String name;
/**
* file content type [optional]
*/
private String contentType;
/**
* file format
*/
private String format;
/**
* file download name
*/
private String downloadName;
}

View File

@ -1,59 +0,0 @@
package com.pudonghot.ambition.file.request;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.InputStream;
import java.io.Serializable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* @author Donghuang
* @date May 29, 2022 12:14:35
*/
@Getter
@Setter
@ToString
public class AmInputStreamUploadReq implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Input stream
*/
@NotNull
private InputStream inputStream;
/**
* file content length
*/
@Min(1)
@NotNull
private Number contentLength;
/**
* custom folder
*/
private String folder;
/**
* optional file name, such as "some-file.doc"
* A UUID will be the name, if name not specified
*/
private String name;
/**
* file content type [optional]
*/
private String contentType;
/**
* file format
*/
private String format;
/**
* file download name
*/
private String downloadName;
}

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.file.support;
import lombok.val;
import java.io.File;
import java.util.List;
import java.io.IOException;
@ -17,13 +16,11 @@ import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import me.chyxion.tigon.sequence.IdSequence;
import com.pudonghot.ambition.file.ImageTool;
import org.springframework.util.MimeTypeUtils;
import me.chyxion.tigon.kit.sequence.IdSequence;
import com.pudonghot.ambition.file.AmbitionFileApi;
import com.pudonghot.ambition.file.request.AmFileUploadReq;
import org.springframework.beans.factory.annotation.Autowired;
import com.pudonghot.ambition.file.request.AmInputStreamUploadReq;
/**
* @version 0.0.1
@ -43,41 +40,55 @@ public abstract class AbstractAmbitionFileApi<UploadReturn> implements AmbitionF
* {@inheritDoc}
*/
@Override
public UploadReturn upload(final AmFileUploadReq fileReq) {
val file = fileReq.getFile();
val folder = fileReq.getFolder();
String name = fileReq.getName();
val contentType = fileReq.getContentType();
String format = fileReq.getFormat();
public UploadReturn upload(final File file, final String folder, String name, final String contentType, String format) {
log.info("Upload input stream file [{}].", name);
if (StringUtils.isBlank(name)) {
name = idSeq.get();
val fileExt = FilenameUtils.getExtension(file.getName());
if (StringUtils.isNotBlank(fileExt)
String fileExt = FilenameUtils.getExtension(file.getName());
if (StringUtils.isNotBlank(fileExt)
&& StringUtils.isBlank(format)) {
format = fileExt;
}
}
val req = new AmInputStreamUploadReq();
try {
req.setInputStream(new FileInputStream(file));
return upload(new FileInputStream(file),
file.length(),
folder,
name,
contentType,
format);
}
catch (FileNotFoundException e) {
throw new IllegalStateException(
"Upload file error caused, file not found", e);
"Upload File Error Caused, File Not Found", e);
}
}
req.setContentLength(file.length());
req.setFolder(folder);
req.setName(name);
req.setContentType(contentType);
req.setFormat(format);
req.setDownloadName(fileReq.getDownloadName());
/**
* {@inheritDoc}
*/
@Override
public UploadReturn upload(File file, String name) {
return upload(file, null, name, null, null);
}
return upload(req);
/**
* {@inheritDoc}
*/
@Override
public UploadReturn upload(InputStream in, long contentLength, String name) {
return upload(in, contentLength, null, name, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public UploadReturn upload(InputStream in,
long contentLength,
String folder, String name,
String contentType, String fileFormat) {
return upload(in, contentLength, folder, name, contentType, fileFormat, null);
}
/**
@ -85,19 +96,25 @@ public abstract class AbstractAmbitionFileApi<UploadReturn> implements AmbitionF
*/
@Override
public byte[] combineAvatars(List<String> members) {
val images = new LinkedList<BufferedImage>();
for (val memberId : members) {
try (val imageInput = getInputStream("avatar/" + memberId)) {
List<BufferedImage> images = new LinkedList<BufferedImage>();
for (String memberId : members) {
InputStream imageInput = null;
try {
imageInput = getInputStream("avatar/" + memberId);
images.add(ImageIO.read(imageInput));
}
catch (IOException e) {
uploadAvatar(memberId, "U", "");
log.error("Read Member [{}] Avatar Error Caused", memberId, e);
}
finally {
IOUtils.closeQuietly(imageInput);
}
}
if (!images.isEmpty()) {
try (val baos = new ByteArrayOutputStream()) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
ImageIO.write(imageTool.combine(images), "png", baos);
return baos.toByteArray();
}
@ -105,9 +122,12 @@ public abstract class AbstractAmbitionFileApi<UploadReturn> implements AmbitionF
throw new IllegalStateException(
"Write Image File Error Caused", e);
}
finally {
IOUtils.closeQuietly(baos);
}
}
throw new IllegalStateException(
"No image found in members " + members);
"No Image Found In Members " + members);
}
/**
@ -132,14 +152,11 @@ public abstract class AbstractAmbitionFileApi<UploadReturn> implements AmbitionF
@Override
public UploadReturn uploadAvatar(String folder, String memberId, String name, String gender) {
byte[] bytesAvatar = imageTool.genAvatar(name, gender);
val req = new AmInputStreamUploadReq();
req.setInputStream(new ByteArrayInputStream(bytesAvatar));
req.setContentLength(bytesAvatar.length);
req.setFolder(folder);
req.setName(memberId);
req.setContentType(MimeTypeUtils.IMAGE_PNG_VALUE);
req.setFormat("png");
return upload(req);
return upload(new ByteArrayInputStream(bytesAvatar),
bytesAvatar.length,
folder,
memberId,
MimeTypeUtils.IMAGE_PNG_VALUE, "png");
}
/**
@ -185,21 +202,15 @@ public abstract class AbstractAmbitionFileApi<UploadReturn> implements AmbitionF
String format = imageTool.imageType(new ByteArrayInputStream(bytesFile));
if (StringUtils.isNotBlank(format)) {
if (!ArrayUtils.contains(new String[] {"png", "jpg", "jpeg"}, format)) {
log.info("Image file type is not `JPG` Or `PNG`, convert to JPG.");
log.info("Image File Type Is Not JPG Or PNG, Convert To JPG.");
bytesFile = imageTool.toJpegBytes(bytesFile);
format = "jpg";
}
log.info("Upload Image With Folder [{}], Name [{}], Format [{}].", folder, name, format);
val req = new AmInputStreamUploadReq();
req.setInputStream(new ByteArrayInputStream(bytesFile));
req.setContentLength(bytesFile.length);
req.setFolder(folder);
req.setName(name);
req.setContentType("image/" + format);
req.setFormat(format);
return upload(req);
return upload(
new ByteArrayInputStream(bytesFile),
bytesFile.length,
folder, name, "image/" + format, format);
}
else {
throw new IllegalArgumentException(

View File

@ -6,11 +6,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>file-disk</artifactId>
<name>Ambition File Disk</name>
<packaging>jar</packaging>
<parent>
<groupId>com.pudonghot.ambition</groupId>
<artifactId>lemo-crm</artifactId>
<version>${revision}</version>
<artifactId>ambition-crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
@ -22,6 +24,10 @@
<groupId>com.pudonghot.ambition</groupId>
<artifactId>crm-mapper</artifactId>
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-sequence</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>

View File

@ -1,7 +1,6 @@
package com.pudonghot.ambition.file.disk;
import java.io.*;
import lombok.val;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
@ -16,7 +15,6 @@ import com.pudonghot.ambition.crm.mapper.FileInfoMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.pudonghot.ambition.file.request.AmInputStreamUploadReq;
import com.pudonghot.ambition.file.support.AbstractAmbitionFileApi;
/**
@ -43,11 +41,11 @@ public class DiskFileSupport
* {@inheritDoc}
*/
@Override
public InputStream getInputStream(final String name) {
public InputStream getInputStream(String name) {
try {
return new FileInputStream(getFile(name));
}
catch (final FileNotFoundException e) {
catch (FileNotFoundException e) {
throw new IllegalStateException(
"Get file [" + name + "] input stream error caused");
}
@ -67,7 +65,7 @@ public class DiskFileSupport
@Override
@Transactional(rollbackFor = Throwable.class)
public void delete(final String name) {
val fileInfo = findFileInfo(name);
final FileInfo fileInfo = findFileInfo(name);
if (fileInfo != null) {
fileInfoMapper.delete(fileInfo.getId());
FileUtils.deleteQuietly(getFile(fileInfo));
@ -87,24 +85,23 @@ public class DiskFileSupport
*/
@Override
@Transactional
public FileInfo upload(final AmInputStreamUploadReq req) {
val folder = req.getFolder();
val name = req.getName();
val fileId = idSeq.get();
val fullName = getFileFullName(fileId, folder, name);
public FileInfo upload(final InputStream in,
final long contentLength,
String folder,
final String name,
String contentType,
String fileFormat,
String downloadName) {
final String fileId = idSeq.get();
final String fullName = getFileFullName(fileId, folder, name);
boolean update = false;
val now = new Date();
Date now = new Date();
FileInfo fileInfo = findFileInfo(fullName);
if (fileInfo != null) {
fileInfo.setDateUpdated(now);
update = true;
// delete previous file
val prevFile = getFile(fileInfo);
final File prevFile = getFile(fileInfo);
log.info("Will delete previous file [{}].", prevFile);
// delete previous files
if (prevFile != null) {
@ -119,15 +116,12 @@ public class DiskFileSupport
fileInfo.setDateCreated(now);
}
val fileFormat = req.getFormat();
val filePath = getFilePath(fileId, folder, name, fileFormat);
final String filePath = getFilePath(fileId, folder, name, fileFormat);
fileInfo.setFilePath(filePath);
fileInfo.setEnabled(true);
fileInfo.setContentLength(req.getContentLength().longValue());
fileInfo.setDownloadName(req.getDownloadName());
fileInfo.setContentType(StringUtils.defaultIfBlank(req.getContentType(),
fileInfo.setContentLength(contentLength);
fileInfo.setDownloadName(downloadName);
fileInfo.setContentType(StringUtils.defaultIfBlank(contentType,
MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE));
fileInfo.setFormat(fileFormat);
@ -140,24 +134,29 @@ public class DiskFileSupport
// File
log.info("Upload input stream with name [{}].", fullName);
OutputStream fout = null;
try {
val storeFile = new File(getFileDir(), filePath);
val fileParent = storeFile.getParentFile();
if (!fileParent.isDirectory()) {
fileParent.mkdirs();
}
final File storeFile = new File(getFileDir(), filePath);
final File fileParent = storeFile.getParentFile();
if (!fileParent.isDirectory()) {
fileParent.mkdirs();
}
try (val in = req.getInputStream();
val fout = new FileOutputStream(storeFile)) {
fout = new FileOutputStream(storeFile);
IOUtils.copy(in, fout);
// return basePath + fullName;
fileInfo.setUrl(basePath + filePath);
return fileInfo;
}
catch (IOException e) {
throw new IllegalStateException(
"Upload file [" + fullName + "] error caused", e);
"Upload file [" + fullName + "] error caused", e);
}
finally {
IOUtils.closeQuietly(fout);
IOUtils.closeQuietly(in);
}
// return basePath + fullName;
fileInfo.setUrl(basePath + filePath);
return fileInfo;
}
/**
@ -165,7 +164,7 @@ public class DiskFileSupport
*/
@Override
public File getFile(final String name) {
val fileInfo = findFileInfo(name);
final FileInfo fileInfo = findFileInfo(name);
return fileInfo != null ? getFile(fileInfo): null;
}
@ -173,7 +172,7 @@ public class DiskFileSupport
* {@inheritDoc}
*/
@Override
public long getContentLength(final String name) {
public long getContentLength(String name) {
return getFile(name).length();
}
@ -181,16 +180,23 @@ public class DiskFileSupport
* {@inheritDoc}
*/
@Override
public String getUrl(final String folder, String name) {
val fileFullName = prependFolder(folder, name);
val fileInfo = findFileInfo(fileFullName);
if (fileInfo != null) {
return basePath + fileInfo.getFilePath();
public String getUrl(String folder, String name) {
String fileFullName = null;
if (StringUtils.isNotBlank(folder)) {
if (!folder.endsWith("/")) {
folder += "/";
}
fileFullName = folder + name;
}
log.error("No File [{}] Found.", fileFullName);
return basePath + fileFullName;
else {
fileFullName = name;
}
final FileInfo fileInfo = findFileInfo(fileFullName);
if (fileInfo == null) {
log.error("No File [{}] Found.", fileFullName);
return basePath + fileFullName;
}
return basePath + fileInfo.getFilePath();
}
/**
@ -221,8 +227,8 @@ public class DiskFileSupport
* {@inheritDoc}
*/
@Override
public void deleteById(final String id) {
val fileInfo = fileInfoMapper.find(id);
public void deleteById(String id) {
final FileInfo fileInfo = fileInfoMapper.find(id);
if (fileInfo != null) {
log.info("Delete file [{}].", fileInfo);
fileInfoMapper.delete(id);
@ -234,35 +240,54 @@ public class DiskFileSupport
// private methods
File getFileDir() {
val baseFileDir = new File(baseDir);
File baseFileDir = new File(baseDir);
if (!baseFileDir.exists()) {
baseFileDir.mkdirs();
}
return baseFileDir;
}
String getFileFullName(final String fileId,
final String folder,
final String name) {
String getFileFullName(String fileId, String folder, String name) {
if (StringUtils.isNotBlank(folder)) {
if (!folder.endsWith("/")) {
folder += "/";
}
}
String fullName = null;
if (StringUtils.isNotBlank(name)) {
log.debug("Name [{}] is not blank.", name);
if (name.startsWith(basePath)) {
log.debug("Name starts with base path [{}], trim.", basePath);
return name.replaceFirst(basePath, "");
fullName = name.replaceFirst(basePath, "");
}
else if (StringUtils.isNotBlank(folder)) {
fullName = folder + name;
}
else {
fullName = name;
}
}
return prependFolder(folder, fileId);
// name is blank, folder is not blank
else if (StringUtils.isNotBlank(folder)) {
fullName = folder + fileId;
}
// name and folder are blank
else {
fullName = fileId;
}
return fullName;
}
String getFilePath(final String fileId,
final String folder,
final String name,
final String fileFormat) {
val distFolder = prependFolder(folder,
DateFormatUtils.format(new Date(), "yyyyMMdd") + "/");
String getFilePath(final String fileId, final String folder, final String name, String fileFormat) {
String distFolder = DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
if (StringUtils.isNotBlank(folder)) {
if (folder.endsWith("/")) {
distFolder = folder + distFolder;
}
else {
distFolder = folder + "/" + distFolder;
}
}
String filePath = null;
if (StringUtils.isNotBlank(name)) {
@ -282,14 +307,4 @@ public class DiskFileSupport
return StringUtils.isNotBlank(fileFormat) ?
filePath + "." + fileFormat : filePath;
}
String prependFolder(final String folder, final String file) {
if (StringUtils.isNotBlank(folder)) {
if (folder.endsWith("/")) {
return folder + file;
}
return folder + "/" + file;
}
return file;
}
}

2
server/start.sh → server/launch.sh Normal file → Executable file
View File

@ -23,8 +23,6 @@ pushd $(dirname "$prg_path")
WORK_DIR=$(pwd)
echo "Work dir [$WORK_DIR]"
export MAVEN_OPTS='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000'
mvn -T 4C clean -pl crm -am -DskipTests \
-Dspring-boot.run.fork=false \
spring-boot:run

View File

@ -11,8 +11,9 @@
<parent>
<groupId>com.pudonghot.ambition</groupId>
<artifactId>lemo-crm</artifactId>
<version>${revision}</version>
<artifactId>ambition-crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<modules>

@ -1 +1 @@
Subproject commit 2b1df37ce5b3aa0ae401c0368c2156b1b8f27d3b
Subproject commit 40acef80b8af560cbf19a0a841748c0d63406dde

View File

@ -6,11 +6,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>crm-mapper</artifactId>
<name>Ambition Mapper</name>
<packaging>jar</packaging>
<parent>
<groupId>com.pudonghot.ambition</groupId>
<artifactId>lemo-crm</artifactId>
<version>${revision}</version>
<artifactId>ambition-crm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
@ -48,11 +50,6 @@
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -1,4 +0,0 @@
package com.pudonghot.ambition.crm;
public class Test {
}

View File

@ -33,7 +33,7 @@ public interface CustomerMapper extends BaseMapper<String, Customer> {
* @return customers
*/
List<Customer> listForShow(
@NotNull @Param(PARAM_SEARCH_KEY) Search search,
@NotNull @Param("s") Search search,
@Param("account") String account);
/**
@ -67,7 +67,7 @@ public interface CustomerMapper extends BaseMapper<String, Customer> {
* @return count of customers
*/
int countForShow(
@NotNull @Param(PARAM_SEARCH_KEY) Search search,
@NotNull @Param("s") Search search,
@Param("account") String account);
List<Map<String, String>> listMs();

View File

@ -234,24 +234,24 @@
<sql id="showFilter">
<!-- Application not null -->
<if test="__search__.getAttr('APPLICATION_NOT_NULL') != null">
<if test="s.getAttr('APPLICATION_NOT_NULL') != null">
join (select distinct customer_id
from crm_customer_application) app_not_null
on customer.id = app_not_null.customer_id
</if>
<if test="__search__.getAttr('APPLICATIONS') != null">
<if test="s.getAttr('APPLICATIONS') != null">
join (select distinct customer_id
from crm_customer_application
where application_id in
<foreach item="appId" collection="__search__.getAttr('APPLICATIONS')" open="(" close=")" separator=",">
<foreach item="appId" collection="s.getAttr('APPLICATIONS')" open="(" close=")" separator=",">
#{appId}
</foreach>
) app
on customer.id = app.customer_id
</if>
<if test="__search__.getAttr('YTD_SALE') != null">
<if test="s.getAttr('YTD_SALE') != null">
left join (select customer_id, max(year) year
from crm_customer_year_to_date_sale
where enabled = 1

View File

@ -1,11 +0,0 @@
package com.pudonghot.ambition.crm.mapper;
import me.chyxion.tigon.mybatis.BaseMapper;
import com.pudonghot.ambition.crm.model.ExportTask;
/**
* @author Donghuang
* @date May 29, 2022 14:44:46
*/
public interface ExportTaskMapper extends BaseMapper<Long, ExportTask> {
}

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
* @author Donghuang
* @date Jun 18, 2022 10:07:26
*/
-->
<!DOCTYPE mapper PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pudonghot.ambition.crm.mapper.ExportTaskMapper">
</mapper>

View File

@ -18,12 +18,12 @@ public interface ImportRecordMapper extends BaseMapper<String, ImportRecord> {
* @param search search
* @return import records
*/
List<ImportRecord> listForShow(@Param(PARAM_SEARCH_KEY) Search search);
List<ImportRecord> listForShow(@Param("s") Search search);
/**
* count for show
* @param search search
* @return count of import records
*/
int countForShow(@Param(PARAM_SEARCH_KEY) Search search);
int countForShow(@Param("s") Search search);
}

View File

@ -20,14 +20,14 @@ public interface WeekGoalMapper extends BaseMapper<String, WeekGoal> {
* @param search search
* @return week goals
*/
List<WeekGoal> listJoinUser(@Param(PARAM_SEARCH_KEY) Search search);
List<WeekGoal> listJoinUser(@Param("s") Search search);
/**
* count join user
* @param search search
* @return count of week goals
*/
int countJoinUser(@Param(PARAM_SEARCH_KEY) Search search);
int countJoinUser(@Param("s") Search search);
/**
* @return list user

View File

@ -2,9 +2,15 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init"
destroy-method="close"
@ -14,9 +20,15 @@
p:connectionInitSqls="set names utf8mb4;"
/>
<!-- Transaction -->
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- MyBatis SqlSessionFactory -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean"
class="me.chyxion.tigon.mybatis.TigonSqlSessionFactoryBean"
p:dataSource-ref="dataSource"
p:typeAliasesPackage="com.pudonghot.ambition.crm.model"
p:configLocation="classpath:mybatis/mybatis-config.xml"

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.crm.mapper;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Test;
import java.util.Date;
import org.junit.Assert;
@ -35,7 +34,7 @@ public class AuthFailedLogMapperTest extends AbstractTransactionalJUnit4SpringCo
m.setUserAgent("s");
m.setExt("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
AuthFailedLog m1 = mapper.find(id);
@ -64,7 +63,7 @@ public class AuthFailedLogMapperTest extends AbstractTransactionalJUnit4SpringCo
Assert.assertEquals("S", m.getUserAgent());
Assert.assertEquals("S", m.getExt());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.crm.mapper;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Test;
import java.util.Date;
import org.junit.Assert;
@ -34,7 +33,7 @@ public class AuthLogMapperTest extends AbstractTransactionalJUnit4SpringContextT
m.setIp("s");
m.setExt("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
AuthLog m1 = mapper.find(id);
@ -60,7 +59,7 @@ public class AuthLogMapperTest extends AbstractTransactionalJUnit4SpringContextT
Assert.assertEquals("S", m.getIp());
Assert.assertEquals("S", m.getExt());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,6 +1,5 @@
package com.pudonghot.ambition.crm.mapper;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Test;
import java.util.Date;
import org.junit.Assert;
@ -34,7 +33,7 @@ public class CustomerApplicationMapperTest extends AbstractTransactionalJUnit4Sp
m.setCustomerId("s");
m.setApplicationId("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
CustomerApplication m1 = mapper.find(id);
@ -54,7 +53,7 @@ public class CustomerApplicationMapperTest extends AbstractTransactionalJUnit4Sp
Assert.assertEquals("S", m.getCustomerId());
Assert.assertEquals("S", m.getPropertyId());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,7 +1,6 @@
package com.pudonghot.ambition.crm.mapper;
import com.pudonghot.ambition.crm.model.CustomerIssue;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -35,7 +34,7 @@ public class CustomerIssueMapperTest extends AbstractTransactionalJUnit4SpringCo
m.setCustomerId("s");
m.setIssue("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
CustomerIssue m1 = mapper.find(id);
@ -55,7 +54,7 @@ public class CustomerIssueMapperTest extends AbstractTransactionalJUnit4SpringCo
Assert.assertEquals("S", m.getCustomerId());
Assert.assertEquals("S", m.getIssue());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,7 +1,6 @@
package com.pudonghot.ambition.crm.mapper;
import com.pudonghot.ambition.crm.model.Customer;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -41,7 +40,7 @@ public class CustomerMapperTest extends AbstractTransactionalJUnit4SpringContext
m.setRegion("s");
m.setStatus("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
Customer m1 = mapper.find(id);
@ -79,7 +78,7 @@ public class CustomerMapperTest extends AbstractTransactionalJUnit4SpringContext
Assert.assertEquals("S", m.getRegion());
Assert.assertEquals("S", m.getLevel());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,7 +1,6 @@
package com.pudonghot.ambition.crm.mapper;
import com.pudonghot.ambition.crm.model.CustomerPermission;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -35,7 +34,7 @@ public class CustomerPermissionMapperTest extends AbstractTransactionalJUnit4Spr
m.setUserAccount("s");
m.setCustomerId("s");
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
CustomerPermission m1 = mapper.find(id);
@ -55,7 +54,7 @@ public class CustomerPermissionMapperTest extends AbstractTransactionalJUnit4Spr
Assert.assertEquals("S", m.getUserAccount());
Assert.assertEquals("S", m.getCustomerId());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

View File

@ -1,7 +1,6 @@
package com.pudonghot.ambition.crm.mapper;
import com.pudonghot.ambition.crm.model.CustomerYearToDateSale;
import me.chyxion.tigon.mybatis.Search;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -36,7 +35,7 @@ public class CustomerYearToDateSaleMapperTest extends AbstractTransactionalJUnit
m.setYear("s");
m.setYtdSale(1L);
mapper.insert(m);
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
/*
// Your Test Logics
CustomerYearToDateSale m1 = mapper.find(id);
@ -59,7 +58,7 @@ public class CustomerYearToDateSaleMapperTest extends AbstractTransactionalJUnit
Assert.assertEquals("S", m.getYear());
Assert.assertEquals(2L, m.getYtdSale());
// list
Assert.assertTrue(mapper.list(new Search()).size() > 0);
Assert.assertTrue(mapper.list(null).size() > 0);
// delete
mapper.delete(id);
m1 = mapper.find(id);

Some files were not shown because too many files have changed in this diff Show More