Commit 4b201f38 authored by ='s avatar =

Merge remote-tracking branch 'origin/master'

parents 295d13ca bf23537e
......@@ -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,6 +121,12 @@
<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>
......
......@@ -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;
}
}
......@@ -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);
}
......@@ -2,15 +2,15 @@ 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 java.io.File;
import java.util.Date;
import java.util.List;
import java.util.List;
import java.util.Map;
public interface CustomerService {
......@@ -62,9 +62,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, Long companySiteId);
List<CustomizeFieldDTO> getCustomizeField(Long customerId);
List<CustomizeFieldObject> getCustomizeField(Long customerId);
}
......@@ -3,21 +3,21 @@ 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.*;
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.*;
import com.viettel.campaign.web.dto.request_dto.CustomerDetailRequestDTO;
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 +26,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 +35,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 +80,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 +811,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 +875,604 @@ 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, Long companySiteId) {
LOGGER.info("------------READ AND VALIDATE--------------");
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<String> staticHeader = new ArrayList<>();
// staticHeader.add("STT");
// staticHeader.add("Họ và tên#Bắt buộc\nĐịnh dạng chữ\ntối đa 1000 ký tự");
// staticHeader.add("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ự");
// staticHeader.add("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\ntối đa 50 ký tự");
// staticHeader.add("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ự");
// staticHeader.add("Địa chỉ#Tối đa 500 ký tự");
// staticHeader.add("Loại khách hàng");
// staticHeader.add("Công ty#Tối đa 100 ký tự");
// staticHeader.add("Ghi chú#Tối đa 2000 ký tự");
// staticHeader.add("Cho phép gọi ra");
// staticHeader.add("Cho phép gửi email");
// staticHeader.add("Cho phép gửi sms");
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.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"));
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", "Template sai dinh dang");
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", "File khong co du lieu");
result.put("file", file);
return result;
} else {
Cell resultCell = sheet.getRow(3).createCell(sheet.getRow(3).getPhysicalNumberOfCells());
resultCell.setCellValue("Kết quả");
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("Loại khách hàng")) {
obj[j] = "Thường";
} else if (headerCell.getStringCellValue().equals("Cho phép gọi ra") || headerCell.getStringCellValue().equals("Cho phép gửi email")
|| headerCell.getStringCellValue().equals("Cho phép gửi sms")) {
obj[j] = "Có";
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++) {
// sb.append(validateRecord(rawDataList.get(i)));
// sb.append(validateLength(row.getCell(1).getStringCellValue(), rawDataList.get(i)[1].toString(), 1000));
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[2] != null) {
// sb.append(validateLength(row.getCell(2).getStringCellValue(), rawDataList.get(i)[2].toString(), 50));
// }
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[3] != null) {
// sb.append(validateLength(row.getCell(3).getStringCellValue(), rawDataList.get(i)[3].toString(), 50));
// }
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[4] != null) {
// sb.append(validateLength(row.getCell(4).getStringCellValue(), rawDataList.get(i)[4].toString(), 100));
// String[] emails = rawDataList.get(i)[4].toString().split(";");
// boolean email = false;
// for (int j = 0; j < emails.length; j++) {
// if (!validateEmail(emails[j])) {
// email = true;
// }
// }
// if (email) {
// sb.append("Email khong dung dinh dang;");
// }
// }
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[5] != null) {
// sb.append(validateLength(row.getCell(5).getStringCellValue(), rawDataList.get(i)[5].toString(), 500));
// }
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[7] != null) {
// sb.append(validateLength(row.getCell(7).getStringCellValue(), rawDataList.get(i)[7].toString(), 100));
// }
// if (rawDataList.get(i).length > 12 && rawDataList.get(i)[8] != null) {
// sb.append(validateLength(row.getCell(8).getStringCellValue(), rawDataList.get(i)[8].toString(), 2000));
// }
// 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();
// }
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("Họ và tên", rawDataList.get(i)[1].toString(), 1000);
if (!str.equals("")) {
sb.append(str);
}
} else sb.append("Họ và tên không được để trống;");
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());
str.concat(validateLength("Số điện thoại phụ", rawDataList.get(i)[3].toString(), 50));
if (validateEmail(rawDataList.get(i)[4].toString().trim())) {
str.concat("Email không được quá 50 kí tự");
}
sb.append(str);
} else {
sb.append("Cả 3 thông tin liên lạc không được để trống;");
}
if (rawDataList.get(i).length > 5 && rawDataList.get(i)[5] != null) {
sb.append(validateLength("Địa chỉ", rawDataList.get(i)[5].toString(), 500));
}
if (rawDataList.get(i).length > 7 && rawDataList.get(i)[7] != null) {
sb.append(validateLength("Công ty", rawDataList.get(i)[7].toString(), 100));
}
if (rawDataList.get(i).length > 8 && rawDataList.get(i)[8] != null) {
sb.append(validateLength("Ghi chú", rawDataList.get(i)[8].toString(), 2000));
}
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()));
} else if (header.get(j).getType().equals("date")) {
sb.append(validateUsingRegexp(header.get(j).getTitle(), rawDataList.get(i)[j].toString(), header.get(j).getRegexpForValidation()));
} 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()));
}
}
}
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(companySiteId);
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();
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 "Thường":
c.setCustomerType(1L);
break;
case "VIP":
c.setCustomerType(2L);
break;
case "Blacklist":
c.setCustomerType(3L);
break;
}
switch (rawDataList.get(i)[9].toString()) {
case "Có":
c.setCallAllowed(1L);
break;
case "Không":
c.setCallAllowed(0L);
break;
}
switch (rawDataList.get(i)[10].toString()) {
case "Có":
c.setEmailAllowed(1L);
break;
case "Không":
c.setEmailAllowed(0L);
break;
}
switch (rawDataList.get(i)[11].toString()) {
case "Có":
c.setSmsAllowed(1L);
break;
case "Không":
c.setSmsAllowed(0L);
break;
}
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();
// cc.setUpdateBy();
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();
// cc.setUpdateBy();
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();
// cc.setUpdateBy();
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("có")) {
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();
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(companySiteId);
// clm.setCustomerListId();
customerListMappingRepository.save(clm);
}
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
workbook.close();
result.put("file", file);
result.put("message", "Import thanh cong");
} else {
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
result.put("file", file);
result.put("message", "Import du lieu loi");
}
//</editor-fold>
return result;
} catch (Exception e) {
LOGGER.info(e.getMessage());
result.put("message", "Error validate file");
return result;
}
}
//<editor-fold desc="Validate Methods" defaultstate="collapsed">
private String validatePhone(String str) {
String result = "";
String[] arr = str.split(";");
if (str.length() > 50) {
result = "Số điện thoại chính không được quá 50 kí tự;";
}
for (int i = 0; i < str.length(); i++) {
CustomerContact cc = customerContactRepository.findCustomerContactByContactTypeAndContactAndIsDirectLine((short)5, arr[i], (short)1);
if (cc != null) {
return result.concat("Số điện thoại chính đã tồn tại");
}
}
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) {
if (data.matches(regexp)) {
return header + " khong dung dinh dang";
}else return "";
}
StringBuilder sb = new StringBuilder();
private String validateLength(String header, String str, int length) {
if (str.trim().length() > length) {
return header + " khong duoc vuot qua " + length + " ki tu;";
}
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 String validateDynamicLength(String header, String str, Long min, Long max) {
if (str.trim().length() < min || str.trim().length() > max) {
return header + " khong duoc lon hon " + max + " hoac nho hon " + min;
}
return "";
}
private boolean validateEmail(String str) {
String regexp = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
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-----------");
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"));
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[]{"Có", "Không"});
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[]{"Thường", "VIP", "Blacklist"});
DataValidationConstraint isAllowConstraint = dataValidationHelper.createExplicitListConstraint(new String[]{"Có", "Không"});
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("IMPORT KHÁCH HÀNG");
Cell cell2 = row2.createCell(0);
cell2.setCellStyle(importantStyle);
cell2.setCellValue("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)");
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.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.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 +25,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 +169,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 +186,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("companySiteId") Long companySiteId,
@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);
}
// 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;
// UserSession userSession = (UserSession) RedisUtil.getInstance().get(authToken);
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file", HttpStatus.OK);
}
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(companySiteId);
Map<String, Object> map = customerService.readAndValidateCustomer(path, dynamicHeaders, companySiteId);
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 +229,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/
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
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