Commit 81d01727 authored by Cristian Aguirre's avatar Cristian Aguirre

Updating Service 'Eliminación de Datos Sensibles'

parent 4b0a2139
...@@ -33,4 +33,7 @@ public class DeploymentChannelParamValueBean { ...@@ -33,4 +33,7 @@ public class DeploymentChannelParamValueBean {
@Expose @Expose
private Long agen_id; private Long agen_id;
@Expose
private String channel;
} }
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter
public class SessionByClientBean implements Serializable {
@Expose
private BigInteger user_id;
@Expose
private BigInteger count;
}
...@@ -7,6 +7,7 @@ import lombok.Setter; ...@@ -7,6 +7,7 @@ import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Getter @Setter @Getter @Setter
...@@ -18,7 +19,5 @@ public class SummaryBean implements Serializable { ...@@ -18,7 +19,5 @@ public class SummaryBean implements Serializable {
@Expose @Expose
private BigDecimal percent; private BigDecimal percent;
@Expose @Expose
private boolean up = false; private List<ArrayList<Object>> detail_history;
@Expose
private boolean down = false;
} }
package com.bytesw.bytebot.controller; package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.provider.TwilioService; import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.BusinessExceptionHandler;
import com.bytesw.xdf.exception.NotFoundException; import com.bytesw.xdf.exception.NotFoundException;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.NullArgumentException;
import com.twilio.exception.AuthenticationException; import com.twilio.exception.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.springframework.web.context.request.WebRequest;
import javax.management.ObjectName;
import javax.validation.constraints.NotNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -26,17 +34,27 @@ public class ProviderController { ...@@ -26,17 +34,27 @@ public class ProviderController {
@Autowired @Autowired
private Gson gson; private Gson gson;
@ApiResponses(value={
@ApiResponse(code=200, message = "OK"),
@ApiResponse(code=400, message = "Bad Request. Datos de entrada inválido"),
@ApiResponse(code=401, message = "Unauthorized. Credenciales erróneas"),
@ApiResponse(code=404, message = "Not Found. Recursos no encontrados")
})
@RequestMapping(value="/twilio/messages/{sid_message}",method = {RequestMethod.DELETE}) @RequestMapping(value="/twilio/messages/{sid_message}",method = {RequestMethod.DELETE})
public ResponseEntity<String> deleteSensibleInfo(@PathVariable("sid_message") String sid_message, @RequestBody Map<String,Object> body){ public ResponseEntity<String> deleteSensibleInfo(@ApiParam(value="sid_message",required = true) @PathVariable("sid_message") String sid_message,
@ApiParam(value = "agent_id: Agente a cual eliminar su data sensible\n{\"agent_id\":1}",
example = "{agent_id:1}",required = true) @NotNull @RequestBody(required = false) Map<String,Object> body){
Map<String,Object> info = new HashMap<>(); Map<String,Object> info = new HashMap<>();
try{ try {
if(sid_message == null){ if (body == null) {
throw new InvalidInput(); log.info("Body Input Inválido");
throw new ClassCastException("Input inválido");
} }
info = twilioService.generateInfo(sid_message,body); info = twilioService.generateInfo(sid_message, body);
} }catch (ClassCastException e){
catch(NotFoundException e){ return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}catch(NotFoundException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND); return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
}catch (AuthenticationException e){ }catch (AuthenticationException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(e.getMessage(),HttpStatus.UNAUTHORIZED);
...@@ -45,10 +63,4 @@ public class ProviderController { ...@@ -45,10 +63,4 @@ public class ProviderController {
} }
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK); return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
} }
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR, reason = "Input vacío")
public class InvalidInput extends RuntimeException{
}
} }
...@@ -24,9 +24,11 @@ import java.util.Map; ...@@ -24,9 +24,11 @@ import java.util.Map;
@Log4j2 @Log4j2
public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, RowMapper<DynaBean>> { public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, RowMapper<DynaBean>> {
@Override @Override
public ItemReader<DynaBean> createReader(RowMapper<DynaBean> mapper, Map<String, Object> params) { public ItemReader<DynaBean> createReader(RowMapper<DynaBean> mapper, Map<String, Object> params) {
JdbcCursorItemReader<DynaBean> databaseReader; JdbcCursorItemReader<DynaBean> databaseReader;
databaseReader = new ByteDataBaseItemReaderFactory<>(); databaseReader = new ByteDataBaseItemReaderFactory<>();
......
...@@ -4,6 +4,8 @@ import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean; ...@@ -4,6 +4,8 @@ import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.model.enums.AgentStatusEnum; import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
...@@ -19,6 +21,7 @@ public class AgentJDBCRepository { ...@@ -19,6 +21,7 @@ public class AgentJDBCRepository {
@Qualifier("sqlSessionFactory") @Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlsession; private SqlSessionFactory sqlsession;
@Cacheable(value="deploy_agents")
public List<DeploymentChannelParamValueBean> getCredentialsFromAgentStatus(String status){ public List<DeploymentChannelParamValueBean> getCredentialsFromAgentStatus(String status){
SqlSession session = sqlsession.openSession(); SqlSession session = sqlsession.openSession();
......
package com.bytesw.bytebot.jdbc; package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.etl.model.Session;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.bytesw.bytebot.bean.SessionByClientBean;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.List;
@Component @Component
public class BotSessionJDCBRepository { public class BotSessionJDCBRepository {
...@@ -18,14 +21,14 @@ public class BotSessionJDCBRepository { ...@@ -18,14 +21,14 @@ public class BotSessionJDCBRepository {
@Qualifier("sqlSessionFactory") @Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory; private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) { public List<SessionByClientBean> countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession(); SqlSession session = sqlSessionFactory.openSession();
try { try {
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate); params.put("startDate", startDate);
params.put("endDate", endDate); params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.countSessionsInRange", params); return session.selectList("com.bytesw.bytebot.dao.jdbc.SessionMapper.countSessionsInRange", params);
} finally { } finally {
session.close(); session.close();
} }
......
...@@ -67,8 +67,6 @@ public class MessageJDBCRepository { ...@@ -67,8 +67,6 @@ public class MessageJDBCRepository {
params.put("directionSort", "DESC"); params.put("directionSort", "DESC");
} }
completeDates(params, pagination.getFilterExpression()); completeDates(params, pagination.getFilterExpression());
//params.put("startDate", startDate);
//params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntentAndSentence", params); return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntentAndSentence", params);
} finally { } finally {
session.close(); session.close();
......
...@@ -16,7 +16,7 @@ import java.io.Serializable; ...@@ -16,7 +16,7 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
@Entity @Entity
@Getter @Setter @ToString @EqualsAndHashCode(of = "id") @Getter @Setter @EqualsAndHashCode(of = "id")
@NoArgsConstructor @NoArgsConstructor
@Table(name = "avb_agent") @Table(name = "avb_agent")
@NamedQuery(name = "Agent.findByPK", query = "Select u from Agent u where u.id = ?1") @NamedQuery(name = "Agent.findByPK", query = "Select u from Agent u where u.id = ?1")
......
...@@ -9,7 +9,6 @@ import java.util.List; ...@@ -9,7 +9,6 @@ import java.util.List;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@EqualsAndHashCode(of = "id")
@NoArgsConstructor @NoArgsConstructor
@Table(name = "avb_country") @Table(name = "avb_country")
@NamedQuery(name = "Country.findByPK", query = "Select u from Country u where u.id = ?1") @NamedQuery(name = "Country.findByPK", query = "Select u from Country u where u.id = ?1")
......
...@@ -25,7 +25,6 @@ import java.util.List; ...@@ -25,7 +25,6 @@ import java.util.List;
@Table(name = "AVB_DEPLOYMENT_CHANNEL") @Table(name = "AVB_DEPLOYMENT_CHANNEL")
@Getter @Getter
@Setter @Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false) @EqualsAndHashCode(of = {"id"}, callSuper = false)
public class DeploymentChannel { public class DeploymentChannel {
......
...@@ -17,16 +17,17 @@ import javax.persistence.*; ...@@ -17,16 +17,17 @@ import javax.persistence.*;
*/ */
@Entity @Entity
@Getter @Setter @ToString @EqualsAndHashCode(of = "id") @Getter @Setter
@NoArgsConstructor @NoArgsConstructor
@Table(name = "avb_timezone") @Table(name = "avb_timezone")
@NamedQuery(name = "Timezone.findByPK", query = "Select u from Timezone u where u.id = ?1")
public class Timezone { public class Timezone {
@Id @Id
@Column(name = "tzon_id") @Column(name = "tzon_id")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_TIMEZONE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "avb_timezone_generator")
@TableGenerator(name = "AVB_TIMEZONE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "avb_timezone_generator", table = "sequence_table", pkColumnName = "seq_name", valueColumnName = "seq_count",
pkColumnValue = "AVB_TIMEZONE_SEQ", allocationSize = 1) pkColumnValue = "avb_timezone_seq", allocationSize = 1)
private Long id; private Long id;
@Column(name = "tzon_zone", nullable = false) @Column(name = "tzon_zone", nullable = false)
......
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum ChannelEnum {
WHATSAPP("WhatsApp"),
MESSENGER("Facebook Messenger");
private static final Map<String, ChannelEnum> map = new HashMap<>();
private String name;
ChannelEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (ChannelEnum type : ChannelEnum.values()) {
map.put(type.name, type);
}
}
public static ChannelEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.repository; package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannelParamValue; import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
/** /**
...@@ -14,5 +15,5 @@ import org.springframework.data.repository.CrudRepository; ...@@ -14,5 +15,5 @@ import org.springframework.data.repository.CrudRepository;
* Confidencial y debe usarla de acuerdo con los términos de aceptación de * Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
public interface DeploymentChannelParamValueRepository extends CrudRepository<DeploymentChannelParamValue, Long> {
} public interface DeploymentChannelParamValueRepository extends CrudRepository<DeploymentChannelParamValue, Long> { }
...@@ -10,6 +10,8 @@ import com.bytesw.xdf.sql.beans.Pagination; ...@@ -10,6 +10,8 @@ import com.bytesw.xdf.sql.beans.Pagination;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
import org.apache.camel.ProducerTemplate; import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
...@@ -58,7 +60,6 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -58,7 +60,6 @@ public class AgentService extends CustomPaginationService<Agent> {
@Autowired @Autowired
private ProducerTemplate producerTemplate; private ProducerTemplate producerTemplate;
public List<DeploymentChannelParamValueBean> GetKeysFromAgents(AgentStatusEnum status){ public List<DeploymentChannelParamValueBean> GetKeysFromAgents(AgentStatusEnum status){
List<DeploymentChannelParamValueBean> values = agentJDBCRepository.getCredentialsFromAgentStatus(status.getName()); List<DeploymentChannelParamValueBean> values = agentJDBCRepository.getCredentialsFromAgentStatus(status.getName());
...@@ -110,6 +111,7 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -110,6 +111,7 @@ public class AgentService extends CustomPaginationService<Agent> {
} }
@Transactional(propagation = Propagation.REQUIRED) @Transactional(propagation = Propagation.REQUIRED)
@CacheEvict(value="deploy_agents",allEntries = true)
public void save(AgentBean agent) { public void save(AgentBean agent) {
boolean isModify = true; boolean isModify = true;
...@@ -276,7 +278,6 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -276,7 +278,6 @@ public class AgentService extends CustomPaginationService<Agent> {
deploymentChannelBD.setName(agentBD.getName() + "_" + UUID.randomUUID()); deploymentChannelBD.setName(agentBD.getName() + "_" + UUID.randomUUID());
deploymentChannelBD.setChannel(null); deploymentChannelBD.setChannel(null);
} }
deploymentChannelRepository.save(deploymentChannelBD); deploymentChannelRepository.save(deploymentChannelBD);
// Deployment Channel parameters // Deployment Channel parameters
...@@ -332,6 +333,7 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -332,6 +333,7 @@ public class AgentService extends CustomPaginationService<Agent> {
} else { } else {
deploymentChannelParamValue.setParameter(null); deploymentChannelParamValue.setParameter(null);
} }
log.debug("SE GUARDO DEPLOYMEN: "+deploymentChannelBD);
deploymentChannelParamValueRepository.save(deploymentChannelParamValue); deploymentChannelParamValueRepository.save(deploymentChannelParamValue);
} }
......
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import com.bytesw.bytebot.service.AgentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import com.bytesw.bytebot.repository.AgentRepository;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@Component
@Transactional
public class ProviderStartupService implements ApplicationRunner {
@Autowired
private AgentService agentService;
@Autowired
private AgentRepository agentRepository;
public static List<DeploymentChannelParamValueBean> agents = new ArrayList<>();
@Override
public void run(ApplicationArguments args) throws Exception{
log.debug("Iinitial agents");
List<DeploymentChannelParamValueBean> agentsBD;
agents = agentService.GetKeysFromAgents(AgentStatusEnum.DEPLOYED);
log.debug(agents);
}
}
...@@ -10,6 +10,8 @@ import org.springframework.stereotype.Service; ...@@ -10,6 +10,8 @@ import org.springframework.stereotype.Service;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
...@@ -26,7 +28,7 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -26,7 +28,7 @@ public class CustomerInteractionDashboardService extends DashboardService {
private ActionJDBCRepository actionJDBCRepository; private ActionJDBCRepository actionJDBCRepository;
@Override @Override
protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Map<String, Object> info) { protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Integer rangeMinutes,Map<String, Object> info) {
List<RangeBean> rangeList = calculateRangeList(startDate, endDate); List<RangeBean> rangeList = calculateRangeList(startDate, endDate);
info.put("sessionFlow", generateInteractionByCustomerData(startDate, endDate)); info.put("sessionFlow", generateInteractionByCustomerData(startDate, endDate));
info.put("summaryGoals", generateSummaryByGoals(startDate, endDate)); info.put("summaryGoals", generateSummaryByGoals(startDate, endDate));
...@@ -60,11 +62,15 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -60,11 +62,15 @@ public class CustomerInteractionDashboardService extends DashboardService {
return data; return data;
} }
private List<Double> generateAverageIntentsByCustomer(List<RangeBean> rangeList) { private List<Object[]> generateAverageIntentsByCustomer(List<RangeBean> rangeList) {
List<Double> averageList = new ArrayList<>(); List<Object[]> averageList = new ArrayList<>();
rangeList.stream().forEach(x -> { rangeList.stream().forEach(x -> {
LocalDateTime times = x.getStartDate().toLocalDateTime().plusHours(12);
Long timestamp = Timestamp.valueOf(times).getTime();
Double avg = messageJDBCRepository.avgIntentsByCustomerAndRange(x.getStartDate(), x.getEndDate()); Double avg = messageJDBCRepository.avgIntentsByCustomerAndRange(x.getStartDate(), x.getEndDate());
averageList.add(avg != null ? round(avg) : Double.valueOf(0)); if(avg!=null){
averageList.add(new Object[]{timestamp,avg});
}
}); });
return averageList; return averageList;
} }
......
...@@ -15,7 +15,8 @@ import java.util.Map; ...@@ -15,7 +15,8 @@ import java.util.Map;
@Log4j2 @Log4j2
public abstract class DashboardService { public abstract class DashboardService {
abstract void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Map<String, Object> info); abstract void completeData(OffsetDateTime startDate, OffsetDateTime endDate,
Integer rangeMinutes, Map<String, Object> info);
public Map<String, Object> generateInfo(Map<String, Object> params) { public Map<String, Object> generateInfo(Map<String, Object> params) {
...@@ -27,12 +28,13 @@ public abstract class DashboardService { ...@@ -27,12 +28,13 @@ public abstract class DashboardService {
OffsetDateTime startDate = convertToOffsetDatetime((String) params.get("startDate")); OffsetDateTime startDate = convertToOffsetDatetime((String) params.get("startDate"));
OffsetDateTime endDate = convertToOffsetDatetime((String) params.get("endDate")); OffsetDateTime endDate = convertToOffsetDatetime((String) params.get("endDate"));
Integer rangeMinutes = (Integer)params.get("rangeMinutes");
if (startDate == null || endDate == null) { if (startDate == null || endDate == null) {
return info; return info;
} }
this.completeData(startDate, endDate, info); this.completeData(startDate, endDate, rangeMinutes, info);
return info; return info;
} }
...@@ -76,6 +78,29 @@ public abstract class DashboardService { ...@@ -76,6 +78,29 @@ public abstract class DashboardService {
return nextDate; return nextDate;
} }
protected List<RangeBean> calculateMinutesRangeList(OffsetDateTime startDate, OffsetDateTime endDate, Integer range){
List<RangeBean> rangeList = new ArrayList<>();
log.debug("START: "+startDate);
log.debug("END: "+endDate);
log.debug("PERIOD: "+range);
OffsetDateTime nextRange = startDate.plusMinutes(range);
OffsetDateTime startNextRange = startDate;
while(nextRange.isBefore(endDate)){
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextRange);
rangeBean.setEndDate(nextRange);
rangeList.add(rangeBean);
startNextRange = nextRange;
nextRange = nextRange.plusMinutes(range);
//log.debug("DATE: "+rangeBean.getStartDate());
}
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextRange);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
return rangeList;
}
protected List<RangeBean> calculateRangeList(OffsetDateTime startDate, OffsetDateTime endDate) { protected List<RangeBean> calculateRangeList(OffsetDateTime startDate, OffsetDateTime endDate) {
OffsetDateTime nextDate = getNextDay(startDate); OffsetDateTime nextDate = getNextDay(startDate);
OffsetDateTime startNextDate = startDate; OffsetDateTime startNextDate = startDate;
......
...@@ -3,24 +3,26 @@ package com.bytesw.bytebot.service.dashboard; ...@@ -3,24 +3,26 @@ package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.AverageBean; import com.bytesw.bytebot.bean.AverageBean;
import com.bytesw.bytebot.bean.RangeBean; import com.bytesw.bytebot.bean.RangeBean;
import com.bytesw.bytebot.bean.SummaryBean; import com.bytesw.bytebot.bean.SummaryBean;
import com.bytesw.bytebot.bean.SessionByClientBean;
import com.bytesw.bytebot.jdbc.BotSessionJDCBRepository; import com.bytesw.bytebot.jdbc.BotSessionJDCBRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository; import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.bytebot.jdbc.ResponseJDBCRepository; import com.bytesw.bytebot.jdbc.ResponseJDBCRepository;
import com.bytesw.xdf.exception.NotFoundException; import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.management.ObjectName;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.Duration; import java.time.*;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Log4j2
@Service @Service
public class OperativeDashboardService extends DashboardService { public class OperativeDashboardService extends DashboardService {
...@@ -34,16 +36,19 @@ public class OperativeDashboardService extends DashboardService { ...@@ -34,16 +36,19 @@ public class OperativeDashboardService extends DashboardService {
private ResponseJDBCRepository responseJDBCRepository; private ResponseJDBCRepository responseJDBCRepository;
@Override @Override
protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Map<String, Object> info) { protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Integer rangeMinutes,Map<String, Object> info) {
List<RangeBean> rangeList = calculateRangeList(startDate, endDate); List<RangeBean> rangeList = calculateRangeList(startDate, endDate);
List<RangeBean> rangeMinutsList = calculateMinutesRangeList(startDate,endDate,rangeMinutes);
List<Object[]> messageByActivity = generateData(rangeList); List<Object[]> messageByActivity = generateData(rangeList);
//Cantidad de sesiones //Cantidad de sesiones
int cantSessions = botSessionJDCBRepository.countSessionInRange(startDate, endDate); List<SessionByClientBean> sessions_by_user = botSessionJDCBRepository.countSessionInRange(startDate, endDate);
int cantReceivedMessages = messageJDBCRepository.countSessionInRange(startDate, endDate); // Mensajes recibidos
List<Object[]> recivedMessages = generateDataVariablePeriod(rangeMinutsList,true);
int cantResponseMessages = responseJDBCRepository.countSessionInRange(startDate, endDate); // Mensajes enviados
List<Object[]> responseMessages = generateDataVariablePeriod(rangeMinutsList,false);
//Promedio primera respuesta en mili //Promedio primera respuesta en mili
Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate); Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate);
...@@ -65,54 +70,29 @@ public class OperativeDashboardService extends DashboardService { ...@@ -65,54 +70,29 @@ public class OperativeDashboardService extends DashboardService {
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault()); OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate); Duration difference = Duration.between(lastSessionDate, endDate);
// Adjuntando tiempo de inactividad
SummaryBean sessionInactivity = new SummaryBean(); SummaryBean sessionInactivity = new SummaryBean();
sessionInactivity.setValue(new BigInteger(String.valueOf(difference.getSeconds()))); sessionInactivity.setValue(new BigInteger(String.valueOf(difference.getSeconds())));
sessionInactivity.setHistory(new ArrayList<>());
sessionInactivity.setPercent(new BigDecimal("1.2"));
sessionInactivity.getHistory().add(new BigInteger("10"));
sessionInactivity.getHistory().add(new BigInteger("10"));
sessionInactivity.getHistory().add(new BigInteger("10"));
sessionInactivity.getHistory().add(new BigInteger("10"));
sessionInactivity.getHistory().add(new BigInteger("10"));
// Adjutando el total de sesiones por cliente
SummaryBean totalSessions = new SummaryBean(); SummaryBean totalSessions = new SummaryBean();
totalSessions.setValue(new BigInteger(String.valueOf(cantSessions))); totalSessions.setDetail_history(new ArrayList<>());
totalSessions.setHistory(new ArrayList<>()); sessions_by_user.stream().forEach(x ->{
totalSessions.setPercent(new BigDecimal("1.2")); ArrayList<Object> session = new ArrayList<Object>();
totalSessions.getHistory().add(new BigInteger("2")); session.add(x.getUser_id());
totalSessions.getHistory().add(new BigInteger("4")); session.add(x.getCount());
totalSessions.getHistory().add(new BigInteger("6")); totalSessions.getDetail_history().add(session);
totalSessions.getHistory().add(new BigInteger("8")); });
totalSessions.getHistory().add(new BigInteger("10"));
SummaryBean totalReceivedMessages = new SummaryBean();
totalReceivedMessages.setValue(new BigInteger(String.valueOf(cantReceivedMessages)));
totalReceivedMessages.setHistory(new ArrayList<>());
totalReceivedMessages.setPercent(new BigDecimal("1.2"));
totalReceivedMessages.getHistory().add(new BigInteger("10"));
totalReceivedMessages.getHistory().add(new BigInteger("8"));
totalReceivedMessages.getHistory().add(new BigInteger("6"));
totalReceivedMessages.getHistory().add(new BigInteger("8"));
totalReceivedMessages.getHistory().add(new BigInteger("10"));
SummaryBean totalSentMessages = new SummaryBean();
totalSentMessages.setValue(new BigInteger(String.valueOf(cantResponseMessages)));
totalSentMessages.setHistory(new ArrayList<>());
totalSentMessages.setPercent(new BigDecimal("1.2"));
totalSentMessages.getHistory().add(new BigInteger("2"));
totalSentMessages.getHistory().add(new BigInteger("5"));
totalSentMessages.getHistory().add(new BigInteger("10"));
totalSentMessages.getHistory().add(new BigInteger("5"));
totalSentMessages.getHistory().add(new BigInteger("2"));
// Adjuntamos los mensajes recibidos
info.put("totalReceivedMessages", recivedMessages);
// Adjuntamos los mensajes enviados
info.put("totalSentMessages",responseMessages);
Map<String, Object> summary = new HashMap<>(); Map<String, Object> summary = new HashMap<>();
summary.put("sessionInactivity", sessionInactivity); summary.put("sessionInactivity", sessionInactivity);
summary.put("totalSessions", totalSessions); summary.put("totalSessions", totalSessions);
summary.put("totalReceivedMessages", totalReceivedMessages);
summary.put("totalSentMessages", totalSentMessages);
AverageBean averageBean = new AverageBean(); AverageBean averageBean = new AverageBean();
if (avgFirstResponse == null) { if (avgFirstResponse == null) {
...@@ -126,6 +106,32 @@ public class OperativeDashboardService extends DashboardService { ...@@ -126,6 +106,32 @@ public class OperativeDashboardService extends DashboardService {
info.put("customerMessageDetail", messageByActivity); info.put("customerMessageDetail", messageByActivity);
} }
private List<Object[]> generateDataVariablePeriod(List<RangeBean> rangeList, boolean recieved){
List<Object[]> data = new ArrayList<>();
Map<Long,Map<Integer,Integer>> accumulated = new HashMap<>();
int cont = 0;
for (RangeBean range: rangeList){
int cant = 0;
if(recieved){
cant = messageJDBCRepository.countMessageInRangeHour(range.getStartDate(),range.getEndDate());
}else{
cant = responseJDBCRepository.countSessionInRange(range.getStartDate(),range.getEndDate());
}
LocalDateTime times = range.getStartDate().toLocalDateTime();
Long timestamp = Timestamp.valueOf(times).getTime();
if(!accumulated.containsKey(timestamp)){
accumulated.put(timestamp, new HashMap<>());
}
accumulated.get(timestamp).put(cont,cant);
cont++;
}
accumulated.keySet().stream().forEach(x ->{
accumulated.get(x).keySet().stream().forEach(y ->{
data.add(new Object[]{x, accumulated.get(x).get(y)});
});
});
return data;
}
private List<Object[]> generateData(List<RangeBean> rangeList) { private List<Object[]> generateData(List<RangeBean> rangeList) {
List<Object[]> data = new ArrayList<>(); List<Object[]> data = new ArrayList<>();
Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>(); Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>();
......
...@@ -25,8 +25,9 @@ public abstract class ProviderService { ...@@ -25,8 +25,9 @@ public abstract class ProviderService {
this.completeData(info, sid, agen_id); this.completeData(info, sid, agen_id);
}catch (NotFoundException e){ }catch (NotFoundException e){
throw new NotFoundException(e.getMessage()); throw new NotFoundException(e.getMessage());
}catch (java.lang.NullPointerException e){ }catch (java.lang.ClassCastException e){
throw new NullArgumentException("Entradas vacías"); log.info("Body Input inválido");
throw new ClassCastException("Input inválido");
}catch (AuthenticationException e){ }catch (AuthenticationException e){
throw new AuthenticationException(e.getMessage()); throw new AuthenticationException(e.getMessage());
}catch (InternalError e){ }catch (InternalError e){
......
...@@ -2,7 +2,10 @@ package com.bytesw.bytebot.service.provider; ...@@ -2,7 +2,10 @@ package com.bytesw.bytebot.service.provider;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean; import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.model.enums.AgentParameterEnum; import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.ChannelEnum;
import com.bytesw.bytebot.model.enums.ProviderErrorEnum; import com.bytesw.bytebot.model.enums.ProviderErrorEnum;
import com.bytesw.bytebot.service.AgentService;
import com.bytesw.xdf.exception.NotFoundException; import com.bytesw.xdf.exception.NotFoundException;
import com.twilio.http.TwilioRestClient; import com.twilio.http.TwilioRestClient;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
...@@ -12,36 +15,57 @@ import org.springframework.stereotype.Service; ...@@ -12,36 +15,57 @@ import org.springframework.stereotype.Service;
import com.twilio.Twilio; import com.twilio.Twilio;
import com.twilio.base.ResourceSet; import com.twilio.base.ResourceSet;
import com.twilio.rest.api.v2010.account.message.Media; import com.twilio.rest.api.v2010.account.message.Media;
import com.bytesw.bytebot.service.ProviderStartupService;
import java.util.Arrays; import java.util.*;
import java.util.HashMap;
import java.util.Map;
@Log4j2 @Log4j2
@Service @Service
public class TwilioService extends ProviderService{ public class TwilioService extends ProviderService{
@Autowired @Autowired
private ProviderStartupService providerStartupService; private AgentService agentService;
public List<DeploymentChannelParamValueBean> getAllParamsWithRefresh(){
return getAllParams();
}
public List<DeploymentChannelParamValueBean> getAllParams(){
List<DeploymentChannelParamValueBean> agents = new ArrayList<>();
agents = agentService.GetKeysFromAgents(AgentStatusEnum.DEPLOYED);
log.debug("AGENTS FROM DB: "+agents);
return agents;
}
@Override @Override
protected void completeData(Map<String, Object> info, String SmsId,int agent_id) throws AuthenticationException{ protected void completeData(Map<String, Object> info, String SmsId,int agent_id) throws AuthenticationException{
long start_time = System.nanoTime();
List<DeploymentChannelParamValueBean> agents = getAllParamsWithRefresh();
long end_time = System.nanoTime();
long duration = (end_time - start_time) / 1000000;
log.debug("DURACION: "+duration);
String sid = new String(); String sid = new String();
String token = new String(); String token = new String();
int MAX_LIMIT = 999; int MAX_LIMIT = 999;
Map<String,Object> data = new HashMap<>(); Map<String,Object> data = new HashMap<>();
log.debug(agents);
try { try {
boolean exist_agent = false; boolean exist_agent = false;
for (DeploymentChannelParamValueBean agent : providerStartupService.agents) { for (DeploymentChannelParamValueBean agent : agents) {
if (agent.getAgen_id() == agent_id) { if (agent.getAgen_id() == agent_id && agent.getChannel().equals(ChannelEnum.WHATSAPP.getName())) {
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_ID.getName())) { if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_ID.getName())) {
sid = agent.getValue(); sid = agent.getValue();
} }
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_TOKEN.getName())) { if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_TOKEN.getName())) {
token = agent.getValue(); token = agent.getValue();
} }
exist_agent = true;
}
} }
log.debug("EXISTE AGENT: "+exist_agent);
if(!exist_agent){
log.info("No existe un agente con el ID especificado");
throw new NotFoundException("No se encontró un agente con canales deployados con dicho ID");
} }
String[] images_droped = new String[MAX_LIMIT]; String[] images_droped = new String[MAX_LIMIT];
Twilio.init(sid, token); Twilio.init(sid, token);
...@@ -54,20 +78,24 @@ public class TwilioService extends ProviderService{ ...@@ -54,20 +78,24 @@ public class TwilioService extends ProviderService{
cont++; cont++;
} }
if (cont == 0) { if (cont == 0) {
log.info("No hay imágenes para el mensaje indicado");
throw new NotFoundException("No se encontraron imágenes para dicho mensaje"); throw new NotFoundException("No se encontraron imágenes para dicho mensaje");
} else { } else {
data.put("images_droped", Arrays.copyOfRange(images_droped, 0, cont)); data.put("images_droped", Arrays.copyOfRange(images_droped, 0, cont));
} }
info.put("status", "success"); info.put("status", "success");
info.put("data", data); info.put("data", data);
}catch (com.twilio.exception.ApiException e){ }catch (com.twilio.exception.ApiException e){
if (e.getMessage().toString().equals(ProviderErrorEnum.AUTHENTICATE.getName())){ if (e.getMessage().toString().equals(ProviderErrorEnum.AUTHENTICATE.getName())){
log.error("Credenciales inválidas para borrar imagen");
throw new AuthenticationException("Credenciales inválidas"); throw new AuthenticationException("Credenciales inválidas");
}else if(e.getMessage().toString().contains(ProviderErrorEnum.CONEXION.getName())){ }else if(e.getMessage().toString().contains(ProviderErrorEnum.CONEXION.getName())){
log.error("Fallo temporal en la conexión con el Proveedor");
throw new InternalError("Fallo en la conexión con Twilio API"); throw new InternalError("Fallo en la conexión con Twilio API");
}else{ }else{
throw new NotFoundException("No se encontro el mensaje para dicho Sid"); log.info("El mensaje no existe para tal SID");
throw new NotFoundException("No se encontro el mensaje en el Proveedor");
} }
} }
} }
......
...@@ -55,7 +55,7 @@ application: ...@@ -55,7 +55,7 @@ application:
multi-tenant-conf: multi-tenant-conf:
exclude-service: / exclude-service: /
authorization-service.url: http://localhost:17580 authorization-service.url: http://localhost:17580
security: oauth2sso # none, basic, oauth2sso security: none # none, basic, oauth2sso
security.method: true security.method: true
security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot
messaging: messaging:
......
...@@ -8,11 +8,13 @@ ...@@ -8,11 +8,13 @@
SELECT chpv_id as id, SELECT chpv_id as id,
chpa_label as channelParamName, chpa_label as channelParamName,
chpv_value as value, chpv_value as value,
AG.agen_id as agen_id AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id JOIN avb_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status} WHERE agen_state=#{status}
</select> </select>
</mapper> </mapper>
...@@ -28,8 +28,13 @@ ...@@ -28,8 +28,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate} AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY ${columnSort} ${directionSort} LIMIT ${initLimit},${itemsForPage} ORDER BY ${columnSort} ${directionSort} LIMIT ${initLimit},${itemsForPage}
</select> </select>
...@@ -43,8 +48,13 @@ ...@@ -43,8 +48,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate} AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY count DESC) as AVB_SUMMARY ORDER BY count DESC) as AVB_SUMMARY
</select> </select>
...@@ -56,8 +66,13 @@ ...@@ -56,8 +66,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4 ORDER BY count DESC LIMIT 4
</select> </select>
...@@ -86,9 +101,16 @@ ...@@ -86,9 +101,16 @@
<select id="countByIntentAndRange" resultType="int" flushCache="true"> <select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(M.MESSA_ID)
FROM AVB_MESSAGE FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
left join avb_blacklist_params abkp
on abkp.inten_id=I.inten_id
left join avb_blacklist abk
on abk.blis_id=abkp.blis_id
WHERE INTEN_ID IS NOT NULL WHERE INTEN_ID IS NOT NULL
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select> </select>
...@@ -123,7 +145,7 @@ ...@@ -123,7 +145,7 @@
</select> </select>
<select id="countCustomersBySentence" resultType="Double" flushCache="true"> <select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID) SELECT COUNT(distinct USER_ID)
FROM AVB_SESSION FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence}) WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
......
...@@ -12,11 +12,14 @@ ...@@ -12,11 +12,14 @@
ORDER BY SESSION_LEDAT DESC LIMIT 1 ORDER BY SESSION_LEDAT DESC LIMIT 1
</select> </select>
<select id="countSessionsInRange" resultType="int" flushCache="true"> <select id="countSessionsInRange" resultType="SessionByClient" flushCache="true">
select COUNT(SESSION_ID) select bas.user_id as user_id,
count(session_id) as count
FROM AVB_SESSION bas FROM AVB_SESSION bas
join avb_user au on au.user_id=bas.user_id
WHERE SESSION_LEDAT &lt;= #{endDate} WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate} AND SESSION_LEDAT &gt;= #{startDate}
group by bas.user_id
</select> </select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true"> <select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
......
...@@ -8,11 +8,13 @@ ...@@ -8,11 +8,13 @@
SELECT chpv_id as id, SELECT chpv_id as id,
chpa_label as channelParamName, chpa_label as channelParamName,
chpv_value as value, chpv_value as value,
AG.agen_id as agen_id AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id JOIN AVB_CHANNEL_PARAM ACP ON ACP.chpa_id=ADCP.chpa_id
JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id JOIN avb_deployment_channel AD on AD.dcha_id=ADCP.dcha_id
JOIN avb_agent AG on AG.agen_id=AD.agen_id JOIN avb_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status} WHERE agen_state=#{status}
</select> </select>
</mapper> </mapper>
...@@ -28,8 +28,13 @@ ...@@ -28,8 +28,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate} AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit} ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit}
</select> </select>
...@@ -43,8 +48,13 @@ ...@@ -43,8 +48,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate} AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY M.MESSA_CONT, I.INTEN_ID GROUP BY M.MESSA_CONT, I.INTEN_ID
ORDER BY count DESC) as AVB_SUMMARY ORDER BY count DESC) as AVB_SUMMARY
</select> </select>
...@@ -56,8 +66,13 @@ ...@@ -56,8 +66,13 @@
FROM AVB_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
LEFT JOIN avb_blacklist_params ABKP
ON ABKP.inten_id=I.inten_id
LEFT JOIN avb_blacklist ABK
ON abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL WHERE M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4 ORDER BY count DESC LIMIT 4
</select> </select>
...@@ -86,9 +101,16 @@ ...@@ -86,9 +101,16 @@
<select id="countByIntentAndRange" resultType="int" flushCache="true"> <select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(M.MESSA_ID)
FROM AVB_MESSAGE FROM AVB_MESSAGE M
WHERE INTEN_ID IS NOT NULL LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID
left join avb_blacklist_params abkp
on abkp.inten_id=I.inten_id
left join avb_blacklist abk
on abk.blis_id=abkp.blis_id
WHERE M.INTEN_ID IS NOT NULL
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select> </select>
......
...@@ -12,11 +12,14 @@ ...@@ -12,11 +12,14 @@
ORDER BY SESSION_LEDAT DESC LIMIT 1 ORDER BY SESSION_LEDAT DESC LIMIT 1
</select> </select>
<select id="countSessionsInRange" resultType="int" flushCache="true"> <select id="countSessionsInRange" resultType="SessionByClient" flushCache="true">
select COUNT(SESSION_ID) select bas.user_id as user_id,
count(session_id) as count
FROM AVB_SESSION bas FROM AVB_SESSION bas
join avb_user au on au.user_id=bas.user_id
WHERE SESSION_LEDAT &lt;= #{endDate} WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate} AND SESSION_LEDAT &gt;= #{startDate}
group by bas.user_id
</select> </select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true"> <select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
......
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
<typeAlias type="com.bytesw.bytebot.bean.ActionSummaryByGoalBean" alias="ActionSummaryByGoal"/> <typeAlias type="com.bytesw.bytebot.bean.ActionSummaryByGoalBean" alias="ActionSummaryByGoal"/>
<typeAlias type="com.bytesw.bytebot.bean.MessageByIntentBean" alias="MessageByIntent"/> <typeAlias type="com.bytesw.bytebot.bean.MessageByIntentBean" alias="MessageByIntent"/>
<typeAlias type="com.bytesw.bytebot.bean.DeploymentChannelParamValueBean" alias="DeploymentChannelParamValue"/> <typeAlias type="com.bytesw.bytebot.bean.DeploymentChannelParamValueBean" alias="DeploymentChannelParamValue"/>
<typeAlias type="com.bytesw.bytebot.bean.SessionByClientBean" alias="SessionByClient"/>
<typeAlias type="com.bytesw.bytebot.etl.beans.SessionBean" alias="Session"/> <typeAlias type="com.bytesw.bytebot.etl.beans.SessionBean" alias="Session"/>
</typeAliases> </typeAliases>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment