File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
2024-11-14
File name
Commit message
Commit date
File name
Commit message
Commit date
2025-07-21
package itn.let.mjo.test.web;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.UriUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import itn.com.cmm.ComDefaultCodeVO;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.cmm.service.EgovCmmUseService;
import itn.com.cmm.service.EgovFileMngService;
import itn.com.cmm.service.EgovFileMngUtil;
import itn.com.cmm.service.FileVO;
import itn.com.cmm.util.MJUtil;
import itn.com.cmm.util.StringUtil;
import itn.let.kakao.kakaoComm.KakaoVO;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiProfile;
import itn.let.kakao.kakaoComm.kakaoApi.KakaoApiProfileCategory;
import itn.let.lett.service.LetterService;
import itn.let.mail.service.StatusResponse;
import itn.let.mjo.addr.service.AddrGroupService;
import itn.let.mjo.addr.service.AddrService;
import itn.let.mjo.addragency.service.AddrAgencyVO;
import itn.let.mjo.apikey.service.ApiKeyMngService;
import itn.let.mjo.event.service.MjonEventService;
import itn.let.mjo.event.service.MjonEventVO;
import itn.let.mjo.mjocommon.MjonCommon;
import itn.let.mjo.mjocommon.MjonHolidayApi;
import itn.let.mjo.msg.service.MjonMsgService;
import itn.let.mjo.msg.service.MjonMsgVO;
import itn.let.mjo.msg.service.RefundDTO;
import itn.let.mjo.msgdata.service.MjonMsgDataService;
import itn.let.mjo.msgdata.service.MjonMsgReturnVO;
import itn.let.mjo.msgdata.service.impl.MjonMsgDataDAO;
import itn.let.mjo.msgholiday.service.MsgAlarmSetVO;
import itn.let.mjo.msgholiday.service.MsgHolidayService;
import itn.let.mjo.msgholiday.service.MsgHolidayVO;
import itn.let.mjo.pay.service.MjonPayService;
import itn.let.mjo.payva.service.VacsVactService;
import itn.let.mjo.payva.service.VacsVactVO;
import itn.let.mjo.spammsg.service.MjonSpamMsgService;
import itn.let.mjo.spammsg.web.ComGetSpamStringParser;
import itn.let.mjo.symbol.service.MjonSymbolService;
import itn.let.schdlr.service.SchdlrManageService;
import itn.let.sym.ccm.cde.service.EgovCcmCmmnDetailCodeManageService;
import itn.let.sym.grd.service.MberGrdService;
import itn.let.sym.site.service.EgovSiteManagerService;
import itn.let.sym.site.service.JoinSettingVO;
import itn.let.sym.site.service.TermsVO;
import itn.let.uat.uia.service.AuthCertVO;
import itn.let.uat.uia.web.KmcCertChecker;
import itn.let.uss.umt.service.EgovMberManageService;
import itn.let.uss.umt.service.EgovUserManageService;
import itn.let.uss.umt.service.MberManageVO;
import itn.let.uss.umt.service.UserManageVO;
import itn.let.utl.user.service.CheckFileUtil;
import itn.let.utl.user.service.CheckLoginUtil;
import itn.let.utl.user.service.CheckNoServiceCommon;
@Controller
public class TestController {
@Resource(name = "mjonMsgService")
private MjonMsgService mjonMsgService;
@Resource(name = "mjonPayService")
private MjonPayService mjonPayService;
@Resource(name = "MjonMsgDataService")
private MjonMsgDataService mjonMsgDataService;
@Resource(name = "LetterService")
private LetterService letterService;
@Resource(name = "mjonSymbolService")
private MjonSymbolService mjonSymbolService;
/** mberManageService */
@Resource(name = "mberManageService")
private EgovMberManageService mberManageService;
@Resource (name = "AddrService")
private AddrService addrService;
@Resource (name = "AddrGroupService")
private AddrGroupService addrGroupService;
/** EgovMessageSource */
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
@Resource(name="EgovFileMngUtil")
private EgovFileMngUtil fileUtil;
@Resource(name="EgovFileMngService")
private EgovFileMngService fileMngService;
@Resource(name = "SchdlrManageService")
private SchdlrManageService schdlrManageService;
@Resource(name = "egovMjonMsgGroupIdGnrService")
private EgovIdGnrService idgenMjonMsgGroupId;
@Resource(name = "egovMjonCashIdGnrService")
private EgovIdGnrService idgenMjonCashId;
@Resource(name = "CmmnDetailCodeManageService")
private EgovCcmCmmnDetailCodeManageService cmmnDetailCodeManageService;
/** 첨부파일 저장경로 */
@Value("#{globalSettings['Globals.file.saveDir']}")
private String fileSaveDir;
@Resource(name = "MjonEventService")
private MjonEventService mjonEventService;
@Resource(name = "mjonSpamMsgService")
private MjonSpamMsgService mjonSpamMsgService;
//로그인 처리
@Resource(name = "checkLoginUtil")
private CheckLoginUtil checkLoginUtil;
//첨부파일 체크
@Resource(name = "checkFileUtil")
private CheckFileUtil checkFileUtil;
//가상계좌원장
@Resource(name="vacsVactService")
private VacsVactService vacsVactService;
//파일 체크 & 관리
@Resource(name="EgovFileMngUtil")
private EgovFileMngUtil egovFileMngUtil;
@Resource(name = "EgovCmmUseService")
private EgovCmmUseService cmmUseService;
@Autowired
KakaoApiProfile kakaoApiProfile;
@Autowired
KakaoApiProfileCategory kakaoApiProfileCategory;
@Autowired
CheckNoServiceCommon checkNoServiceCommon;
@Autowired
MjonHolidayApi mjonHolidayApi;
@Resource(name = "egovSiteManagerService")
private EgovSiteManagerService egovSiteManagerService;
/** userManageService */
@Resource(name = "userManageService")
private EgovUserManageService userManageService;
//api key 정보
@Resource(name = "apiKeyMngService")
private ApiKeyMngService apiKeyMngService;
/*
//파일 정보 관리
@Resource(name="EgovFileMngService")
private EgovFileMngService fileMngService;
*/
/** 등급제 관리 서비스 */
@Resource(name = "mberGrdService")
MberGrdService mberGrdService;
/** 후불제 자동 충전 서비스 */
@Resource (name = "userManageService")
private EgovUserManageService egovUserManageService;
@Resource(name = "MsgHolidayService")
private MsgHolidayService msgHolidayService;
@Resource(name="MjonMsgDataDAO")
private MjonMsgDataDAO mjonMsgDataDAO;
@Autowired
private MjonCommon mjonCommon;
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
/////////////////////////////////////////////////////////////////////////////////////////
//
//
// USER
//
//
/////////////////////////////////////////////////////////////////////////////////////////
//
//
// ADMIN
//
//
/*@RequestMapping(value= {"/web/mjon/test/selectSendTestView.do"})
public String selectSendTestView(ModelMap model) throws Exception {
// 결제방식 코드조회
ComDefaultCodeVO vo = new ComDefaultCodeVO();
vo.setCodeId("BIZ01");
List<?> bizList= cmmUseService.selectCmmCodeDetail(vo);
model.addAttribute("bizList", bizList);
return "/uss/ion/test/TestSandKakao";
}*/
/*@RequestMapping(value= {"/web/mjon/test/kakaoApiProfileTokenSendAjax.do"})
public ModelAndView kakaoApiProfileTokenSendAjax(KakaoVO kakaoVO
, ModelAndView modelAndView
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
try {
KakaoVO kakaoInfo = new KakaoVO();
String tempUrl = kakaoVO.getBizUrl();
if(!tempUrl.equals("") && tempUrl != null) {
if(tempUrl.contains("profile/category/all")) {
//발신프로필 카테고리 전체 내역 조회하기
kakaoApiProfileCategory.kakaoApiProfileCategoryAll(kakaoVO);
}else if(tempUrl.contains("profile/category")) {
//발신프로필 카테고리 코드 정보 조회하기
kakaoApiProfileCategory.kakaoApiProfileCategoryCode(kakaoVO);
}else if(tempUrl.contains("profile/token")) {
//발신프로필 인증 토큰 요처하기
kakaoInfo = kakaoApiProfile.kakaoApiProfileToken(kakaoVO);
}
}else{//요청 정보가 없으면 오류 반환
modelAndView.addObject("message", "요청 URL이 없습니다.");
modelAndView.addObject("result", "fail");
return modelAndView;
}
modelAndView.addObject("kakaoInfo", kakaoInfo);
modelAndView.addObject("result", "success");
}catch(Exception ex){
ex.printStackTrace();
modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
modelAndView.addObject("result", "fail");
return modelAndView;
}
return modelAndView;
}*/
@RequestMapping(value= {"/web/mjon/test/insertJsonTestAjax.do"})
public ModelAndView insertJsonTestAjax(KakaoVO kakaoVO
, ModelAndView modelAndView
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
try {
// kakaoService.kakaoBizJson(kakaoVO);
modelAndView.addObject("result", "success");
}catch(Exception ex){
ex.printStackTrace();
modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
modelAndView.addObject("result", "fail");
}
return modelAndView;
}
/**
* egov sample list 페이지
* @param addrVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value= {"/uss/ion/test/selectTestList.do"})
public String selectTestList(
HttpServletRequest request
, @ModelAttribute("searchVO") VacsVactVO vacsVactVO
, ModelMap model
, RedirectAttributes redirectAttributes
) throws Exception {
//관리자 로그인 여부 체크
String isLogin = checkLoginUtil.isAdminLogin4PageMove(redirectAttributes);
if (!"Y".equals(isLogin)) return isLogin;
//로그인 정보 획득
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
//login 정보
model.addAttribute("loginVO", loginVO);
//ajax를 위한 현재 URL 정보 받기
vacsVactVO.setUrl(request.getRequestURI());
return "/uss/ion/test/TestList";
}
/**
* 주소록 입력 대행(무료) 관리 리스트 ajax 부분
* @param addrVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value= {
"/uss/ion/test/selectTestListAjax.do"
})
public String selectTestListAjax(
HttpServletRequest request
, @ModelAttribute("searchVO") VacsVactVO vacsVactVO
, ModelMap model
, RedirectAttributes redirectAttributes
) throws Exception {
System.out.println("1111111111111");
System.out.println("selectTestListAjax");
System.out.println(vacsVactVO.toString());
//return "/uss/ion/payva/VirtualAccountListAjax";
//관리자 로그인 여부 체크
String isLogin = checkLoginUtil.isLoginCheck4JsonPage(redirectAttributes);
if ("N".equals(isLogin)) return "/uss/ion/test/TestListAjax";
// pageing step1
PaginationInfo paginationInfo = this.setPagingStep1(vacsVactVO);
// pageing step2
vacsVactVO = this.setPagingStep2(vacsVactVO, paginationInfo);
//대상 리스트 가져오기
//관리자 리스트는 30일 마감에 대한 제한을 없애기 위해서 해당 값을 넣어준다.
List<VacsVactVO> vacsVactList = vacsVactService.selectList(vacsVactVO);
// pageing step3
paginationInfo = this.setPagingStep3(vacsVactList, paginationInfo);
//대상 리스트, 페이징 정보 전달
model.addAttribute("resultList", vacsVactList);
model.addAttribute("paginationInfo", paginationInfo);
return "/uss/ion/test/TestListAjax";
}
/**
* egov ec:code sample 페이지
* @param addrVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value= {
"/uss/ion/test/selectTestEcList.do"
})
public String selectTestEcList(
) throws Exception {
return "/uss/ion/test/TestEcList";
}
/**
* egov file 업로드시 사용자 제약 관리 페이지
* @param addrVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value= {
"/uss/ion/test/selectTestFileList.do"
})
public String selectTestFileList(
) throws Exception {
return "/uss/ion/test/TestFileList";
}
/**
*egov file 업로드시 사용자 제약 관리 페이지
*
* @param boardVO
* @param board
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value=
{
"/uss/ion/test/insertTestFileAjax.do"
}
)
public ModelAndView insertTestFileList(
HttpServletRequest request
, final MultipartHttpServletRequest multiRequest
//, ModelMap model
, ModelAndView modelAndView
, RedirectAttributes redirectAttributes
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
//사용자 로그인 여부 체크 for json
String isLogin = checkLoginUtil.isLoginCheck4JsonAction(modelAndView);
if ("N".equals(isLogin)) return modelAndView;
//파일 정상 처리 여부와 첨부 파일 정보 - DB 저장 없이 업로드 파일명받기어서 배열로 처리
//DB 저장인 경우는 대표 파일 ID를 받으므로 하나의 ID만 넘겨 받는다.(file저장은 master-defail 구조)
String[] atchFileIds = this.readFiles(multiRequest, modelAndView, "txt|xls|xlsx|png|jpg", 10, 3); //MB size and ea
//String atchFileId = this.readFile(multiRequest, modelAndView, "txt|xls|xlsx", 10, 1); //size and ea
for(int i=0;i<atchFileIds.length;i++) {
System.out.println(atchFileIds[i]);
}
if ("ERROR".equals(atchFileIds[0])) return modelAndView;
System.out.println("success");
return modelAndView;
}
/**
* egov file 업로드시 사용자 제약 관리 페이지
* @param addrVO
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value= {
"/uss/ion/test/selectTestValidatorList.do"
})
public String selectTestValidatorList(
RedirectAttributes redirectAttributes
, ModelMap model
) throws Exception {
//사용자 로그인 여부 체크 - 페이지 이동
/*
String isLogin = checkLoginUtil.isUserLogin4PageMove(redirectAttributes);
if (!"Y".equals(isLogin)) return isLogin;
*/
//json 로그인 여부 체크 - action 처리
/*
String isLogin = checkLoginUtil.isLoginCheck4JsonAction(modelAndView);
if ("N".equals(isLogin)) return modelAndView;
*/
//json 로그인 여부 체크 - 페이지 생성
/*
String isLogin = checkLoginUtil.isLoginCheck4JsonPage(redirectAttributes);
if ("N".equals(isLogin)) return "/uss/ion/addragency/AddrAgencyListAjax";
*/
//관리자 로그인 여부 체크 - 페이지 이동
String isLogin = checkLoginUtil.isAdminLogin4PageMove(redirectAttributes);
if (!"Y".equals(isLogin)) return isLogin;
//login 정보 전달
LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
model.addAttribute("loginVO", loginVO);
return "/uss/ion/test/TestValidatorList";
}
/**
*egov file 업로드시 사용자 제약 관리 페이지
*
* @param boardVO
* @param board
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value=
{
"/uss/ion/test/insertTestValidatorAjax.do"
}
)
public ModelAndView insertTestValidatorList(
@ModelAttribute("searchVO") AddrAgencyVO addrAgencyVO
//, ModelMap model
, ModelAndView modelAndView
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
//json 로그인 여부 체크 - action 처리
String isLogin = checkLoginUtil.isLoginCheck4JsonAction(modelAndView);
if ("N".equals(isLogin)) return modelAndView;
//action
try {
System.out.println(addrAgencyVO.toString());
modelAndView.addObject("message", egovMessageSource.getMessage("success.common.update"));
modelAndView.addObject("result", "success");
}catch(Exception ex){
ex.printStackTrace();
modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
modelAndView.addObject("result", "fail");
}
return modelAndView;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// private function
//
//
//사용자 업로드 파일 처리 - 하나의 파일만 처리
private String[] readFiles(
MultipartHttpServletRequest p_multiRequest
, ModelAndView p_modelAndView
, String p_exts //가능한 확장자를 받는다. |
, int p_i_file_size //가능한 파일 용량 MB 단위
, int p_i_file_count //가능한 파일 수량
//, BoardMasterVO p_bmVO
) throws Exception{
String[] p_atchFileId = new String[p_i_file_count];
boolean in_bool = true;
List<FileVO> result = null;
String atchFileId = "";
String isThumbFile = "";
//String isThumbFile = "thumbFile"; //"thumbFile" - 썸네일을 생성한다.
final Map<String, MultipartFile> files = p_multiRequest.getFileMap();
if (!files.isEmpty()) {
System.out.println("isnotempty");
result = egovFileMngUtil.parseFileInf(files, "ADDRAGENCY_", 0, "", "", isThumbFile);
//관리자에서 게시판 설정시 업로드 파일 사이즈와 수량 체크용
//사용자 설정용 업로드 파일 사이즈 & 파일 수량 & 확장자 체크용
if(!checkFileUtil.isPosblAtchFileMvWithUserSetting(result, p_modelAndView, 0, p_exts, p_i_file_size, p_i_file_count)) {
// 공통코드 Set
//setBBSCommCd(model, bmVO);
//model.addAttribute("bdMstr", bmVO);
//return "web/cop/bbs/EgovNoticeRegist";
//modelAndView.addObject("bdMstr", bmVO);
p_modelAndView.addObject("result", "fail");
in_bool = false;
}else {
//atchFileId = fileMngService.insertFileInfs(result); //첨부 파일
for(int i=0;i<result.size();i++) {
FileVO vo = (FileVO) result.get(i);
p_atchFileId[i] = vo.fileStreCours + vo.streFileNm; //첨부 파일
}
}
//atchFileId = atchFileId + "|" + fileMngService.insertFileInfs(result); //첨부 파일
}else {
System.out.println("isempty");
}
if (!in_bool) p_atchFileId[0] = "ERROR";
return p_atchFileId;
}
//페이징을 위한 처리 step1 - 페이징 기본 정보 설정
private PaginationInfo setPagingStep1(VacsVactVO p_vacsVactVO)throws Exception{
// pageing step1
PaginationInfo paginationInfo = new PaginationInfo();
paginationInfo.setCurrentPageNo(p_vacsVactVO.getPageIndex());
paginationInfo.setRecordCountPerPage(p_vacsVactVO.getPageUnit());
paginationInfo.setPageSize(p_vacsVactVO.getPageSize());
return paginationInfo;
}
//페이징을 위한 처리 step2 - 게시물 리스트 수량 설정 및 검색 조건 초기화
private VacsVactVO setPagingStep2(
VacsVactVO p_vacsVactVO
, PaginationInfo p_paginationInfo
)throws Exception{
// pageing step2
p_vacsVactVO.setFirstIndex(p_paginationInfo.getFirstRecordIndex());
p_vacsVactVO.setLastIndex(p_paginationInfo.getLastRecordIndex());
p_vacsVactVO.setRecordCountPerPage(p_paginationInfo.getRecordCountPerPage());
if("".equals(p_vacsVactVO.getSearchSortCnd())){ //최초조회시 최신것 조회List
p_vacsVactVO.setSearchSortCnd("REG_IL");
p_vacsVactVO.setSearchSortOrd("desc");
}
return p_vacsVactVO;
}
//페이징을 위한 처리 step3 - 전체 게시물 수량 설정하기
private PaginationInfo setPagingStep3(
List<VacsVactVO> p_vacsVactList
, PaginationInfo p_paginationInfo
)throws Exception{
// pageing step3
int totCnt = 0;
if(p_vacsVactList.size() > 0) totCnt = p_vacsVactList.get(0).getTotCnt();
p_paginationInfo.setTotalRecordCount(totCnt);
return p_paginationInfo;
}
/*
@RequestMapping(value= {"/web/mjon/test/checkBizNoTestAjax.do"})
public ModelAndView checkBizNoTestAjax(KakaoVO kakaoVO
, HttpServletRequest request
, ModelAndView modelAndView
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
System.out.println("bizId " );
System.out.println("Kakao " );
//System.out.println(request.getParameter("b_no") );
try {
//String s_b_no = request.getParameter("b_no");
String s_b_no = request.getParameter("b_no").replaceAll("-", ""); //사업자등록번호
String s_b_nm = request.getParameter("b_nm"); //업체명
String s_p_nm = request.getParameter("p_nm"); //대표자명
//KakaoVO kakaoInfo = checkNoServiceCommon.BizNoCheckApi(kakaoVO);
KakaoVO kakaoInfo = checkNoServiceCommon.BizNoCheckApiEx2(
kakaoVO
, s_b_no
, s_b_nm
, s_p_nm
);
modelAndView.addObject("kakaoInfo", kakaoInfo);
modelAndView.addObject("result", kakaoInfo.getBizReturnCode());
}catch(Exception ex){
ex.printStackTrace();
modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
modelAndView.addObject("result", "fail");
}
return modelAndView;
}
*/
/*
@RequestMapping(value= {"/uss/umt/user/checkBizNoTaxAjax.do"})
public ModelAndView checkBizNoTaxAjax(KakaoVO kakaoVO
, HttpServletRequest request
, ModelAndView modelAndView
) throws Exception {
//json 알림
modelAndView.setViewName("jsonView");
System.out.println("bizId " );
System.out.println("Kakao " );
//System.out.println(request.getParameter("b_no") );
try {
//String s_b_no = request.getParameter("b_no");
String s_b_no = request.getParameter("b_no").replaceAll("-", ""); //사업자등록번호
String s_b_nm = request.getParameter("b_nm"); //업체명
String s_p_nm = request.getParameter("p_nm"); //대표자명
String s_start_dt = request.getParameter("start_dt").replaceAll("-", ""); //설립일자
System.out.println("s_start_dt");
System.out.println(s_start_dt);
System.out.println(s_start_dt);
//KakaoVO kakaoInfo = checkNoServiceCommon.BizNoCheckApi(kakaoVO);
KakaoVO kakaoInfo = checkNoServiceCommon.BizNoCheckApiEx3(
kakaoVO
, s_b_no
, s_b_nm
, s_p_nm
, s_start_dt
);
modelAndView.addObject("msg", kakaoInfo.getBizReturnMsg());
modelAndView.addObject("result", kakaoInfo.getBizReturnCode());
}catch(Exception ex){
ex.printStackTrace();
modelAndView.addObject("message", egovMessageSource.getMessage("fail.common.update"));
modelAndView.addObject("result", "fail");
}
return modelAndView;
}
*/
// 회원가입 2뎁스 - 약관 동의
@RequestMapping(value = "/web/user/login/test_checkTerms.do")
public String checkTerms(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes,
@ModelAttribute("mberManageVO") MberManageVO mberManageVO, TermsVO termsVO, ModelMap model)
throws Exception {
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
if (isAuthenticated)
return "redirect:/";
//URL을 이용한 비정상적인 접근 차단
/*
if("".equals(mberManageVO.getDept()) || mberManageVO.getDept() == null) {
redirectAttributes.addFlashAttribute("message", "잘못된 경로로 접속하여 메인화면으로 이동됩니다");
return "redirect:/web/main/mainPage.do";
}
*/
// 본인인증 방식 선택 정보 불러오기
JoinSettingVO joinSettingVO = egovSiteManagerService.selectJoinCertTypeDetail();
model.addAttribute("joinSettingVO", joinSettingVO);
// 약관 사용메뉴 - 01:회원가입
termsVO.setMenuNm("01");
List<TermsVO> termsList = new ArrayList<TermsVO>();
termsList = egovSiteManagerService.selectTermsMenu(termsVO);
model.addAttribute("termsList", termsList);
// 나이스 본인인증
/*
* String referer = (String) request.getHeader("REFERER");
*
* URL newURL = new URL(referer);
*
* String protocol = newURL.getProtocol() + "://"; String host =
* newURL.getHost();
*
* String succUrl = protocol + host + "/web/user/login/niceCheckAjax.do"; // 성공시
* 이동할 URL - String failUrl = protocol + host +
* "/web/user/login/selectUserDept.do";
*
* mberManageVO.setNiceSuccUrl(succUrl); mberManageVO.setNiceFailUrl(failUrl);
*/
model.addAttribute("mberManageVO", mberManageVO);
// KMC 본인인증 데이터 불러오기
// 핸드폰인증만 사용할 시
if (joinSettingVO.getJoinCertType().equals("M")) {
KmcCertChecker kmcCertCheck = new KmcCertChecker();
// kmc 본인인증 실/개발 서버 구분
String serverNm = "";
if (request.getServerName().contains("219.240.88.15") || request.getServerName().contains("localhost")) {
serverNm = request.getScheme() + "://219.240.88.15:8095";
}else if(request.getRequestURL().toString().contains("www.")){
serverNm = request.getScheme() + "://www.munjaon.co.kr";
}
else {
serverNm = request.getScheme() + "://munjaon.co.kr";
}
// AuthCertVO certVO = kmcCertCheck.authCertCheck(serverNm + "/web/cop/kmc/authRequestAjax.do");
// model.addAttribute("tr_cert", certVO.getTr_cert());
// model.addAttribute("tr_url", certVO.getTr_url());
// model.addAttribute("tr_add", certVO.getTr_add());
}
return "web/login/test_usrCheckTerms";
}
// 회원가입 3뎁스 - 정보입력
@RequestMapping(value = "/web/user/login/test_insertUsrView.do")
public String insertUsrView(HttpServletRequest request, HttpServletResponse response,
@ModelAttribute("mberManageVO") MberManageVO mberManageVO, TermsVO termsVO, ModelMap model,
HttpSession session, JoinSettingVO joinSettingVO, RedirectAttributes redirectAttributes) throws Exception {
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
if (isAuthenticated)
return "redirect:/cmm/main/mainPage.do";
//URL을 이용한 비정상적인 접근 차단
if("".equals(mberManageVO.getDept()) || mberManageVO.getDept() == null || "".equals(mberManageVO.getMblDn()) || mberManageVO.getMblDn() == null) {
redirectAttributes.addFlashAttribute("message", "잘못된 경로로 접속하여 메인화면으로 이동됩니다");
return "redirect:/web/main/mainPage.do";
}
System.out.println("++++++++++++ 세션체크 ::: " + (MberManageVO) session.getAttribute("mberSession"));
if (null == session.getAttribute("mberSession")) { // 세션이 없을 시 메인화면으로 팅김
redirectAttributes.addFlashAttribute("message", "쿠키 설정을 확인하세요.");
return "redirect:/";
}
// 이메일 코드조회
ComDefaultCodeVO voComCode = new ComDefaultCodeVO();
voComCode.setCodeId("ITN031");
model.addAttribute("emailCode", cmmUseService.selectCmmCodeDetail(voComCode));
// 방문경로 코드조회
voComCode.setCodeId("ITN025");
model.addAttribute("visitRoute", cmmUseService.selectCmmCodeDetail(voComCode));
// 기업유형 코드조회
voComCode.setCodeId("ITN033");
model.addAttribute("bizTypeCode", cmmUseService.selectCmmCodeDetail(voComCode));
// 본인인증 방식 선택 정보 불러오기
JoinSettingVO joinCertType = egovSiteManagerService.selectJoinCertTypeDetail();
String joinType = joinCertType.getJoinCertType();
model.addAttribute("joinType", joinType);
// 본인인증
// 회원타입(개인,기업) 담아둔 세션 조회
session = request.getSession();
MberManageVO mberSessionVO = (MberManageVO) session.getAttribute("mberSession");
if (joinType.equals("M") || joinType.equals("A")) {
// 크롬 SameSite정책 방지 - 도메인이 다른 타사로 이동 시 크롬 정책에 의해 세션 유실이 일어나는 경우가 있는데, 이를 방지하기 위해
// samesite 보안을 none처리
/*
* response.setHeader("Set-Cookie",
* "AuthKmcCertVO=AuthKmcCertVO; Secure; SameSite=None"); //KMC 문자 본인인증 세션 정보
* 받아오기 AuthCertVO certKmcVO = (AuthCertVO)
* session.getAttribute("AuthKmcCertVO");
*
* if(certKmcVO != null) {
*
* mberManageVO.setNiceNm(certKmcVO.getCertName()); //본인인증 이름
* mberManageVO.setMoblphonNo(certKmcVO.getCertPhone()); //본인인증 핸드폰
* mberManageVO.setMblDn(certKmcVO.getCertDi()); //본인인증 중복가입방지 번호
* mberManageVO.setNationality(certKmcVO.getCertNation());
* mberManageVO.setBirthDay(certKmcVO.getBirthDay());
* mberManageVO.setSexdstnCode(certKmcVO.getSexdstnCode());
*
* }
*/
} else {
// ARS 전화 본인인증 세션 정보 받아오기
AuthCertVO certArsVO = (AuthCertVO) session.getAttribute("AuthARSCertVO");
if (certArsVO != null) {
mberManageVO.setMoblphonNo(certArsVO.getCertPhone()); // 본인인증 핸드폰
}
}
model.addAttribute("mberSessionVO", mberSessionVO);
// 나이스 본인인증을 했을때 세션처리 후 데이터 저장해주기.
/*
* MberManageVO VO = new MberManageVO(); if (null !=
* request.getSession().getAttribute("userSearchVO")) { // 세션체크 VO =
* ((MberManageVO) request.getSession().getAttribute("userSearchVO"));
* mberManageVO.setNiceNm(VO.getNiceNm()); // 이름
* mberManageVO.setSexdstnCode(VO.getSexdstnCode()); // 성별
* mberManageVO.setMoblphonNo(VO.getMoblphonNo()); // 핸드폰번호
* mberManageVO.setBirthDay(VO.getBirthDay()); // 생년월일
* mberManageVO.setMblDn(VO.getMblDn()); // 모바일 인증키
* session.removeAttribute("userSearchVO"); }
*/
model.addAttribute("mberManageVO", mberManageVO);
return "web/login/test_usrInsertView";
}
@RequestMapping(value= {"/web/user/login/apiRequestTest.do"})
public ResponseEntity<StatusResponse> faxApiTest() throws Exception{
try {
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.OK, "요청 성공!!!", LocalDateTime.now()));
// return ResponseEntity.ok().body(new StatusResponse(HttpStatus.BAD_REQUEST, "임시 성공.", LocalDateTime.now()));
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.BAD_REQUEST, "발송 요청 중 오류가 발생하였습니다.", LocalDateTime.now()));
}
@RequestMapping(value= {"/web/user/login/returnTest.do"})
public ModelAndView returnTest(@RequestBody MjonMsgVO mjonMsgVO,
// public ResponseEntity<StatusResponse> returnTest(@RequestBody MjonMsgVO mjonMsgVO,
RedirectAttributes redirectAttributes,
HttpServletRequest request,
ModelMap model) throws Exception{
ModelAndView modelAndView = new ModelAndView("jsonView");
System.out.println("mjonMsgVO.getSmsTxt() : "+ mjonMsgVO.getSmsTxt());
// return ResponseEntity.ok().body(new StatusResponse(HttpStatus.BAD_REQUEST, "발송 요청 중 오류가 발생하였습니다.", LocalDateTime.now()));
modelAndView.addObject("result", "OK");
modelAndView.addObject("message", "요청 성공!");
return modelAndView;
}
// ========================================================================================================
@RequestMapping(value= {"/web/user/login/selectSpamTxtChkAjax.do"})
public ModelAndView selectSpamTxtChkAjax(@RequestBody MjonMsgVO mjonMsgVO) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("jsonView");
try {
//회원 정보 중 금지어 예외 항목에 대해서 스팸 필터링 처리 유무 적용 - 20240820 우영두
MberManageVO mberManageVO = new MberManageVO();
//회원정보 불러오기
mberManageVO = mberManageService.selectMber(mjonMsgVO.getMberId());
//스팸 필터링 예외처리 여부 값 - (온: Y, 오프 : N) 온 일때 스미싱의심 예외 되도록 적용
String exceptSpamYn = mberManageVO.getExceptSpamYn();
if(exceptSpamYn.equals("Y")) {//스팸 필터링 예외 온 일 경우 리턴 처리
modelAndView.addObject("result", "clear");
return modelAndView;
}
List<String> resultSpamTxt = mjonMsgDataService.selectSpamKeywordList();
String spmFilterTxt = "";
if(resultSpamTxt == null) {//스팸 체크리스트가 없는 경우
modelAndView.addObject("result", "listEmpty");
return modelAndView;
}else {
String smsTxt = mjonMsgVO.getSmsTxt(); //발송 문자 내용
/*
* 치환문자에 스팸문구가 있을수 있어서 첫번째 치환데이터만 변환 적용 해서 스팸문구가 있는지 체크하도록 함.
* 차후에 전체 치환 데이터에 대한 체크를 할지를 검토하겠음.
*
* */
String txtReplYn = mjonMsgVO.getTxtReplYn();
if(txtReplYn.equals("Y")) {
String[] nameList = mjonMsgVO.getNameList(); //치환 이름 리스트
String[] rep1 = mjonMsgVO.getRep1List(); //치환 문자1 리스트
String[] rep2 = mjonMsgVO.getRep2List(); //치환 문자2 리스트
String[] rep3 = mjonMsgVO.getRep3List(); //치환 문자3 리스트
String[] rep4 = mjonMsgVO.getRep4List(); //치환 문자4 리스트
//이름, 휴대폰, 치환문자 데이터가 없으면 취소 처리
if((nameList.length == 0 || nameList == null)
&& (rep1.length == 0 || rep1 == null)
&& (rep2.length == 0 || rep2 == null)
&& (rep3.length == 0 || rep3 == null)
&& (rep4.length == 0 || rep4 == null)) {
//modelAndView.addObject("message", "특정문구 일괄변환 치환문자 데이터가 없습니다.");
//modelAndView.addObject("result", "fail");
return modelAndView;
}
if (smsTxt.indexOf("[*이름*]") > -1) {
smsTxt = smsTxt.replaceAll("\\[\\*이름\\*\\]", StringUtil.getString(nameList[0].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*이름\\*\\]", "");
}
if (smsTxt.indexOf("[*1*]") > -1) {
smsTxt = smsTxt.replaceAll("\\[\\*1\\*\\]", StringUtil.getString(rep1[0].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*1\\*\\]", "");
}
if (smsTxt.indexOf("[*2*]") > -1) {
smsTxt = smsTxt.replaceAll("\\[\\*2\\*\\]", StringUtil.getString(rep2[0].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*2\\*\\]", "");
}
if (smsTxt.indexOf("[*3*]") > -1) {
smsTxt = smsTxt.replaceAll("\\[\\*3\\*\\]", StringUtil.getString(rep3[0].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*3\\*\\]", "");
}
if (smsTxt.indexOf("[*4*]") > -1) {
smsTxt = smsTxt.replaceAll("\\[\\*4\\*\\]", StringUtil.getString(rep4[0].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*4\\*\\]", "");
}
}
//입력 문장에 대해서 우회 문장 또는 특수 기호 입력 제거 등 문장 재구성 처리, 한글 자모음 분리 및 재조함도 함께 처리함.
String resultParser = ComGetSpamStringParser.getSpamTextParse(smsTxt).trim();
//List<String> jasoList = HangulParser.disassemble(resultParser);
//String assembleStr = HangulParser.assemble(jasoList);
System.out.println("++++++++++++++ spam resultParser ::: "+resultParser);
/*
//형태소 분석기 처리
KomoranUtils komoran = new KomoranUtils();
String resultKomoran = komoran.parseKomoranTextByString(assembleStr);*/
//System.out.println(resultKomoran);
//한글, 영문, 숫자, 띄어쓰기를 제외한 다른 단어들을 삭제함.
//String repSmsTxt = smsTxt.replaceAll("[^ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9 ]", "");
//데이터베이스에 등록된 스팸문구와 일치하는 단어/문구가 있는지 체크함.
int spmCnt = 0;
for(String spmTxt : resultSpamTxt) {
String parserStr = ComGetSpamStringParser.getSpamTextParse(spmTxt).trim();
if(resultParser.contains(parserStr)) {
//스팸 단어/문구가 있으면 콤마로 연결시킨 후 리턴해줌.
spmFilterTxt += spmTxt + ",";
spmCnt++;
}
}
if(spmCnt > 0) {//스팸문자가 포함되어 있으면 문자열 끝 , 단어 삭제 처리
if (StringUtil.getWordRight(spmFilterTxt.trim(), 1).equals(",")) {
// 처음부터 idx 만큼 잘라낸 나머지 글자
spmFilterTxt = StringUtil.getWordLeft(spmFilterTxt.trim(), 1);
}
System.out.println("++++++++++++++ spmFilterTxt ::: "+spmFilterTxt);
modelAndView.addObject("result", "spams");
// modelAndView.addObject("spmFilterTxt", spmFilterTxt);
return modelAndView;
}
}
}catch(Exception e) {
logger.error(e.getMessage(), e);
modelAndView.addObject("result", "fail");
modelAndView.addObject("message", "기타 시스템 오류 : " + e.getMessage());
return modelAndView;
}
// modelAndView.addObject("message", "test ");
return modelAndView;
}
@RequestMapping(value= {"/web/user/login/sendMsgDataAjax.do"})
public ModelAndView sendMsgData(@RequestBody MjonMsgVO mjonMsgVO,
RedirectAttributes redirectAttributes,
HttpServletRequest request,
ModelMap model) throws Exception{
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("jsonView");
String resultSts = "0";
String resultBlockSts = "0";
String userId = "";
try {
// LoginVO loginVO = EgovUserDetailsHelper.isAuthenticated()? (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser():null;
// userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
userId = mjonMsgVO.getMberId();
if(userId.equals("")) {
modelAndView.addObject("message", "로그인 후 이용이 가능합니다.");
modelAndView.addObject("result", "loginFail");
modelAndView.addObject("resultSts", resultSts);
return modelAndView;
}else {
mjonMsgVO.setUserId(userId);
/**
* 회원 정지된 상태이면 문자 발송이 안되도록 처리함
* 현재 로그인 세션도 만료 처리함
* */
boolean mberSttus = userManageService.selectUserStatusInfo(userId);
if(!mberSttus) {
modelAndView.addObject("message", "현재 고객님께서는 문자온 서비스 이용이 정지된 상태로 문자를 발송하실 수 없습니다. 이용정지 해제를 원하시면 고객센터로 연락주시기 바랍니다.");
modelAndView.addObject("result", "statusFail");
modelAndView.addObject("resultSts", resultSts);
request.getSession().invalidate();
return modelAndView;
}
}
//회원정보에서 스미싱 회원 여부 정보 조회
UserManageVO userManageVO = new UserManageVO();
userManageVO.setMberId(userId);
UserManageVO resultUserVO = userManageService.selectSmishingYnUserInfo(userManageVO);
String smishingYn = resultUserVO.getSmishingYn();
mjonMsgVO.setSmishingYn(smishingYn);
//문자열 길이 체크 해주기
String charset = "euc-kr"; //문자 바이트 계산에 필요한 캐릭터 셋 : 한글 2Byte로 계산
String smsCont = mjonMsgVO.getSmsTxt().replace("\r\n", "\n");
int FrBytes = smsCont.getBytes(charset).length;
if(FrBytes > 2000) {
modelAndView.addObject("message", "문자 내용은 2000Byte를 넘을 수 없습니다.");
modelAndView.addObject("result", "smsLengFail");
return modelAndView;
}
System.out.println("mjonMsgVO.getMsgType1() ::: "+mjonMsgVO.getMsgType());
String msgType = mjonMsgVO.getMsgType();
//내문자저장함에 저장후 문자를 발송하는경우 문자 타입이 숫자가 아닌 문자로 넘어와서 변경 처리함- 20220520 우영두
if(msgType.equals("P") || msgType.equals("L")) {
msgType = "6";
}else if(msgType.equals("S")) {
msgType = "4";
}
//메세지 타입이 단문이면 진짜 단문인지 한번더 확인해 준다.
if(msgType.equals("4")) {
//메세지 길이가 90Byte를초과 하거나, 그림 이미지가 있는경우 메세지 타입을 6으로 변경해준다.
if(FrBytes > 90 || mjonMsgVO.getImgFilePath().length > 0) {
msgType = "6";
}
}
mjonMsgVO.setMsgType(msgType);
//장문 메세지일 경우
int fileCount = 0;
if(msgType.equals("6")) {
//그림 이미지가 첨부된 경우
if(mjonMsgVO.getImgFilePath() != null || mjonMsgVO.getImgFilePath().length > 0) {
String[] path = mjonMsgVO.getImgFilePath();
String[] fileId = mjonMsgVO.getImgFileId();
String[] templateYn = mjonMsgVO.getTemplateYn();
for(int i=0; i<path.length; i++) {
if("Y".equals(templateYn[i])) {
//템플릿 사용누계 증가
letterService.updateTemplateUseCount(fileId[i]);
}
String atchFileId = fileId[i];
String imgFilePath = mjonMsgService.selectPhotoImgFileRealPath(atchFileId);
// 아이하트, 현대퓨쳐넷 두 중계사는 이미지 경로는 풀패스 경로로 넘겨주면 됨
if(i == 0) {
mjonMsgVO.setFileName1(imgFilePath);
}else if(i == 1) {
mjonMsgVO.setFileName2(imgFilePath);
}else {
mjonMsgVO.setFileName3(imgFilePath);
}
fileCount ++;
}
//첨부파일 갯수 셋팅해주기
mjonMsgVO.setFileCnt(Integer.toString(fileCount));
}
}
//파일 갯수는 있는데 파일 경로가 없는 경우 문자발송이 안되도록 튕겨내도록 함 - 20220520 우영두
if(fileCount > 0) {
if(mjonMsgVO.getFileName1() == null && mjonMsgVO.getFileName2() == null && mjonMsgVO.getFileName3() == null) {
modelAndView.addObject("message", "문자 메세지 이미지 추가에 오류가 발생하여 문자 발송이 취소 되었습니다.");
modelAndView.addObject("result", "imgSourceFail");
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
/*
* 화면에서 넘어오는 단가 금액 및 총 결제 캐시 금액 체크 해주기
* 검증을 위해서 시스템 단가, 회원 협의 단가, 이벤트 단가 정보 조회
* 조회 단가를 이용하여 총 결제 캐시 금액 계산
* 파라미터로 넘어온 개별단가(eachPrice), 총 결제캐시(totPrice)를 비요하여 동일하지 않으면 컨트롤러에서 계산한 금액으로 입력해줌.
*/
MjonEventVO mjonEventVO = new MjonEventVO();
mjonEventVO.setMberId(userId);
MjonEventVO eventMberInfo = mjonEventService.selectEventMsgMberDefaultInfo(mjonEventVO);
//1.시스템 기본 단가 정보 불러오기
JoinSettingVO sysJoinSetVO = mjonMsgDataService.selectJoinSettingInfo();
// 등급제 단가 추출 => 시스템 단가에 적용
sysJoinSetVO = mberGrdService.selectMberGrdDefaultInfo(sysJoinSetVO, userId);
//2.사용자 개인 단가 정보 불러오기
MberManageVO mberManageVO = new MberManageVO();
mberManageVO = mjonMsgDataService.selectMberManageInfo(userId);
//3.사용자 개인단가 정보가 0이 아니면 개인단가 사용, 없으면 시스템 기본 단가 사용
Float shortPrice = mberManageVO.getShortPrice();
Float longPrice = mberManageVO.getLongPrice();
Float picturePrice = mberManageVO.getPicturePrice();
Float picture2Price = mberManageVO.getPicture2Price();
Float picture3Price = mberManageVO.getPicture3Price();
//기존 소수점 2째자리에서 반올림하였으나, 정책 변경으로 소수점 버림 처리함 20220623
boolean compareEndDate = false;
float eventRemainCash = 0;
float paramEachPrice = Float.parseFloat(mjonMsgVO.getEachPrice());
if(eventMberInfo != null) {
String eventEndDate = eventMberInfo.getEventEndDate();
if(eventEndDate != null) {
compareEndDate = MJUtil.getCompareDate(eventEndDate);
eventRemainCash = (float) eventMberInfo.getEventRemainCash();
//이벤트 금액 및 기간 체크
if(!compareEndDate || eventRemainCash < paramEachPrice) {
if(!eventMberInfo.getEventStatus().equals("E")) {
//이벤트 상태값을 종료로 변경한다.
mjonEventVO.setEventInfoId(eventMberInfo.getEventInfoId());
mjonEventVO.setEventStatus("E");
mjonEventVO.setEventMemo("발송 최소 금액("+ paramEachPrice +") 부족 혹은 이벤트 종료일 초과되어 이벤트 종료 시킴");
mjonEventVO.setEventRemainCash(eventRemainCash);
mjonEventService.updateEventEndStatus(mjonEventVO);
eventMberInfo.setEventStatus("E");
}
}
}
}
//이벤트 진행 회원의 발송 단가 처리해주기
if(eventMberInfo != null && eventMberInfo.getEventStatus().equals("Y") && compareEndDate) {
shortPrice = Float.parseFloat(eventMberInfo.getEventShortPrice());
longPrice = Float.parseFloat(eventMberInfo.getEventLongPrice());
picturePrice = Float.parseFloat(eventMberInfo.getEventPicturePrice());
picture2Price = Float.parseFloat(eventMberInfo.getEventPicture2Price());
picture3Price = Float.parseFloat(eventMberInfo.getEventPicture3Price());
}else if(shortPrice < 1 || longPrice < 1 || picturePrice < 1) {//협의 단가가 없는 경우 시스템 단가 적용해 주기
shortPrice = (float) sysJoinSetVO.getShortPrice();
longPrice = (float) sysJoinSetVO.getLongPrice();
picturePrice = (float) sysJoinSetVO.getPicturePrice();
picture2Price = (float) sysJoinSetVO.getPicture2Price();
picture3Price = (float) sysJoinSetVO.getPicture3Price();
}
// 토탈금액 "," 리플레이스 처리
mjonMsgVO.setTotPrice(mjonMsgVO.getTotPrice().replaceAll(",", ""));
float tmpOrgEachPrice = Float.parseFloat(mjonMsgVO.getEachPrice());
float tmpOrgTotPrice = Float.parseFloat(mjonMsgVO.getTotPrice());
System.out.println("mjonMsgVO.getMsgType2() ::: "+mjonMsgVO.getMsgType());
//각 문자 종류별 단가 셋팅해주기
float tmpEachPrice = 0;
if(mjonMsgVO.getMsgType().equals("4")) {
mjonMsgVO.setEachPrice(shortPrice.toString());
tmpEachPrice = shortPrice;
}else if(mjonMsgVO.getMsgType().equals("6")) {
if(mjonMsgVO.getFileName3() != null) {
mjonMsgVO.setEachPrice(picture3Price.toString());
tmpEachPrice = picture3Price;
}else if(mjonMsgVO.getFileName2() != null) {
mjonMsgVO.setEachPrice(picture2Price.toString());
tmpEachPrice = picture2Price;
}else if(mjonMsgVO.getFileName1() != null) {
mjonMsgVO.setEachPrice(picturePrice.toString());
tmpEachPrice = picturePrice;
}else {
mjonMsgVO.setEachPrice(longPrice.toString());
tmpEachPrice = longPrice;
}
}
//수신자 총 수 * 단가 를 통해 총 결제 금액 계산
int tmpTotCallCnt = mjonMsgVO.getCallToList().length;
float tmpTotPrice = tmpTotCallCnt * tmpEachPrice;
//화면에서 넘어온 파라미터 개별 단가와 컨트롤러에서 계산한 단가를 비교하여 맞지 않으면 컨트롤러 계산 단가 입력
if(tmpOrgEachPrice != tmpEachPrice) {
mjonMsgVO.setEachPrice(Float.toString(tmpEachPrice));
System.out.println("화면 : tmpOrgEachPrice ::: "+tmpOrgEachPrice);
System.out.println("컨트롤러 : tmpEachPrice ::: "+tmpEachPrice);
}else {
System.out.println("tmpOrgEachPrice ::: "+tmpOrgEachPrice);
}
if(tmpOrgTotPrice != tmpTotPrice ) {
mjonMsgVO.setTotPrice(Float.toString(tmpTotPrice));
System.out.println("화면 : tmpOrgTotPrice ::: "+tmpOrgTotPrice);
System.out.println("컨트롤러 : tmpTotPrice ::: "+tmpTotPrice);
}else {
System.out.println("tmpOrgTotPrice ::: "+tmpOrgTotPrice);
}
/*
* 개별단가 및 총결제 캐시 금액 체크 로직 종료
*
* */
// 치환문자가 있는경우
String txtReplYn = mjonMsgVO.getTxtReplYn();
if(txtReplYn.equals("Y")) {
//치환문자 체크 처리
int totListCnt = mjonMsgVO.getCallToList().length;
String[] nameList = mjonMsgVO.getNameList(); //치환 이름 리스트
String[] phone = mjonMsgVO.getCallToList(); //수신자 휴대폰 번호
String[] rep1 = mjonMsgVO.getRep1List(); //치환 문자1 리스트
String[] rep2 = mjonMsgVO.getRep2List(); //치환 문자2 리스트
String[] rep3 = mjonMsgVO.getRep3List(); //치환 문자3 리스트
String[] rep4 = mjonMsgVO.getRep4List(); //치환 문자4 리스트
//이름, 휴대폰, 치환문자 데이터가 없으면 취소 처리
if((nameList.length == 0 || nameList == null)
&& (rep1.length == 0 || rep1 == null)
&& (rep2.length == 0 || rep2 == null)
&& (rep3.length == 0 || rep3 == null)
&& (rep4.length == 0 || rep4 == null)) {
modelAndView.addObject("message", "특정문구 일괄변환 치환문자 데이터가 없습니다.");
modelAndView.addObject("result", "fail");
return modelAndView;
}
// 치환문자 전체 필수체크 Start
boolean isRepCountOk = true;
if (mjonMsgVO.getSmsTxt().indexOf("[*이름*]") > -1) {
if(nameList.length != phone.length) {
isRepCountOk = false;
}
}
if (mjonMsgVO.getSmsTxt().indexOf("[*1*]") > -1) {
if(rep1.length != phone.length) {
isRepCountOk = false;
}
}
if (mjonMsgVO.getSmsTxt().indexOf("[*2*]") > -1) {
if(rep2.length != phone.length) {
isRepCountOk = false;
}
}
if (mjonMsgVO.getSmsTxt().indexOf("[*3*]") > -1) {
if(rep3.length != phone.length) {
isRepCountOk = false;
}
}
if (mjonMsgVO.getSmsTxt().indexOf("[*4*]") > -1) {
if(rep4.length != phone.length) {
isRepCountOk = false;
}
}
if (isRepCountOk == false) {
modelAndView.addObject("message", "특정문구 일괄변환 치환문자 데이터가 없습니다");
modelAndView.addObject("result", "fail");
return modelAndView;
}
// End
//---------------------------------------------------------------------------------------------------------------
//단문, 장문 분리해서 전달하기 위해서 동일한 VO를 생성해 준다.
MjonMsgVO shortMsgVO = new MjonMsgVO();
MjonMsgVO longMsgVO = new MjonMsgVO();
MjonMsgVO imgMsgVO = new MjonMsgVO();
shortMsgVO = mjonMsgVO;
longMsgVO = mjonMsgVO;
imgMsgVO = mjonMsgVO;
int shortMsgCnt = Integer.parseInt(mjonMsgVO.getShortMsgCnt());
int longMsgCnt = Integer.parseInt(mjonMsgVO.getLongMsgCnt());
int imgMsgCnt = mjonMsgVO.getCallToList().length;
int tmpFileCnt = Integer.parseInt(mjonMsgVO.getFileCnt());
int tmpPhoMsgCnt = mjonMsgVO.getCallToList().length;
/*if(tmpFileCnt > 0) {
shortMsgCnt = tmpPhoMsgCnt;
longMsgCnt = tmpPhoMsgCnt;
}*/
String[] shortNameList = new String[shortMsgCnt]; //단문 치환 이름 리스트
String[] shortPhone = new String[shortMsgCnt]; //단문 수신자 휴대폰 번호
String[] shortRep1 = new String[shortMsgCnt]; //단문 치환 문자1 리스트
String[] shortRep2 = new String[shortMsgCnt]; //단문 치환 문자2 리스트
String[] shortRep3 = new String[shortMsgCnt]; //단문 치환 문자3 리스트
String[] shortRep4 = new String[shortMsgCnt]; //단문 치환 문자4 리스트
String[] longNameList = new String[longMsgCnt]; //장문 치환 이름 리스트
String[] longPhone = new String[longMsgCnt]; //장문 수신자 휴대폰 번호
String[] longRep1 = new String[longMsgCnt]; //장문 치환 문자1 리스트
String[] longRep2 = new String[longMsgCnt]; //장문 치환 문자2 리스트
String[] longRep3 = new String[longMsgCnt]; //장문 치환 문자3 리스트
String[] longRep4 = new String[longMsgCnt]; //장문 치환 문자4 리스트
String[] imgNameList = new String[imgMsgCnt]; //이미지 치환 이름 리스트
String[] imgPhone = new String[imgMsgCnt]; //이미지 수신자 휴대폰 번호
String[] imgRep1 = new String[imgMsgCnt]; //이미지 치환 문자1 리스트
String[] imgRep2 = new String[imgMsgCnt]; //이미지 치환 문자2 리스트
String[] imgRep3 = new String[imgMsgCnt]; //이미지 치환 문자3 리스트
String[] imgRep4 = new String[imgMsgCnt]; //이미지 치환 문자4 리스트
int shortCnt = 0;
int longCnt = 0;
int imgCnt = 0;
Map<String, String> returnImgMap = new HashMap<String, String>();
Map<String, String> returnShortMap = new HashMap<String, String>();
Map<String, String> returnLongMap = new HashMap<String, String>();
for(int i=0; i < totListCnt; i ++) {
String smsTxt = mjonMsgVO.getSmsTxt(); //발송 문자 내용
//본문 내용 - 치환 처리
smsTxt = smsTxt.replaceAll(String.valueOf((char)13), "");
if (smsTxt.indexOf("[*이름*]") > -1) {
if(nameList.length > i && StringUtil.isNotEmpty(nameList[i])) {
smsTxt = smsTxt.replaceAll("\\[\\*이름\\*\\]", StringUtil.getString(nameList[i].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*이름\\*\\]", "");
}
}
if (smsTxt.indexOf("[*1*]") > -1) {
if(rep1.length > i && StringUtil.isNotEmpty(rep1[i])) {
smsTxt = smsTxt.replaceAll("\\[\\*1\\*\\]", StringUtil.getString(rep1[i].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*1\\*\\]", "");
}
}
if (smsTxt.indexOf("[*2*]") > -1) {
if(rep2.length > i && StringUtil.isNotEmpty(rep2[i])) {
smsTxt = smsTxt.replaceAll("\\[\\*2\\*\\]", StringUtil.getString(rep2[i].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*2\\*\\]", "");
}
}
if (smsTxt.indexOf("[*3*]") > -1) {
if(rep3.length > i && StringUtil.isNotEmpty(rep3[i])) {
smsTxt = smsTxt.replaceAll("\\[\\*3\\*\\]", StringUtil.getString(rep3[i].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*3\\*\\]", "");
}
}
if (smsTxt.indexOf("[*4*]") > -1) {
if(rep4.length > i && StringUtil.isNotEmpty(rep4[i])) {
smsTxt = smsTxt.replaceAll("\\[\\*4\\*\\]", StringUtil.getString(rep4[i].replaceAll("§", ",")));
}else {
smsTxt = smsTxt.replaceAll("\\[\\*4\\*\\]", "");
}
}
//문자열 바이트 수 구하기(한글 2Byte로 계산)
// 한글 3Byte로 하기 위해서는 StandardCharsets.UTF_8 로 변경하면 된다.
int bytes = smsTxt.getBytes(charset).length;
//단문문자 리스트 만들기
if(bytes < 2000) {
if(fileCount > 0) {
if(nameList.length > i && !"".equals(nameList[i]) && nameList[i] != null) {
imgNameList[imgCnt] = StringUtil.getString(nameList[i].replaceAll("§", ",")); //장문 치환 이름 리스트
}else {
imgNameList[imgCnt] = " ";
}
if(phone.length > i && !"".equals(phone[i]) && phone[i] != null) {
imgPhone[imgCnt] = StringUtil.getString(phone[i].replaceAll("§", ",")); //장문 수신자 휴대폰 번호
}
if(rep1.length > i && !"".equals(rep1[i]) && rep1[i] != null) {
imgRep1[imgCnt] = StringUtil.getString(rep1[i].replaceAll("§", ",")); //장문 치환 문자1 리스트
}else {
imgRep1[imgCnt] = " ";
}
if(rep2.length > i && !"".equals(rep2[i]) && rep2[i] != null) {
imgRep2[imgCnt] = StringUtil.getString(rep2[i].replaceAll("§", ",")); //장문 치환 문자2 리스트
}else {
imgRep2[imgCnt] = " ";
}
if(rep3.length > i && !"".equals(rep3[i]) && rep3[i] != null) {
imgRep3[imgCnt] = StringUtil.getString(rep3[i].replaceAll("§", ",")); //장문 치환 문자3 리스트
}else {
imgRep3[imgCnt] = " ";
}
if(rep4.length > i && !"".equals(rep4[i]) && rep4[i] != null) {
imgRep4[imgCnt] = StringUtil.getString(rep4[i].replaceAll("§", ",")); //장문 치환 문자4 리스트
}else {
imgRep4[imgCnt] = " ";
}
imgCnt++;
}else if(bytes > 90) {//장문문자 리스트 만들기
//shortMsgListVO.add(mjonMsgVO.get)
/**
*
* 치환 리스트 중 데이터가 없는 경우 데이터 밀림방지를 위하여 공백 하나를 추가해줌
* 공백처리를 안하는 경우 데이터가 밀려서 치환되는 오류가 있어서 처리해줌
*
* */
if(nameList.length > i && !"".equals(nameList[i]) && nameList[i] != null) {
longNameList[longCnt] = StringUtil.getString(nameList[i].replaceAll("§", ",")); //장문 치환 이름 리스트
}else {
longNameList[longCnt] = " ";
}
if(phone.length > i && !"".equals(phone[i]) && phone[i] != null) {
longPhone[longCnt] = StringUtil.getString(phone[i].replaceAll("§", ",")); //장문 수신자 휴대폰 번호
}
if(rep1.length > i && !"".equals(rep1[i]) && rep1[i] != null) {
longRep1[longCnt] = StringUtil.getString(rep1[i].replaceAll("§", ",")); //장문 치환 문자1 리스트
}else {
longRep1[longCnt] = " ";
}
if(rep2.length > i && !"".equals(rep2[i]) && rep2[i] != null) {
longRep2[longCnt] = StringUtil.getString(rep2[i].replaceAll("§", ",")); //장문 치환 문자2 리스트
}else {
longRep2[longCnt] = " ";
}
if(rep3.length > i && !"".equals(rep3[i]) && rep3[i] != null) {
longRep3[longCnt] = StringUtil.getString(rep3[i].replaceAll("§", ",")); //장문 치환 문자3 리스트
}else {
longRep3[longCnt] = " ";
}
if(rep4.length > i && !"".equals(rep4[i]) && rep4[i] != null) {
longRep4[longCnt] = StringUtil.getString(rep4[i].replaceAll("§", ",")); //장문 치환 문자4 리스트
}else {
longRep4[longCnt] = " ";
}
longCnt++;
} else {//단문문자 리스트 만들기
/**
*
* 치환 리스트 중 데이터가 없는 경우 데이터 밀림방지를 위하여 공백 하나를 추가해줌
* 공백처리를 안하는 경우 데이터가 밀려서 치환되는 오류가 있어서 처리해줌
*
* */
if(nameList.length > i && !"".equals(nameList[i]) && nameList[i] != null) {
shortNameList[shortCnt] = StringUtil.getString(nameList[i].replaceAll("§", ",")); //단문 치환 이름 리스트
}else {
shortNameList[shortCnt] = " ";
}
if(phone.length > i && !"".equals(phone[i]) && phone[i] != null) {
shortPhone[shortCnt] = StringUtil.getString(phone[i].replaceAll("§", ",")); //단문 수신자 휴대폰 번호
}
if(rep1.length > i && !"".equals(rep1[i]) && rep1[i] != null) {
shortRep1[shortCnt] = StringUtil.getString(rep1[i].replaceAll("§", ",")); //단문 치환 문자1 리스트
}else {
shortRep1[shortCnt] = " ";
}
if(rep2.length > i && !"".equals(rep2[i]) && rep2[i] != null) {
shortRep2[shortCnt] = StringUtil.getString(rep2[i].replaceAll("§", ",")); //단문 치환 문자2 리스트
}else {
shortRep2[shortCnt] = " ";
}
if(rep3.length > i && !"".equals(rep3[i]) && rep3[i] != null) {
shortRep3[shortCnt] = StringUtil.getString(rep3[i].replaceAll("§", ",")); //단문 치환 문자3 리스트
}else {
shortRep3[shortCnt] = " ";
}
if(rep4.length > i && !"".equals(rep4[i]) && rep4[i] != null) {
shortRep4[shortCnt] = StringUtil.getString(rep4[i].replaceAll("§", ",")); //단문 치환 문자4 리스트
}else {
shortRep4[shortCnt] = " ";
}
shortCnt++;
}
}else {
modelAndView.addObject("message", "문자 치환 후 전송 문자 길이를 초과하였습니다.");
modelAndView.addObject("result", "fail");
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
if(imgCnt > 0) {//그림문자 전송 이름, 전화번호, 변환문자 입력해주기
imgMsgVO.setNameList(imgNameList);
imgMsgVO.setCallToList(imgPhone);
imgMsgVO.setRep1List(imgRep1);
imgMsgVO.setRep2List(imgRep2);
imgMsgVO.setRep3List(imgRep3);
imgMsgVO.setRep4List(imgRep4);
//개별단가 계산하기
String eachPrice = imgMsgVO.getPPrice();
//api 서버에서 pPrice 값이 없는 경우가 있어서 오류 방지를위해서 추가
if(eachPrice == null) {
eachPrice = imgMsgVO.getEachPrice();
}
/**
* 그림문자에 치환 내용이 포함되어 있는 경우 단가 계산하기.
* 그림문자의 경우 이로직을 타지 않지만 혹시 몰라서 추가해놓음
* */
if(fileCount > 2) {//그림 이미지가 3개
eachPrice = mjonMsgVO.getP3Price();
}else if(fileCount > 1) {//그림 이미지가 2개
eachPrice = mjonMsgVO.getP2Price();
}else if(fileCount == 1) {//그림 이미지가 1개
eachPrice = mjonMsgVO.getPPrice();
}
imgMsgVO.setEachPrice(eachPrice);
//문자 종류 선택
imgMsgVO.setMsgType("6");
//총금액 계산하기
Float sTotPrice = Float.parseFloat(imgMsgVO.getEachPrice()) * imgCnt;
imgMsgVO.setTotPrice(sTotPrice.toString());
//그림문자 발송 처리
returnImgMap = fncSendMsgRtnMap(imgMsgVO);
}
if(shortCnt > 0) {//단문문자 전송 이름, 전화번호, 변환문자 입력해주기
shortMsgVO.setNameList(shortNameList);
shortMsgVO.setCallToList(shortPhone);
shortMsgVO.setRep1List(shortRep1);
shortMsgVO.setRep2List(shortRep2);
shortMsgVO.setRep3List(shortRep3);
shortMsgVO.setRep4List(shortRep4);
//개별단가 계산하기
String eachPrice = shortMsgVO.getSPrice();
//api 서버에서 sPrice 값이 없는 경우가 있어서 오류 방지를위해서 추가
if(eachPrice == null) {
eachPrice = shortMsgVO.getEachPrice();
}
/**
* 그림문자에 치환 내용이 포함되어 있는 경우 단가 계산하기.
* 그림문자의 경우 이로직을 타지 않지만 혹시 몰라서 추가해놓음
* */
if(fileCount > 2) {//그림 이미지가 3개
eachPrice = mjonMsgVO.getP3Price();
}else if(fileCount > 1) {//그림 이미지가 2개
eachPrice = mjonMsgVO.getP2Price();
}else if(fileCount == 1) {//그림 이미지가 1개
eachPrice = mjonMsgVO.getPPrice();
}
shortMsgVO.setEachPrice(eachPrice);
//문자 종류 선택
if(fileCount > 0) {//그림문자인 경우 문자타임 지정
shortMsgVO.setMsgType("6");
}else {
shortMsgVO.setMsgType("4");
}
//총금액 계산하기
Float sTotPrice = Float.parseFloat(shortMsgVO.getEachPrice()) * shortCnt;
shortMsgVO.setTotPrice(sTotPrice.toString());
//단문문자 발송 처리
returnShortMap = fncSendMsgRtnMap(shortMsgVO);
}
if(longCnt > 0) {//장문문자 전송 이름, 전화번호, 변환문자 입력해주기
longMsgVO.setNameList(longNameList);
longMsgVO.setCallToList(longPhone);
longMsgVO.setRep1List(longRep1);
longMsgVO.setRep2List(longRep2);
longMsgVO.setRep3List(longRep3);
longMsgVO.setRep4List(longRep4);
/**
* 그림문자에 치환 내용이 포함되어 있는 경우 단가 계산하기.
* 그림문자의 경우 이로직을 타지 않지만 혹시 몰라서 추가해놓음
* */
String eachPrice = longMsgVO.getMPrice();
//api 서버에서 mPrice 값이 없는 경우가 있어서 오류 방지를위해서 추가
if(eachPrice == null) {
eachPrice = longMsgVO.getEachPrice();
}
if(fileCount > 2) {//그림 이미지가 3개
eachPrice = mjonMsgVO.getP3Price();
}else if(fileCount > 1) {//그림 이미지가 2개
eachPrice = mjonMsgVO.getP2Price();
}else if(fileCount == 1) {//그림 이미지가 1개
eachPrice = mjonMsgVO.getPPrice();
}
longMsgVO.setEachPrice(eachPrice);
//문자 종류 선택
longMsgVO.setMsgType("6");
//총금액 계산하기
Float mTotPrice = Float.parseFloat(longMsgVO.getEachPrice()) * longCnt;
longMsgVO.setTotPrice(mTotPrice.toString());
//장문문자 발송
returnLongMap = fncSendMsgRtnMap(longMsgVO);
}
//일괄변환에 의한 단문, 장문 별개로 전송을 했기 때문에 각각 전송 결과 건수를 합쳐준 후 결과를 modelAndView로 리턴해준다.
String returnMessage = "";
String returnStatus = "";
String msgGroupIdListComma = "";
String msgTypeListComma = "";
//그림 결과 내용
if(!returnImgMap.isEmpty()) {
if(!returnImgMap.get("result").contains("fail")) {
//발송건수 계산
int sendCnt = Integer.parseInt(resultSts) + Integer.parseInt(returnImgMap.get("resultSts"));
resultSts = Integer.toString(sendCnt);
//수신거부 건수 계산
int sendBlockCnt = Integer.parseInt(resultBlockSts) + Integer.parseInt(returnImgMap.get("resultBlockSts"));
resultBlockSts = Integer.toString(sendBlockCnt);
returnMessage = returnImgMap.get("message");
returnStatus = returnImgMap.get("result");
msgGroupIdListComma = returnImgMap.get("msgGroupId");
}else {
returnMessage = returnImgMap.get("message");
returnStatus = returnImgMap.get("result");
modelAndView.addObject("message", returnMessage);
modelAndView.addObject("result", returnStatus);
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
//장문발송 결과 내용
if(!returnLongMap.isEmpty()) {
if(!returnLongMap.get("result").contains("fail")) {
//발송건수 계산
int sendCnt = Integer.parseInt(resultSts) + Integer.parseInt(returnLongMap.get("resultSts"));
resultSts = Integer.toString(sendCnt);
//수신거부 건수 계산
int sendBlockCnt = Integer.parseInt(resultBlockSts) + Integer.parseInt(returnLongMap.get("resultBlockSts"));
resultBlockSts = Integer.toString(sendBlockCnt);
returnMessage = returnLongMap.get("message");
returnStatus = returnLongMap.get("result");
msgGroupIdListComma = StringUtils.isNotEmpty(msgGroupIdListComma)
? msgGroupIdListComma+","+returnLongMap.get("msgGroupId")
: returnLongMap.get("msgGroupId");
msgTypeListComma = StringUtils.isNotEmpty(msgTypeListComma)
? msgTypeListComma+","+"6"
: "6";
}else {
returnMessage = returnLongMap.get("message");
returnStatus = returnLongMap.get("result");
modelAndView.addObject("message", returnMessage);
modelAndView.addObject("result", returnStatus);
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
//단문발송 결과 내용
if(!returnShortMap.isEmpty()) {
if(!returnShortMap.get("result").contains("fail")) {
//발송건수 계산
int sendCnt = Integer.parseInt(resultSts) + Integer.parseInt(returnShortMap.get("resultSts"));
resultSts = Integer.toString(sendCnt);
//수신거부 건수 계산
int sendBlockCnt = Integer.parseInt(resultBlockSts) + Integer.parseInt(returnShortMap.get("resultBlockSts"));
resultBlockSts = Integer.toString(sendBlockCnt);
returnMessage = returnShortMap.get("message");
returnStatus = returnShortMap.get("result");
msgGroupIdListComma = StringUtils.isNotEmpty(msgGroupIdListComma)
? msgGroupIdListComma+","+returnShortMap.get("msgGroupId")
: returnShortMap.get("msgGroupId");
msgTypeListComma = StringUtils.isNotEmpty(msgTypeListComma)
? msgTypeListComma+","+"4"
: "4";
}else {
returnMessage = returnShortMap.get("message");
returnStatus = returnShortMap.get("result");
modelAndView.addObject("message", returnMessage);
modelAndView.addObject("result", returnStatus);
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
modelAndView.addObject("msgType", msgTypeListComma);
modelAndView.addObject("msgGroupId", msgGroupIdListComma);
modelAndView.addObject("message", returnMessage);
modelAndView.addObject("result", returnStatus);
modelAndView.addObject("resultSts", resultSts);
modelAndView.addObject("resultBlockSts", resultBlockSts);
}else {
//문자발송 함수 호출 - 일괄변환이 없거나, 그림문자 일괄변환의 경우 한번에 전송 처리
modelAndView = fncSendMsg(mjonMsgVO);
}
}catch(Exception e) {
System.out.println("=========================================================================");
System.out.println("+++++++++++++++++++++++++++++ 일반문자 ==> 기타 시스템 오류 !!! : " + e.getMessage());
System.out.println("=========================================================================");
//logger.error(e.getMessage(), e);
e.printStackTrace();
modelAndView.addObject("result", "fail");
modelAndView.addObject("message", "기타 시스템 오류 : " + e.getMessage());
return modelAndView;
}
/**
* 사용자가 보낸 문자를 문자온 법인폰으로도 하나 전송하는 기능 시작
*
* */
try {
String adminSmsNoticeYn = "Y";
String smishingYn = "N";
String spamStatus = mjonMsgVO.getSpamStatus(); //스미싱 의심으로 체크된 문자 정보
UserManageVO userManageVO = new UserManageVO();
userManageVO.setMberId(userId);
if(!userId.equals("")) {
userManageVO = userManageService.selectAdminSmsNoticeYn(userManageVO);
adminSmsNoticeYn = userManageVO.getAdminSmsNoticeYn();
smishingYn = userManageVO.getSmishingYn();
}
//법인폰 알림 온 이거나 스미싱의심 문자인 경우 법인폰으로 발송
if(adminSmsNoticeYn.equals("Y") || spamStatus.equals("Y") || smishingYn.equals("Y")) {
if(spamStatus.equals("Y")) {
mjonMsgVO.setDelayYn("Y");
}else if(smishingYn.equals("Y")) {
mjonMsgVO.setSmishingYn("Y");
}
// 법인폰 알람여부 체크
JoinSettingVO joinSettingVO = new JoinSettingVO();
joinSettingVO = egovSiteManagerService.selectAdminNotiDetail();
String holiSmishingNoti = joinSettingVO.getHoliSmishingNoti();
//야간 스미싱의심 알림이 활성화 되어있는 경우
if(holiSmishingNoti.equals("Y")) {
// SLACK 체크
if (joinSettingVO != null && joinSettingVO.getSlackNoti().equals("Y")) {
MsgAlarmSetVO msgAlarmSetVO = new MsgAlarmSetVO();
msgAlarmSetVO.setUseYn("Y");
msgAlarmSetVO.setFirstIndex(0);
List<MsgAlarmSetVO> resultAlarmList = msgHolidayService.selectAlarmSettingList(msgAlarmSetVO);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
MsgHolidayVO msgHolidayVO = new MsgHolidayVO();
msgHolidayVO.setFirstIndex(0);
msgHolidayVO.setRecordCountPerPage(100);
msgHolidayVO.setSearchHoliYear(Integer.toString(year));
List<MsgHolidayVO> resultHolidayList = msgHolidayService.selectMsgHolidayList(msgHolidayVO);
MjonHolidayApi mjonHolidayApi = new MjonHolidayApi();
boolean smishingAlarmPassSts = mjonHolidayApi.getHolidaySmishingPassStatus(resultAlarmList, resultHolidayList);
if(!smishingAlarmPassSts) {//평일,주말, 공휴일 알림설정 시간에 포함되지 않는 경우 슬랙 알림 발송
/*
MjonCommon comm = new MjonCommon();
comm.getAdminMsgSandSlack(mjonMsgVO);
*/
mjonCommon.getAdminMsgSandSlack(mjonMsgVO);
}
//Slack으로 메세지 전송 처리
/*MjonCommon comm = new MjonCommon();
System.out.println("slack noti");
comm.getAdminMsgSandSlack(mjonMsgVO);*/
}
}
/*else {//야간스미싱 알림 비활성화인 경우 - 알림일정에 포함되지 않으면 슬랙 발송 처리(알림일정에 포함되면 슬랙발송 X - 알림 비활성화이기 때문에 발송X)
MsgAlarmSetVO msgAlarmSetVO = new MsgAlarmSetVO();
msgAlarmSetVO.setUseYn("Y");
msgAlarmSetVO.setFirstIndex(0);
List<MsgAlarmSetVO> resultAlarmList = msgHolidayService.selectAlarmSettingList(msgAlarmSetVO);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
MsgHolidayVO msgHolidayVO = new MsgHolidayVO();
msgHolidayVO.setFirstIndex(0);
msgHolidayVO.setRecordCountPerPage(100);
msgHolidayVO.setSearchHoliYear(Integer.toString(year));
List<MsgHolidayVO> resultHolidayList = msgHolidayService.selectMsgHolidayList(msgHolidayVO);
MjonHolidayApi mjonHolidayApi = new MjonHolidayApi();
boolean smishingAlarmPassSts = mjonHolidayApi.getHolidaySmishingPassStatus(resultAlarmList, resultHolidayList);
if(!smishingAlarmPassSts) {//평일,주말, 공휴일 알림설정 시간에 포함되지 않는 경우 슬랙 알림 발송
MjonCommon comm = new MjonCommon();
comm.getAdminMsgSandSlack(mjonMsgVO);
}
}*/
}
} catch (Exception e) {
throw new Exception("++++++++++++++++++++++ getAdminPhoneSendMsgData Error !!! " + e);
}
return modelAndView;
}
/**
* 문자발송시 치환문자가 있거나 단문, 장문 일경우 타는 로직
* param : MjonMsgVO
* return : ModelAndView
*
* */
public Map<String, String> fncSendMsgRtnMap(MjonMsgVO mjonMsgVO) {
Map<String, String> returnMap = new HashMap<String, String>();
//String resultSts = "0"; //발송결과 건수
//String resultBlockSts = "0"; //수신거부 등록번호로 발송을 안한 건수
int resultSts = 0; //발송결과 건수
int resultBlockSts = 0; //수신거부 등록번호로 발송을 안한 건수
try {
//현재 고객의 보유 캐시가 문자 발송이 가능한 금액인지 체크
String userMoney = mjonMsgDataService.selectBeforeCashData(mjonMsgVO);
String userPoint = mjonMsgDataService.selectBeforePointData(mjonMsgVO);
mjonMsgVO.setBefPoint(userPoint); //현재 보유 포인트 정보 저장
String totPrice = mjonMsgVO.getTotPrice();
BigDecimal befCash = new BigDecimal(userMoney).setScale(2, RoundingMode.HALF_EVEN);
BigDecimal totMsgPrice = new BigDecimal(totPrice).setScale(2, RoundingMode.HALF_EVEN);
//현재 보유 금액이 발송 문자 총 금액보다 클 경우만 문자 발송
//BigDecimal 비교 연산
// befCash(현재 보유금액) 값이 totMsgPrice(문자전송 금액) 보다 많으면 문자 전송
if(befCash.compareTo(totMsgPrice) != -1) { // -1 : befCash < totMsgPrice, 0 : befCash = totMsgPrice, 1 : befCash > totMsgPrice,
//문자 발송 처리
//MjonMsgReturnVO returnVO = new MjonMsgReturnVO();
//현재 보유 캐쉬금액 셋팅
mjonMsgVO.setBefCash(befCash.toString());
//문자 전송 그룹아이디 생성
mjonMsgVO.setMsgGroupId(idgenMjonMsgGroupId.getNextStringId());
String[] tempPhoneList = new String[200]; //임시 수신번호 리스트 저장용 배열
String[] tempNameList = new String[200]; //임시 이름 리스트 저장용 배열
String[] tempRep1List = new String[200]; //임시 치환문자1 리스트 저장용 배열
String[] tempRep2List = new String[200]; //임시 치환문자1 리스트 저장용 배열
String[] tempRep3List = new String[200]; //임시 치환문자1 리스트 저장용 배열
String[] tempRep4List = new String[200]; //임시 치환문자1 리스트 저장용 배열
String[] phoneList = mjonMsgVO.getCallToList();
String[] nameList = mjonMsgVO.getNameList();
String[] rep1List = mjonMsgVO.getRep1List();
String[] rep2List = mjonMsgVO.getRep2List();
String[] rep3List = mjonMsgVO.getRep3List();
String[] rep4List = mjonMsgVO.getRep4List();
int callToListCnt = mjonMsgVO.getCallToList().length;
mjonMsgVO.setTotalCallCnt(callToListCnt);
/** 예약 문자인 경우 시간 및 분할 시간 셋팅 해주기 */
//분할문자 시간에 간격시간 더해주기
String dividDay = null;
Calendar cal = Calendar.getInstance();
//예약시간 변환
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
int turmMin = 0;
int totalCallCnt = 0; // 수신자 전체 갯수
int divideCnt = 0;
int count = 1; //분할 카운트
if(!mjonMsgVO.getReserveYn().equals("N")) {//예약문자인 경우 시간 셋팅
Date toDate = transFormat.parse(mjonMsgVO.getReqDate());
cal.setTime(toDate); //예약 시간 캘린터 변수에 입력
//String 타입 시간 Int로 변환
turmMin = Integer.parseInt(mjonMsgVO.getDivideTime()); //분할발송 시간 간격
dividDay = transFormat.format(cal.getTime());
totalCallCnt = mjonMsgVO.getCallToList().length; // 수신자 전체 갯수
divideCnt = Integer.parseInt(mjonMsgVO.getDivideCnt()); //분할 발송 갯수
}
//분할 예약 시간 저장 리스트 생성
List<String> dividDayList = new ArrayList<String>();
//서비스 단으로 특정 문자 건수 이상으로 한번에 보내지 않기 위해서 처리함
if(callToListCnt > 200) {
int sendCnt = 0;
for(int i=0; i< callToListCnt; i++) {
//분할 발송을 체크 한 경우
if(mjonMsgVO.getDivideChk() != null) {
if(count > divideCnt) {
count = 1;
//분할 시간 간격을 증가시켜 준다.
cal.add(Calendar.MINUTE, turmMin);
dividDay = transFormat.format(cal.getTime());
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}else {
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}
}
if((i < callToListCnt -1) && sendCnt == 199) {
//sendCnt 4번째 값을 추가해준다.
tempPhoneList[sendCnt] = phoneList[i];
tempNameList[sendCnt] = nameList[i];
tempRep1List[sendCnt] = rep1List[i];
tempRep2List[sendCnt] = rep2List[i];
tempRep3List[sendCnt] = rep3List[i];
tempRep4List[sendCnt] = rep4List[i];
List<String> arrPhoneList = new ArrayList<String>();
List<String> arrNameList = new ArrayList<String>();
List<String> arrRep1List = new ArrayList<String>();
List<String> arrRep2List = new ArrayList<String>();
List<String> arrRep3List = new ArrayList<String>();
List<String> arrRep4List = new ArrayList<String>();
for(String temp : tempPhoneList) {
if(temp != null) {
arrPhoneList.add(temp);
}
}
for(String tmpName : tempNameList) {
if(tmpName != null) {
arrNameList.add(tmpName);
}
}
for(String tmpRep1 : tempRep1List) {
if(tmpRep1 != null) {
arrRep1List.add(tmpRep1);
}
}
for(String tmpRep2 : tempRep2List) {
if(tmpRep2 != null) {
arrRep2List.add(tmpRep2);
}
}
for(String tmpRep3 : tempRep3List) {
if(tmpRep3 != null) {
arrRep3List.add(tmpRep3);
}
}
for(String tmpRep4 : tempRep4List) {
if(tmpRep4 != null) {
arrRep4List.add(tmpRep4);
}
}
String[] sendPhoneList = new String[arrPhoneList.size()];
String[] sendNameList = new String[arrNameList.size()];
String[] sendRep1List = new String[arrRep1List.size()];
String[] sendRep2List = new String[arrRep2List.size()];
String[] sendRep3List = new String[arrRep3List.size()];
String[] sendRep4List = new String[arrRep4List.size()];
for(int j=0; j< arrPhoneList.size(); j++) {
sendPhoneList[j] = arrPhoneList.get(j);
}
for(int k=0; k< arrNameList.size(); k++) {
sendNameList[k] = arrNameList.get(k);
}
for(int k=0; k< arrRep1List.size(); k++) {
sendRep1List[k] = arrRep1List.get(k);
}
for(int k=0; k< arrRep2List.size(); k++) {
sendRep2List[k] = arrRep2List.get(k);
}
for(int k=0; k< arrRep3List.size(); k++) {
sendRep3List[k] = arrRep3List.get(k);
}
for(int k=0; k< arrRep4List.size(); k++) {
sendRep4List[k] = arrRep4List.get(k);
}
mjonMsgVO.setCallToList(sendPhoneList);
mjonMsgVO.setNameList(sendNameList);
mjonMsgVO.setRep1List(sendRep1List);
mjonMsgVO.setRep2List(sendRep2List);
mjonMsgVO.setRep3List(sendRep3List);
mjonMsgVO.setRep4List(sendRep4List);
sendCnt = 0;
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = resultSts + Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = resultBlockSts + Integer.parseInt(returnVO.getSendMsgBlockCnt());
//발송 처리후 배열 초기화
Arrays.fill(tempPhoneList, null);
dividDayList.clear();
}else if((i == callToListCnt -1) && sendCnt < 200){//200개의 마지막일 경우 처리
//마지막 리스트의 수신번호를 추가해 준다.
tempPhoneList[sendCnt] = phoneList[i];
tempNameList[sendCnt] = nameList[i];
tempRep1List[sendCnt] = rep1List[i];
tempRep2List[sendCnt] = rep2List[i];
tempRep3List[sendCnt] = rep3List[i];
tempRep4List[sendCnt] = rep4List[i];
List<String> arrPhoneList2 = new ArrayList<String>();
List<String> arrNameList2 = new ArrayList<String>();
List<String> arrRep1List2 = new ArrayList<String>();
List<String> arrRep2List2 = new ArrayList<String>();
List<String> arrRep3List2 = new ArrayList<String>();
List<String> arrRep4List2 = new ArrayList<String>();
for(String temp : tempPhoneList) {
if(temp != null) {
arrPhoneList2.add(temp);
}
}
for(String tmpName : tempNameList) {
if(tmpName != null) {
arrNameList2.add(tmpName);
}
}
for(String tmpRep1 : tempRep1List) {
if(tmpRep1 != null) {
arrRep1List2.add(tmpRep1);
}
}
for(String tmpRep2 : tempRep2List) {
if(tmpRep2 != null) {
arrRep2List2.add(tmpRep2);
}
}
for(String tmpRep3 : tempRep3List) {
if(tmpRep3 != null) {
arrRep3List2.add(tmpRep3);
}
}
for(String tmpRep4 : tempRep4List) {
if(tmpRep4 != null) {
arrRep4List2.add(tmpRep4);
}
}
String[] sendPhoneList2 = new String[arrPhoneList2.size()];
String[] sendNameList2 = new String[arrNameList2.size()];
String[] sendRep1List2 = new String[arrRep1List2.size()];
String[] sendRep2List2 = new String[arrRep2List2.size()];
String[] sendRep3List2 = new String[arrRep3List2.size()];
String[] sendRep4List2 = new String[arrRep4List2.size()];
for(int j=0; j< arrPhoneList2.size(); j++) {
sendPhoneList2[j] = arrPhoneList2.get(j);
}
for(int j=0; j< arrNameList2.size(); j++) {
sendNameList2[j] = arrNameList2.get(j);
}
for(int k=0; k< arrRep1List2.size(); k++) {
sendRep1List2[k] = arrRep1List2.get(k);
}
for(int k=0; k< arrRep2List2.size(); k++) {
sendRep2List2[k] = arrRep2List2.get(k);
}
for(int k=0; k< arrRep3List2.size(); k++) {
sendRep3List2[k] = arrRep3List2.get(k);
}
for(int k=0; k< arrRep4List2.size(); k++) {
sendRep4List2[k] = arrRep4List2.get(k);
}
mjonMsgVO.setCallToList(sendPhoneList2);
mjonMsgVO.setNameList(sendNameList2);
mjonMsgVO.setRep1List(sendRep1List2);
mjonMsgVO.setRep2List(sendRep2List2);
mjonMsgVO.setRep3List(sendRep3List2);
mjonMsgVO.setRep4List(sendRep4List2);
sendCnt = 0;
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = resultSts + Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = resultBlockSts + Integer.parseInt(returnVO.getSendMsgBlockCnt());
}else {//198개가 될때까지 배열에 데이터를 쌓는다
tempPhoneList[sendCnt] = phoneList[i];
if(nameList.length > 0) {//이름 치환문자가 있는 경우
tempNameList[sendCnt] = nameList[i];
}
if(rep1List.length > 0) {//치환1 문자가 있는 경우
tempRep1List[sendCnt] = rep1List[i];
}
if(rep2List.length > 0) {//치환2 문자가 있는 경우
tempRep2List[sendCnt] = rep2List[i];
}
if(rep3List.length > 0) {//치환3 문자가 있는 경우
tempRep3List[sendCnt] = rep3List[i];
}
if(rep4List.length > 0) {//치환4 문자가 있는 경우
tempRep4List[sendCnt] = rep4List[i];
}
sendCnt++;
}
}
}else {
//분할 발송을 체크 한 경우
if(mjonMsgVO.getDivideChk() != null) {
for(int i=0; i< callToListCnt; i++) {
if(count > divideCnt) {
count = 1;
//분할 시간 간격을 증가시켜 준다.
cal.add(Calendar.MINUTE, turmMin);
dividDay = transFormat.format(cal.getTime());
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}else {
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}
}
}
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = Integer.parseInt(returnVO.getSendMsgBlockCnt());
}
System.out.println("=========================================================================");
System.out.println(" 25xx +++++++++++++++++++++++++++++++++++++++++++ resultSts ::: " + resultSts);
System.out.println("=========================================================================");
try {
//문자 발송 캐시 차감 해주기 - serviceImple에서 처리하도록 변경 함
/*MjonPayVO mjonPayVO = new MjonPayVO();
if(resultSts > 0 && resultBlockSts > 0) {
Float blockPrice = Float.parseFloat(mjonMsgVO.getEachPrice()) * resultBlockSts;
Float resultTotPrice = Float.parseFloat(mjonMsgVO.getTotPrice());
Float endPrice = resultTotPrice - blockPrice;
mjonMsgVO.setTotPrice(Float.toString(endPrice));
//수신거부가 있는 경우 총 건수에서 수신거부 건수를 차감 후 그룹 테이블에 업데이트 해준다.
int groupCnt = resultSts;
mjonMsgVO.setMsgGroupCnt(Integer.toString(groupCnt));
}
//1건 이상 발송이 있는 경우만 캐쉬를 차감 시킨다.
if(resultSts > 0) {
mjonPayVO.setCashId(idgenMjonCashId.getNextStringId());
mjonPayVO.setUserId(mjonMsgVO.getUserId());
mjonPayVO.setCash(-Float.parseFloat(mjonMsgVO.getTotPrice()));
mjonPayVO.setFrstRegisterId(mjonMsgVO.getUserId());
mjonPayVO.setMemo("SMS 문자 " + resultSts + "건 발송");
mjonPayVO.setMsgGroupId(mjonMsgVO.getMsgGroupId());
mjonPayService.insertCash(mjonPayVO); //캐시차감
mjonPayService.updateMemberCash(mjonPayVO); //회원정보 업데이트
}
//문자 발송 테이블에 입력 데이터가 있는 경우 그룹 테이블에도 입력 해 준다.
if(resultSts > 0) {
// 문자 전송 그룹 테이블에 정보 입력
int groupCnt = resultSts;
mjonMsgVO.setMsgGroupCnt(Integer.toString(groupCnt));
mjonMsgService.insertGroupMsgData(mjonMsgVO);
//이벤트 회원 남은 캐시 업데이트
fnUpdateEventRemainCash(mjonPayVO);
}*/
//스팸문구 포함된 문자 발송의 경우 스팸 문구 내용도 별도 저장함.
String spamStatus = mjonMsgVO.getSpamStatus();
if(spamStatus == null) {
spamStatus = "N";
mjonMsgVO.setSpamStatus("N");
}
if(spamStatus.equals("Y")) {
int resultCnt = mjonSpamMsgService.insertSpamKeyWordMsgData(mjonMsgVO);
System.out.println("+++++++++++++스팸문구 발송 내용 등록 +++++++++++++++++++++ "+resultCnt);
}
} catch (Exception e) {
System.out.println("=========================================================================");
System.out.println("+++++++++++++++++++++++++++++ fncSendMsgRtnMap() MJ_MSG_GROUP && CASH INSER ERROR !!! : " + e.getMessage());
System.out.println("=========================================================================");
}
}else {
returnMap.put("message", "문자 발송에 필요한 보유 잔액이 부족 합니다.");
returnMap.put("result", "fail");
returnMap.put("resultSts", "0");
returnMap.put("resultBlockSts", "0");
return returnMap;
}
//문자 발송 후 남은 보유 캐시 정보 불러오기
String afterCash = mjonMsgDataService.selectBeforeCashData(mjonMsgVO);
returnMap.put("afterCash", afterCash);
}catch(Exception e) {
logger.error(e.getMessage(), e);
System.out.println("=========================================================================");
System.out.println("+++++++++++++++++++++++++++++ 기타 시스템 오류 : " + e.getMessage());
System.out.println("=========================================================================");
returnMap.put("result", "fail");
returnMap.put("message", "기타 시스템 오류 : " + e.getMessage());
}
returnMap.put("message", "문자 전송이 완료되었습니다.");
returnMap.put("result", "success");
returnMap.put("msgGroupId", mjonMsgVO.getMsgGroupId());
returnMap.put("resultSts", Integer.toString(resultSts));
returnMap.put("resultSts", Integer.toString(resultSts));
returnMap.put("resultBlockSts", Integer.toString(resultBlockSts));
return returnMap;
}
/**
* 문자발송시 치환문자가 없거나 그림문자일 경우 타는 로직
* param : MjonMsgVO
* return : ModelAndView
*
* */
public ModelAndView fncSendMsg(MjonMsgVO mjonMsgVO) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("jsonView");
int resultSts = 0; //발송결과 건수
int resultBlockSts = 0; //수신거부 등록번호로 발송을 안한 건수
try {
//문자열 길이 체크 해주기
String charset = "euc-kr";
String smsCont = mjonMsgVO.getSmsTxt().replace("\r\n", "\n");
int bytes = smsCont.getBytes(charset).length; //발송 문자 길이
if(mjonMsgVO.getFileName1() != null) {
mjonMsgVO.setMsgType("6");
}else {
if(bytes < 2000) {
if(bytes > 90) {// 90Byte 초과시 장문
mjonMsgVO.setMsgType("6");
}else {// 그외 단문
mjonMsgVO.setMsgType("4");
}
}else { //최대 문자길이 초과시
modelAndView.addObject("message", "문자 치환 후 전송 문자 길이를 초과하였습니다.");
modelAndView.addObject("result", "fail");
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
}
//현재 고객의 보유 캐시가 문자 발송이 가능한 금액인지 체크
String userMoney = mjonMsgDataService.selectBeforeCashData(mjonMsgVO);
String userPoint = mjonMsgDataService.selectBeforePointData(mjonMsgVO);
mjonMsgVO.setBefPoint(userPoint); //현재 보유 포인트 정보 저장
String totPrice = mjonMsgVO.getTotPrice();
BigDecimal befCash = new BigDecimal(userMoney).setScale(2, RoundingMode.HALF_EVEN);
BigDecimal totMsgPrice = new BigDecimal(totPrice).setScale(2, RoundingMode.HALF_EVEN);
// 현재 보유 금액이 발송 문자 총 금액보다 클 경우만 문자 발송
// BigDecimal 비교 연산
// befCash(현재 보유금액) 값이 totMsgPrice(문자전송 금액) 보다 많으면 문자 전송
if(befCash.compareTo(totMsgPrice) != -1) { // -1 : befCash < totMsgPrice, 0 : befCash = totMsgPrice, 1 : befCash > totMsgPrice,
mjonMsgVO.setBefCash(userMoney);
// 문자 전송 그룹아이디 생성
mjonMsgVO.setMsgGroupId(idgenMjonMsgGroupId.getNextStringId());
//문자 발송 처리
//MjonMsgReturnVO returnVO = new MjonMsgReturnVO();
String[] tempPhoneList = new String[200]; //임시 수신번호 리스트 저장용 배열
String[] phoneList = mjonMsgVO.getCallToList();
int callToListCnt = mjonMsgVO.getCallToList().length;
mjonMsgVO.setTotalCallCnt(callToListCnt);
/**
* 예약 문자인 경우 시간 및 분할 시간 셋팅 해주기
*
*
* */
//분할문자 시간에 간격시간 더해주기
String dividDay = null;
Calendar cal = Calendar.getInstance();
//예약시간 변환
SimpleDateFormat transFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
int turmMin = 0;
int totalCallCnt = 0;
int divideCnt = 0;
int count = 1; //분할 카운트
if(!mjonMsgVO.getReserveYn().equals("N")) {//예약문자인 경우 시간 셋팅
Date toDate = transFormat.parse(mjonMsgVO.getReqDate());
cal.setTime(toDate); //예약 시간 캘린터 변수에 입력
//String 타입 시간 Int로 변환
turmMin = Integer.parseInt(mjonMsgVO.getDivideTime()); //분할발송 시간 간격
dividDay = transFormat.format(cal.getTime());
totalCallCnt = mjonMsgVO.getCallToList().length; // 수신자 전체 갯수
divideCnt = Integer.parseInt(mjonMsgVO.getDivideCnt()); //분할 발송 갯수
}
//분할 예약 시간 저장 리스트 생성
List<String> dividDayList = new ArrayList<String>();
//서비스 단으로 특정 문자 건수 이상으로 한번에 보내지 않기 위해서 처리함
if(callToListCnt > 200) {
int sendCnt = 0;
for(int i=0; i< callToListCnt; i++) {
//분할 발송을 체크 한 경우
if(mjonMsgVO.getDivideChk() != null) {
if(count > divideCnt) {
count = 1;
//분할 시간 간격을 증가시켜 준다.
cal.add(Calendar.MINUTE, turmMin);
dividDay = transFormat.format(cal.getTime());
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}else {
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}
}
if((i < callToListCnt -1) && sendCnt == 199) {
//sendCnt 4번째 값을 추가해준다.
tempPhoneList[sendCnt] = phoneList[i];
List<String> arrPhoneList = new ArrayList<String>();
for(String temp : tempPhoneList) {
if(temp != null) {
arrPhoneList.add(temp);
}
}
String[] sendPhoneList = new String[arrPhoneList.size()];
for(int j=0; j< arrPhoneList.size(); j++) {
sendPhoneList[j] = arrPhoneList.get(j);
}
mjonMsgVO.setCallToList(sendPhoneList);
sendCnt = 0;
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = resultSts + Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = resultBlockSts + Integer.parseInt(returnVO.getSendMsgBlockCnt());
//발송 처리후 배열 초기화
Arrays.fill(tempPhoneList, null);
dividDayList.clear();
}else if((i == callToListCnt -1) && sendCnt < 200){
//마지막 리스트의 수신번호를 추가해 준다.
tempPhoneList[sendCnt] = phoneList[i];
List<String> arrPhoneList2 = new ArrayList<String>();
for(String temp : tempPhoneList) {
if(temp != null) {
arrPhoneList2.add(temp);
}
}
String[] sendPhoneList2 = new String[arrPhoneList2.size()];
for(int j=0; j< arrPhoneList2.size(); j++) {
sendPhoneList2[j] = arrPhoneList2.get(j);
}
mjonMsgVO.setCallToList(sendPhoneList2);
sendCnt = 0;
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = resultSts + Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = resultBlockSts + Integer.parseInt(returnVO.getSendMsgBlockCnt());
}else {
tempPhoneList[sendCnt] = phoneList[i];
sendCnt++;
}
}
}else {
//분할 발송을 체크 한 경우
if(mjonMsgVO.getDivideChk() != null) {
for(int i=0; i< callToListCnt; i++) {
if(count > divideCnt) {
count = 1;
//분할 시간 간격을 증가시켜 준다.
cal.add(Calendar.MINUTE, turmMin);
dividDay = transFormat.format(cal.getTime());
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}else {
dividDayList.add(dividDay);
//tempVO.setReqDate(dividDay); //분할 문자 예약 시간 입력해주기
count++;
}
}
}
mjonMsgVO.setDividDay(dividDayList);
MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
mjonMsgVO.setAgentCode(returnVO.getAgentCode());
resultSts = Integer.parseInt(returnVO.getSendMsgCnt());
resultBlockSts = Integer.parseInt(returnVO.getSendMsgBlockCnt());
System.out.println("======================================== totPrice ::: "+mjonMsgVO.getTotPrice());
}
System.out.println("=========================================================================");
System.out.println("+++++++++++++++++++++++++++++++++++++++++++ resultSts ::: " + resultSts);
System.out.println("+++++++++++++++++++++++++++++++++++++++++++ resultBlockSts ::: " + resultBlockSts);
System.out.println("=========================================================================");
try {
//문자 발송 캐시 차감 해주기 - serviceImple에서 처리하도록 변경 함
/*MjonPayVO mjonPayVO = new MjonPayVO();
if(resultSts > 0 && resultBlockSts > 0) {
Float blockPrice = Float.parseFloat(mjonMsgVO.getEachPrice()) * resultBlockSts;
Float resultTotPrice = Float.parseFloat(mjonMsgVO.getTotPrice());
Float endPrice = resultTotPrice - blockPrice;
mjonMsgVO.setTotPrice(Float.toString(endPrice));
//수신거부가 있는 경우 총 건수에서 수신거부 건수를 차감 후 그룹 테이블에 업데이트 해준다.
int groupCnt = resultSts;
mjonMsgVO.setMsgGroupCnt(Integer.toString(groupCnt));
}
//1건 이상 발송이 있는 경우만 캐쉬를 차감 시킨다.
if(resultSts > 0) {
mjonPayVO.setCashId(idgenMjonCashId.getNextStringId());
mjonPayVO.setUserId(mjonMsgVO.getUserId());
mjonPayVO.setCash(-Float.parseFloat(mjonMsgVO.getTotPrice()));
mjonPayVO.setFrstRegisterId(mjonMsgVO.getUserId());
mjonPayVO.setMemo("SMS 문자 " + resultSts + "건 발송");
mjonPayVO.setMsgGroupId(mjonMsgVO.getMsgGroupId());
//mjonPayService.insertCash(mjonPayVO); //캐시차감
//mjonPayService.updateMemberCash(mjonPayVO); //회원정보 업데이트
}
//문자 발송 테이블에 입력 데이터가 있는 경우 그룹 테이블에도 입력 해 준다.
if(resultSts > 0) {
// 문자 전송 그룹 테이블에 정보 입력
int groupCnt = resultSts;
mjonMsgVO.setMsgGroupCnt(Integer.toString(groupCnt));
mjonMsgService.insertGroupMsgData(mjonMsgVO);
//이벤트 회원 남은 캐시 업데이트
fnUpdateEventRemainCash(mjonPayVO);
}*/
//스팸문구 포함된 문자 발송의 경우 스팸 문구 내용도 별도 저장함.
String spamStatus = mjonMsgVO.getSpamStatus();
if(spamStatus == null) {
spamStatus = "N";
mjonMsgVO.setSpamStatus("N");
}
if(spamStatus.equals("Y")) {
int resultCnt = mjonSpamMsgService.insertSpamKeyWordMsgData(mjonMsgVO);
System.out.println("+++++++++++++스팸문구 발송 내용 등록 +++++++++++++++++++++ "+resultCnt);
}
} catch (Exception e) {
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("====================================== fncSendMsg MJ_MSG_GROUP && CASH ERROR !!! ::: " + e.getMessage());
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}else {
modelAndView.addObject("message", "문자 발송에 필요한 보유 잔액이 부족 합니다.");
modelAndView.addObject("result", "fail");
modelAndView.addObject("resultSts", "0");
modelAndView.addObject("resultBlockSts", "0");
return modelAndView;
}
//문자 발송 후 남은 보유 캐시 정보 불러오기
String afterCash = mjonMsgDataService.selectBeforeCashData(mjonMsgVO);
System.out.println("afterCash :: "+ afterCash);
modelAndView.addObject("afterCash", afterCash);
}catch(Exception e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
System.out.println("=========================================================================");
System.out.println("++++++++++++++++++++++++++++++++++++++++++++기타 시스템 오류 : " + e.getMessage());
System.out.println("=========================================================================");
modelAndView.addObject("result", "fail");
modelAndView.addObject("message", "기타 시스템 오류 : " + e.getMessage());
}
modelAndView.addObject("message", "문자 전송이 완료되었습니다.");
modelAndView.addObject("result", "success");
//TODO 기존 로직에 추가해야함
modelAndView.addObject("msgType", mjonMsgVO.getMsgType());
modelAndView.addObject("msgGroupId", mjonMsgVO.getMsgGroupId());
modelAndView.addObject("resultSts", resultSts);
modelAndView.addObject("resultBlockSts", resultBlockSts);
// return ResponseEntity.ok().body(new StatusResponse(HttpStatus.OK, "성공", LocalDateTime.now()));
return modelAndView;
}
@RequestMapping(value= {"/web/user/login/fileTest.do"})
public void downloadAndSaveFile() throws Exception {
String downloadUrl = "http://192.168.0.11:5000/converHWPtoPDF";
String filePath = "D:\\Development\\test_dev";
String fileNm = "저작권분쟁조정규칙(20220516)";
// String fileNm = "testFileName(20220516)";
String fileExt = ".pdf";
String cnvtfileExt = ".jpg";
byte[] fileData = fileSendAnddownloadFile(downloadUrl, filePath + File.separator + fileNm + ".hwp");
// byte[] fileData = downloadFile(downloadUrl, fileNm);
this.saveFile(fileData, filePath, fileNm+fileExt);
this.pdfToJpg(filePath, fileNm, fileExt, cnvtfileExt);
}
/**
* @methodName : fileSendAnddownloadFile
* @author : 이호영
* @date : 2023.08.04
* @description : 파일을 보내서 PFD로 변환한 파일을 받는다
* @param downloadUrl
* @param filePathNm
* @return
* @throws IOException
*/
public byte[] fileSendAnddownloadFile(String downloadUrl, String filePathNm) throws IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// Create a ByteArrayResource to wrap the file content without relying on the file system
FileSystemResource fileResource = new FileSystemResource(filePathNm);
// To ensure correct encoding for non-ASCII characters
String encodedFilename = UriUtils.encode(fileResource.getFilename(), "UTF-8");
// Create a new HttpEntity for file and use encoded filename
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new ByteArrayResource(Files.readAllBytes(fileResource.getFile().toPath())) {
@Override
public String getFilename() {
return encodedFilename;
}
});
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(downloadUrl, HttpMethod.POST, entity, byte[].class);
if (responseEntity.getStatusCodeValue() == 200) {
return responseEntity.getBody();
} else {
throw new RuntimeException("Failed to download file from " + downloadUrl);
}
}
/**
* @methodName : downloadFile
* @author : 이호영
* @date : 2023.08.04
* @description : 서버에 파일을 요청해서 받는 형식
* @param downloadUrl
* @param fileNm
* @return
public byte[] downloadFile(String downloadUrl, String fileNm) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("fileNm", fileNm);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, headers);
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(downloadUrl, HttpMethod.POST, entity, byte[].class);
// System.out.println("responseEntity :: "+ responseEntity);
if (responseEntity.getStatusCodeValue() == 200) {
return responseEntity.getBody();
} else {
throw new RuntimeException("Failed to download file from " + downloadUrl);
}
}
*/
/**
* @methodName : saveFile
* @author : 이호영
* @date : 2023.08.04
* @description : 파일 저장
* @param fileData
* @param filePath
* @param fileNm
*/
public void saveFile(byte[] fileData, String filePath, String fileNm) {
Path path = Paths.get(filePath, fileNm);
try {
Files.write(path, fileData);
} catch (IOException e) {
throw new RuntimeException("Failed to save file to " + filePath, e);
}
}
/**
* @methodName : pdfToJpg
* @author : 이호영
* @date : 2023.08.04
* @description : 저장한 파일을 불러와서 파일명의 폴더를 생성하여 jpg로 저장
* @param filePath
* @param fileNm
* @param oriFileExt
* @param cnvtfileExt
* @throws Exception
*/
public void pdfToJpg(String filePath, String fileNm, String oriFileExt, String cnvtfileExt) throws Exception {
File file = new File(filePath + File.separator + fileNm + oriFileExt);
PDDocument document = PDDocument.load(file);
try {
int pageCount = document.getNumberOfPages();
PDFRenderer pdfRenderer = new PDFRenderer(document);
System.out.println("pageCount : "+ pageCount);
String saveFilePath = this.filePathChk(filePath + File.separator +fileNm);
if(StringUtils.isNotEmpty(saveFilePath))
{
for (int i = 0; i < pageCount; i++) {
BufferedImage imageObj = pdfRenderer.renderImageWithDPI(i, 100, ImageType.RGB);
File outputfile = new File(saveFilePath + File.separator + fileNm + i + cnvtfileExt);
ImageIO.write(imageObj, "jpg", outputfile);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}finally {
if (document != null) {
document.close();
}
}
}
/**
* @methodName : filePathChk
* @author : 이호영
* @date : 2023.08.04
* @description : jpg 파일 저장할 디렉토리 생성
* @param filePath
* @return
*/
private String filePathChk(String filePath) {
// TODO Auto-generated method stub
String directoryPath = filePath;
Path path = Paths.get(directoryPath);
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
System.out.println("Directory created");
return directoryPath;
} catch (IOException e) {
throw new RuntimeException("Failed to create directory!", e);
}
} else {
System.out.println("Directory already exists");
}
return null;
}
@RequestMapping(value="/web/mjon/test/insertAfterPayCashChargeSchedulerAjax.do")
public void testAfterPayCashCharge() throws Exception{
System.out.println("=================================testAfterPayCashCharge Start==========================================");
try {
egovUserManageService.updateUserCashByAutoCash();
} catch (Exception e) {
System.out.println("++++++++++++++ testAfterPayCashCharge Error!!! "+e);
}
}
@RequestMapping(value = "/web/mjon/test/ajaxTest.do")
public ResponseEntity<StatusResponse> ajaxTest(
@RequestParam String isSuccess,
@RequestParam String s_msg,
@RequestParam String f_msg,
@RequestParam int sleep,
HttpServletRequest request,
ModelMap model) throws Exception {
System.out.println("sleep :: "+ sleep);
int s = sleep*1000;
try {
// 3초 지연
Thread.sleep(s);
} catch (InterruptedException e) {
e.printStackTrace();
}
if("Y".equals(isSuccess)) {
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.OK, s_msg, ""));
}else {
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.BAD_REQUEST, f_msg, ""));
}
}
@RequestMapping(value = "/web/mjon/test/refundTest.do")
public ResponseEntity<StatusResponse> refundTest(
@RequestParam String p_type,
HttpServletRequest request,
ModelMap model) throws Exception {
System.out.println(" p_type :: "+p_type);
long startTime = System.nanoTime(); // 시작 시간 기록
try {
// 문자 환불
if ("ONE".equals(p_type)) { //하루에 한번만 31일 대상으로 실행
schdlrManageService.msgFailPayBackOneByDay();
}else {
// 10분 마다 1주일 데이터에서 환불 대상을 찾아서 환불 한다.
//어플리케이션 트랜잭션 문제가 있어 Util 단으로 DB 호출을 가져옴 - 2024-03-14
//schdlrManageService.msgFailPayBack();
long forBeforeTime = System.currentTimeMillis(); // 코드 실행 전 시간
List<MjonMsgVO> msgFailList = mjonMsgDataDAO.selectMsgSentFailList();
long forAfterTime1 = System.currentTimeMillis(); // 코드 실행 후 시간
long forSecDiffTime1 = (forAfterTime1 - forBeforeTime)/1000; // 코드 실행 전후 시간 차이 계산(초 단위)
System.out.println("==PayBack list =============> 수량 : "+msgFailList.size()+" ===== " + forSecDiffTime1 +"초");
// 리스트가 비어있는 경우 종료
if (msgFailList == null || msgFailList.isEmpty()) {
System.out.println("No messages to process.");
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.OK, "데이터 없음", ""));
}
// TEST
// 필요한 필드만 DTO로 매핑
List<RefundDTO> dtoList = msgFailList.stream()
// .limit(10)
.map(msg ->
new RefundDTO(
msg.getUserId()
, msg.getMsgGroupId()
, msg.getUserData()
, Integer.parseInt(msg.getUserData())
, msg.getEachPrice())
)
.collect(Collectors.toList());
System.out.println("== dtoList =============> : "+ dtoList.size());
// JSON 변환
ObjectMapper objectMapper = new ObjectMapper();
String msgFailListJson = objectMapper.writeValueAsString(dtoList);
mjonMsgDataDAO.updateMsgSentFailPayBackBatch(msgFailListJson);
long forAfterTime = System.currentTimeMillis(); // 코드 실행 후 시간
long forSecDiffTime = (forAfterTime - forBeforeTime)/1000; // 코드 실행 전후 시간 차이 계산(초 단위)
System.out.println("==PayBack for 2 =============> 수량 : "+msgFailList.size()+" ===== " + forSecDiffTime +"초");
}
}catch(Exception ex) {
ex.printStackTrace();
}
long endTime = System.nanoTime(); // 종료 시간 기록
long executionTimeInSeconds = (endTime - startTime) / 1_000_000_000; // 실행 시간 (초)
// 분과 초로 변환
long minutes = executionTimeInSeconds / 60; // 분
long seconds = executionTimeInSeconds % 60; // 초
System.out.println("Execution time: " + minutes + " minutes " + seconds + " seconds");
// return ResponseEntity.ok().body(new StatusResponse(HttpStatus.BAD_REQUEST, "", ""));
return ResponseEntity.ok().body(new StatusResponse(HttpStatus.OK, "테스트", ""));
}
}