<commit_before>package com.servinglynk.hmis.warehouse.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.servinglynk.hmis.warehouse.common.MQDateUtil;
import com.servinglynk.hmis.warehouse.core.model.ClientSurveySubmission;
import com.servinglynk.hmis.warehouse.core.model.ClientSurveySubmissions;
import com.servinglynk.hmis.warehouse.core.model.HmisPostingModel;
import com.servinglynk.hmis.warehouse.core.model.QuestionResponseModel;
import com.servinglynk.hmis.warehouse.core.model.Questionv2;
import com.servinglynk.hmis.warehouse.core.model.Response;
import com.servinglynk.hmis.warehouse.core.model.Responses;
import com.servinglynk.hmis.warehouse.core.model.Session;
import com.servinglynk.hmis.warehouse.core.model.Sort;
import com.servinglynk.hmis.warehouse.core.model.SortedPagination;
import com.servinglynk.hmis.warehouse.model.AMQEvent;
import com.servinglynk.hmis.warehouse.model.ClientEntity;
import com.servinglynk.hmis.warehouse.model.ClientSurveySubmissionEntity;
import com.servinglynk.hmis.warehouse.model.SurveyEntity;
import com.servinglynk.hmis.warehouse.service.ClientSurveySubmissionService;
import com.servinglynk.hmis.warehouse.service.converter.ClientSurveySubmissionConverter;
import com.servinglynk.hmis.warehouse.service.exception.ResourceNotFoundException;
import com.servinglynk.hmis.warehouse.util.SecurityContextUtil;

@Component
public class ClientSurveySubmissionServiceImpl extends ServiceBase implements ClientSurveySubmissionService {
	final static Logger logger = Logger.getLogger(ClientSurveySubmissionServiceImpl.class);
	
	@Transactional
	public UUID createClientSurveySubmission(UUID clientId, UUID surveyId, UUID submissionId,LocalDateTime submissionDate, String surveyCategory) {
		SurveyEntity surveyEntity = daoFactory.getSurveyDao().getSurveyById(surveyId);
		ClientEntity clientEntity = daoFactory.getClientDao().getClientById(clientId);
		ClientSurveySubmissionEntity entity = new ClientSurveySubmissionEntity();
		entity.setClientId(clientEntity);
		entity.setSubmissionId(submissionId);
		entity.setSurveyId(surveyEntity);
		entity.setSurveyCategory(surveyCategory);
		entity.setSubmissionDate(submissionDate);
		entity.setCreatedAt(LocalDateTime.now());
		entity.setUpdatedAt(LocalDateTime.now());
		entity.setUser(getUser());
		entity.setProjectGroupCode(SecurityContextUtil.getUserProjectGroup());
		UUID clientSurveySubmissionId = daoFactory.getClientSurveySubmissionDao().create(entity);
		
		// creating active mq request
		AMQEvent amqEvent = new AMQEvent();
		amqEvent.setEventType("survey.submissions");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("clientId", clientId);
		data.put("dedupClientId", clientEntity.getDedupClientId());
		data.put("submissionId", submissionId);
		data.put("surveyId",surveyId);
		data.put("submissionDate",MQDateUtil.dateTimeToString(submissionDate));
		data.put("deleted", false);
		data.put("projectGroupCode", SecurityContextUtil.getUserProjectGroup());
		data.put("userId",SecurityContextUtil.getUserAccount().getAccountId());
		amqEvent.setPayload(data);
		amqEvent.setModule("ces");
		amqEvent.setSubsystem("survey");
		messageSender.sendAmqMessage(amqEvent);
		
		return clientSurveySubmissionId;
	}
	
	@Transactional
	public void updateClientSurveySubmission(UUID clientSurveySubmissionId, ClientSurveySubmission clientSurveySubmission, Session session) {
		ClientSurveySubmissionEntity clientSurveySubmissionEntity = daoFactory.getClientSurveySubmissionDao().getById(clientSurveySubmissionId);
		if(clientSurveySubmissionEntity==null) throw new ResourceNotFoundException("Client Survey submission not found");
		clientSurveySubmissionEntity.setUpdatedAt(LocalDateTime.now());
		clientSurveySubmissionEntity.setUser(getUser());
		ClientSurveySubmissionEntity entity = ClientSurveySubmissionConverter.modelToEntity(clientSurveySubmission, clientSurveySubmissionEntity);
		
		daoFactory.getClientSurveySubmissionDao().updateClientSurveySubmission(entity);
		HmisPostingModel hmisPostingModel = buildHmisPostingModel(entity, clientSurveySubmission, clientSurveySubmissionId);

			try {
				// creating active mq request
				AMQEvent amqEvent = new AMQEvent();
				amqEvent.setEventType("survey.submissions");
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("clientId", entity.getClientId().getId());
				data.put("dedupClientId", entity.getClientId().getDedupClientId());
				data.put("submissionId", entity.getSubmissionId());
				data.put("surveyId",entity.getSurveyId().getId());
				data.put("submissionDate",MQDateUtil.dateTimeToString(entity.getSubmissionDate()));
				data.put("deleted", false);
				data.put("projectGroupCode", SecurityContextUtil.getUserProjectGroup());
				data.put("userId",SecurityContextUtil.getUserAccount().getAccountId());
				data.put("trustedAppId", session.getClientTypeId());
				data.put("sessionToken",SecurityContextUtil.getSession().getToken());
				if(hmisPostingModel !=null)
					data.put("hmisPosting", hmisPostingModel.toJSONString());
				amqEvent.setModule("ces");
				amqEvent.setSubsystem("survey");
				amqEvent.setPayload(data);
				messageSender.sendAmqMessage(amqEvent);
			} catch (Exception e) {
				logger.error(" Error posting MQ hmis.posting ", e);
			}
	}
	/***
	 * Build Hmis posting model for double posting.
	 * @param entity
	 * @param clientSurveySubmission
	 * @param clientSurveySubmissionId
	 * @return
	 */
	private HmisPostingModel buildHmisPostingModel(ClientSurveySubmissionEntity entity, ClientSurveySubmission clientSurveySubmission,UUID clientSurveySubmissionId) {
		DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyy-MM-dd");
		SurveyEntity surveyEntity = entity.getSurveyId();
		HmisPostingModel hmisPostingModel = null;
		if(clientSurveySubmission.getHmisPostingStatus() != null && surveyEntity !=null && surveyEntity.getId() != null) {
			hmisPostingModel = new HmisPostingModel();
			Responses responesBySubmissionId = serviceFactory.getResponseServiceV3().getResponsesBySubmissionId(surveyEntity.getId(), entity.getSubmissionId(), null, null);
			if(responesBySubmissionId != null) {
				if(entity.getClientId() != null) {
					hmisPostingModel.setDedupClientId(entity.getClientId().getDedupClientId());
					hmisPostingModel.setClientId(entity.getClientId().getId());
				}
				hmisPostingModel.setClientSurveySubmissionId(clientSurveySubmissionId);<commit_msg>Add logging<commit_after>package com.servinglynk.hmis.warehouse.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.servinglynk.hmis.warehouse.common.MQDateUtil;
import com.servinglynk.hmis.warehouse.core.model.ClientSurveySubmission;
import com.servinglynk.hmis.warehouse.core.model.ClientSurveySubmissions;
import com.servinglynk.hmis.warehouse.core.model.HmisPostingModel;
import com.servinglynk.hmis.warehouse.core.model.QuestionResponseModel;
import com.servinglynk.hmis.warehouse.core.model.Questionv2;
import com.servinglynk.hmis.warehouse.core.model.Response;
import com.servinglynk.hmis.warehouse.core.model.Responses;
import com.servinglynk.hmis.warehouse.core.model.Session;
import com.servinglynk.hmis.warehouse.core.model.Sort;
import com.servinglynk.hmis.warehouse.core.model.SortedPagination;
import com.servinglynk.hmis.warehouse.model.AMQEvent;
import com.servinglynk.hmis.warehouse.model.ClientEntity;
import com.servinglynk.hmis.warehouse.model.ClientSurveySubmissionEntity;
import com.servinglynk.hmis.warehouse.model.SurveyEntity;
import com.servinglynk.hmis.warehouse.service.ClientSurveySubmissionService;
import com.servinglynk.hmis.warehouse.service.converter.ClientSurveySubmissionConverter;
import com.servinglynk.hmis.warehouse.service.exception.ResourceNotFoundException;
import com.servinglynk.hmis.warehouse.util.SecurityContextUtil;

@Component
public class ClientSurveySubmissionServiceImpl extends ServiceBase implements ClientSurveySubmissionService {
	final static Logger logger = Logger.getLogger(ClientSurveySubmissionServiceImpl.class);
	
	@Transactional
	public UUID createClientSurveySubmission(UUID clientId, UUID surveyId, UUID submissionId,LocalDateTime submissionDate, String surveyCategory) {
		SurveyEntity surveyEntity = daoFactory.getSurveyDao().getSurveyById(surveyId);
		ClientEntity clientEntity = daoFactory.getClientDao().getClientById(clientId);
		ClientSurveySubmissionEntity entity = new ClientSurveySubmissionEntity();
		entity.setClientId(clientEntity);
		entity.setSubmissionId(submissionId);
		entity.setSurveyId(surveyEntity);
		entity.setSurveyCategory(surveyCategory);
		entity.setSubmissionDate(submissionDate);
		entity.setCreatedAt(LocalDateTime.now());
		entity.setUpdatedAt(LocalDateTime.now());
		entity.setUser(getUser());
		entity.setProjectGroupCode(SecurityContextUtil.getUserProjectGroup());
		UUID clientSurveySubmissionId = daoFactory.getClientSurveySubmissionDao().create(entity);
		
		// creating active mq request
		AMQEvent amqEvent = new AMQEvent();
		amqEvent.setEventType("survey.submissions");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("clientId", clientId);
		data.put("dedupClientId", clientEntity.getDedupClientId());
		data.put("submissionId", submissionId);
		data.put("surveyId",surveyId);
		data.put("submissionDate",MQDateUtil.dateTimeToString(submissionDate));
		data.put("deleted", false);
		data.put("projectGroupCode", SecurityContextUtil.getUserProjectGroup());
		data.put("userId",SecurityContextUtil.getUserAccount().getAccountId());
		amqEvent.setPayload(data);
		amqEvent.setModule("ces");
		amqEvent.setSubsystem("survey");
		messageSender.sendAmqMessage(amqEvent);
		
		return clientSurveySubmissionId;
	}
	
	@Transactional
	public void updateClientSurveySubmission(UUID clientSurveySubmissionId, ClientSurveySubmission clientSurveySubmission, Session session) {
		ClientSurveySubmissionEntity clientSurveySubmissionEntity = daoFactory.getClientSurveySubmissionDao().getById(clientSurveySubmissionId);
		if(clientSurveySubmissionEntity==null) throw new ResourceNotFoundException("Client Survey submission not found");
		clientSurveySubmissionEntity.setUpdatedAt(LocalDateTime.now());
		clientSurveySubmissionEntity.setUser(getUser());
		ClientSurveySubmissionEntity entity = ClientSurveySubmissionConverter.modelToEntity(clientSurveySubmission, clientSurveySubmissionEntity);
		logger.info("Before updating client survey submissions:"+clientSurveySubmissionId);
		daoFactory.getClientSurveySubmissionDao().updateClientSurveySubmission(entity);
		HmisPostingModel hmisPostingModel = buildHmisPostingModel(entity, clientSurveySubmission, clientSurveySubmissionId);

			try {
				// creating active mq request
				AMQEvent amqEvent = new AMQEvent();
				amqEvent.setEventType("survey.submissions");
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("clientId", entity.getClientId().getId());
				data.put("dedupClientId", entity.getClientId().getDedupClientId());
				data.put("submissionId", entity.getSubmissionId());
				data.put("surveyId",entity.getSurveyId().getId());
				data.put("submissionDate",MQDateUtil.dateTimeToString(entity.getSubmissionDate()));
				data.put("deleted", false);
				data.put("projectGroupCode", SecurityContextUtil.getUserProjectGroup());
				data.put("userId",SecurityContextUtil.getUserAccount().getAccountId());
				data.put("trustedAppId", session.getClientTypeId());
				data.put("sessionToken",SecurityContextUtil.getSession().getToken());
				if(hmisPostingModel !=null) {
					data.put("hmisPosting", hmisPostingModel.toJSONString());
					logger.info("hmisPosting :"+hmisPostingModel.toJSONString());
				}
				amqEvent.setModule("ces");
				amqEvent.setSubsystem("survey");
				amqEvent.setPayload(data);
				logger.info(" Sending survey.submissions to MQ :"+clientSurveySubmissionId);
				messageSender.sendAmqMessage(amqEvent);
			} catch (Exception e) {
				logger.error(" Error posting MQ hmis.posting ", e);
			}
	}
	/***
	 * Build Hmis posting model for double posting.
	 * @param entity
	 * @param clientSurveySubmission
	 * @param clientSurveySubmissionId
	 * @return
	 */
	private HmisPostingModel buildHmisPostingModel(ClientSurveySubmissionEntity entity, ClientSurveySubmission clientSurveySubmission,UUID clientSurveySubmissionId) {
		DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyy-MM-dd");
		SurveyEntity surveyEntity = entity.getSurveyId();
		HmisPostingModel hmisPostingModel = null;
		if(clientSurveySubmission.getHmisPostingStatus() != null && surveyEntity !=null && surveyEntity.getId() != null) {
			hmisPostingModel = new HmisPostingModel();
			Responses responesBySubmissionId = serviceFactory.getResponseServiceV3().getResponsesBySubmissionId(surveyEntity.getId(), entity.getSubmissionId(), null, null);
			if(responesBySubmissionId != null) {
				if(entity.getClientId() != null) {
					hmisPostingModel.setDedupClientId(entity.getClientId().getDedupClientId());
					hmisPostingModel.setClientId(entity.getClientId().getId());
				}
				hmisPostingModel.setClientSurveySubmissionId(clientSurveySubmissionId);
{'fraction_non_alphanumeric': 0.10855565777368906, 'fraction_numerical': 0.00042459840067935747, 'mean_word_length': 7.274004683840749, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7156559', 'n_tokens_mistral': 4602, 'n_tokens_neox': 4249, 'n_words': 585}