Commit 9a9fed56 authored by Tu Bach's avatar Tu Bach
parents 82799e42 5e715b1e
......@@ -162,6 +162,18 @@
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
<build>
......
......@@ -4,6 +4,7 @@ import com.viettel.campaign.model.ccms_full.*;
import com.viettel.campaign.service.*;
import com.viettel.campaign.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.core.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
......@@ -41,6 +42,7 @@ public class CampaignJob {
// @Scheduled(fixedRate = 5000)
// @Transactional( propagation = Propagation.REQUIRED)
@SchedulerLock(name = "testTimer", lockAtMostFor = 20*1000, lockAtLeastFor = 20*1000)
public void process() {
log.info(Thread.currentThread().getName() + " The Task executed at " + dateFormat.format(new Date()));
List<ProcessConfig> list = processConfigService.findAll();
......
......@@ -13,6 +13,9 @@ import java.util.List;
@Repository
public interface CampaignCfgRepository extends JpaRepository<CampaignCfg, Long> {
@Query("select c from CampaignCfg c where c.companySiteId=:p_company_site_id and c.status = 1")
List<CampaignCfg> findByCampaignCompleteCodeId( @Param("p_company_site_id") Long p_company_site_id);
@Query("select c from CampaignCfg c where c.campaignCompleteCodeId in (:p_ids) and c.companySiteId=:p_company_site_id and c.status = 1")
List<CampaignCfg> findAllCampaignCfg(@Param("p_ids") List<Long> p_ids, @Param("p_company_site_id") Long p_company_site_id);
......
......@@ -14,6 +14,9 @@ public interface CustomerListRepository extends JpaRepository<CustomerList, Long
CustomerList findByCustomerListCode(String customerListCode);
@Query("select c from CustomerList c where c.customerListId in (:p_ids) and c.companySiteId=:p_company_site_id and c.status = 1")
List<CustomerList> findAllCustomerList(@Param("p_ids") List<Long> p_ids, @Param("p_company_site_id") Long p_company_site_id);
@Modifying
@Query("update CustomerList c set c.status = 0 where c.customerListId=:p_customer_list_id and c.companySiteId=:p_company_site_id")
int deleteCustomerList(@Param("p_customer_list_id") Long p_customer_list_id, @Param("p_company_site_id") Long p_company_site_id);
......
......@@ -4,10 +4,7 @@ import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.CampaignCustomer;
import com.viettel.campaign.repository.ccms_full.CampaignCustomerRepository;
import com.viettel.campaign.repository.ccms_full.CampaignRepositoryCustom;
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.utils.*;
import com.viettel.campaign.web.dto.*;
import com.viettel.campaign.web.dto.request_dto.CampaignRequestDTO;
import org.apache.logging.log4j.LogManager;
......@@ -29,10 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@Repository
public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
......@@ -52,6 +46,7 @@ public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
@Override
public ResultDTO search(CampaignRequestDTO requestDto) {
TimeZone tzClient = TimeZoneUtils.getZoneMinutes((long) requestDto.getTimezoneOffset());
logger.info("Start search campaign::");
ResultDTO result = new ResultDTO();
......@@ -131,16 +126,16 @@ public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
sb.append(" AND a.STATUS IN (:p_statuses) ");
}
if (!DataUtil.isNullOrEmpty(requestDto.getFromDateFr())) {
sb.append(" AND TO_DATE(a.START_TIME, 'DD-MM-RR') >= TO_DATE(:p_frDateFr, 'YYYYMMDD')");
sb.append(" AND a.START_TIME >= TO_DATE(:p_frDateFr, 'DD/MM/YYYY HH24:MI:SS')");
}
if (!DataUtil.isNullOrEmpty(requestDto.getToDateFr())) {
sb.append(" AND TO_DATE(a.START_TIME, 'DD-MM-RR') <= TO_DATE(:p_toDateFr, 'YYYYMMDD')");
sb.append(" AND a.START_TIME <= TO_DATE(:p_toDateFr, 'DD/MM/YYYY HH24:MI:SS')");
}
if (!DataUtil.isNullOrEmpty(requestDto.getFromDateTo())) {
sb.append(" AND TO_DATE(a.END_TIME, 'DD-MM-RR') >= TO_DATE(:p_frDateTo, 'YYYYMMDD')");
sb.append(" AND a.END_TIME >= TO_DATE(:p_frDateTo, 'DD/MM/YYYY HH24:MI:SS')");
}
if (!DataUtil.isNullOrEmpty(requestDto.getToDateTo())) {
sb.append(" AND TO_DATE(a.END_TIME, 'DD-MM-RR') <= TO_DATE(:p_toDateTo, 'YYYYMMDD')");
sb.append(" AND a.END_TIME <= TO_DATE(:p_toDateTo, 'DD/MM/YYYY HH24:MI:SS')");
}
if (!DataUtil.isNullOrZero(requestDto.getNumOfCusFr())) {
sb.append(" AND a.CUSTOMER_NUMBER >= :p_cusNumFr");
......@@ -185,16 +180,16 @@ public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
query.setParameterList("p_statuses", statuses);
}
if (!DataUtil.isNullOrEmpty(requestDto.getFromDateFr())) {
query.setParameter("p_frDateFr", requestDto.getFromDateFr());
query.setParameter("p_frDateFr", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",requestDto.getFromDateFr()), tzClient));
}
if (!DataUtil.isNullOrEmpty(requestDto.getFromDateTo())) {
query.setParameter("p_frDateTo", requestDto.getFromDateTo());
query.setParameter("p_frDateTo", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",requestDto.getFromDateTo()), tzClient));
}
if (!DataUtil.isNullOrEmpty(requestDto.getToDateFr())) {
query.setParameter("p_toDateFr", requestDto.getToDateFr());
query.setParameter("p_toDateFr", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",requestDto.getToDateFr()), tzClient));
}
if (!DataUtil.isNullOrEmpty(requestDto.getToDateTo())) {
query.setParameter("p_toDateTo", requestDto.getToDateTo());
query.setParameter("p_toDateTo", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",requestDto.getToDateTo()), tzClient));
}
if (!DataUtil.isNullOrEmpty(requestDto.getTypes())) {
String[] types = requestDto.getTypes().split(",");
......@@ -247,10 +242,18 @@ public class CampaignRepositoryImpl implements CampaignRepositoryCustom {
query.setMaxResults(pageable.getPageSize());
}
List<CampaignDTO> data = query.list();
data.forEach(item -> {
item.setStartTime(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getStartTime(),tzClient)));
item.setEndTime(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getEndTime(),tzClient)));
});
Page<CampaignDTO> dataPage = new PageImpl<>(data, pageable, count);
result.setData(dataPage);
} else {
List<CampaignDTO> dataExport = query.list();
dataExport.forEach(item -> {
item.setStartTime(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getStartTime(),tzClient)));
item.setEndTime(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getEndTime(),tzClient)));
});
result.setData(dataExport);
}
result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
......
......@@ -20,7 +20,7 @@ public interface CampaignCfgService {
ResultDTO deleteList(CampaignCfgRequestDTO campaignCfgRequestDTO);
ResultDTO deleteById(Long id);
ResultDTO deleteById(CampaignCfgRequestDTO campaignCfgRequestDTO);
ResultDTO findMaxValueCampaignCompleteCode(CampaignCfgDTO completeCodeDTO);
......
......@@ -167,12 +167,6 @@ public class CampaignCfgServiceImpl implements CampaignCfgService {
try {
if (completeCodeDTO != null) {
// insert
// compCode = compCodeMapper.toPersistenceBean(completeCodeDTO);
// compCode = completeCodeRepository.save(compCode);
//
// resultDTO.setErrorCode("0");
// resultDTO.setDescription("Complete Code: " + compCode.getCampaignCompleteCodeId() + " created!");
CampaignCfg cl = new CampaignCfg();
cl.setStatus((short) 1);
cl.setCreateBy(String.valueOf(userId));
......@@ -241,14 +235,23 @@ public class CampaignCfgServiceImpl implements CampaignCfgService {
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO deleteCompleteCode(CampaignCfgRequestDTO completeCodeDTO) {
ResultDTO resultDTO = new ResultDTO();
List<Long> listId = new ArrayList<>();
listId.add(completeCodeDTO.getCampaignCompleteCodeID());
try {
// delete
if (completeCodeDTO != null) {
completeCodeRepository.deleteCampaignCompleteCodeBy(completeCodeDTO.getCampaignCompleteCodeID(), completeCodeDTO.getCompanySiteId());
// completeCodeRepository.deleteCampaignCompleteCodeBy(completeCodeDTO.getCampaignCompleteCodeID(), completeCodeDTO.getCompanySiteId());
if (completeCodeRepository.findAllCampaignCfg(listId, completeCodeDTO.getCompanySiteId()).size() > 0) {
completeCodeRepository.deleteCampaignCompleteCodeBy(completeCodeDTO.getCampaignCompleteCodeID(), completeCodeDTO.getCompanySiteId());
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
}
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
......@@ -256,6 +259,7 @@ public class CampaignCfgServiceImpl implements CampaignCfgService {
} catch (Exception e) {
// e.printStackTrace();
logger.error(e.getMessage(), e);
}
return resultDTO;
......@@ -284,26 +288,36 @@ public class CampaignCfgServiceImpl implements CampaignCfgService {
}
} catch (Exception e) {
// e.printStackTrace();
logger.error(e.getMessage(), e);
}
return resultDTO;
}
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO deleteById(Long id) {
public ResultDTO deleteById(CampaignCfgRequestDTO completeCodeDTO) {
ResultDTO result = new ResultDTO();
try {
completeCodeRepository.deleteById(id);
result.setErrorCode(Constants.Status.ACTIVE_STR);
result.setDescription(Constants.Status.ACTIVE_STR);
if (completeCodeDTO != null) {
if (completeCodeRepository.findAllCampaignCfg(completeCodeDTO.getListId(), completeCodeDTO.getCompanySiteId()).size() > 0) {
completeCodeRepository.deletedList(completeCodeDTO.getListId(), completeCodeDTO.getCompanySiteId());
result.setErrorCode(Constants.ApiErrorCode.SUCCESS);
result.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
result.setErrorCode(Constants.ApiErrorCode.ERROR);
result.setDescription(Constants.ApiErrorDesc.ERROR);
}
} else {
result.setErrorCode(Constants.ApiErrorCode.ERROR);
result.setDescription(Constants.ApiErrorDesc.ERROR);
}
} catch (Exception e) {
result.setErrorCode("-1");
return result;
// e.printStackTrace();
logger.error(e.getMessage(), e);
}
result.setErrorCode("0");
return result;
return result;
}
......
......@@ -357,7 +357,7 @@ public class CampaignServiceImpl implements CampaignService {
entity.setUpdateBy(campaignDTO.getUpdateBy());
entity.setEndTime(campaignDTO.getEndTime());
campaignRepository.save(entity);
//campaignRepository.save(entity);
UserActionLogDTO userActionLog = new UserActionLogDTO();
userActionLog.setAgentId(null);
......@@ -368,7 +368,7 @@ public class CampaignServiceImpl implements CampaignService {
userActionLog.setEndTime(null);
userActionLog.setObjectId(entity.getCampaignId());
userActionLog.setActionType((short) 6);
userActionLogRepository.insertToUserActionLog(userActionLog);
//userActionLogRepository.insertToUserActionLog(userActionLog);
resultDTO.setData(entity);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
......
......@@ -393,10 +393,9 @@ public class CustomerServiceImpl implements CustomerService {
public ResultDTO deleteCustomer(CustomerRequestDTO customerRequestDTO) {
ResultDTO resultDTO = new ResultDTO();
List<Long> listId = new ArrayList<>();
listId.add(customerRequestDTO.getCustomerId());
try {
if (customerRequestDTO != null) {
listId.add(customerRequestDTO.getCustomerId());
if (customerListMappingRepository.findAllCustomerListMapping(listId, customerRequestDTO.getCustomerListId(), customerRequestDTO.getCompanySiteId()).size() > 0) {
// delete
// customerRepository.deleteById(customerDTO.getCustomerId());
......@@ -405,8 +404,8 @@ public class CustomerServiceImpl implements CustomerService {
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
resultDTO.setErrorCode(Constants.ApiErrorCode.DELETE_ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.DELETE_ERROR);
}
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
......@@ -425,10 +424,15 @@ public class CustomerServiceImpl implements CustomerService {
ResultDTO resultDTO = new ResultDTO();
try {
if (customerRequestDTO != null) {
// customerRepository.deleteIds(ids);
customerListMappingRepository.deleteMappingByCustomerIds(customerRequestDTO.getIds(), customerRequestDTO.getCustomerListId(), customerRequestDTO.getCompanySiteId());
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
if (customerListMappingRepository.findAllCustomerListMapping(customerRequestDTO.getIds(), customerRequestDTO.getCustomerListId(), customerRequestDTO.getCompanySiteId()).size() > 0) {
//customerRepository.deleteIds(ids);
customerListMappingRepository.deleteMappingByCustomerIds(customerRequestDTO.getIds(), customerRequestDTO.getCustomerListId(), customerRequestDTO.getCompanySiteId());
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.DELETE_ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.DELETE_ERROR);
}
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
......@@ -721,17 +725,23 @@ public class CustomerServiceImpl implements CustomerService {
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO deleteCustomerList(CustomerListDTO customerListDTO) {
ResultDTO resultDTO = new ResultDTO();
List<Long> ids = new ArrayList<>();
ids.add(customerListDTO.getCustomerListId());
try {
// delete
if (DataUtil.isNullOrZero(campaignCustomerListRepository.campaignCount(customerListDTO.getCustomerListId()))) {
customerListRepository.deleteCustomerList(customerListDTO.getCustomerListId(), customerListDTO.getCompanySiteId());
if (customerListRepository.findAllCustomerList(ids, customerListDTO.getCompanySiteId()).size() > 0) {
customerListRepository.deleteCustomerList(customerListDTO.getCustomerListId(), customerListDTO.getCompanySiteId());
customerListMappingRepository.deleteMappingByCustomerListId(customerListDTO.getCustomerListId(), customerListDTO.getCompanySiteId());
customerListMappingRepository.deleteMappingByCustomerListId(customerListDTO.getCustomerListId(), customerListDTO.getCompanySiteId());
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.DELETE_ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.DELETE_ERROR);
}
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
......@@ -751,12 +761,17 @@ public class CustomerServiceImpl implements CustomerService {
try {
if (customerRequestDTO != null) {
if (DataUtil.isNullOrZero(campaignCustomerListRepository.campaignIdsCount(customerRequestDTO.getIds()))) {
customerListRepository.deleteCustomerListIds(customerRequestDTO.getIds(), customerRequestDTO.getCompanySiteId());
if (customerListRepository.findAllCustomerList(customerRequestDTO.getIds(), customerRequestDTO.getCompanySiteId()).size() > 0) {
customerListRepository.deleteCustomerListIds(customerRequestDTO.getIds(), customerRequestDTO.getCompanySiteId());
customerListMappingRepository.deleteMappingByCustomerListIds(customerRequestDTO.getIds(), customerRequestDTO.getCompanySiteId());
customerListMappingRepository.deleteMappingByCustomerListIds(customerRequestDTO.getIds(), customerRequestDTO.getCompanySiteId());
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.DELETE_ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.DELETE_ERROR);
}
} else {
resultDTO.setErrorCode(Constants.ApiErrorCode.ERROR);
resultDTO.setDescription(Constants.ApiErrorDesc.ERROR);
......@@ -774,6 +789,7 @@ public class CustomerServiceImpl implements CustomerService {
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public ResultDTO searchCustomerList(SearchCustomerRequestDTO searchCustomerRequestDTO) {
TimeZone tzClient = TimeZoneUtils.getZoneMinutes((long) searchCustomerRequestDTO.getTimezoneOffset());
ResultDTO resultDTO = new ResultDTO();
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
......@@ -814,7 +830,7 @@ public class CustomerServiceImpl implements CustomerService {
sb.append(" AND a.STATUS = 1");
sb.append(" AND a.COMPANY_SITE_ID = :p_company_site_id");
sb.append(" AND to_date(CREATE_AT, 'DD-MM-RR') >= to_date(:p_date_from, 'YYYYMMDD') AND to_date(CREATE_AT, 'DD-MM-RR') <= to_date(:p_date_to, 'YYYYMMDD')");
sb.append(" AND CREATE_AT >= to_date(:p_date_from, 'DD/MM/YYYY HH24:MI:SS') AND CREATE_AT <= to_date(:p_date_to, 'DD/MM/YYYY HH24:MI:SS')");
if (!DataUtil.isNullOrEmpty(searchCustomerRequestDTO.getCustomerListCode())) {
sb.append(" AND UPPER(CUSTOMER_LIST_CODE) LIKE UPPER(:p_list_code)");
......@@ -828,8 +844,8 @@ public class CustomerServiceImpl implements CustomerService {
SQLQuery query = session.createSQLQuery(sb.toString());
query.setParameter("p_company_site_id", searchCustomerRequestDTO.getCompanySiteId());
query.setParameter("p_date_from", searchCustomerRequestDTO.getConvertedDateFrom());
query.setParameter("p_date_to", searchCustomerRequestDTO.getConvertedDateTo());
query.setParameter("p_date_from", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",searchCustomerRequestDTO.getConvertedDateFrom()), tzClient));
query.setParameter("p_date_to", TimeZoneUtils.toDateStringWithTimeZone(DateTimeUtil.parseDate("YYYYMMdd",searchCustomerRequestDTO.getConvertedDateTo()), tzClient));
if (!DataUtil.isNullOrEmpty(searchCustomerRequestDTO.getCustomerListCode())) {
query.setParameter("p_list_code", "%" +
......@@ -877,6 +893,12 @@ public class CustomerServiceImpl implements CustomerService {
List<CustomerListDTO> data = query.list();
Page<CustomerListDTO> dataPage = new PageImpl<>(data, pageable, count);
dataPage.forEach(item -> {
item.setCreateAt(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getCreateAt(),tzClient)));
if (item.getUpdateAt() != null) {
item.setUpdateAt(DateTimeUtil.parseDate("dd/MM/yyyy HH:mm:ss",TimeZoneUtils.toDateStringWithTimeZone(item.getUpdateAt(),tzClient)));
}
});
resultDTO.setData(dataPage);
resultDTO.setErrorCode(Constants.ApiErrorCode.SUCCESS);
resultDTO.setDescription(Constants.ApiErrorDesc.SUCCESS);
......@@ -960,8 +982,11 @@ public class CustomerServiceImpl implements CustomerService {
DataFormatter dataFormat = new DataFormatter();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Map<String, Object> result = new HashMap<>();
Map<String, Integer> headerMap = new HashMap<>();
List<String> stringHeader = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int failedCount = 0;
int objectSize;
XSSFWorkbook workbook = null;
boolean isMainPhoneNull = false, isSecondPhoneNull = false, isEmailNull = false;
try {
......@@ -983,62 +1008,53 @@ public class CustomerServiceImpl implements CustomerService {
header.add(new CustomizeFields("combobox", BundleUtils.getLangString("customer.smsAllowed", locale)));
header.addAll(dynamicHeader);
for (CustomizeFields cf : header) {
stringHeader.add(cf.getTitle().split("#")[0].trim());
}
//</editor-fold>
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
workbook = new XSSFWorkbook(fis);
ByteArrayOutputStream os = new ByteArrayOutputStream();
XSSFSheet 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);
resultStyle.setAlignment(HorizontalAlignment.CENTER);
resultStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//</editor-fold>
//<editor-fold desc="Kiểm tra header của template" defaultstate="collapsed">
if (row.getPhysicalNumberOfCells() > header.size()) {
for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
if (sheet.isColumnHidden(i)) {
sheet.setColumnHidden(i, false);
}
if (isColumnNullOrBlank(sheet, i)) {
sheet.shiftColumns(i + 1, i + 1, -1);
sheet.removeMergedRegion(0);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 13));
if (row.getLastCellNum() > header.size()) {
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell c = row.getCell(i);
if (c != null && !c.getStringCellValue().trim().equals("")) {
if (stringHeader.contains(c.getStringCellValue().trim()) && !headerMap.containsKey(c.getStringCellValue().trim())) {
headerMap.put(c.getStringCellValue().trim(), c.getColumnIndex());
}
}
}
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("content", Files.readAllBytes(file.toPath()));
result.put("message", "template-invalid");
return result;
}
if (headerMap.size() != header.size()) {
result.put("content", Files.readAllBytes(file.toPath()));
result.put("message", "template-invalid");
return result;
}
} else if (row.getPhysicalNumberOfCells() < header.size()) {
objectSize = row.getLastCellNum();
} else if (row.getLastCellNum() < header.size()) {
result.put("content", Files.readAllBytes(file.toPath()));
result.put("message", "template-invalid");
return result;
} else {
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("content", Files.readAllBytes(file.toPath()));
result.put("message", "template-invalid");
return result;
Cell c = row.getCell(i);
if (c != null && !"".equals(c.getStringCellValue().trim())) {
if (stringHeader.contains(c.getStringCellValue().trim()) && !headerMap.containsKey(c.getStringCellValue().trim())) {
headerMap.put(c.getStringCellValue().trim(), c.getColumnIndex());
}
}
}
if (headerMap.size() != header.size()) {
result.put("content", Files.readAllBytes(file.toPath()));
result.put("message", "template-invalid");
return result;
}
objectSize = row.getLastCellNum();
}
//</editor-fold>
......@@ -1049,13 +1065,6 @@ public class CustomerServiceImpl implements CustomerService {
result.put("message", "template-no-data");
result.put("content", Files.readAllBytes(file.toPath()));
return result;
} else {
Cell resultCell = sheet.getRow(3).getCell(header.size());
if (resultCell == null) {
resultCell = sheet.getRow(3).createCell(header.size());
}
resultCell.setCellValue(BundleUtils.getLangString("customer.result", locale));
resultCell.setCellStyle(resultStyle);
}
//</editor-fold>
......@@ -1063,23 +1072,36 @@ public class CustomerServiceImpl implements CustomerService {
for (int i = 4; i <= sheet.getPhysicalNumberOfRows(); i++) {
Row dataRow = sheet.getRow(i);
if (dataRow != null) {
Object[] obj = new Object[row.getPhysicalNumberOfCells() - 1];
for (int j = 0; j < row.getPhysicalNumberOfCells() - 1; j++) {
Cell dataCell = dataRow.getCell(j);
Object[] obj = new Object[objectSize + 1];
// for (int j = 0; j < header.size(); j++) {
// Cell dataCell = dataRow.getCell(j);
// if (dataCell != null) {
// obj[j] = dataFormat.formatCellValue(dataCell);
// } 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);
// } else {
// obj[j] = null;
// }
// }
// }
headerMap.forEach((k, v) -> {
Cell dataCell = dataRow.getCell(v);
if (dataCell != null) {
obj[j] = dataFormat.formatCellValue(dataCell);
obj[v] = dataFormat.formatCellValue(dataCell);
} 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);
} else {
obj[j] = null;
}
if (k.equals(BundleUtils.getLangString("customer.cusType", locale))) {
obj[v] = BundleUtils.getLangString("customer.cusType.normal", locale);
} else if (k.equals(BundleUtils.getLangString("customer.callAllowed", locale)) || k.equals(BundleUtils.getLangString("customer.emailAllowed", locale))
|| k.equals(BundleUtils.getLangString("customer.smsAllowed", locale))) {
obj[v] = BundleUtils.getLangString("customer.yes", locale);
} else obj[v] = null;
}
}
});
rawDataList.add(obj);
}
}
......@@ -1088,54 +1110,61 @@ public class CustomerServiceImpl implements CustomerService {
//<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 (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.fullname", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.fullname", locale).split("#")[0])] != null
&& !rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.fullname", locale).split("#")[0])].toString().trim().equals("")) {
String str = validateLength(BundleUtils.getLangString("customer.fullname", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.fullname", locale).split("#")[0])].toString(), 1000, locale);
if (!str.equals("")) {
sb.append(str);
}
} else sb.append(BundleUtils.getLangString("customer.nameRequired", locale));
if (rawDataList.get(i).length > 4 && (rawDataList.get(i)[2] == null || rawDataList.get(i)[2].toString().trim().equals(""))) {
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])
&& (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])] == null || rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])].toString().trim().equals(""))) {
isMainPhoneNull = true;
} else {
if (validateNumberOnly(rawDataList.get(i)[2].toString().trim())) {
sb.append(validateExistPhone(rawDataList.get(i)[2].toString().trim(), locale));
if (validateNumberOnly(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])].toString().trim())) {
sb.append(validateExistPhone(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])].toString().trim(), locale));
} else {
sb.append(BundleUtils.getLangString("customer.onlyNumber", locale));
}
}
if (rawDataList.get(i).length > 4 && (rawDataList.get(i)[3] == null || rawDataList.get(i)[3].toString().trim().equals(""))) {
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0]) && (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])] == null || rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])].toString().trim().equals(""))) {
isSecondPhoneNull = true;
} else {
if (validateNumberOnly(rawDataList.get(i)[3].toString().trim())) {
sb.append(validateLength(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0], rawDataList.get(i)[3].toString(), 50, locale));
if (validateNumberOnly(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])].toString().trim())) {
sb.append(validateLength(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])].toString(), 50, locale));
} else {
sb.append(BundleUtils.getLangString("customer.onlyNumber", locale));
}
}
if (rawDataList.get(i).length > 4 && (rawDataList.get(i)[4] == null || rawDataList.get(i)[4].toString().trim().equals(""))) {
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])
&& (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])] == null || rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])].toString().trim().equals(""))) {
isEmailNull = true;
} else {
if (!validateEmail(rawDataList.get(i)[4].toString().trim())) {
if (!validateEmail(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])].toString().trim())) {
sb.append(BundleUtils.getLangString("customer.emailInvalid", locale));
} else {
sb.append(validateDuplicateEmail(rawDataList.get(i)[4].toString().trim(), locale));
sb.append(validateLength(BundleUtils.getLangString("customer.email", locale).split("#")[0], rawDataList.get(i)[4].toString(), 50, locale));
sb.append(validateDuplicateEmail(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])].toString().trim(), locale));
sb.append(validateLength(BundleUtils.getLangString("customer.email", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])].toString(), 100, locale));
}
}
if (isEmailNull && isMainPhoneNull && isSecondPhoneNull) {
sb.append(BundleUtils.getLangString("customer.invalidRecord", 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 > headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0]) && rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.address", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])].toString(), 500, locale));
}
if (rawDataList.get(i).length > 6 && rawDataList.get(i)[6] != null) {
sb.append(validateCusType(rawDataList.get(i)[6].toString().trim(), locale));
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.cusType", locale))
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.cusType", locale))] != null) {
sb.append(validateCusType(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.cusType", locale))].toString().trim(), 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 > headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.companyName", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])].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));
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])] != null) {
sb.append(validateLength(BundleUtils.getLangString("customer.description", locale).split("#")[0], rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])].toString(), 2000, locale));
}
// for (int j = 12; j < header.size(); j++) {
// if (rawDataList.get(i).length > j && rawDataList.get(i)[j] != null) {
......@@ -1148,13 +1177,13 @@ public class CustomerServiceImpl implements CustomerService {
// }
// }
// }
Row dataRow = sheet.getRow(4 + i);
Cell resultCell = dataRow.createCell(row.getPhysicalNumberOfCells() - 1);
// Row dataRow = sheet.getRow(4 + i);
// Cell resultCell = dataRow.createCell(row.getPhysicalNumberOfCells() - 1);
if (sb.length() > 0) {
resultCell.setCellValue(sb.toString());
rawDataList.get(i)[objectSize] = sb.toString();
failedCount++;
} else {
resultCell.setCellValue("Ok");
rawDataList.get(i)[objectSize] = "Ok";
}
sb = new StringBuilder();
isEmailNull = false;
......@@ -1163,18 +1192,24 @@ public class CustomerServiceImpl implements CustomerService {
}
//</editor-fold>
byte[] content = buildResultTemplate(rawDataList, header, headerMap, row.getLastCellNum());
//<editor-fold desc="Insert dữ liệu nếu validate Ok" defaultstate="collapsed">
if (failedCount == 0) {
for (int i = 0; i < rawDataList.size(); i++) {
Customer c = new Customer();
c.setName(rawDataList.get(i)[1].toString().trim());
c.setName(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.fullname", locale).split("#")[0])].toString().trim());
c.setSiteId(userSession.getSiteId());
c.setCode(null);
if (rawDataList.get(i).length > 8 && rawDataList.get(i)[8] != null && !rawDataList.get(i)[8].toString().trim().equals("")) {
c.setDescription(rawDataList.get(i)[8].toString().trim());
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])] != null
&& !rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])].toString().trim().equals("")) {
c.setDescription(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.description", locale).split("#")[0])].toString().trim());
}
if (rawDataList.get(i).length > 7 && rawDataList.get(i)[7] != null && !rawDataList.get(i)[7].toString().trim().equals("")) {
c.setCompanyName(rawDataList.get(i)[7].toString().trim());
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])] != null
&& !rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])].toString().trim().equals("")) {
c.setCompanyName(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.companyName", locale).split("#")[0])].toString().trim());
}
c.setCustomerImg(null);
c.setCreateDate(new Date());
......@@ -1183,8 +1218,10 @@ public class CustomerServiceImpl implements CustomerService {
c.setCreateBy(userSession.getUserName());
c.setUpdateBy(null);
c.setGender((short) 1);
if (rawDataList.get(i).length > 5 && rawDataList.get(i)[5] != null && !rawDataList.get(i)[5].toString().trim().equals("")) {
c.setCurrentAddress(rawDataList.get(i)[5].toString().trim());
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])] != null
&& !rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])].toString().trim().equals("")) {
c.setCurrentAddress(rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.address", locale).split("#")[0])].toString().trim());
}
// c.setPlaceOfBirth();
// c.setDateOfBirth();
......@@ -1192,7 +1229,7 @@ public class CustomerServiceImpl implements CustomerService {
c.setEmail(null);
c.setUserName(null);
c.setAreaCode(null);
switch (rawDataList.get(i)[6].toString().trim()) {
switch (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.cusType", locale))].toString().trim()) {
case "VIP":
c.setCustomerType(2L);
break;
......@@ -1203,25 +1240,26 @@ public class CustomerServiceImpl implements CustomerService {
c.setCustomerType(1L);
break;
}
if (rawDataList.get(i)[9].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
if (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.callAllowed", locale))].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setCallAllowed(1L);
} else {
c.setCallAllowed(0L);
}
if (rawDataList.get(i)[10].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
if (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.emailAllowed", locale))].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setEmailAllowed(1L);
} else {
c.setEmailAllowed(0L);
}
if (rawDataList.get(i)[11].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
if (rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.smsAllowed", locale))].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
c.setSmsAllowed(1L);
} else {
c.setSmsAllowed(0L);
}
c.setIpccStatus("active");
Customer saved = customerRepository.save(c);
if (rawDataList.get(i).length > 2 && rawDataList.get(i)[2] != null) {
String[] mainPhone = rawDataList.get(i)[2].toString().trim().split(";");
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])] != null) {
String[] mainPhone = rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.mainPhone", locale).split("#")[0])].toString().trim().split(";");
for (int j = 0; j < mainPhone.length; j++) {
CustomerContact cc = new CustomerContact();
cc.setCustomerId(saved.getCustomerId());
......@@ -1237,8 +1275,9 @@ public class CustomerServiceImpl implements CustomerService {
customerContactRepository.save(cc);
}
}
if (rawDataList.get(i).length > 3 && rawDataList.get(i)[3] != null) {
String[] subPhone = rawDataList.get(i)[3].toString().trim().split(";");
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])] != null) {
String[] subPhone = rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.secondPhone", locale).split("#")[0])].toString().trim().split(";");
for (int j = 0; j < subPhone.length; j++) {
CustomerContact cc = new CustomerContact();
cc.setCustomerId(saved.getCustomerId());
......@@ -1254,8 +1293,9 @@ public class CustomerServiceImpl implements CustomerService {
customerContactRepository.save(cc);
}
}
if (rawDataList.get(i).length > 4 && rawDataList.get(i)[4] != null) {
String[] email = rawDataList.get(i)[4].toString().split(";");
if (rawDataList.get(i).length > headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])
&& rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])] != null) {
String[] email = rawDataList.get(i)[headerMap.get(BundleUtils.getLangString("customer.email", locale).split("#")[0])].toString().split(";");
for (int j = 0; j < email.length; j++) {
CustomerContact cc = new CustomerContact();
cc.setCustomerId(saved.getCustomerId());
......@@ -1275,29 +1315,29 @@ public class CustomerServiceImpl implements CustomerService {
CustomizeFieldObject cfo = new CustomizeFieldObject();
cfo.setObjectId(saved.getCustomerId());
cfo.setCustomizeFieldId(dynamicHeader.get(j).getCustomizeFieldId());
if (rawDataList.get(i).length > (12 + j) && rawDataList.get(i)[12 + j] != null) {
if (rawDataList.get(i).length > headerMap.get(dynamicHeader.get(j).getTitle()) && rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())] != null) {
switch (dynamicHeader.get(j).getType()) {
case "combobox":
CustomizeFieldOptionValue cfov =
customizeFieldOptionValueRepository.findCustomizeFieldOptionValueByNameEqualsAndStatus(rawDataList.get(i)[12 + j].toString().trim(), 1L);
customizeFieldOptionValueRepository.findCustomizeFieldOptionValueByNameEqualsAndStatus(rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())].toString().trim(), 1L);
cfo.setFieldOptionValueId(cfov.getFieldOptionValueId());
break;
case "checkbox":
if (rawDataList.get(i)[12 + j].toString().trim().equals(BundleUtils.getLangString("customer.yes", locale))) {
if (rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())].toString().trim().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().trim());
Date date = dateFormat.parse(rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())].toString().trim());
cfo.setValueDate(date);
break;
case "number":
cfo.setValueNumber(Long.parseLong(rawDataList.get(i)[12 + j].toString().trim()));
cfo.setValueNumber(Long.parseLong(rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())].toString().trim()));
break;
default:
cfo.setValueText(rawDataList.get(i)[12 + j].toString().trim());
cfo.setValueText(rawDataList.get(i)[headerMap.get(dynamicHeader.get(j).getTitle())].toString().trim());
break;
}
}
......@@ -1314,18 +1354,14 @@ public class CustomerServiceImpl implements CustomerService {
clm.setCustomerListId(customerListId);
customerListMappingRepository.save(clm);
}
workbook.write(os);
os.flush();
os.close();
// workbook.write(os);
workbook.close();
result.put("content", os.toByteArray());
result.put("content", content);
result.put("message", "import-success");
} else {
workbook.write(os);
os.flush();
os.close();
// workbook.write(os);
workbook.close();
result.put("content", os.toByteArray());
result.put("content", content);
result.put("message", "import-error");
}
//</editor-fold>
......@@ -1346,12 +1382,23 @@ public class CustomerServiceImpl implements CustomerService {
String[] arr = str.split(";");
List<CustomerContact> contactList;
if (str.length() > 50) {
result = BundleUtils.getLangString("customer.phoneMax50", locale);
result += BundleUtils.getLangString("customer.phoneMax50", locale);
}
if (arr.length > 3) {
result += BundleUtils.getLangString("customer.3phone", locale);
} else {
for (int i = 0; i < arr.length; i++) {
if (arr[i].length() < 8 || arr[i].length() > 15) {
result += BundleUtils.getLangString("customer.phone8to15", locale);
break;
}
}
}
for (int i = 0; i < arr.length; i++) {
contactList = customerContactRepository.findCustomerContactsByContactEquals(arr[i]);
if (contactList.size() != 0) {
return result.concat(BundleUtils.getLangString("customer.phoneExists", locale));
result += BundleUtils.getLangString("customer.phoneExists", locale);
break;
}
}
return result;
......@@ -1371,7 +1418,7 @@ public class CustomerServiceImpl implements CustomerService {
private String validateDuplicateEmail(String str, Locale locale) {
String result = "";
String[] arr = str.split(";");
String[] arr = str.split(",");
List<CustomerContact> contactList;
for (int i = 0; i < arr.length; i++) {
contactList = customerContactRepository.findCustomerContactsByContactEquals(arr[i]);
......@@ -1403,7 +1450,7 @@ public class CustomerServiceImpl implements CustomerService {
}
private boolean validateEmail(String str) {
String[] arr = str.split(";");
String[] arr = str.split(",");
for (int i = 0; i < arr.length; i++) {
Matcher matcher = EMAIL_REGEXP.matcher(arr[i]);
if (!matcher.matches()) {
......@@ -1443,6 +1490,183 @@ public class CustomerServiceImpl implements CustomerService {
//</editor-fold>
private byte[] buildResultTemplate(List<Object[]> rawData, List<CustomizeFields> header, Map<String, Integer> dataMap, int lastNum) throws IOException {
LOGGER.info("---------------CREATE RESULT FILE--------------");
Locale locale = new Locale("vi", "VN");
XSSFWorkbook workbook = null;
Map<String, Integer> headerMap = new HashMap<>();
try {
workbook = new XSSFWorkbook();
CreationHelper creationHelper = workbook.getCreationHelper();
ByteArrayOutputStream os = new ByteArrayOutputStream();
Sheet sheet = workbook.createSheet("RESULT");
dataMap.put(BundleUtils.getLangString("customer.result", locale), lastNum);
//<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();
CellStyle columnStyle = workbook.createCellStyle();
importantStyle.setFont(importantFont);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFont(headerFont);
columnStyle.setVerticalAlignment(VerticalAlignment.CENTER);
columnStyle.setAlignment(HorizontalAlignment.CENTER);
columnStyle.setWrapText(true);
//</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 = 12; i < header.size(); i++) {
if (header.get(i).getType().equals("combobox")) {
String[] constraint;
List<CustomizeFieldOptionValue> list =
customizeFieldOptionValueRepository.findCustomizeFieldOptionValuesByFieldOptionIdAndStatus(header.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 (header.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(4, 9999, 6, 6);
CellRangeAddressList callCellRangeAddressList = new CellRangeAddressList(4, 9999, 9, 9);
CellRangeAddressList emailCellRangeAddressList = new CellRangeAddressList(4, 9999, 10, 10);
CellRangeAddressList smsCellRangeAddressList = new CellRangeAddressList(4, 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++) {
sheet.setDefaultColumnStyle(i, columnStyle);
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);
}
headerMap.put(header.get(i).getTitle().split("#")[0].trim(), i);
}
sheet.setColumnWidth(header.size(), 8000);
Cell resultCell = row3.createCell(header.size());
resultCell.setCellStyle(headerStyle);
resultCell.setCellValue(BundleUtils.getLangString("customer.result", locale));
headerMap.put(BundleUtils.getLangString("customer.result", locale), headerMap.size());
//</editor-fold>
//<editor-fold desc="Ghi dữ liệu">
for (int i = 0; i < rawData.size(); i++) {
Row dataRow = sheet.createRow(4 + i);
int finalI = i;
headerMap.forEach((k, v) -> {
Cell c = dataRow.createCell(v);
c.setCellType(CellType.STRING);
if (rawData.get(finalI).length > dataMap.get(k)
&& rawData.get(finalI)[dataMap.get(k)] != null
&& !"".equals(rawData.get(finalI)[dataMap.get(k)].toString().trim())) {
c.setCellValue(rawData.get(finalI)[dataMap.get(k)].toString());
}
});
// for (int j = 0; j < header.size(); j++) {
// headerMap.get(header.get(j).getTitle().split("#")[0]);
// if (rawData.get(i).length > header.size() + 1 && rawData.get(i)[j] != null && !"".equals(rawData.get(i)[j].toString().trim())) {
// Cell c = dataRow.createCell(j);
// c.setCellType(CellType.STRING);
// c.setCellValue(rawData.get(i)[j].toString());
// }
// }
}
//</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();
return os.toByteArray();
} catch (Exception e) {
LOGGER.error(e.getMessage());
return null;
} finally {
if (workbook != null) workbook.close();
}
}
@Override
@Transactional(DataSourceQualify.CCMS_FULL)
public byte[] buildTemplate(Long companySiteId) throws IOException {
......@@ -1454,6 +1678,7 @@ public class CustomerServiceImpl implements CustomerService {
CreationHelper creationHelper = workbook.getCreationHelper();
ByteArrayOutputStream os = new ByteArrayOutputStream();
Sheet sheet = workbook.createSheet("IMPORT");
DataFormat dataFormat = workbook.createDataFormat();
//<editor-fold desc="Tạo array header" defaultstate="collapsed">
List<CustomizeFields> header = new ArrayList<>();
......@@ -1489,6 +1714,7 @@ public class CustomerServiceImpl implements CustomerService {
columnStyle.setVerticalAlignment(VerticalAlignment.CENTER);
columnStyle.setAlignment(HorizontalAlignment.CENTER);
columnStyle.setWrapText(true);
columnStyle.setDataFormat(dataFormat.getFormat("@"));
//</editor-fold>
//<editor-fold desc="Thêm combobox" defaultstate="collapsed">
......
......@@ -69,6 +69,7 @@ public class ScenarioQuestionServiceImpl implements ScenarioQuestionService {
ResultDTO resultDTO = new ResultDTO();
List<ScenarioAnswerDTO> lstAnswers = new ArrayList<>();
List<ScenarioAnswer> lstAnswersToInsert = new ArrayList<>();
scenarioQuestionDTO.setQuestion(scenarioQuestionDTO.getQuestion().trim());
try {
ScenarioQuestion scenarioQuestion = modelMapper.map(scenarioQuestionDTO, ScenarioQuestion.class);
......
......@@ -7,10 +7,12 @@ public class Constants {
public interface ApiErrorCode {
String ERROR = "01";
String SUCCESS = "00";
String DELETE_ERROR = "02";
}
public interface ApiErrorDesc {
String ERROR = "ERROR";
String SUCCESS = "SUCCESS";
String DELETE_ERROR = "DELETE_ERROR";
}
public interface FileType {
String pdf = "pdf";
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.viettel.campaign.utils;
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
/**
*
* @author phamky
*/
public class TimeZoneUtils {
private static Long getTimeZone(TimeZone tz) {
return TimeUnit.MILLISECONDS.toHours(tz.getRawOffset());
}
private static Long getTimeZoneToMinutes(TimeZone tz) {
return TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset());
}
public static String toQueryTimeZoneZero(Date date){
String dateStr = toDateStringWithTimeZoneZero(date);
return "to_date( '"+dateStr+"', 'DD/MM/YYYY HH24:MI:SS')";
}
public static String changeTimeZoneString(String dateStr, TimeZone tz){
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = sdf.parse(dateStr);
sdf.setTimeZone(tz);
return sdf.format(date);
} catch (ParseException ex) {
}
return "";
}
public static String changeTimeZoneStringPattern(String dateStr, TimeZone tz, String pattern){
try {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = sdf1.parse(dateStr);
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(tz);
return sdf.format(date);
} catch (ParseException ex) {
}
return "";
}
public static String toDateStringWithTimeZoneZero(Date date){
TimeZone tz = getZone(0l);
return toDateStringWithTimeZone(date, tz);
}
public static String toDateStringWithTimeZonePattern(Date date, long tz, String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(getZone(tz));
return sdf.format(date);
}
// public static String toHourStringWithTimeZonePattern(Long hour, long tz){
// SimpleDateFormat sdf = new SimpleDateFormat(pattern);
// sdf.setTimeZone(getZone(tz));
// return sdf.format(date);
// }
public static String toDateStringWithTimeZonePattern(Date date, TimeZone tz, String pattern){
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setTimeZone(tz);
return sdf.format(date);
}
public static String toDateStringWithTimeZone(Date date, TimeZone tz){
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
sdf.setTimeZone(tz);
return sdf.format(date);
}
public static TimeZone getZone(Long timeZone){
if(timeZone == null){
//timezone is null, return default
return TimeZone.getDefault();
}
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if(getTimeZone(tz).equals(timeZone)){
//zone need change
return tz;
}
}
return TimeZone.getDefault();
}
public static TimeZone getZoneMinutes(Long timeZone){
if(timeZone == null){
//timezone is null, return default
return TimeZone.getDefault();
}
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if(getTimeZoneToMinutes(tz).equals(timeZone)){
//zone need change
return tz;
}
}
return TimeZone.getDefault();
}
public static Date changeTimeZone(Date date, Long timeZone){
if(timeZone == null){
//timezone is null, do not change timezone
return date;
}
String[] ids = TimeZone.getAvailableIDs();
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if(getTimeZone(tz).equals(timeZone)){
//zone need change
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(tz);
try {
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = df2.parse(df.format(date));
System.out.println(df2.format(newDate));
return newDate;
} catch (ParseException ex) {
}
}
}
return date;
}
public static void main(String args[]){
Date date = new Date();
System.out.println(changeTimeZone(date, -6l));
System.out.println(changeTimeZone(date, 0l));
System.out.println(getZone(0l));
}
}
......@@ -66,4 +66,7 @@ public class CampaignDTO extends BaseDTO {
private String sessionId;
private Long numOfInteractedCus;
private Long numOfNotInteractedCus;
//timezone to get true date
private Double timezone;
}
......@@ -10,5 +10,5 @@ public class CampaignCfgRequestDTO {
List<Long> listId;
Long companySiteId;
Long campaignCompleteCodeID;
String completeValue;
}
......@@ -12,4 +12,5 @@ public class SearchCustomerRequestDTO extends BaseDTO {
String convertedDateFrom;
String convertedDateTo;
String companySiteId;
Integer timezoneOffset;
}
......@@ -106,9 +106,9 @@ public class CampaignCfgController {
@PostMapping("/deleteById")
@ResponseBody
public ResultDTO deleteById(@RequestParam("id") Long id){
public ResultDTO deleteById(@RequestBody @Valid CampaignCfgRequestDTO campaignCfgRequestDTO){
ResultDTO resultDTO = new ResultDTO();
resultDTO = completeCodeService.deleteById(id);
resultDTO = completeCodeService.deleteById(campaignCfgRequestDTO);
return resultDTO;
}
......
......@@ -87,15 +87,13 @@ customer.cusType.vip = VIP
customer.cusType.blacklist = Blacklist
customer.yes = Yes
customer.not = No
customer.noData = Template empty
customer.nameRequired = Full name required;
customer.emailMax100=Email must less than 100 character;
customer.invalidRecord=Invalid Record, required one more contact information;
customer.onlyNumber=Phone contain number only;
customer.importSuccess = Import Successful
customer.importFailed = Import Failed
customer.errorValidate = Error while validating
customer.phoneMax50 = Mobile phone must less than 50 character;
customer.phoneMax50=Mobile phone must less than 50 characters;
customer.phone8to15=Mobile phone from 8 to 15 characters;
customer.3phone=Max 3 mobile phone;
customer.phoneExists = Mobile phone exists;
customer.notMatch = not match regexp validation
customer.notGreaterThan = not greater than
......
......@@ -89,15 +89,13 @@ customer.cusType.vip = VIP
customer.cusType.blacklist = Blacklist
customer.yes =
customer.not = Không
customer.noData = Template không có dữ liệu
customer.nameRequired = Họ và tên không được để trống;
customer.emailMax100=Email không được quá 100 kí tự;
customer.invalidRecord=Bắt buộc nhập 1 trong 3 thông tin liên lạc(Số điện thoại chính, Số điện thoại phụ, Email);
customer.onlyNumber=Số điện thoại chỉ được nhập số;
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.phone8to15=Số điện thoại chỉ được từ 8 đến 15 kí tự;
customer.3phone=Tối đa chỉ được nhập 3 số điện thoại;
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
......
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