Commit 2475de3e authored by Roberto Loayza Miljanovich's avatar Roberto Loayza Miljanovich

Merge branch 'dev_marcos' into 'developer'

Merge To Developer

See merge request ByteBot/web/bytebot-service!12
parents fff3f7b6 1aaa0bc6
...@@ -240,6 +240,12 @@ ...@@ -240,6 +240,12 @@
<groupId>org.mybatis</groupId> <groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId> <artifactId>mybatis-spring</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.twilio.sdk/twilio -->
<dependency>
<groupId>com.twilio.sdk</groupId>
<artifactId>twilio</artifactId>
<version>8.22.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
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;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterBean implements Serializable {
@Expose private BigInteger id;
@Expose private long version;
@Expose private String key;
@Expose private String description;
@Expose private String required;
@Expose private String defaultValue;
@Expose private String currentValue;
@Expose private OffsetDateTime dateFrom;
@Expose private OffsetDateTime dateApplyFrom;
@Expose private String programmedValue;
@Expose private BigInteger currentConfigurationId;
@Expose private BigInteger programmedConfigurationId;
}
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;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterConfigurationBean implements Serializable {
@Expose private BigInteger id;
@Expose private long version;
@Expose private OffsetDateTime from;
@Expose private OffsetDateTime to;
@Expose private String value;
@Expose private String programmedValue;
@Expose private BusinessParameterBean businessParameters;
@Expose private BigInteger currentConfigurationId;
@Expose private BigInteger programmedConfigurationId;
}
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;
import java.time.OffsetDateTime;
@Getter @Setter
public class BusinessParameterValueBean implements Serializable {
@Expose private String key;
@Expose private String description;
@Expose private boolean required;
@Expose private String defaultValue;
@Expose private String value;
@Expose private OffsetDateTime from;
@Expose private BigInteger id;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
@Getter
@Setter
public class CalendarBean implements Serializable {
@Expose
private String id;
@Expose
private long version;
@Expose
private String name;
//@TODO: Revisar List<WeekScheduler> weekSchedulerList de la clase Calendar
@Expose
private List<WeekSchedulerBean> weekSchedulerBeanList;
@Expose
private List<CalendarExceptionBean> calendarExceptionBeanList;
}
\ No newline at end of file
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@Getter
@Setter
public class CalendarExceptionBean {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private String description;
@Expose
private CalendarBean calendar;
@Expose
private String calendarExceptionType;
//Frecuencia
@Expose
private String frequencyType;
//annualCalendar y UniqueWeekly
@Expose
private int month;
@Expose
private int dayOfMonth;
@Expose
private int weekOfMonth;
@Expose
private int dayOfWeek;
//UniqueCalendar
@Expose
private LocalDate date;
//rangeCalendar
@Expose
private OffsetDateTime from;
@Expose
private OffsetDateTime to;
@Expose
private boolean delete;
}
...@@ -35,6 +35,7 @@ public class CountryBean { ...@@ -35,6 +35,7 @@ public class CountryBean {
@Expose @Expose
private List<String> timezones; private List<String> timezones;
public static CountryBean clone(Country country) { public static CountryBean clone(Country country) {
CountryBean bean = new CountryBean(); CountryBean bean = new CountryBean();
......
...@@ -30,4 +30,10 @@ public class DeploymentChannelParamValueBean { ...@@ -30,4 +30,10 @@ public class DeploymentChannelParamValueBean {
@Expose @Expose
private String value; private String value;
@Expose
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;
@Getter
@Setter
public class ProcessETLBean implements Serializable {
@Expose
private int id;
@Expose
private String name;
@Expose
private long version;
}
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 SchedulerTaskBean implements Serializable {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private String description;
@Expose
private String internals;
@Expose
private String cronExpression;
@Expose
private String stringParameters;
@Expose
private String calendarID;
@Expose
private String calendarName;
// @Expose
// private int idEtl;
}
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 String sender_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
...@@ -14,11 +15,7 @@ public class SummaryBean implements Serializable { ...@@ -14,11 +15,7 @@ public class SummaryBean implements Serializable {
@Expose @Expose
private BigInteger value; private BigInteger value;
@Expose @Expose
private List<BigInteger> history;
@Expose
private BigDecimal percent; private BigDecimal percent;
@Expose @Expose
private boolean up = false; private List<ArrayList<Object>> history;
@Expose
private boolean down = false;
} }
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
@Getter
@Setter
public class WeekSchedulerBean {
@Expose
private BigInteger id;
@Expose
private long version;
@Expose
private int dayOfWeek;
@Expose
private OffsetDateTime from;
@Expose
private OffsetDateTime to;
@Expose
private String calendarID;
@Expose
private String calendarName;
}
...@@ -7,14 +7,12 @@ import com.bytesw.bytebot.http.FileValidationResponse; ...@@ -7,14 +7,12 @@ import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.service.AgentService; import com.bytesw.bytebot.service.AgentService;
import com.bytesw.bytebot.service.FileManagementService; import com.bytesw.bytebot.service.FileManagementService;
import com.bytesw.xdf.annotation.ProgramSecurity; import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import com.bytesw.xdf.sql.beans.Pagination; import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
import java.security.Principal; import java.security.Principal;
import java.time.LocalDate;
import java.util.UUID; import java.util.UUID;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
......
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.BusinessParameterConfigurationService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigInteger;
@RestController()
@RequestMapping("/service/settings/business-parameter-configuration")
@ProgramSecurity("BUSINESS_PARAMETERS_CONFIGURATION")
@Log4j2
public class BusinessParameterConfigurationController extends XDFController<BusinessParameterConfigurationBean, BigInteger> {
public BusinessParameterConfigurationController(BusinessParameterConfigurationService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.BusinessParameterBean;
import com.bytesw.bytebot.bean.BusinessParameterValueBean;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.exception.ReferentialIntegrityException;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.List;
@RestController()
@RequestMapping("/service/settings/business-parameter")
@ProgramSecurity("business-parameters")
@Log4j2
public class BusinessParameterController extends XDFController<BusinessParameterBean, BigInteger> {
@Autowired BusinessParameterService service;
@Autowired
protected GsonBuilder gsonBuilder;
public BusinessParameterController(BusinessParameterService service) {
super(service);
}
@RequestMapping(value = {"/value/{key}"}, method = {RequestMethod.PUT})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 404,message = "Not Found"),
@ApiResponse(code = 409,message = "Already exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<Void> addNewAddValue(
@ApiParam(value = "key", required = true) @PathVariable("key") String key,
@ApiParam(value = "value", required = true) @RequestParam("value") String value,
@ApiParam(value = "from", required = false) @RequestParam("from") String fromString) {
OffsetDateTime from = OffsetDateTime.parse(fromString);
this.service.addValue(key, value, from);
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(value = {"/create"}, method = {RequestMethod.POST})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 409, message = "Already Exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> createWithValue(@RequestBody BusinessParameterValueBean bean, HttpServletRequest req) {
Gson gson = gsonBuilder.create();
bean = this.service.createWithValue(bean);
return new ResponseEntity(gson.toJson(bean), HttpStatus.OK);
}
@RequestMapping(value = {"/current/{key}"}, method = {RequestMethod.GET})
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = ResponseEntity.class),
@ApiResponse(code = 404,message = "Not Found"),
@ApiResponse(code = 409, message = "Already Exists"),
@ApiResponse(code = 505, message = "Internal Server Error")
})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> getCurrentValue(@ApiParam(value = "key", required = true) @PathVariable("key") String key) {
Gson gson = gsonBuilder.create();
// String value = this.service.getCurrentValue(key);
String value = this.service.getCurrentValueParameterByKey(key);
return new ResponseEntity(gson.toJson(value), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.GET},
value = {"/parameter-value/{key}"}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getFeaturesTemplate(@PathVariable("key") String key) {
String featuresTemplate = ((BusinessParameterService)this.service).getCurrentValueParameterByKey(key);
return new ResponseEntity(this.gson.toJson(featuresTemplate), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.POST},
value = {"/page"}
)
@ResponseBody
@Override
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<BusinessParameterBean> pagination) {
if (pagination.getFilterExpression()!=null) {
if (pagination.getFilterExpression().contains("(required==Y)")) {
pagination.setFilterExpression(pagination.getFilterExpression().replace("(required==Y)", "(required==true)"));
}
}
this.service.searchByPagination(pagination);
return new ResponseEntity(this.gson.toJson(pagination), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/{id}"},
method = {RequestMethod.DELETE}
)
@PreAuthorize("hasPermission(this, 'delete')")
public ResponseEntity<String> delete(@PathVariable("id") BigInteger id, HttpServletRequest req) {
this.service.delete(id);
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(
value = {"/{id}"},
method = {RequestMethod.PUT}
)
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> update(@PathVariable("id") BigInteger id, @RequestBody BusinessParameterBean bean, HttpServletRequest req) {
try {
if (this.service.validateKey(bean)) {
throw new ReferentialIntegrityException("Ya existe un identificador con el mismo nombre");
} else {
this.service.update(bean, id);
}
} catch (ObjectOptimisticLockingFailureException var6) {
BusinessParameterBean actualBean = this.service.getById(id);
return new ResponseEntity(this.gson.toJson(actualBean), HttpStatus.CONFLICT);
}
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(
value = {"/"},
method = {RequestMethod.POST}
)
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 409,
message = "Already Exists"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> create(@RequestBody BusinessParameterBean bean, HttpServletRequest req) {
if (this.service.validateKey(bean)) {
throw new ReferentialIntegrityException("Ya existe un identificador con el mismo nombre");
} else {
bean = this.service.create(bean);
return new ResponseEntity(this.gson.toJson(bean), HttpStatus.OK);
}
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/searchKey/{busnessKey}"},
method = {RequestMethod.GET}
)
@PreAuthorize("hasPermission(this, 'showHistory')")
public ResponseEntity<String> findByKey(@PathVariable("busnessKey") BigInteger busnessKey, HttpServletRequest req) {
List<BusinessParameterConfigurationBean> bean = this.service.getConfigurationParametersList(busnessKey);
return new ResponseEntity(this.gson.toJson(bean), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.bytebot.service.CalendarService;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/calendar")
@ProgramSecurity("CALENDAR")
@Log4j2
public class CalendarController extends XDFController<CalendarBean, String> {
public CalendarController(CalendarService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.service.CalendarExceptionService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
@RestController()
@RequestMapping("/calendar-exception")
@ProgramSecurity("calendar-exception")
@Log4j2
public class CalendarExceptionController extends XDFController<CalendarExceptionBean, BigInteger> {
@Autowired
CalendarExceptionService service;
public CalendarExceptionController(CalendarExceptionService service) {
super(service);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 404,
message = "Not Found"
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
value = {"/find-by-calendar-id"},
method = {RequestMethod.POST}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getCalendarExceptionbyID(@RequestBody Map<String, String> parametersCalendar, HttpServletRequest req) {
List<CalendarExceptionBean> calendarExceptionBeanList = this.service.getCalendarExceptionbyID(parametersCalendar);
return new ResponseEntity(this.gson.toJson(calendarExceptionBeanList), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller; package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean; import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean;
import com.bytesw.bytebot.service.dashboard.CustomerInteractionDashboardService; import com.bytesw.bytebot.service.dashboard.CustomerInteractionDashboardService;
import com.bytesw.bytebot.service.dashboard.OperativeDashboardService; import com.bytesw.bytebot.service.dashboard.OperativeDashboardService;
......
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.etl.beans.GoalBean;
import com.bytesw.bytebot.service.GoalService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController()
@RequestMapping("/service/settings/goal")
@ProgramSecurity("GOAL")
@Log4j2
public class GoalController extends XDFController<GoalBean, Long> {
@Autowired
private GoalService goalService;
@Autowired
private GsonBuilder gsonBuilder;
public GoalController(GoalService service) {
super(service);
}
@PostMapping(value = "/goalForAction")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> createGoalForAction(@RequestBody Map<String, Object> body) {
GoalBean info = goalService.saveGoalForAction(body);
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
}
@DeleteMapping(value = "/goalForAction/{id}")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> GoalForAction(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
String info = "";
try{
goalService.deleteGoalForAction(id);
info = id.toString();
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
} catch (Exception e) {
info = e.getMessage();
}
return new ResponseEntity(gson.toJson(info), HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping(value = "/goalForAction/{id}")
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> updateConversationalAgent(@PathVariable("id") Long id,
@RequestBody Map<String, Object> body) {
String info = "";
try{
goalService.updateGoalForActions(body, id);
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
} catch (Exception e) {
info = e.getMessage();
}
return new ResponseEntity(gson.toJson(info), HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping(value = "/goalForAction/{id}")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getActionByGoalId(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(goalService.getGoalForActions(id)), hs);
} catch (Exception e) {
String info = "Error detectado al obtener informacion";
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(info), hs);
}
}
@GetMapping(value = "/goalForAction/")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getActionByGoalIdAll() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(goalService.getGoalForActionsAll()), hs);
} catch (Exception e) {
String info = "Error detectado al obtener informacion";
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(info), hs);
}
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.etl.beans.GoalForActionsBean;
import com.bytesw.bytebot.service.GoalForActionService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/goal-for-actions")
@ProgramSecurity("GOALFORACTIONS")
@Log4j2
public class GoalForActionController extends XDFController<GoalForActionsBean, Long> {
public GoalForActionController(GoalForActionService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.ProcessETLBean;
import com.bytesw.bytebot.service.CalendarService;
import com.bytesw.bytebot.service.ProcessETLService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/service/settings/ProcessETL")
@ProgramSecurity("PROCESSETL")
@Log4j2
public class ProcessETLController extends XDFController<ProcessETLBean, Integer> {
public ProcessETLController(ProcessETLService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.provider.TwilioService;
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 com.twilio.exception.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.gson.Gson;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@Log4j2
@RestController
@RequestMapping("/providers")
public class ProviderController {
@Autowired
private TwilioService twilioService;
@Autowired
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})
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<>();
try {
if (body == null) {
log.info("Body Input Inválido");
throw new ClassCastException("Input inválido");
}
info = twilioService.generateInfo(sid_message, body);
}catch (ClassCastException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}catch(NotFoundException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.NOT_FOUND);
}catch (AuthenticationException e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.UNAUTHORIZED);
}catch (InternalError e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.SchedulerTaskBean;
import com.bytesw.bytebot.service.SchedulerTaskService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@RestController()
@RequestMapping("/service/scheduler-task")
@ProgramSecurity("scheduler")
@Log4j2
public class SchedulerTaskController extends XDFController<SchedulerTaskBean, BigInteger> {
public SchedulerTaskController(SchedulerTaskService service) {
super(service);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.POST},
value = {"/page"}
)
@ResponseBody
@Override
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<SchedulerTaskBean> pagination) {
if (!Objects.isNull(pagination.getFilterExpression()) && !pagination.getFilterExpression().isEmpty()) {
String filterExpression = pagination.getFilterExpression();
if (filterExpression.contains("(internals==Y)")) {
filterExpression = filterExpression.replace("(internals==Y)", "(internals==true)");
}
if (filterExpression.contains("calendarName")) {
filterExpression = filterExpression.replace("calendarName", "calendar.name");
}
pagination.setFilterExpression(filterExpression);
}
this.service.searchByPagination(pagination);
return new ResponseEntity(this.gson.toJson(pagination), HttpStatus.OK);
}
@ApiResponses({@ApiResponse(
code = 200,
message = "Success",
response = ResponseEntity.class
), @ApiResponse(
code = 505,
message = "Internal Server Error"
)})
@RequestMapping(
method = {RequestMethod.GET},
value = {"/initial-data"}
)
@ResponseBody
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getInitialData() {
Map<String, List> initialData = ((SchedulerTaskService) this.service).getInitialData();
return new ResponseEntity(this.gson.toJson(initialData), HttpStatus.OK);
}
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class DeleteDataSensBean {
private Long id;
private String channelValue;
private String value;
private Long agenId;
private Long deletePeriod;
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
@Getter
@Setter
public class DeleteDataSensControlBean {
private Long id;
private Long agenId;
private Timestamp dateDelete;
private Long eventId;
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.time.OffsetDateTime;
@Getter @Setter
public class DeleteDataSensRegistryBean {
private Long id;
private Long inten_id;
private String sender_id;
private String message_sid;
private String multimedia_sid;
private OffsetDateTime update_time;
}
package com.bytesw.bytebot.etl.batch.factory.reader; package com.bytesw.bytebot.etl.batch.factory.reader;
import com.bytesw.bytebot.etl.batch.beans.DynaBean; import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader; import org.springframework.batch.item.database.JdbcCursorItemReader;
...@@ -20,11 +21,14 @@ import java.util.Map; ...@@ -20,11 +21,14 @@ import java.util.Map;
* -query * -query
*/ */
@Component @Component
@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<>();
...@@ -61,5 +65,4 @@ public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, Ro ...@@ -61,5 +65,4 @@ public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, Ro
return dataSource; return dataSource;
} }
} }
...@@ -3,11 +3,9 @@ package com.bytesw.bytebot.etl.batch.processor; ...@@ -3,11 +3,9 @@ package com.bytesw.bytebot.etl.batch.processor;
import com.bytesw.bytebot.etl.batch.beans.DynaBean; import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean; import com.bytesw.bytebot.etl.beans.EventBean;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemProcessor;
@Log4j2 public class ConvertToBeanProcessor implements ItemProcessor<DynaBean, DynaBean> {
public class ConvertToBeanProcessor implements ItemProcessor<DynaBean, DynaBean> {
private ObjectMapper mapper = new ObjectMapper(); private ObjectMapper mapper = new ObjectMapper();
......
package com.bytesw.bytebot.etl.batch.service; package com.bytesw.bytebot.etl.batch.service;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean;
import com.bytesw.bytebot.etl.batch.beans.DynaBean; import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.batch.beans.TenantBatchBean; import com.bytesw.bytebot.etl.batch.beans.TenantBatchBean;
import com.bytesw.bytebot.etl.batch.factory.mapper.RowMapperFactory; import com.bytesw.bytebot.etl.batch.factory.mapper.RowMapperFactory;
import com.bytesw.bytebot.etl.batch.factory.reader.DataBaseItemReaderFactory; import com.bytesw.bytebot.etl.batch.factory.reader.DataBaseItemReaderFactory;
import com.bytesw.bytebot.etl.batch.processor.ConvertToBeanProcessor; import com.bytesw.bytebot.etl.batch.processor.ConvertToBeanProcessor;
import com.bytesw.bytebot.etl.batch.writer.ByteBotJPAWriter; import com.bytesw.bytebot.etl.batch.writer.ByteBotJPAWriter;
import com.bytesw.bytebot.etl.batch.writer.DataSensibleJPAWriter;
import com.bytesw.bytebot.etl.config.BatchProperties; import com.bytesw.bytebot.etl.config.BatchProperties;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleLogRepository;
import com.bytesw.bytebot.etl.dao.EventHistoryRepository; import com.bytesw.bytebot.etl.dao.EventHistoryRepository;
import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.enums.IntentTypeEnum;
import com.bytesw.bytebot.etl.services.DeleteSensMessageService;
import com.bytesw.bytebot.etl.services.ProcessMessageService; import com.bytesw.bytebot.etl.services.ProcessMessageService;
import com.bytesw.bytebot.jdbc.DeleteDataSensJDBCRepository;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.FrequencyType;
import com.bytesw.bytebot.model.enums.ProcessETLEnum;
import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage; import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import com.google.gson.Gson; import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
...@@ -29,10 +44,15 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar; ...@@ -29,10 +44,15 @@ import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger; import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.*; import java.util.*;
import java.util.Calendar;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
//@Service // Descomentar lo siguiente para que funcione
@Service
@Log4j2 @Log4j2
public class ScheduleService implements SchedulingConfigurer { public class ScheduleService implements SchedulingConfigurer {
...@@ -75,6 +95,9 @@ public class ScheduleService implements SchedulingConfigurer { ...@@ -75,6 +95,9 @@ public class ScheduleService implements SchedulingConfigurer {
@Autowired @Autowired
private ProcessMessageService service; private ProcessMessageService service;
@Autowired
private DeleteSensMessageService deleteSensMessageService;
@Autowired @Autowired
private Gson gson; private Gson gson;
...@@ -84,6 +107,37 @@ public class ScheduleService implements SchedulingConfigurer { ...@@ -84,6 +107,37 @@ public class ScheduleService implements SchedulingConfigurer {
@Autowired @Autowired
private EventHistoryRepository eventHistoryRepository; private EventHistoryRepository eventHistoryRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private DeleteDataSensJDBCRepository deleteDataSensJDBCRepository;
@Autowired
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
@Autowired
private DeleteDataSensibleLogRepository deleteDataSensibleLogRepository;
@Autowired
private IntentRepository intentRepository;
@Autowired
private ProcessETLRepository processETLRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private CalendarExceptionFullRepository calendarExceptionFullRepository;
private boolean schedulerFlag = false;
private List<String> keys = new ArrayList<>();
@Override @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (scheduledTaskRegistrar == null) { if (scheduledTaskRegistrar == null) {
...@@ -102,21 +156,115 @@ public class ScheduleService implements SchedulingConfigurer { ...@@ -102,21 +156,115 @@ public class ScheduleService implements SchedulingConfigurer {
throw new RuntimeException("batch properties not found"); throw new RuntimeException("batch properties not found");
} }
// identifier "prueba" Cambiar luego
properties.getTenants().stream().forEach(tenant -> { properties.getTenants().stream().forEach(tenant -> {
ThreadLocalStorage.setTenantName(tenant.getId()); ThreadLocalStorage.setTenantName(tenant.getId());
configureTask(tenant.getId(), "prueba", taskRegistrar); configureTask(tenant.getId(), "prueba", taskRegistrar);
}); });
//@TODO Falta añadir el modo multitenant
//@TODO Falta añadir el modo multitenan
} }
private void configureTask(String tenantIdentifier, String identifier, ScheduledTaskRegistrar taskRegistrar) { private void configureTask(String tenantIdentifier, String identifier, ScheduledTaskRegistrar taskRegistrar) {
Trigger trigger = new CronTrigger(cronExpression, TimeZone.getDefault()); Trigger trigger = new CronTrigger(cronExpression, TimeZone.getDefault());
/* ETL de Dashboard */
String key = String.format("%s-%s", tenantIdentifier, identifier); String key = String.format("%s-%s", tenantIdentifier, identifier);
futureMap.put(key, taskRegistrar.getScheduler().schedule(() -> scheduleCron(createJob(tenantIdentifier), tenantIdentifier), trigger)); futureMap.put(key, taskRegistrar.getScheduler().schedule(() -> scheduleCron(createJob(tenantIdentifier), tenantIdentifier), trigger));
/* Extraer el id del proceso - Delete */
ProcessETL processDelete = processETLRepository.findByName(ProcessETLEnum.PROCESS_DELETE.getName());
/* Busca las listas de SchedulerTask */
List<SchedulerTask> listSchedulerTask = schedulerTaskRepository.findByEtlId(processDelete.getId());
for (SchedulerTask schedulerTask : listSchedulerTask) {
Trigger triggerDelete = new CronTrigger(schedulerTask.getCronExpression(), TimeZone.getDefault());
String keyScheduler = String.format("%s-%s", tenantIdentifier, schedulerTask.getCalendarID());
futureMap.put(keyScheduler, taskRegistrar.getScheduler()
.schedule(() -> processDeleteData(tenantIdentifier, taskRegistrar, schedulerTask.getCalendarID().trim()), triggerDelete));
}
} }
/*ETL eliminacion de data sensible*/
public void processDeleteData(String tenantIdentifier, ScheduledTaskRegistrar taskRegistrar, String calendarId) {
Optional<List<WeekScheduler>> dates = weekSchedulerRepository.findByCalendarId(calendarId);
OffsetDateTime actual = OffsetDateTime.now();
for(WeekScheduler weekScheduler: dates.get()) {
if (actual.isBefore(weekScheduler.getTo()) && actual.isAfter(weekScheduler.getFrom())) {
//schedulerFlag = true;
Optional<List<CalendarExceptionFull>> calendarException = calendarExceptionFullRepository.findByCalendarId(calendarId);
if (calendarException.isPresent()){
schedulerFlag = validateException(calendarException.get());
break;
}
} else {
schedulerFlag = false;
}
}
if (schedulerFlag) {
Trigger trigger = new CronTrigger(cronExpression, TimeZone.getDefault());
List<DeleteDataSensBean> deleteDataSensBeans = deleteDataSensJDBCRepository
.getListAgentChannel(AgentStatusEnum.DEPLOYED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
String keyDataSens = "";
for (DeleteDataSensBean data : deleteDataSensBeans) {
keyDataSens = String.format("deleteSensible-%s-%s", tenantIdentifier, data.getValue());
if (!futureMap.containsKey(keyDataSens)) {
keys.add(keyDataSens);
futureMap.put(keyDataSens, taskRegistrar.getScheduler()
.schedule(() -> scheduleCron(createJobDataSens(tenantIdentifier, data), tenantIdentifier), trigger));
}
}
} else {
keys.forEach(x -> {
futureMap.remove(x);
});
}
}
private boolean validateException(List<CalendarExceptionFull> calendarException){
boolean result = true;
FrequencyType[] frecuencyType = FrequencyType.values();
OffsetDateTime now = OffsetDateTime.now();
for (CalendarExceptionFull exception : calendarException){
for (int i = 0; i < frecuencyType.length; i++) {
if (frecuencyType[i].getName().equals(exception.getFrequencyType())) {
if (exception.getFrequencyType().equals(FrequencyType.ANNUAL.getName())) {
if (now.getMonth().getValue() == exception.getMonth().intValue() && exception.getDayOfMonth().intValue() == now.getDayOfMonth()){
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.RANGE.getName())) {
if (now.isBefore(exception.getTo()) && now.isAfter(exception.getFrom())){
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.UNIQUE.getName())) {
if (now.toLocalDate() == exception.getDate()) {
result = false;
}
} else if (exception.getFrequencyType().equals(FrequencyType.UniqueWeekly.getName())) {
Calendar ca1 = Calendar.getInstance();
ca1.set(now.getYear(), now.getMonth().getValue(), now.getDayOfMonth());
ca1.setMinimalDaysInFirstWeek(1);
if (now.getMonth().getValue() == exception.getMonth().intValue() && exception.getDayOfWeek().intValue() == now.getDayOfWeek().getValue()
&& exception.getWeekOfMonth().intValue() == ca1.WEEK_OF_MONTH){
result = false;
}
}
break;
}
}
if (!result) {
break;
}
}
return result;
}
/* Métodos utilizados para ETL de dashboard */
private Job createJob(String tenantIdentifier) { private Job createJob(String tenantIdentifier) {
ThreadLocalStorage.setTenantName(tenantIdentifier); ThreadLocalStorage.setTenantName(tenantIdentifier);
return jobBuilderFactory.get("processJob") return jobBuilderFactory.get("processJob")
...@@ -127,8 +275,7 @@ public class ScheduleService implements SchedulingConfigurer { ...@@ -127,8 +275,7 @@ public class ScheduleService implements SchedulingConfigurer {
private Step createStep(String tenantIdentifier) { private Step createStep(String tenantIdentifier) {
ByteBotJPAWriter writer = new ByteBotJPAWriter(); ByteBotJPAWriter writer = new ByteBotJPAWriter();
writer.setService(service); writer.setService(service);
return stepBuilderFactory.get("processByteBotData").<DynaBean, DynaBean>chunk(chunk)
return stepBuilderFactory.get("processByteBotData").<DynaBean, DynaBean> chunk(chunk)
.reader(getReader(tenantIdentifier)) .reader(getReader(tenantIdentifier))
.processor(new ConvertToBeanProcessor()) .processor(new ConvertToBeanProcessor())
.writer(writer).build(); .writer(writer).build();
...@@ -148,9 +295,74 @@ public class ScheduleService implements SchedulingConfigurer { ...@@ -148,9 +295,74 @@ public class ScheduleService implements SchedulingConfigurer {
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
params.putAll(tenantFound.get().getDatasource()); params.putAll(tenantFound.get().getDatasource());
params.put("query", String.format((String) params.get("query"), id != null ? id : 0)); params.put("query", String.format((String) params.get("query"), id != null ? id : 0));
return dataBaseItemReaderFactory.createReader(rowMapperFactory.createMapper(new HashMap<>()), params);
}
/* Métodos ETL de data sensible */
private Job createJobDataSens(String tenantIdentifier, DeleteDataSensBean data) {
ThreadLocalStorage.setTenantName(tenantIdentifier);
return jobBuilderFactory.get( String.format("processDataSensible%d",+data.getAgenId()))
.incrementer(new RunIdIncrementer()).listener(listener)
.flow(createStepDataSens(tenantIdentifier, data)).end().build();
}
private Step createStepDataSens(String tenantIdentifier, DeleteDataSensBean data) {
DataSensibleJPAWriter writer = new DataSensibleJPAWriter();
List<String> intentByAgent = deleteDataSensJDBCRepository.getIntentByAgent(IntentTypeEnum.SENSIBLE.getName(), data.getAgenId());
writer.setIntentByAgent(intentByAgent);
writer.setAgent(data);
writer.setService(deleteSensMessageService);
writer.setIntentRepository(intentRepository);
writer.setDeleteDataSensibleControlRepository(deleteDataSensibleControlRepository);
writer.setDeleteDataSensibleLogRepository(deleteDataSensibleLogRepository);
return stepBuilderFactory.get("processByteBotDatasSens")
.<DynaBean, DynaBean>chunk(chunk)
.reader(getReaderDataSens(tenantIdentifier, data))
.processor(new ConvertToBeanProcessor())
.writer(writer).build();
}
private ItemReader getReaderDataSens(String tenantIdentifier, DeleteDataSensBean data) {
if (properties == null) {
throw new RuntimeException("Properties not found");
}
Optional<TenantBatchBean> tenantFound = findTenant(tenantIdentifier);
if (!tenantFound.isPresent()) {
throw new RuntimeException("Properties not found");
}
DeleteDataSensControlBean control = deleteDataSensJDBCRepository.getControl(data.getAgenId());
OffsetDateTime endDate = OffsetDateTime.now();
Long id = 0L;
int differenceTime = 0;
if (control != null) {
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(control.getDateDelete().toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate);
differenceTime = (int) (difference.getSeconds() / 60);
if (differenceTime < data.getDeletePeriod()) {
log.info("Agente " + data.getValue() + " aun no cumple con el periodo de espera.");
id = null;
} else {
id = control.getEventId();
}
}
Map<String, Object> params = new HashMap<>();
params.putAll(tenantFound.get().getDatasource());
params.put("query", String.format((String) params.get("query"), id));
return dataBaseItemReaderFactory.createReader(rowMapperFactory.createMapper(new HashMap<>()), params); return dataBaseItemReaderFactory.createReader(rowMapperFactory.createMapper(new HashMap<>()), params);
} }
/* Métodos generales */
private Optional<TenantBatchBean> findTenant(String tenantId) { private Optional<TenantBatchBean> findTenant(String tenantId) {
return properties.getTenants().stream().filter(x -> x.getId().equals(tenantId)).findFirst(); return properties.getTenants().stream().filter(x -> x.getId().equals(tenantId)).findFirst();
} }
......
...@@ -19,7 +19,8 @@ import java.util.List; ...@@ -19,7 +19,8 @@ import java.util.List;
@Log4j2 @Log4j2
public class ByteBotJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener { public class ByteBotJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {
@Getter @Setter @Getter
@Setter
private ProcessMessageService service; private ProcessMessageService service;
@Override @Override
......
package com.bytesw.bytebot.etl.batch.writer;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensRegistryBean;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleLogRepository;
import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.enums.EventTypeEnum;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleControl;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleLog;
import com.bytesw.bytebot.etl.model.Intent;
import com.bytesw.bytebot.etl.services.DeleteSensMessageService;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.*;
@Log4j2
public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {
@Getter
@Setter
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
@Getter
@Setter
private DeleteDataSensibleLogRepository deleteDataSensibleLogRepository;
@Getter
@Setter
private IntentRepository intentRepository;
@Getter
@Setter
private DeleteSensMessageService service;
@Getter
@Setter
private List<String> intentByAgent;
@Getter
@Setter
private DeleteDataSensBean agent;
@Override
@Transactional
public void write(List<? extends DynaBean> list) throws Exception {
Object numeros = JsonUtils.getFieldFromJson(agent.getChannelValue(), "$.telefonos_desplegados");
List<String> numerosAgentes = numbersAgent((List<Map>) numeros);
for (DynaBean dynaBean : list) {
Long id = Long.parseLong(dynaBean.get("id").toString());
String json = (String) dynaBean.get("data");
String event = (String) JsonUtils.getFieldFromJson(json, "$.event");
String sender_id;
boolean update_control = false;
String presentDate = OffsetDateTime.now().toString().replace('T', ' ');
String timeZone = presentDate.substring(presentDate.length() - 6);
presentDate = presentDate.replace(timeZone, "");
if (EventTypeEnum.USER.getName().equals(event)) {
String toAgent = (String) JsonUtils.getFieldFromJson(json, "$.metadata.To");
String agentNumber = new String();
if (toAgent == null) {
continue;
}
if (toAgent.isEmpty()) {
agentNumber = toAgent.split(":")[1];
}
if (numerosAgentes.contains(agentNumber)) {
String intent = (String) JsonUtils.getFieldFromJson(json, "$.parse_data.intent.name");
if (intentByAgent.contains(intent)) {
String SmSMessageSid = (String) JsonUtils.getFieldFromJson(json, "$.metadata.SmsMessageSid");
Optional<Intent> intenId = this.intentRepository.findIntenNameById(intent, agent.getAgenId());
if (!intenId.isPresent()) {
throw new Exception("Intent no esta presente");
}
try {
sender_id = (String) JsonUtils.getFieldFromJson(json, "$.sender_id");
log.info(sender_id);
} catch (Exception e) {
log.info(e.getMessage());
sender_id = (String) JsonUtils.getFieldFromJson(json, "$.metadata.sender_id");
}
List<DeleteDataSensRegistryBean> deleteSensibleBean = new ArrayList<>();
try {
deleteSensibleBean = service.deleteMessage(agent.getAgenId()
, SmSMessageSid, intenId.get().getId(), sender_id);
update_control = true;
} catch (NotFoundException e) {
update_control = true;
} catch (Exception e) {
update_control = false;
}
for (DeleteDataSensRegistryBean registry : deleteSensibleBean) {
DeleteDataSensibleLog reg = new DeleteDataSensibleLog();
reg.setIntenId(registry.getInten_id());
reg.setMessageId(registry.getMessage_sid());
reg.setMultimediaId(registry.getMultimedia_sid());
reg.setSendId(registry.getSender_id());
reg.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleLogRepository.save(reg);
}
}
}
}
DeleteDataSensibleControl control = new DeleteDataSensibleControl();
Optional<DeleteDataSensibleControl> controlBd = deleteDataSensibleControlRepository.findEventIdByAgentId(agent.getAgenId());
if (update_control) {
if (controlBd.isPresent()) {
// Update
control.setId(controlBd.get().getId());
control.setAgentId(agent.getAgenId());
control.setEventId(id);
control.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleControlRepository.save(control);
} else {
// Create
control.setAgentId(agent.getAgenId());
control.setEventId(id);
control.setDate(Timestamp.valueOf(presentDate));
deleteDataSensibleControlRepository.save(control);
}
}
}
}
private List<String> numbersAgent(List<Map> listNumber){
List<String> result = new ArrayList<>();
for (Map map : listNumber){
String cod = (String) map.get("CodigoInternacional");
String number = (String) map.get("numero");
String agent = "+" + cod + number;
result.add(agent);
}
return result;
}
@Override
public void beforeStep(StepExecution stepExecution) {
String tenantId = stepExecution.getJobParameters().getString("tenantId");
ThreadLocalStorage.setTenantName(tenantId);
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return stepExecution.getExitStatus();
}
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class ActionBean {
@Expose
private Long id;
@Expose
private String ident;
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class GoalBean {
@Expose
private Long id;
@Expose
private String identifier;
@Expose
private Long agenId;
}
\ No newline at end of file
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class GoalForActionsBean {
@Expose
private Long id;
@Expose
private Long goalId;
@Expose
private Long actionId;
}
package com.bytesw.bytebot.etl.beans;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class IntentBean {
private Long id;
private String identifier;
private String sensible;
private Long agenId;
}
package com.bytesw.bytebot.etl.dao; package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Action; import com.bytesw.bytebot.etl.model.Action;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional; import java.util.Optional;
......
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleControl;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface DeleteDataSensibleControlRepository extends CrudRepository<DeleteDataSensibleControl, Long> {
@Query("SELECT s from DeleteDataSensibleControl s WHERE s.agentId = :agentId")
Optional<DeleteDataSensibleControl> findEventIdByAgentId(@Param("agentId") Long agentId);
}
package com.bytesw.bytebot.etl.dao; package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.ETLChannel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface ETLChannelRepository extends CrudRepository<ETLChannel, Long> { import com.bytesw.bytebot.etl.model.DeleteDataSensibleLog;
import org.springframework.data.repository.CrudRepository;
Optional<ETLChannel> findByIdentifier(String identifier); public interface DeleteDataSensibleLogRepository extends CrudRepository<DeleteDataSensibleLog, Long> {
} }
package com.bytesw.bytebot.etl.dao; package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Intent; import com.bytesw.bytebot.etl.model.Intent;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional; import java.util.Optional;
public interface IntentRepository extends CrudRepository<Intent, Long> { public interface IntentRepository extends CrudRepository<Intent, Long> {
Optional<Intent> findByIdentifier(String identifier); Optional<Intent> findByIdentifier(String identifier);
@Query("SELECT s from Intent s WHERE s.identifier = :intenIdent and s.agenId = :agenId")
Optional<Intent> findIntenNameById(@Param("intenIdent") String intenIdent, @Param("agenId") Long agenId);
} }
package com.bytesw.bytebot.etl.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum IntentTypeEnum {
SENSIBLE("1"), NO_SENSIBLE("0");
private final String name;
private static final Map<String, IntentTypeEnum> map = new HashMap<>();
static {
for (IntentTypeEnum type : IntentTypeEnum.values()) {
map.put(type.name, type);
}
}
IntentTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static IntentTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.etl.model; package com.bytesw.bytebot.etl.model;
import com.bytesw.xdf.model.converter.BooleanToStringConverter;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -9,26 +8,21 @@ import javax.persistence.*; ...@@ -9,26 +8,21 @@ import javax.persistence.*;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter
@Table(name="BBOT_ACTION") @Setter
@ToString
@Table(name = "AVB_ACTION")
@NamedQuery(name = "Action.findByPK", query = "Select p from Action p where p.id = ?1") @NamedQuery(name = "Action.findByPK", query = "Select p from Action p where p.id = ?1")
public class Action { public class Action {
@Id @Id
@Column(name = "ACTION_ID") @Column(name = "action_id")
@TableGenerator(name = "BBOT_ACTION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_ACTION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_ACTION_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_ACTION_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_ACTION_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_ACTION_GENERATOR")
private Long id; private Long id;
@Column(name = "ACTION_IDENT") @Column(name = "action_ident")
private String identifier; private String identifier;
@ManyToOne(optional = false)
@JoinColumn(name = "GOAL_ID", referencedColumnName = "GOAL_ID")
private Goal goal;
@Column(name = "ACTION_RGOAL")
@Convert(converter = BooleanToStringConverter.class)
private boolean meetGoal;
} }
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.sql.Timestamp;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name="avb_delete_sens_msg_control")
public class DeleteDataSensibleControl {
@Id
@Column(name = "dsmc_id")
@TableGenerator(name = "AVB_DELETE_MSG_SENS_CONTROL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_DELETE_MSG_SENS_CONTROL_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_DELETE_MSG_SENS_CONTROL_GENERATOR")
private Long id;
@Column(name = "agent_id")
private Long agentId;
@Column(name = "dsmc_date")
private Timestamp date;
@Column(name = "evnt_id")
private Long eventId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.sql.Timestamp;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name="avb_delete_sens_msg_log")
public class DeleteDataSensibleLog {
@Id
@Column(name = "dele_id")
@TableGenerator(name = "AVB_DELETE_MSG_SENS_LOG_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_DELETE_MSG_SENS_LOG_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_DELETE_MSG_SENS_LOG_GENERATOR")
private Long id;
@Column(name = "inten_id")
private Long intenId;
@Column(name = "send_id")
private String sendId;
@Column(name = "dele_smsg")
private String messageId;
@Column(name = "dele_msmsg")
private String multimediaId;
@Column(name = "dele_fecej")
private Timestamp date;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="BBOT_CHANNEL_DASHBOARD")
@NamedQuery(name = "ETLChannel.findByPK", query = "Select p from ETLChannel p where p.id = ?1")
public class ETLChannel {
@Id
@Column(name = "CHANN_ID")
@TableGenerator(name = "BBOT_CHANNEL_DASHBOARD_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_CHANNEL_DASHBOARD_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_CHANNEL_DASHBOARD_GENERATOR")
private Long id;
@Column(name = "CHANN_IDENT")
private String identifier;
}
...@@ -10,23 +10,23 @@ import java.time.OffsetDateTime; ...@@ -10,23 +10,23 @@ import java.time.OffsetDateTime;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_EVENT_HISTORY") @Table(name="avb_event_history")
@NamedQuery(name = "EventHistory.findByPK", query = "Select p from EventHistory p where p.id = ?1") @NamedQuery(name = "EventHistory.findByPK", query = "Select p from EventHistory p where p.id = ?1")
public class EventHistory { public class EventHistory {
@Id @Id
@Column(name = "EVENH_ID") @Column(name = "evenh_id")
@TableGenerator(name = "BBOT_EVENT_HISTORY_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_EVENT_HISTORY_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_EVENT_HISTORY_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_EVENT_HISTORY_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_EVENT_HISTORY_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_EVENT_HISTORY_GENERATOR")
private Long id; private Long id;
@Column(name = "EVENH_SENDID") @Column(name = "evenh_sendid")
private String senderId; private String senderId;
@Column(name = "EVENH_EVID") @Column(name = "evenh_evid")
private Long eventId; private Long eventId;
@Column(name = "EVENH_DATE") @Column(name = "evenh_date")
private OffsetDateTime date; private OffsetDateTime date;
} }
...@@ -9,17 +9,20 @@ import javax.persistence.*; ...@@ -9,17 +9,20 @@ import javax.persistence.*;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_GOAL") @Table(name="avb_goal")
@NamedQuery(name = "Goal.findByPK", query = "Select p from Goal p where p.id = ?1") @NamedQuery(name = "Goal.findByPK", query = "Select p from Goal p where p.id = ?1")
public class Goal { public class Goal {
@Id @Id
@Column(name = "GOAL_ID") @Column(name = "goal_id")
@TableGenerator(name = "BBOT_GOAL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_GOAL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_GOAL_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_GOAL_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_GOAL_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_GOAL_GENERATOR")
private Long id; private Long id;
@Column(name = "GOAL_IDENT") @Column(name = "goal_ident")
private String identifier; private String identifier;
@Column(name = "agen_id")
private Long agenId;
} }
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name = "avb_GoalForActions")
@NamedQuery(name = "GoalForActions.findByPK", query = "Select p from GoalForActions p where p.id = ?1")
public class GoalForActions {
@Id
@Column(name = "gfac_id")
@TableGenerator(name = "AVB_GOALFORACTIONS_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_GOALFORACTIONS_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_GOALFORACTIONS_GENERATOR")
private Long id;
@Column(name = "goal_id")
private Long goalId;
@Column(name = "action_id")
private Long actionId;
}
...@@ -6,21 +6,27 @@ import lombok.ToString; ...@@ -6,21 +6,27 @@ import lombok.ToString;
import javax.persistence.*; import javax.persistence.*;
//BBOT_INTENT //AVB_INTENT
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_INTENT") @Table(name="avb_intent")
@NamedQuery(name = "Intent.findByPK", query = "Select p from Intent p where p.id = ?1") @NamedQuery(name = "Intent.findByPK", query = "Select p from Intent p where p.id = ?1")
public class Intent { public class Intent {
@Id @Id
@Column(name = "INTEN_ID") @Column(name = "inten_id")
@TableGenerator(name = "BBOT_INTENT_DASHBOARD_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_INTENT_DASHBOARD_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_INTENT_DASHBOARD_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_INTENT_DASHBOARD_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_INTENT_DASHBOARD_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_INTENT_DASHBOARD_GENERATOR")
private Long id; private Long id;
@Column(name = "INTEN_IDENT") @Column(name = "inten_ident")
private String identifier; private String identifier;
@Column(name = "intent_is_sensible")
private String sensible;
@Column(name = "agen_id")
private Long agenId;
} }
...@@ -14,36 +14,36 @@ import java.time.OffsetDateTime; ...@@ -14,36 +14,36 @@ import java.time.OffsetDateTime;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Builder @Getter @Setter @ToString @Builder
@Table(name="BBOT_MESSAGE") @Table(name="avb_message")
@NamedQuery(name = "Message.findByPK", query = "Select p from Message p where p.id = ?1") @NamedQuery(name = "Message.findByPK", query = "Select p from Message p where p.id = ?1")
public class Message { public class Message {
@Id @Id
@Column(name = "MESSA_ID") @Column(name = "messa_id")
@TableGenerator(name = "BBOT_MESSAGE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_MESSAGE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_MESSAGE_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_MESSAGE_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_MESSAGE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_MESSAGE_GENERATOR")
private Long id; private Long id;
@Column(name = "SESSION_ID") @Column(name = "session_id")
private Long sessionId; private Long sessionId;
@Column(name = "MESSA_DATE") @Column(name = "messa_date")
private OffsetDateTime date; private OffsetDateTime date;
@Column(name = "MESSA_CONT") @Column(name = "messa_cont")
private String content; private String content;
@Column(name = "MESSA_CORRE") @Column(name = "messa_corre")
private int correlative; private int correlative;
@Column(name = "MESSA_PROB") @Column(name = "messa_prob")
private BigDecimal probability; private BigDecimal probability;
@Convert(converter = MessageTypeConverter.class) @Convert(converter = MessageTypeConverter.class)
@Column(name = "MESSA_TYPE") @Column(name = "messa_type")
private MessageTypeEnum type; private MessageTypeEnum type;
@Column(name = "INTEN_ID") @Column(name = "inten_id")
private Long intentId; private Long intentId;
} }
...@@ -10,26 +10,26 @@ import java.time.OffsetDateTime; ...@@ -10,26 +10,26 @@ import java.time.OffsetDateTime;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_RESPONSE") @Table(name="avb_response")
@NamedQuery(name = "Response.findByPK", query = "Select p from Response p where p.id = ?1") @NamedQuery(name = "Response.findByPK", query = "Select p from Response p where p.id = ?1")
public class Response { public class Response {
@Id @Id
@Column(name = "RESPO_ID") @Column(name = "respo_id")
@TableGenerator(name = "BBOT_RESPONSE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_RESPONSE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_RESPONSE_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_RESPONSE_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_RESPONSE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_RESPONSE_GENERATOR")
private Long id; private Long id;
@Column(name = "RESPO_DATE") @Column(name = "respo_date")
private OffsetDateTime date; private OffsetDateTime date;
@Column(name = "RESPO_CONT") @Column(name = "respo_cont")
private String content; private String content;
@Column(name = "RESPO_CORR") @Column(name = "respo_corr")
private int correlative; private int correlative;
@Column(name = "SESSION_ID") @Column(name = "session_id")
private Long sessionId; private Long sessionId;
} }
package com.bytesw.bytebot.etl.model; package com.bytesw.bytebot.etl.model;
import com.bytesw.bytebot.model.Channel;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -10,31 +11,31 @@ import java.time.OffsetDateTime; ...@@ -10,31 +11,31 @@ import java.time.OffsetDateTime;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_SESSION") @Table(name="avb_session")
@NamedQuery(name = "Session.findByPK", query = "Select p from Session p where p.id = ?1") @NamedQuery(name = "Session.findByPK", query = "Select p from Session p where p.id = ?1")
public class Session { public class Session {
@Id @Id
@Column(name = "SESSION_ID") @Column(name = "session_id")
@TableGenerator(name = "BBOT_SESSION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_SESSION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_SESSION_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_SESSION_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_SESSION_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_SESSION_GENERATOR")
private Long id; private Long id;
@Column(name = "SESSION_DATE", nullable = false) @Column(name = "session_date", nullable = false)
private OffsetDateTime sessionDate; private OffsetDateTime sessionDate;
@Column(name = "SESSION_LEDAT", nullable = false) @Column(name = "session_ledat", nullable = false)
private OffsetDateTime lastEventDate; private OffsetDateTime lastEventDate;
@Column(name = "SESSION_FRDAT", nullable = false) @Column(name = "session_frdat", nullable = false)
private OffsetDateTime responseDate; private OffsetDateTime responseDate;
@ManyToOne @ManyToOne
@JoinColumn(name = "CHANN_ID", referencedColumnName = "CHANN_ID") @JoinColumn(name = "chan_id", referencedColumnName = "chan_id")
private ETLChannel channel; private Channel channel;
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID") @JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user; private User user;
} }
...@@ -10,24 +10,24 @@ import java.time.OffsetDateTime; ...@@ -10,24 +10,24 @@ import java.time.OffsetDateTime;
@Cacheable(false) @Cacheable(false)
@Entity @Entity
@Getter @Setter @ToString @Getter @Setter @ToString
@Table(name="BBOT_ACTION_SESSION") @Table(name="avb_action_session")
@NamedQuery(name = "SessionAction.findByPK", query = "Select p from SessionAction p where p.id = ?1") @NamedQuery(name = "SessionAction.findByPK", query = "Select p from SessionAction p where p.id = ?1")
public class SessionAction { public class SessionAction {
@Id @Id
@Column(name = "ASESS_ID") @Column(name = "asess_id")
@TableGenerator(name = "BBOT_ACTION_SESSION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_ACTION_SESSION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_ACTION_SESSION_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_ACTION_SESSION_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_ACTION_SESSION_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_ACTION_SESSION_GENERATOR")
private Long id; private Long id;
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "ACTION_ID", referencedColumnName = "ACTION_ID") @JoinColumn(name = "action_id", referencedColumnName = "action_id")
private Action action; private Action action;
@Column(name = "ASESS_DATE") @Column(name = "asess_date")
private OffsetDateTime date; private OffsetDateTime date;
@Column(name = "SESSION_ID") @Column(name = "session_id")
private Long sessionId; private Long sessionId;
} }
...@@ -8,17 +8,17 @@ import javax.persistence.*; ...@@ -8,17 +8,17 @@ import javax.persistence.*;
@Cacheable(false) @Cacheable(false)
@Entity @Getter @Setter @ToString @Entity @Getter @Setter @ToString
@Table(name="BBOT_USER") @Table(name="avb_user")
@NamedQuery(name = "User.findByPK", query = "Select p from User p where p.id = ?1") @NamedQuery(name = "User.findByPK", query = "Select p from User p where p.id = ?1")
public class User { public class User {
@Id @Id
@Column(name = "USER_ID") @Column(name = "user_id")
@TableGenerator(name = "BBOT_USER_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_USER_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_USER_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_USER_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE,generator = "BBOT_USER_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE,generator = "AVB_USER_GENERATOR")
private Long id; private Long id;
@Column(name = "USER_IDENT") @Column(name = "user_ident")
private String identifier; private String identifier;
} }
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensRegistryBean;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.service.provider.TwilioService;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Log4j2
public class DeleteSensMessageService {
@Autowired
private TwilioService twilioService;
@Autowired
DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
public List<DeleteDataSensRegistryBean> deleteMessage(Long agentId, String SmsMessage, Long inten_id, String sender_id) throws Exception {
List<DeleteDataSensRegistryBean> deleteMessages = new ArrayList<DeleteDataSensRegistryBean>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> params = new HashMap<>();
params.put("agent_id", agentId.intValue());
try {
Map<String, Object> result = new HashMap<>();
data = twilioService.generateInfo(SmsMessage, params);
if (data.isEmpty()) {
throw new Exception("Parámetros vacíos");
}
DeleteDataSensRegistryBean registry = new DeleteDataSensRegistryBean();
if (data.get("status") != null) {
List<String> images = new ArrayList<String>();
images = (List<String>) data.get("data");
for (String image : images) {
if (image.trim().isEmpty()) {
continue;
}
// Info del Bean
registry.setMultimedia_sid(image);
registry.setMessage_sid(SmsMessage);
registry.setUpdate_time(OffsetDateTime.now());
registry.setInten_id(inten_id);
registry.setSender_id(sender_id);
// Agregado a la lista
deleteMessages.add(registry);
}
}
return deleteMessages;
} catch (NotFoundException e) {
log.debug(e);
throw new NotFoundException(e.getMessage());
} catch (Exception e) {
log.debug(e);
throw new Exception(e.getMessage());
}
}
}
...@@ -2,6 +2,7 @@ package com.bytesw.bytebot.etl.services; ...@@ -2,6 +2,7 @@ package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.dao.SessionBotRepository; import com.bytesw.bytebot.etl.dao.SessionBotRepository;
import com.bytesw.bytebot.etl.model.Session; import com.bytesw.bytebot.etl.model.Session;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -14,6 +15,7 @@ import java.util.Optional; ...@@ -14,6 +15,7 @@ import java.util.Optional;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@Log4j2
public abstract class MessageProcessedSupport { public abstract class MessageProcessedSupport {
protected static final String SENDER_ID_FIELD_NAME = "senderId"; protected static final String SENDER_ID_FIELD_NAME = "senderId";
...@@ -43,15 +45,13 @@ public abstract class MessageProcessedSupport { ...@@ -43,15 +45,13 @@ public abstract class MessageProcessedSupport {
} }
dateDecimal = new BigDecimal(String.valueOf(objectTimestamp)); dateDecimal = new BigDecimal(String.valueOf(objectTimestamp));
} }
Long timestamp = (long) (dateDecimal.doubleValue() * 1000);
Long timestamp = dateDecimal.longValue();
if (String.valueOf(timestamp).length() < 13) { if (String.valueOf(timestamp).length() < 13) {
int numberOfZero = 13 - String.valueOf(timestamp).length(); int numberOfZero = 13 - String.valueOf(timestamp).length();
for (int i = 0; i < numberOfZero; i++) { for (int i = 0; i < numberOfZero; i++) {
timestamp = timestamp * 10; timestamp = timestamp * 10;
} }
} }
OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()); OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
return date; return date;
} }
......
package com.bytesw.bytebot.etl.services; package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.ProcessMessageResult; import com.bytesw.bytebot.etl.beans.ProcessMessageResult;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.EventHistoryRepository; import com.bytesw.bytebot.etl.dao.EventHistoryRepository;
import com.bytesw.bytebot.etl.enums.EventTypeEnum; import com.bytesw.bytebot.etl.enums.EventTypeEnum;
import com.bytesw.bytebot.etl.model.EventHistory; import com.bytesw.bytebot.etl.model.EventHistory;
...@@ -19,18 +20,20 @@ public class ProcessMessageService { ...@@ -19,18 +20,20 @@ public class ProcessMessageService {
@Autowired @Autowired
private EventHistoryRepository eventHistoryRepository; private EventHistoryRepository eventHistoryRepository;
@Autowired
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
public void saveHistory(Long id, String senderId) { public void saveHistory(Long id, String senderId) {
EventHistory eventHistory = new EventHistory(); EventHistory eventHistory = new EventHistory();
eventHistory.setDate(OffsetDateTime.now()); eventHistory.setDate(OffsetDateTime.now());
eventHistory.setEventId(id); eventHistory.setEventId(id);
eventHistory.setSenderId(senderId); eventHistory.setSenderId(senderId);
eventHistoryRepository.save(eventHistory); eventHistoryRepository.save(eventHistory);
} }
public ProcessMessageResult processMessage(String json, String senderId) throws Exception { public ProcessMessageResult processMessage(String json, String senderId) throws Exception {
ProcessMessageResult result = new ProcessMessageResult(); ProcessMessageResult result = new ProcessMessageResult();
log.debug(json);
MessageProcessed messageProcessed = detectType(json); MessageProcessed messageProcessed = detectType(json);
if (messageProcessed == null) { if (messageProcessed == null) {
result.setProcessed(false); result.setProcessed(false);
...@@ -50,6 +53,14 @@ public class ProcessMessageService { ...@@ -50,6 +53,14 @@ public class ProcessMessageService {
String name = (String) JsonUtils.getFieldFromJson(json, "$.name"); String name = (String) JsonUtils.getFieldFromJson(json, "$.name");
type = EventTypeEnum.fromString(event); type = EventTypeEnum.fromString(event);
if (type != null) { if (type != null) {
// Verify if message is valid
if (EventTypeEnum.USER.equals(type)) {
String message_id = (String) JsonUtils.getFieldFromJson(json, "$.message_id");
if (message_id == null) {
return null;
}
}
if (EventTypeEnum.ACTION.equals(type) && EventTypeEnum.START_SESSION.getName().equals(name)) { if (EventTypeEnum.ACTION.equals(type) && EventTypeEnum.START_SESSION.getName().equals(name)) {
type = EventTypeEnum.START_SESSION; type = EventTypeEnum.START_SESSION;
} }
...@@ -60,7 +71,6 @@ public class ProcessMessageService { ...@@ -60,7 +71,6 @@ public class ProcessMessageService {
} catch (Exception e) { } catch (Exception e) {
log.debug(e); log.debug(e);
} }
return messageProcessed; return messageProcessed;
} }
......
...@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service; ...@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional; import java.util.Optional;
@Service @Service
...@@ -43,6 +44,8 @@ public class StartSessionMessageProcessed extends MessageProcessedSupport implem ...@@ -43,6 +44,8 @@ public class StartSessionMessageProcessed extends MessageProcessedSupport implem
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME)); Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
if (timestamp != null) { if (timestamp != null) {
// Validate if the below method is ok
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX");
OffsetDateTime sessionDate = getOffsetDateTimeFromTimestampPython(timestamp); OffsetDateTime sessionDate = getOffsetDateTimeFromTimestampPython(timestamp);
if (sessionDate != null) { if (sessionDate != null) {
Session session = new Session(); Session session = new Session();
......
package com.bytesw.bytebot.etl.services; package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.beans.SessionBean; import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.ETLChannelRepository;
import com.bytesw.bytebot.etl.dao.IntentRepository; import com.bytesw.bytebot.etl.dao.IntentRepository;
import com.bytesw.bytebot.etl.dao.MessageRepository; import com.bytesw.bytebot.etl.dao.MessageRepository;
import com.bytesw.bytebot.etl.dao.UserRepository; import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum; import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import com.bytesw.bytebot.etl.jdbc.ETLMessageJDBCRepository; import com.bytesw.bytebot.etl.jdbc.ETLMessageJDBCRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository; import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.*; import com.bytesw.bytebot.etl.model.Intent;
import com.bytesw.bytebot.etl.model.Message;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils; import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.bytebot.jdbc.DeleteDataSensJDBCRepository;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.enums.AgentParameterEnum;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.repository.ChannelRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -18,8 +27,12 @@ import javax.annotation.PostConstruct; ...@@ -18,8 +27,12 @@ import javax.annotation.PostConstruct;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
@Log4j2
@Service @Service
@Transactional @Transactional
public class UserMessageProcessed extends MessageProcessedSupport implements MessageProcessed { public class UserMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
...@@ -31,7 +44,7 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes ...@@ -31,7 +44,7 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes
private ETLMessageJDBCRepository messageJDBCRepository; private ETLMessageJDBCRepository messageJDBCRepository;
@Autowired @Autowired
private ETLChannelRepository channelRepository; private ChannelRepository chanelRepository;
@Autowired @Autowired
private UserRepository userRepository; private UserRepository userRepository;
...@@ -42,6 +55,9 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes ...@@ -42,6 +55,9 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes
@Autowired @Autowired
private IntentRepository intentRepository; private IntentRepository intentRepository;
@Autowired
private DeleteDataSensJDBCRepository deleteDataSensJDBCRepository;
@Value("${application.etl.text-user.threshold:0.5}") @Value("${application.etl.text-user.threshold:0.5}")
private BigDecimal threshold; private BigDecimal threshold;
...@@ -63,26 +79,27 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes ...@@ -63,26 +79,27 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes
if (!userFound.isPresent()) { if (!userFound.isPresent()) {
return false; return false;
} }
SessionBean session = sessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId()); SessionBean session = sessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
if (session != null) { if (session != null) {
Message message = cloneMessage(json, session.getId()); /* ID del agente */
if (message != null) { Long agentId = identifierAgent(json);
int correlative = messageJDBCRepository.getLastCorrelativeBySession(message.getSessionId()); if (agentId >= 1) {
correlative++; Message message = cloneMessage(json, session.getId(), agentId);
message.setCorrelative(correlative); if (message != null) {
int correlative = messageJDBCRepository.getLastCorrelativeBySession(message.getSessionId());
messageRepository.save(message); correlative++;
message.setCorrelative(correlative);
String channel = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CHANNEL_FIELD_NAME));
messageRepository.save(message);
updateSession(session.getId(), message.getDate(), channel);
return true; String channel = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CHANNEL_FIELD_NAME));
updateSession(session.getId(), message.getDate(), channel);
return true;
}
} }
} }
} }
return false; return false;
} }
...@@ -92,17 +109,16 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes ...@@ -92,17 +109,16 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes
Session session = sessionFond.get(); Session session = sessionFond.get();
session.setLastEventDate(date); session.setLastEventDate(date);
if (channelIdentifier != null && session.getChannel() == null) { if (channelIdentifier != null && session.getChannel() == null) {
Optional<ETLChannel> channelFound = channelRepository.findByIdentifier(channelIdentifier); Optional<Channel> channelFound = chanelRepository.findByName(channelIdentifier);
if (channelFound.isPresent()) { if (channelFound.isPresent()) {
session.setChannel(channelFound.get()); session.setChannel(channelFound.get());
} }
} }
sessionBotRepository.save(session); sessionBotRepository.save(session);
} }
} }
private Message cloneMessage(String json, Long sessionId) { private Message cloneMessage(String json, Long sessionId, Long agentId) {
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME)); Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
Object confidence = JsonUtils.getFieldFromJson(json, this.fields.get(CONFIDENCE_FIELD_NAME)); Object confidence = JsonUtils.getFieldFromJson(json, this.fields.get(CONFIDENCE_FIELD_NAME));
String content = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CONTENT_FIELD_NAME)); String content = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CONTENT_FIELD_NAME));
...@@ -131,11 +147,44 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes ...@@ -131,11 +147,44 @@ public class UserMessageProcessed extends MessageProcessedSupport implements Mes
if (MessageTypeEnum.ACCEPTED.equals(message.getType())) { if (MessageTypeEnum.ACCEPTED.equals(message.getType())) {
String intentName = (String) JsonUtils.getFieldFromJson(json, this.fields.get(INTENT_NAME)); String intentName = (String) JsonUtils.getFieldFromJson(json, this.fields.get(INTENT_NAME));
Optional<Intent> optionalIntent = intentRepository.findByIdentifier(intentName); Optional<Intent> optionalIntent = intentRepository.findIntenNameById(intentName, agentId);
if (optionalIntent.isPresent()) { if (optionalIntent.isPresent()) {
message.setIntentId(optionalIntent.get().getId()); message.setIntentId(optionalIntent.get().getId());
} }
} }
return message; return message;
} }
//-------
private Long identifierAgent(String json){
Long agentId = 0l;
String number= (String) JsonUtils.getFieldFromJson(json, "$.metadata.To");
if (number != null) {
number = number.split(":")[1];
List<DeleteDataSensBean> deleteDataSensBeans = deleteDataSensJDBCRepository
.getListAgentChannel(AgentStatusEnum.DEPLOYED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
for (DeleteDataSensBean deleteDataSensBean: deleteDataSensBeans) {
Object numeros = JsonUtils.getFieldFromJson(deleteDataSensBean.getChannelValue(), "$.telefonos_desplegados");
List<String> numerosAgentes = numbersAgent((List<Map>) numeros);
if (numerosAgentes.contains(number)) {
agentId = deleteDataSensBean.getAgenId();
break;
}
}
}
return agentId;
}
private List<String> numbersAgent(List<Map> listNumber){
List<String> result = new ArrayList<>();
for (Map map : listNumber){
String cod = (String) map.get("CodigoInternacional");
String number = (String) map.get("numero");
String agent = "+" + cod + number;
result.add(agent);
}
return result;
}
//------
} }
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class AgentJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlsession;
@Cacheable(value = "deploy_agents")
public List<DeploymentChannelParamValueBean> getCredentialsFromAgentStatus(String status) {
SqlSession session = sqlsession.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
return session.selectList("com.bytesw.bytebot.dao.jdbc.AgentMapper.getCredentialsFromAgentandChannel", params);
} finally {
session.close();
}
}
}
...@@ -5,11 +5,13 @@ import org.apache.ibatis.session.SqlSessionFactory; ...@@ -5,11 +5,13 @@ 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 {
......
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean;
import com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class DeleteDataSensJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public List<DeleteDataSensBean> getListAgentChannel(String status, String channel){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
params.put("channel", channel);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getAgentChannel", params);
} finally {
session.close();
}
}
public DeleteDataSensControlBean getControl(Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("agenId", id);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getControl", params);
} finally {
session.close();
}
}
public List<String> getIntentByAgent(String sensible, Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sensible", sensible);
params.put("agenId", id);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getIntentByAgent", params);
} finally {
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();
......
...@@ -9,55 +9,60 @@ import com.bytesw.bytebot.model.enums.AgentTypeEnum; ...@@ -9,55 +9,60 @@ import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import com.bytesw.bytebot.model.enums.LanguageEnum; import com.bytesw.bytebot.model.enums.LanguageEnum;
import com.bytesw.bytebot.model.enums.StatusEnum; import com.bytesw.bytebot.model.enums.StatusEnum;
import lombok.*; import lombok.*;
import org.hibernate.annotations.Type;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; 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 = "BBOT_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")
public class Agent implements Serializable { public class Agent implements Serializable {
@Id @Id
@Column(name = "AGEN_ID") @Column(name = "agen_id")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_AGENT_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_AGENT_GENERATOR")
@TableGenerator(name = "BBOT_AGENT_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_AGENT_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_AGENT_SEQ", allocationSize = 1) pkColumnValue = "AVB_AGENT_SEQ", allocationSize = 1)
private Long id; private Long id;
@Column(name = "AGEN_IDEN") @Column(name = "agen_iden")
private String name; private String name;
@Column(name = "AGEN_DESCR") @Column(name = "agen_descr")
private String description; private String description;
@Column(name = "AGEN_VERS") @Column(name = "agen_vers")
private String version; private String version;
@Column(name = "AGEN_LANG") @Column(name = "agen_lang")
@Convert(converter = LanguageConverter.class) @Convert(converter = LanguageConverter.class)
private LanguageEnum language; private LanguageEnum language;
@Column(name = "AGEN_TZONE") @Column(name = "agen_tzone")
private String timezone; private String timezone;
@Column(name = "agen_delete_sensible_period")
private String period;
@Lob @Lob
@Type(type = "org.hibernate.type.TextType")
@Basic(fetch = FetchType.LAZY) @Basic(fetch = FetchType.LAZY)
@Column(name = "AGEN_AVAT") @Column(name = "agen_avat")
private String avatar; private String avatar;
@ManyToOne @ManyToOne
@JoinColumn(name = "COUN_ID", referencedColumnName = "COUN_ID") @JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
private Country country; private Country country;
@Column(name = "AGEN_STATE") @Column(name = "agen_state")
@Convert(converter = AgentStatusConverter.class) @Convert(converter = AgentStatusConverter.class)
private AgentStatusEnum status; private AgentStatusEnum status;
@Column(name = "AGEN_TYPE") @Column(name = "agen_type")
@Convert(converter = AgentTypeConverter.class) @Convert(converter = AgentTypeConverter.class)
private AgentTypeEnum type; private AgentTypeEnum type;
......
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
//@Audited
@Entity
@DiscriminatorValue(value=AnnualCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "AnnualCalendarException.findByPK", query = "Select u from AnnualCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class AnnualCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "Y";
@Column(name = "CALE_EXC_MONTH", nullable = false)
private int month;
@Column(name = "CALE_EXC_DAYMO", nullable = false)
private int dayOfMonth;
}
package com.bytesw.bytebot.model;
import com.bytesw.xdf.model.converter.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
@Audited
@Entity
@Table(name = "AVB_BUSINESS_PARAMETER")
@NamedQuery(name = "BusinessParameter.findByPK", query = "Select u from BusinessParameter u where u.id = ?1")
@Getter @Setter @EqualsAndHashCode @ToString(exclude = "id")
public class BusinessParameter implements Serializable {
@Id
@Column(name = "BUPA_ID")
@SequenceGenerator(name = "AVB_BUSINESS_PARAMETER_GENERATOR", sequenceName = "AVB_BUSINESS_PARAMETER_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BUSINESS_PARAMETER_GENERATOR")
private BigInteger id;
@Version
@Column(name = "VERSION")
@Basic(optional = false)
private long version;
@Column(name = "BUPA_KEY", nullable = false, unique = true)
private String key;
@Column(name = "BUPA_DESCR", nullable = false)
private String description;
@Column(name = "BUPA_REQUI", nullable = false)
@Convert(converter = BooleanToStringConverter.class)
private Boolean required;
@Column(name = "BUPA_DEFVA")
private String defaultValue;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
@Audited
@Entity
@Table(name = "AVB_BUSINESS_PARAMETER_CONFIG")
@NamedQuery(name = "BusinessParameterConfiguration.findByPK", query = "Select u from BusinessParameterConfiguration u where u.id = ?1")
@Getter @Setter @EqualsAndHashCode @ToString(exclude = "id")
public class BusinessParameterConfiguration implements Serializable, Comparable<BusinessParameterConfiguration> {
@Id
@Column(name = "BUPC_ID")
@SequenceGenerator(name = "AVB_BUSINESS_PARAMETER_CONFIG_GENERATOR", sequenceName = "AVB_BUSINESS_PARAM_CONFIG_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BUSINESS_PARAMETER_CONFIG_GENERATOR")
private BigInteger id;
@Version
@Column(name = "VERSION")
@Basic(optional = false)
private long version;
@Column(name = "BUPC_FROM", nullable = false)
private OffsetDateTime from;
@Column(name = "BUPC_TO")
private OffsetDateTime to;
@Column(name = "BUPC_VALUE", nullable = false)
private String value;
@ManyToOne(optional = false)
@JoinColumn(name = "BUPA_ID", referencedColumnName = "BUPA_ID", nullable = false)
private BusinessParameter businessParameter;
@Override
public int compareTo(BusinessParameterConfiguration o) {
return from.compareTo(o.getFrom());
}
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
//@Audited
@Entity
@Table(name = "AVB_CALENDAR")
@NamedQuery(name = "Calendar.findByPK", query = "Select u from Calendar u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class Calendar implements Serializable {
@Id
@Column(name = "cale_id")
private String id;
@Version
@Column(name = "cale_version")
@Basic(optional = false)
private long version;
@Column(name = "cale_name", nullable = false)
private String name;
@OneToMany(mappedBy = "calendar")
private List<WeekScheduler> weekSchedulerList;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.CalendarExceptionTypeConverter;
import com.bytesw.bytebot.model.converters.FrequencyTypeConverter;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
//@Audited
@Entity
@Inheritance(
strategy = InheritanceType.SINGLE_TABLE
)
@DiscriminatorColumn(name="CALE_EXC_FRECU", discriminatorType = DiscriminatorType.STRING)
@Table(name = "AVB_CALENDAR_EXCEPTION")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public abstract class CalendarException implements Serializable {
@Id
@Column(name = "CALE_EXC_ID")
// @SequenceGenerator(name = "AVB_CALENDAR_EXCEPTION_GENERATOR", sequenceName = "AVB_CALENDAR_EXCEPTION_SEQ", initialValue = 1, allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CALENDAR_EXCEPTION_GENERATOR")
private BigInteger id;
@Version
@Column(name = "CALE_EXC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "CALE_EXC_TYPE")
@Convert(converter = CalendarExceptionTypeConverter.class)
private CalendarExceptionType calendarExceptionType;
@Column(name = "CALE_EXC_FRECU", insertable = false, updatable = false)
private String frequencyType;
@Column(name = "CALE_EXC_DESCR")
private String description;
@ManyToOne(optional = false)
@JoinColumn(name = "CALE_ID", referencedColumnName = "CALE_ID", nullable = false)
private Calendar calendar;
}
\ No newline at end of file
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.CalendarExceptionTypeConverter;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
//@Audited
@Entity
@Inheritance(
strategy = InheritanceType.SINGLE_TABLE
)
@DiscriminatorColumn(name="CALE_EXC_FRECU", discriminatorType = DiscriminatorType.STRING)
@Table(name = "AVB_CALENDAR_EXCEPTION")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class CalendarExceptionFull implements Serializable {
@Id
@Column(name = "CALE_EXC_ID")
// @SequenceGenerator(name = "AVB_CALENDAR_EXCEPTION_GENERATOR", sequenceName = "AVB_CALENDAR_EXCEPTION_SEQ", initialValue = 1, allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CALENDAR_EXCEPTION_GENERATOR")
private BigInteger id;
@Version
@Column(name = "CALE_EXC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "CALE_EXC_TYPE")
@Convert(converter = CalendarExceptionTypeConverter.class)
private CalendarExceptionType calendarExceptionType;
@Column(name = "CALE_EXC_FRECU", insertable = false, updatable = false)
private String frequencyType;
@Column(name = "CALE_EXC_DESCR")
private String description;
@Column(name = "CALE_ID")
private String calendarID;
// @ManyToOne(optional = false)
// @JoinColumn(name = "CALE_ID", referencedColumnName = "CALE_ID", nullable = false)
// private Calendar calendar;
@Column(name = "CALE_EXC_MONTH")
private BigInteger month;
@Column(name = "CALE_EXC_DAYMO")
private BigInteger dayOfMonth;
@Column(name = "CALE_EXC_WEEK")
private BigInteger weekOfMonth;
@Column(name = "CALE_EXC_DAYWE")
private BigInteger dayOfWeek;
@Column(name = "CALE_EXC_DATE")
private LocalDate date;
@Column(name = "CALE_EXC_FROM")
private OffsetDateTime from;
@Column(name = "CALE_EXC_TO")
private OffsetDateTime to;
}
\ No newline at end of file
...@@ -20,18 +20,16 @@ import java.util.List; ...@@ -20,18 +20,16 @@ import java.util.List;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
@Entity @Entity
@Table(name = "BBOT_CHANNEL") @Table(name = "AVB_CHANNEL")
@Getter @Getter @Setter @ToString
@Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false) @EqualsAndHashCode(of = {"id"}, callSuper = false)
public class Channel { public class Channel {
@Id @Id
@Column(name = "CHAN_ID") @Column(name = "CHAN_ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_CHANNEL_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_CHANNEL_GENERATOR")
@TableGenerator(name = "BBOT_CHANNEL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_CHANNEL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_CHANNEL_SEQ", allocationSize = 1) pkColumnValue = "AVB_CHANNEL_SEQ", allocationSize = 1)
private Long id; private Long id;
@Column(name = "CHAN_IDEN") @Column(name = "CHAN_IDEN")
......
...@@ -20,7 +20,7 @@ import javax.persistence.*; ...@@ -20,7 +20,7 @@ import javax.persistence.*;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
@Entity @Entity
@Table(name = "BBOT_CHANNEL_PARAM") @Table(name = "AVB_CHANNEL_PARAM")
@Getter @Getter
@Setter @Setter
@ToString @ToString
...@@ -29,9 +29,9 @@ public class ChannelParam { ...@@ -29,9 +29,9 @@ public class ChannelParam {
@Id @Id
@Column(name = "CHPA_ID") @Column(name = "CHPA_ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_CHANNEL_PARAM_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_CHANNEL_PARAM_GENERATOR")
@TableGenerator(name = "BBOT_CHANNEL_PARAM_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_CHANNEL_PARAM_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_CHANNEL_PARAM_SEQ", allocationSize = 1) pkColumnValue = "AVB_CHANNEL_PARAM_SEQ", allocationSize = 1)
private Long id; private Long id;
@Column(name = "CHPA_IDEN") @Column(name = "CHPA_IDEN")
......
...@@ -9,20 +9,19 @@ import java.util.List; ...@@ -9,20 +9,19 @@ import java.util.List;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@EqualsAndHashCode(of = "id")
@NoArgsConstructor @NoArgsConstructor
@Table(name = "BBOT_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")
public class Country { public class Country {
@Id @Id
@Column(name = "COUN_ID") @Column(name = "coun_id")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_COUNTRY_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_COUNTRY_GENERATOR")
@TableGenerator(name = "BBOT_COUNTRY_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_COUNTRY_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_COUNTRY_SEQ", allocationSize = 1) pkColumnValue = "AVB_COUNTRY_SEQ", allocationSize = 1)
private Long id; private Long id;
@Column(name = "COUN_NAME", nullable = false) @Column(name = "coun_name", nullable = false)
private String name; private String name;
@OneToMany(mappedBy = "country") @OneToMany(mappedBy = "country")
......
...@@ -22,18 +22,17 @@ import java.util.List; ...@@ -22,18 +22,17 @@ import java.util.List;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
@Entity @Entity
@Table(name = "BBOT_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 {
@Id @Id
@Column(name = "DCHA_ID") @Column(name = "DCHA_ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_DEPLOYMENT_CHANNEL_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_DEPLOYMENT_CHANNEL_GENERATOR")
@TableGenerator(name = "BBOT_DEPLOYMENT_CHANNEL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_DEPLOYMENT_CHANNEL_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_DEPLOYMENT_CHANNEL_SEQ", allocationSize = 1) pkColumnValue = "AVB_DEPLOYMENT_CHANNEL_SEQ", allocationSize = 1)
private Long id; private Long id;
@Column(name = "DCHA_NAME") @Column(name = "DCHA_NAME")
......
...@@ -19,7 +19,7 @@ import javax.persistence.*; ...@@ -19,7 +19,7 @@ import javax.persistence.*;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
@Entity @Entity
@Table(name = "BBOT_DEPLOYMENT_CHANNEL_PARAM_VALUE") @Table(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE")
@Getter @Getter
@Setter @Setter
@ToString @ToString
...@@ -28,9 +28,9 @@ public class DeploymentChannelParamValue { ...@@ -28,9 +28,9 @@ public class DeploymentChannelParamValue {
@Id @Id
@Column(name = "CHPV_ID") @Column(name = "CHPV_ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR")
@TableGenerator(name = "BBOT_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_DEPLOYMENT_CHANNEL_PARAM_VALUE_SEQ", allocationSize = 1) pkColumnValue = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_SEQ", allocationSize = 1)
private Long id; private Long id;
@ManyToOne @ManyToOne
......
...@@ -25,7 +25,7 @@ import java.time.OffsetDateTime; ...@@ -25,7 +25,7 @@ import java.time.OffsetDateTime;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
@Entity @Entity
@Table(name = "BBOT_FREQUENT_QUESTION") @Table(name = "AVB_FREQUENT_QUESTION")
@Getter @Getter
@Setter @Setter
@ToString @ToString
...@@ -33,9 +33,9 @@ import java.time.OffsetDateTime; ...@@ -33,9 +33,9 @@ import java.time.OffsetDateTime;
public class FrequentQuestion { public class FrequentQuestion {
@Id @Id
@Column(name = "FQUE_ID") @Column(name = "FQUE_ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_FREQUENT_QUESTION_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_FREQUENT_QUESTION_GENERATOR")
@TableGenerator(name = "BBOT_FREQUENT_QUESTION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", @TableGenerator(name = "AVB_FREQUENT_QUESTION_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT",
pkColumnValue = "BBOT_FREQUENT_QUESTION_SEQ", initialValue = 1, allocationSize = 1) pkColumnValue = "AVB_FREQUENT_QUESTION_SEQ", initialValue = 1, allocationSize = 1)
private Long id; private Long id;
@Column(name = "FQUE_UUID") @Column(name = "FQUE_UUID")
......
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
//@Audited
@Entity
@Table(name = "avb_process_etl")
@NamedQuery(name = "ProcessETL.findByPK", query = "Select u from ProcessETL u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class ProcessETL implements Serializable {
@Id
@Column(name = "etl_id")
private int id;
@Version
@Column(name = "etl_version")
@Basic(optional = false)
private long version;
@Column(name = "etl_name", nullable = false)
private String name;
}
...@@ -22,6 +22,7 @@ import lombok.Getter; ...@@ -22,6 +22,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.annotations.Type;
@Entity @Entity
@Getter @Getter
...@@ -29,15 +30,15 @@ import lombok.ToString; ...@@ -29,15 +30,15 @@ import lombok.ToString;
@ToString @ToString
@EqualsAndHashCode(of = "id") @EqualsAndHashCode(of = "id")
@NoArgsConstructor @NoArgsConstructor
@Table(name = "BBOT_QUESTION_FILE") @Table(name = "AVB_QUESTION_FILE")
@NamedQuery(name = "QuestionFile.findByPK", query = "Select u from QuestionFile u where u.id = ?1") @NamedQuery(name = "QuestionFile.findByPK", query = "Select u from QuestionFile u where u.id = ?1")
public class QuestionFile { public class QuestionFile {
@Id @Id
@Column(name = "QUFI_ID") @Column(name = "QUFI_ID")
@TableGenerator(name = "BBOT_QUESTION_FILE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", @TableGenerator(name = "AVB_QUESTION_FILE_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "BBOT_QUESTION_FILE_SEQ", allocationSize = 1) valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_QUESTION_FILE_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "BBOT_QUESTION_FILE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_QUESTION_FILE_GENERATOR")
private Long id; private Long id;
@Column(name = "QUFI_UUID", nullable = false) @Column(name = "QUFI_UUID", nullable = false)
...@@ -52,7 +53,7 @@ public class QuestionFile { ...@@ -52,7 +53,7 @@ public class QuestionFile {
@Column(name = "QUFI_UDATE", columnDefinition = "TIMESTAMP") @Column(name = "QUFI_UDATE", columnDefinition = "TIMESTAMP")
private LocalDateTime uploadDate; private LocalDateTime uploadDate;
@Lob @Type(type="org.hibernate.type.BinaryType")
@Basic(fetch = FetchType.LAZY) @Basic(fetch = FetchType.LAZY)
@Column(name = "QUFI_DATA", length= 100000, nullable = false) @Column(name = "QUFI_DATA", length= 100000, nullable = false)
private byte[] data; private byte[] data;
......
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import java.time.OffsetDateTime;
//@Audited
@Entity
@DiscriminatorValue(value= RangeCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "RangeCalendarException.findByPK", query = "Select u from RangeCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class RangeCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "R";
@Column(name = "CALE_EXC_FROM", nullable = false)
private OffsetDateTime from;
@Column(name = "CALE_EXC_TO", nullable = false)
private OffsetDateTime to;
}
\ No newline at end of file
package com.bytesw.bytebot.model;
import com.bytesw.xdf.model.converter.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
//@Audited
@Entity
@Table(name = "AVB_SCHEDULER_TASK")
@NamedQuery(name = "SchedulerTask.findByPK", query = "Select u from SchedulerTask u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "id")
public class SchedulerTask implements Serializable {
@Id
@Column(name = "SHTA_ID")
// @SequenceGenerator(name = "AVB_SCHEDULER_TASK_GENERATOR", sequenceName = "AVB_SCHEDULER_TASK_SEQ", initialValue = 1, allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_SCHEDULER_TASK_GENERATOR")
private BigInteger id;
@Version
@Column(name = "SHTA_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "SHTA_DESCR", nullable = false)
private String description;
@Column(name = "SHTA_INTER", nullable = false)
@Convert(converter = BooleanToStringConverter.class)
private Boolean internals;
@Column(name = "SHTA_CROEX", nullable = false)
private String cronExpression;
@Column(name = "SHTA_PARAM")
private String stringParameters;
@Column(name= "cale_id")
private String calendarID;
@ManyToOne(optional = false)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "CALE_ID", referencedColumnName = "CALE_ID", nullable = false)
private Calendar calendar;
/*@ManyToOne(optional = false)
@JoinColumn(name = "ETL_ID", referencedColumnName = "ETL_ID", nullable = false)
private ProcessETL processETL;*/
@Column(name = "etl_id")
private Integer processETL;
}
...@@ -17,22 +17,23 @@ import javax.persistence.*; ...@@ -17,22 +17,23 @@ import javax.persistence.*;
*/ */
@Entity @Entity
@Getter @Setter @ToString @EqualsAndHashCode(of = "id") @Getter @Setter
@NoArgsConstructor @NoArgsConstructor
@Table(name = "BBOT_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 = "BBOT_TIMEZONE_GENERATOR") @GeneratedValue(strategy = GenerationType.TABLE, generator = "avb_timezone_generator")
@TableGenerator(name = "BBOT_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 = "BBOT_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)
private String timezone; private String timezone;
@ManyToOne @ManyToOne
@JoinColumn(name = "COUN_ID", referencedColumnName = "COUN_ID") @JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
private Country country; private Country country;
} }
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import java.time.LocalDate;
//@Audited
@Entity
@DiscriminatorValue(value= UniqueCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "UniqueCalendarException.findByPK", query = "Select u from UniqueCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class UniqueCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "U";
@Column(name = "CALE_EXC_DATE", nullable = true)
private LocalDate date;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
//@Audited
@Entity
@DiscriminatorValue(value= UniqueWeeklyCalendarException.DISCRIMINATOR_VALUE)
@NamedQuery(name = "UniqueWeeklyCalendarException.findByPK", query = "Select u from UniqueWeeklyCalendarException u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class UniqueWeeklyCalendarException extends CalendarException {
public static final String DISCRIMINATOR_VALUE = "W";
@Column(name = "CALE_EXC_MONTH", nullable = false)
private int month;
@Column(name = "CALE_EXC_WEEK", nullable = false)
private int weekOfMonth;
@Column(name = "CALE_EXC_DAYWE", nullable = false)
private int dayOfWeek;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
//@Audited
@Entity
@Table(name = "AVB_WEEK_SCHEDULER")
@NamedQuery(name = "WeekScheduler.findByPK", query = "Select u from WeekScheduler u where u.id = ?1")
@Getter
@Setter
@EqualsAndHashCode
@ToString(exclude = "calendar")
public class WeekScheduler implements Serializable {
@Id
@Column(name = "WESC_ID")
// @SequenceGenerator(name = "AVB_WEEK_SCHEDULER_GENERATOR", sequenceName = "AVB_WEEK_SCHEDULER_SEQ", initialValue = 1, allocationSize = 1)
// @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_WEEK_SCHEDULER_GENERATOR")
private BigInteger id;
@Version
@Column(name = "WESC_VERSION")
@Basic(optional = false)
private long version;
@Column(name = "WESC_DAY", nullable = false)
private int dayOfWeek;
@Column(name = "WESC_FROM", nullable = false)
private OffsetDateTime from;
@Column(name = "WESC_TO", nullable = false)
private OffsetDateTime to;
@Column(name = "CALE_ID")
private String calendarID;
@ManyToOne(optional = false)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "cale_id", referencedColumnName = "cale_id", nullable = false)
private Calendar calendar;
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* @author Renzo Carranza
* @version 26/08/2021
* <p>
* Copyright (c) 2019 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
@Converter
public class CalendarExceptionTypeConverter implements AttributeConverter<CalendarExceptionType, String> {
@Override
public String convertToDatabaseColumn(CalendarExceptionType calendarExceptionType) {
if (calendarExceptionType == null) return null;
return calendarExceptionType.getName();
}
@Override
public CalendarExceptionType convertToEntityAttribute(String s) {
return CalendarExceptionType.fromString(s);
}
}
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.FrequencyType;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class FrequencyTypeConverter implements AttributeConverter<FrequencyType, String> {
@Override
public String convertToDatabaseColumn(FrequencyType frequencyType) {
if (frequencyType == null) return null;
return frequencyType.getName();
}
@Override
public FrequencyType convertToEntityAttribute(String s) {
return FrequencyType.fromString(s);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum AgentParameterEnum {
ACCESS_ID("account-identifier"),
ACCESS_TOKEN("authentication-token"),
ACCESS_TWILIO("twillio-number");
private static final Map<String, AgentParameterEnum> map = new HashMap<>();
private String name;
AgentParameterEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (AgentParameterEnum type : AgentParameterEnum.values()) {
map.put(type.name, type);
}
}
public static AgentParameterEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum CalendarExceptionType {
HOLIDAY("H"), WORK_EXCEPTION("W"), NO_WORK_EXCEPTION("N");
private final String name;
private static final Map<String, CalendarExceptionType> map = new HashMap<>();
static {
for (CalendarExceptionType type : CalendarExceptionType.values()) {
map.put(type.name, type);
}
}
CalendarExceptionType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static CalendarExceptionType fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
\ No newline at end of file
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.model.enums;
import com.bytesw.bytebot.model.AnnualCalendarException;
import com.bytesw.bytebot.model.RangeCalendarException;
import com.bytesw.bytebot.model.UniqueCalendarException;
import com.bytesw.bytebot.model.UniqueWeeklyCalendarException;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum FrequencyType {
ANNUAL(AnnualCalendarException.DISCRIMINATOR_VALUE),
UNIQUE(UniqueCalendarException.DISCRIMINATOR_VALUE),
UniqueWeekly(UniqueWeeklyCalendarException.DISCRIMINATOR_VALUE),
RANGE(RangeCalendarException.DISCRIMINATOR_VALUE);
private final String name;
private static final Map<String, FrequencyType> map = new HashMap<>();
static {
for (FrequencyType type : FrequencyType.values()) {
map.put(type.name, type);
}
}
FrequencyType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static FrequencyType fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum MetricMessageTypeEnum {
RECEIVED("received"),
SENT("sent"),
SESSION("session");
private static final Map<String, MetricMessageTypeEnum> map = new HashMap<>();
private String name;
MetricMessageTypeEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (MetricMessageTypeEnum type : MetricMessageTypeEnum.values()) {
map.put(type.name, type);
}
}
public static MetricMessageTypeEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum ProcessETLEnum {
PROCESS_DELETE ( "Eliminación de Data Sensible");
private final String name;
private static final Map<String, ProcessETLEnum> map = new HashMap<>();
static {
for (ProcessETLEnum type : ProcessETLEnum.values()) {
map.put(type.name, type);
}
}
ProcessETLEnum (String name) {
this.name = name;
}
public String getName() {
return name;
}
public static ProcessETLEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum ProviderErrorEnum {
AUTHENTICATE("Authenticate"),
CONEXION("name resolution");
private static final Map<String, ProviderErrorEnum> map = new HashMap<>();
private String name;
ProviderErrorEnum(String name){ this.name = name;}
public String getName() {return name;}
static {
for (ProviderErrorEnum type : ProviderErrorEnum.values()) {
map.put(type.name, type);
}
}
public static ProviderErrorEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.repository; package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Agent; import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.bean.AgentBean;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import java.util.List;
/** /**
* @author Sebastián Chicoma Sandmann. * @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020 * @version 9-sep-2020
...@@ -16,4 +20,6 @@ import org.springframework.data.repository.CrudRepository; ...@@ -16,4 +20,6 @@ import org.springframework.data.repository.CrudRepository;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
public interface AgentRepository extends CrudRepository<Agent, Long>, JpaSpecificationExecutor<Agent> { public interface AgentRepository extends CrudRepository<Agent, Long>, JpaSpecificationExecutor<Agent> {
List<Agent> findByStatus(AgentStatusEnum status);
} }
package com.bytesw.bytebot.repository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface BusinessParameterConfigurationRepository extends CrudRepository<BusinessParameterConfiguration, BigInteger>, JpaSpecificationExecutor<BusinessParameterConfiguration> {
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :fromDate and b.to >= :fromDate) OR (b.to is null))")
List<BusinessParameterConfiguration> findValidByKey(@Param("key") String key, @Param("fromDate") OffsetDateTime fromDate);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.key = :key and ((b.from < :currentDate and b.to >= :currentDate) OR (b.from < :currentDate and b.to is null))")
Optional<BusinessParameterConfiguration> findCurrentValueByKey(@Param("key") String key, @Param("currentDate") OffsetDateTime currentDate);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id")
List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameter(@Param("id") BigInteger id);
@Query("select b from BusinessParameterConfiguration b where b.businessParameter.id = :id and (b.to > :toDate or b.to is null) order by b.from desc")
List<BusinessParameterConfiguration> findBusinessParameterConfigurationListByBusinessParameterWithLowestDateFrom(@Param("id") BigInteger id, @Param("toDate") OffsetDateTime toDate);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.BusinessParameter;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.Optional;
/**
* @author Renzo Carranza
* @version 26/08/2021
* <p>
* Copyright (c) 2019 Byte, S.A. Todos los derechos reservados.
* <p>
* Este software constituye información confidencial y propietaria de Byte, S.A.
* ("Información Confidencial"). Usted no debe develar dicha Información
* Confidencial y debe usarla de acuerdo con los términos de aceptación de
* licencia de uso que firmó con Byte.
*/
public interface BusinessParameterRepository extends CrudRepository<BusinessParameter, BigInteger>, JpaSpecificationExecutor<BusinessParameter> {
@Query("select b from BusinessParameter b where b.key = :key")
Optional<BusinessParameter> findByKey(@Param("key") String key);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.CalendarExceptionFull;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface CalendarExceptionFullRepository extends CrudRepository<CalendarExceptionFull, BigInteger>, JpaSpecificationExecutor<CalendarExceptionFull> {
@Query("select s from CalendarExceptionFull s where s.calendarID = :calendarId")
Optional<List<CalendarExceptionFull>> findByCalendarId(@Param("calendarId") String calendarId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
public interface CalendarExceptionRepository extends CrudRepository<CalendarException, BigInteger>, JpaSpecificationExecutor<CalendarException> {
@Query("select s from RangeCalendarException s where s.calendar.id = :calendarId and s.from < :date and s.to > :date and s.calendarExceptionType = :type")
Optional<CalendarException> findByRangeExceptionByCalendarIdAndDateAndType(@Param("calendarId") String calendarId, @Param("date") OffsetDateTime date, @Param("type") CalendarExceptionType type);
@Query("select s from AnnualCalendarException s where s.calendar.id = :calendarId and s.month = :month and s.dayOfMonth = :dayOfMonth")
Optional<CalendarException> findByAnnualExceptionByCalendarIdAndYearAndDay(@Param("calendarId") String calendarId, @Param("month") int month, @Param("dayOfMonth") int dayOfMonth);
@Query("select s from UniqueCalendarException s where s.calendar.id = :calendarId and s.date = :date")
Optional<CalendarException> findByUniqueExceptionByCalendarIdAndDate(@Param("calendarId") String calendarId, @Param("date") LocalDate date);
@Query("select s from UniqueWeeklyCalendarException s where s.calendar.id = :calendarId and s.month = :month and s.dayOfWeek = :dayOfWeek and s.weekOfMonth = :weekOfMonth")
Optional<CalendarException> findByUniqueWeeklyExceptionByCalendarIdAndDayOfWeekAndWeekOfMonth(@Param("calendarId") String calendarId, @Param("month") int month, @Param("dayOfWeek") int dayOfWeek, @Param("weekOfMonth") int weekOfMonth);
@Query("select s from RangeCalendarException s where s.calendar.id = :calendarId and s.from >= :date and s.calendarExceptionType = :type")
Optional<CalendarException> findByRangeExceptionByCalendarIdFromDateAndType(@Param("calendarId") String calendarId, @Param("date") OffsetDateTime date, @Param("type") CalendarExceptionType type);
@Query("select s from CalendarException s where s.calendar.id = :calendarId")
Optional<List<CalendarException>> findByCalendarId(@Param("calendarId") String calendarId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Calendar;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
public interface CalendarRepository extends CrudRepository<Calendar, String>, JpaSpecificationExecutor<Calendar> {
}
\ No newline at end of file
...@@ -3,6 +3,8 @@ package com.bytesw.bytebot.repository; ...@@ -3,6 +3,8 @@ package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Channel; import com.bytesw.bytebot.model.Channel;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/** /**
* @author Sebastián Chicoma Sandmann. * @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020 * @version 9-sep-2020
...@@ -15,4 +17,6 @@ import org.springframework.data.repository.CrudRepository; ...@@ -15,4 +17,6 @@ import org.springframework.data.repository.CrudRepository;
* licencia de uso que firmó con Byte. * licencia de uso que firmó con Byte.
*/ */
public interface ChannelRepository extends CrudRepository<Channel, Long> { public interface ChannelRepository extends CrudRepository<Channel, Long> {
Optional<Channel> findByName(String 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> { }
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.GoalForActions;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;
public interface GoalForActionsRepository extends CrudRepository<GoalForActions, Long>, JpaSpecificationExecutor<GoalForActions> {
@Query("select s from GoalForActions s where s.goalId= :goalId")
Optional<List<GoalForActions>> findGoalForActionsByGoalId(@Param("goalId") Long goalId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.Goal;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface GoalRepository extends CrudRepository<Goal, Long>, JpaSpecificationExecutor<Goal> {
@Query("select s from Goal s where s.agenId = :agentId and s.identifier = :identifier")
Optional<Goal> findByAgentAndIdent(@Param("agentId") Long agentId, @Param("identifier") String identifier);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.ProcessETL;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface ProcessETLRepository extends CrudRepository<ProcessETL, Integer>, JpaSpecificationExecutor<ProcessETL> {
@Query("select b from ProcessETL b where b.name = :etlName")
ProcessETL findByName(@Param("etlName") String etlName);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.SchedulerTask;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
public interface SchedulerTaskRepository extends CrudRepository<SchedulerTask, BigInteger>, JpaSpecificationExecutor<SchedulerTask> {
@Query("select b from SchedulerTask b where b.calendar.id = :calendarId")
Optional<List<SchedulerTask>> findByCalendarId(@Param("calendarId") String calendarId);
@Query("select b from SchedulerTask b where b.processETL = :processId")
List<SchedulerTask> findByEtlId(@Param("processId") int processId);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.WeekScheduler;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
public interface WeekSchedulerRepository extends CrudRepository<WeekScheduler, BigInteger>, JpaSpecificationExecutor<WeekScheduler> {
@Query("select b from WeekScheduler b where b.calendarID = :caleId")
Optional<List<WeekScheduler>> findByCalendarId(@Param("caleId") String caleId);
}
...@@ -2,6 +2,7 @@ package com.bytesw.bytebot.service; ...@@ -2,6 +2,7 @@ package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.*; import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.model.*; import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.jdbc.AgentJDBCRepository;
import com.bytesw.bytebot.model.enums.*; import com.bytesw.bytebot.model.enums.*;
import com.bytesw.bytebot.repository.*; import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.config.AppContextManager; import com.bytesw.xdf.config.AppContextManager;
...@@ -9,6 +10,7 @@ import com.bytesw.xdf.sql.beans.Pagination; ...@@ -9,6 +10,7 @@ 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.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;
...@@ -30,6 +32,9 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -30,6 +32,9 @@ public class AgentService extends CustomPaginationService<Agent> {
@Autowired @Autowired
private AgentRepository agentRepository; private AgentRepository agentRepository;
@Autowired
private AgentJDBCRepository agentJDBCRepository;
@Autowired @Autowired
private CountryRepository countryRepository; private CountryRepository countryRepository;
...@@ -53,7 +58,17 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -53,7 +58,17 @@ public class AgentService extends CustomPaginationService<Agent> {
@Autowired @Autowired
private ProducerTemplate producerTemplate; private ProducerTemplate producerTemplate;
public List<DeploymentChannelParamValueBean> GetKeysFromAgents(AgentStatusEnum status){
List<DeploymentChannelParamValueBean> values = agentJDBCRepository.getCredentialsFromAgentStatus(status.getName());
if (values == null){
values = new ArrayList<>();
}
//log.debug(values);
return values;
}
public void searchByPagination(Pagination<AgentBean> pagination) { public void searchByPagination(Pagination<AgentBean> pagination) {
if (pagination.getItemsPerPage() == 0) { if (pagination.getItemsPerPage() == 0) {
pagination.setItemsPerPage(10); pagination.setItemsPerPage(10);
...@@ -94,6 +109,7 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -94,6 +109,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;
...@@ -260,7 +276,6 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -260,7 +276,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
...@@ -316,7 +331,6 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -316,7 +331,6 @@ public class AgentService extends CustomPaginationService<Agent> {
} else { } else {
deploymentChannelParamValue.setParameter(null); deploymentChannelParamValue.setParameter(null);
} }
deploymentChannelParamValueRepository.save(deploymentChannelParamValue); deploymentChannelParamValueRepository.save(deploymentChannelParamValue);
} }
...@@ -422,6 +436,9 @@ public class AgentService extends CustomPaginationService<Agent> { ...@@ -422,6 +436,9 @@ public class AgentService extends CustomPaginationService<Agent> {
agentRepository.save(agent); agentRepository.save(agent);
} }
} }
else{
isValid = false;
}
return isValid; return isValid;
} }
......
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.Optional;
@Service
@Transactional
public class BusinessParameterConfigurationService extends XDFService<BusinessParameterConfiguration, BusinessParameterConfigurationBean, BigInteger> {
@Autowired
private BusinessParameterService gatewayBusinessParameterService;
@Autowired
private BusinessParameterRepository businessParameterRepository;
@Autowired
private BusinessParameterConfigurationRepository businessParameterConfigurationRepository;
protected BusinessParameterConfigurationService(BusinessParameterConfigurationRepository repository) {
super(repository);
}
@Override
protected BusinessParameterConfiguration toModel(BusinessParameterConfiguration model, BusinessParameterConfigurationBean bean) {
if (model == null) {
model = new BusinessParameterConfiguration();
}
BeanUtils.copyProperties(bean, model);
if (bean.getBusinessParameters() == null) {
throw new NotFoundException("BusinessParameter can not be null");
}
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findById(bean.getBusinessParameters().getId());
if (!businessParameterOptional.isPresent()) {
throw new NotFoundException("BusinessParameter not found " + bean.getBusinessParameters().getId());
}
model.setBusinessParameter(businessParameterOptional.get());
return model;
}
@Override
protected BusinessParameterConfigurationBean toBean(BusinessParameterConfiguration model) {
BusinessParameterConfigurationBean bean = new BusinessParameterConfigurationBean();
BeanUtils.copyProperties(model, bean);
bean.setBusinessParameters(gatewayBusinessParameterService.toBean(model.getBusinessParameter()));
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.bean.BusinessParameterBean;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.bytebot.bean.BusinessParameterValueBean;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import java.math.BigInteger;
import java.time.OffsetDateTime;
import java.util.*;
@Service
@Transactional
public class BusinessParameterService extends XDFService<BusinessParameter, BusinessParameterBean, BigInteger> {
@Autowired
BusinessParameterRepository businessParameterRepository;
@Autowired
BusinessParameterConfigurationRepository businessParameterConfigurationRepository;
@Autowired
private BusinessParameterService businessParameterService;
@Autowired
private BusinessParameterConfigurationService businessParameterConfigurationService;
protected BusinessParameterService(BusinessParameterRepository repository) {
super(repository);
}
@Override
protected BusinessParameter toModel(BusinessParameter model, BusinessParameterBean bean) {
if (model == null) {
model = new BusinessParameter();
}
BeanUtils.copyProperties(bean, model);
model.setRequired("Y".equals(bean.getRequired()));
return model;
}
@Override
protected BusinessParameterBean toBean(BusinessParameter model) {
BusinessParameterBean bean = new BusinessParameterBean();
BeanUtils.copyProperties(model, bean);
bean.setRequired(model.getRequired() ? "Y" : "N");
BusinessParameterConfigurationBean businessParameterConfigurationBean = getBusinessConfiguration(model.getId());
bean.setCurrentValue(businessParameterConfigurationBean.getValue());
bean.setDateFrom(businessParameterConfigurationBean.getFrom());
bean.setDateApplyFrom(businessParameterConfigurationBean.getTo());
bean.setProgrammedValue(businessParameterConfigurationBean.getProgrammedValue());
bean.setCurrentConfigurationId(businessParameterConfigurationBean.getCurrentConfigurationId());
bean.setProgrammedConfigurationId(businessParameterConfigurationBean.getProgrammedConfigurationId());
return bean;
}
/**
* Permite crear un parámetro general utilizando el valor y la fecha de aplicación. Si la fecha no viene entonces se utiliza la fecha actual.
* <p></p>
*
* @param bean
* @return
*/
public BusinessParameterValueBean createWithValue(BusinessParameterValueBean bean) {
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findByKey(bean.getKey());
if (businessParameterOptional.isPresent()) {
String message = String.format("BusinessParameter is already created: %s. ", bean.getKey());
throw new AlreadyExistsException(message);
}
BusinessParameter businessParameter = new BusinessParameter();
businessParameter.setKey(bean.getKey());
businessParameter.setDescription(bean.getDescription());
businessParameter.setRequired(bean.isRequired());
businessParameter.setDefaultValue(bean.getDefaultValue());
businessParameter = businessParameterRepository.save(businessParameter);
if (bean.getFrom() == null) {
bean.setFrom(OffsetDateTime.now());
}
BusinessParameterConfiguration businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameter, bean.getValue(), bean.getFrom());
businessParameterConfiguration.setBusinessParameter(businessParameter);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
bean.setId(businessParameter.getId());
return bean;
}
/**
* Este método parte de que solo se puede un valor actual y/o un valor programado.
*
* @param key
* @param value
* @return
*/
public void addValue(String key, String value, OffsetDateTime from) {
Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findByKey(key);
if (!businessParameterOptional.isPresent()) {
String message = String.format("BusinessParameter %s not found.", key);
throw new NotFoundException(message);
}
if (from == null) {
from = OffsetDateTime.now();
} else if (from.compareTo(OffsetDateTime.now()) < 0) {
String message = String.format("New date (%s) for the parameter (%s) cannot be less than the current", key, from.toString());
throw new NotFoundException(message);
}
List<BusinessParameterConfiguration> businessParameterConfigurationList = businessParameterConfigurationRepository.findValidByKey(key, from);
if (businessParameterConfigurationList.isEmpty()) {
BusinessParameterConfiguration businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameterOptional.get(), value, from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
} else {
Collections.sort(businessParameterConfigurationList);
OffsetDateTime temporallyTo = null;
for (BusinessParameterConfiguration businessParameterConfiguration : businessParameterConfigurationList) {
if (businessParameterConfiguration.getTo() != null) {
if (temporallyTo != null) {
businessParameterConfiguration.setFrom(temporallyTo);
}
temporallyTo = businessParameterConfiguration.getTo();
businessParameterConfiguration.setTo(from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
continue;
}
if (temporallyTo != null) {
businessParameterConfiguration.setFrom(from);
businessParameterConfiguration.setValue(value);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
} else {
businessParameterConfiguration.setTo(from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
businessParameterConfiguration = prepareBusinessParameterConfiguration(businessParameterOptional.get(), value, from);
businessParameterConfigurationRepository.save(businessParameterConfiguration);
}
}
}
}
private BusinessParameterConfiguration prepareBusinessParameterConfiguration(BusinessParameter businessParameter, String value, OffsetDateTime from) {
BusinessParameterConfiguration businessParameterConfiguration = new BusinessParameterConfiguration();
businessParameterConfiguration.setValue(value);
if (from == null) {
businessParameterConfiguration.setFrom(OffsetDateTime.now());
} else {
businessParameterConfiguration.setFrom(from);
}
businessParameterConfiguration.setBusinessParameter(businessParameter);
return businessParameterConfiguration;
}
public String getCurrentValueParameterByKey(String key) {
String value = businessParameterService.getCurrentValueParameterByKey(key);
// String value = businessParameterService.getCurrentValue(key);
if (Objects.isNull(value)) {
throw new RuntimeException(String.format("Parameter %s not found", key));
}
return value;
}
@Override
public void delete(BigInteger id) {
List<BusinessParameterConfiguration> businessParameterConfigurationList = businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameter(id);
for (BusinessParameterConfiguration businessParameterConfiguration : businessParameterConfigurationList) {
businessParameterConfigurationRepository.delete(businessParameterConfiguration);
}
Optional<BusinessParameter> found = this.repository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
} else {
this.repository.delete(found.get());
}
}
@Override
public BusinessParameterBean update(BusinessParameterBean bean, BigInteger id) {
Optional<BusinessParameter> found = this.repository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
} else {
BusinessParameter businesParameter = this.toModel(found.get(), bean);
BeanUtils.copyProperties(businesParameter, found.get());
businesParameter = (BusinessParameter) this.repository.save(found.get());
if (bean.getDateFrom() != null) {
if (bean.getCurrentConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationCurrent = businessParameterConfigurationRepository.findById(bean.getCurrentConfigurationId());
businessParameterConfigurationCurrent.get().setFrom(bean.getDateFrom());
businessParameterConfigurationCurrent.get().setTo(bean.getDateApplyFrom());
businessParameterConfigurationCurrent.get().setValue(bean.getCurrentValue());
businessParameterConfigurationRepository.save(businessParameterConfigurationCurrent.get());
} else {
BusinessParameterConfiguration businessParameterConfigurationCurrent = new BusinessParameterConfiguration();
businessParameterConfigurationCurrent.setFrom(bean.getDateFrom());
businessParameterConfigurationCurrent.setTo(bean.getDateApplyFrom());
businessParameterConfigurationCurrent.setValue(bean.getCurrentValue());
businessParameterConfigurationCurrent.setBusinessParameter(businesParameter);
businessParameterConfigurationRepository.save(businessParameterConfigurationCurrent);
}
} else if (bean.getCurrentConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationCurrent = businessParameterConfigurationRepository.findById(bean.getCurrentConfigurationId());
businessParameterConfigurationRepository.delete(businessParameterConfigurationCurrent.get());
}
if (bean.getDateApplyFrom() != null) {
if (bean.getProgrammedConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationProgrammed = businessParameterConfigurationRepository.findById(bean.getProgrammedConfigurationId());
businessParameterConfigurationProgrammed.get().setFrom(bean.getDateApplyFrom());
businessParameterConfigurationProgrammed.get().setValue(bean.getProgrammedValue());
businessParameterConfigurationRepository.save(businessParameterConfigurationProgrammed.get());
} else {
BusinessParameterConfiguration businessParameterConfigurationProgrammed = new BusinessParameterConfiguration();
businessParameterConfigurationProgrammed.setFrom(bean.getDateApplyFrom());
businessParameterConfigurationProgrammed.setValue(bean.getProgrammedValue());
businessParameterConfigurationProgrammed.setBusinessParameter(businesParameter);
businessParameterConfigurationRepository.save(businessParameterConfigurationProgrammed);
}
} else if (bean.getProgrammedConfigurationId() != null) {
Optional<BusinessParameterConfiguration> businessParameterConfigurationProgrammed = businessParameterConfigurationRepository.findById(bean.getProgrammedConfigurationId());
businessParameterConfigurationRepository.delete(businessParameterConfigurationProgrammed.get());
}
return this.toBean(businesParameter);
}
}
@Override
public BusinessParameterBean create(BusinessParameterBean bean) {
BusinessParameter model = new BusinessParameter();
BusinessParameterConfiguration businessParameterConfiguration = new BusinessParameterConfiguration();
if (this.existsByUK(bean)) {
throw new AlreadyExistsException();
}
model = this.businessParameterRepository.save(this.toModel(model, bean));
if (bean.getCurrentValue() != null && !bean.getCurrentValue().isEmpty()) {
businessParameterConfiguration.setTo(bean.getDateApplyFrom());
businessParameterConfiguration.setFrom(bean.getDateFrom());
businessParameterConfiguration.setValue(bean.getCurrentValue());
businessParameterConfiguration.setBusinessParameter(model);
this.businessParameterConfigurationRepository.save(businessParameterConfiguration);
}
if (bean.getProgrammedValue() != null && !bean.getProgrammedValue().isEmpty()) {
BusinessParameterConfiguration programmedValue = new BusinessParameterConfiguration();
programmedValue.setFrom(bean.getDateApplyFrom());
programmedValue.setValue(bean.getProgrammedValue());
programmedValue.setBusinessParameter(model);
this.businessParameterConfigurationRepository.save(programmedValue);
}
return this.toBean(model);
}
public BusinessParameterConfigurationBean getBusinessConfiguration(BigInteger id) {
List<BusinessParameterConfiguration> businessConfigurationList = businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameterWithLowestDateFrom(id, OffsetDateTime.now());
BusinessParameterConfigurationBean bean = new BusinessParameterConfigurationBean();
if (!businessConfigurationList.isEmpty()) {
BusinessParameterConfiguration businessParameterConfigurationFirst = businessConfigurationList.get(0);
if (businessConfigurationList.size() == 1) {
bean.setValue(businessParameterConfigurationFirst.getValue());
bean.setFrom(businessParameterConfigurationFirst.getFrom());
bean.setCurrentConfigurationId(businessParameterConfigurationFirst.getId());
} else {
for (BusinessParameterConfiguration bpc : businessConfigurationList) {
if (businessParameterConfigurationFirst.getFrom().equals(bpc.getTo())) {
bean.setValue(bpc.getValue());
bean.setFrom(bpc.getFrom());
bean.setTo(bpc.getTo());
bean.setProgrammedValue(businessParameterConfigurationFirst.getValue());
bean.setCurrentConfigurationId(bpc.getId());
bean.setProgrammedConfigurationId(bpc.getId());
bean.setCurrentConfigurationId(businessParameterConfigurationFirst.getId());
}
}
}
}
return bean;
}
public boolean validateKey(BusinessParameterBean bean) {
Optional<BusinessParameter> businessParameterOptional = this.businessParameterRepository.findByKey(bean.getKey());
System.out.println(businessParameterOptional);
if (businessParameterOptional.isPresent()) {
BusinessParameterBean businessParameterBeanOptional = toBean(businessParameterOptional.get());
if (!businessParameterBeanOptional.getId().equals(bean.getId())) {
return true;
}
}
return false;
}
public List<BusinessParameterConfigurationBean> getConfigurationParametersList(BigInteger busnessKey) {
List<BusinessParameterConfiguration> businessParametersConfigurationModelList = this.businessParameterConfigurationRepository.findBusinessParameterConfigurationListByBusinessParameter(busnessKey);
List<BusinessParameterConfigurationBean> beanList = new ArrayList<>();
if (!businessParametersConfigurationModelList.isEmpty()) {
for (BusinessParameterConfiguration model : businessParametersConfigurationModelList) {
BusinessParameterConfigurationBean businessParametersConfigurationBean = businessParameterConfigurationService.toBean(model);
beanList.add(businessParametersConfigurationBean);
}
return beanList;
}
return beanList;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.enums.CalendarExceptionType;
import com.bytesw.bytebot.repository.CalendarExceptionRepository;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.xdf.dao.rsql.CustomRsqlVisitor;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import cz.jirutka.rsql.parser.RSQLParser;
import cz.jirutka.rsql.parser.ast.Node;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.*;
@Service
@Transactional
public class CalendarExceptionService extends XDFService<CalendarException, CalendarExceptionBean, BigInteger> {
@Autowired
CalendarRepository calendarRepository;
@Autowired
CalendarService calendarService;
@Autowired
CalendarExceptionRepository calendarExceptionRepository;
protected CalendarExceptionService(CalendarExceptionRepository repository) {
super(repository);
}
@Override
protected CalendarException toModel(CalendarException model, CalendarExceptionBean bean) {
if (model == null) {
model = getCalendarException(bean);
}
BeanUtils.copyProperties(bean, model);
if (bean.getCalendar() == null) {
throw new NotFoundException("Calendar can not be null");
}
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendar().getId());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendar().getId());
}
if (bean.getCalendarExceptionType() == null) {
throw new NotFoundException("Calendar Exception Type can not be null");
}
model.setCalendar(calendarOptional.get());
model.setCalendarExceptionType(CalendarExceptionType.fromString(bean.getCalendarExceptionType()));
return model;
}
public static CalendarException getCalendarException(CalendarExceptionBean bean) {
CalendarException model;
switch (bean.getFrequencyType()) {
case UniqueCalendarException.DISCRIMINATOR_VALUE:
model = new UniqueCalendarException();
break;
case AnnualCalendarException.DISCRIMINATOR_VALUE:
model = new AnnualCalendarException();
break;
case RangeCalendarException.DISCRIMINATOR_VALUE:
model = new RangeCalendarException();
break;
default:
model = new UniqueWeeklyCalendarException();
}
return model;
}
@Override
protected CalendarExceptionBean toBean(CalendarException model) {
CalendarExceptionBean bean = new CalendarExceptionBean();
BeanUtils.copyProperties(model, bean);
bean.setCalendar(this.calendarService.toBean(model.getCalendar()));
bean.setCalendarExceptionType(model.getCalendarExceptionType().getName());
bean.setFrequencyType(model.getFrequencyType());
return bean;
}
public List<CalendarExceptionBean> getCalendarExceptionbyID(Map<String, String> parametersCalendar) {
String sortDirection = parametersCalendar.get("sortDirection");
String columnName = parametersCalendar.get("columnName");
String caleId = parametersCalendar.get("caleId");
String filterExpresion = parametersCalendar.get("filterExpresion");
Specification<CalendarException> calendarExceptionSpecification = null;
Sort sort;
switch (sortDirection) {
case "desc":
sort = Sort.by(Sort.Direction.DESC, columnName);
break;
case "asc":
sort = Sort.by(Sort.Direction.ASC, columnName);
break;
default:
sort = Sort.by(Sort.Direction.ASC, "description");
}
if (filterExpresion != null) {
if (!filterExpresion.isEmpty()) {
filterExpresion = filterExpresion + ";";
}
filterExpresion = filterExpresion + String.format("calendar.id=='%s'", caleId);
calendarExceptionSpecification = createSpecification(filterExpresion);
}
List<CalendarException> optionalCalendarExceptionList = calendarExceptionRepository.findAll(calendarExceptionSpecification, sort);
List<CalendarExceptionBean> calendarExceptionBeanList = new ArrayList<>();
for (int i = 0; i < optionalCalendarExceptionList.size(); i++) {
CalendarExceptionBean aux = new CalendarExceptionBean();
BeanUtils.copyProperties(optionalCalendarExceptionList.get(i), aux);
calendarExceptionBeanList.add(i, toBean(optionalCalendarExceptionList.get(i)));
}
return calendarExceptionBeanList;
}
private Specification<CalendarException> createSpecification(String filterExpression) {
Node rootNode = (new RSQLParser()).parse(filterExpression);
return (Specification) rootNode.accept(new CustomRsqlVisitor<>());
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.CalendarExceptionBean;
import com.bytesw.bytebot.bean.WeekSchedulerBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.CalendarException;
import com.bytesw.bytebot.model.SchedulerTask;
import com.bytesw.bytebot.model.WeekScheduler;
import com.bytesw.bytebot.repository.CalendarExceptionRepository;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.SchedulerTaskRepository;
import com.bytesw.bytebot.repository.WeekSchedulerRepository;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.exception.ReferentialIntegrityException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class CalendarService extends XDFService<Calendar, CalendarBean, String> {
@Autowired
private WeekSchedulerService weekSchedulerService;
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private CalendarExceptionRepository calendarExceptionRepository;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private CalendarExceptionService calendarExceptionService;
protected CalendarService(CalendarRepository repository) {
super(repository);
}
@Override
protected Calendar toModel(Calendar model, CalendarBean bean) {
if (model == null) {
model = new Calendar();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected CalendarBean toBean(Calendar model) {
CalendarBean bean = new CalendarBean();
BeanUtils.copyProperties(model, bean);
bean.setWeekSchedulerBeanList(this.weekSchedulerService.getWeekSchedulerByCalId(model.getId().trim()));
return bean;
}
@Override
public void delete(String id) {
Optional<Calendar> found = this.calendarRepository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
}
Optional<List<SchedulerTask>> schedulerTaskList = this.schedulerTaskRepository.findByCalendarId(id);
if (schedulerTaskList.isPresent()) {
throw new ReferentialIntegrityException("CALENDAR_EXCEPTION_DELETE_SCHEDULER_TASK");
}
Optional<List<CalendarException>> calendarExceptionList = this.calendarExceptionRepository.findByCalendarId(id);
calendarExceptionList.ifPresent(list -> this.calendarExceptionRepository.deleteAll(list));
Optional<List<WeekScheduler>> weekSchedulerList = this.weekSchedulerRepository.findByCalendarId(id);
weekSchedulerList.ifPresent(list -> this.weekSchedulerRepository.deleteAll(list));
this.calendarRepository.delete(found.get());
}
@Override
public CalendarBean create(CalendarBean bean) {
if (this.calendarRepository.existsById(bean.getId())) {
throw new AlreadyExistsException("errors.form.duplicated.id");
}
Calendar model = new Calendar();
model = this.calendarRepository.save(this.toModel(model, bean));
saveWeekScheduler(bean, model);
saveCalendarException(bean, model);
return this.toBean(model);
}
@Override
public CalendarBean update(CalendarBean bean, String id) {
Optional<Calendar> found = this.calendarRepository.findById(id);
if (!found.isPresent()) {
throw new NotFoundException();
}
Calendar calendar = this.toModel(found.get(), bean);
BeanUtils.copyProperties(calendar, found.get());
calendar = this.calendarRepository.save(found.get());
saveWeekScheduler(bean, calendar);
saveCalendarException(bean, calendar);
return this.toBean(calendar);
}
private void saveWeekScheduler(CalendarBean bean, Calendar calendar) {
List<WeekSchedulerBean> weekSchedulerBeanList = bean.getWeekSchedulerBeanList();
for (WeekSchedulerBean weekSchedulerBean : weekSchedulerBeanList) {
WeekScheduler weekScheduler;
boolean delete = weekSchedulerBean.getFrom() == null;
if (weekSchedulerBean.getId() != null) {
Optional<WeekScheduler> weekSchedulerOptional = this.weekSchedulerRepository.findById(weekSchedulerBean.getId());
if (weekSchedulerOptional.isPresent()) {
if (delete) {
this.weekSchedulerRepository.delete(weekSchedulerOptional.get());
continue;
}
weekScheduler = weekSchedulerOptional.get();
} else {
weekScheduler = new WeekScheduler();
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
}
weekScheduler.setCalendar(calendar);
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
} else if (!delete) {
weekScheduler = new WeekScheduler();
weekScheduler.setCalendar(calendar);
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
}
}
}
private void saveCalendarException(CalendarBean bean, Calendar calendar) {
List<CalendarExceptionBean> calendarExceptionBeanList = bean.getCalendarExceptionBeanList();
CalendarException calendarException = null;
for (CalendarExceptionBean calendarExceptionBean : calendarExceptionBeanList) {
if (calendarExceptionBean.getId() != null) {
Optional<CalendarException> calendarExceptionOptional = calendarExceptionRepository.findById(calendarExceptionBean.getId());
if (calendarExceptionBean.isDelete()) {
calendarExceptionRepository.delete(calendarExceptionOptional.get());
continue;
}
// modificar
if (!calendarExceptionOptional.get().getFrequencyType().equals(calendarExceptionBean.getFrequencyType())) {
calendarExceptionRepository.delete(calendarExceptionOptional.get());
} else {
calendarExceptionBean.setCalendar(bean);
calendarException = calendarExceptionService.toModel(calendarExceptionOptional.get(), calendarExceptionBean);
calendarExceptionRepository.save(calendarException);
continue;
}
}
// Nueva excepción
calendarException = calendarExceptionService.getCalendarException(calendarExceptionBean);
calendarExceptionBean.setCalendar(bean);
calendarException = calendarExceptionService.toModel(calendarException, calendarExceptionBean);
calendarException.setCalendar(calendar);
calendarExceptionRepository.save(calendarException);
}
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.ActionBean;
import com.bytesw.bytebot.etl.beans.GoalForActionsBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
import com.bytesw.bytebot.etl.model.Action;
import com.bytesw.bytebot.etl.model.GoalForActions;
import com.bytesw.bytebot.repository.GoalForActionsRepository;
import com.bytesw.bytebot.repository.GoalRepository;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
@Transactional
@Log4j2
public class GoalForActionService extends XDFService<GoalForActions, GoalForActionsBean, Long> {
@Autowired
private GoalRepository goalRepository;
@Autowired
private ActionRepository actionRepository;
@Autowired
private GoalForActionsRepository goalForActionsRepository;
protected GoalForActionService(GoalForActionsRepository repository) {
super(repository);
}
@Override
protected GoalForActions toModel(GoalForActions model, GoalForActionsBean bean) {
if (model == null) {
model = new GoalForActions();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected GoalForActionsBean toBean(GoalForActions model) {
GoalForActionsBean bean = new GoalForActionsBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public void saveGoalForAction(Long idGoal, List<Object> actions) {
if (!goalRepository.existsById(idGoal)) {
throw new NotFoundException("Goal no registrado.");
}
Map<String, String> dataAction = new HashMap<String, String>();
for(Object action : actions){
GoalForActions goalForActions = new GoalForActions();
goalForActions.setGoalId(idGoal);
dataAction = (HashMap) action;
if (!actionRepository.existsById(Long.valueOf(dataAction.get("IdAction").toString()))) {
continue;
}
goalForActions.setActionId(Long.valueOf(dataAction.get("IdAction").toString()));
goalForActions = goalForActionsRepository.save(goalForActions);
}
}
@Transactional(propagation = Propagation.REQUIRED)
public void deleteGoalForAction(Long goalId) {
Optional<List<GoalForActions>> listGoalForActions = goalForActionsRepository.findGoalForActionsByGoalId(goalId);
if (!listGoalForActions.isPresent()) {
throw new NotFoundException("GoalForActions no econtrados.");
}
for (GoalForActions goalForActions: listGoalForActions.get()) {
goalForActionsRepository.delete(goalForActions);
}
}
@Transactional(propagation = Propagation.REQUIRED)
public void updateGoalForAction(Long idGoal, List<Object> actions) {
Optional<List<GoalForActions>> listActual = goalForActionsRepository.findGoalForActionsByGoalId(idGoal);
if (!listActual.isPresent()) {
throw new NotFoundException("GoalForActions no encontrados.");
}
Map<String, String> dataAction = new HashMap<>();
List<Long> idActions = new ArrayList<>();
for (Object object: actions) {
dataAction = (HashMap) object;
idActions.add(Long.valueOf(dataAction.get("IdAction")));
}
for (GoalForActions goalForActions : listActual.get()) {
if (!idActions.contains(goalForActions.getActionId())) {
goalForActionsRepository.delete(goalForActions);
} else {
idActions.remove(goalForActions.getActionId());
}
}
for (Long id: idActions) {
GoalForActions newGoalForActions = new GoalForActions();
newGoalForActions.setGoalId(idGoal);
newGoalForActions.setActionId(id);
goalForActionsRepository.save(newGoalForActions);
}
}
public List<Map> getGoalForAction(Long id) {
List<Map> list = new ArrayList<>();
Optional<List<GoalForActions>> goalForActions = goalForActionsRepository.findGoalForActionsByGoalId(id);
if (!goalForActions.isPresent()) {
throw new NotFoundException("No se encontraron actions.");
}
for (GoalForActions actions : goalForActions.get()) {
Action action = actionRepository.findById(actions.getActionId()).get();
if (action == null) {
log.debug("No se encontró la accion.");
continue;
}
Map<String, String> map = new HashMap<>();
map.put("IdAction", String.valueOf(action.getId()));
map.put("desc", action.getIdentifier());
list.add(map);
}
return list;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.GoalBean;
import com.bytesw.bytebot.etl.model.Goal;
import com.bytesw.bytebot.etl.model.GoalForActions;
import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
@Service
@Transactional
@Log4j2
public class GoalService extends XDFService<Goal, GoalBean, Long> {
@Autowired
private GoalRepository goalRepository;
@Autowired
private GoalForActionsRepository goalForActionsRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private GoalForActionService goalForActionService;
protected GoalService(GoalRepository repository) {
super(repository);
}
@Override
protected Goal toModel(Goal model, GoalBean bean) {
if (model == null) {
model = new Goal();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected GoalBean toBean(Goal model) {
GoalBean bean = new GoalBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public GoalBean saveGoalForAction(Map<String, Object> body) {
Goal goal = new Goal();
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
Long agenId = Long.valueOf(body.get("AgentId").toString());
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
String ident = body.get("Ident").toString();
Optional<Goal> goalOptional= goalRepository.findByAgentAndIdent(agenId, ident);
if (goalOptional.isPresent()) {
throw new AlreadyExistsException("Goal ya existe en la base de datos.");
}
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.saveGoalForAction(goal.getId(), (List) body.get("actionList"));
return toBean(goal);
}
@Transactional(propagation = Propagation.REQUIRED)
public void deleteGoalForAction(Long goalId) {
if (!goalRepository.existsById(goalId)){
throw new NotFoundException("Goal no registrado.");
}
goalForActionService.deleteGoalForAction(goalId);
goalRepository.deleteById(goalId);
}
@Transactional(propagation = Propagation.REQUIRED)
public void updateGoalForActions(Map<String, Object> body, Long goalId) {
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
if (!goalRepository.existsById(goalId)) {
throw new NotFoundException("Goal no se encuenta registrado");
}
Long agenId = Long.valueOf(body.get("AgentId").toString());
String ident = body.get("Ident").toString();
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
Goal goal = new Goal();
goal.setId(goalId);
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.updateGoalForAction(goal.getId(), (List) body.get("actionList"));
}
public Map<String, Object> getGoalForActions(Long id){
Map<String, Object> result = new HashMap<>();
Optional<Goal> goal = goalRepository.findById(id);
if (!goal.isPresent()) {
throw new NotFoundException("Goal no se encuenta registrado");
}
List<Map> listAction = goalForActionService.getGoalForAction(id);
if (listAction.isEmpty()) {
throw new NotFoundException("Actions no encontrados");
}
result.put("AgentId", goal.get().getAgenId());
result.put("Ident", goal.get().getIdentifier());
result.put("actionList", listAction);
return result;
}
public List<Map> getGoalForActionsAll(){
List<Map> result = new ArrayList<>();
List<Goal> list = (List<Goal>) goalRepository.findAll();
for (Goal goal: list) {
result.add(getGoalForActions(goal.getId()));
}
return result;
}
}
\ No newline at end of file
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.ProcessETLBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.ProcessETL;
import com.bytesw.bytebot.repository.ProcessETLRepository;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ProcessETLService extends XDFService<ProcessETL, ProcessETLBean, Integer> {
protected ProcessETLService(ProcessETLRepository repository) {
super(repository);
}
@Override
protected ProcessETL toModel(ProcessETL model, ProcessETLBean bean) {
if (model == null) {
model = new ProcessETL();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected ProcessETLBean toBean(ProcessETL model) {
ProcessETLBean bean = new ProcessETLBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.SchedulerTaskBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.SchedulerTask;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.SchedulerTaskRepository;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.*;
@Service
@Transactional
public class SchedulerTaskService extends XDFService<SchedulerTask, SchedulerTaskBean, BigInteger> {
@Autowired
private CalendarService CalendarService;
@Autowired
private CalendarRepository calendarRepository;
protected SchedulerTaskService(SchedulerTaskRepository repository) {
super(repository);
}
@Override
protected SchedulerTask toModel(SchedulerTask model, SchedulerTaskBean bean) {
if (model == null) {
model = new SchedulerTask();
}
BeanUtils.copyProperties(bean, model);
model.setInternals("Y".equals(bean.getInternals()));
if (bean.getCalendarID() == null) {
throw new NotFoundException("Calendar can not be null");
}
bean.setCalendarID(bean.getCalendarID().trim());
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendarID());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
// model.setCalendar(calendarOptional.get());
return model;
}
@Override
protected SchedulerTaskBean toBean(SchedulerTask model) {
SchedulerTaskBean bean = new SchedulerTaskBean();
BeanUtils.copyProperties(model, bean);
bean.setInternals(model.getInternals().booleanValue() ? "Y" : "N");
bean.setCalendarID(bean.getCalendarID().trim());
// CalendarBean found = this.CalendarService.getById(bean.getCalendarID());
Optional<Calendar> calendarOptional = this.calendarRepository.findById(bean.getCalendarID());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
bean.setCalendarName(calendarOptional.get().getName());
return bean;
}
public Map<String, List> getInitialData() {
List<CalendarBean> calendarBeanList = this.CalendarService.getAll();
Map<String, List> initialData = new HashMap<>();
initialData.put("calendarList", calendarBeanList);
return initialData;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.CalendarBean;
import com.bytesw.bytebot.bean.WeekSchedulerBean;
import com.bytesw.bytebot.model.Calendar;
import com.bytesw.bytebot.model.WeekScheduler;
import com.bytesw.bytebot.repository.CalendarRepository;
import com.bytesw.bytebot.repository.WeekSchedulerRepository;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class WeekSchedulerService extends XDFService<WeekScheduler, WeekSchedulerBean, BigInteger> {
@Autowired
private WeekSchedulerRepository weekSchedulerRepository;
@Autowired
private CalendarService calendarService;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private CalendarService CalendarService;
protected WeekSchedulerService(WeekSchedulerRepository repository) {
super(repository);
}
@Override
protected WeekScheduler toModel(WeekScheduler model, WeekSchedulerBean bean) {
if (model == null) {
model = new WeekScheduler();
}
BeanUtils.copyProperties(bean, model);
if (bean.getCalendarID() == null) {
throw new NotFoundException("Calendar can not be null");
}
bean.setCalendarID(bean.getCalendarID().trim());
Optional<Calendar> calendarOptional = calendarRepository.findById(bean.getCalendarID().trim());
if (!calendarOptional.isPresent()) {
throw new NotFoundException("Calendar not found " + bean.getCalendarID());
}
model.setCalendar(calendarOptional.get());
return model;
}
@Override
protected WeekSchedulerBean toBean(WeekScheduler model) {
WeekSchedulerBean bean = new WeekSchedulerBean();
BeanUtils.copyProperties(model, bean);
bean.setCalendarID(model.getCalendarID());
CalendarBean found = this.CalendarService.getById(bean.getCalendarID().trim());
if(found != null){
bean.setCalendarName(found.getName());
}
return bean;
}
public List<WeekSchedulerBean> getWeekSchedulerByCalId(String caleID) {
List<WeekSchedulerBean> weekSchedulerBeanList = new ArrayList<>(7);
Optional<List<WeekScheduler>> weekSchedulerOptional = this.weekSchedulerRepository.findByCalendarId(caleID.trim());
if (!weekSchedulerOptional.isPresent()) {
for (int i = 0; i < 7; i++) {
weekSchedulerBeanList.add(i, new WeekSchedulerBean());
}
} else {
for (int i = 0; i < 7; i++) {
WeekSchedulerBean aux = new WeekSchedulerBean();
for (int j = 0; j < weekSchedulerOptional.get().size(); j++){
aux.setDayOfWeek(i+1);
if(weekSchedulerOptional.get().get(j).getDayOfWeek() == i+1){
BeanUtils.copyProperties(weekSchedulerOptional.get().get(j), aux);
}
}
weekSchedulerBeanList.add(i, aux);
}
}
return weekSchedulerBeanList;
}
}
...@@ -4,18 +4,22 @@ import com.bytesw.bytebot.bean.*; ...@@ -4,18 +4,22 @@ import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.jdbc.ActionJDBCRepository; import com.bytesw.bytebot.jdbc.ActionJDBCRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository; import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.xdf.sql.beans.Pagination; import com.bytesw.xdf.sql.beans.Pagination;
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 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;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Log4j2
@Service @Service
public class CustomerInteractionDashboardService extends DashboardService { public class CustomerInteractionDashboardService extends DashboardService {
...@@ -26,12 +30,12 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -26,12 +30,12 @@ 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));
info.put("intentAvgByCustomer", generateAverageIntentsByCustomer(rangeList)); info.put("intentAvgByCustomer", generateAverageIntentsByCustomer(rangeList));
info.put("summaryIntents", generateSummaryMessageByIntent(rangeList)); info.put("summaryIntents", generateSummaryMessageByIntent(rangeList,startDate,endDate));
} }
...@@ -46,25 +50,40 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -46,25 +50,40 @@ public class CustomerInteractionDashboardService extends DashboardService {
return actionByGoalList; return actionByGoalList;
} }
private Map<String, List<Object>> generateSummaryMessageByIntent(List<RangeBean> rangeList) { private Map<String, List<Object>> generateSummaryMessageByIntent(List<RangeBean> rangeList,OffsetDateTime startDate, OffsetDateTime endDate) {
List<MessageByIntentBean> total_list = messageJDBCRepository.countMessageByIntent(startDate,endDate);
Map<String, List<Object>> data = new HashMap<>(); Map<String, List<Object>> data = new HashMap<>();
rangeList.stream().forEach(x -> { rangeList.stream().forEach(x -> {
List<String> identifiers = new ArrayList<>();
List<MessageByIntentBean> list = messageJDBCRepository.countMessageByIntent(x.getStartDate(), x.getEndDate()); List<MessageByIntentBean> list = messageJDBCRepository.countMessageByIntent(x.getStartDate(), x.getEndDate());
list.stream().forEach(intentSummary -> { list.stream().forEach(intentSummary -> {
identifiers.add((intentSummary.getIdentifier()));
if (!data.containsKey(intentSummary.getIdentifier())){ if (!data.containsKey(intentSummary.getIdentifier())){
data.put(intentSummary.getIdentifier(), new ArrayList<>()); data.put(intentSummary.getIdentifier(), new ArrayList<>());
} }
data.get(intentSummary.getIdentifier()).add(new Object[]{getDayOnStart(x.getStartDate()).toInstant().toEpochMilli()/1000, intentSummary.getCount()}); data.get(intentSummary.getIdentifier()).add(new Object[]{getDayOnStart(x.getStartDate()).toInstant().toEpochMilli()/1000, intentSummary.getCount()});
}); });
total_list.stream().forEach(intentSummary -> {
if(!identifiers.contains(intentSummary.getIdentifier())){
if(!data.containsKey(intentSummary.getIdentifier())){
data.put(intentSummary.getIdentifier(),new ArrayList<>());
}
data.get(intentSummary.getIdentifier()).add(new Object[]{getDayOnStart(x.getStartDate()).toInstant().toEpochMilli()/1000, 0});
}
});
}); });
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;
} }
...@@ -94,8 +113,9 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -94,8 +113,9 @@ public class CustomerInteractionDashboardService extends DashboardService {
others.setId(0L); others.setId(0L);
others.setIdentifier("others"); others.setIdentifier("others");
intentTopList.add(others); if(others.getCount().intValue()>0){
intentTopList.add(others);
}
data.get("intent").put("total", totalIntents); data.get("intent").put("total", totalIntents);
data.get("intent").put("topList", intentTopList); data.get("intent").put("topList", intentTopList);
...@@ -117,7 +137,9 @@ public class CustomerInteractionDashboardService extends DashboardService { ...@@ -117,7 +137,9 @@ public class CustomerInteractionDashboardService extends DashboardService {
othersSentence.setId(0L); othersSentence.setId(0L);
othersSentence.setIdentifier("others"); othersSentence.setIdentifier("others");
sentenceTopList.add(othersSentence); if(othersSentence.getCount().intValue()>0){
sentenceTopList.add(othersSentence);
}
data.get("sentence").put("topList", sentenceTopList); data.get("sentence").put("topList", sentenceTopList);
data.get("sentence").put("total", totalSentences); data.get("sentence").put("total", totalSentences);
......
...@@ -15,24 +15,26 @@ import java.util.Map; ...@@ -15,24 +15,26 @@ 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) {
Map<String, Object> info = new HashMap<>(); Map<String, Object> info = new HashMap<>();
log.info(params);
if (params == null) { if (params == null) {
return info; return info;
} }
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,25 @@ public abstract class DashboardService { ...@@ -76,6 +78,25 @@ public abstract class DashboardService {
return nextDate; return nextDate;
} }
protected List<RangeBean> calculateMinutesRangeList(OffsetDateTime startDate, OffsetDateTime endDate, Integer range){
List<RangeBean> rangeList = new ArrayList<>();
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);
}
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,22 @@ package com.bytesw.bytebot.service.dashboard; ...@@ -3,24 +3,22 @@ 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 com.bytesw.bytebot.model.enums.MetricMessageTypeEnum;
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.util.*;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@Service @Service
public class OperativeDashboardService extends DashboardService { public class OperativeDashboardService extends DashboardService {
...@@ -34,26 +32,42 @@ public class OperativeDashboardService extends DashboardService { ...@@ -34,26 +32,42 @@ 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) {
if (startDate.isAfter(endDate)) {
throw new NotFoundException("Invalid data range");
}
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<Object[]> sessions = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.SESSION.getName());
int totalSessions = botSessionJDCBRepository.countSessionInRange(startDate, endDate);
int cantReceivedMessages = messageJDBCRepository.countSessionInRange(startDate, endDate);
int cantResponseMessages = responseJDBCRepository.countSessionInRange(startDate, endDate); // Mensajes recibidos
List<Object[]> recivedMessages = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.RECEIVED.getName());
int totalrecivedMessages = messageJDBCRepository.countSessionInRange(startDate, endDate);
// Mensajes enviados
List<Object[]> responseMessages = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.SENT.getName());
int totalresponseMessages = responseJDBCRepository.countSessionInRange(startDate, endDate);
//Promedio primera respuesta en mili //Promedio primera respuesta en mili
Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate); Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate);
Double avgFirstResponse; Double avgFirstResponse;
if (avgFRObject instanceof Long) { if (avgFRObject instanceof Long) {
avgFirstResponse = new Double((Long)avgFRObject); avgFirstResponse = new Double((Long) avgFRObject);
} else { } else {
avgFirstResponse = (Double) avgFRObject; avgFirstResponse = (Double) avgFRObject;
} }
Double avgSessionsByCustomer = botSessionJDCBRepository.getAvgSessionByCustomerInRange(startDate, endDate);
Double avgSessionsByCustomerRaw = botSessionJDCBRepository.getAvgSessionByCustomerInRange(startDate, endDate);
// Tomar solo parte entera
if (avgSessionsByCustomerRaw == null){
avgSessionsByCustomerRaw = 0.0;
}
int avgSessionsByCustomer = avgSessionsByCustomerRaw.intValue();
Timestamp timestamp = botSessionJDCBRepository.getLastDateInRage(startDate, endDate); Timestamp timestamp = botSessionJDCBRepository.getLastDateInRage(startDate, endDate);
...@@ -65,54 +79,31 @@ public class OperativeDashboardService extends DashboardService { ...@@ -65,54 +79,31 @@ 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()))); BigInteger value = new BigInteger(String.valueOf(difference.getSeconds()));
sessionInactivity.setHistory(new ArrayList<>()); sessionInactivity.setValue(value);
sessionInactivity.setPercent(new BigDecimal("1.2"));
sessionInactivity.getHistory().add(new BigInteger("10")); // Adjutando las sesiones totales
sessionInactivity.getHistory().add(new BigInteger("10")); Map<String,Object> totalSession = new HashMap<>();
sessionInactivity.getHistory().add(new BigInteger("10")); totalSession.put("value",totalSessions);
sessionInactivity.getHistory().add(new BigInteger("10")); totalSession.put("history",sessions);
sessionInactivity.getHistory().add(new BigInteger("10"));
// Adjuntamos los mensajes recibidos
Map<String, Object> recivedMessage = new HashMap<>();
SummaryBean totalSessions = new SummaryBean(); recivedMessage.put("value", totalrecivedMessages);
totalSessions.setValue(new BigInteger(String.valueOf(cantSessions))); recivedMessage.put("history", recivedMessages);
totalSessions.setHistory(new ArrayList<>());
totalSessions.setPercent(new BigDecimal("1.2"));
totalSessions.getHistory().add(new BigInteger("2"));
totalSessions.getHistory().add(new BigInteger("4"));
totalSessions.getHistory().add(new BigInteger("6"));
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 enviados
Map<String, Object> responseMessage = new HashMap<>();
responseMessage.put("value", totalresponseMessages);
responseMessage.put("history", 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", totalSession);
summary.put("totalReceivedMessages", totalReceivedMessages); summary.put("totalSentMessages", responseMessage);
summary.put("totalSentMessages", totalSentMessages); summary.put("totalReceivedMessages", recivedMessage);
AverageBean averageBean = new AverageBean(); AverageBean averageBean = new AverageBean();
if (avgFirstResponse == null) { if (avgFirstResponse == null) {
...@@ -126,6 +117,35 @@ public class OperativeDashboardService extends DashboardService { ...@@ -126,6 +117,35 @@ public class OperativeDashboardService extends DashboardService {
info.put("customerMessageDetail", messageByActivity); info.put("customerMessageDetail", messageByActivity);
} }
private List<Object[]> generateDataVariablePeriod(List<RangeBean> rangeList, String metric) {
List<Object[]> data = new ArrayList<>();
Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>();
int cont = 0;
for (RangeBean range : rangeList) {
int cant = 0;
if (metric.equals(MetricMessageTypeEnum.RECEIVED.getName())) {
cant = messageJDBCRepository.countMessageInRangeHour(range.getStartDate(), range.getEndDate());
} else if (metric.equals(MetricMessageTypeEnum.SENT.getName())) {
cant = responseJDBCRepository.countSessionInRange(range.getStartDate(), range.getEndDate());
}else if (metric.equals(MetricMessageTypeEnum.SESSION.getName())){
cant = botSessionJDCBRepository.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<>();
......
package com.bytesw.bytebot.service.provider;
import com.bytesw.xdf.exception.NotFoundException;
import com.twilio.exception.AuthenticationException;
import lombok.extern.log4j.Log4j2;
import java.util.HashMap;
import java.util.Map;
@Log4j2
public abstract class ProviderService {
abstract void completeData(Map<String, Object> info, String SmsId, int Agent_id) throws Exception;
public Map<String, Object> generateInfo(String sid, Map<String, Object> params) throws AuthenticationException {
Map<String, Object> info = new HashMap<>();
if (params == null) {
return info;
}
try {
int agen_id = (Integer) params.get("agent_id");
this.completeData(info, sid, agen_id);
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch (java.lang.ClassCastException e) {
log.info("Body Input inválido");
throw new ClassCastException("Input inválido");
} catch (AuthenticationException e) {
throw new AuthenticationException(e.getMessage());
} catch (InternalError e) {
throw new InternalError(e.getMessage());
} catch (Exception e) {
throw new InternalError(e.getMessage());
}
return info;
}
}
package com.bytesw.bytebot.service.provider;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
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.service.AgentService;
import com.bytesw.xdf.exception.NotFoundException;
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.exception.AuthenticationException;
import com.twilio.rest.api.v2010.account.message.Media;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Log4j2
@Service
public class TwilioService extends ProviderService {
@Autowired
private AgentService agentService;
public List<DeploymentChannelParamValueBean> getAllParamsWithRefresh() {
return getAllParams();
}
public List<DeploymentChannelParamValueBean> getAllParams() {
List<DeploymentChannelParamValueBean> agents = new ArrayList<>();
agents = agentService.GetKeysFromAgents(AgentStatusEnum.DEPLOYED);
return agents;
}
@Override
protected void completeData(Map<String, Object> info, String SmsId, int agent_id) throws Exception {
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 = "";
String token = "";
int MAX_LIMIT = 999;
List<String> data = new ArrayList<String>();
log.debug(agents);
try {
boolean exist_agent = false;
for (DeploymentChannelParamValueBean agent : agents) {
if (agent.getAgen_id() == agent_id && agent.getChannel().equals(ChannelEnum.WHATSAPP.getName())) {
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_ID.getName())) {
sid = agent.getValue();
}
if (agent.getChannelParamName().equals(AgentParameterEnum.ACCESS_TOKEN.getName())) {
token = agent.getValue();
}
exist_agent = true;
}
}
if (!exist_agent) {
log.info("No existe un agente con el ID especificado");
throw new Exception("No se encontró un agente con canales deployados con dicho ID");
}
String[] images_droped = new String[MAX_LIMIT];
Twilio.init(sid, token);
ResourceSet<Media> media = Media.reader(SmsId).limit(MAX_LIMIT).read();
int cont = 0;
for (Media record : media) {
Media.deleter(SmsId, record.getSid()).delete();
images_droped[cont] = record.getSid();
cont++;
}
if (cont == 0) {
log.info("No hay imágenes para el mensaje indicado");
throw new NotFoundException("No se encontraron imágenes para el mensaje " + SmsId);
} else {
for (String image : Arrays.copyOfRange(images_droped, 0, cont)) {
data.add(image);
}
}
info.put("status", "success");
info.put("data", data);
} catch (com.twilio.exception.ApiException e) {
if (e.getMessage().equals(ProviderErrorEnum.AUTHENTICATE.getName())) {
log.error("Credenciales inválidas para borrar imagen");
throw new AuthenticationException("Credenciales inválidas");
} else if (e.getMessage().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");
} else {
log.info("El mensaje no existe para : " + SmsId + "\n" + e.getMessage());
throw new NotFoundException("No se encontraron imágenes para el mensaje " + SmsId);
}
} catch (NotFoundException e) {
throw new NotFoundException(e.getMessage());
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
...@@ -4,7 +4,7 @@ server: ...@@ -4,7 +4,7 @@ server:
servlet.context-path: ${APPLICATION_PATH:/bytebot} servlet.context-path: ${APPLICATION_PATH:/bytebot}
port: ${APPLICATION_PORT:9077} port: ${APPLICATION_PORT:9077}
web: web:
static-content-location: file:C:/Users/aaron/Documents/proyectos/BYTEBOT/bytebot-workspace/dist/bytebot-html/ static-content-location: file:/home/cristian/Documents/AVB_Backend/bytebot-html/
#NOTA debe terminar con / #NOTA debe terminar con /
security: security:
...@@ -26,8 +26,8 @@ management: ...@@ -26,8 +26,8 @@ management:
application: application:
byte-bot: byte-bot:
batch: batch:
chunk: 1 chunk: 10
cron: 0/5 * * * * * cron: 0/50 * * * * *
show-side-bar: false show-side-bar: false
test: ENC(OEchnTXpIZnCVdPNthgCZBfQjMt1AUS1) test: ENC(OEchnTXpIZnCVdPNthgCZBfQjMt1AUS1)
name: xdf-example name: xdf-example
...@@ -42,7 +42,7 @@ application: ...@@ -42,7 +42,7 @@ application:
web: web:
server: docker # weblogic, docker server: docker # weblogic, docker
ignore: ignore:
path: /v2/api-docs, /configuration/**, /swagger-resources/**, /swagger-ui.html, /webjars/**, /api-docs/**, /resources/**, /css/**, /js/**, /fonts/**, /img/**, /modules/**, /system/**, /views/**, /font-awesome/**, /translations/**, /bower_components/**, /cache.manifest, /favicon.ico, /service/file path: /v2/api-docs, /configuration/**, /swagger-resources/**, /swagger-ui.html, /webjars/**, /api-docs/**, /resources/**, /css/**, /js/**, /fonts/**, /img/**, /modules/**, /system/**, /views/**, /font-awesome/**, /translations/**, /bower_components/**, /cache.manifest, /favicon.ico, /service/file, /providers/**
goodbyeURL: /goodbye goodbyeURL: /goodbye
api.info: api.info:
title: 'pilotoXDF Service' title: 'pilotoXDF Service'
...@@ -53,19 +53,19 @@ application: ...@@ -53,19 +53,19 @@ application:
license-url: 'https://help.github.com/articles/open-source-licensing/' license-url: 'https://help.github.com/articles/open-source-licensing/'
services: services:
multi-tenant-conf: multi-tenant-conf:
exclude-service: /health exclude-service: /
authorization-service.url: http://192.168.27.96:7580 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 security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot
messaging: messaging:
queue-support: activemq queue-support: activemq
multi-tenant: true multi-tenant: false
clustering: true clustering: true
database: true database: true
send-email: false send-email: false
jt400: false jt400: false
rabbitMQ: false rabbitMQ: true
webservices: false webservices: false
statistics.type: log # database or log statistics.type: log # database or log
messaging: messaging:
...@@ -89,10 +89,10 @@ application: ...@@ -89,10 +89,10 @@ application:
# password: poiuyt5 # password: poiuyt5
# host: 192.168.27.30 # host: 192.168.27.30
# queue-name: V4STCPGM.LIB/COLGENESIS.DTAQ # queue-name: V4STCPGM.LIB/COLGENESIS.DTAQ
# rabbitMQ.info: rabbitMQ.info:
# host: localhost host: localhost
# port: 5672 port: 8161
# queue-name: task_queue queue-name: task_queue
spring: spring:
main: main:
...@@ -102,47 +102,62 @@ spring: ...@@ -102,47 +102,62 @@ spring:
name: xdf-example name: xdf-example
datasource: datasource:
database-type: mysql database-type: postgres
schemaName: BYTEBOT_BASE schemaName: avb
url: jdbc:mysql://192.168.27.96:3306/BYTEBOT_BASE?useSSL=false url: jdbc:postgresql://192.168.21.74:5432/avb?useSSL=false
driverClassName: 'com.mysql.cj.jdbc.Driver' driverClassName: 'org.postgresql.Driver'
username: root username: postgres
password: byte2k20 password:
minimum-idle: 10 minimum-idle: 10
maximum-pool-size: 10 maximum-pool-size: 10
validationQuery: SELECT 1 validationQuery: SELECT 1
testWhileIdle: true testWhileIdle: true
hikari.registerMbeans: true hikari.registerMbeans: true
security:
basepath: http://192.168.1.6:9077/bytebot
provider: byte # oracle, amazon
oauth2-client:
clientId: xdf-client
clientSecret: xdf-secret
accessTokenUri: http://127.0.0.1:18080/oauth/token
userAuthorizationUri: http://127.0.0.1:18080/oauth/authorize
oauth2-resource:
userInfoUri: http://127.0.0.1:18080/oauth/userinfo
logoutUri: http://127.0.0.1:18080/oauth/userlogout
tenants: tenants:
- -
id: T186A1 id: T186A1
servername: cdb.bytebot.t186a1 servername: prueba_avb
datasource: datasource:
url: jdbc:mysql://192.168.27.96:3306/BYTEBOT_T186A1?useSSL=false database-type: postgres
username: root schemaName: avb
password: byte2k20 url: jdbc:postgresql://192.168.21.74:5432/avb?useSSL=false
driverClassName: 'org.postgresql.Driver'
username: postgres
password:
minimum-idle: 10 minimum-idle: 10
maximum-pool-size: 100 maximum-pool-size: 10
validationQuery: SELECT 1 validationQuery: SELECT 1
testWhileIdle: true testWhileIdle: true
hikari.registerMbeans: true hikari.registerMbeans: true
security: security:
basepath: http://cdb.bytebot.t186a1:9077/bytebot basepath: http://192.168.1.6:9077/bytebot
provider: byte # oracle, amazon provider: byte # oracle, amazon
oauth2-client: oauth2-client:
clientId: xdf-client clientId: xdf-client
clientSecret: xdf-secret clientSecret: xdf-secret
accessTokenUri: http://192.168.27.96:8080/oauth/token accessTokenUri: http://127.0.0.1:18080/oauth/token
userAuthorizationUri: http://192.168.27.96:8080/oauth/authorize userAuthorizationUri: http://127.0.0.1:18080/oauth/authorize
oauth2-resource: oauth2-resource:
userInfoUri: http://192.168.27.96:8080/oauth/userinfo userInfoUri: http://127.0.0.1:18080/oauth/userinfo
logoutUri: http://192.168.27.96:8080/oauth/userlogout logoutUri: http://127.0.0.1:18080/oauth/userlogout
jpa: jpa:
open-in-view: false open-in-view: true
properties.hibernate: properties.hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect dialect: org.hibernate.dialect.PostgreSQLDialect #org.hibernate.dialect.MySQL5Dialect
format_sql: false format_sql: false
hbm2ddl.auto: none hbm2ddl.auto: none
jdbc: jdbc:
...@@ -150,20 +165,20 @@ spring: ...@@ -150,20 +165,20 @@ spring:
non_contextual_creation: true non_contextual_creation: true
show-sql: true show-sql: true
#session.store-type: jdbc #session.store-type: jdbc
activemq.broker-url: tcp://192.168.27.96:61616 activemq.broker-url: tcp://localhost:8161
batch: batch:
tenants: tenants:
- -
id: T186A1 id: T186A1
datasource: datasource:
jdbc-driver: com.mysql.cj.jdbc.Driver jdbc-driver: 'org.postgresql.Driver'
username: root username: postgres
password: byte2k20 password:
jdbc-url: jdbc:mysql://192.168.27.96:3306/BYTEBOT_T186A1?useSSL=false jdbc-url: jdbc:postgresql://192.168.21.74:5432/broker_rasa_db?useSSL=false
query: 'select * from events WHERE id > %d order by id asc' query: 'select * from events WHERE id > %d order by id asc'
logging.level.root: INFO logging.level.root: DEBUG
logging.pattern.console: '%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n' logging.pattern.console: '%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n'
logging.level.com.zaxxer.hikari: ERROR logging.level.com.zaxxer.hikari: ERROR
......
...@@ -7,11 +7,11 @@ ...@@ -7,11 +7,11 @@
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true"> <select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count, SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal G.GOAL_IDENT as goal
FROM BBOT_ACTION_SESSION BAS FROM AVB_ACTION_SESSION BAS
LEFT JOIN BBOT_ACTION A ON BAS.ACTION_ID = A.ACTION_ID JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
LEFT JOIN BBOT_GOAL G ON G.GOAL_ID = A.GOAL_ID JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
WHERE A.ACTION_RGOAL = 'Y' JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
AND BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate} WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID GROUP BY G.GOAL_ID;
</select> </select>
</mapper> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.AgentMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getCredentialsFromAgentandChannel" resultType="DeploymentChannelParamValue" flushCache="true">
SELECT chpv_id as id,
chpa_label as channelParamName,
chpv_value as value,
AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
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_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status}
</select>
</mapper>
...@@ -6,14 +6,16 @@ ...@@ -6,14 +6,16 @@
<select id="countMessagesInRange" resultType="int" flushCache="true"> <select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID) SELECT COUNT(MESSA_ID)
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
and INTEN_ID IS NOT NULL
</select> </select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true"> <select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID) SELECT COUNT(MESSA_ID)
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
and INTEN_ID IS NOT NULL
</select> </select>
<!-- @TODO Pendiente agregar la fecha --> <!-- @TODO Pendiente agregar la fecha -->
...@@ -23,11 +25,16 @@ ...@@ -23,11 +25,16 @@
COUNT(MESSA_ID) AS count, COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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>
...@@ -38,24 +45,34 @@ ...@@ -38,24 +45,34 @@
COUNT(MESSA_ID) AS count, COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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 BBOT_SUMMARY ORDER BY count DESC) as AVB_SUMMARY
</select> </select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true"> <select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count, SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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>
...@@ -64,7 +81,7 @@ ...@@ -64,7 +81,7 @@
SELECT SELECT
COUNT(MESSA_ID) as count, COUNT(MESSA_ID) as count,
MESSA_CONT as identifier MESSA_CONT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT GROUP BY MESSA_CONT
...@@ -75,25 +92,32 @@ ...@@ -75,25 +92,32 @@
SELECT count(*) FROM (SELECT SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count, COUNT(MESSA_ID) as count,
MESSA_CONT as identifier MESSA_CONT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL WHERE INTEN_ID IS 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}
GROUP BY MESSA_CONT GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as BBOT_SUMMARY ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select> </select>
<select id="countByIntentAndRange" resultType="int" flushCache="true"> <select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(M.MESSA_ID)
FROM BBOT_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>
<select id="countBySentencesAndRange" resultType="int" flushCache="true"> <select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(MESSA_ID)
FROM BBOT_MESSAGE WHERE INTEN_ID IS NULL FROM AVB_MESSAGE WHERE 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>
...@@ -102,28 +126,28 @@ ...@@ -102,28 +126,28 @@
( (
SELECT COUNT(MESSA_ID) as COUNT_MESSA, SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID S.USER_ID
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_SESSION S ON M.SESSION_ID = S.SESSION_ID LEFT JOIN AVB_SESSION S ON M.SESSION_ID = S.SESSION_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate} WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY S.USER_ID GROUP BY S.USER_ID
) BBOT_INTENT_CUSTOMER ) AVB_INTENT_CUSTOMER
</select> </select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true"> <select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT SELECT
COUNT(M.MESSA_ID) as count, COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier I.INTEN_IDENT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate} WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY I.INTEN_IDENT GROUP BY I.INTEN_IDENT
</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 BBOT_SESSION FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from BBOT_MESSAGE bm WHERE MESSA_CONT = #{sentence}) WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select> </select>
</mapper> </mapper>
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<select id="countMessagesInRange" resultType="int" flushCache="true"> <select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID) SELECT COUNT(RESPO_ID)
FROM BBOT_RESPONSE FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate} WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select> </select>
</mapper> </mapper>
...@@ -6,35 +6,34 @@ ...@@ -6,35 +6,34 @@
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true"> <select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT select SESSION_LEDAT
FROM BBOT_SESSION bas FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate} WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate} AND SESSION_LEDAT &gt;= #{startDate}
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="int" flushCache="true">
select COUNT(SESSION_ID) select count(session_id) from avb_session
FROM BBOT_SESSION bas WHERE SESSION_LEDAT &lt;= #{endDate}
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_LEDAT &gt;= #{startDate}
AND SESSION_DATE &gt;= #{startDate}
</select> </select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true"> <select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM select avg(SESSION_CANT) FROM
( (
select count(USER_ID) as SESSION_CANT select count(USER_ID) as SESSION_CANT
from BBOT_SESSION bas from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID WHERE SESSION_LEDAT &lt;= #{endDate} AND SESSION_LEDAT &gt;= #{startDate} GROUP BY USER_ID
) BBOT_SESSION_COUNT ) AVB_SESSION_COUNT
</select> </select>
<select id="avgFirstResponseTime" resultType="Long" flushCache="true"> <select id="avgFirstResponseTime" resultType="Long" flushCache="true">
SELECT AVG(RESP_TIME) SELECT AVG(RESP_TIME)
FROM ( FROM (
select TIMESTAMPDIFF(SECOND, SESSION_DATE, SESSION_FRDAT) AS RESP_TIME select TIMESTAMPDIFF(MICROSECOND, SESSION_DATE, SESSION_FRDAT)/1000 AS RESP_TIME
from BBOT_SESSION bs WHERE SESSION_FRDAT IS NOT NULL from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT NULL
AND SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate} AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF ) RESPONSE_DIF
</select> </select>
</mapper> </mapper>
...@@ -7,11 +7,11 @@ ...@@ -7,11 +7,11 @@
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true"> <select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count, SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal G.GOAL_IDENT as goal
FROM BBOT_ACTION_SESSION BAS FROM AVB_ACTION_SESSION BAS
LEFT JOIN BBOT_ACTION A ON BAS.ACTION_ID = A.ACTION_ID JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
LEFT JOIN BBOT_GOAL G ON G.GOAL_ID = A.GOAL_ID JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
WHERE A.ACTION_RGOAL = 'Y' JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
AND BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate} WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID GROUP BY G.GOAL_ID;
</select> </select>
</mapper> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.AgentMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getCredentialsFromAgentandChannel" resultType="DeploymentChannelParamValue" flushCache="true">
SELECT chpv_id as id,
chpa_label as channelParamName,
chpv_value as value,
AG.agen_id as agen_id,
AC.chan_iden as channel
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
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_agent AG on AG.agen_id=AD.agen_id
JOIN avb_channel AC on AC.chan_id=ACP.chan_id
WHERE agen_state=#{status}
</select>
</mapper>
...@@ -6,14 +6,16 @@ ...@@ -6,14 +6,16 @@
<select id="countMessagesInRange" resultType="int" flushCache="true"> <select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID) SELECT COUNT(MESSA_ID)
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
and INTEN_ID IS NOT NULL
</select> </select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true"> <select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID) SELECT COUNT(MESSA_ID)
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
and INTEN_ID IS NOT NULL
</select> </select>
<!-- @TODO Pendiente agregar la fecha --> <!-- @TODO Pendiente agregar la fecha -->
...@@ -23,11 +25,16 @@ ...@@ -23,11 +25,16 @@
COUNT(MESSA_ID) AS count, COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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>
...@@ -38,24 +45,34 @@ ...@@ -38,24 +45,34 @@
COUNT(MESSA_ID) AS count, COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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 BBOT_SUMMARY ORDER BY count DESC) as AVB_SUMMARY
</select> </select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true"> <select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count, SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier, I.INTEN_IDENT as identifier,
I.INTEN_ID as id I.INTEN_ID as id
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_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>
...@@ -64,7 +81,7 @@ ...@@ -64,7 +81,7 @@
SELECT SELECT
COUNT(MESSA_ID) as count, COUNT(MESSA_ID) as count,
MESSA_CONT as identifier MESSA_CONT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate} AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT GROUP BY MESSA_CONT
...@@ -75,25 +92,32 @@ ...@@ -75,25 +92,32 @@
SELECT count(*) FROM (SELECT SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count, COUNT(MESSA_ID) as count,
MESSA_CONT as identifier MESSA_CONT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL WHERE INTEN_ID IS 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}
GROUP BY MESSA_CONT GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as BBOT_SUMMARY ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select> </select>
<select id="countByIntentAndRange" resultType="int" flushCache="true"> <select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(M.MESSA_ID)
FROM BBOT_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>
<select id="countBySentencesAndRange" resultType="int" flushCache="true"> <select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT SELECT
COUNT(MESSA_ID) COUNT(MESSA_ID)
FROM BBOT_MESSAGE WHERE INTEN_ID IS NULL FROM AVB_MESSAGE WHERE 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>
...@@ -102,19 +126,19 @@ ...@@ -102,19 +126,19 @@
( (
SELECT COUNT(MESSA_ID) as COUNT_MESSA, SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID S.USER_ID
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_SESSION S ON M.SESSION_ID = S.SESSION_ID LEFT JOIN AVB_SESSION S ON M.SESSION_ID = S.SESSION_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate} WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY S.USER_ID GROUP BY S.USER_ID
) BBOT_INTENT_CUSTOMER ) AVB_INTENT_CUSTOMER
</select> </select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true"> <select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT SELECT
COUNT(M.MESSA_ID) as count, COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier I.INTEN_IDENT as identifier
FROM BBOT_MESSAGE M FROM AVB_MESSAGE M
LEFT JOIN BBOT_INTENT I LEFT JOIN AVB_INTENT I
ON M.INTEN_ID = I.INTEN_ID ON M.INTEN_ID = I.INTEN_ID
WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate} WHERE M.INTEN_ID IS NOT NULL AND M.MESSA_DATE &lt; #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY I.INTEN_IDENT GROUP BY I.INTEN_IDENT
...@@ -123,7 +147,7 @@ ...@@ -123,7 +147,7 @@
<select id="countCustomersBySentence" resultType="int" flushCache="true"> <select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID) SELECT COUNT(distinct USER_ID)
FROM BBOT_SESSION FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from BBOT_MESSAGE bm WHERE MESSA_CONT = #{sentence}) WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select> </select>
</mapper> </mapper>
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<select id="countMessagesInRange" resultType="int" flushCache="true"> <select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID) SELECT COUNT(RESPO_ID)
FROM BBOT_RESPONSE FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate} WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select> </select>
</mapper> </mapper>
...@@ -6,38 +6,34 @@ ...@@ -6,38 +6,34 @@
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true"> <select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT select SESSION_LEDAT
FROM BBOT_SESSION bas FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate} WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate} AND SESSION_LEDAT &gt;= #{startDate}
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="int" flushCache="true">
select COUNT(SESSION_ID) select count(session_id) from avb_session
FROM BBOT_SESSION bas WHERE SESSION_LEDAT &lt;= #{endDate}
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_LEDAT &gt;= #{startDate}
AND SESSION_DATE &gt;= #{startDate}
</select> </select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true"> <select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM select avg(SESSION_CANT) FROM
( (
select count(USER_ID) as SESSION_CANT select count(USER_ID) as SESSION_CANT
from BBOT_SESSION bas from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID WHERE SESSION_LEDAT &lt;= #{endDate} AND SESSION_LEDAT &gt;= #{startDate} GROUP BY USER_ID
) BBOT_SESSION_COUNT ) AVB_SESSION_COUNT
</select> </select>
<select id="avgFirstResponseTime" resultType="Double" flushCache="true"> <select id="avgFirstResponseTime" resultType="Double" flushCache="true">
SELECT AVG(RESP_TIME) SELECT AVG(RESP_TIME)
FROM ( FROM (
SELECT ((DATE_PART('day', SESSION_FRDAT - SESSION_DATE) * 24 + SELECT DATE_PART('milliseconds', SESSION_FRDAT - SESSION_DATE) AS RESP_TIME
DATE_PART('hour', SESSION_FRDAT - SESSION_DATE)) * 60 + from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT null
DATE_PART('minute', SESSION_FRDAT - SESSION_DATE)) * 60 + AND SESSION_DATE &lt;= #{endDate}
DATE_PART('second', SESSION_FRDAT - SESSION_DATE) AS RESP_TIME AND SESSION_DATE &gt;= #{startDate}
from BBOT_SESSION bs WHERE SESSION_FRDAT IS NOT null
AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF ) RESPONSE_DIF
</select> </select>
</mapper> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAgentChannel" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
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_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel}
</select>
<select id="getControl" resultType="DeleteControl" flushCache="true">
SELECT dsmc_id as id,
agent_id as agentId,
dsmc_date as dateDelete,
evnt_id as eventId
FROM avb_delete_sens_msg_control
WHERE agent_id=#{agenId}
</select>
<select id="getIntentByAgent" resultType="String" flushCache="true">
SELECT
inten_ident as intent
FROM avb_intent
WHERE intent_is_sensible = #{sensible} AND agen_id = #{agenId}
</select>
</mapper>
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true"> <select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT SELECT IFNULL( (SELECT
MESSA_CORRE MESSA_CORRE
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId} WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative LIMIT 1) ,0) as correlative
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true"> <select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT SELECT IFNULL( (SELECT
RESPO_CORR RESPO_CORR
FROM BBOT_RESPONSE FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId} WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative LIMIT 1) ,0) as correlative
......
...@@ -10,9 +10,9 @@ ...@@ -10,9 +10,9 @@
SESSION_DATE as sessionDate, SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate, SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate, SESSION_FRDAT as responseDate,
CHANN_ID as channelId, chan_id as channelId,
USER_ID as userId USER_ID as userId
FROM BBOT_SESSION FROM AVB_SESSION
WHERE USER_ID = ${userId} WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC ORDER BY SESSION_DATE DESC
LIMIT 1 LIMIT 1
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
<update id="updateLastEventDate" flushCache="true"> <update id="updateLastEventDate" flushCache="true">
UPDATE UPDATE
BBOT_SESSION SET AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate} SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID} WHERE SESSION_ID = ${sessionID}
</update> </update>
......
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getAgentChannel" resultType="ChannelByAgent" flushCache="true">
SELECT chpv_id as id,
chpv_value as channelValue,
AG.agen_iden as value,
AG.agen_id as agenId,
AG.agen_delete_sensible_period as deletePeriod
FROM AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE ADCP
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_agent AG on AG.agen_id=AD.agen_id
WHERE agen_state=#{status} AND chpa_label=#{channel}
</select>
<select id="getControl" resultType="DeleteControl" flushCache="true">
SELECT dsmc_id as id,
agent_id as agentId,
dsmc_date as dateDelete,
evnt_id as eventId
FROM avb_delete_sens_msg_control
WHERE agent_id=#{agenId}
</select>
<select id="getIntentByAgent" resultType="String" flushCache="true">
SELECT
inten_ident as intent
FROM avb_intent
WHERE intent_is_sensible = #{sensible} AND agen_id = #{agenId}
</select>
</mapper>
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true"> <select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT SELECT coalesce( (SELECT
MESSA_CORRE MESSA_CORRE
FROM BBOT_MESSAGE FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId} WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative LIMIT 1) ,0) as correlative
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true"> <select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT SELECT coalesce( (SELECT
RESPO_CORR RESPO_CORR
FROM BBOT_RESPONSE FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId} WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative LIMIT 1) ,0) as correlative
......
...@@ -10,9 +10,9 @@ ...@@ -10,9 +10,9 @@
SESSION_DATE as sessionDate, SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate, SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate, SESSION_FRDAT as responseDate,
CHANN_ID as channelId, chan_id as channelId,
USER_ID as userId USER_ID as userId
FROM BBOT_SESSION FROM AVB_SESSION
WHERE USER_ID = ${userId} WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC ORDER BY SESSION_DATE DESC
LIMIT 1 LIMIT 1
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
<update id="updateLastEventDate" flushCache="true"> <update id="updateLastEventDate" flushCache="true">
UPDATE UPDATE
BBOT_SESSION SET AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate} SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID} WHERE SESSION_ID = ${sessionID}
</update> </update>
......
...@@ -10,7 +10,12 @@ ...@@ -10,7 +10,12 @@
<typeAlias type="com.bytesw.bytebot.bean.SummaryMessageBySentenceBean" alias="SummaryMessageBySentence"/> <typeAlias type="com.bytesw.bytebot.bean.SummaryMessageBySentenceBean" alias="SummaryMessageBySentence"/>
<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.SessionByClientBean" alias="SessionByClient"/>
<typeAlias type="com.bytesw.bytebot.etl.beans.SessionBean" alias="Session"/> <typeAlias type="com.bytesw.bytebot.etl.beans.SessionBean" alias="Session"/>
<typeAlias type="com.bytesw.bytebot.etl.batch.beans.DeleteDataSensBean" alias="ChannelByAgent"/>
<typeAlias type="com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean" alias="DeleteControl"/>
</typeAliases> </typeAliases>
<mappers> <mappers>
...@@ -19,10 +24,13 @@ ...@@ -19,10 +24,13 @@
<mapper resource="config/mappers/bytebot/${database-type-xdf}/MessageMapper.xml"/> <mapper resource="config/mappers/bytebot/${database-type-xdf}/MessageMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/ResponseMapper.xml"/> <mapper resource="config/mappers/bytebot/${database-type-xdf}/ResponseMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/ActionMapper.xml"/> <mapper resource="config/mappers/bytebot/${database-type-xdf}/ActionMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/AgentMapper.xml"/>
<mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/> <mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/SessionMapper.xml"/> <mapper resource="config/mappers/etl/${database-type-xdf}/SessionMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/MessageMapper.xml"/> <mapper resource="config/mappers/etl/${database-type-xdf}/MessageMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/ResponseMapper.xml"/> <mapper resource="config/mappers/etl/${database-type-xdf}/ResponseMapper.xml"/>
<mapper resource="config/mappers/etl/${database-type-xdf}/DataSensibleMapper.xml"/>
</mappers> </mappers>
</configuration> </configuration>
database-type-xdf=mysql database-type-xdf=postgres
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