Commit 53e4bbe3 authored by Vu Duy Anh's avatar Vu Duy Anh

anhvd accept merge

parents 7b4fe988 bf2e747e
log4j.rootLogger=INFO, R, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=[%t] %d{dd/MM/yyyy HH:mm:ss} %5p %c{1}: (%L) : %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.DatePattern='.'yyyy-MM-dd
log4j.appender.R.File=log/campaign.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%t] %d{dd/MM/yyyy HH:mm:ss} %5p %c{1}: (%L) : %m%n
\ No newline at end of file
[main] 19/08/2019 17:50:53 INFO RedisUtil: (38) : Start connect Redis: 10.60.156.82:8011,10.60.156.82:8012,10.60.156.82:8013,10.60.156.82:8014,10.60.156.82:8015,10.60.156.82:8016
[main] 19/08/2019 17:53:34 INFO RedisUtil: (38) : Start connect Redis: 10.60.156.82:8011,10.60.156.82:8012,10.60.156.82:8013,10.60.156.82:8014,10.60.156.82:8015,10.60.156.82:8016
......@@ -49,8 +49,8 @@
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<!-- <scope>system</scope>-->
<!-- <systemPath>${project.basedir}/lib/ojdbc7.jar</systemPath>-->
<scope>system</scope>
<systemPath>${project.basedir}/lib/ojdbc7.jar</systemPath>
<version>1.0</version>
</dependency>
<dependency>
......@@ -121,17 +121,18 @@
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.cronutils</groupId>
<artifactId>cron-utils</artifactId>
<version>9.0.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
......@@ -153,45 +154,8 @@
</dependencies>
<!--<dependencyManagement>-->
<!--<dependencies>-->
<!--<dependency>-->
<!--<groupId>org.springframework.cloud</groupId>-->
<!--<artifactId>spring-cloud-dependencies</artifactId>-->
<!--<version>${spring-cloud.version}</version>-->
<!--<type>pom</type>-->
<!--<scope>import</scope>-->
<!--</dependency>-->
<!--</dependencies>-->
<!--</dependencyManagement>-->
<build>
<plugins>
<!--<plugin>-->
<!--<groupId>org.asciidoctor</groupId>-->
<!--<artifactId>asciidoctor-maven-plugin</artifactId>-->
<!--<version>1.5.3</version>-->
<!--<executions>-->
<!--<execution>-->
<!--<id>generate-docs</id>-->
<!--<phase>prepare-package</phase>-->
<!--<goals>-->
<!--<goal>process-asciidoc</goal>-->
<!--</goals>-->
<!--<configuration>-->
<!--<backend>html</backend>-->
<!--<doctype>book</doctype>-->
<!--</configuration>-->
<!--</execution>-->
<!--</executions>-->
<!--<dependencies>-->
<!--<dependency>-->
<!--<groupId>org.springframework.restdocs</groupId>-->
<!--<artifactId>spring-restdocs-asciidoctor</artifactId>-->
<!--<version>${spring-restdocs.version}</version>-->
<!--</dependency>-->
<!--</dependencies>-->
<!--</plugin>-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
......
package com.viettel.campaign.config;
//import com.viettel.campaign.job.CampaignJob;
import com.viettel.campaign.job.CampaignJob;
import com.viettel.campaign.service.ApParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
......
......@@ -25,33 +25,33 @@ public class CorsFilter implements Filter {
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept, token1, X-Auth-Token");
HttpServletRequest request = (HttpServletRequest) req;
chain.doFilter(req, resp);
// if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
// chain.doFilter(req, resp);
// return;
// }
// if ("/".equals(request.getRequestURI())) {
// chain.doFilter(req, resp);
// return;
// }
// String xAuthToken = request.getHeader("X-Auth-Token");
// if (xAuthToken == null || "".equals(xAuthToken)) {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is null.");
// return;
// }
// Object obj = RedisUtil.getInstance().get(xAuthToken);
// if (obj instanceof UserSession) {
// chain.doFilter(req, resp);
// } else {
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is invalid.");
// }
// chain.doFilter(req, resp);
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
chain.doFilter(req, resp);
return;
}
if ("/".equals(request.getRequestURI())) {
chain.doFilter(req, resp);
return;
}
String xAuthToken = request.getHeader("X-Auth-Token");
if (xAuthToken == null || "".equals(xAuthToken)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is null.");
return;
}
Object obj = RedisUtil.getInstance().get(xAuthToken);
if (obj instanceof UserSession) {
chain.doFilter(req, resp);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is invalid.");
}
}
@Override
......
......@@ -21,7 +21,7 @@ public class CustomerMapper extends BaseMapper<Customer, CustomerDTO> {
obj.setMobileNumber(model.getMobileNumber());
obj.setName(model.getName());
obj.setSiteId(model.getSiteId());
obj.setStatus(model.getStatus());
obj.setStatus(model.getStatus().toString());
// String additionalInfo = "";
// if (model.getName() != null && !"".equals(model.getName())) {
// additionalInfo += model.getName();
......@@ -58,7 +58,7 @@ public class CustomerMapper extends BaseMapper<Customer, CustomerDTO> {
obj.setCustomerImg(dtoBean.getCustomerImg());
obj.setCreateDate(dtoBean.getCreateDate());
obj.setUpdateDate(dtoBean.getUpdateDate());
obj.setStatus(dtoBean.getStatus());
obj.setStatus(Long.parseLong(dtoBean.getStatus()));
obj.setCreateBy(dtoBean.getCreateBy());
obj.setUpdateBy(dtoBean.getUpdateBy());
obj.setSiteId(dtoBean.getSiteId());
......@@ -71,7 +71,7 @@ public class CustomerMapper extends BaseMapper<Customer, CustomerDTO> {
obj.setUserName(dtoBean.getUserName());
obj.setAreaCode(dtoBean.getAreaCode());
obj.setCustomerType(dtoBean.getCustomerType());
obj.setCallAllowed(dtoBean.getCallAllowed());
obj.setCallAllowed(Long.parseLong(dtoBean.getCallAllowed()));
obj.setEmailAllowed(dtoBean.getEmailAllowed());
obj.setSmsAllowed(dtoBean.getSmsAllowed());
obj.setIpccStatus(dtoBean.getIpccStatus());
......
......@@ -45,7 +45,7 @@ public class Customer implements Serializable {
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
@Column(name = "STATUS")
private String status;
private Long status;
@Size(max = 50)
@Column(name = "CREATE_BY")
private String createBy;
......@@ -80,7 +80,7 @@ public class Customer implements Serializable {
@Column(name = "CUSTOMER_TYPE")
private Long customerType;
@Column(name = "CALL_ALLOWED")
private String callAllowed;
private Long callAllowed;
@Column(name = "EMAIL_ALLOWED")
private Long emailAllowed;
@Column(name = "SMS_ALLOWED")
......@@ -88,4 +88,7 @@ public class Customer implements Serializable {
@Size(max = 100)
@Column(name = "IPCC_STATUS")
private String ipccStatus;
@Size(max = 2000)
@Column(name = "AVATAR_LINK")
private String avatarLink;
}
......@@ -43,4 +43,6 @@ public class CustomerContact {
@Column(name = "END_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date endDate;
@Column(name = "SITE_ID")
private Long siteId;
}
package com.viettel.campaign.model.ccms_full;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
......@@ -13,6 +15,8 @@ import java.util.Date;
@Table(name = "CUSTOMER_LIST")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CustomerList implements Serializable {
@Id
......
package com.viettel.campaign.model.ccms_full;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Entity
@Table(name = "CUSTOMER_LIST_MAPPING")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CustomerListMapping implements Serializable {
@Id
@GeneratedValue(generator = "customer_list_mapping_seq")
@SequenceGenerator(name = "customer_list_mapping_seq", sequenceName = "customer_list_mapping_seq", allocationSize = 1)
@Basic(optional = false)
@NotNull
@Column(name = "CUSTOMER_LIST_MAPPING_ID")
private Long customerListMappingId;
@NotNull
@Column(name = "CUSTOMER_ID")
private Long customerId;
@Column(name = "COMPANY_SITE_ID")
private Long companySiteId;
@NotNull
@Column(name = "CUSTOMER_LIST_ID")
private Long customerListId;
}
package com.viettel.campaign.web.dto;
package com.viettel.campaign.model.ccms_full;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "CUSTOMIZE_FIELD_OBJECT")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CustomizeFieldDTO {
public class CustomizeFieldObject implements Serializable {
@Id
@GeneratedValue(generator = "CUSTOMIZE_FIELD_OBJECT_SEQ")
@SequenceGenerator(name = "CUSTOMIZE_FIELD_OBJECT_SEQ", sequenceName = "CUSTOMIZE_FIELD_OBJECT_SEQ", allocationSize = 1)
@Basic(optional = false)
@NotNull
@Column(name = "CUSTOMIZE_FIELD_OBJECT_ID")
private Long customizeFieldObjectId;
@Column(name = "OBJECT_ID")
private Long objectId;
@Column(name = "CUSTOMIZE_FIELDS_ID")
private Long customizeFieldId;
@Column(name = "VALUE_TEXT")
private String valueText;
@Column(name = "VALUE_NUMBER")
private Long valueNumber;
@Column(name = "VALUE_DATE")
private Date valueDate;
@Column(name = "VALUE_CHECKBOX")
private Long valueCheckbox;
private Date createBy;
@Column(name = "CREATE_BY")
private String createBy;
@Column(name = "CREATE_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "UPDATE_BY")
private String updateBy;
@Column(name = "UPDATE_DATE")
private Date updateDate;
@Column(name = "STATUS")
private Long status;
@Column(name = "FIELD_OPTION_VALUE_ID")
private Long fieldOptionValueId;
@Column(name = "TITLE")
private String title;
@Column(name = "FUNCTION_CODE")
private String functionCode;
}
package com.viettel.campaign.model.ccms_full;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "CUSTOMIZE_FIELD_OPTION_VALUE")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CustomizeFieldOptionValue implements Serializable {
@Id
@Column(name = "FIELD_OPTION_VALUE_ID")
@Basic(optional = false)
@NotNull
private Long fieldOptionValueId;
@Column(name = "FIELD_OPTION_ID")
private Long fieldOptionId;
@Column(name = "NAME")
private String name;
@Column(name = "VALUE")
private String value;
@Column(name = "POSITION")
private Long position;
@Column(name = "CREATE_BY")
private String createBy;
@Column(name = "CREATE_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "UPDATE_BY")
private String updateBy;
@Column(name = "UPDATE_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
@Column(name = "STATUS")
private Long status;
}
package com.viettel.campaign.web.dto;
package com.viettel.campaign.model.ccms_full;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "CUSTOMIZE_FIELDS")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DynamicExcelHeaderDTO {
public class CustomizeFields implements Serializable {
@Id
@GeneratedValue(generator = "CUSTOMIZE_FIELDS_SEQ")
@SequenceGenerator(name = "CUSTOMIZE_FIELDS_SEQ", sequenceName = "CUSTOMIZE_FIELDS_SEQ", allocationSize = 1)
@Basic(optional = false)
@NotNull
@Column(name = "CUSTOMIZE_FIELD_ID")
private Long customizeFieldId;
@Column(name = "SITE_ID")
private Long siteId;
@Column(name = "FUNCTION_CODE")
private String functionCode;
@Column(name = "CREATE_BY")
private String createBy;
@Column(name = "CREATE_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date createDate;
@Column(name = "UPDATE_BY")
private String updateBy;
@Column(name = "UPDATE_DATE")
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
@Column(name = "STATUS")
private Long status;
@Column(name = "TYPE")
private String type;
@Column(name = "TITLE")
private String title;
@Column(name = "PLACEHOLDER")
private String placeholder;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "POSITION")
private Long position;
@Column(name = "REQUIRED")
private Long required;
@Column(name = "FIELD_OPTIONS_ID")
private Long fieldOptionsId;
@Column(name = "REGEXP_FOR_VALIDATION")
private String regexpForValidation;
@Column(name = "MAX_LENGTH")
private Long maxLength;
@Column(name = "MIN_LENGTH")
private Long minLength;
@Column(name = "MIN")
private Long min;
@Column(name = "MAX")
private Long max;
@Column(name = "ACTIVE")
private Long active;
public CustomizeFields(String type, String title) {
this.type = type;
this.title = title;
}
}
......@@ -26,4 +26,6 @@ public interface CampaignRepositoryCustom {
ResultDTO getListFieldsNotShow(CampaignRequestDTO dto);
//hungtt
ResultDTO getListFieldsToShow(CampaignRequestDTO dto);
//hungtt
ResultDTO getCampaignCustomerList(CampaignRequestDTO dto);
}
......@@ -11,4 +11,6 @@ import java.util.List;
public interface CustomerContactRepository extends JpaRepository<CustomerContact, Long> {
@Query("FROM CustomerContact WHERE status = 1 AND customerId = :customerId AND contactType = :contactType AND (contact IS NULL OR UPPER(contact) LIKE UPPER(concat('%', :contact, '%')))")
List<CustomerContact> findByCustomerIdAndAndContactTypeAndContact(@Param("customerId") Long customerId, @Param("contactType") Short contactType, @Param("contact") String contact, Pageable pageable);
CustomerContact findCustomerContactByContactTypeAndContactAndIsDirectLine(Short contactType, String contact, Short isDirectLine);
}
package com.viettel.campaign.repository.ccms_full;
import com.viettel.campaign.model.ccms_full.CustomizeFieldObject;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CustomizeFieldObjectRepository extends JpaRepository<CustomizeFieldObject, Long> {
List<CustomizeFieldObject> findCustomizeFieldObjectsByFunctionCodeEqualsAndObjectId(String str, Long id);
}
package com.viettel.campaign.repository.ccms_full;
import com.viettel.campaign.model.ccms_full.CustomizeFieldOptionValue;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CustomizeFieldOptionValueRepository extends JpaRepository<CustomizeFieldOptionValue, Long> {
List<CustomizeFieldOptionValue> findCustomizeFieldOptionValuesByFieldOptionIdAndStatus(Long id, Long status);
CustomizeFieldOptionValue findCustomizeFieldOptionValueByNameEqualsAndStatus(String name, Long status);
}
package com.viettel.campaign.repository.ccms_full;
import com.viettel.campaign.model.ccms_full.CustomizeFields;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CustomizeFieldsRepository extends JpaRepository<CustomizeFields, Long> {
List<CustomizeFields> findCustomizeFieldsByFunctionCodeEqualsAndStatusAndActiveAndSiteId(String functionCode, Long status, Long active, Long siteId);
}
......@@ -20,4 +20,6 @@ public interface TimeRangeDialModeRepository extends JpaRepository<TimeRangeDial
@Query(value = "SELECT * FROM TIME_RANGE_DIAL_MODE r " +
"WHERE r.CAMPAIGN_ID = :campaignId AND r.COMPANY_SITE_ID = :companySiteId AND TO_CHAR(r.START_TIME,'HH24:MI:SS') <= TO_CHAR(SYSDATE,'HH24:MI:SS')", nativeQuery = true)
TimeRangeDialMode findDialModeAtCurrent(@Param("campaignId") Long campaignId, @Param("companySiteId") Long companySiteId);
void deleteAllByCampaignIdAndCompanySiteId(Long campaignId, Long companySiteId);
}
......@@ -20,4 +20,6 @@ public interface TimeZoneDialModeRepository extends JpaRepository<TimeZoneDialMo
@Query(value = "SELECT * FROM TIME_ZONE_DIAL_MODE z " +
"WHERE z.CAMPAIGN_ID = :campaignId AND z.COMPANY_SITE_ID = :companySiteId AND concat(z.HOUR, ':', z.MINUTE) <= TO_CHAR(SYSDATE,'HH24:MI')", nativeQuery = true)
TimeZoneDialMode findDialModeAtCurrent(@Param("campaignId") Long campaignId, @Param("companySiteId") Long companySiteId);
void deleteAllByCampaignIdAndCompanySiteId(Long campaignId, Long companySiteId);
}
......@@ -14,10 +14,7 @@ import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.DateType;
import org.hibernate.type.LongType;
import org.hibernate.type.ShortType;
import org.hibernate.type.StringType;
import org.hibernate.type.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -107,7 +104,10 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
ResultDTO resultDTO = new ResultDTO();
List<ContactCusResDTO> list = new ArrayList<>();
Map<String, Object> params = new HashMap<>();
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
// String sql = SQLBuilder.getSqlQueryById(Constants.SQL_MODULES.MODULE_EXECUTE, "get-execute-interactive");
StringBuilder sql = new StringBuilder();
......@@ -176,29 +176,52 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
sql.append(" select a.*, rownum row_ from data_temp a");
sql.append(" where a.callTime >= :p_call_time_from");
sql.append(" and a.callTime <= :p_call_time_to");
sql.append(" ),");
sql.append(" count_total as (");
sql.append(" select count(*) totalRow from data");
sql.append(" )");
sql.append(" select contactCustResultId, createTime, campaignCode, campaignName, userName, phoneNumber, customerName, startCall, contactStatus, surveyStatus, status, recordStatus, callTime from data");
sql.append(" select contactCustResultId, createTime, campaignCode, campaignName, userName, phoneNumber, customerName, startCall, contactStatus, surveyStatus, status, recordStatus, callTime, totalRow from data, count_total");
sql.append(" where :p_page_size = 0 or (row_ >= ((:p_page_number - 1) * :p_page_size + 1) and row_ < (:p_page_number * :p_page_size + 1))");
params.put("p_company_site_id", dto.getCompanySiteId());
params.put("p_customer_id", dto.getCustomerId());
params.put("p_date_from", dto.getFromDate());
params.put("p_date_to", dto.getToDate());
params.put("p_list_compaign_type", dto.getCampaignType());
params.put("p_list_contact_status", dto.getContactStatus());
params.put("p_list_survey_status", dto.getSurveyStatus());
params.put("p_list_record_status", dto.getRecordStatus());
params.put("p_call_time_from", dto.getCallTimeFrom());
params.put("p_call_time_to", dto.getCallTimeTo());
params.put("p_list_campaign_id", dto.getCampaignId());
params.put("p_phone_number", dto.getPhoneNumber());
params.put("p_campaign_name", DataUtil.isNullOrEmpty(dto.getCampaignName()) ? null : dto.getCampaignName().toUpperCase());
params.put("p_user_name", DataUtil.isNullOrEmpty(dto.getAgentId()) ? null : dto.getAgentId().toUpperCase());
params.put("p_page_number", dto.getPage().toString());
params.put("p_page_size", dto.getPageSize().toString());
list = namedParameterJdbcTemplate.query(sql.toString(), params, BeanPropertyRowMapper.newInstance(ContactCusResDTO.class));
SQLQuery query = session.createSQLQuery(sql.toString());
query.setParameter("p_company_site_id", dto.getCompanySiteId());
query.setParameter("p_customer_id", dto.getCustomerId());
query.setParameter("p_date_from", dto.getFromDate());
query.setParameter("p_date_to", dto.getToDate());
query.setParameter("p_list_compaign_type", dto.getCampaignType());
query.setParameter("p_list_contact_status", dto.getContactStatus());
query.setParameter("p_list_survey_status", dto.getSurveyStatus());
query.setParameter("p_list_record_status", dto.getRecordStatus());
query.setParameter("p_call_time_from", dto.getCallTimeFrom());
query.setParameter("p_call_time_to", dto.getCallTimeTo());
query.setParameter("p_list_campaign_id", dto.getCampaignId());
query.setParameter("p_phone_number", dto.getPhoneNumber());
query.setParameter("p_campaign_name", DataUtil.isNullOrEmpty(dto.getCampaignName()) ? null : dto.getCampaignName().toUpperCase());
query.setParameter("p_user_name", DataUtil.isNullOrEmpty(dto.getAgentId()) ? null : dto.getAgentId().toUpperCase());
query.setParameter("p_page_number", dto.getPage());
query.setParameter("p_page_size", dto.getPageSize());
query.addScalar("contactCustResultId", new LongType());
query.addScalar("createTime", new DateType());
query.addScalar("campaignCode", new StringType());
query.addScalar("campaignName", new StringType());
query.addScalar("userName", new StringType());
query.addScalar("phoneNumber", new StringType());
query.addScalar("customerName", new StringType());
query.addScalar("startCall", new DateType());
query.addScalar("contactStatus", new StringType());
query.addScalar("surveyStatus", new StringType());
query.addScalar("status", new StringType());
query.addScalar("callTime", new LongType());
query.addScalar("totalRow", new IntegerType());
query.setResultTransformer(Transformers.aliasToBean(ContactCusResDTO.class));
int total = 0;
list = query.list();
if (list.size() > 0) {
total = list.get(0).getTotalRow();
}
for (ContactCusResDTO contactCusResDTO : list) {
if (!"AGENT".equals(dto.getRoleUser())) {
contactCusResDTO.setEnableEdit(true);
......@@ -214,7 +237,7 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
}
resultDTO.setListData(list);
resultDTO.setTotalRow(list.size());
resultDTO.setTotalRow(total);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} catch (Exception e) {
......@@ -222,6 +245,7 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
} finally {
session.close();
return resultDTO;
}
}
......@@ -230,7 +254,11 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
@Transactional(DataSourceQualify.CCMS_FULL)
public List<ContactCusResDTO> getExcelInteractiveResult(CampaignRequestDTO dto) {
List<ContactCusResDTO> list = new ArrayList<>();
Map<String, Object> params = new HashMap<>();
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
StringBuilder sb = new StringBuilder();
......@@ -302,27 +330,61 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
sb.append(" select campaignCode, createTime, campaignName, userName, phoneNumber, customerName, startCall, contactStatus, surveyStatus, status, recordStatus, callTime from data");
sb.append(" where :p_page_size = 0 or (row_ >= ((:p_page_number - 1) * :p_page_size + 1) and row_ < (:p_page_number * :p_page_size + 1))");
params.put("p_company_site_id", dto.getCompanySiteId());
params.put("p_customer_id", dto.getCustomerId());
params.put("p_date_from", dto.getFromDate());
params.put("p_date_to", dto.getToDate());
params.put("p_list_compaign_type", dto.getCampaignType());
params.put("p_list_contact_status", dto.getContactStatus());
params.put("p_list_survey_status", dto.getSurveyStatus());
params.put("p_list_record_status", dto.getRecordStatus());
params.put("p_call_time_from", dto.getCallTimeFrom());
params.put("p_call_time_to", dto.getCallTimeTo());
params.put("p_list_campaign_id", dto.getCampaignId());
params.put("p_phone_number", dto.getPhoneNumber());
params.put("p_campaign_name", DataUtil.isNullOrEmpty(dto.getCampaignName()) ? null : dto.getCampaignName().toUpperCase());
params.put("p_user_name", DataUtil.isNullOrEmpty(dto.getAgentId()) ? null : dto.getAgentId().toUpperCase());
params.put("p_page_number", dto.getPage().toString());
params.put("p_page_size", "0");
list = namedParameterJdbcTemplate.query(sb.toString(), params, BeanPropertyRowMapper.newInstance(ContactCusResDTO.class));
// params.put("p_company_site_id", dto.getCompanySiteId());
// params.put("p_customer_id", dto.getCustomerId());
// params.put("p_date_from", dto.getFromDate());
// params.put("p_date_to", dto.getToDate());
// params.put("p_list_compaign_type", dto.getCampaignType());
// params.put("p_list_contact_status", dto.getContactStatus());
// params.put("p_list_survey_status", dto.getSurveyStatus());
// params.put("p_list_record_status", dto.getRecordStatus());
// params.put("p_call_time_from", dto.getCallTimeFrom());
// params.put("p_call_time_to", dto.getCallTimeTo());
// params.put("p_list_campaign_id", dto.getCampaignId());
// params.put("p_phone_number", dto.getPhoneNumber());
// params.put("p_campaign_name", DataUtil.isNullOrEmpty(dto.getCampaignName()) ? null : dto.getCampaignName().toUpperCase());
// params.put("p_user_name", DataUtil.isNullOrEmpty(dto.getAgentId()) ? null : dto.getAgentId().toUpperCase());
// params.put("p_page_number", dto.getPage().toString());
// params.put("p_page_size", "0");
//
// list = namedParameterJdbcTemplate.query(sb.toString(), params, BeanPropertyRowMapper.newInstance(ContactCusResDTO.class));
SQLQuery query = session.createSQLQuery(sb.toString());
query.setParameter("p_company_site_id", dto.getCompanySiteId());
query.setParameter("p_customer_id", dto.getCustomerId());
query.setParameter("p_date_from", dto.getFromDate());
query.setParameter("p_date_to", dto.getToDate());
query.setParameter("p_list_compaign_type", dto.getCampaignType());
query.setParameter("p_list_contact_status", dto.getContactStatus());
query.setParameter("p_list_survey_status", dto.getSurveyStatus());
query.setParameter("p_list_record_status", dto.getRecordStatus());
query.setParameter("p_call_time_from", dto.getCallTimeFrom());
query.setParameter("p_call_time_to", dto.getCallTimeTo());
query.setParameter("p_list_campaign_id", dto.getCampaignId());
query.setParameter("p_phone_number", dto.getPhoneNumber());
query.setParameter("p_campaign_name", DataUtil.isNullOrEmpty(dto.getCampaignName()) ? null : dto.getCampaignName().toUpperCase());
query.setParameter("p_user_name", DataUtil.isNullOrEmpty(dto.getAgentId()) ? null : dto.getAgentId().toUpperCase());
query.setParameter("p_page_number", dto.getPage());
query.setParameter("p_page_size", dto.getPageSize());
query.addScalar("createTime", new DateType());
query.addScalar("campaignCode", new StringType());
query.addScalar("campaignName", new StringType());
query.addScalar("userName", new StringType());
query.addScalar("phoneNumber", new StringType());
query.addScalar("customerName", new StringType());
query.addScalar("startCall", new DateType());
query.addScalar("contactStatus", new StringType());
query.addScalar("surveyStatus", new StringType());
query.addScalar("status", new StringType());
query.addScalar("callTime", new LongType());
query.setResultTransformer(Transformers.aliasToBean(ContactCusResDTO.class));
list = query.list();
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
session.close();
return list;
}
}
......@@ -469,5 +531,4 @@ public class CampaignExecuteRepositoryImp implements CampaignExecuteRepository {
return result;
}
}
......@@ -8,10 +8,7 @@ import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.utils.DataUtil;
import com.viettel.campaign.utils.HibernateUtil;
import com.viettel.campaign.utils.SQLBuilder;
import com.viettel.campaign.web.dto.CampaignDTO;
import com.viettel.campaign.web.dto.CustomerCustomDTO;
import com.viettel.campaign.web.dto.FieldsToShowDTO;
import com.viettel.campaign.web.dto.ResultDTO;
import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.web.dto.request_dto.CampaignRequestDTO;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -571,4 +568,27 @@ public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
return resultDTO;
}
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO getCampaignCustomerList(CampaignRequestDTO dto) {
List<CustomerListDTO> list = new ArrayList();
ResultDTO resultDTO = new ResultDTO();
Map<String, String> params = new HashMap<>();
// StringBuilder sb = new StringBuilder();
try {
String sql = SQLBuilder.getSqlQueryById(SQLBuilder.SQL_MODULE_CAMPAIGN_MNG, "get-list-campaign-customer");
params.put("p_campaign_id", dto.getCampaignId());
list = namedParameterJdbcTemplate.query(sql, params, BeanPropertyRowMapper.newInstance(CustomerListDTO.class));
resultDTO.setListData(list);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} catch (Exception e) {
logger.error(e.getMessage(), e);
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
}
return resultDTO;
}
}
......@@ -54,6 +54,8 @@ public interface CampaignService {
ResultDTO getListFieldsNotShow(CampaignRequestDTO dto);
ResultDTO getListFieldsToShow(CampaignRequestDTO dto);
ResultDTO getCampaignCustomerList(CampaignRequestDTO dto);
//</editor-fold>
}
......@@ -2,15 +2,16 @@ package com.viettel.campaign.service;
import com.viettel.campaign.model.ccms_full.Customer;
import com.viettel.campaign.model.ccms_full.CustomerList;
import com.viettel.campaign.model.ccms_full.CustomizeFieldObject;
import com.viettel.campaign.model.ccms_full.CustomizeFields;
import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.web.dto.request_dto.CustomerRequestDTO;
import com.viettel.campaign.web.dto.request_dto.SearchCustomerRequestDTO;
import com.viettel.econtact.filter.UserSession;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.List;
import java.util.Map;
public interface CustomerService {
......@@ -62,9 +63,11 @@ public interface CustomerService {
List<Customer> findAllByCondition(Long siteId, Date endTime);
Customer update(Customer c);
List<DynamicExcelHeaderDTO> getDynamicHeader(Long companySiteId);
List<CustomizeFields> getDynamicHeader(Long companySiteId);
byte[] buildTemplate(Long companySiteId);
void buildTemplate(Long companySiteId);
Map<String, Object> readAndValidateCustomer(String path, List<CustomizeFields> headerDTOS, UserSession userSession, Long customerListId);
List<CustomizeFieldDTO> getCustomizeField(Long customerId);
List<CustomizeFieldObject> getCustomizeField(Long customerId);
}
......@@ -28,7 +28,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Transactional(rollbackFor = Exception.class)
......@@ -405,6 +404,8 @@ public class CampaignServiceImpl implements CampaignService {
// Save campaign to database
campaignRepository.save(campaignEntity);
// Save time dial
timeRangeDialModeRepository.deleteAllByCampaignIdAndCompanySiteId(dto.getCampaignId(), dto.getCompanySiteId());
timeZoneDialModeRepository.deleteAllByCampaignIdAndCompanySiteId(dto.getCampaignId(), dto.getCompanySiteId());
for (TimeRangeDialModeDTO timeRangeDto : lstTimeRange) {
timeRangeDto.setCampaignId(dto.getCampaignId());
TimeRangeDialMode timeRangeEntity = modelMapper.map(timeRangeDto, TimeRangeDialMode.class);
......@@ -480,6 +481,12 @@ public class CampaignServiceImpl implements CampaignService {
return resultDTO;
}
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO getCampaignCustomerList(CampaignRequestDTO dto) {
return campaignRepositoryCustom.getCampaignCustomerList(dto);
}
// hungtt
private Map<String, String> setMapData(Map<String, String> mapColumn, Locale locale) {
mapColumn.put("CUSTOMER_ID", BundleUtils.getLangString("CUSTOMER_ID", locale));
......
......@@ -3,9 +3,7 @@ package com.viettel.campaign.service.impl;
import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.mapper.CustomerListMapper;
import com.viettel.campaign.mapper.CustomerMapper;
import com.viettel.campaign.model.ccms_full.Customer;
import com.viettel.campaign.model.ccms_full.CustomerContact;
import com.viettel.campaign.model.ccms_full.CustomerList;
import com.viettel.campaign.model.ccms_full.*;
import com.viettel.campaign.repository.ccms_full.*;
import com.viettel.campaign.service.CustomerService;
import com.viettel.campaign.utils.*;
......@@ -15,9 +13,9 @@ import com.viettel.campaign.web.dto.request_dto.CustomerRequestDTO;
import com.viettel.campaign.web.dto.request_dto.SearchCustomerRequestDTO;
import com.viettel.econtact.filter.UserSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.jetty.client.HttpRequest;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
......@@ -26,6 +24,8 @@ import org.hibernate.type.DateType;
import org.hibernate.type.LongType;
import org.hibernate.type.ShortType;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
......@@ -33,19 +33,22 @@ import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class CustomerServiceImpl implements CustomerService {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerServiceImpl.class);
@Autowired
@PersistenceContext( unitName= DataSourceQualify.JPA_UNIT_NAME_CCMS_FULL)
EntityManager entityManager;
......@@ -75,6 +78,15 @@ public class CustomerServiceImpl implements CustomerService {
@Autowired
VSAUsersRepository vsaUsersRepository;
@Autowired
CustomizeFieldsRepository customizeFieldsRepository;
@Autowired
CustomizeFieldObjectRepository customizeFieldObjectRepository;
@Autowired
CustomizeFieldOptionValueRepository customizeFieldOptionValueRepository;
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO getAllCustomer(int page, int pageSize, String sort, long customerListId, long companySiteId) {
......@@ -797,8 +809,7 @@ public class CustomerServiceImpl implements CustomerService {
resultDTO.setData(dataPage);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} catch (
Exception e) {
} catch (Exception e) {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
} finally {
......@@ -862,97 +873,570 @@ public class CustomerServiceImpl implements CustomerService {
}
@Override
public List<DynamicExcelHeaderDTO> getDynamicHeader(Long companySiteId) {
List<DynamicExcelHeaderDTO> headerList;
public List<CustomizeFields> getDynamicHeader(Long companySiteId) {
LOGGER.info("------------------GET DYNAMIC HEADER-------------------");
List<CustomizeFields> headerList;
try {
//String sql = SQLBuilder.getSqlQueryById(SQLBuilder.SQL_MODULE_CAMPAIGN_CUSTOMER_MNG, "get-dynamic-header");
StringBuilder sb = new StringBuilder();
sb.append(" select CUSTOMIZE_FIELD_ID customizeFieldId,");
sb.append(" SITE_ID companySiteId,");
sb.append(" FUNCTION_CODE functionCode,");
sb.append(" CREATE_BY createBy,");
sb.append(" CREATE_DATE createDate,");
sb.append(" UPDATE_BY updateBy,");
sb.append(" UPDATE_DATE updateDate,");
sb.append(" STATUS status,");
sb.append(" TYPE type,");
sb.append(" TITLE title,");
sb.append(" PLACEHOLDER placeholder,");
sb.append(" DESCRIPTION description,");
sb.append(" POSITION position,");
sb.append(" REQUIRED required,");
sb.append(" FIELD_OPTIONS_ID fieldOptionsId,");
sb.append(" REGEXP_FOR_VALIDATION regexpForValidation,");
sb.append(" MAX_LENGTH maxLength,");
sb.append(" MIN min,");
sb.append(" MAX max,");
sb.append(" MIN_LENGTH minLength,");
sb.append(" ACTIVE active");
sb.append(" from customize_fields");
sb.append(" where function_code = 'CUSTOMER'");
sb.append(" and site_id = :p_company_site_id");
Map<String, Object> param = new HashMap<>();
param.put("p_company_site_id", companySiteId);
headerList = namedParameterJdbcTemplate.query(sb.toString(), param, new BeanPropertyRowMapper<>(DynamicExcelHeaderDTO.class));
headerList = customizeFieldsRepository.findCustomizeFieldsByFunctionCodeEqualsAndStatusAndActiveAndSiteId("CUSTOMER", 1L, 1L, companySiteId);
} catch (Exception e) {
LOGGER.info(e.getMessage());
return null;
}
return headerList;
}
@Override
public void buildTemplate(Long companySiteId) {
public Map<String, Object> readAndValidateCustomer(String path, List<CustomizeFields> dynamicHeader, UserSession userSession, Long customerListId) {
LOGGER.info("------------READ AND VALIDATE--------------");
Locale locale = new Locale("vi", "VN");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Map<String, Object> result = new HashMap<>();
StringBuilder sb = new StringBuilder();
boolean validateOk = false;
try {
List<DynamicExcelHeaderDTO> headerList = getDynamicHeader(companySiteId);
FileInputStream fis = new FileInputStream(ResourceUtils.getFile("classpath:templates/import_customer_template.xlsx"));
//<editor-fold desc="Khởi tạo mảng header tĩnh" defaultstate="collapsed">
List<CustomizeFields> header = new ArrayList<>();
// header.add(new CustomizeFields("text", "STT"));
// header.add(new CustomizeFields("text", "Họ và tên#Bắt buộc\nĐịnh dạng chữ\ntối đa 1000 ký tự"));
// header.add(new CustomizeFields("text", "Số điện thoại chính#Định dạng số\ncho phép nhập nhiều số điện thoại chính\ncác số cách nhau bởi dấu chấm phấy hoặc dấu phẩy\ntối đa 50 ký tự"));
// header.add(new CustomizeFields("text", "Số điện thoại phụ#Định dạng số\ncho phép nhập nhiều số điện thoại phụ\ncác số cách nhau bởi dấu chấm phấy hoặc dấu phẩy\ntối đa 50 ký tự"));
// header.add(new CustomizeFields("text", "Email chính#Cho phép nhập nhiều email\nmỗi email cách nhau bởi dấu \",\"\ntối đa 100 ký tự"));
// header.add(new CustomizeFields("text", "Địa chỉ#Tối đa 500 ký tự"));
// header.add(new CustomizeFields("combobox", "Loại khách hàng"));
// header.add(new CustomizeFields("text", "Công ty#Tối đa 100 ký tự"));
// header.add(new CustomizeFields("text", "Ghi chú#Tối đa 2000 ký tự"));
// header.add(new CustomizeFields("combobox", "Cho phép gọi ra"));
// header.add(new CustomizeFields("combobox", "Cho phép gửi email"));
// header.add(new CustomizeFields("combobox", "Cho phép gửi sms"));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.no", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.fullname", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.mainPhone", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.secondPhone", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.email", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.address", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.cusType", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.companyName", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.description", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.callAllowed", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.emailAllowed", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.smsAllowed", locale)));
header.addAll(dynamicHeader);
//</editor-fold>
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.createCell(row.getPhysicalNumberOfCells());
cell.setCellType(CellType.STRING);
cell.setCellValue("test");
FileOutputStream fos = new FileOutputStream(ResourceUtils.getFile("classpath:templates/import_customer_template.xlsx"));
workbook.write(fos);
fos.close();
workbook.close();
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(3);
//<editor-fold desc="Tạo style cho cột kết quả" defaultstate="collapsed">
Font resultFont = workbook.createFont();
resultFont.setBold(true);
resultFont.setFontHeightInPoints((short) 11);
CellStyle resultStyle = workbook.createCellStyle();
resultStyle.setFont(resultFont);
resultStyle.setBorderLeft(BorderStyle.THIN);
resultStyle.setBorderRight(BorderStyle.THIN);
resultStyle.setBorderBottom(BorderStyle.THIN);
resultStyle.setBorderTop(BorderStyle.THIN);
//</editor-fold>
//<editor-fold desc="Kiểm tra header của template" defaultstate="collapsed">
for (int i = 0; i < header.size(); i++) {
Cell cell = row.getCell(i);
if (!cell.getStringCellValue().equals(header.get(i).getTitle().split("#")[0])) {
result.put("file", file);
result.put("message", BundleUtils.getLangString("customer.invalidTemplate", locale));
return result;
}
}
//</editor-fold>
List<Object[]> rawDataList = new ArrayList<>();
//<editor-fold desc="Kiểm tra file dữ liệu rỗng" defaultstate="collapsed">
if (sheet.getPhysicalNumberOfRows() == 3) {
result.put("message", BundleUtils.getLangString("customer.noData", locale));
result.put("file", file);
return result;
} else {
Cell resultCell = sheet.getRow(3).createCell(sheet.getRow(3).getPhysicalNumberOfCells());
resultCell.setCellValue(BundleUtils.getLangString("customer.result", locale));
resultCell.setCellStyle(resultStyle);
}
//</editor-fold>
//<editor-fold desc="Đọc dữ liệu từng dòng 1" defaultstate="collapsed">
for (int i = 4; i < sheet.getPhysicalNumberOfRows(); i++) {
Row dataRow = sheet.getRow(i);
if (dataRow != null) {
Object[] obj = new Object[row.getPhysicalNumberOfCells()];
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
Cell dataCell = dataRow.getCell(j);
if (dataCell != null) {
switch (dataCell.getCellTypeEnum()) {
case NUMERIC:
obj[j] = dataCell.getNumericCellValue();
break;
default:
obj[j] = dataCell.getStringCellValue();
break;
}
} else {
Cell headerCell = row.getCell(j);
if (headerCell.getStringCellValue().equals(BundleUtils.getLangString("customer.cusType", locale))) {
obj[j] = BundleUtils.getLangString("customer.cusType.normal", locale);
} else if (headerCell.getStringCellValue().equals(BundleUtils.getLangString("customer.callAllowed", locale)) || headerCell.getStringCellValue().equals(BundleUtils.getLangString("customer.emailAllowed", locale))
|| headerCell.getStringCellValue().equals(BundleUtils.getLangString("customer.smsAllowed", locale))) {
obj[j] = BundleUtils.getLangString("customer.yes", locale);
break;
} else {
obj[j] = null;
}
}
}
rawDataList.add(obj);
}
}
//</editor-fold>
//<editor-fold desc="Validate dữ liệu" defaultstate="collapsed">
for (int i = 0; i < rawDataList.size(); i++) {
if (rawDataList.get(i).length > 1 && rawDataList.get(i)[1] != null && !rawDataList.get(i)[1].toString().trim().equals("")) {
String str = validateLength(BundleUtils.getLangString("customer.fullname", locale).split("#")[0], rawDataList.get(i)[1].toString(), 1000, locale);
if (!str.equals("")) {
sb.append(str);
}
} else sb.append(BundleUtils.getLangString("customer.nameRequired"));
if (rawDataList.get(i).length > 4
&& rawDataList.get(i)[2] != null
&& !rawDataList.get(i)[2].toString().trim().equals("")
&& rawDataList.get(i)[3] != null
&& !rawDataList.get(i)[3].toString().trim().equals("")
&& rawDataList.get(i)[4] != null
&& !rawDataList.get(i)[4].toString().trim().equals("")) {
String str = validatePhone(rawDataList.get(i)[2].toString().trim(), locale);
str.concat(validateLength(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0], rawDataList.get(i)[3].toString(), 50, locale));
if (validateEmail(rawDataList.get(i)[4].toString().trim())) {
str.concat(BundleUtils.getLangString("customer.emailMax50", locale));
}
sb.append(str);
} else {
sb.append(BundleUtils.getLangString("customer.invalidCustomer", locale));
}
if (rawDataList.get(i).length > 5 && rawDataList.get(i)[5] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.address", locale).split("#")[0], rawDataList.get(i)[5].toString(), 500, locale));
}
if (rawDataList.get(i).length > 7 && rawDataList.get(i)[7] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.companyName", locale).split("#")[0], rawDataList.get(i)[7].toString(), 100, locale));
}
if (rawDataList.get(i).length > 8 && rawDataList.get(i)[8] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.description", locale).split("#")[0], rawDataList.get(i)[8].toString(), 2000, locale));
}
for (int j = 12; j < header.size(); j++) {
if (rawDataList.get(i).length > j && rawDataList.get(i)[j] != null) {
if (header.get(j).getType().equals("text")) {
sb.append(validateDynamicLength(header.get(j).getTitle(), rawDataList.get(i)[j].toString(), header.get(j).getMinLength(), header.get(j).getMaxLength(), locale));
} else if (header.get(j).getType().equals("date")) {
sb.append(validateUsingRegexp(header.get(j).getTitle(), rawDataList.get(i)[j].toString(), header.get(j).getRegexpForValidation(), locale));
} else if (header.get(j).getType().equals("number")) {
sb.append(validateDynamicLength(header.get(j).getTitle(), rawDataList.get(i)[j].toString(), header.get(j).getMin(), header.get(j).getMax(), locale));
}
}
}
Row dataRow = sheet.getRow(4 + i);
Cell resultCell = dataRow.createCell(row.getPhysicalNumberOfCells() - 1);
if (sb.length() > 0) {
resultCell.setCellValue(sb.toString());
validateOk = false;
} else {
validateOk = true;
resultCell.setCellValue("Ok");
}
sb = new StringBuilder();
}
//</editor-fold>
//<editor-fold desc="Insert dữ liệu nếu validate Ok" defaultstate="collapsed">
if (validateOk) {
for (int i = 0; i < rawDataList.size(); i++) {
Customer c = new Customer();
c.setName(rawDataList.get(i)[1].toString());
c.setSiteId(userSession.getCompanySiteId());
c.setCode(null);
c.setDescription(rawDataList.get(i)[8].toString());
c.setCompanyName(rawDataList.get(i)[7].toString());
c.setCustomerImg(null);
c.setCreateDate(new Date());
c.setUpdateDate(null);
c.setStatus(1L);
c.setCreateBy(userSession.getUserName());
c.setUpdateBy(null);
c.setGender((short) 1);
c.setCurrentAddress(rawDataList.get(i)[5].toString());
// c.setPlaceOfBirth();
// c.setDateOfBirth();
c.setMobileNumber(null);
c.setEmail(null);
c.setUserName(null);
c.setAreaCode(null);
switch (rawDataList.get(i)[6].toString()) {
case "VIP":
c.setCustomerType(2L);
break;
case "Blacklist":
c.setCustomerType(3L);
break;
default:
c.setCustomerType(1L);
break;
}
if (rawDataList.get(i)[9].toString().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setCallAllowed(1L);
} else {
c.setCallAllowed(0L);
}
if (rawDataList.get(i)[10].toString().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setEmailAllowed(1L);
} else {
c.setEmailAllowed(0L);
}
if (rawDataList.get(i)[11].toString().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setSmsAllowed(1L);
} else {
c.setSmsAllowed(0L);
}
c.setIpccStatus("active");
Customer saved = customerRepository.save(c);
CustomerContact cc = new CustomerContact();
cc.setCustomerId(saved.getCustomerId());
if (rawDataList.get(i).length > 2 && rawDataList.get(i)[2] != null) {
String[] mainPhone = rawDataList.get(i)[2].toString().split(";");
for (int j = 0; j < mainPhone.length; j++) {
cc.setContactType((short) 5);
cc.setContact(mainPhone[j]);
cc.setIsDirectLine((short) 1);
cc.setStatus((short) 1);
cc.setCreateDate(new Date());
cc.setUpdateDate(new Date());
cc.setCreateBy(userSession.getUserName());
cc.setUpdateBy(userSession.getUserName());
customerContactRepository.save(cc);
}
}
if (rawDataList.get(i).length > 3 && rawDataList.get(i)[3] != null) {
String[] subPhone = rawDataList.get(i)[3].toString().split(";");
for (int j = 0; j < subPhone.length; j++) {
cc.setContactType((short) 5);
cc.setContact(subPhone[j]);
cc.setIsDirectLine((short) 0);
cc.setStatus((short) 1);
cc.setCreateDate(new Date());
cc.setUpdateDate(new Date());
cc.setCreateBy(userSession.getUserName());
cc.setUpdateBy(userSession.getUserName());
customerContactRepository.save(cc);
}
}
if (rawDataList.get(i).length > 4 && rawDataList.get(i)[4] != null) {
String[] email = rawDataList.get(i)[3].toString().split(";");
for (int j = 0; j < email.length; j++) {
cc.setContactType((short) 2);
cc.setContact(email[j]);
cc.setIsDirectLine((short) 1);
cc.setStatus((short) 1);
cc.setCreateDate(new Date());
cc.setUpdateDate(new Date());
cc.setCreateBy(userSession.getUserName());
cc.setUpdateBy(userSession.getUserName());
customerContactRepository.save(cc);
}
}
CustomizeFieldObject cfo = new CustomizeFieldObject();
cfo.setObjectId(saved.getCustomerId());
for (int j = 0; j < dynamicHeader.size(); j++) {
cfo.setCustomizeFieldId(dynamicHeader.get(j).getCustomizeFieldId());
if (rawDataList.get(i).length > (12 + j) && rawDataList.get(i)[12 + j] != null) {
switch (dynamicHeader.get(i).getType()) {
case "combobox":
CustomizeFieldOptionValue cfov =
customizeFieldOptionValueRepository.findCustomizeFieldOptionValueByNameEqualsAndStatus(rawDataList.get(i)[12 + j].toString(), 1L);
cfo.setFieldOptionValueId(cfov.getFieldOptionValueId());
break;
case "checkbox":
if (rawDataList.get(i)[12 + j].toString().equals(BundleUtils.getLangString("customer.yes", locale))) {
cfo.setValueCheckbox(1L);
} else {
cfo.setValueCheckbox(0L);
}
break;
case "date":
Date date = dateFormat.parse(rawDataList.get(i)[12 + j].toString());
cfo.setValueDate(date);
break;
case "number":
cfo.setValueNumber((Long) rawDataList.get(i)[12 + j]);
break;
default:
cfo.setValueText(rawDataList.get(i)[12 + j].toString());
break;
}
}
cfo.setCreateBy(userSession.getUserName());
cfo.setCreateDate(new Date());
cfo.setStatus(1L);
cfo.setFunctionCode("CUSTOMER");
cfo.setTitle(dynamicHeader.get(j).getTitle());
customizeFieldObjectRepository.save(cfo);
}
CustomerListMapping clm = new CustomerListMapping();
clm.setCustomerId(saved.getCustomerId());
clm.setCompanySiteId(userSession.getCompanySiteId());
clm.setCustomerListId(customerListId);
customerListMappingRepository.save(clm);
}
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
result.put("file", file);
result.put("message", BundleUtils.getLangString("customer.importSuccess", locale));
} else {
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
result.put("file", file);
result.put("message", BundleUtils.getLangString("customer.importFailed", locale));
}
//</editor-fold>
return result;
} catch (Exception e) {
LOGGER.info(e.getMessage());
result.put("message", BundleUtils.getLangString("customer.errorValidate", locale));
return result;
}
}
//<editor-fold desc="Validate Methods" defaultstate="collapsed">
private String validatePhone(String str, Locale locale) {
String result = "";
String[] arr = str.split(";");
if (str.length() > 50) {
result = BundleUtils.getLangString("customer.phoneMax50", locale);
}
for (int i = 0; i < str.length(); i++) {
CustomerContact cc = customerContactRepository.findCustomerContactByContactTypeAndContactAndIsDirectLine((short)5, arr[i], (short)1);
if (cc != null) {
return result.concat(BundleUtils.getLangString("customer.phoneExists", locale));
}
}
return result;
}
@Override
public List<CustomizeFieldDTO> getCustomizeField(Long customerId) {
List<CustomizeFieldDTO> customizeFieldDTOList;
try {
//String sql = SQLBuilder.getSqlQueryById(SQLBuilder.SQL_MODULE_CAMPAIGN_MNG, "get-customize-field");
private String validateUsingRegexp(String header, String data, String regexp, Locale locale) {
if (data.matches(regexp)) {
return header + " " + BundleUtils.getLangString("customer.notMatch", locale);
} else return "";
}
StringBuilder sb = new StringBuilder();
private String validateLength(String header, String str, int length, Locale locale) {
if (str.trim().length() > length) {
return header + " " + BundleUtils.getLangString("customer.notGreaterThan", locale) + " " + length;
}
return "";
}
private String validateDynamicLength(String header, String str, Long min, Long max, Locale locale) {
if (str.trim().length() < min || str.trim().length() > max) {
return header + " " + BundleUtils.getLangString("customer.notGreaterThan", locale) + " " + max + " " + BundleUtils.getLangString("customer.notLessThan", locale) + " " + min;
}
return "";
}
sb.append(" select CUSTOMIZE_FIELD_OBJECT_ID customizeFieldObjectId,");
sb.append(" OBJECT_ID objectId,");
sb.append(" CUSTOMIZE_FIELDS_ID customizeFieldId,");
sb.append(" VALUE_TEXT valueText,");
sb.append(" VALUE_NUMBER valueNumber,");
sb.append(" VALUE_DATE valueDate,");
sb.append(" VALUE_CHECKBOX valueCheckbox,");
sb.append(" CREATE_BY createBy,");
sb.append(" CREATE_DATE createDate,");
sb.append(" UPDATE_BY updateBy,");
sb.append(" UPDATE_DATE updateDate,");
sb.append(" STATUS status,");
sb.append(" FIELD_OPTION_VALUE_ID fieldOptionValueId,");
sb.append(" TITLE title,");
sb.append(" FUNCTION_CODE functionCode");
sb.append(" from customize_field_object");
sb.append(" where function_code = 'CUSTOMER' and object_id = :p_customer_id");
private boolean validateEmail(String str) {
String regexp = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
return str.matches(regexp);
}
private boolean validateLetter(String str) {
String regexp = "@\"^\\p{L}+$\"";
return str.matches(regexp);
}
//</editor-fold>
Map<String, Object> param = new HashMap<>();
param.put("p_customer_id", customerId);
customizeFieldDTOList = namedParameterJdbcTemplate.query(sb.toString(), param, new BeanPropertyRowMapper<>(CustomizeFieldDTO.class));
@Override
public byte[] buildTemplate(Long companySiteId) {
LOGGER.info("-----------BUILD TEMPLATE-----------");
Locale locale = new Locale("vi", "VN");
try {
XSSFWorkbook workbook = new XSSFWorkbook();
CreationHelper creationHelper = workbook.getCreationHelper();
ByteArrayOutputStream os = new ByteArrayOutputStream();
Sheet sheet = workbook.createSheet("IMPORT");
//<editor-fold desc="Tạo array header" defaultstate="collapsed">
List<CustomizeFields> header = new ArrayList<>();
// header.add(new CustomizeFields("text", "STT"));
// header.add(new CustomizeFields("text", "Họ và tên#Bắt buộc\nĐịnh dạng chữ\ntối đa 1000 ký tự"));
// header.add(new CustomizeFields("text", "Số điện thoại chính#Định dạng số\ncho phép nhập nhiều số điện thoại chính\ncác số cách nhau bởi dấu chấm phấy hoặc dấu phẩy\ntối đa 50 ký tự"));
// header.add(new CustomizeFields("text", "Số điện thoại phụ#Định dạng số\ncho phép nhập nhiều số điện thoại phụ\ncác số cách nhau bởi dấu chấm phấy hoặc dấu phẩy\ntối đa 50 ký tự"));
// header.add(new CustomizeFields("text", "Email chính#Cho phép nhập nhiều email\nmỗi email cách nhau bởi dấu \",\"\ntối đa 100 ký tự"));
// header.add(new CustomizeFields("text", "Địa chỉ#Tối đa 500 ký tự"));
// header.add(new CustomizeFields("combobox", "Loại khách hàng"));
// header.add(new CustomizeFields("text", "Công ty#Tối đa 100 ký tự"));
// header.add(new CustomizeFields("text", "Ghi chú#Tối đa 2000 ký tự"));
// header.add(new CustomizeFields("combobox", "Cho phép gọi ra"));
// header.add(new CustomizeFields("combobox", "Cho phép gửi email"));
// header.add(new CustomizeFields("combobox", "Cho phép gửi sms"));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.no", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.fullname", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.mainPhone", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.secondPhone", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.email", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.address", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.cusType", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.companyName", locale)));
header.add(new CustomizeFields("text", BundleUtils.getLangString("customer.description", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.callAllowed", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.emailAllowed", locale)));
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.smsAllowed", locale)));
List<CustomizeFields> dynamicHeader = getDynamicHeader(companySiteId);
header.addAll(dynamicHeader);
//</editor-fold>
//<editor-fold desc="Tạo style và font" defaultstate="collapsed">
Font headerFont = workbook.createFont();
Font importantFont = workbook.createFont();
importantFont.setColor(IndexedColors.RED.index);
headerFont.setBold(true);
CellStyle headerStyle = workbook.createCellStyle();
CellStyle importantStyle = workbook.createCellStyle();
importantStyle.setFont(importantFont);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFont(headerFont);
//</editor-fold>
//<editor-fold desc="Thêm combobox" defaultstate="collapsed">
//<editor-fold desc="Cho những trường động" defaultstate="collapsed">
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
for (int i = 0; i < dynamicHeader.size(); i++) {
if (dynamicHeader.get(i).getType().equals("combobox")) {
String[] constraint;
List<CustomizeFieldOptionValue> list =
customizeFieldOptionValueRepository.findCustomizeFieldOptionValuesByFieldOptionIdAndStatus(dynamicHeader.get(i).getFieldOptionsId(), 1L);
constraint = new String[list.size()];
for (int j = 0; j < list.size(); j++) {
constraint[j] = list.get(j).getName();
}
DataValidationConstraint comboboxConstraint = dataValidationHelper.createExplicitListConstraint(constraint);
CellRangeAddressList comboboxCellRange = new CellRangeAddressList(4,9999,12 + i, 12 + i);
DataValidation comboboxValidation = dataValidationHelper.createValidation(comboboxConstraint,comboboxCellRange);
comboboxValidation.setSuppressDropDownArrow(true);
comboboxValidation.setShowErrorBox(true);
sheet.addValidationData(comboboxValidation);
} else if (dynamicHeader.get(i).getType().equals("checkbox")) {
DataValidationConstraint yesNoConstraint = dataValidationHelper.createExplicitListConstraint(new String[]{BundleUtils.getLangString("customer.yes", locale), BundleUtils.getLangString("customer.not", locale)});
CellRangeAddressList checkboxCellRange = new CellRangeAddressList(4,9999,12 + i,12 + i);
DataValidation yesNoValidation = dataValidationHelper.createValidation(yesNoConstraint, checkboxCellRange);
yesNoValidation.setShowErrorBox(true);
yesNoValidation.setSuppressDropDownArrow(true);
sheet.addValidationData(yesNoValidation);
}
}
//</editor-fold>
//<editor-fold desc="Cho những trường tĩnh" defaultstate="collapsed">
DataValidationConstraint cusTypeConstraint = dataValidationHelper.createExplicitListConstraint(new String[]{BundleUtils.getLangString("customer.cusType.normal", locale), BundleUtils.getLangString("customer.cusType.vip", locale), BundleUtils.getLangString("customer.cusType.blacklist", locale)});
DataValidationConstraint isAllowConstraint = dataValidationHelper.createExplicitListConstraint(new String[]{BundleUtils.getLangString("customer.yes", locale), BundleUtils.getLangString("customer.not", locale)});
CellRangeAddressList cusTypeCellRangeAddressList = new CellRangeAddressList(3, 9999, 6, 6);
CellRangeAddressList callCellRangeAddressList = new CellRangeAddressList(3, 9999, 9, 9);
CellRangeAddressList emailCellRangeAddressList = new CellRangeAddressList(3, 9999, 10, 10);
CellRangeAddressList smsCellRangeAddressList = new CellRangeAddressList(3, 9999, 11, 11);
DataValidation cusTypeValidation = dataValidationHelper.createValidation(cusTypeConstraint, cusTypeCellRangeAddressList);
DataValidation callValidation = dataValidationHelper.createValidation(isAllowConstraint, callCellRangeAddressList);
DataValidation emailValidation = dataValidationHelper.createValidation(isAllowConstraint, emailCellRangeAddressList);
DataValidation smsValidation = dataValidationHelper.createValidation(isAllowConstraint, smsCellRangeAddressList);
cusTypeValidation.setSuppressDropDownArrow(true);
cusTypeValidation.setShowErrorBox(true);
callValidation.setSuppressDropDownArrow(true);
callValidation.setShowErrorBox(true);
emailValidation.setSuppressDropDownArrow(true);
emailValidation.setShowErrorBox(true);
smsValidation.setSuppressDropDownArrow(true);
smsValidation.setShowErrorBox(true);
sheet.addValidationData(cusTypeValidation);
sheet.addValidationData(callValidation);
sheet.addValidationData(emailValidation);
sheet.addValidationData(smsValidation);
//</editor-fold>
//</editor-fold>
//<editor-fold desc="Ghi header" defaultstate="collapsed">
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = creationHelper.createClientAnchor();
Row row0 = sheet.createRow(0);
Row row2 = sheet.createRow(2);
Row row3 = sheet.createRow(3);
Cell cell0 = row0.createCell(0);
cell0.setCellStyle(headerStyle);
cell0.setCellValue(BundleUtils.getLangString("customer.importCustomer", locale));
Cell cell2 = row2.createCell(0);
cell2.setCellStyle(importantStyle);
cell2.setCellValue(BundleUtils.getLangString("customer.notice", locale));
for (int i = 0; i < header.size(); i++) {
Cell headerCell = row3.createCell(i);
headerCell.setCellValue(header.get(i).getTitle().split("#")[0]);
headerStyle.setBorderTop(BorderStyle.THIN);
headerStyle.setBorderRight(BorderStyle.THIN);
headerStyle.setBorderBottom(BorderStyle.THIN);
headerStyle.setBorderLeft(BorderStyle.THIN);
headerFont.setFontHeightInPoints((short) 11);
headerCell.setCellStyle(headerStyle);
if (i == 0) {
sheet.setColumnWidth(i, 2500);
} else {
sheet.setColumnWidth(i, 6000);
}
anchor.setCol1(headerCell.getColumnIndex());
anchor.setCol2(headerCell.getColumnIndex() + 2);
anchor.setRow1(row3.getRowNum());
anchor.setRow2(row3.getRowNum() + 4);
if (header.get(i).getTitle().contains("#")) {
Comment comment = drawing.createCellComment(anchor);
RichTextString str = creationHelper.createRichTextString(header.get(i).getTitle().split("#")[1]);
comment.setString(str);
comment.setAuthor("APACHE POI");
headerCell.setCellComment(comment);
}
}
//</editor-fold>
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 13));
sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 13));
workbook.write(os);
os.flush();
os.close();
workbook.close();
return os.toByteArray();
} catch (Exception e) {
LOGGER.error(e.getMessage());
return null;
}
}
@Override
public List<CustomizeFieldObject> getCustomizeField(Long customerId) {
List<CustomizeFieldObject> customizeFieldDTOList;
try {
customizeFieldDTOList = customizeFieldObjectRepository.findCustomizeFieldObjectsByFunctionCodeEqualsAndObjectId("CUSTOMER", customerId);
} catch (Exception e) {
LOGGER.info(e.getMessage());
return null;
}
return customizeFieldDTOList;
......
......@@ -13,14 +13,15 @@ import java.util.ResourceBundle;
public class BundleUtils {
protected static final Logger logger = LoggerFactory.getLogger(BundleUtils.class);
private static volatile ResourceBundle rsConfig = null;
private static final String GLOBAL_CONFIG = "config/globalConfig";
public static String getLangString(String key, Locale... locale) {
Locale vi = new Locale("vi");
Locale mlocale = vi;
try {
if(locale != null) {
if(locale.length == 0) {
if (locale != null) {
if (locale.length == 0) {
rsConfig = ResourceBundle.getBundle(Constants.LANGUAGE.LANGUAGE, mlocale);
} else {
rsConfig = ResourceBundle.getBundle(Constants.LANGUAGE.LANGUAGE, locale[0]);
......@@ -34,4 +35,15 @@ public class BundleUtils {
return key;
}
}
public static String getGlobalConfig(String configKey) {
String result = null;
try {
ResourceBundle bundle = ResourceBundle.getBundle(GLOBAL_CONFIG);
result = bundle.getString(configKey);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return result;
}
}
......@@ -43,4 +43,8 @@ public class Constants {
public interface DATE_FORMAT {
String FOMART_DATE_TYPE_1 = "DD/MM/YYYY";
}
public interface MIME_TYPE {
String EXCEL_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
}
package com.viettel.campaign.utils;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.quartz.CronExpression;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicReference;
import static com.cronutils.model.CronType.QUARTZ;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
......@@ -29,11 +20,24 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS;
@Slf4j
public final class DateTimeUtil {
public static final long DAY_IN_MILLIS = 86400000L;
public static interface DateTimeProvider { long now(); }
public static interface DateTimeProvider {
long now();
}
private static final AtomicReference<DateTimeProvider> PROVIDER = new AtomicReference<DateTimeProvider>();
public static final DateTimeProvider getProvider() { return PROVIDER.get(); }
public static final DateTimeProvider getProvider() {
return PROVIDER.get();
}
static {
PROVIDER.set(new DateTimeProvider() { @Override public long now() { return System.currentTimeMillis(); } });
PROVIDER.set(new DateTimeProvider() {
@Override
public long now() {
return System.currentTimeMillis();
}
});
}
public static Date currentTime() {
......@@ -47,7 +51,8 @@ public final class DateTimeUtil {
public static final Date date(final long millis) {
final int offset = getTimeZoneOffset(millis);
long t = millis - ((t = (millis + offset) % DAY_IN_MILLIS) < 0 ? DAY_IN_MILLIS + t : t);
t = t + (offset - getTimeZoneOffset(t)); return new Date(t);
t = t + (offset - getTimeZoneOffset(t));
return new Date(t);
}
public static int getTimeZoneOffset(long millis) {
......@@ -74,8 +79,8 @@ public final class DateTimeUtil {
}
public static String format(String pattern, Date date, String defaultValue) {
if(date == null) return defaultValue;
return format(pattern ,date.getTime());
if (date == null) return defaultValue;
return format(pattern, date.getTime());
}
/**
......@@ -84,6 +89,7 @@ public final class DateTimeUtil {
public static boolean isValid(final long millis) {
return millis > 0L;
}
/**
*
*/
......@@ -99,9 +105,9 @@ public final class DateTimeUtil {
*
*/
public static boolean isRun(String cron, Date lastCheck){
public static boolean isRun(String cron, Date lastCheck) {
boolean isOk = false;
String format="dd-MMM-YYYY hh:mm:ss";
String format = "dd-MMM-YYYY hh:mm:ss";
// String cronExpression="* * 12 ? * FRI *";
SimpleDateFormat sdf = new SimpleDateFormat(format);
CronExpression expression = null;
......@@ -110,14 +116,14 @@ public final class DateTimeUtil {
} catch (ParseException e) {
e.printStackTrace();
}
Date currentDate = new Date();
Date currentDate = new Date();
assert expression != null;
Date lastDate = expression.getNextValidTimeAfter(lastCheck);
long interval = lastDate.getTime() - currentDate.getTime();
if(interval <= 0){
long interval = lastDate.getTime() - currentDate.getTime();
if (interval <= 0) {
isOk = true;
}
return isOk;
return isOk;
}
}
......@@ -5,14 +5,14 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
//import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ContactCusResDTO implements Serializable {
public class ContactCusResDTO {
private Long contactCustResultId;
private String campaignCode;
private String campaignName;
......@@ -27,4 +27,5 @@ public class ContactCusResDTO implements Serializable {
private String recordStatus;
private Long callTime;
private Boolean enableEdit;
private Integer totalRow;
}
......@@ -24,4 +24,7 @@ public class CustomerListDTO extends BaseDTO {
private Long totalCusInList;
private Long totalCusInteract;
private Long totalCusNotInteract;
private Long totalCusList;
private Long totalCusCampaign;
private Long totalCusCalled;
}
......@@ -248,6 +248,13 @@ public class CampaignController {
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PostMapping("/getCampaignCustomerList")
@ResponseBody
public ResponseEntity getCampaignCustomerList(@RequestBody CampaignRequestDTO campaignRequestDTO) {
ResultDTO resultDTO = campaignService.getCampaignCustomerList(campaignRequestDTO);
return new ResponseEntity<>(resultDTO, HttpStatus.OK);
}
@RequestMapping(value = "/renewCampaign", method = RequestMethod.PUT)
public ResponseEntity<ResultDTO> renewCampaign(@RequestBody CampaignDTO campaignDTO) {
ResultDTO result = campaignService.renewCampaign(campaignDTO);
......
package com.viettel.campaign.web.rest;
import com.viettel.campaign.model.ccms_full.CustomizeFieldObject;
import com.viettel.campaign.model.ccms_full.CustomizeFields;
import com.viettel.campaign.service.CustomerService;
import com.viettel.campaign.utils.BundleUtils;
import com.viettel.campaign.utils.Constants;
import com.viettel.campaign.utils.RedisUtil;
import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.service.CustomerService;
import com.viettel.campaign.web.dto.request_dto.SearchCustomerRequestDTO;
import com.viettel.campaign.web.dto.request_dto.CustomerRequestDTO;
import com.viettel.campaign.web.dto.request_dto.SearchCustomerRequestDTO;
import com.viettel.econtact.filter.UserSession;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.jetty.server.Authentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
......@@ -21,17 +26,22 @@ import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Controller
@RequestMapping("/ipcc/customer")
@CrossOrigin(origins = "*")
public class CustomerController {
private static final Logger LOGGER = Logger.getLogger(CustomerController.class);
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);
@Autowired(required=true)
@Autowired(required = true)
CustomerService customerService;
@GetMapping("/findAll")
......@@ -160,17 +170,15 @@ public class CustomerController {
return new ResponseEntity(result, HttpStatus.OK);
}
//<editor-fold desc="Download and import excel" defaultState="collapsed">
//<editor-fold desc="Download and import excel" defaultstate="collapsed">
@GetMapping(value = "/downloadFileTemplate")
public ResponseEntity<byte[]> downloadFileTemplate(@RequestParam("companySiteId") Long companySiteId) {
LOGGER.debug("--------DOWNLOAD FILE TEMPLATE---------");
LOGGER.info("--------DOWNLOAD FILE TEMPLATE---------");
try {
customerService.buildTemplate(companySiteId);
File file = ResourceUtils.getFile("classpath:templates/import_customer_template.xlsx");
byte[] content = Files.readAllBytes(file.toPath());
byte[] content = customerService.buildTemplate(companySiteId);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template_import_customer.xlsx")
.header("Content-Type", Constants.MIME_TYPE.EXCEL_XLSX)
.body(content);
} catch (Exception e) {
LOGGER.error(e.getMessage());
......@@ -179,39 +187,28 @@ public class CustomerController {
}
@PostMapping(value = "/importFile")
public ResponseEntity<byte[]> importFile(@RequestParam("file") MultipartFile file) {
LOGGER.debug("--------IMPORT FILE TEMPLATE---------");
public ResponseEntity<?> importFile(@RequestParam("file") MultipartFile file,
@RequestParam("customerListId") Long customerListId,
@RequestHeader("X-Auth-Token") String authToken) {
LOGGER.info("------------IMPORT FILE TEMPLATE--------------");
try {
List<CustomerDTO> listCustomer = new ArrayList<>();
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
CustomerDTO customer = new CustomerDTO();
XSSFRow row = sheet.getRow(i);
customer.setCustomerId(Double.valueOf(row.getCell(0).getNumericCellValue()).longValue());
customer.setCreateDate(row.getCell(1).getDateCellValue());
customer.setName(row.getCell(2).getStringCellValue());
listCustomer.add(customer);
UserSession userSession = (UserSession) RedisUtil.getInstance().get(authToken);
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file", HttpStatus.OK);
}
// for (int i = 0; i < listCustomer.size(); i++) {
// validate du lieu
// }
// if (okay) {
// for (int i = 0; i < listCustomer.size(); i++) {
// customerService.createCustomer(listCustomer.get(i));
// }
// return ResponseEntity.ok()
// .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
// .contentType(MediaType.APPLICATION_OCTET_STREAM)
// .body(file.getBytes());
// } else {
// return ResponseEntity.ok()
// .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
// .header("Message", "Validate failed!")
// .contentType(MediaType.APPLICATION_OCTET_STREAM)
// .body(file.getBytes());
// }
return null;
if (!Objects.equals(FilenameUtils.getExtension(file.getOriginalFilename()), Constants.FileType.xlsx)) {
return new ResponseEntity<>("File khong dung dinh dang", HttpStatus.OK);
}
String path = saveUploadFile(file);
List<CustomizeFields> dynamicHeaders = customerService.getDynamicHeader(userSession.getCompanySiteId());
Map<String, Object> map = customerService.readAndValidateCustomer(path, dynamicHeaders, userSession, customerListId);
File fileExport = (File) map.get("file");
String message = (String) map.get("message");
return ResponseEntity.ok()
.header("Content-Type", Constants.MIME_TYPE.EXCEL_XLSX)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template_import_customer.xlsx")
.header("Message", message)
.body(Files.readAllBytes(fileExport.toPath()));
} catch (Exception e) {
LOGGER.error(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
......@@ -233,7 +230,25 @@ public class CustomerController {
@PostMapping("/getCustomizeField")
public ResponseEntity<?> getCustomizeField(@RequestBody Long customerId) {
List<CustomizeFieldDTO> data = customerService.getCustomizeField(customerId);
List<CustomizeFieldObject> data = customerService.getCustomizeField(customerId);
return new ResponseEntity<>(data, HttpStatus.OK);
}
private String saveUploadFile(MultipartFile file) {
try {
String currentTime = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss").format(new Date());
String fileName = FilenameUtils.getBaseName(file.getOriginalFilename()) + "_" + currentTime + "." + FilenameUtils.getExtension(file.getOriginalFilename());
byte[] content = file.getBytes();
File uploadFolder = new File(BundleUtils.getGlobalConfig("import.uploadFolder"));
if (!uploadFolder.exists()) {
uploadFolder.mkdir();
}
Path path = Paths.get(BundleUtils.getGlobalConfig("import.uploadFolder"), fileName);
Files.write(path, content);
return path.toString();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return null;
}
}
#DEV
import.uploadFolder=D:/temp/upload
#STAGGING
#import.uploadFolder=/root/temp/
#PROD
#import.uploadFolder=/root/temp/
......@@ -67,3 +67,38 @@ IPCC_STATUS = IPCC_STATUS
EMAIL = EMAIL
CUSTOMER_TYPE = CUSTOMER_TYPE
AVATAR_LINK = AVATAR_LINK
#Customer Excel Header
customer.no = No
customer.fullname = Full Name#Required\nLetters only\nmaximum 1000 characters
customer.mainPhone = Main mobile phone#Number only\nmultiple numbers allowed\neach seperate by semicolon\nmaximum 50 characters
customer.secondPhone = Secondary phone#Number only\nmultiple numbers allowed\neach seperate by semicolon\nmaximum 50 characters
customer.email = Email#multiple emails allowed\neach seperate by semicolon\nmaximum 100 characters
customer.address = Address#maximum 500 characters
customer.cusType = Customer Type
customer.companyName = Company#maximum 100 characters
customer.description = Description#maximum 2000 characters
customer.callAllowed = Call Allowed
customer.emailAllowed = Email Allowed
customer.smsAllowed = Sms Allowed
customer.result = Result
customer.cusType.normal = Normal
customer.cusType.vip = VIP
customer.cusType.blacklist = Blacklist
customer.yes = Yes
customer.not = No
customer.invalidTemplate = Invalid Template
customer.noData = Template empty
customer.nameRequired = Full name required;
customer.emailMax50 = Email must less than 50 character;
customer.invalidCustomer = All 3 fields Main phone, second phone and email must not null;
customer.importSuccess = Import Successful
customer.importFailed = Import Failed
customer.errorValidate = Error while validating
customer.phoneMax50 = Mobile phone must less than 50 character;
customer.phoneExists = Mobile phone exists;
customer.notMatch = not match regexp validation
customer.notGreaterThan = not greater than
customer.notLessThan = not less than
customer.importCustomer = IMPORT CUSTOMER
customer.notice = Attention: A record is valid when Full Name is not null and one of three fields Main phone, secondary phone or email is not null
......@@ -69,3 +69,38 @@ IPCC_STATUS = IPCC_STATUS
EMAIL = EMAIL
CUSTOMER_TYPE = CUSTOMER_TYPE
AVATAR_LINK = AVATAR_LINK
#Customer Excel Header
customer.no = STT
customer.fullname = Họ và tên#Bắt buộc\nĐịnh dạng chữ\ntối đa 1000 kí tự
customer.mainPhone = Số điện thoại chính#Định dạng số\ncho phép nhập nhiều số điện thoại chính\ncác số cách nhau bởi dấu chấm phấy\ntối đa 50 ký tự
customer.secondPhone = Số điện thoại phụ#Định dạng số\ncho phép nhập nhiều số điện thoại phụ\ncác số cách nhau bởi dấu chấm phấy hoặc dấu phẩy\ntối đa 50 ký tự
customer.email = Email chính#Cho phép nhập nhiều email\nmỗi email cách nhau bởi dấu \";\"\ntối đa 100 ký tự
customer.address = Địa chỉ#Tối đa 500 ký tự
customer.cusType = Loại khách hàng
customer.companyName = Công ty#Tối đa 100 ký tự
customer.description = Ghi chú#Tối đa 2000 ký tự
customer.callAllowed = Cho phép gọi ra
customer.emailAllowed = Cho phép gửi email
customer.smsAllowed = Cho phép gửi sms
customer.result = Kết quả
customer.cusType.normal = Thường
customer.cusType.vip = VIP
customer.cusType.blacklist = Blacklist
customer.yes =
customer.not = Không
customer.invalidTemplate = Template sai định dạng
customer.noData = Template không có dữ liệu
customer.nameRequired = Họ và tên không được để trống;
customer.emailMax50 = Email không được quá 50 kí tự;
customer.invalidCustomer = Cả 3 thông tin số điện thoại chính, số điện phụ và email không được để trống;
customer.importSuccess = Import dữ liệu thành công
customer.importFailed = Import dữ liệu thất bại
customer.errorValidate = Validate dữ liệu lỗi
customer.phoneMax50 = Số điện thoại không được quá 50 kí tự;
customer.phoneExists = Số điện thoại chính đã tồn tại;
customer.notMatch = không đúng định dạng
customer.notGreaterThan = không được lớn hơn
customer.notLessThan = không được nhỏ hơn
customer.importCustomer = IMPORT KHÁCH HÀNG
customer.notice = Chú ý: 1 bản ghi được coi là hợp lệ bắt buộc phải có thông tin Họ và Tên và 1 trong 3 thông tin liên lạc (số điện thoại chính, số điện thoại phụ hoặc email)
select CUSTOMIZE_FIELD_OBJECT_ID customizeFieldObjectId,
OBJECT_ID objectId,
CUSTOMIZE_FIELDS_ID customizeFieldId,
VALUE_TEXT valueText,
VALUE_NUMBER valueNumber,
VALUE_DATE valueDate,
VALUE_CHECKBOX valueCheckbox,
CREATE_BY createBy,
CREATE_DATE createDate,
UPDATE_BY updateBy,
UPDATE_DATE updateDate,
STATUS status,
FIELD_OPTION_VALUE_ID fieldOptionValueId,
TITLE title,
FUNCTION_CODE functionCode
from customize_field_object
where function_code = 'CUSTOMER' and object_id = :p_customer_id
\ No newline at end of file
with customer_table as (
select count(a.customer_id) totalCustomer, a.customer_list_id customerListId from customer_list_mapping a
left join customer b on a.customer_id = b.customer_id
where b.status = 1
group by a.customer_list_id
),
campaign_customer_table as (
select count(a.customer_id) campaignCustomer, a.customer_list_id customerListId, a.campaign_id from campaign_customer a
where a.campaign_id = :p_campaign_id
group by a.customer_list_id, a.campaign_id
),
customer_interactive_table as (
select count(a.customer_id) campaignCustomerCalled, a.customer_list_id customerListId, a.campaign_id from campaign_customer a
where a.status <> 0 and a.campaign_id = :p_campaign_id
group by a.customer_list_id, a.campaign_id
),
customer_not_interactive_table as (
select count(a.customer_id) cusNotInteractive, a.customer_list_id customerListId, a.campaign_id from campaign_customer a
where a.status = 0 and a.campaign_id = :p_campaign_id and a.in_campaign_status = 1
group by a.customer_list_id, a.campaign_id
)
select a.customer_list_id customerListId,
a.customer_list_code customerListCode,
a.customer_list_name customerListName,
nvl(b.totalCustomer, 0) totalCusList,
nvl(c.campaignCustomer, 0) totalCusCampaign,
nvl(d.campaignCustomerCalled, 0) totalCusCalled,
nvl(e.cusNotInteractive, 0) totalCusNotInteract
from customer_list a
left join customer_table b on a.customer_list_id = b.customerListId
left join campaign_customer_table c on a.customer_list_id = c.customerListId
left join customer_interactive_table d on a.customer_list_id = d.customerListId
left join customer_not_interactive_table e on a.customer_list_id = e.customerListId
package com.viettel.econtact;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceCampaignApplicationTests {
@Test
public void contextLoads() {
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment