Commit 750843b0 authored by Josue's avatar Josue

Initial commit

parent 353037f9
Pipeline #354 failed with stages
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 ActionSummaryByGoalBean implements Serializable {
@Expose
private String goal;
@Expose
private BigInteger count;
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Agent;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter @Setter
@ToString
public class AgentBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String description;
@Expose
private String version;
@Expose
private String status;
@Expose
private Long countryId;
@Expose
private String countryName;
@Expose
private String timezone;
@Expose
private String avatar;
@Expose
private String language;
@Expose
private String type;
@Expose
private int period;
@Expose
private List<DeploymentChannelBean> deploymentChannels;
@Expose
private List<FrequentQuestionBean> frequentQuestions;
public static AgentBean miniClone(Agent agent) {
AgentBean bean = new AgentBean();
bean.setId(agent.getId());
bean.setName(agent.getName());
bean.setVersion(agent.getVersion());
bean.setStatus(agent.getStatus().getName());
bean.setTimezone(agent.getTimezone());
bean.setAvatar(agent.getAvatar());
if (agent.getCountry() != null) {
bean.setCountryName(agent.getCountry().getName());
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigDecimal;
@Getter @Setter
public class AverageBean implements Serializable {
@Expose
private BigDecimal firstResponseAverage;
@Expose
private BigDecimal sessionAverage;
}
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 BdcControlBean implements Serializable {
@Expose private Long id;
@Expose private String uuid;
@Expose private String fileName;
@Expose private String status;
@Expose private String user;
@Expose private String date;
@Expose private Long fileId;
}
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.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;
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 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.
*/
@Getter
@Setter
@ToString
public class ChannelBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String image;
@Expose
private List<ChannelParamBean> parameters;
@Expose
private String suggestTitle;
@Expose
private String suggestDetail;
public static ChannelBean clone(Channel channel) {
ChannelBean bean = new ChannelBean();
bean.setId(channel.getId());
bean.setName(channel.getName());
bean.setImage(channel.getImage());
bean.setParameters(new ArrayList<>());
bean.setSuggestTitle(channel.getSuggestTitle());
bean.setSuggestDetail(channel.getSuggestDetail());
if (channel.getParameters() != null) {
Collections.sort(channel.getParameters(), (o1, o2) -> o1.getOrder() - o2.getOrder());
for (ChannelParam param : channel.getParameters()) {
bean.getParameters().add(ChannelParamBean.clone(param));
}
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.ChannelParam;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 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.
*/
@Getter
@Setter
@ToString
public class ChannelParamBean {
@Expose
private String name;
@Expose
private String label;
@Expose
private Integer maxlength;
@Expose
private String type;
@Expose
private Boolean required;
@Expose
private Integer order;
@Expose
private String traductions;
@Expose
private String regex;
public static ChannelParamBean clone(ChannelParam channelParam) {
ChannelParamBean bean = new ChannelParamBean();
bean.setName(channelParam.getName());
bean.setLabel(channelParam.getLabel());
bean.setMaxlength(channelParam.getMaxlength());
bean.setRequired(channelParam.isRequired());
bean.setType(channelParam.getType());
bean.setOrder(channelParam.getOrder());
bean.setTraductions(channelParam.getTraductions());
bean.setRegex(channelParam.getRegex());
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.bytesw.bytebot.model.Country;
import com.bytesw.bytebot.model.Timezone;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
* <p>
* Copyright (c) 2020 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.
*/
@Getter
@Setter
@ToString
public class CountryBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private List<String> timezones;
public static CountryBean clone(Country country) {
CountryBean bean = new CountryBean();
bean.setId(country.getId());
bean.setName(country.getName());
bean.setTimezones(new ArrayList<>());
if (country.getTimezones() != null) {
for (Timezone timezone : country.getTimezones()) {
bean.getTimezones().add(timezone.getTimezone());
}
}
return bean;
}
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
@Setter
@ToString
public class DeploymentChannelBean {
@Expose
private Long id;
@Expose
private String name;
@Expose
private String status;
@Expose
private Long channelId;
@Expose
private String channelName;
@Expose
private List<DeploymentChannelParamValueBean> parameters;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
@Setter
@ToString
public class DeploymentChannelParamValueBean {
@Expose
private Long id;
@Expose
private String channelParamName;
@Expose
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 lombok.ToString;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
* <p>
* Copyright (c) 2020 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.
*/
@Getter
@Setter
@ToString
public class FrequentQuestionBean {
@Expose
private Long id;
@Expose
private String uuid;
@Expose
private String filename;
@Expose
private String description;
@Expose
private String status;
@Expose
private String user;
@Expose
private String uploadDate;
}
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 MessageByIntentBean implements Serializable {
@Expose
private String identifier;
@Expose
private BigInteger count;
}
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 lombok.Getter;
import lombok.Setter;
import java.time.OffsetDateTime;
@Getter @Setter
public class RangeBean {
private OffsetDateTime startDate;
private OffsetDateTime endDate;
}
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;
}
package com.bytesw.bytebot.bean;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@Getter @Setter
public class SummaryBean implements Serializable {
@Expose
private BigInteger value;
@Expose
private BigDecimal percent;
@Expose
private List<ArrayList<Object>> history;
}
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 SummaryMessageByIntentBean implements Serializable {
@Expose
private Long id;
@Expose
private String identifier;
@Expose
private BigInteger count;
}
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 OffsetTime from;
@Expose
private OffsetTime to;
@Expose
private String calendarID;
@Expose
private String calendarName;
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.etl.beans.ActionBean;
import com.bytesw.bytebot.service.ActionService;
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/actions")
@ProgramSecurity("ACTIONS")
@Log4j2
public class ActionController extends XDFController<ActionBean, Long> {
public ActionController(ActionService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.controller.bean.ResponseController;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.service.*;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.swagger.annotations.ApiParam;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
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 org.springframework.web.multipart.MultipartFile;
@Log4j2
@RestController
@RequestMapping("/service/agent")
@ProgramSecurity("conversational_agent")
public class AgentController {
@Autowired
private AgentService agentService;
@Autowired
private FileManagementService fileManagementService;
@Autowired
private GsonBuilder gsonBuilder;
@Autowired
private OrquestadorService orquestadorService;
@PostMapping(value = "/page")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> paginationConversationalAgent(@RequestBody Pagination<AgentBean> pagination) {
HttpStatus hs = HttpStatus.OK;
try {
agentService.searchByPagination(pagination);
return new ResponseEntity<>(gsonBuilder.create().toJson(pagination), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getConversartionalAgentById(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getAgent(id)), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PutMapping(value = "/")
@PreAuthorize("hasPermission(this, 'new')")
public ResponseEntity<String> createConversationalAgent(@RequestBody AgentBean agentBean) {
HttpStatus hs = HttpStatus.OK;
try {
agentService.save(agentBean);
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.insert.success", hs.value())), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PutMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> updateConversationalAgent(@PathVariable("id") Long id,
@RequestBody AgentBean agentBean) {
HttpStatus hs = HttpStatus.OK;
try {
if (id != null) {
agentService.save(agentBean);
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.update.success", hs.value())), hs);
} else {
hs = HttpStatus.UNAUTHORIZED;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.update.error", hs.value())), hs);
}
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasPermission(this, 'delete')")
public ResponseEntity<String> deleteConversationalAgent(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
HttpStatus hs = HttpStatus.OK;
try {
if (id != null) {
boolean deleteValid = agentService.delete(id);
if (deleteValid) {
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.success", hs.value())), hs);
} else {
// hs = HttpStatus.FAILED_DEPENDENCY;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.error.integrity", hs.FAILED_DEPENDENCY.value())), hs);
}
} else {
hs = HttpStatus.UNAUTHORIZED;
return new ResponseEntity<>(gsonBuilder.create().toJson(new ResponseController("agent.delete.error.unauthtorized", hs.value())), hs);
}
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/countries")
public ResponseEntity<String> getCountries() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getCountries()), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@GetMapping(value = "/channels")
public ResponseEntity<String> getChannels() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getChannels()), hs);
} catch (Exception e) {
log.error("Error detectado: ", e);
hs = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(gsonBuilder.create().toJson(ExceptionUtils.getFullStackTrace(e)), hs);
}
}
@PostMapping("/file-upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, Principal principal) {
Gson gson = gsonBuilder.create();
try {
String uuid = UUID.randomUUID().toString();
FileValidationResponse response = orquestadorService.executeGenerateBCD(uuid, file);
response.setUser(principal != null ? principal.getName() : null);
return new ResponseEntity<>(gson.toJson(response), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping("/file-upload/{uuid}")
public ResponseEntity<String> uploadFile(@PathVariable("uuid") String uuid, Principal principal) {
Gson gson = gsonBuilder.create();
try {
FileValidationResponse response = orquestadorService.retry(uuid);
response.setUser(principal != null ? principal.getName() : null);
return new ResponseEntity<>(gson.toJson(response), HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("/file-upload/{uuid}")
public ResponseEntity<String> deleteBdc(@ApiParam(value = "uuid", required = true) @PathVariable("uuid") String uuid) {
Gson gson = gsonBuilder.create();
Map<String, String> resp = new HashMap<>();
try {
orquestadorService.deleteBcd(uuid);
resp.put("message", "OK");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.OK);
} catch (Exception e) {
resp.put("message", "ERROR");
return new ResponseEntity<>(gson.toJson(resp), HttpStatus.OK);
}
}
@GetMapping("/synchronize/{id}")
public ResponseEntity<String> synchronizeFiles(@PathVariable("id") Long id,
@RequestParam("user") String user) {
Gson gson = new GsonBuilder().create();
try {
agentService.synchronizeFiles(id, user);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(value = "/")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> getAgentAll() {
HttpStatus hs = HttpStatus.OK;
try {
return new ResponseEntity<>(gsonBuilder.create().toJson(agentService.getAgentAll()), 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.dto.AirportDto;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.service.AirportService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/service/airport")
public class AirportController extends BasicXDFController<AirportDto, Long> {
@Autowired
private AirportService airportService;
@Autowired
private GsonBuilder gsonBuilder;
public AirportController(AirportService airportService) {
super(airportService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<AirportDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<AirportDto> value = new DataPage<>();
value.setData(airportService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.BdcControlBean;
import com.bytesw.bytebot.service.BcdControlService;
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/bcdControl")
@ProgramSecurity("BCDCONTROL")
@Log4j2
public class BdcControlController extends XDFController<BdcControlBean, Long> {
public BdcControlController(BcdControlService service) {
super(service);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.dto.BookingAgentDto;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.service.BookingAgentService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/service/agent")
public class BookingAgentController extends BasicXDFController<BookingAgentDto, Long> {
@Autowired
private BookingAgentService agentService;
@Autowired
private GsonBuilder gsonBuilder;
public BookingAgentController(BookingAgentService bookingAgentService) {
super(bookingAgentService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<BookingAgentDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<BookingAgentDto> value = new DataPage<>();
value.setData(agentService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
}
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.createBP(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("/service/settings/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;
import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean;
import com.bytesw.bytebot.service.dashboard.CustomerInteractionDashboardService;
import com.bytesw.bytebot.service.dashboard.OperativeDashboardService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/dashboard")
public class DashboardController {
@Autowired
private OperativeDashboardService operativeDashboardService;
@Autowired
private CustomerInteractionDashboardService customerInteractionDashboardService;
@Autowired
private Gson gson;
@PostMapping("/operative")
public ResponseEntity<String> getOperativeInfo(@RequestBody Map<String, Object> body) {
Map<String, Object> info = operativeDashboardService.generateInfo(body);
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
@PostMapping("/operative/sentence-by-intent/page")
public ResponseEntity<String> getSentenceByIntentPage(@RequestBody Pagination<SummaryMessageBySentenceBean> pagination) {
customerInteractionDashboardService.getSummaryBySentencePagination(pagination);
return new ResponseEntity<>(gson.toJson(pagination), HttpStatus.OK);
}
@PostMapping("/customer-interaction")
public ResponseEntity<String> getCustomerInteractionInfo(@RequestBody Map<String, Object> body) {
Map<String, Object> info = customerInteractionDashboardService.generateInfo(body);
return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
}
@PostMapping("/customer-interaction/message-by-intent/page")
public ResponseEntity<String> getMessageByIntentPage(@RequestBody Pagination<SummaryMessageBySentenceBean> pagination) {
customerInteractionDashboardService.getSummaryByIntentAndSentencePagination(pagination);
return new ResponseEntity<>(gson.toJson(pagination), HttpStatus.OK);
}
@GetMapping("/test")
public ResponseEntity<String> getTest() {
Map<String, Object> data = customerInteractionDashboardService.generateInfo(new HashMap<>());
return new ResponseEntity<>(gson.toJson(data), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.dto.FlightDto;
import com.bytesw.bytebot.service.AirportService;
import com.bytesw.bytebot.service.FlightService;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/service/flight")
public class FlightController extends XDFController<FlightDto, Long> {
@Autowired
private FlightService flightService;
@Autowired
private AirportService airportService;
@Autowired
private GsonBuilder gsonBuilder;
public FlightController(FlightService flightService) {
super(flightService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<FlightDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<FlightDto> value = new DataPage<>();
value.setData(flightService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
public ResponseEntity<String> findAll(HttpServletRequest req) {
return new ResponseEntity(this.flightService.getAll(), HttpStatus.OK);
}
public ResponseEntity<String> findOne(@PathVariable("id") Long id, HttpServletRequest req) {
return new ResponseEntity(this.flightService.getById(id), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.service.GoalService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.google.gson.GsonBuilder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController()
@RequestMapping("/service/settings/goal")
@ProgramSecurity("GOAL")
@Log4j2
public class GoalController extends XDFController<Map, Long> {
@Autowired
private GoalService goalService;
@Autowired
private GsonBuilder gsonBuilder;
public GoalController(GoalService service) {
super(service);
}
}
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.dto.DataPage;
import com.bytesw.bytebot.dto.ItineraryReservationDto;
import com.bytesw.bytebot.service.ItineraryReservationService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/service/itinerarys")
public class ItineraryReservationController extends BasicXDFController<ItineraryReservationDto, Long> {
@Autowired
private ItineraryReservationService itineraryReservationService;
@Autowired
private GsonBuilder gsonBuilder;
public ItineraryReservationController(ItineraryReservationService itineraryReservationService) {
super(itineraryReservationService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<ItineraryReservationDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<ItineraryReservationDto> value = new DataPage<>();
value.setData(itineraryReservationService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
public ResponseEntity<String> finAll(HttpServletRequest req) {
return new ResponseEntity(this.itineraryReservationService.getAll(), HttpStatus.OK);
}
public ResponseEntity<String> findOne(@PathVariable("id") Long id, HttpServletRequest req) {
return new ResponseEntity(this.itineraryReservationService.getById(id), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.dto.LegDto;
import com.bytesw.bytebot.model.Leg;
import com.bytesw.bytebot.repository.IItineraryReservationRepository;
import com.bytesw.bytebot.repository.ILegRepository;
import com.bytesw.bytebot.service.FlightService;
import com.bytesw.bytebot.service.LegService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/service/leg")
public class LegController extends BasicXDFController<LegDto, Long> {
@Autowired
private LegService legService;
@Autowired
private FlightService flightService;
@Autowired
private IItineraryReservationRepository iItineraryReservationRepository;
@Autowired
private ILegRepository legRepository;
@Autowired
private GsonBuilder gsonBuilder;
public LegController(LegService legService) {
super(legService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<LegDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<LegDto> value = new DataPage<>();
value.setData(legService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
@GetMapping("list/{id}/flights")
public ResponseEntity<String> listFlightsByLegs(@PathVariable(value = "id") Long id) {
return new ResponseEntity(flightService.getById(id).getLegs(), HttpStatus.OK);
}
@PostMapping("/reservation/{id}")
public ResponseEntity<String> addLeg(@PathVariable(value = "id") Long id, @RequestBody Leg legReq) {
Leg leg = iItineraryReservationRepository.findById(id).map( itineraryReservation -> {
Long legId = legReq.getId();
Leg nLeg = legRepository.getOne(legId);
itineraryReservation.addLeg(nLeg);
iItineraryReservationRepository.save(itineraryReservation);
return nLeg;
}).orElseThrow(null);
return new ResponseEntity(HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.dto.PassengerDto;
import com.bytesw.bytebot.service.PassengerService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/service/passenger")
public class PassengerController extends BasicXDFController<PassengerDto, Long> {
@Autowired
private PassengerService passengerService;
@Autowired
private GsonBuilder gsonBuilder;
public PassengerController(PassengerService passengerService) {
super(passengerService);
}
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<PassengerDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<PassengerDto> value = new DataPage<>();
value.setData(passengerService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
public ResponseEntity<String> findAll(HttpServletRequest req) {
return new ResponseEntity(this.passengerService.getAll(), HttpStatus.OK);
}
}
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.dto.DataPage;
import com.bytesw.bytebot.dto.PaymentDto;
import com.bytesw.bytebot.model.Payment;
import com.bytesw.bytebot.repository.IItineraryReservationRepository;
import com.bytesw.bytebot.repository.IPaymentRepository;
import com.bytesw.bytebot.service.PaymentService;
import com.bytesw.xdf.controller.BasicXDFController;
import com.bytesw.xdf.service.XDFService;
import com.bytesw.xdf.sql.beans.Pagination;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/service/payment")
public class PaymentController extends BasicXDFController<PaymentDto, Long> {
@Autowired
private PaymentService paymentService;
@Autowired
private IItineraryReservationRepository itineraryReservationRepository;
@Autowired
private IPaymentRepository paymentRepository;
@Autowired
private GsonBuilder gsonBuilder;
public PaymentController(PaymentService paymentService) {
super(paymentService);
}
@Override
public ResponseEntity<String> findAllByPagination(@RequestBody Pagination<PaymentDto> pagination) {
Gson gson = gsonBuilder.create();
DataPage<PaymentDto> value = new DataPage<>();
value.setData(paymentService.getAll());
return new ResponseEntity(value, HttpStatus.OK);
}
@PostMapping("/reservations/{id}/payments")
public ResponseEntity<String> addTag(@PathVariable(value = "id") Long id, @RequestBody Payment paymentReq) {
Payment payment = itineraryReservationRepository.findById(id).map(itineraryReservation -> {
Long paymentId = paymentReq.getId();
Payment pay = paymentRepository.findById(paymentId).orElseThrow(null);
itineraryReservation.addPayment(pay);
itineraryReservationRepository.save(itineraryReservation);
return pay;
}).orElseThrow(null);
return new ResponseEntity(HttpStatus.OK);
}
}
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/settings/scheduler-task")
@ProgramSecurity("SCHEDULER-TASK")
@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.beans; package com.bytesw.bytebot.dto;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import java.io.Serializable;
@Getter @Getter
@Setter @Setter
@ToString @ToString
public class GoalBean { public class AirportDto implements Serializable {
@Expose @Expose
private Long id; private Long id;
@Expose @Expose
private String identifier; private String airportCode;
@Expose @Expose
private Long agenId; private String airportName;
@Expose
} private String airportLocation;
\ No newline at end of file @Expose
private String details;
}
package com.bytesw.bytebot.bean; package com.bytesw.bytebot.dto;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger;
@Getter @Setter @Getter
public class SummaryMessageBySentenceBean implements Serializable { @Setter
@ToString
public class BookingAgentDto implements Serializable {
@Expose @Expose
private Long id; private Long id;
@Expose @Expose
private String identifier; private String agentName;
@Expose @Expose
private String sentence; private String agentLastname;
@Expose @Expose
private BigInteger count; private String dni;
@Expose @Expose
private BigInteger customerCount; private String agentPhone;
@Expose
private String agentDetails;
} }
package com.bytesw.bytebot.etl.beans; package com.bytesw.bytebot.dto;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
@Getter @Getter
@Setter @Setter
@ToString public class DataPage<T> implements Serializable {
public class ActionBean {
@Expose
private Long id;
@Expose @Expose
private String identifier; private List<T> data;
} }
package com.bytesw.bytebot.dto;
import com.bytesw.bytebot.model.Leg;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Getter
@Setter
@ToString
public class FlightDto implements Serializable {
@Expose
private Long id;
@Expose
private String airlineCode;
@Expose
private String codeTypeAircraft;
@Expose
private Date departureDate;
@Expose
private Date arrivalDate;
@Expose
private Long codeAirportOrigin;
@Expose
private Long codeAirportDestination;
@Expose
private List<Leg> legs;
@Expose
private double flightCost;
@Expose
private String airportOrigin;
@Expose
private String airportDestination;
}
package com.bytesw.bytebot.bean; package com.bytesw.bytebot.dto;
import com.bytesw.bytebot.model.Leg;
import com.bytesw.bytebot.model.Payment;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date;
import java.util.List; import java.util.List;
@Getter @Getter
@Setter @Setter
public class CalendarBean implements Serializable { @ToString
public class ItineraryReservationDto implements Serializable {
@Expose @Expose
private String id; private Long id;
@Expose @Expose
private long version; private Date dateReservation;
@Expose @Expose
private String name; private String status;
@Expose
//@TODO: Revisar List<WeekScheduler> weekSchedulerList de la clase Calendar private Long codePassenger;
@Expose
private Long codeAgent;
@Expose @Expose
private List<WeekSchedulerBean> weekSchedulerBeanList; private List<Payment> payments;
@Expose @Expose
private List<CalendarExceptionBean> calendarExceptionBeanList; private List<Leg> legs;
} }
\ No newline at end of file
package com.bytesw.bytebot.bean; package com.bytesw.bytebot.dto;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigInteger; import java.util.Date;
@Getter @Getter
@Setter @Setter
public class SchedulerTaskBean implements Serializable { @ToString
public class LegDto implements Serializable {
@Expose @Expose
private BigInteger id; private Long id;
@Expose @Expose
private long version; private Date departureDate;
@Expose @Expose
private String description; private Date arrivalDate;
@Expose @Expose
private String internals; private Long codeAirportOrigin;
@Expose @Expose
private String cronExpression; private Long codeAirportDestination;
@Expose @Expose
private String stringParameters; private Long codeFlight;
@Expose @Expose
private Integer etlId; private String airportOrigin;
@Expose @Expose
private String calendarID; private String airportDestination;
@Expose
private String calendarName;
// @Expose
// private int idEtl;
} }
package com.bytesw.bytebot.dto;
import com.bytesw.bytebot.model.ItineraryReservation;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
@ToString
public class PassengerDto implements Serializable {
@Expose
private Long id;
@Expose
private String firstName;
@Expose
private String secondName;
@Expose
private String lastName;
@Expose
private String phoneNumber;
@Expose
private String email;
@Expose
private String address;
@Expose
private String city;
@Expose
private String province;
@Expose
private String country;
@Expose
private String details;
@Expose
private List<ItineraryReservation> itineraryReservations = new ArrayList<>();
}
package com.bytesw.bytebot.etl.beans; package com.bytesw.bytebot.dto;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Getter @Getter
@Setter @Setter
@ToString @ToString
public class GoalForActionsBean { public class PaymentDto implements Serializable {
@Expose @Expose
private Long id; private Long id;
@Expose @Expose
private Long goalId; private Date paymentDate;
@Expose @Expose
private Long actionId; private double paymentAmount;
@Expose
private String status;
} }
package com.bytesw.bytebot.etl.batch.beans;
import lombok.*;
import java.io.Serializable;
@Getter @Setter
@EqualsAndHashCode
@AllArgsConstructor
@ToString
public class AttributeValueBean implements Serializable {
private final String identifier;
private String value;
private final Long dataTypeId;
}
package com.bytesw.bytebot.etl.batch.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class DBConfig{
@Value("${spring.datasource.driverClassName}")
private String classDriver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(classDriver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
}
\ No newline at end of file
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.beans;
import java.util.HashMap;
public class DynaBean extends HashMap<String, Object> {
}
package com.bytesw.bytebot.etl.batch.beans;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
@Getter @Setter
public class TenantBatchBean {
private String id;
private Map<String, String> datasource;
}
package com.bytesw.bytebot.etl.batch.factory.mapper;
import java.util.Map;
public interface MapperFactory<T> {
T createMapper(Map<String, Object> params);
}
package com.bytesw.bytebot.etl.batch.factory.mapper;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.batch.mapper.DynaBeanRowMapper;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class RowMapperFactory implements MapperFactory<DynaBeanRowMapper<DynaBean>>{
@Override
public DynaBeanRowMapper<DynaBean> createMapper(Map<String, Object> params) {
DynaBeanRowMapper<DynaBean> rowMapper = new DynaBeanRowMapper<>();
return rowMapper;
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.database.JdbcCursorItemReader;
@Log4j2
public class ByteDataBaseItemReaderFactory<T> extends JdbcCursorItemReader<T> implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
closeDatabase();
return stepExecution.getExitStatus();
}
private void closeDatabase() {
if (this.getDataSource() instanceof BasicDataSource) {
BasicDataSource dataSource = (BasicDataSource) this.getDataSource();
if (!dataSource.isClosed()) {
try {
dataSource.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
}
}
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import javax.sql.DataSource;
import java.util.Map;
/**
* Params:
* -jdbc-driver
* -username
* -password
* -jdbc-url
* -query
*/
@Component
@Log4j2
public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, RowMapper<DynaBean>> {
@Override
public ItemReader<DynaBean> createReader(RowMapper<DynaBean> mapper, Map<String, Object> params) {
JdbcCursorItemReader<DynaBean> databaseReader;
databaseReader = new ByteDataBaseItemReaderFactory<>();
String jdbcDriver = params.containsKey("jdbc-driver") ? String.valueOf(params.get("jdbc-driver")): null;;
Assert.isTrue(jdbcDriver != null, "jdbc-driver is required!");
String username = params.containsKey("username") ? String.valueOf(params.get("username")): null;;
Assert.isTrue(username != null, "username is required!");
String password = params.containsKey("password") ? String.valueOf(params.get("password")): null;;
Assert.isTrue(password != null, "password is required!");
String jdbcURL = params.containsKey("jdbc-url") ? String.valueOf(params.get("jdbc-url")): null;;
Assert.isTrue(jdbcURL != null, "jdbc-url is required!");
String query = params.containsKey("query") ? String.valueOf(params.get("query")): null;;
Assert.isTrue(query != null, "query is required!");
DataSource dataSource = getBasicDataSource(jdbcDriver, username, password, jdbcURL);
databaseReader.setDataSource(dataSource);
databaseReader.setRowMapper(mapper);
databaseReader.setSql(query);
return databaseReader;
}
protected DataSource getBasicDataSource(String jdbcDriver, String username, String password, String jdbcURL) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(jdbcURL);
return dataSource;
}
}
package com.bytesw.bytebot.etl.batch.factory.reader;
import org.springframework.batch.item.ItemReader;
import java.util.Map;
public interface ItemReaderFactory<T, E> {
ItemReader<T> createReader(E mapper, Map<String, Object> params);
}
package com.bytesw.bytebot.etl.batch.listener;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
@Log4j2
public class JobCompletionListener extends JobExecutionListenerSupport {
@Override
public void afterJob(JobExecution jobExecution) {
if (jobExecution.getStatus() == BatchStatus.COMPLETED) {
log.debug("BATCH JOB COMPLETED SUCCESSFULLY");
}
}
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.mapper;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class DynaBeanRowMapper<T> implements RowMapper<T> {
@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
DynaBean bean = new DynaBean();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String column = JdbcUtils.lookupColumnName(rsmd, i);
bean.putIfAbsent(column, JdbcUtils.getResultSetValue(rs, i));
}
return (T) bean;
}
}
package com.bytesw.bytebot.etl.batch.processor;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.batch.item.ItemProcessor;
public class ConvertToBeanProcessor implements ItemProcessor<DynaBean, DynaBean> {
private ObjectMapper mapper = new ObjectMapper();
@Override
public DynaBean process(DynaBean dynaBean) throws Exception {
Long id = new Long(String.valueOf(dynaBean.get("id")));
String data = (String) dynaBean.get("data");
String senderId = (String) dynaBean.get("sender_id");
EventBean eventBean = new EventBean();
eventBean.setId(id);
eventBean.setData(data);
eventBean.setSenderId(senderId);
dynaBean.put("bean", eventBean);
return dynaBean;
}
}
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.TenantBatchBean;
import com.bytesw.bytebot.etl.batch.factory.mapper.RowMapperFactory;
import com.bytesw.bytebot.etl.batch.factory.reader.DataBaseItemReaderFactory;
import com.bytesw.bytebot.etl.batch.processor.ConvertToBeanProcessor;
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.dao.DeleteDataSensibleControlRepository;
import com.bytesw.bytebot.etl.dao.DeleteDataSensibleLogRepository;
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.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.bytebot.service.BusinessParameterService;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor;
import net.javacrumbs.shedlock.core.LockingTaskExecutor;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.ZoneId;
import java.util.*;
import java.util.Calendar;
import java.util.concurrent.ScheduledFuture;
// Descomentar lo siguiente para que funcione
@Service
@Log4j2
@Component
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor="PT15M")
public class ScheduleService implements SchedulingConfigurer {
ScheduledTaskRegistrar scheduledTaskRegistrar;
Map<String, ScheduledFuture> futureMap = new HashMap<>();
@Autowired
@Qualifier("schedulerLockTaskScheduler")
TaskScheduler poolScheduler;
@Value("${application.byte-bot.batch.cron}")
private String cronExpression;
@Value("${application.byte-bot.batch.chunk:500}")
private int chunk;
@Value("${application.scheduler.cron}")
private String cronScheduler;
@Autowired
private JobExplorer jobExplorer;
@Autowired
@Qualifier("asyncJobLauncher")
JobLauncher asyncJobLauncher;
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
@Autowired
private DataBaseItemReaderFactory dataBaseItemReaderFactory;
@Autowired
private RowMapperFactory rowMapperFactory;
@Autowired
private JobExecutionListener listener;
@Autowired
private ProcessMessageService service;
@Autowired
private DeleteSensMessageService deleteSensMessageService;
@Autowired
private Gson gson;
@Autowired
private BatchProperties properties;
@Autowired
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;
@Autowired
private BusinessParameterService businessParameterService;
private boolean schedulerFlag = false;
private List<String> keys = new ArrayList<>();
private String tenant;
private ScheduledTaskRegistrar taskRegister;
private TimeZone timeZone;
@Value("${application.timezone.zone}")
private String parameter;
@Value("${application.timezone.default}")
private String zoneDefault;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
if (scheduledTaskRegistrar == null) {
scheduledTaskRegistrar = taskRegistrar;
}
if (taskRegistrar.getScheduler() == null) {
taskRegistrar.setScheduler(poolScheduler);
}
if (properties == null) {
throw new RuntimeException("batch properties not found");
}
if (properties.getTenants() == null) {
throw new RuntimeException("batch properties not found");
}
// identifier "prueba" Cambiar luego
properties.getTenants().stream().forEach(tenant -> {
ThreadLocalStorage.setTenantName(tenant.getId());
configureTask(tenant.getId(), "prueba", taskRegistrar);
});
//@TODO Falta añadir el modo multitenant
}
private void configureTask(String tenantIdentifier, String identifier, ScheduledTaskRegistrar taskRegistrar) {
tenant = tenantIdentifier;
taskRegister = taskRegistrar;
String zone = businessParameterService.getBusinessParameterForKey(parameter);
if (zone != null) {
timeZone = TimeZone.getTimeZone(zone);
} else {
timeZone = TimeZone.getTimeZone(zoneDefault);
}
/* 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());
if (!listSchedulerTask.isEmpty()) {
for (SchedulerTask schedulerTask : listSchedulerTask) {
Trigger triggerDelete = new CronTrigger(schedulerTask.getCronExpression(), timeZone);
String keyScheduler = String.format("%s-%s-%s", tenantIdentifier, schedulerTask.getCalendarID().trim(), schedulerTask.getId());
futureMap.put(keyScheduler, taskRegistrar.getScheduler()
.schedule(() -> processDeleteData(tenantIdentifier, taskRegistrar, schedulerTask), triggerDelete));
}
} else {
String keyScheduler = "refresh-schdeduler-task";
Trigger triggerDelete = new CronTrigger(cronScheduler, timeZone);
futureMap.put(keyScheduler, taskRegistrar.getScheduler()
.schedule(() -> syncSchedulerTask(), triggerDelete));
}
}
private void syncSchedulerTask() {
List<SchedulerTask> schedulerTasks = (List) schedulerTaskRepository.findAll();
for (SchedulerTask model: schedulerTasks) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
if (!futureMap.containsKey(key)) {
Trigger trigger = new CronTrigger(model.getCronExpression(), timeZone);
futureMap.put(key, taskRegister.getScheduler()
.schedule(() -> processDeleteData(tenant, taskRegister, model), trigger));
}
}
}
public void restartTask(SchedulerTask model) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
Trigger trigger = new CronTrigger(model.getCronExpression(), timeZone);
if (futureMap.containsKey(key)) {
cancelTask(model);
}
futureMap.put(key, taskRegister.getScheduler()
.schedule(() -> processDeleteData(tenant, taskRegister, model), trigger));
}
public void cancelTaskDelete(Long id) {
String keyDataSens = String.format("deleteSensible-%s-%s", tenant, id);
if (futureMap.containsKey(keyDataSens)) {
ScheduledFuture future = futureMap.get(keyDataSens);
future.cancel(true);
futureMap.remove(keyDataSens);
if (keys.contains(keyDataSens)) {
keys.remove(keyDataSens);
}
}
}
public void cancelTask(SchedulerTask model) {
String key = String.format("%s-%s-%s", tenant, model.getCalendarID().trim(), model.getId());
if (futureMap.containsKey(key)){
ScheduledFuture future = futureMap.get(key);
future.cancel(true);
futureMap.remove(key);
}
if (!keys.isEmpty()) {
for (String keyTask: keys) {
if (futureMap.containsKey(keyTask)) {
ScheduledFuture future = futureMap.get(keyTask);
future.cancel(true);
futureMap.remove(keyTask);
}
}
}
}
/*ETL eliminacion de data sensible*/
public void processDeleteData(String tenantIdentifier, ScheduledTaskRegistrar taskRegistrar, SchedulerTask schedulerTask) {
String zone = businessParameterService.getBusinessParameterForKey(parameter);
if (zone != null) {
timeZone = TimeZone.getTimeZone(zone);
} else {
timeZone = TimeZone.getTimeZone(zoneDefault);
}
Optional<SchedulerTask> schedulerTaskActual = schedulerTaskRepository.findById(schedulerTask.getId());
if (schedulerTaskActual.isPresent()) {
schedulerTask = schedulerTaskActual.get();
} else {
log.info(String.format("No se encuentra la tarea de %s regristrado.", schedulerTask.getDescription()));
cancelTask(schedulerTask);
return;
}
String calendarId = schedulerTask.getCalendarID().trim();
Optional<List<WeekScheduler>> dates = weekSchedulerRepository.findByCalendarId(calendarId);
OffsetTime actual = OffsetTime.now();
OffsetDateTime now = OffsetDateTime.now();
for(WeekScheduler weekScheduler: dates.get()) {
int day = now.getDayOfWeek().getValue() == 7? 1: (now.getDayOfWeek().getValue() + 1);
if(day != weekScheduler.getDayOfWeek()){
schedulerFlag = false;
continue;
}
if (actual.isBefore(weekScheduler.getTo()) && actual.isAfter(weekScheduler.getFrom())) {
Optional<List<CalendarExceptionFull>> calendarException = calendarExceptionFullRepository.findByCalendarId(calendarId);
if (calendarException.isPresent()){
schedulerFlag = validateException(calendarException.get());
} else {
schedulerFlag = true;
}
break;
} else {
schedulerFlag = false;
}
}
if (schedulerFlag) {
List<DeleteDataSensBean> deleteDataSensBeans = deleteDataSensJDBCRepository
.getListAgentChannel(AgentStatusEnum.DEPLOYED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
String keyDataSens = "";
for (DeleteDataSensBean data : deleteDataSensBeans) {
Trigger trigger = new CronTrigger(cronExpression, timeZone);
keyDataSens = String.format("deleteSensible-%s-%s", tenantIdentifier, data.getAgenId());
if (!futureMap.containsKey(keyDataSens)) {
keys.add(keyDataSens);
futureMap.put(keyDataSens, taskRegistrar.getScheduler()
.schedule(() -> scheduleCron(createJobDataSens(data), tenantIdentifier), trigger));
}
}
deleteDataSensBeans = deleteDataSensJDBCRepository.getListAgentChannel(AgentStatusEnum.DELETED.getName(), AgentParameterEnum.ACCESS_TWILIO.getName());
if (!deleteDataSensBeans.isEmpty()) {
for (DeleteDataSensBean data : deleteDataSensBeans) {
cancelTaskDelete(data.getAgenId());
}
}
} else {
keys.forEach(x -> {
if (futureMap.containsKey(x)) {
ScheduledFuture future = futureMap.get(x);
future.cancel(true);
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().equals(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 */
@Scheduled(cron = "${application.byte-bot.batch.cron}")
@SchedulerLock(name = "Dashboard-ETL", lockAtLeastFor = "PT40S", lockAtMostFor = "PT50S")
protected void createJob() {
List<Agent> agentDeployed = agentRepository.findByStatus(AgentStatusEnum.DEPLOYED);
if (!agentDeployed.isEmpty()) {
ThreadLocalStorage.setTenantName(tenant);
Job job = jobBuilderFactory.get("processJob")
.incrementer(new RunIdIncrementer()).listener(listener)
.flow(createStep(tenant)).end().build();
scheduleCron(job, tenant);
} else {
log.info("No hay agentes deployados.");
}
}
private Step createStep(String tenantIdentifier) {
ByteBotJPAWriter writer = new ByteBotJPAWriter();
writer.setService(service);
return stepBuilderFactory.get("processByteBotData").<DynaBean, DynaBean>chunk(chunk)
.reader(getReader(tenantIdentifier))
.processor(new ConvertToBeanProcessor())
.writer(writer).build();
}
private ItemReader getReader(String tenantIdentifier) {
if (properties == null) {
throw new RuntimeException("Properties not found");
}
Optional<TenantBatchBean> tenantFound = findTenant(tenantIdentifier);
if (!tenantFound.isPresent()) {
throw new RuntimeException("Properties not found");
}
Long id = eventHistoryRepository.maxEventId();
Map<String, Object> params = new HashMap<>();
params.putAll(tenantFound.get().getDatasource());
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(DeleteDataSensBean data) {
log.info("ETL de eliminacion");
data = deleteDataSensJDBCRepository.getAgentChannelByAgentID(AgentStatusEnum.DEPLOYED.getName(),
AgentParameterEnum.ACCESS_TWILIO.getName(), data.getAgenId());
ThreadLocalStorage.setTenantName(tenant);
if (data == null) {
return null;
}
return jobBuilderFactory.get( String.format("processDataSensible-%d",data.getAgenId()))
.incrementer(new RunIdIncrementer()).listener(listener)
.flow(createStepDataSens(tenant, 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;
Long differenceTime = 0L;
if (control != null) {
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(control.getDateDelete().toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate);
differenceTime = (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);
}
/* Métodos generales */
private Optional<TenantBatchBean> findTenant(String tenantId) {
return properties.getTenants().stream().filter(x -> x.getId().equals(tenantId)).findFirst();
}
private void scheduleCron(Job job, String tenantId) {
UUID traceID = UUID.randomUUID();
Map<String, JobParameter> maps = new HashMap<>();
maps.put("time", new JobParameter(System.currentTimeMillis()));
maps.put("uuid", new JobParameter(traceID.toString()));
maps.put("tenantId", new JobParameter(tenantId));
JobParameters parameters = new JobParameters(maps);
Set<JobExecution> jobExecutions = new HashSet<>();
try {
if (job != null) {
jobExecutions = jobExplorer.findRunningJobExecutions(job.getName());
String JobInfo = String.format("Jobs {} en Ejecución: {}", job.getName(), jobExecutions.size());
log.info(JobInfo);
if (jobExecutions.isEmpty()) {
asyncJobLauncher.run(job, parameters);
} else {
log.info("El Job " + job.getName() + " no se ejecutará porque hay jobs pendientes: " + jobExecutions.size());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.bytesw.bytebot.etl.batch.service;
import com.bytesw.bytebot.etl.batch.beans.DBConfig;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class SchedulerConfiguration {
@Bean
public LockProvider lockProvider(DataSource dataSource) {
DBConfig dbConfig = new DBConfig();
dataSource = dbConfig.dataSource();
return new JdbcTemplateLockProvider(dataSource);
}
}
\ No newline at end of file
package com.bytesw.bytebot.etl.batch.writer;
import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean;
import com.bytesw.bytebot.etl.beans.ProcessMessageResult;
import com.bytesw.bytebot.etl.services.ProcessMessageService;
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.util.List;
@Log4j2
public class ByteBotJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {
@Getter
@Setter
private ProcessMessageService service;
@Override
@Transactional
public void write(List<? extends DynaBean> list) throws Exception {
for (DynaBean dynaBean : list) {
EventBean eventBean = (EventBean) dynaBean.get("bean");
String json = (String) dynaBean.get("data");
ProcessMessageResult result = service.processMessage(json, eventBean.getSenderId());
log.debug(String.format("senderId: %s, processed: %s", eventBean.getSenderId(), result.isProcessed()));
service.saveHistory(eventBean.getId(), eventBean.getSenderId());
}
}
@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.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(), "$.telefono_despliegue");
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);
}
}
}
} else {
update_control = true;
}
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 lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
@Getter @Setter @ToString
public class EventBean implements Serializable {
private Long id;
private String data;
private String senderId;
}
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.beans;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class ProcessMessageResult {
private boolean processed = true;
private String message;
}
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
@Getter @Setter
public class SessionBean {
@Expose
private Long id;
@Expose
private Timestamp sessionDate;
@Expose
private Timestamp lastEventDate;
@Expose
private Timestamp responseDate;
@Expose
private Long userId;
@Expose
private Long channelId;
}
package com.bytesw.bytebot.etl.config;
import com.bytesw.bytebot.etl.batch.listener.JobCompletionListener;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
@Configuration
public class BatchConfig {
@Bean
public JobExecutionListener listener() {
return new JobCompletionListener();
}
@Bean("asyncJobLauncher")
public JobLauncher asyncJobLauncher(JobRepository jobRepository) {
final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
final SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
jobLauncher.setTaskExecutor(simpleAsyncTaskExecutor);
return jobLauncher;
}
}
package com.bytesw.bytebot.etl.config;
import com.bytesw.bytebot.etl.batch.beans.TenantBatchBean;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "batch")
public class BatchProperties {
@Getter @Setter
private List<TenantBatchBean> tenants;
}
package com.bytesw.bytebot.etl.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Map;
@ConfigurationProperties(prefix = "batch")
public class BatchPropertiesWithoutTenant {
@Getter @Setter
Map<String, String> datasource;
}
package com.bytesw.bytebot.etl.converter;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class MessageTypeConverter implements AttributeConverter<MessageTypeEnum, String> {
@Override
public String convertToDatabaseColumn(MessageTypeEnum agentTypeEnum) {
return (agentTypeEnum != null ? agentTypeEnum.getName() : null);
}
@Override
public MessageTypeEnum convertToEntityAttribute(String s) {
return MessageTypeEnum.fromString(s);
}
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Action;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface ActionRepository extends CrudRepository<Action, Long>, JpaSpecificationExecutor<Action> {
Optional<Action> findByIdentifier(String identifier);
}
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;
import com.bytesw.bytebot.etl.model.DeleteDataSensibleLog;
import org.springframework.data.repository.CrudRepository;
public interface DeleteDataSensibleLogRepository extends CrudRepository<DeleteDataSensibleLog, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.EventHistory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
public interface EventHistoryRepository extends CrudRepository<EventHistory, Long> {
@Query("SELECT MAX(e.eventId) FROM EventHistory e")
Long maxEventId();
}
package com.bytesw.bytebot.etl.dao;
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.query.Param;
import java.util.Optional;
public interface IntentRepository extends CrudRepository<Intent, Long> {
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.dao;
import com.bytesw.bytebot.etl.model.Message;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface MessageRepository extends CrudRepository<Message, Long> {
@Query("SELECT s from Message s WHERE s.sessionId = :sessionId")
Long findLastCorrelativeBySession(@Param("sessionId") Long sessionId);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Response;
import org.springframework.data.repository.CrudRepository;
public interface ResponseRepository extends CrudRepository<Response, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.SessionAction;
import org.springframework.data.repository.CrudRepository;
public interface SessionActionRepository extends CrudRepository<SessionAction, Long> {
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Session;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.time.OffsetDateTime;
public interface SessionBotRepository extends CrudRepository<Session, Long> {
@Query("UPDATE Session s set s.lastEventDate = :lastEventDate WHERE s.id = :id")
void updateLastEventDateBySession(@Param("id") Long id, @Param("lastEventDate") OffsetDateTime dateTime);
}
package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.User;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByIdentifier(String identifier);
}
package com.bytesw.bytebot.etl.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum EventTypeEnum {
USER("user"), BOT("bot"), ACTION("action"), START_SESSION("action_session_start");
private final String name;
private static final Map<String, EventTypeEnum> map = new HashMap<>();
static {
for (EventTypeEnum type : EventTypeEnum.values()) {
map.put(type.name, type);
}
}
EventTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static EventTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
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.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum MessageTypeEnum {
REJECTED("R"), ACCEPTED("A");
private final String name;
private static final Map<String, MessageTypeEnum> map = new HashMap<>();
static {
for (MessageTypeEnum type : MessageTypeEnum.values()) {
map.put(type.name, type);
}
}
MessageTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static MessageTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.etl.jdbc;
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.Map;
@Component
public class ETLMessageJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int getLastCorrelativeBySession(Long sessionId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLMessageMapper.getLastCorrelativeBySession", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.etl.jdbc;
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.Map;
@Component
public class ETLResponseJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int getLastCorrelativeBySession(Long sessionId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLResponseMapper.getLastCorrelativeBySession", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.etl.jdbc;
import com.bytesw.bytebot.etl.beans.SessionBean;
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.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
@Component
public class ETLSessionBotJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public SessionBean getLastSessionByUser(Long userId) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("userId", userId);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.getLastSessionByUser", params);
} finally {
session.close();
}
}
public void updateLastEventDate(Long sessionID, OffsetDateTime lastEventDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sessionId", sessionID);
params.put("lastEventDate", lastEventDate);
session.update("com.bytesw.bytebot.dao.jdbc.ETLSessionMapper.updateLastEventDate", params);
} finally {
session.close();
}
}
}
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_ACTION")
@NamedQuery(name = "Action.findByPK", query = "Select p from Action p where p.id = ?1")
public class Action {
@Id
@Column(name = "action_id")
@SequenceGenerator(name = "AVB_ACTION_GENERATOR", sequenceName = "AVB_ACTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_ACTION_GENERATOR")
private Long id;
@Column(name = "action_ident")
private String identifier;
}
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")
@SequenceGenerator(name = "AVB_DELETE_MSG_SENS_CONTROL_GENERATOR", sequenceName = "AVB_DELETE_SENS_MSG_CONTROL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,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")
@SequenceGenerator(name = "AVB_DELETE_MSG_SENS_LOG_GENERATOR", sequenceName = "AVB_DELETE_SENS_MSG_LOG_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,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.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_event_history")
@NamedQuery(name = "EventHistory.findByPK", query = "Select p from EventHistory p where p.id = ?1")
public class EventHistory {
@Id
@Column(name = "evenh_id")
@SequenceGenerator(name = "AVB_EVENT_HISTORY_GENERATOR", sequenceName = "AVB_EVENT_HISTORY_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_EVENT_HISTORY_GENERATOR")
private Long id;
@Column(name = "evenh_sendid")
private String senderId;
@Column(name = "evenh_evid")
private Long eventId;
@Column(name = "evenh_date")
private OffsetDateTime 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="avb_goal")
@NamedQuery(name = "Goal.findByPK", query = "Select p from Goal p where p.id = ?1")
public class Goal {
@Id
@Column(name = "goal_id")
@SequenceGenerator(name = "AVB_GOAL_GENERATOR", sequenceName = "AVB_GOAL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_GOAL_GENERATOR")
private Long id;
@Column(name = "goal_ident")
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")
@SequenceGenerator(name = "AVB_GOALFORACTIONS_GENERATOR", sequenceName = "AVB_GOALFORACTIONS_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_GOALFORACTIONS_GENERATOR")
private Long id;
@Column(name = "goal_id")
private Long goalId;
@Column(name = "action_id")
private Long actionId;
}
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_intent")
@NamedQuery(name = "Intent.findByPK", query = "Select p from Intent p where p.id = ?1")
public class Intent {
@Id
@Column(name = "inten_id")
@SequenceGenerator(name = "AVB_INTENT_DASHBOARD_GENERATOR", sequenceName = "AVB_INTENT_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_INTENT_DASHBOARD_GENERATOR")
private Long id;
@Column(name = "inten_ident")
private String identifier;
@Column(name = "intent_is_sensible")
private String sensible;
@Column(name = "agen_id")
private Long agenId;
}
package com.bytesw.bytebot.etl.model;
import com.bytesw.bytebot.etl.converter.MessageTypeConverter;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString @Builder
@Table(name="avb_message")
@NamedQuery(name = "Message.findByPK", query = "Select p from Message p where p.id = ?1")
public class Message {
@Id
@Column(name = "messa_id")
@SequenceGenerator(name = "AVB_MESSAGE_GENERATOR", sequenceName = "AVB_MESSAGE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_MESSAGE_GENERATOR")
private Long id;
@Column(name = "session_id")
private Long sessionId;
@Column(name = "messa_date")
private OffsetDateTime date;
@Column(name = "messa_cont")
private String content;
@Column(name = "messa_corre")
private int correlative;
@Column(name = "messa_prob")
private BigDecimal probability;
@Convert(converter = MessageTypeConverter.class)
@Column(name = "messa_type")
private MessageTypeEnum type;
@Column(name = "inten_id")
private Long intentId;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_response")
@NamedQuery(name = "Response.findByPK", query = "Select p from Response p where p.id = ?1")
public class Response {
@Id
@Column(name = "respo_id")
@SequenceGenerator(name = "AVB_RESPONSE_GENERATOR", sequenceName = "AVB_RESPONSE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_RESPONSE_GENERATOR")
private Long id;
@Column(name = "respo_date")
private OffsetDateTime date;
@Column(name = "respo_cont")
private String content;
@Column(name = "respo_corr")
private int correlative;
@Column(name = "session_id")
private Long sessionId;
}
package com.bytesw.bytebot.etl.model;
import com.bytesw.bytebot.model.Channel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_session")
@NamedQuery(name = "Session.findByPK", query = "Select p from Session p where p.id = ?1")
public class Session {
@Id
@Column(name = "session_id")
@SequenceGenerator(name = "AVB_SESSION_GENERATOR", sequenceName = "AVB_SESSION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_SESSION_GENERATOR")
private Long id;
@Column(name = "session_date", nullable = false)
private OffsetDateTime sessionDate;
@Column(name = "session_ledat", nullable = false)
private OffsetDateTime lastEventDate;
@Column(name = "session_frdat", nullable = false)
private OffsetDateTime responseDate;
@ManyToOne
@JoinColumn(name = "chan_id", referencedColumnName = "chan_id")
private Channel channel;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", referencedColumnName = "user_id")
private User user;
}
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.time.OffsetDateTime;
@Cacheable(false)
@Entity
@Getter @Setter @ToString
@Table(name="avb_action_session")
@NamedQuery(name = "SessionAction.findByPK", query = "Select p from SessionAction p where p.id = ?1")
public class SessionAction {
@Id
@Column(name = "asess_id")
@SequenceGenerator(name = "AVB_ACTION_SESSION_GENERATOR", sequenceName = "AVB_ACTION_SESSION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_ACTION_SESSION_GENERATOR")
private Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "action_id", referencedColumnName = "action_id")
private Action action;
@Column(name = "asess_date")
private OffsetDateTime date;
@Column(name = "session_id")
private Long sessionId;
}
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_user")
@NamedQuery(name = "User.findByPK", query = "Select p from User p where p.id = ?1")
public class User {
@Id
@Column(name = "user_id")
@SequenceGenerator(name = "AVB_USER_GENERATOR", sequenceName = "AVB_USER_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "AVB_USER_GENERATOR")
private Long id;
@Column(name = "user_ident")
private String identifier;
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
import com.bytesw.bytebot.etl.dao.SessionActionRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.Action;
import com.bytesw.bytebot.etl.model.SessionAction;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.util.Optional;
@Service
@Transactional
public class ActionMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private ETLSessionBotJDBCRepository ETLSessionBotJDBCRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ActionRepository actionRepository;
@Autowired
private SessionActionRepository sessionActionRepository;
@Value("${application.etl.action.user-field:sender_id}")
private String userIdentifierFieldName;
@Value("${application.etl.action.event-field:name}")
private String eventFieldName;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
this.fields.put(ACTION_FIELD_NAME, "$.name");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = ETLSessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
String actionIdentifier = (String) JsonUtils.getFieldFromJson(json, this.fields.get(ACTION_FIELD_NAME));
if (session != null && actionIdentifier != null && !actionIdentifier.isEmpty()) {
Optional<Action> actionFound = actionRepository.findByIdentifier(actionIdentifier);
if (!actionFound.isPresent()) {
return false;
}
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
SessionAction sessionAction = new SessionAction();
sessionAction.setAction(actionFound.get());
sessionAction.setSessionId(session.getId());
sessionAction.setDate(getOffsetDateTimeFromTimestampPython(timestamp));
sessionActionRepository.save(sessionAction);
updateEventDate(session.getId(), sessionAction.getDate());
return true;
}
}
return false;
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.beans.SessionBean;
import com.bytesw.bytebot.etl.dao.ResponseRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.jdbc.ETLResponseJDBCRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
import com.bytesw.bytebot.etl.model.Response;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.util.Optional;
@Service
@Transactional
public class BotMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private UserRepository userRepository;
@Autowired
private ETLSessionBotJDBCRepository ETLSessionBotJDBCRepository;
@Autowired
private ETLResponseJDBCRepository responseJDBCRepository;
@Autowired
private ResponseRepository responseRepository;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(CONTENT_FIELD_NAME, "$.text");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = ETLSessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
if (session != null) {
int correlative = responseJDBCRepository.getLastCorrelativeBySession(session.getId());
String content = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CONTENT_FIELD_NAME));
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
if (content != null && timestamp != null) {
Response response = new Response();
response.setSessionId(session.getId());
response.setCorrelative(correlative++);
response.setContent(content);
response.setDate(getOffsetDateTimeFromTimestampPython(timestamp));
responseRepository.save(response);
updateEventDate(session.getId(), response.getDate());
updateFirstResponse(session, response.getDate());
return true;
}
}
}
return false;
}
private void updateFirstResponse(SessionBean session, OffsetDateTime date) {
if (session.getResponseDate() == null) {
Optional<Session> sessionFond = sessionBotRepository.findById(session.getId());
if (sessionFond.isPresent()) {
Session sessionDB = sessionFond.get();
sessionDB.setResponseDate(date);
sessionBotRepository.save(sessionDB);
}
}
}
}
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());
}
}
}
package com.bytesw.bytebot.etl.services;
@FunctionalInterface
public interface MessageProcessed {
boolean process(String json, String senderId);
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.dao.SessionBotRepository;
import com.bytesw.bytebot.etl.model.Session;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Log4j2
public abstract class MessageProcessedSupport {
protected static final String SENDER_ID_FIELD_NAME = "senderId";
protected static final String CONTENT_FIELD_NAME = "content";
protected static final String CONFIDENCE_FIELD_NAME = "confidence";
protected static final String CHANNEL_FIELD_NAME = "channel";
protected static final String TIMESTAMP_FIELD_NAME = "timestamp";
protected static final String ACTION_FIELD_NAME = "actionName";
protected static final String INTENT_NAME = "intentName";
protected Map<String, String> fields = new HashMap<>();
@Autowired
protected SessionBotRepository sessionBotRepository;
protected static final String PYTHON_TIMESTAMP_FORMAT = "^\\d*\\.?\\d*$";
protected static final Pattern pattern = Pattern.compile(PYTHON_TIMESTAMP_FORMAT);
protected OffsetDateTime getOffsetDateTimeFromTimestampPython(Object objectTimestamp) {
BigDecimal dateDecimal;
if (objectTimestamp instanceof Double) {
dateDecimal = new BigDecimal((Double) objectTimestamp);
} else {
if (!isValidTimestampFormat(String.valueOf(objectTimestamp), pattern)) {
return null;
}
dateDecimal = new BigDecimal(String.valueOf(objectTimestamp));
}
Long timestamp = (long) (dateDecimal.doubleValue() * 1000);
if (String.valueOf(timestamp).length() < 13) {
int numberOfZero = 13 - String.valueOf(timestamp).length();
for (int i = 0; i < numberOfZero; i++) {
timestamp = timestamp * 10;
}
}
OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
return date;
}
protected boolean isValidTimestampFormat(String text, Pattern pattern) {
Matcher matcher = pattern.matcher(text);
boolean matches = matcher.matches();
return matches;
}
protected void updateEventDate(Long sessionId, OffsetDateTime date) {
Optional<Session> sessionFond = sessionBotRepository.findById(sessionId);
if (sessionFond.isPresent()) {
Session session = sessionFond.get();
session.setLastEventDate(date);
sessionBotRepository.save(session);
}
}
}
package com.bytesw.bytebot.etl.services;
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.enums.EventTypeEnum;
import com.bytesw.bytebot.etl.model.EventHistory;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.xdf.config.AppContextManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
@Log4j2
@Service
public class ProcessMessageService {
@Autowired
private EventHistoryRepository eventHistoryRepository;
@Autowired
private DeleteDataSensibleControlRepository deleteDataSensibleControlRepository;
public void saveHistory(Long id, String senderId) {
EventHistory eventHistory = new EventHistory();
eventHistory.setDate(OffsetDateTime.now());
eventHistory.setEventId(id);
eventHistory.setSenderId(senderId);
eventHistoryRepository.save(eventHistory);
}
public ProcessMessageResult processMessage(String json, String senderId) throws Exception {
ProcessMessageResult result = new ProcessMessageResult();
MessageProcessed messageProcessed = detectType(json);
if (messageProcessed == null) {
result.setProcessed(false);
result.setMessage("Event type not support");
return result;
}
result.setProcessed(messageProcessed.process(json, senderId));
return result;
}
private MessageProcessed detectType(String json) {
MessageProcessed messageProcessed = null;
EventTypeEnum type;
try {
String event = (String) JsonUtils.getFieldFromJson(json, "$.event");
if (AppContextManager.getAppContext() != null && event != null) {
String name = (String) JsonUtils.getFieldFromJson(json, "$.name");
type = EventTypeEnum.fromString(event);
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)) {
type = EventTypeEnum.START_SESSION;
}
messageProcessed = (MessageProcessed) AppContextManager.getAppContext().getBean(getMessageProcessedName(type));
}
}
} catch (Exception e) {
log.debug(e);
}
return messageProcessed;
}
private String getMessageProcessedName(EventTypeEnum type) {
String[] words = type.toString().toLowerCase().split("_");
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String word : words) {
if (isFirst) {
sb.append(word);
isFirst = false;
} else {
sb.append(word.substring(0, 1).toUpperCase() + word.substring(1));
}
}
sb.append("MessageProcessed");
return sb.toString();
}
}
package com.bytesw.bytebot.etl.services;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.model.Session;
import com.bytesw.bytebot.etl.model.User;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
@Service
@Transactional
public class StartSessionMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private UserRepository userRepository;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
User user;
if (!userFound.isPresent()) {
user = new User();
user.setIdentifier(senderId);
user = userRepository.save(user);
} else {
user = userFound.get();
}
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_FIELD_NAME));
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);
if (sessionDate != null) {
Session session = new Session();
session.setSessionDate(sessionDate);
session.setUser(user);
session.setLastEventDate(sessionDate);
sessionBotRepository.save(session);
return true;
}
}
}
return false;
}
}
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.dao.IntentRepository;
import com.bytesw.bytebot.etl.dao.MessageRepository;
import com.bytesw.bytebot.etl.dao.UserRepository;
import com.bytesw.bytebot.etl.enums.MessageTypeEnum;
import com.bytesw.bytebot.etl.jdbc.ETLMessageJDBCRepository;
import com.bytesw.bytebot.etl.jdbc.ETLSessionBotJDBCRepository;
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.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.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Log4j2
@Service
@Transactional
public class UserMessageProcessed extends MessageProcessedSupport implements MessageProcessed {
@Autowired
private ETLSessionBotJDBCRepository sessionBotJDBCRepository;
@Autowired
private ETLMessageJDBCRepository messageJDBCRepository;
@Autowired
private ChannelRepository chanelRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private MessageRepository messageRepository;
@Autowired
private IntentRepository intentRepository;
@Autowired
private DeleteDataSensJDBCRepository deleteDataSensJDBCRepository;
@Value("${application.etl.text-user.threshold:0.5}")
private BigDecimal threshold;
@PostConstruct
private void init() {
this.fields.put(SENDER_ID_FIELD_NAME, "$.sender_id");
this.fields.put(CONFIDENCE_FIELD_NAME, "$.parse_data.intent.confidence");
this.fields.put(CONTENT_FIELD_NAME, "$.text");
this.fields.put(CHANNEL_FIELD_NAME, "$.input_channel");
this.fields.put(TIMESTAMP_FIELD_NAME, "$.timestamp");
this.fields.put(INTENT_NAME, "$.parse_data.intent.name");
}
@Override
public boolean process(String json, String oldSenderId) {
String senderId = oldSenderId != null ? oldSenderId : (String) JsonUtils.getFieldFromJson(json, this.fields.get(SENDER_ID_FIELD_NAME));
if (senderId != null) {
Optional<User> userFound = userRepository.findByIdentifier(senderId);
if (!userFound.isPresent()) {
return false;
}
SessionBean session = sessionBotJDBCRepository.getLastSessionByUser(userFound.get().getId());
if (session != null) {
/* ID del agente */
Long agentId = identifierAgent(json);
if (agentId >= 1) {
Message message = cloneMessage(json, session.getId(), agentId);
if (message != null) {
int correlative = messageJDBCRepository.getLastCorrelativeBySession(message.getSessionId());
correlative++;
message.setCorrelative(correlative);
messageRepository.save(message);
String channel = (String) JsonUtils.getFieldFromJson(json, this.fields.get(CHANNEL_FIELD_NAME));
updateSession(session.getId(), message.getDate(), channel);
return true;
}
}
}
}
return false;
}
private void updateSession(Long sessionId, OffsetDateTime date, String channelIdentifier) {
Optional<Session> sessionFond = sessionBotRepository.findById(sessionId);
if (sessionFond.isPresent()) {
Session session = sessionFond.get();
session.setLastEventDate(date);
if (channelIdentifier != null && session.getChannel() == null) {
Optional<Channel> channelFound = chanelRepository.findByName(channelIdentifier);
if (channelFound.isPresent()) {
session.setChannel(channelFound.get());
}
}
sessionBotRepository.save(session);
}
}
private Message cloneMessage(String json, Long sessionId, Long agentId) {
Double timestamp = (Double) JsonUtils.getFieldFromJson(json, this.fields.get(TIMESTAMP_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));
OffsetDateTime messageDate = getOffsetDateTimeFromTimestampPython(timestamp);
BigDecimal probability = null;
if (confidence instanceof Double) {
probability = new BigDecimal((Double) confidence);
} else if (confidence instanceof BigDecimal) {
probability = (BigDecimal) confidence;
}
if (messageDate == null || probability == null) {
return null;
}
Message message = Message.builder()
.content(content)
.sessionId(sessionId)
.date(messageDate)
.probability(new BigDecimal(String.valueOf(probability)))
.type((probability.compareTo(threshold) >= 0) ? MessageTypeEnum.ACCEPTED : MessageTypeEnum.REJECTED)
//.correlative()
.build();
if (MessageTypeEnum.ACCEPTED.equals(message.getType())) {
String intentName = (String) JsonUtils.getFieldFromJson(json, this.fields.get(INTENT_NAME));
Optional<Intent> optionalIntent = intentRepository.findIntenNameById(intentName, agentId);
if (optionalIntent.isPresent()) {
message.setIntentId(optionalIntent.get().getId());
}
}
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(), "$.telefono_despliegue");
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.etl.utils;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class JsonUtils {
public static Object getFieldFromJson(String json, String jsonPath) {
Object result = null;
try {
result = JsonPath.parse(json)
.read(jsonPath);
} catch (PathNotFoundException e) {
log.debug(e);
} catch (Exception e) {
log.error(e);
}
return result;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class FileValidationResponse {
private Long id;
private String uuid;
private String fileName;
private String status;
private String user;
private String uploadDate;
private String message;
private FileValidationResult fileValidationResult;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class FileValidationResult {
private ValidationStatusEnum status;
private Map<String, String> headersErrorMap;
private Map<Integer, Object> recordsErrorMap;
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.http.enums;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
public enum ValidationStatusEnum {
OK("OK"),
ERROR("ERROR"),
DATA_INCOMPLETE ("DI"),
FORMAT_INCORRECT("FI"),
INCOMPATIBLE_EXTENSION("IE"),
HEADER_ERROR ("HE"),
CONTENT_ERROR("CE");
private final String name;
private static final Map<String, ValidationStatusEnum> map = new HashMap<>();
static {
for (ValidationStatusEnum type : ValidationStatusEnum.values()) {
map.put(type.name, type);
}
}
ValidationStatusEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static ValidationStatusEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
package com.bytesw.bytebot.jdbc; //package com.bytesw.bytebot.jdbc;
//
import com.bytesw.bytebot.bean.ActionSummaryByGoalBean; //import com.bytesw.bytebot.bean.ActionSummaryByGoalBean;
import org.apache.ibatis.session.SqlSession; //import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; //import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; //import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
//
import java.time.OffsetDateTime; //import java.time.OffsetDateTime;
import java.util.HashMap; //import java.util.HashMap;
import java.util.List; //import java.util.List;
import java.util.Map; //import java.util.Map;
//
@Component //@Component
public class ActionJDBCRepository { //public class ActionJDBCRepository {
@Autowired // @Autowired
@Qualifier("sqlSessionFactory") // @Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory; // private SqlSessionFactory sqlSessionFactory;
//
public List<ActionSummaryByGoalBean> getSummaryByGoals(OffsetDateTime startDate, OffsetDateTime endDate) { // public List<ActionSummaryByGoalBean> getSummaryByGoals(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession(); // SqlSession session = sqlSessionFactory.openSession();
//
try { // try {
Map<String, Object> params = new HashMap<>(); // Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate); // params.put("startDate", startDate);
params.put("endDate", endDate); // params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.ActionMapper.getSummaryActionsByGoal", params); // return session.selectList("com.bytesw.bytebot.dao.jdbc.ActionMapper.getSummaryActionsByGoal", params);
} finally { // } finally {
session.close(); // session.close();
} // }
} // }
} //}
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();
}
}
}
package com.bytesw.bytebot.jdbc;
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 com.bytesw.bytebot.bean.SessionByClientBean;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
@Component
public class BotSessionJDCBRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.countSessionsInRange", params);
} finally {
session.close();
}
}
public Timestamp getLastDateInRage(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.getLastDateInRange", params);
} finally {
session.close();
}
}
public Double getAvgSessionByCustomerInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.avgSessionsByCustomerInRange", params);
} finally {
session.close();
}
}
public Object getAvgFirstResponseTime(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.SessionMapper.avgFirstResponseTime", params);
} finally {
session.close();
}
}
}
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 DeleteDataSensBean getAgentChannelByAgentID(String status, String channel, Long id){
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("status", status);
params.put("channel", channel);
params.put("agentId", id);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ETLDataSensibleMapper.getAgentChannelByAgentId", 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();
}
}
}
package com.bytesw.bytebot.jdbc;
import com.bytesw.bytebot.bean.MessageByIntentBean;
import com.bytesw.bytebot.bean.SummaryMessageByIntentBean;
import com.bytesw.bytebot.bean.SummaryMessageBySentenceBean;
import com.bytesw.xdf.sql.beans.Pagination;
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.math.BigInteger;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class MessageJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessagesInRange", params);
} finally {
session.close();
}
}
public int countMessageInRangeHour(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessagesInRangeForHour", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getSummaryByIntentAndSentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("initLimit", pagination.getCurrentPage() * pagination.getItemsPerPage());
params.put("itemsForPage", pagination.getItemsPerPage());
if (pagination.getSortFields() != null && pagination.getSortFields().length > 0) {
params.put("columnSort", pagination.getSortFields()[0].getField());
params.put("directionSort", pagination.getSortFields()[0].getDirection().toUpperCase());
} else {
params.put("columnSort", "count");
params.put("directionSort", "DESC");
}
completeDates(params, pagination.getFilterExpression());
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntentAndSentence", params);
} finally {
session.close();
}
}
public List<SummaryMessageByIntentBean> getSummaryByIntent(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryByIntent", params);
} finally {
session.close();
}
}
/**
* Metodo que consulta el total de mensajes con intent asociado
* @return
*/
public int countByIntentAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countByIntentAndRange", params);
} finally {
session.close();
}
}
/**
* Metodo que consulta el total de frases sin intent asociado
* @return
*/
public int countBySentencesAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countBySentencesAndRange", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getSummaryBySentence(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
params.put("initLimit", 0);
params.put("itemsForPage", 4);
params.put("columnSort", "count");
params.put("directionSort", "DESC");
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryBySentence", params);
} finally {
session.close();
}
}
public List<SummaryMessageBySentenceBean> getMessageBySentencePage(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("initLimit", pagination.getCurrentPage() * pagination.getItemsPerPage());
params.put("itemsForPage", pagination.getItemsPerPage());
if (pagination.getSortFields() != null && pagination.getSortFields().length > 0) {
params.put("columnSort", pagination.getSortFields()[0].getField());
params.put("directionSort", pagination.getSortFields()[0].getDirection().toUpperCase());
} else {
params.put("columnSort", "count");
params.put("directionSort", "DESC");
}
completeDates(params, pagination.getFilterExpression());
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.getSummaryBySentence", params);
} finally {
session.close();
}
}
public int countSummaryBySentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
completeDates(params, pagination.getFilterExpression());
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countSummaryBySentence", params);
} finally {
session.close();
}
}
/**
* obtiene el promedio intenciones por cliente y rango de fechas
* @return
*/
public Double avgIntentsByCustomerAndRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.avgIntentsByCustomerAndRange", params);
} finally {
session.close();
}
}
/**
* Obtiene la cantidad por cada intención en un periodo de tiempo
* @return
*/
public List<MessageByIntentBean> countMessageByIntent(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectList("com.bytesw.bytebot.dao.jdbc.MessageMapper.countMessageByIntent", params);
} finally {
session.close();
}
}
public int countSummaryByIntentAndSentence(Pagination<SummaryMessageBySentenceBean> pagination) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
completeDates(params, pagination.getFilterExpression());
return session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countSummaryByIntentAndSentence", params);
} finally {
session.close();
}
}
public int countCustomersBySentence(String sentence) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("sentence", sentence);
Object result = session.selectOne("com.bytesw.bytebot.dao.jdbc.MessageMapper.countCustomersBySentence", params);
if (result instanceof Double) {
return ((Double) result).intValue();
} else if (result instanceof Integer) {
return (Integer) result;
}
return 0;
} finally {
session.close();
}
}
private void completeDates(Map<String, Object> params, String filterString) {
if (filterString == null || filterString.isEmpty()) {
return;
}
String[] filters = filterString.split("&&");
if (filters != null) {
for (String filter : filters) {
String[] filterValue = filter.split("=");
params.put(filterValue[0], OffsetDateTime.ofInstant(Instant.ofEpochMilli(new Long(filterValue[1])), ZoneId.systemDefault()));
}
}
}
}
package com.bytesw.bytebot.jdbc;
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.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;
@Component
public class ResponseJDBCRepository {
@Autowired
@Qualifier("sqlSessionFactory")
private SqlSessionFactory sqlSessionFactory;
public int countSessionInRange(OffsetDateTime startDate, OffsetDateTime endDate) {
SqlSession session = sqlSessionFactory.openSession();
try {
Map<String, Object> params = new HashMap<>();
params.put("startDate", startDate);
params.put("endDate", endDate);
return session.selectOne("com.bytesw.bytebot.dao.jdbc.ResponseMapper.countMessagesInRange", params);
} finally {
session.close();
}
}
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.AgentStatusConverter;
import com.bytesw.bytebot.model.converters.AgentTypeConverter;
import com.bytesw.bytebot.model.converters.LanguageConverter;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import lombok.*;
import org.hibernate.annotations.Type;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Audited
@Entity
@Getter @Setter @EqualsAndHashCode(of = "id")
@NoArgsConstructor
@Table(name = "avb_agent")
@NamedQuery(name = "Agent.findByPK", query = "Select u from Agent u where u.id = ?1")
public class Agent implements Serializable {
@Id
@Column(name = "agen_id")
@SequenceGenerator(name = "AVB_AGENT_GENERATOR", sequenceName = "AVB_AGENT_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_AGENT_GENERATOR")
private Long id;
@Column(name = "agen_iden")
private String name;
@Column(name = "agen_descr")
private String description;
@Column(name = "agen_vers")
private String version;
@Column(name = "agen_lang")
@Convert(converter = LanguageConverter.class)
private LanguageEnum language;
@Column(name = "agen_tzone")
private String timezone;
@Column(name = "agen_delete_sensible_period")
private int period;
@Lob
@Type(type = "org.hibernate.type.TextType")
@Basic(fetch = FetchType.LAZY)
@Column(name = "agen_avat")
private String avatar;
@ManyToOne
@JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
private Country country;
@Column(name = "agen_state")
@Convert(converter = AgentStatusConverter.class)
private AgentStatusEnum status;
@Column(name = "agen_type")
@Convert(converter = AgentTypeConverter.class)
private AgentTypeEnum type;
@OneToMany(mappedBy = "agent")
private List<DeploymentChannel> deploymentChannels;
@OneToMany(mappedBy = "agent")
private List<FrequentQuestion> frequentQuestions;
}
package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name = "airports")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class Airport implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="airport_code")
private String airportCode;
@Column(name="airport_name")
private String airportName;
@Column(name="airport_location")
private String airportLocation;
@Column(name="other_details")
private String details;
@OneToMany(mappedBy = "codeAirportOrigin", cascade = CascadeType.ALL)
private List<FlightSchedule> flights;
@OneToMany(mappedBy = "codeAirportDestination", cascade = CascadeType.ALL)
private List<FlightSchedule> flightsDes;
@OneToMany(mappedBy = "codeAirportOrigin", cascade = CascadeType.ALL)
private List<Leg> legs;
@OneToMany(mappedBy = "codeAirportDestination", cascade = CascadeType.ALL)
private List<Leg> legsDes;
}
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 lombok.*;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Getter
@Setter
@ToString
@Table(name = "avb_bcd_control")
@NamedQuery(name = "BdcControl.findByPK", query = "Select u from BdcControl u where u.id = ?1")
public class BdcControl implements Serializable {
@Id
@Column(name = "bcd_id")
@SequenceGenerator(name = "AVB_BCD_CONTROL_GENERATOR", sequenceName = "AVB_BCD_CONTROL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BCD_CONTROL_GENERATOR")
private Long id;
@Column(name = "bcd_uuid")
private String uuid;
@Column(name = "bcd_file")
private String fileName;
@Column(name = "bcd_file_id")
private Long fileId;
@Column(name = "bcd_status")
private String status;
@Column(name = "bcd_user")
private String user;
@Column(name = "bcd_date")
private String date;
}
package com.bytesw.bytebot.model; package com.bytesw.bytebot.model;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import javax.persistence.*; import java.io.Serializable;
import java.io.Serializable;
@Entity
@Audited @Table(name = "booking_agents")
@Entity @Getter
@Table(name = "avb_process_etl") @Setter
@NamedQuery(name = "ProcessETL.findByPK", query = "Select u from ProcessETL u where u.id = ?1") @EqualsAndHashCode
@Getter @ToString
@Setter public class BookingAgent implements Serializable {
@EqualsAndHashCode
@ToString(exclude = "id") @Id
public class ProcessETL implements Serializable { @GeneratedValue( strategy = GenerationType.IDENTITY)
@Id private Long id;
@Column(name = "etl_id")
private int id; @Column(name = "agent_name")
private String agentName;
@Version
@Column(name = "etl_version") @Column(name = "agent_lastname")
@Basic(optional = false) private String agentLastname;
private long version;
@Column(name = "agent_dni")
@Column(name = "etl_name", nullable = false) private String dni;
private String name;
} @Column(name = "agent_phone")
private String agentPhone;
@Column(name = "agent_details")
private String agentDetails;
}
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_GEN", sequenceName = "AVB_BUSINESS_PARAMETER_CONFIG_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_BUSINESS_PARAMETER_CONFIG_GEN")
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;
@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;
@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
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.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Table(name = "AVB_CHANNEL")
@Getter @Setter @ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class Channel {
@Id
@Column(name = "CHAN_ID")
@SequenceGenerator(name = "AVB_CHANNEL_GENERATOR", sequenceName = "AVB_CHANNEL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CHANNEL_GENERATOR")
private Long id;
@Column(name = "CHAN_IDEN")
private String name;
@Column(name = "CHAN_IMAG")
private String image;
@OneToMany(mappedBy = "channel")
private List<ChannelParam> parameters;
@Column(name = "CHAN_TITLE")
private String suggestTitle;
@Column(name = "CHAN_DETAIL")
private String suggestDetail;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.BooleanToStringConverter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Table(name = "AVB_CHANNEL_PARAM")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class ChannelParam {
@Id
@Column(name = "CHPA_ID")
@SequenceGenerator(name = "AVB_CHANNEL_PARAM_GENERATOR", sequenceName = "AVB_CHANNEL_PARAM_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_CHANNEL_PARAM_GENERATOR")
private Long id;
@Column(name = "CHPA_IDEN")
private String name;
@ManyToOne
@JoinColumn(name = "CHAN_ID",referencedColumnName = "CHAN_ID")
private Channel channel;
@Column(name = "CHPA_ORDER")
private Integer order;
@Column(name = "CHPA_REQU")
@Convert(converter = BooleanToStringConverter.class)
private boolean required;
@Column(name = "CHPA_LABEL")
private String label;
@Column(name = "CHPA_TRADU")
private String traductions;
@Column(name = "CHPA_TYPE")
private String type;
@Column(name = "CHPA_MAXLE")
private Integer maxlength;
@Column(name = "CHPA_REGEX")
private String regex;
}
package com.bytesw.bytebot.model;
import lombok.*;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.List;
@Audited
@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@Table(name = "avb_country")
@NamedQuery(name = "Country.findByPK", query = "Select u from Country u where u.id = ?1")
public class Country {
@Id
@Column(name = "coun_id")
@SequenceGenerator(name = "AVB_COUNTRY_GENERATOR", sequenceName = "AVB_COUNTRY_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_COUNTRY_GENERATOR")
private Long id;
@Column(name = "coun_name", nullable = false)
private String name;
@OneToMany(mappedBy = "country")
private List<Timezone> timezones;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.StatusConverter;
import com.bytesw.bytebot.model.enums.StatusEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.List;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Table(name = "AVB_DEPLOYMENT_CHANNEL")
@Getter
@Setter
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class DeploymentChannel {
@Id
@Column(name = "DCHA_ID")
@SequenceGenerator(name = "AVB_DEPLOYMENT_CHANNEL_GENERATOR", sequenceName = "AVB_DEPLOYMENT_CHANNEL_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_DEPLOYMENT_CHANNEL_GENERATOR")
private Long id;
@Column(name = "DCHA_NAME")
private String name;
@ManyToOne
@JoinColumn(name = "AGEN_ID", referencedColumnName = "AGEN_ID")
private Agent agent;
@Column(name = "DCHA_STATE")
@Convert(converter = StatusConverter.class)
private StatusEnum status;
@ManyToOne
@JoinColumn(name = "CHAN_ID", referencedColumnName = "CHAN_ID")
private Channel channel;
@OneToMany(mappedBy = "deploymentChannel")
private List<DeploymentChannelParamValue> parameters;
}
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.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Table(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = {"id"}, callSuper = false)
public class DeploymentChannelParamValue {
@Id
@Column(name = "CHPV_ID")
@SequenceGenerator(name = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR", sequenceName = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_DEPLOYMENT_CHANNEL_PARAM_VALUE_GENERATOR")
private Long id;
@ManyToOne
@JoinColumn(name = "CHPA_ID", referencedColumnName = "CHPA_ID")
private ChannelParam parameter;
@ManyToOne
@JoinColumn(name = "DCHA_ID", referencedColumnName = "DCHA_ID")
private DeploymentChannel deploymentChannel;
@Column(name = "CHPV_VALUE")
private String value;
}
package com.bytesw.bytebot.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "flight_schedules")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class FlightSchedule implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "airline_code")
private String airlineCode;
@Column(name = "usual_aircraft_type_code")
private String codeTypeAircraft;
@Column(name = "departure_date_time")
@Temporal(TemporalType.TIMESTAMP)
private Date departureDate;
@Column(name = "arrival_date_time")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date arrivalDate;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "origin_airport_code")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Airport codeAirportOrigin;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "destination_airport_code")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Airport codeAirportDestination;
@OneToMany(mappedBy = "codeFlight", cascade = CascadeType.ALL)
private List<Leg> legs;
@Column(name = "flight_cost")
private double flightCost;
}
package com.bytesw.bytebot.model;
import com.bytesw.bytebot.model.converters.FrequentQuestionStatusConverter;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.time.LocalDateTime;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Table(name = "AVB_FREQUENT_QUESTION")
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
@NamedQuery(name = "FrequentQuestion.findByPK", query = "Select u from FrequentQuestion u where u.id = ?1")
public class FrequentQuestion {
@Id
@Column(name = "FQUE_ID")
@SequenceGenerator(name = "AVB_FREQUENT_QUESTION_GENERATOR", sequenceName = "AVB_FREQUENT_QUESTION_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_FREQUENT_QUESTION_GENERATOR")
private Long id;
@Column(name = "FQUE_UUID")
private String uuid;
@Column(name = "FQUE_NAME")
private String filename;
@Column(name = "FQUE_DESC")
private String description;
@Column(name = "FQUE_STATE")
@Convert(converter = FrequentQuestionStatusConverter.class)
private FrequentQuestionStatusEnum status;
@ManyToOne
@JoinColumn(name = "AGEN_ID", referencedColumnName = "AGEN_ID")
private Agent agent;
@Column(name = "FQUE_USER")
private String user;
@Column(name = "FQUE_LDATE", columnDefinition = "TIMESTAMP")
private LocalDateTime uploadDate;
}
package com.bytesw.bytebot.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "itinerary_reservations")
@Getter
@Setter
public class ItineraryReservation implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "reservation_id", nullable = false)
private Long id;
@Column(name = "date_reservation_made")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dateReservation;
@Column(name = "reservation_status_code")
private String status;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "passenger_id", referencedColumnName = "id")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Passenger passenger;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "agent_id")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private BookingAgent agent;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE } )
@JoinTable(name = "reservation_payments",
joinColumns = { @JoinColumn(name = "reservation_id") },
inverseJoinColumns = { @JoinColumn(name = "payment_id") })
private List<Payment> payments;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.ALL})
@JoinTable(name = "itinerary_legs",
joinColumns = { @JoinColumn(name = "reservation_id") },
inverseJoinColumns = { @JoinColumn(name = "leg_id") })
private List<Leg> legs;
@PrePersist
public void prePersist() {
dateReservation = new Date();
}
public void addPayment(Payment payment) {
this.payments.add(payment);
payment.getItineraryReservations().add(this);
}
public void addLeg(Leg leg) {
this.legs.add(leg);
leg.getItineraryReservations().add(this);
}
}
package com.bytesw.bytebot.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "legs")
@Getter
@Setter
public class Leg implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "actual_departure_time")
@Temporal(TemporalType.TIMESTAMP)
private Date departureDate;
@Column(name = "actual_arrival_time")
@Temporal(TemporalType.TIMESTAMP)
private Date arrivalDate;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "origin_airport_code")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Airport codeAirportOrigin;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "destination_airport_code")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Airport codeAirportDestination;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "flight_number")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private FlightSchedule codeFlight;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.ALL }, mappedBy="legs")
@JsonIgnore
private List<ItineraryReservation> itineraryReservations;
}
package com.bytesw.bytebot.model;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "passengers")
@Getter
@Setter
public class Passenger implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="second_name")
private String secondName;
@Column(name="last_name")
private String lastName;
@Column(name="phone_number")
private String phoneNumber;
@Column(name="email_address")
private String email;
@Column(name="address_lines")
private String address;
@Column(name="city")
private String city;
@Column(name="state_province_country")
private String province;
@Column(name="country")
private String country;
@Column(name="other_passenger_details")
private String details;
@OneToMany(mappedBy = "passenger")
private List<ItineraryReservation> itineraryReservations = new ArrayList<>();
}
package com.bytesw.bytebot.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "payments")
@Getter
@Setter
@EqualsAndHashCode
@ToString
public class Payment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "payment_id")
private Long id;
@Column(name = "payment_date")
@Temporal(TemporalType.TIMESTAMP)
private Date paymentDate;
@Column(name = "payment_amount")
private double paymentAmount;
@Column(name = "payment_status_code")
private String status;
@ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.ALL, CascadeType.MERGE}, mappedBy = "payments")
@JsonIgnore
private List<ItineraryReservation> itineraryReservations;
@PrePersist
public void prePersist() {
paymentDate = new Date();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model;
import java.time.LocalDateTime;
import javax.persistence.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Type;
import org.hibernate.envers.Audited;
@Audited
@Entity
@Getter
@Setter
@ToString
@EqualsAndHashCode(of = "id")
@NoArgsConstructor
@Table(name = "AVB_QUESTION_FILE")
@NamedQuery(name = "QuestionFile.findByPK", query = "Select u from QuestionFile u where u.id = ?1")
public class QuestionFile {
@Id
@Column(name = "QUFI_ID")
@SequenceGenerator(name = "AVB_QUESTION_FILE_GENERATOR", sequenceName = "AVB_QUESTION_FILE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AVB_QUESTION_FILE_GENERATOR")
private Long id;
@Column(name = "QUFI_UUID", nullable = false)
private String uuid;
@Column(name = "QUFI_NAME", nullable = false)
private String name;
@Column(name = "QUFI_SIZE", nullable = false)
private Long size;
@Column(name = "QUFI_UDATE", columnDefinition = "TIMESTAMP")
private LocalDateTime uploadDate;
@Type(type="org.hibernate.type.BinaryType")
@Basic(fetch = FetchType.LAZY)
@Column(name = "QUFI_DATA", length= 100000, nullable = false)
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;
}
package com.bytesw.bytebot.model;
import lombok.*;
import org.hibernate.envers.Audited;
import javax.persistence.*;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Audited
@Entity
@Getter @Setter
@NoArgsConstructor
@Table(name = "avb_timezone")
@NamedQuery(name = "Timezone.findByPK", query = "Select u from Timezone u where u.id = ?1")
public class Timezone {
@Id
@Column(name = "tzon_id")
@SequenceGenerator(name = "avb_timezone_generator", sequenceName = "AVB_TIMEZONE_SEQ", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "avb_timezone_generator")
private Long id;
@Column(name = "tzon_zone", nullable = false)
private String timezone;
@ManyToOne
@JoinColumn(name = "coun_id", referencedColumnName = "coun_id")
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 OffsetTime from;
@Column(name = "WESC_TO", nullable = false)
private OffsetTime 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.AgentStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 AgentStatusConverter implements AttributeConverter<AgentStatusEnum, String> {
@Override
public String convertToDatabaseColumn(AgentStatusEnum value) {
return value.getName();
}
@Override
public AgentStatusEnum convertToEntityAttribute(String value) {
return AgentStatusEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
@Converter
public class AgentTypeConverter implements AttributeConverter<AgentTypeEnum, String> {
@Override
public String convertToDatabaseColumn(AgentTypeEnum agentTypeEnum) {
if (agentTypeEnum == null) return null;
return agentTypeEnum.getName();
}
@Override
public AgentTypeEnum convertToEntityAttribute(String s) {
return AgentTypeEnum.fromString(s);
}
}
package com.bytesw.bytebot.model.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 BooleanToStringConverter implements AttributeConverter<Boolean, String> {
public BooleanToStringConverter() {
}
public String convertToDatabaseColumn(Boolean value) {
return value != null && value ? "Y" : "N";
}
public Boolean convertToEntityAttribute(String value) {
return "Y".equals(value);
}
}
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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.FileQuestionStatusEnum;
import javax.persistence.AttributeConverter;
import org.apache.camel.Converter;
/**
* @author Hernán Uriarte Melchor
* @version 13-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 FileQuestionStatusConverter implements AttributeConverter<FileQuestionStatusEnum, String> {
@Override
public String convertToDatabaseColumn(FileQuestionStatusEnum value) {
return value.getName();
}
@Override
public FileQuestionStatusEnum convertToEntityAttribute(String value) {
return FileQuestionStatusEnum.fromString(value);
}
}
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.converters;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 10-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 FrequentQuestionStatusConverter implements AttributeConverter<FrequentQuestionStatusEnum, String> {
@Override
public String convertToDatabaseColumn(FrequentQuestionStatusEnum value) {
if (value == null) {
return null;
}
return value.getName();
}
@Override
public FrequentQuestionStatusEnum convertToEntityAttribute(String value) {
return FrequentQuestionStatusEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 LanguageConverter implements AttributeConverter<LanguageEnum, String> {
@Override
public String convertToDatabaseColumn(LanguageEnum value) {
return value.getName();
}
@Override
public LanguageEnum convertToEntityAttribute(String value) {
return LanguageEnum.fromString(value);
}
}
\ No newline at end of file
package com.bytesw.bytebot.model.converters;
import com.bytesw.bytebot.model.enums.StatusEnum;
import org.apache.camel.Converter;
import javax.persistence.AttributeConverter;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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 StatusConverter implements AttributeConverter<StatusEnum, String> {
@Override
public String convertToDatabaseColumn(StatusEnum value) {
if (value == null) {
return null;
}
return value.getName();
}
@Override
public StatusEnum convertToEntityAttribute(String value) {
return StatusEnum.fromString(value);
}
}
\ 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 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 lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
public enum AgentStatusEnum {
CREATED("CR"),
PENDING_SYNCHRONIZED("PS"),
DEPLOYED("DP"),
DELETED("DE");
private static final Map<String, AgentStatusEnum> map = new HashMap<>();
private String name;
AgentStatusEnum(String name) {
this.name = name;
}
static {
for (AgentStatusEnum type : AgentStatusEnum.values()) {
map.put(type.name, type);
}
}
public static AgentStatusEnum 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 AgentTypeEnum {
FREQUENT_QUESTION("FQ");
private final String name;
private static final Map<String, AgentTypeEnum> map = new HashMap<>();
static {
for (AgentTypeEnum type : AgentTypeEnum.values()) {
map.put(type.name, type);
}
}
AgentTypeEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static AgentTypeEnum fromString(String name) {
if (map.containsKey(name)) {
return map.get(name);
}
throw new NoSuchElementException(name + " not found");
}
}
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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.model.enums;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
/**
* @author Hernán Uriarte Melchor
* @version 13-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
public enum FileQuestionStatusEnum {
ACTIVE("AC"),
LOADED("LO"),
DISABLED("DI");
private static final Map<String, FileQuestionStatusEnum> map = new HashMap<>();
private String name;
FileQuestionStatusEnum(String name) {
this.name = name;
}
static {
for (FileQuestionStatusEnum type : FileQuestionStatusEnum.values()) {
map.put(type.name, type);
}
}
public static FileQuestionStatusEnum 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;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
public enum FrequentQuestionStatusEnum {
PENDING_SYNCHRONIZED("PS"),
UPLOADED("LO"),
DELETED("DE"),
ERROR("ER"),
CORRECTO("OK");
private static final Map<String, FrequentQuestionStatusEnum> map = new HashMap<>();
private String name;
FrequentQuestionStatusEnum(String name) {
this.name = name;
}
static {
for (FrequentQuestionStatusEnum type : FrequentQuestionStatusEnum.values()) {
map.put(type.name, type);
}
}
public static FrequentQuestionStatusEnum 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 LanguageEnum {
SPANISH("ES");
private final String name;
private static final Map<String, LanguageEnum> map = new HashMap<>();
static {
for (LanguageEnum type : LanguageEnum.values()) {
map.put(type.name, type);
}
}
LanguageEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static LanguageEnum 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.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
@Getter
public enum StatusBcdEnum {
CARGANDO("Cargando"),
CARGADO("Cargado"),
INDEXANDO("Indexando"),
INDEXADO("Indexado");
private static final Map<String, StatusBcdEnum> map = new HashMap<>();
private String name;
StatusBcdEnum(String name) {
this.name = name;
}
static {
for (StatusBcdEnum type : StatusBcdEnum.values()) {
map.put(type.name, type);
}
}
public static StatusBcdEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.model.enums;
import lombok.Getter;
import java.util.HashMap;
import java.util.Map;
/**
* @author Sebastian Chicoma Sandmann
* @version 09-sep-2020
*
* Copyright (c) 2020 Byte, S.A. Todos los derechos reservados.
*
* 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.
*/
@Getter
public enum StatusEnum {
ACTIVE("AC"),
INACTIVE("IN"),
DELETED("DE");
private static final Map<String, StatusEnum> map = new HashMap<>();
private String name;
StatusEnum(String name) {
this.name = name;
}
static {
for (StatusEnum type : StatusEnum.values()) {
map.put(type.name, type);
}
}
public static StatusEnum fromString(String name) {
return map.get(name);
}
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 AgentRepository extends CrudRepository<Agent, Long>, JpaSpecificationExecutor<Agent> {
List<Agent> findByStatus(AgentStatusEnum status);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.BdcControl;
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 BdcControlRepository extends CrudRepository<BdcControl, Long>, JpaSpecificationExecutor<BdcControl> {
@Query("select s from BdcControl s where s.uuid = :uuid")
Optional<BdcControl> findByUuid(@Param("uuid") String uuid);
}
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.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 ChannelParamRepository extends CrudRepository<ChannelParam, Long> {
Optional<ChannelParam> findByNameAndChannelId(String name, Long id);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Channel;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 ChannelRepository extends CrudRepository<Channel, Long> {
Optional<Channel> findByName(String name);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Country;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 CountryRepository extends CrudRepository<Country, Long> {
@Query("select c from Country c order by c.name")
List<Country> findAllOrder();
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 DeploymentChannelParamValueRepository extends CrudRepository<DeploymentChannelParamValue, Long> {
@Query("select d from DeploymentChannelParamValue d where d.deploymentChannel.id = :id order by d.id asc")
List<DeploymentChannelParamValue> getParameter(@Param("id") Long id);
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannel;
import org.springframework.data.repository.CrudRepository;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 DeploymentChannelRepository extends CrudRepository<DeploymentChannel, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.DeploymentChannel;
import com.bytesw.bytebot.model.FrequentQuestion;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* @author Sebastián Chicoma Sandmann.
* @version 9-sep-2020
* <p>
* Copyright (c) 2020 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 FrequentQuestionRepository extends CrudRepository<FrequentQuestion, Long> {
public List<FrequentQuestion> findAllByAgentIdAndStatus(Long id, FrequentQuestionStatusEnum status);
}
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; package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Calendar; import com.bytesw.bytebot.model.Airport;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface CalendarRepository extends CrudRepository<Calendar, String>, JpaSpecificationExecutor<Calendar> { @Repository
} public interface IAirportRepository extends CrudRepository<Airport, Long> {
\ No newline at end of file }
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.BookingAgent;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IBookingAgentRepository extends JpaRepository<BookingAgent, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.FlightSchedule;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IFlightRepository extends CrudRepository<FlightSchedule, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.ItineraryReservation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IItineraryReservationRepository extends JpaRepository<ItineraryReservation, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Leg;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ILegRepository extends JpaRepository<Leg, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Passenger;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IPassengerRepository extends JpaRepository<Passenger, Long> {
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.Payment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface IPaymentRepository extends JpaRepository<Payment, Long> {
}
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);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.model.QuestionFile;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.Optional;
/**
* @author Hernán Uriarte Melchor.
* @version 13-sep-2020
* <p>
* Copyright (c) 2020 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 QuestionFileRepository extends CrudRepository<QuestionFile, Long> {
public Optional<QuestionFile> findByUuid(String uuid);
@Query("Select q.uploadDate from QuestionFile q where q.uuid = :uuid")
LocalDateTime findUploadDateByUuid(@Param("uuid") String uuid);
}
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.calendarID = :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);
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.etl.batch.service.ScheduleService;
import com.bytesw.bytebot.model.*;
import com.bytesw.bytebot.jdbc.AgentJDBCRepository;
import com.bytesw.bytebot.model.enums.*;
import com.bytesw.bytebot.repository.*;
import com.bytesw.xdf.config.AppContextManager;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.sql.beans.Pagination;
import lombok.extern.log4j.Log4j2;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Service
@Transactional
@Log4j2
public class AgentService extends CustomPaginationService<Agent> {
@Autowired
private AgentRepository agentRepository;
@Autowired
private AgentJDBCRepository agentJDBCRepository;
@Autowired
private CountryRepository countryRepository;
@Autowired
private DeploymentChannelRepository deploymentChannelRepository;
@Autowired
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@Autowired
private ChannelRepository channelRepository;
@Autowired
private ChannelParamRepository channelParamRepository;
@Autowired
private FrequentQuestionRepository frequentQuestionRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private ProducerTemplate producerTemplate;
@Autowired
private ScheduleService scheduleService;
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) {
if (pagination.getItemsPerPage() == 0) {
pagination.setItemsPerPage(10);
}
Sort sort = null;
if (pagination.getSortFields() != null) {
sort = createSort(pagination);
}
Pageable pageable = null;
if (sort != null) {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage(), sort);
} else {
pageable = PageRequest.of(pagination.getCurrentPage(), pagination.getItemsPerPage());
}
Specification<Agent> specification = (Specification<Agent>) (root, query, criteriaBuilder)
-> criteriaBuilder.notEqual(root.get("status"), AgentStatusEnum.DELETED);
if (pagination.getFilterExpression() != null && pagination.getFilterExpression().length() > 0) {
specification = createSpecification(pagination.getFilterExpression()).and(specification);
}
Page<Agent> page = agentRepository.findAll(specification, pageable);
pagination.setTotalItems(page.getTotalElements());
pagination.setTotalPages(page.getTotalPages());
// Clone to array
List<AgentBean> list = new ArrayList<>();
for (Agent agent : page.getContent()) {
list.add(AgentBean.miniClone(agent));
}
pagination.setData(list);
}
@Transactional(propagation = Propagation.REQUIRED)
@CacheEvict(value="deploy_agents",allEntries = true)
public void save(AgentBean agent) {
boolean isModify = true;
Agent agentBD = null;
if (agent.getId() != null) {
Optional<Agent> agentFound = agentRepository.findById(agent.getId());
if (agentFound.isPresent()) {
agentBD = agentFound.get();
}
}
if (agentBD == null) {
agentBD = new Agent();
agentBD.setStatus(AgentStatusEnum.CREATED);
isModify = false;
} else {
agentBD.setStatus(AgentStatusEnum.fromString(agent.getStatus()));
}
// General Information
agentBD.setName(agent.getName());
agentBD.setDescription(agent.getDescription());
agentBD.setLanguage(LanguageEnum.fromString(agent.getLanguage()));
agentBD.setTimezone(agent.getTimezone());
agentBD.setVersion(agent.getVersion());
agentBD.setType(AgentTypeEnum.fromString(agent.getType()));
agentBD.setAvatar(agent.getAvatar());
agentBD.setPeriod(agent.getPeriod());
if (agent.getCountryId() != null) {
Optional<Country> countryFound = countryRepository.findById(agent.getCountryId());
if (countryFound.isPresent()) {
agentBD.setCountry(countryFound.get());
}
} else {
agentBD.setCountry(null);
}
agentBD = agentRepository.save(agentBD);
// Frequent questions
if (agent.getFrequentQuestions() == null) {
agent.setFrequentQuestions(new ArrayList<>());
}
if (agentBD.getFrequentQuestions() != null) {
for (FrequentQuestion frequentQuestionBD : agentBD.getFrequentQuestions()) {
boolean found = false;
for (FrequentQuestionBean frequentQuestionBean : agent.getFrequentQuestions()) {
if (frequentQuestionBean.getId() != null && frequentQuestionBD.getId().compareTo(frequentQuestionBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
frequentQuestionRepository.delete(frequentQuestionBD);
}
}
}
boolean changeToPendingSynchronized = false;
for (FrequentQuestionBean frequentQuestionBean : agent.getFrequentQuestions()) {
FrequentQuestion frequentQuestionBD = null;
boolean existInDB = false;
if (frequentQuestionBean.getId() != null) {
Optional<FrequentQuestion> frequentQuestionFound = frequentQuestionRepository.findById(frequentQuestionBean.getId());
if (frequentQuestionFound.isPresent()) {
existInDB = true;
frequentQuestionBD = frequentQuestionFound.get();
}
}
if (frequentQuestionBD == null) {
frequentQuestionBD = new FrequentQuestion();
frequentQuestionBD.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestionBD.setUuid(frequentQuestionBean.getUuid());
changeToPendingSynchronized = true;
}
frequentQuestionBD.setAgent(agentBD);
frequentQuestionBD.setDescription(frequentQuestionBean.getDescription());
frequentQuestionBD.setFilename(frequentQuestionBean.getFilename());
frequentQuestionBD.setStatus(FrequentQuestionStatusEnum.fromString(frequentQuestionBean.getStatus()));
frequentQuestionBD.setUser(frequentQuestionBean.getUser());
if (!existInDB) {
LocalDateTime uploadDate = questionFileRepository.findUploadDateByUuid(frequentQuestionBean.getUuid());
frequentQuestionBD.setUploadDate(uploadDate);
}
frequentQuestionRepository.save(frequentQuestionBD);
}
if (changeToPendingSynchronized) {
agentBD.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentBD = agentRepository.save(agentBD);
}
// Deployment channels
if (agent.getDeploymentChannels() == null) {
agent.setDeploymentChannels(new ArrayList<>());
}
if (agentBD.getDeploymentChannels() != null) {
for (DeploymentChannel deploymentChannelBD : agentBD.getDeploymentChannels()) {
boolean found = false;
for (DeploymentChannelBean deploymentChannelBean : agent.getDeploymentChannels()) {
if (deploymentChannelBean.getId() != null && deploymentChannelBD.getId().compareTo(deploymentChannelBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
deploymentChannelParamValueRepository.deleteAll(deploymentChannelBD.getParameters());
deploymentChannelRepository.delete(deploymentChannelBD);
}
}
}
for (DeploymentChannelBean deploymentChannelBean : agent.getDeploymentChannels()) {
DeploymentChannel deploymentChannelBD = null;
boolean existInBD = false;
if (deploymentChannelBean.getId() != null) {
Optional<DeploymentChannel> deploymentChannelFound = deploymentChannelRepository.findById(deploymentChannelBean.getId());
if (deploymentChannelFound.isPresent()) {
deploymentChannelBD = deploymentChannelFound.get();
existInBD = true;
}
}
if (deploymentChannelBD == null) {
deploymentChannelBD = new DeploymentChannel();
}
deploymentChannelBD.setAgent(agentBD);
deploymentChannelBD.setStatus(StatusEnum.fromString(deploymentChannelBean.getStatus()));
if (deploymentChannelBean.getChannelId() != null) {
Optional<Channel> channelFound = channelRepository.findById(deploymentChannelBean.getChannelId());
if (channelFound.isPresent()) {
deploymentChannelBD.setChannel(channelFound.get());
if (!existInBD) {
deploymentChannelBD.setName(agentBD.getName() + "_" + channelFound.get().getName());
}
}
} else {
deploymentChannelBD.setName(agentBD.getName() + "_" + UUID.randomUUID());
deploymentChannelBD.setChannel(null);
}
deploymentChannelRepository.save(deploymentChannelBD);
// Deployment Channel parameters
if (deploymentChannelBean.getParameters() == null) {
deploymentChannelBean.setParameters(new ArrayList<>());
}
if (deploymentChannelBD.getParameters() != null) {
for (DeploymentChannelParamValue deploymentChannelParamValueBD : deploymentChannelBD.getParameters()) {
boolean found = false;
for (DeploymentChannelParamValueBean deploymentChannelParamValueBean : deploymentChannelBean.getParameters()) {
if (deploymentChannelParamValueBean.getId() != null &&
deploymentChannelParamValueBD.getId().compareTo(deploymentChannelParamValueBean.getId()) == 0) {
found = true;
break;
}
}
if (!found) {
deploymentChannelParamValueRepository.delete(deploymentChannelParamValueBD);
}
}
}
for (DeploymentChannelParamValueBean deploymentChannelParamValueBean : deploymentChannelBean.getParameters()) {
DeploymentChannelParamValue deploymentChannelParamValue = null;
if (deploymentChannelParamValueBean.getId() != null) {
Optional<DeploymentChannelParamValue> deploymentChannelParamValueFound = deploymentChannelParamValueRepository
.findById(deploymentChannelParamValueBean.getId());
if (deploymentChannelParamValueFound.isPresent()) {
deploymentChannelParamValue = deploymentChannelParamValueFound.get();
}
}
if (deploymentChannelParamValue == null) {
deploymentChannelParamValue = new DeploymentChannelParamValue();
}
deploymentChannelParamValue.setDeploymentChannel(deploymentChannelBD);
deploymentChannelParamValue.setValue(deploymentChannelParamValueBean.getValue());
if (deploymentChannelParamValueBean.getChannelParamName() != null) {
Optional<ChannelParam> channelParamFound = channelParamRepository.findByNameAndChannelId(
deploymentChannelParamValueBean.getChannelParamName(), deploymentChannelBean.getChannelId());
if (channelParamFound.isPresent()) {
deploymentChannelParamValue.setParameter(channelParamFound.get());
}
} else {
deploymentChannelParamValue.setParameter(null);
}
deploymentChannelParamValueRepository.save(deploymentChannelParamValue);
}
}
}
public AgentBean getAgent(Long id) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
AgentBean bean = null;
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
bean = new AgentBean();
bean.setId(agent.getId());
bean.setName(agent.getName());
bean.setDescription(agent.getDescription());
bean.setVersion(agent.getVersion());
bean.setLanguage(agent.getLanguage().getName());
bean.setTimezone(agent.getTimezone());
bean.setType(agent.getType().getName());
bean.setStatus(agent.getStatus().getName());
bean.setAvatar(agent.getAvatar());
bean.setPeriod(agent.getPeriod());
if (agent.getCountry() != null) {
bean.setCountryName(agent.getCountry().getName());
bean.setCountryId(agent.getCountry().getId());
}
// Deployment channel
bean.setFrequentQuestions(new ArrayList<>());
for (FrequentQuestion frequentQuestion : agent.getFrequentQuestions()) {
FrequentQuestionBean frequentQuestionBean = new FrequentQuestionBean();
frequentQuestionBean.setId(frequentQuestion.getId());
frequentQuestionBean.setUuid(frequentQuestion.getUuid());
frequentQuestionBean.setDescription(frequentQuestion.getDescription());
frequentQuestionBean.setUser(frequentQuestion.getUser());
frequentQuestionBean.setFilename(frequentQuestion.getFilename());
frequentQuestionBean.setStatus(frequentQuestion.getStatus().getName());
if(frequentQuestion.getUploadDate() != null) {
frequentQuestionBean.setUploadDate(frequentQuestion.getUploadDate().format(formatter));
}
bean.getFrequentQuestions().add(frequentQuestionBean);
}
// Deployment channel
bean.setDeploymentChannels(new ArrayList<>());
for (DeploymentChannel deploymentChannel : agent.getDeploymentChannels()) {
DeploymentChannelBean deploymentChannelBean = new DeploymentChannelBean();
deploymentChannelBean.setId(deploymentChannel.getId());
deploymentChannelBean.setName(deploymentChannel.getName());
deploymentChannelBean.setStatus(deploymentChannel.getStatus().getName());
deploymentChannelBean.setParameters(new ArrayList<>());
if (deploymentChannel.getChannel() != null) {
deploymentChannelBean.setChannelId(deploymentChannel.getChannel().getId());
deploymentChannelBean.setChannelName(deploymentChannel.getChannel().getName());
}
//Parameters
List<DeploymentChannelParamValue> list = deploymentChannelParamValueRepository.getParameter(deploymentChannel.getId());
for (DeploymentChannelParamValue parameter : list) {
DeploymentChannelParamValueBean parameterBean = new DeploymentChannelParamValueBean();
parameterBean.setId(parameter.getId());
parameterBean.setValue(parameter.getValue());
if (parameter.getParameter() != null) {
parameterBean.setChannelParamName(parameter.getParameter().getName());
}
deploymentChannelBean.getParameters().add(parameterBean);
}
bean.getDeploymentChannels().add(deploymentChannelBean);
}
}
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public boolean delete(Long id) {
boolean isValid = true;
if (id != null) {
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
agent.setStatus(AgentStatusEnum.DELETED);
scheduleService.cancelTaskDelete(id);
agentRepository.save(agent);
}
}
else{
isValid = false;
}
return isValid;
}
public List<CountryBean> getCountries() {
List<CountryBean> countriesBean = new ArrayList<>();
List<Country> countries = countryRepository.findAllOrder();
for (Country country : countries) {
countriesBean.add(CountryBean.clone(country));
}
return countriesBean;
}
public List<ChannelBean> getChannels() {
List<ChannelBean> channelsBean = new ArrayList<>();
List<Channel> channels = (List<Channel>) channelRepository.findAll();
for (Channel channel : channels) {
List<ChannelParam> channelParamList = channel.getParameters();
for (ChannelParam channelParam : channelParamList) {
channelParam.setTraductions(channelParam.getTraductions().replace("\\", ""));
}
channelsBean.add(ChannelBean.clone(channel));
}
return channelsBean;
}
@Transactional(propagation = Propagation.REQUIRED)
public void synchronizeFiles(Long id, String user) {
if (AppContextManager.getAppContext() == null) {
return;
}
FileConverter fileConverter = (FileConverter) AppContextManager.getAppContext().getBean("xlsToCsvFileConverter");
List<FrequentQuestion> frequentQuestions = frequentQuestionRepository.findAllByAgentIdAndStatus(id, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
Map<String, Object> headers = new HashMap<>();
for (FrequentQuestion frequentQuestion : frequentQuestions) {
Optional<QuestionFile> questionFileFound = questionFileRepository.findByUuid(frequentQuestion.getUuid());
if (questionFileFound.isPresent()) {
headers.put("CamelFileName", fileConverter.getFileName(questionFileFound.get().getName()));
// try {
// FileUtils.writeByteArrayToFile(new File("/home/schicoma/Escritorio/" + questionFileFound.get().getName()), questionFileFound.get().getData());
// } catch (IOException e) {
// e.printStackTrace();
// }
producerTemplate.sendBodyAndHeaders("direct:transferFile", fileConverter.convert(questionFileFound.get().getData(), questionFileFound.get().getName()), headers);
}
frequentQuestion.setStatus(FrequentQuestionStatusEnum.UPLOADED);
//frequentQuestion.setUser(user);
//frequentQuestion.setUploadDate(LocalDateTime.now());
frequentQuestionRepository.save(frequentQuestion);
}
Optional<Agent> agentFound = agentRepository.findById(id);
if (agentFound.isPresent()) {
Agent agent = agentFound.get();
agent.setStatus(AgentStatusEnum.DEPLOYED);
agentRepository.save(agent);
}
}
public List<Map> getAgentAll() {
List<Agent> lista = (List<Agent>) agentRepository.findAll();
if (lista.size() <= 0) {
throw new NotFoundException("Error al listar agentes.");
}
List<Map> result = new ArrayList<>();
for(Agent agent: lista) {
Map<String, Object> map = new HashMap<>();
map.put("id", agent.getId());
map.put("name", agent.getName());
map.put("description", agent.getDescription());
map.put("version", agent.getVersion());
map.put("status", agent.getStatus().getName());
map.put("period", agent.getPeriod());
map.put("timezone", agent.getTimezone());
result.add(map);
}
return result;
}
}
package com.bytesw.bytebot.service; package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.beans.ActionBean; import com.bytesw.bytebot.dto.AirportDto;
import com.bytesw.bytebot.etl.dao.ActionRepository; import com.bytesw.bytebot.model.Airport;
import com.bytesw.bytebot.etl.model.Action; import com.bytesw.bytebot.repository.IAirportRepository;
import com.bytesw.xdf.service.XDFService; import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@Service @Service
@Transactional @Transactional
@Log4j2 public class AirportService extends XDFService<Airport, AirportDto, Long> {
public class ActionService extends XDFService<Action, ActionBean, Long> { protected AirportService(IAirportRepository airportRepository) {
protected ActionService(ActionRepository repository) { super(airportRepository);
super(repository);
} }
@Override @Override
protected Action toModel(Action model, ActionBean bean) { protected Airport toModel(Airport airport, AirportDto airportDto) {
if (model == null) { if(airport == null) {
model = new Action(); airport = new Airport();
} }
BeanUtils.copyProperties(bean, model); BeanUtils.copyProperties(airportDto, airport);
return model; return airport;
} }
@Override @Override
protected ActionBean toBean(Action model) { protected AirportDto toBean(Airport airport) {
ActionBean bean = new ActionBean(); AirportDto airportDto = new AirportDto();
BeanUtils.copyProperties(model, bean); BeanUtils.copyProperties(airport, airportDto);
return bean; return airportDto;
} }
} }
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.BdcControlBean;
import com.bytesw.bytebot.model.BdcControl;
import com.bytesw.bytebot.repository.BdcControlRepository;
import com.bytesw.xdf.service.XDFService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Log4j2
public class BcdControlService extends XDFService<BdcControl, BdcControlBean, Long> {
protected BcdControlService(BdcControlRepository repository) {
super(repository);
}
@Override
protected BdcControl toModel(BdcControl model, BdcControlBean bean) {
if (model == null) {
model = new BdcControl();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected BdcControlBean toBean(BdcControl model) {
BdcControlBean bean = new BdcControlBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.BookingAgentDto;
import com.bytesw.bytebot.model.BookingAgent;
import com.bytesw.bytebot.repository.IBookingAgentRepository;
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 BookingAgentService extends XDFService<BookingAgent, BookingAgentDto, Long> {
protected BookingAgentService( IBookingAgentRepository bookingAgentRepository) {
super(bookingAgentRepository);
}
@Override
protected BookingAgent toModel(BookingAgent bookingAgent, BookingAgentDto bookingAgentDto) {
if (bookingAgent == null) {
bookingAgent = new BookingAgent();
}
BeanUtils.copyProperties(bookingAgentDto, bookingAgent);
return bookingAgent;
}
@Override
protected BookingAgentDto toBean(BookingAgent bookingAgent) {
BookingAgentDto bookingAgentDto = new BookingAgentDto();
BeanUtils.copyProperties(bookingAgent, bookingAgentDto);
return bookingAgentDto;
}
}
package com.bytesw.bytebot.service;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
@Service
@Log4j2
public class BucketService {
@Value("${application.bucket.tenant}")
private String tenant;
@Value("${application.bucket.region}")
private String region;
@Value("${application.bucket.fileBucket}")
private String fileDir;
@Value("${application.bucket.modelBucket}")
private String modelDir;
@Value("${application.bucket.version}")
private String version;
@Value("${application.bucket.parameter}")
private String parameter;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private BusinessParameterService businessParameterService;
private AmazonS3 getS3Client() {
return AmazonS3ClientBuilder.standard()
.withRegion(region)
.build();
}
public boolean generate(byte[] file, FileValidationResponse response) {
String bucketName = businessParameterService.getBusinessParameterForKey(parameter);
if (bucketName == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
boolean result = false;
File mainFile = new File(response.getFileName());
try {
FileOutputStream stream = new FileOutputStream(mainFile);
stream.write(file);
String newFile = String.format("%s/%s/%s/%s/%s",tenant, response.getUuid(), version, fileDir, mainFile.getName());
PutObjectRequest request = new PutObjectRequest(bucketName, newFile, mainFile);
AmazonS3 amazonS3 = getS3Client();
amazonS3.putObject(request);
String modelFile = String.format("%s/%s/%s/%s",tenant, response.getUuid(), version, modelDir);
createFolder(bucketName, modelFile, amazonS3);
mainFile.delete();
result = true;
} catch (Exception e) {
log.error("Error al cargar archivo");
}
return result;
}
public static void createFolder(String bucketName, String folderName, AmazonS3 client) {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(0);
InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
folderName+"/", emptyContent, metadata);
client.putObject(putObjectRequest);
}
public void delete(String uuid) {
String bucketName = businessParameterService.getBusinessParameterForKey(parameter);
if (bucketName == null) {
throw new NotFoundException();
}
try {
AmazonS3 s3Client = getS3Client();
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (!questionFile.isPresent()) {
throw new NotFoundException();
}
String keyName = String.format("%s/%s/%s/%s/%s",tenant, uuid, version, fileDir, questionFile.get().getName());
s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
keyName = String.format("%s/%s/%s/%s/",tenant, uuid, version, modelDir);
s3Client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
} catch (AmazonServiceException e) {
e.printStackTrace();
} catch (SdkClientException e) {
e.printStackTrace();
}
}
}
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 createBP(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());
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;
}
public String getBusinessParameterForKey(String parameter) {
Optional<BusinessParameter> businessParameter = businessParameterRepository.findByKey(parameter);
if(!businessParameter.isPresent()) {
return null;
}
String parameterResult = null;
if (businessParameter.get().getRequired()) {
parameterResult = businessParameter.get().getDefaultValue();
}
List<BusinessParameterConfiguration> parameterConfig = businessParameterConfigurationRepository
.findBusinessParameterConfigurationListByBusinessParameter(businessParameter.get().getId());
if (parameterConfig.isEmpty()) {
return parameterResult;
}
OffsetDateTime nowTime = OffsetDateTime.now();
for (BusinessParameterConfiguration config: parameterConfig) {
if (config.getTo() == null) {
if (nowTime.isAfter(config.getFrom())) {
parameterResult = config.getValue();
break;
}
} else {
if (config.getFrom().equals(config.getTo())) {
if (config.getFrom().isBefore(nowTime)) {
parameterResult = config.getValue();
break;
}
}
if (config.getFrom().isBefore(config.getTo()) && nowTime.isAfter(config.getFrom()) && config.getTo().isAfter(nowTime)) {
parameterResult = config.getValue();
break;
}
}
}
return parameterResult;
}
}
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.math.BigInteger;
import java.util.ArrayList;
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();
Optional<List<WeekScheduler>> weekSchedulerBeanListBD = weekSchedulerRepository.findByCalendarId(calendar.getId().trim());
List<BigInteger> weekIds = new ArrayList<>();
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()) {
weekIds.add(weekSchedulerOptional.get().getId());
if (delete) {
this.weekSchedulerRepository.delete(weekSchedulerOptional.get());
continue;
}
weekScheduler = weekSchedulerOptional.get();
} else {
weekScheduler = new WeekScheduler();
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
}
// weekScheduler.setCalendar(calendar);
weekScheduler.setCalendarID(calendar.getId());
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
} else if (!delete) {
weekScheduler = new WeekScheduler();
// weekScheduler.setCalendar(calendar);
weekScheduler.setCalendarID(calendar.getId());
weekScheduler.setDayOfWeek(weekSchedulerBean.getDayOfWeek());
weekScheduler.setFrom(weekSchedulerBean.getFrom());
weekScheduler.setTo(weekSchedulerBean.getTo());
this.weekSchedulerRepository.save(weekScheduler);
}
}
if (weekSchedulerBeanListBD.isPresent()){
for (WeekScheduler weekScheduler: weekSchedulerBeanListBD.get()) {
if (!weekIds.contains(weekScheduler.getId())) {
weekSchedulerRepository.deleteById(weekScheduler.getId());
}
}
}
}
private void saveCalendarException(CalendarBean bean, Calendar calendar) {
List<CalendarExceptionBean> calendarExceptionBeanList = bean.getCalendarExceptionBeanList();
Optional<List<CalendarException>> calendarExceptionListBD = calendarExceptionRepository.findByCalendarId(calendar.getId().trim());
List<BigInteger> exceptionIds = new ArrayList<>();
CalendarException calendarException = null;
for (CalendarExceptionBean calendarExceptionBean : calendarExceptionBeanList) {
if (calendarExceptionBean.getId() != null) {
Optional<CalendarException> calendarExceptionOptional = calendarExceptionRepository.findById(calendarExceptionBean.getId());
if (calendarExceptionOptional.isPresent()) {
exceptionIds.add(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);
}
if (calendarExceptionListBD.isPresent()){
for (CalendarException calException: calendarExceptionListBD.get()) {
if (!exceptionIds.contains(calException.getId())) {
calendarExceptionRepository.deleteById(calException.getId());
}
}
}
}
}
package com.bytesw.bytebot.service;
public interface FileConverter {
byte[] convert(byte[] inputFile, String fileName);
String getFileName(String fileName);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.amazonaws.services.dynamodbv2.xspec.S;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.FileValidationResult;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.bytebot.utils.Utilities;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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 org.springframework.web.multipart.MultipartFile;
@Service
@Transactional
@Log4j2
public class FileManagementService {
String[] validExtensions = new String[]{"xls", "xlsx", "csv"};
String[] fileHeaders = new String[]{"Class", "Question", "Answer"};
@Autowired
private QuestionFileRepository questionFileRepository;
public FileValidationResponse saveFile(String uuid, MultipartFile file) throws IOException {
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
//@Validaciones: Tipo de Extension
boolean acceptedExtension = false;
String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());
for (String validExension : validExtensions) {
if (validExension.equalsIgnoreCase(fileExtension.trim())) {
acceptedExtension = true;
break;
}
}
if (!acceptedExtension) {
log.info("La extension [" + fileExtension + "] es inválida");
result.setStatus(ValidationStatusEnum.INCOMPATIBLE_EXTENSION);
response.setFileValidationResult(result);
return response;
}
switch (fileExtension) {
case "csv":
response = validateCsv(uuid, file);
break;
case "xls":
case "xlsx":
response = validateAndSaveFile(uuid, file);
break;
}
return response;
}
@Transactional(propagation = Propagation.REQUIRED)
public FileValidationResponse validateAndSaveFile(String uuid, MultipartFile file) throws IOException {
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
//@Validaciones: De Estructura del Excel (Cabeceras)
byte[] fileData = file.getBytes();
log.debug("File Size: [" + file.getSize() + "]");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData);
Workbook workbook = WorkbookFactory.create(byteArrayInputStream);
Sheet sheet = workbook.getSheetAt(0);
Row headerRow = sheet.getRow(0);
//@HU: Llenando los headers encontrados
Map<String, Integer> headersXPosition = new HashMap<>();
List<String> headersList = new ArrayList<>();
//Cabeceras vacias
if (headerRow == null) {
Map<String, String> headerErrorMap = new HashMap<>();
for (String key : fileHeaders) {
headerErrorMap.put(key, "HEADER.NOT.FOUND.FIRST.ROW");
}
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
response.setFileValidationResult(result);
return response;
}
Iterator<Cell> cells = headerRow.cellIterator();
int position = 0;
while (cells.hasNext()) {
Cell cell = (Cell) cells.next();
RichTextString value = cell.getRichStringCellValue();
headersXPosition.put(value.getString(), position++);
headersList.add(value.getString());
}
Map<String, String> headerErrorMap = validateHeaders(headersList);
if (!headerErrorMap.isEmpty()) {
log.info("Se encontraron los siguientes errores: " + headerErrorMap.values());
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
result.setHeadersErrorMap(headerErrorMap);
response.setFileValidationResult(result);
return response;
}
//@Validaciones: De Contenido(Todos deben tener valor)
int rowNumber = 0;
int rowError = 0;
Iterator<Row> rowIterator = sheet.iterator();
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
if (rowNumber == 0) {
rowNumber++;
continue;
}
log.debug("Row number: [" + rowNumber + "]");
Iterator<String> columnsIterator = headersXPosition.keySet().iterator();
Map<String, Object> recordsXRow = new HashMap<>();
while (columnsIterator.hasNext()) {
String name = columnsIterator.next();
log.debug("Read columnName [" + name + "]");
if (!isFileHeader(name.toUpperCase().trim())) {
log.debug("Skip columnName [" + name + "] - not required in format");
continue;
}
Cell cell = row.getCell(headersXPosition.get(name));
if (cell == null) {
recordsXRow.put(name, null);
continue;
}
CellType cellType = row.getCell(headersXPosition.get(name)).getCellType();
switch (cellType) {
case STRING:
RichTextString cellValue = row.getCell(headersXPosition.get(name)).getRichStringCellValue();
String value = (cellValue != null ? cellValue.getString().trim() : null);
recordsXRow.put(name, value);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(row.getCell(headersXPosition.get(name)))) {
Date date = row.getCell(headersXPosition.get(name)).getDateCellValue();
recordsXRow.put(name, Utilities.convertDateToString(date, "dd-MMM-yyyy"));
} else {
double numericVal = row.getCell(headersXPosition.get(name)).getNumericCellValue();
recordsXRow.put(name, numericVal);
}
break;
case BLANK:
recordsXRow.put(name, null);
break;
default:
log.info(" CellType not supported yet [" + row.getCell(headersXPosition.get(name)).getCellType() + "]");
log.info(" Value [" + row.getCell(headersXPosition.get(name)).getStringCellValue() + "]");
}
}
Map<String, String> recordsErrorMap = validateRecordsXRow(recordsXRow);
if (!recordsErrorMap.isEmpty()) {
if (recordsErrorMap.size() != fileHeaders.length){
recordsRowErrorMap.put(rowNumber + 1, recordsErrorMap);
} else {
Map<String, String> rowErrorResult = new HashMap<>();
rowErrorResult.put("ROW.NULL", "ROW.DATA.NULL");
recordsRowErrorMap.put(rowNumber, rowErrorResult);
}
}
rowNumber++;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.CONTENT_ERROR);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
//@HU: Proceder a guardar en BD el archivo subido
result.setStatus(ValidationStatusEnum.OK);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(file.getOriginalFilename());
questionFileBD.setSize(file.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(fileData);
questionFileBD = questionFileRepository.save(questionFileBD);
response.setId(questionFileBD.getId());
response.setUuid(questionFileBD.getUuid());
response.setFileName(questionFileBD.getName());
response.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
response.setUploadDate(getUploadDate(questionFileBD.getUploadDate()));
response.setFileValidationResult(result);
return response;
}
private String getUploadDate(LocalDateTime uploadDate) {
if (uploadDate != null) {
return uploadDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}
return null;
}
public FileValidationResponse validateCsv(String uuid, MultipartFile file) throws IOException{
FileValidationResponse response = new FileValidationResponse();
FileValidationResult result = new FileValidationResult();
List<List<String>> rows = new ArrayList<>();
try {
String line;
InputStream is = file.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> headerErrorMap = new HashMap<>();
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
int rowData = 1;
while ((line = br.readLine()) != null) {
List<String> row = new ArrayList<>();
String[] data = line.split(";");
if (data.length <= 1) {
headerErrorMap.put("FORMAT.SEPARATION", "ERROR.SEPARATION.FORMAT");
}
if (data.length < fileHeaders.length) {
Map<String, String> recordsErrorMap = new HashMap<>();
recordsErrorMap.put(ValidationStatusEnum.DATA_INCOMPLETE.getName(), "DATA.INCOMPLETE");
recordsRowErrorMap.put(rowData, recordsErrorMap);
}
for (String dato : data) {
if (validateData(dato)) {
headerErrorMap.put("FORMAT.DATA", "WRONG.DATA.INCORRECT");
}
row.add(dato);
}
rowData++;
rows.add(row);
}
if(!headerErrorMap.isEmpty()) {
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.FORMAT_INCORRECT);
response.setFileValidationResult(result);
return response;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.DATA_INCOMPLETE);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
List<String> headersList = new ArrayList<>();
for (String header: rows.get(0)) {
headersList.add(header.replace('"', ' '));
}
headerErrorMap = validateHeaders(headersList);
if (!headerErrorMap.isEmpty()) {
result.setHeadersErrorMap(headerErrorMap);
result.setStatus(ValidationStatusEnum.HEADER_ERROR);
response.setFileValidationResult(result);
return response;
}
rows.remove(0);
} catch (IOException e) {
System.err.println(e.getMessage());
}
int rowNumber = 0;
Map<Integer, Object> recordsRowErrorMap = new HashMap<>();
for (List<String> item: rows) {
Map<String, Object> recordsXRow = new HashMap<>();
Map<String, String> recordsErrorMap = validateRecordsXRow(recordsXRow);
if (!recordsErrorMap.isEmpty()) {
if (recordsErrorMap.size() != fileHeaders.length){
recordsRowErrorMap.put(rowNumber + 1, recordsErrorMap);
}
}
rowNumber++;
}
if (!recordsRowErrorMap.isEmpty()) {
log.info("Hay errores en el contenido del archivo: " + recordsRowErrorMap);
result.setStatus(ValidationStatusEnum.CONTENT_ERROR);
result.setRecordsErrorMap(recordsRowErrorMap);
response.setFileValidationResult(result);
return response;
}
result.setStatus(ValidationStatusEnum.OK);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(file.getOriginalFilename());
questionFileBD.setSize(file.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(file.getBytes());
questionFileBD = questionFileRepository.save(questionFileBD);
response.setId(questionFileBD.getId());
response.setUuid(questionFileBD.getUuid());
response.setFileName(questionFileBD.getName());
response.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
response.setUploadDate(getUploadDate(questionFileBD.getUploadDate()));
response.setFileValidationResult(result);
return response;
}
private boolean validateData (String data) {
if (data.charAt(0) == '"' && data.charAt(data.length()-1) == '"') {
return false;
}
return true;
}
private Map<String, String> validateHeaders(List<String> headersList) {
Map<String, Integer> headerOcurrencesMap = new HashMap<>();
Map<String, String> headerErrorMap = new HashMap<>();
Map<String, Integer> headerOrganized = new HashMap<>();
int index = 0;
for (String fileHeader : fileHeaders) {
String keyHeader = fileHeader.toUpperCase().trim();
if (headerOcurrencesMap.get(keyHeader) == null) {
headerOcurrencesMap.put(keyHeader, 0);
}
for (String header : headersList) {
if (header.toUpperCase().trim().equals(keyHeader)) {
int ocurrences = headerOcurrencesMap.get(keyHeader);
headerOcurrencesMap.put(keyHeader, ocurrences + 1);
headerOrganized.put(keyHeader, index);
}
index++;
}
index = 0;
}
for (String keyHeader : headerOcurrencesMap.keySet()) {
int ocurrences = headerOcurrencesMap.get(keyHeader);
if (ocurrences == 0) {
headerErrorMap.put(keyHeader, "HEADER.NOT.FOUND");
} else if (ocurrences >= 1) {
if (ocurrences > 1){
headerErrorMap.put(keyHeader, "HEADER.REPETEAD");
} else if (!keyHeader.equalsIgnoreCase(fileHeaders[headerOrganized.get(keyHeader)])) {
headerErrorMap.put(keyHeader, "HEADER.NOT.ORGANIZED");
}
}
index ++;
}
return headerErrorMap;
}
private Map<String, String> validateRecordsXRow(Map<String, Object> recordsXRow) {
Map<String, String> recordsErrorMap = new HashMap<>();
for (String headerName : recordsXRow.keySet()) {
String keyHeader = headerName.toUpperCase().trim();
if (!isFileHeader(keyHeader)) {
continue;
}
if (recordsErrorMap.get(keyHeader) != null) {
continue;
}
if (recordsXRow.get(headerName) == null) {
recordsErrorMap.put(keyHeader, "NOT.FOUND.VALUE");
} else {
Object recordRowValue = recordsXRow.get(headerName);
if (recordRowValue instanceof String) {
String record = (String) recordRowValue;
if (record.trim().equals("")) {
recordsErrorMap.put(keyHeader, "EMPTY.VALUE");
}
}
}
}
return recordsErrorMap;
}
private boolean isFileHeader(String keyHeader) {
boolean isFileHeader = false;
for (String fileHeader : fileHeaders) {
if (keyHeader.equals(fileHeader.toUpperCase().trim())) {
isFileHeader = true;
break;
}
}
return isFileHeader;
}
@Transactional(propagation = Propagation.REQUIRED)
public void deleteGoalForAction(Long id) {
Optional<QuestionFile> file = questionFileRepository.findById(id);
if (!file.isPresent()) {
throw new NotFoundException("File no econtrado.");
}
questionFileRepository.delete(file.get());
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.AirportDto;
import com.bytesw.bytebot.dto.FlightDto;
import com.bytesw.bytebot.model.Airport;
import com.bytesw.bytebot.model.FlightSchedule;
import com.bytesw.bytebot.repository.IFlightRepository;
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;
@Service
@Transactional
public class FlightService extends XDFService<FlightSchedule, FlightDto, Long> {
protected FlightService(IFlightRepository flightRepository) {
super(flightRepository);
}
@Autowired
private AirportService airportService;
@Override
protected FlightSchedule toModel(FlightSchedule flightSchedule, FlightDto flightDto) {
if(flightSchedule == null) {
flightSchedule = new FlightSchedule();
}
BeanUtils.copyProperties(flightDto, flightSchedule);
AirportDto airportDto = airportService.getById(flightDto.getCodeAirportOrigin());
AirportDto airportDto1 = airportService.getById(flightDto.getCodeAirportDestination());
flightSchedule.setCodeAirportOrigin(airportService.toModel(new Airport(), airportDto));
flightSchedule.setCodeAirportDestination(airportService.toModel(new Airport(), airportDto1));
return flightSchedule;
}
@Override
protected FlightDto toBean(FlightSchedule flightSchedule) {
FlightDto flightDto = new FlightDto();
BeanUtils.copyProperties(flightSchedule, flightDto);
flightDto.setCodeAirportOrigin(flightSchedule.getCodeAirportOrigin().getId());
flightDto.setCodeAirportOrigin(flightSchedule.getCodeAirportDestination().getId());
flightDto.setAirportOrigin(flightSchedule.getCodeAirportOrigin().getAirportCode());
flightDto.setAirportDestination(flightSchedule.getCodeAirportDestination().getAirportCode());
flightDto.setLegs(flightSchedule.getLegs());
return flightDto;
}
}
package com.bytesw.bytebot.service;
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()));
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.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, Map, 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, Map map) {
if (model == null) {
model = new Goal();
}
model.setId((Long) map.get("id"));
model.setIdentifier(String.valueOf(map.get("identifier")));
model.setAgenId((Long) map.get("agentId"));
return model;
}
@Override
protected Map toBean(Goal model) {
Map<String, Object> map = new HashMap<>();
map.put("id",model.getId());
map.put("identifier", model.getIdentifier());
map.put("agentId", model.getAgenId());
return map;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Map create(Map body) {
Goal goal = new Goal();
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
List<Object> actions = (List) body.get("actionList");
if (actions.isEmpty()) {
throw new NotFoundException("Debe poseer minimo un action.");
}
Long agenId = Long.valueOf(body.get("agentId").toString());
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
String ident = body.get("identifier").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(), actions);
return toBean(goal);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void delete(Long goalId) {
if (!goalRepository.existsById(goalId)){
throw new NotFoundException("Goal no registrado.");
}
goalForActionService.deleteGoalForAction(goalId);
goalRepository.deleteById(goalId);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Map update(Map 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");
}
List<Object> actions = (List) body.get("actionList");
if (actions.isEmpty()) {
throw new NotFoundException("Debe poseer minimo un action.");
}
Long agenId = Long.valueOf(body.get("agentId").toString());
String ident = body.get("identifier").toString();
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
Optional<Goal> goalOptional= goalRepository.findByAgentAndIdent(agenId, ident);
if (goalOptional.isPresent()) {
if (goalOptional.get().getId() != goalId) {
throw new AlreadyExistsException("Goal ya existe en la base de datos para el agente ingresado.");
}
}
Goal goal = new Goal();
goal.setId(goalId);
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.updateGoalForAction(goal.getId(), actions);
return toBean(goal);
}
@Override
public Map getById(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("id", goal.get().getId());
result.put("agentId", goal.get().getAgenId());
result.put("identifier", goal.get().getIdentifier());
result.put("actionList", listAction);
return result;
}
@Override
public List<Map> getAll(){
List<Map> result = new ArrayList<>();
List<Goal> list = (List<Goal>) goalRepository.findAll();
for (Goal goal: list) {
result.add(getById(goal.getId()));
}
return result;
}
}
\ No newline at end of file
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.BookingAgentDto;
import com.bytesw.bytebot.dto.ItineraryReservationDto;
import com.bytesw.bytebot.dto.PassengerDto;
import com.bytesw.bytebot.model.BookingAgent;
import com.bytesw.bytebot.model.ItineraryReservation;
import com.bytesw.bytebot.model.Passenger;
import com.bytesw.bytebot.repository.IItineraryReservationRepository;
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;
@Service
@Transactional
public class ItineraryReservationService extends XDFService<ItineraryReservation, ItineraryReservationDto, Long> {
protected ItineraryReservationService(IItineraryReservationRepository repository) {
super(repository);
}
@Autowired
private PassengerService passengerService;
@Autowired
private BookingAgentService bookingAgentService;
@Override
protected ItineraryReservation toModel(ItineraryReservation itineraryReservation, ItineraryReservationDto itineraryReservationDto) {
if (itineraryReservation == null) {
itineraryReservation = new ItineraryReservation();
}
BeanUtils.copyProperties(itineraryReservationDto, itineraryReservation);
PassengerDto passengerDto = passengerService.getById(itineraryReservationDto.getCodePassenger());
BookingAgentDto bookingAgentDto = bookingAgentService.getById(itineraryReservationDto.getCodeAgent());
itineraryReservation.setPassenger(passengerService.toModel(new Passenger(), passengerDto));
itineraryReservation.setAgent(bookingAgentService.toModel(new BookingAgent(), bookingAgentDto));
return itineraryReservation;
}
@Override
protected ItineraryReservationDto toBean(ItineraryReservation model) {
ItineraryReservationDto bean = new ItineraryReservationDto();
BeanUtils.copyProperties(model, bean);
bean.setCodePassenger(model.getPassenger().getId());
bean.setCodeAgent(model.getAgent().getId());
return bean;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.etl.utils.JsonUtils;
import com.bytesw.bytebot.http.FileValidationResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
@Service
@Log4j2
public class KnowledgeService {
@Value("${application.bucket.tenant}")
private String tenant;
@Value("${application.knowledge.url}")
private String url;
@Value("${application.bucket.version}")
private String version;
public boolean generate(FileValidationResponse response) throws IOException {
boolean result = false;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(String.format("%s/clients/%s/versions/%s", url, tenant, version));
String json = String.format("{\"filename_csv\": \"%s\", \"index_name\": \"%s\"}",response.getFileName(), response.getUuid());
StringEntity entity = new StringEntity(json);
try {
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = resp -> {
int status = resp.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entityRes = resp.getEntity();
return entityRes != null ? EntityUtils.toString(entityRes) : null;
} else {
throw new ClientProtocolException("Error inesperado: " + status);
}
};
String res = httpclient.execute(httppost, responseHandler);
String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
httpclient.close();
if (status.equals("success")){
result = true;
}
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}
public boolean delete(String uuid) {
boolean result = false;
try {
HttpDelete httpDelete = new HttpDelete(String.format("%s/clients/%s/indexes/%s/versions/%s", url, tenant, uuid, version));
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Error inesperado: " + status);
}
};
CloseableHttpClient httpclient = HttpClients.createDefault();
String res = httpclient.execute(httpDelete, responseHandler);
httpclient.close();
String status = (String) JsonUtils.getFieldFromJson(res, "$.message.status");
if (status.equals("success")){
result = true;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.AirportDto;
import com.bytesw.bytebot.dto.FlightDto;
import com.bytesw.bytebot.dto.LegDto;
import com.bytesw.bytebot.model.Airport;
import com.bytesw.bytebot.model.FlightSchedule;
import com.bytesw.bytebot.model.Leg;
import com.bytesw.bytebot.repository.ILegRepository;
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;
@Service
@Transactional
public class LegService extends XDFService<Leg, LegDto, Long> {
protected LegService(ILegRepository legRepository) {
super(legRepository);
}
@Autowired
private FlightService flightService;
@Autowired
private AirportService airportService;
@Override
protected Leg toModel(Leg leg, LegDto legDto) {
if (leg == null)
leg = new Leg();
BeanUtils.copyProperties(legDto, leg);
FlightDto flightDto = flightService.getById(legDto.getCodeFlight());
leg.setCodeFlight(flightService.toModel(new FlightSchedule(), flightDto));
AirportDto airportDto = airportService.getById(legDto.getCodeAirportOrigin());
AirportDto airportDto1 = airportService.getById(legDto.getCodeAirportDestination());
leg.setCodeAirportOrigin(airportService.toModel(new Airport(), airportDto));
leg.setCodeAirportDestination(airportService.toModel(new Airport(), airportDto1));
return leg;
}
@Override
protected LegDto toBean(Leg leg) {
LegDto legDto = new LegDto();
BeanUtils.copyProperties(leg, legDto);
legDto.setCodeAirportOrigin(leg.getCodeAirportOrigin().getId());
legDto.setCodeAirportDestination(leg.getCodeAirportDestination().getId());
legDto.setAirportOrigin(leg.getCodeAirportOrigin().getAirportCode());
legDto.setAirportDestination(leg.getCodeAirportDestination().getAirportCode());
return legDto;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.FileValidationResult;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.BdcControl;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.model.enums.StatusBcdEnum;
import com.bytesw.bytebot.repository.BdcControlRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Optional;
@Service
@Transactional
@Log4j2
public class OrquestadorService {
@Autowired
private FileManagementService fileManagementService;
@Autowired
private BucketService bucketService;
@Autowired
private BdcControlRepository bdcControlRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private KnowledgeService knowledgeService;
@Autowired
private BusinessParameterService businessParameterService;
@Value("${application.bucket.deployment}")
private String parameter;
public FileValidationResponse executeGenerateBCD(String uuid, MultipartFile file) {
BdcControl model = new BdcControl();
FileValidationResponse response = new FileValidationResponse();
boolean step = false;
try{
//Modo de despliegue
String modeDeployment = businessParameterService.getBusinessParameterForKey(parameter);
if (modeDeployment == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
//Valida y guarda en base de datos
response = fileManagementService.saveFile(uuid, file);
if(response.getFileValidationResult().getStatus().getName() != ValidationStatusEnum.OK.getName()) {
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
return response;
}
model.setUuid(response.getUuid());
model.setFileId(response.getId());
model.setFileName(response.getFileName());
model.setDate(response.getUploadDate());
model.setStatus(StatusBcdEnum.CARGADO.getName());
model = bdcControlRepository.save(model);
if (modeDeployment.equalsIgnoreCase("onCloud")) {
//Carga archivo a bucket
step = bucketService.generate(file.getBytes(), response);
if (!step) {
response.setMessage("NOT.FOUND.BUCKET");
throw new NotFoundException();
}
step = false;
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
}
//Generacion del modelo
step = knowledgeService.generate(response);
if (!step) {
response.setMessage("NOT.FOUND.KNOWLEDGE");
throw new NotFoundException();
}
response.setStatus(FrequentQuestionStatusEnum.CORRECTO.getName());
model.setStatus(StatusBcdEnum.INDEXADO.getName());
model = bdcControlRepository.save(model);
}catch (Exception e) {
if (response.getMessage() == null) {
response.setMessage("ERROR.UPLOAD");
}
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
}
return response;
}
public FileValidationResponse retry(String uuid) {
Optional<BdcControl> modelBdc = bdcControlRepository.findByUuid(uuid);
if (!modelBdc.isPresent()) {
throw new NotFoundException("NOT.FOUND.DATA.CONTROL");
}
boolean step = false;
BdcControl model = modelBdc.get();
FileValidationResponse response = modelToFileValidation(model);
try {
String modeDeployment = businessParameterService.getBusinessParameterForKey(parameter);
if (modeDeployment == null) {
response.setMessage("NOT.FOUND.BUSINESS.PARAMETER");
throw new NotFoundException();
}
if (model.getStatus().equals(StatusBcdEnum.CARGADO.getName())) {
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (!questionFile.isPresent()) {
response.setMessage("NOT.FOUND.DATA");
throw new NotFoundException();
}
if (modeDeployment.equalsIgnoreCase("onCloud")) {
step = bucketService.generate(questionFile.get().getData(), response);
if (!step) {
response.setMessage("NOT.FOUND.BUCKET");
throw new NotFoundException();
}
}
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
step = false;
}
if (model.getStatus().equals(StatusBcdEnum.INDEXANDO.getName())) {
step = knowledgeService.generate(response);
if (!step) {
response.setMessage("NOT.FOUND.KNOWLEDGE");
throw new NotFoundException();
}
}
model.setStatus(StatusBcdEnum.INDEXADO.getName());
model = bdcControlRepository.save(model);
response.setStatus(FrequentQuestionStatusEnum.CORRECTO.getName());
} catch (Exception e) {
if (response.getMessage() == null) {
response.setMessage("ERROR.UPLOAD");
}
response.setStatus(FrequentQuestionStatusEnum.ERROR.getName());
}
return response;
}
public void deleteBcd(String uuid) {
Optional<BdcControl> bdcControl = bdcControlRepository.findByUuid(uuid);
if (!bdcControl.isPresent()) {
throw new NotFoundException();
}
BdcControl model = bdcControl.get();
if (model.getStatus().equals(StatusBcdEnum.INDEXADO.getName())) {
boolean step = knowledgeService.delete(uuid);
if (!step) {
throw new NotFoundException();
}
model.setStatus(StatusBcdEnum.INDEXANDO.getName());
model = bdcControlRepository.save(model);
}
if (model.getStatus().equals(StatusBcdEnum.INDEXANDO.getName())) {
bucketService.delete(uuid);
model.setStatus(StatusBcdEnum.CARGADO.getName());
model = bdcControlRepository.save(model);
}
Optional<QuestionFile> questionFile = questionFileRepository.findByUuid(uuid);
if (questionFile.isPresent()) {
questionFileRepository.deleteById(bdcControl.get().getFileId());
}
bdcControlRepository.delete(model);
}
private FileValidationResponse modelToFileValidation(BdcControl model){
FileValidationResponse response = new FileValidationResponse();
response.setId(model.getId());
response.setStatus(model.getStatus());
response.setUuid(model.getUuid());
response.setFileName(model.getFileName());
response.setUploadDate(model.getDate());
FileValidationResult result = new FileValidationResult();
result.setStatus(ValidationStatusEnum.OK);
response.setFileValidationResult(result);
return response;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.PassengerDto;
import com.bytesw.bytebot.model.Passenger;
import com.bytesw.bytebot.repository.IPassengerRepository;
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 PassengerService extends XDFService<Passenger, PassengerDto, Long> {
protected PassengerService(IPassengerRepository passengerRepository) {
super(passengerRepository);
}
@Override
protected Passenger toModel(Passenger passenger, PassengerDto passengerDto) {
if (passenger == null)
passenger = new Passenger();
BeanUtils.copyProperties(passengerDto, passenger);
return passenger;
}
@Override
protected PassengerDto toBean(Passenger passenger) {
PassengerDto passengerDto = new PassengerDto();
BeanUtils.copyProperties(passenger, passengerDto);
return passengerDto;
}
}
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.dto.PaymentDto;
import com.bytesw.bytebot.model.Payment;
import com.bytesw.bytebot.repository.IPaymentRepository;
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 PaymentService extends XDFService<Payment, PaymentDto, Long> {
protected PaymentService(IPaymentRepository paymentRepository) {
super(paymentRepository);
}
@Override
protected Payment toModel(Payment payment, PaymentDto paymentDto) {
if(payment == null) {
payment = new Payment();
}
BeanUtils.copyProperties(paymentDto, payment);
return payment;
}
@Override
protected PaymentDto toBean(Payment payment) {
PaymentDto paymentDto = new PaymentDto();
BeanUtils.copyProperties(payment, paymentDto);
return paymentDto;
}
}
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.etl.batch.service.ScheduleService;
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.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 java.math.BigInteger;
import java.util.*;
@Service
@Transactional
public class SchedulerTaskService extends XDFService<SchedulerTask, SchedulerTaskBean, BigInteger> {
@Autowired
private CalendarService CalendarService;
@Autowired
private CalendarRepository calendarRepository;
@Autowired
private SchedulerTaskRepository schedulerTaskRepository;
@Autowired
private ScheduleService scheduleService;
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()));
model.setProcessETL(bean.getEtlId());
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());
bean.setEtlId(model.getProcessETL());
// 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;
}
@Override
public SchedulerTaskBean create(SchedulerTaskBean schedulerTaskBean) {
SchedulerTask schedulerTask = new SchedulerTask();
schedulerTask = toModel(schedulerTask, schedulerTaskBean);
schedulerTask = schedulerTaskRepository.save(schedulerTask);
scheduleService.restartTask(schedulerTask);
return toBean(schedulerTask);
}
@Override
public SchedulerTaskBean update(SchedulerTaskBean bean, BigInteger id) {
Optional<SchedulerTask> model = schedulerTaskRepository.findById(id);
if (!model.isPresent()) {
throw new NotFoundException();
}
SchedulerTask schedulerTask = new SchedulerTask();
schedulerTask = toModel(schedulerTask, bean);
schedulerTask = schedulerTaskRepository.save(schedulerTask);
scheduleService.restartTask(schedulerTask);
return toBean(schedulerTask);
}
@Override
public void delete (BigInteger id) {
Optional<SchedulerTask> model = schedulerTaskRepository.findById(id);
if (!model.isPresent()) {
throw new NotFoundException();
}
scheduleService.cancelTask(model.get());
schedulerTaskRepository.deleteById(id);
}
}
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.setCalendarID(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;
}
}
package com.bytesw.bytebot.service;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
@Component("xlsToCsvFileConverter")
public class XlsToCsvFileConverter implements FileConverter {
private static final String FILE_EXTENSION = ".csv";
@Value("${application.service.file-converter.xls-to-csv.separator:$$}")
private String separator;
@Override
public byte[] convert(byte[] inputFile, String fileName) {
StringBuffer data = new StringBuffer();
InputStream fis = null;
Workbook workbook = null;
try {
//FileOutputStream fos = new FileOutputStream();
// Get the workbook object for XLSX file
fis = new ByteArrayInputStream(inputFile);
String ext = FilenameUtils.getExtension(fileName);
if (ext.equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (ext.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(fis);
}
// Get first sheet from the workbook
int numberOfSheets = workbook.getNumberOfSheets();
Row row;
Cell cell;
// Iterate through each rows from first sheet
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case BOOLEAN:
data.append(cell.getBooleanCellValue() + separator);
break;
case NUMERIC:
data.append(cell.getNumericCellValue() + separator);
break;
case STRING:
data.append(cell.getStringCellValue() + separator);
break;
case BLANK:
data.append("" + separator);
break;
default:
data.append(cell + separator);
}
}
data.setLength(data.length() - separator.length());
data.append('\n'); // appending new line after each row
}
}
return data.toString().getBytes();
//fos.write(data.toString().getBytes());
//fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (Exception e) {}
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {}
}
}
return new byte[]{};
}
@Override
public String getFileName(String fileName) {
int position = fileName.lastIndexOf(".");
String fileNameWithoutExtension = fileName.substring(0, position);
return fileNameWithoutExtension + FILE_EXTENSION;
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.*;
import com.bytesw.bytebot.jdbc.ActionJDBCRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.xdf.sql.beans.Pagination;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
@Service
public class CustomerInteractionDashboardService extends DashboardService {
@Autowired
private MessageJDBCRepository messageJDBCRepository;
@Autowired
private ActionJDBCRepository actionJDBCRepository;
@Override
protected void completeData(OffsetDateTime startDate, OffsetDateTime endDate, Integer rangeMinutes,Map<String, Object> info) {
List<RangeBean> rangeList = calculateRangeList(startDate, endDate);
info.put("sessionFlow", generateInteractionByCustomerData(startDate, endDate));
info.put("summaryGoals", generateSummaryByGoals(startDate, endDate));
info.put("intentAvgByCustomer", generateAverageIntentsByCustomer(rangeList));
info.put("summaryIntents", generateSummaryMessageByIntent(rangeList,startDate,endDate));
}
private List<ActionSummaryByGoalBean> generateSummaryByGoals(OffsetDateTime startDate, OffsetDateTime endDate) {
List<ActionSummaryByGoalBean> actionByGoalList;
actionByGoalList = actionJDBCRepository.getSummaryByGoals(startDate, endDate);
if (actionByGoalList == null) {
actionByGoalList = new ArrayList<>();
}
return actionByGoalList;
}
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<>();
rangeList.stream().forEach(x -> {
List<String> identifiers = new ArrayList<>();
List<MessageByIntentBean> list = messageJDBCRepository.countMessageByIntent(x.getStartDate(), x.getEndDate());
list.stream().forEach(intentSummary -> {
identifiers.add((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, 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;
}
private List<Object[]> generateAverageIntentsByCustomer(List<RangeBean> rangeList) {
List<Object[]> averageList = new ArrayList<>();
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());
if(avg!=null){
averageList.add(new Object[]{timestamp,avg});
}
});
return averageList;
}
private double round(Double value) {
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(2, RoundingMode.HALF_UP);
return bd.doubleValue();
}
private Map<String, Map<String, Object>> generateInteractionByCustomerData(OffsetDateTime startDate, OffsetDateTime endDate) {
Map<String, Map<String, Object>> data = new HashMap<>();
data.put("intent", new HashMap<>());
List<SummaryMessageByIntentBean> intentTopList = messageJDBCRepository.getSummaryByIntent(startDate, endDate);
int totalIntents = messageJDBCRepository.countByIntentAndRange(startDate, endDate);
if (intentTopList == null) {
new ArrayList<>();
}
BigInteger result = intentTopList.stream()
.map(SummaryMessageByIntentBean::getCount)
.reduce(BigInteger.ZERO, BigInteger::add);
SummaryMessageByIntentBean others = new SummaryMessageByIntentBean();
others.setCount(new BigInteger(String.valueOf(totalIntents)).subtract(result));
others.setId(0L);
others.setIdentifier("others");
if(others.getCount().intValue()>0){
intentTopList.add(others);
}
data.get("intent").put("total", totalIntents);
data.get("intent").put("topList", intentTopList);
List<SummaryMessageBySentenceBean> sentenceTopList = messageJDBCRepository.getSummaryBySentence(startDate, endDate);
int totalSentences = messageJDBCRepository.countBySentencesAndRange(startDate, endDate);
if (sentenceTopList == null) {
sentenceTopList = new ArrayList<>();
}
data.put("sentence", new HashMap<>());
BigInteger resultSentence = sentenceTopList.stream()
.map(SummaryMessageBySentenceBean::getCount)
.reduce(BigInteger.ZERO, BigInteger::add);
SummaryMessageBySentenceBean othersSentence = new SummaryMessageBySentenceBean();
othersSentence.setCount(new BigInteger(String.valueOf(totalSentences)).subtract(resultSentence));
othersSentence.setId(0L);
othersSentence.setIdentifier("others");
if(othersSentence.getCount().intValue()>0){
sentenceTopList.add(othersSentence);
}
data.get("sentence").put("topList", sentenceTopList);
data.get("sentence").put("total", totalSentences);
return data;
}
public void getSummaryByIntentAndSentencePagination(Pagination<SummaryMessageBySentenceBean> pagination) {
int total = messageJDBCRepository.countSummaryByIntentAndSentence(pagination);
int totalPages = total / pagination.getItemsPerPage();
if (total % pagination.getItemsPerPage() != 0) {
totalPages++;
}
pagination.setTotalItems(total);
pagination.setTotalPages(totalPages);
List<SummaryMessageBySentenceBean> list = messageJDBCRepository.getSummaryByIntentAndSentence(pagination);
list.stream().forEach(x -> {
int customers = messageJDBCRepository.countCustomersBySentence(x.getSentence());
x.setCustomerCount(BigInteger.valueOf(customers));
});
pagination.setData(list);
}
public void getSummaryBySentencePagination(Pagination<SummaryMessageBySentenceBean> pagination) {
int total = messageJDBCRepository.countSummaryBySentence(pagination);
int totalPages = total / pagination.getItemsPerPage();
if (total % pagination.getItemsPerPage() != 0) {
totalPages++;
}
pagination.setTotalItems(total);
pagination.setTotalPages(totalPages);
List<SummaryMessageBySentenceBean> list = messageJDBCRepository.getMessageBySentencePage(pagination);
pagination.setData(list);
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.RangeBean;
import lombok.extern.log4j.Log4j2;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Log4j2
public abstract class DashboardService {
abstract void completeData(OffsetDateTime startDate, OffsetDateTime endDate,
Integer rangeMinutes, Map<String, Object> info);
public Map<String, Object> generateInfo(Map<String, Object> params) {
Map<String, Object> info = new HashMap<>();
log.info(params);
if (params == null) {
return info;
}
OffsetDateTime startDate = convertToOffsetDatetime((String) params.get("startDate"));
OffsetDateTime endDate = convertToOffsetDatetime((String) params.get("endDate"));
Integer rangeMinutes = (Integer)params.get("rangeMinutes");
if (startDate == null || endDate == null) {
return info;
}
this.completeData(startDate, endDate, rangeMinutes, info);
return info;
}
protected OffsetDateTime convertToOffsetDatetime(String date) {
if (date.length() == 24) {
date = date.substring(0, date.length() - 1);
}
OffsetDateTime dateOffset = null;
try {
LocalDateTime dateParsed = LocalDateTime.parse(date);
dateOffset = OffsetDateTime.ofInstant(dateParsed.toInstant(ZoneOffset.UTC), ZoneId.systemDefault());
} catch (Exception e) {
log.warn(e);
}
return dateOffset;
}
protected OffsetDateTime getNextHour(OffsetDateTime date) {
OffsetDateTime nextDate = date.plusHours(1);
nextDate = nextDate.withMinute(0);
nextDate = nextDate.withSecond(0);
nextDate = nextDate.withNano(0);
return nextDate;
}
protected OffsetDateTime getNextDay(OffsetDateTime date) {
OffsetDateTime newDate = date.plusDays(1);
newDate = newDate.withSecond(0);
newDate = newDate.withMinute(0);
newDate = newDate.withHour(0);
newDate = newDate.withNano(0);
return newDate;
}
protected OffsetDateTime getDayOnStart(OffsetDateTime date) {
OffsetDateTime nextDate = date.withHour(12);
nextDate = nextDate.withMinute(0);
nextDate = nextDate.withSecond(0);
nextDate = nextDate.withNano(0);
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) {
OffsetDateTime nextDate = getNextDay(startDate);
OffsetDateTime startNextDate = startDate;
List<RangeBean> rangeList = new ArrayList<>();
while (nextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(nextDate);
rangeList.add(rangeBean);
startNextDate = nextDate;
nextDate = getNextDay(nextDate);
}
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
return rangeList;
}
}
package com.bytesw.bytebot.service.dashboard;
import com.bytesw.bytebot.bean.AverageBean;
import com.bytesw.bytebot.bean.RangeBean;
import com.bytesw.bytebot.bean.SummaryBean;
import com.bytesw.bytebot.bean.SessionByClientBean;
import com.bytesw.bytebot.jdbc.BotSessionJDCBRepository;
import com.bytesw.bytebot.jdbc.MessageJDBCRepository;
import com.bytesw.bytebot.jdbc.ResponseJDBCRepository;
import com.bytesw.xdf.exception.NotFoundException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bytesw.bytebot.model.enums.MetricMessageTypeEnum;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.*;
import java.util.*;
@Log4j2
@Service
public class OperativeDashboardService extends DashboardService {
@Autowired
private BotSessionJDCBRepository botSessionJDCBRepository;
@Autowired
private MessageJDBCRepository messageJDBCRepository;
@Autowired
private ResponseJDBCRepository responseJDBCRepository;
@Override
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> rangeMinutsList = calculateMinutesRangeList(startDate, endDate, rangeMinutes);
List<Object[]> messageByActivity = generateData(rangeList);
//Cantidad de sesiones
List<Object[]> sessions = generateDataVariablePeriod(rangeMinutsList, MetricMessageTypeEnum.SESSION.getName());
int totalSessions = botSessionJDCBRepository.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
Object avgFRObject = botSessionJDCBRepository.getAvgFirstResponseTime(startDate, endDate);
Double avgFirstResponse;
if (avgFRObject instanceof Long) {
avgFirstResponse = new Double((Long) avgFRObject);
} else {
avgFirstResponse = (Double) avgFRObject;
}
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);
if (timestamp == null) {
throw new NotFoundException("No se encontró una sesión en el rango de fechas indicado");
}
//Calculando el tiempo de inactividad de la sesion
OffsetDateTime lastSessionDate = OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault());
Duration difference = Duration.between(lastSessionDate, endDate);
// Adjuntando tiempo de inactividad
SummaryBean sessionInactivity = new SummaryBean();
BigInteger value = new BigInteger(String.valueOf(difference.getSeconds()));
sessionInactivity.setValue(value);
// Adjutando las sesiones totales
Map<String,Object> totalSession = new HashMap<>();
totalSession.put("value",totalSessions);
totalSession.put("history",sessions);
// Adjuntamos los mensajes recibidos
Map<String, Object> recivedMessage = new HashMap<>();
recivedMessage.put("value", totalrecivedMessages);
recivedMessage.put("history", recivedMessages);
// Adjuntamos los mensajes enviados
Map<String, Object> responseMessage = new HashMap<>();
responseMessage.put("value", totalresponseMessages);
responseMessage.put("history", responseMessages);
Map<String, Object> summary = new HashMap<>();
summary.put("sessionInactivity", sessionInactivity);
summary.put("totalSessions", totalSession);
summary.put("totalSentMessages", responseMessage);
summary.put("totalReceivedMessages", recivedMessage);
AverageBean averageBean = new AverageBean();
if (avgFirstResponse == null) {
averageBean.setFirstResponseAverage(new BigDecimal(0));
} else {
averageBean.setFirstResponseAverage(new BigDecimal(avgFirstResponse));
}
averageBean.setSessionAverage(new BigDecimal(avgSessionsByCustomer));
info.put("summary", summary);
info.put("averages", averageBean);
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) {
List<Object[]> data = new ArrayList<>();
Map<Long, Map<Integer, Integer>> accumulated = new HashMap<>();
for (RangeBean range : rangeList) {
List<RangeBean> hourRanges = getRangeHours(range.getStartDate(), range.getEndDate());
for (RangeBean hourRange : hourRanges) {
int cant = messageJDBCRepository.countMessageInRangeHour(hourRange.getStartDate(), hourRange.getEndDate());
int rangeHour = getRangeHour(hourRange.getStartDate().getHour());
Long timestamp = getTimestamp(hourRange.getStartDate());
if (!accumulated.containsKey(timestamp)) {
accumulated.put(timestamp, new HashMap<>());
}
if (!accumulated.get(timestamp).containsKey(rangeHour)) {
accumulated.get(timestamp).put(rangeHour, 0);
}
accumulated.get(timestamp).put(rangeHour, accumulated.get(timestamp).get(rangeHour) + cant);
}
}
accumulated.keySet().stream().forEach(x -> {
accumulated.get(x).keySet().stream().forEach(y -> {
data.add(new Object[]{x, y, accumulated.get(x).get(y)});
});
});
return data;
}
private int getRangeHour(int hour) {
switch (hour) {
case 3:
case 4:
case 5:
return 1;
case 6:
case 7:
case 8:
return 2;
case 9:
case 10:
case 11:
return 3;
case 12:
case 13:
case 14:
return 4;
case 15:
case 16:
case 17:
return 5;
case 18:
case 19:
case 20:
return 6;
case 21:
case 22:
case 23:
return 7;
default:
return 0;
}
}
private long getTimestamp(OffsetDateTime date) {
OffsetDateTime dateTime;
dateTime = date.withHour(0);
dateTime = dateTime.withMinute(0);
dateTime = dateTime.withSecond(0);
dateTime = dateTime.withNano(0);
return dateTime.toInstant().toEpochMilli();
}
private List<RangeBean> getRangeHours(OffsetDateTime startDate, OffsetDateTime endDate) {
OffsetDateTime nextDate = getNextHour(startDate);
OffsetDateTime startNextDate = startDate;
List<RangeBean> rangeList = new ArrayList<>();
while (nextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(nextDate);
rangeList.add(rangeBean);
startNextDate = nextDate;
nextDate = getNextHour(nextDate);
}
if (startNextDate.isBefore(endDate)) {
RangeBean rangeBean = new RangeBean();
rangeBean.setStartDate(startNextDate);
rangeBean.setEndDate(endDate);
rangeList.add(rangeBean);
}
return rangeList;
}
}
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());
}
}
}
...@@ -5,7 +5,7 @@ server: ...@@ -5,7 +5,7 @@ server:
port: ${APPLICATION_PORT:9077} port: ${APPLICATION_PORT:9077}
web: web:
#static-content-location: file:/home/mgutierrez/Documentos/Bytesw/bytebot-workspace/dist/bytebot-html/ #static-content-location: file:/home/mgutierrez/Documentos/Bytesw/bytebot-workspace/dist/bytebot-html/
static-content-location: file:/home/mgutierrez/Descargas/dist-2022-2/dist/bytebot-html/ static-content-location: file:/home/jponte/capacitacion/capacitacion-front/capacitacion2/plantilla/ejercicio2-framework/dist/bytebot-html/
security: security:
...@@ -55,7 +55,7 @@ application: ...@@ -55,7 +55,7 @@ application:
multi-tenant-conf: multi-tenant-conf:
exclude-service: / exclude-service: /
authorization-service.url: http://localhost:17580 authorization-service.url: http://localhost:17580
security: oauth2sso #none, basic, oauth2sso security: none #none, basic, oauth2sso
security.method: true security.method: true
security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot security-exclude: /service/oauth/userinfo, /actuator/**, /mylogout, /login, /logout, /goodbye, /error, /anon, /cache.manifest, /favicon.ico, /service/file, /goodbye /byteboot
messaging: messaging:
...@@ -118,9 +118,9 @@ spring: ...@@ -118,9 +118,9 @@ spring:
datasource: datasource:
database-type: postgres database-type: postgres
schemaName: avb schemaName: avb_hdi
url: jdbc:postgresql://192.168.0.119:5432/bytebot?useSSL=false&currentSchema=avb_hdi url: jdbc:postgresql://192.168.18.181:5432/bytebot?useSSL=false&currentSchema=avb_hdi #jdbc:mysql://bytebot-db:3306/bytebot?useSSL=false
driverClassName: 'org.postgresql.Driver' driverClassName: 'org.postgresql.Driver' # 'com.mysql.cj.jdbc.Driver'
username: postgres username: postgres
password: postgres password: postgres
minimum-idle: 10 minimum-idle: 10
...@@ -135,18 +135,18 @@ spring: ...@@ -135,18 +135,18 @@ spring:
oauth2-client: oauth2-client:
clientId: xdf-client clientId: xdf-client
clientSecret: xdf-secret clientSecret: xdf-secret
accessTokenUri: http://192.168.0.119:18080/oauth/token accessTokenUri: http://192.168.18.181:18080/oauth/token
userAuthorizationUri: http://192.168.0.119:18080/oauth/authorize userAuthorizationUri: http://192.168.18.181:18080/oauth/authorize
oauth2-resource: oauth2-resource:
userInfoUri: http://192.168.0.119:18080/oauth/userinfo userInfoUri: http://192.168.18.181:18080/oauth/userinfo
logoutUri: http://192.168.0.119:18080/oauth/userlogout logoutUri: http://192.168.18.181:18080/oauth/userlogout
tenants: tenants:
- -
id: T186A1 id: T186A1
servername: prueba_avb servername: prueba_avb
datasource: datasource:
database-type: postgres database-type: postgres
schemaName: avb schemaName: avb_hdi
url: jdbc:postgresql://192.168.0.119:5432/bytebot?useSSL=false&currentSchema=avb_hdi url: jdbc:postgresql://192.168.0.119:5432/bytebot?useSSL=false&currentSchema=avb_hdi
driverClassName: 'org.postgresql.Driver' driverClassName: 'org.postgresql.Driver'
username: postgres username: postgres
......
<?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.ActionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal
FROM AVB_ACTION_SESSION BAS
JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID;
</select>
</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>
<?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.MessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<!-- @TODO Pendiente agregar la fecha -->
<select id="getSummaryByIntentAndSentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
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
ORDER BY ${columnSort} ${directionSort} LIMIT ${initLimit},${itemsForPage}
</select>
<select id="countSummaryByIntentAndSentence" resultType="int" flushCache="true">
select count(*) FROM (SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
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
ORDER BY count DESC) as AVB_SUMMARY
</select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4
</select>
<select id="getSummaryBySentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY ${columnSort} ${directionSort}, identifier DESC LIMIT ${initLimit},${itemsForPage}
</select>
<select id="countSummaryBySentence" resultType="int" flushCache="true">
SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select>
<select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT
COUNT(M.MESSA_ID)
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
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT
COUNT(MESSA_ID)
FROM AVB_MESSAGE WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="avgIntentsByCustomerAndRange" resultType="Double" flushCache="true">
SELECT AVG (COUNT_MESSA) FROM
(
SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID
FROM AVB_MESSAGE M
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}
GROUP BY S.USER_ID
) AVB_INTENT_CUSTOMER
</select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT
COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
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}
GROUP BY I.INTEN_IDENT
</select>
<select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID)
FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select>
</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.ResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID)
FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select>
</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.SessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT
FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate}
ORDER BY SESSION_LEDAT DESC LIMIT 1
</select>
<select id="countSessionsInRange" resultType="int" flushCache="true">
select count(session_id) from avb_session
WHERE SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
</select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM
(
select count(USER_ID) as SESSION_CANT
from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID
) AVB_SESSION_COUNT
</select>
<select id="avgFirstResponseTime" resultType="Long" flushCache="true">
SELECT AVG(RESP_TIME)
FROM (
select TIMESTAMPDIFF(MICROSECOND, SESSION_DATE, SESSION_FRDAT)/1000 AS RESP_TIME
from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT NULL
AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF
</select>
</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.ActionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getSummaryActionsByGoal" resultType="ActionSummaryByGoal" flushCache="true">
SELECT COUNT(BAS.ASESS_ID) as count,
G.GOAL_IDENT as goal
FROM AVB_ACTION_SESSION BAS
JOIN AVB_ACTION A ON BAS.ACTION_ID = A.ACTION_ID
JOIN avb_GoalForActions GFA ON GFA.action_id=A.action_id
JOIN AVB_GOAL G ON G.GOAL_ID = GFA.GOAL_ID
WHERE BAS.ASESS_DATE &lt;= #{endDate} AND BAS.ASESS_DATE &gt;= #{startDate}
GROUP BY G.GOAL_ID;
</select>
</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>
<?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.MessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countMessagesInRangeForHour" resultType="int" flushCache="true">
SELECT COUNT(MESSA_ID)
FROM AVB_MESSAGE
WHERE MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<!-- @TODO Pendiente agregar la fecha -->
<select id="getSummaryByIntentAndSentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
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
ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit}
</select>
<select id="countSummaryByIntentAndSentence" resultType="int" flushCache="true">
select count(*) FROM (SELECT
DISTINCT(MESSA_CONT) as sentence,
COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
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
ORDER BY count DESC) as AVB_SUMMARY
</select>
<select id="getSummaryByIntent" resultType="SummaryMessageByIntent" flushCache="true">
SELECT COUNT(MESSA_ID) AS count,
I.INTEN_IDENT as identifier,
I.INTEN_ID as id
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 M.INTEN_ID IS NOT NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
AND ABKP.inten_id IS NULL
GROUP BY I.INTEN_ID
ORDER BY count DESC LIMIT 4
</select>
<select id="getSummaryBySentence" resultType="SummaryMessageBySentence" flushCache="true">
SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY ${columnSort} ${directionSort} LIMIT ${itemsForPage} OFFSET ${initLimit}
</select>
<select id="countSummaryBySentence" resultType="int" flushCache="true">
SELECT count(*) FROM (SELECT
COUNT(MESSA_ID) as count,
MESSA_CONT as identifier
FROM AVB_MESSAGE M
WHERE INTEN_ID IS NULL
AND M.MESSA_DATE &lt;= #{endDate} AND M.MESSA_DATE &gt;= #{startDate}
GROUP BY MESSA_CONT
ORDER BY count DESC, identifier DESC) as AVB_SUMMARY
</select>
<select id="countByIntentAndRange" resultType="int" flushCache="true">
SELECT
COUNT(M.MESSA_ID)
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 M.INTEN_ID IS NOT NULL
and abkp.inten_id is null
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="countBySentencesAndRange" resultType="int" flushCache="true">
SELECT
COUNT(MESSA_ID)
FROM AVB_MESSAGE WHERE INTEN_ID IS NULL
AND MESSA_DATE &lt;= #{endDate} AND MESSA_DATE &gt;= #{startDate}
</select>
<select id="avgIntentsByCustomerAndRange" resultType="Double" flushCache="true">
SELECT AVG (COUNT_MESSA) FROM
(
SELECT COUNT(MESSA_ID) as COUNT_MESSA,
S.USER_ID
FROM AVB_MESSAGE M
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}
GROUP BY S.USER_ID
) AVB_INTENT_CUSTOMER
</select>
<select id="countMessageByIntent" resultType="MessageByIntent" flushCache="true">
SELECT
COUNT(M.MESSA_ID) as count,
I.INTEN_IDENT as identifier
FROM AVB_MESSAGE M
LEFT JOIN AVB_INTENT I
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}
GROUP BY I.INTEN_IDENT
</select>
<select id="countCustomersBySentence" resultType="int" flushCache="true">
SELECT COUNT(distinct USER_ID)
FROM AVB_SESSION
WHERE SESSION_ID in (select DISTINCT SESSION_ID from AVB_MESSAGE bm WHERE MESSA_CONT = #{sentence})
</select>
</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.ResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="countMessagesInRange" resultType="int" flushCache="true">
SELECT COUNT(RESPO_ID)
FROM AVB_RESPONSE
WHERE RESPO_DATE &lt;= #{endDate} AND RESPO_DATE &gt;= #{startDate}
</select>
</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.SessionMapper">
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastDateInRange" resultType="java.sql.Timestamp" flushCache="true">
select SESSION_LEDAT
FROM AVB_SESSION bas
WHERE SESSION_LEDAT &lt;= #{endDate}
AND SESSION_LEDAT &gt;= #{startDate}
ORDER BY SESSION_LEDAT DESC LIMIT 1
</select>
<select id="countSessionsInRange" resultType="int" flushCache="true">
select count(session_id) from avb_session
WHERE SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
</select>
<select id="avgSessionsByCustomerInRange" resultType="Double" flushCache="true">
select avg(SESSION_CANT) FROM
(
select count(USER_ID) as SESSION_CANT
from AVB_SESSION bas
WHERE SESSION_DATE &lt;= #{endDate} AND SESSION_DATE &gt;= #{startDate} GROUP BY USER_ID
) AVB_SESSION_COUNT
</select>
<select id="avgFirstResponseTime" resultType="Double" flushCache="true">
SELECT AVG(RESP_TIME)
FROM (
SELECT DATE_PART('milliseconds', SESSION_FRDAT - SESSION_DATE) AS RESP_TIME
from AVB_SESSION bs WHERE SESSION_FRDAT IS NOT null
AND SESSION_DATE &lt;= #{endDate}
AND SESSION_DATE &gt;= #{startDate}
) RESPONSE_DIF
</select>
</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="getAgentChannelByAgentId" 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} and AG.agen_id = #{agentId}
</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>
<?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.ETLMessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT
MESSA_CORRE
FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative
</select>
</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.ETLResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT IFNULL( (SELECT
RESPO_CORR
FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative
</select>
</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.ETLSessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastSessionByUser" resultType="Session" flushCache="true">
SELECT
SESSION_ID as id,
SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate,
chan_id as channelId,
USER_ID as userId
FROM AVB_SESSION
WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC
LIMIT 1
</select>
<update id="updateLastEventDate" flushCache="true">
UPDATE
AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID}
</update>
</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="getAgentChannelByAgentId" 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} and AG.agen_id = #{agentId}
</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>
<?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.ETLMessageMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT
MESSA_CORRE
FROM AVB_MESSAGE
WHERE SESSION_ID = ${sessionId}
ORDER BY MESSA_CORRE DESC
LIMIT 1) ,0) as correlative
</select>
</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.ETLResponseMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastCorrelativeBySession" resultType="int" flushCache="true">
SELECT coalesce( (SELECT
RESPO_CORR
FROM AVB_RESPONSE
WHERE SESSION_ID = ${sessionId}
ORDER BY RESPO_CORR DESC
LIMIT 1) ,0) as correlative
</select>
</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.ETLSessionMapper" >
<!-- In Config XML file -->
<cache readOnly="true"></cache>
<select id="getLastSessionByUser" resultType="Session" flushCache="true">
SELECT
SESSION_ID as id,
SESSION_DATE as sessionDate,
SESSION_LEDAT as lastEventDate,
SESSION_FRDAT as responseDate,
chan_id as channelId,
USER_ID as userId
FROM AVB_SESSION
WHERE USER_ID = ${userId}
ORDER BY SESSION_DATE DESC
LIMIT 1
</select>
<update id="updateLastEventDate" flushCache="true">
UPDATE
AVB_SESSION SET
SESSION_LEDAT = ${lastEventDate}
WHERE SESSION_ID = ${sessionID}
</update>
</mapper>
...@@ -6,31 +6,11 @@ ...@@ -6,31 +6,11 @@
<configuration> <configuration>
<properties resource="mybatis.properties" /> <properties resource="mybatis.properties" />
<typeAliases> <typeAliases>
<typeAlias type="com.bytesw.bytebot.bean.SummaryMessageByIntentBean" alias="SummaryMessageByIntent"/>
<typeAlias type="com.bytesw.bytebot.bean.SummaryMessageBySentenceBean" alias="SummaryMessageBySentence"/>
<typeAlias type="com.bytesw.bytebot.bean.ActionSummaryByGoalBean" alias="ActionSummaryByGoal"/>
<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.batch.beans.DeleteDataSensBean" alias="ChannelByAgent"/>
<typeAlias type="com.bytesw.bytebot.etl.batch.beans.DeleteDataSensControlBean" alias="DeleteControl"/>
</typeAliases> </typeAliases>
<mappers> <mappers>
<mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/> <mapper resource="config/mappers/xdf/${database-type-xdf}/AuditMapper.xml"/>
<mapper resource="config/mappers/bytebot/${database-type-xdf}/SessionMapper.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}/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}/MessageMapper.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>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.service.AgentService;
import com.bytesw.bytebot.service.FileManagementService;
import com.bytesw.xdf.config.security.annotation.DummyPermissionEvaluator;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Hernán Uriarte Melchor
* @date 14/09/2020.
* <p>
* <p>
* Copyright (c) 2018 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.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebMvcTest(controllers = AgentController.class)
@ActiveProfiles(value = "test")
@AutoConfigureMockMvc(secure = false)
public class AgentControllerTest {
public static String baseService = "/service/agent";
@TestConfiguration
static class UserServiceTestContextConfiguration {
@Bean
DummyPermissionEvaluator dummyPermissionEvaluator() {
return new DummyPermissionEvaluator();
}
}
@Autowired
private MockMvc mvc;
@MockBean
private AgentService agentService;
@MockBean
private FileManagementService fileManagementService;
@Before
public void setUp() {
}
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void uploadFile_whenFileXLS_isOK() throws Exception {
MockMultipartFile xlsFile = new MockMultipartFile(
"file",
"my-xls-file.xls",
"application/vnd.ms-excel",
"my-xls-file".getBytes());
Mockito.when(fileManagementService.validateAndSaveFile(anyString(), eq(xlsFile) ))
.thenReturn(new FileValidationResponse());
mvc.perform(MockMvcRequestBuilders.multipart(baseService + "/file-upload")
.file(xlsFile))
.andExpect(status().isOk());
}
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void uploadFile_whenFileXLSNotAppropriate_throwException() throws Exception {
MockMultipartFile xlsFile = new MockMultipartFile("file", "my-xls-file.xls", "application/vnd.ms-excel",
"my-xls-file".getBytes());
Mockito.when(fileManagementService.validateAndSaveFile(anyString(), eq(xlsFile) ))
.thenThrow(IOException.class);
mvc.perform(MockMvcRequestBuilders.multipart(baseService + "/file-upload")
.file(xlsFile))
.andExpect(status().isInternalServerError());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.bean.ChannelBean;
import com.bytesw.bytebot.bean.CountryBean;
import com.bytesw.bytebot.bean.DeploymentChannelBean;
import com.bytesw.bytebot.bean.DeploymentChannelParamValueBean;
import com.bytesw.bytebot.bean.FrequentQuestionBean;
import com.bytesw.bytebot.model.Agent;
import com.bytesw.bytebot.model.Channel;
import com.bytesw.bytebot.model.ChannelParam;
import com.bytesw.bytebot.model.Country;
import com.bytesw.bytebot.model.DeploymentChannel;
import com.bytesw.bytebot.model.DeploymentChannelParamValue;
import com.bytesw.bytebot.model.FrequentQuestion;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.model.enums.AgentStatusEnum;
import com.bytesw.bytebot.model.enums.AgentTypeEnum;
import com.bytesw.bytebot.model.enums.FrequentQuestionStatusEnum;
import com.bytesw.bytebot.model.enums.LanguageEnum;
import com.bytesw.bytebot.model.enums.StatusEnum;
import com.bytesw.bytebot.repository.AgentRepository;
import com.bytesw.bytebot.repository.ChannelParamRepository;
import com.bytesw.bytebot.repository.ChannelRepository;
import com.bytesw.bytebot.repository.CountryRepository;
import com.bytesw.bytebot.repository.DeploymentChannelParamValueRepository;
import com.bytesw.bytebot.repository.DeploymentChannelRepository;
import com.bytesw.bytebot.repository.FrequentQuestionRepository;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import com.bytesw.xdf.sql.beans.Pagination;
import com.bytesw.xdf.sql.beans.SortField;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.apache.camel.ProducerTemplate;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Hernán Uriarte Melchor
* @version 14/09/18.
* <p>
* <p>
* Copyright (c) 2018 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.
*/
@RunWith(SpringRunner.class)
public class AgentServiceTest {
@TestConfiguration
static class AgentServiceTestContextConfiguration {
@MockBean
private AgentRepository agentRepository;
@MockBean
private CountryRepository countryRepository;
@MockBean
private DeploymentChannelRepository deploymentChannelRepository;
@MockBean
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@MockBean
private ChannelRepository channelRepository;
@MockBean
private ChannelParamRepository channelParamRepository;
@MockBean
private FrequentQuestionRepository frequentQuestionRepository;
@MockBean
private QuestionFileRepository questionFileRepository;
@MockBean
private ProducerTemplate producerTemplate;
@Bean
public AgentService agentService() {
return new AgentService();
}
}
@Autowired
private AgentService agentService;
@Autowired
private ChannelRepository channelRepository;
@Autowired
private CountryRepository countryRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private FrequentQuestionRepository frequentQuestionRepository;
@Autowired
private QuestionFileRepository questionFileRepository;
@Autowired
private ProducerTemplate producerTemplate;
@Autowired
private DeploymentChannelRepository deploymentChannelRepository;
@Autowired
private DeploymentChannelParamValueRepository deploymentChannelParamValueRepository;
@Autowired
private ChannelParamRepository channelParamRepository;
@Before
public void setUp() {
}
@Test
public void searchByPagination_whenThereAreNotSortField_isOK(){
Pagination<AgentBean> pagination = new Pagination<>();
pagination.setItemsPerPage(20);
pagination.setCurrentPage(1);
List<Agent> listOfAgents = new ArrayList<>();
Country countryPeru = new Country();
countryPeru.setId(1L);
countryPeru.setName("PERU");
Agent agentA = new Agent();
agentA.setId(1L);
agentA.setName("BYTEBOT");
agentA.setVersion("1.0.0");
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentA.setTimezone("GMT-5");
agentA.setAvatar("bytebot.png");
agentA.setCountry(countryPeru);
Agent agentB = new Agent();
agentB.setId(1L);
agentB.setName("BFMBOT");
agentB.setVersion("2.0.0");
agentB.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentB.setTimezone("GMT-5");
agentB.setAvatar("bfmbot.png");
agentB.setCountry(countryPeru);
listOfAgents.add(agentA);
listOfAgents.add(agentB);
Page<Agent> page = new PageImpl<>(listOfAgents);
Mockito.when(agentRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(page);
agentService.searchByPagination(pagination);
}
@Test
public void searchByPagination_whenThereAreResults_isOK(){
Pagination<AgentBean> pagination = new Pagination<>();
pagination.setItemsPerPage(20);
pagination.setCurrentPage(1);
SortField[] orderFields = new SortField[1];
SortField sortFieldA = new SortField();
sortFieldA.setDirection("asc");
sortFieldA.setField("id");
orderFields[0] = sortFieldA;
pagination.setSortFields(orderFields);
List<Agent> listOfAgents = new ArrayList<>();
Country countryPeru = new Country();
countryPeru.setId(1L);
countryPeru.setName("PERU");
Agent agentA = new Agent();
agentA.setId(1L);
agentA.setName("BYTEBOT");
agentA.setVersion("1.0.0");
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentA.setTimezone("GMT-5");
agentA.setAvatar("bytebot.png");
agentA.setCountry(countryPeru);
Agent agentB = new Agent();
agentB.setId(1L);
agentB.setName("BFMBOT");
agentB.setVersion("2.0.0");
agentB.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
agentB.setTimezone("GMT-5");
agentB.setAvatar("bfmbot.png");
agentB.setCountry(countryPeru);
listOfAgents.add(agentA);
listOfAgents.add(agentB);
Page<Agent> page = new PageImpl<>(listOfAgents);
Mockito.when(agentRepository.findAll(any(Specification.class), any(Pageable.class)))
.thenReturn(page);
agentService.searchByPagination(pagination);
}
@Test
public void save_whenAgentExists_OK() {
Long idAgente = 1L;
Long idCountry = 1L;
Long idFrequentQuestion = 1L;
Agent agentBD = new Agent();
agentBD.setId(idAgente);
agentBD.setName("BOT-1");
agentBD.setDescription("BOT BASICO DE PREGUNTAS");
agentBD.setVersion("0.0.1");
agentBD.setLanguage(LanguageEnum.SPANISH);
agentBD.setTimezone("GMT-5");
agentBD.setType(AgentTypeEnum.FREQUENT_QUESTION);
agentBD.setStatus(AgentStatusEnum.CREATED);
agentBD.setAvatar("avatar-png");
Country countryA = new Country();
countryA.setId(idCountry);
countryA.setName("Perú");
agentBD.setCountry(countryA);
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idFrequentQuestion);
frequentQuestionA.setDescription("Preguntas de entrenamiento");
frequentQuestionA.setUser("lortiz");
frequentQuestionA.setFilename("preguntas-base-old.xls");
frequentQuestionA.setUploadDate(LocalDateTime.now());
frequentQuestionA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestions.add(frequentQuestionA);
agentBD.setFrequentQuestions(frequentQuestions);
List<DeploymentChannel> deploymentChannels = new ArrayList<>();
DeploymentChannel deploymentChannelA = new DeploymentChannel();
deploymentChannelA.setId(1L);
deploymentChannelA.setName("FACEBOOK");
deploymentChannelA.setStatus(StatusEnum.ACTIVE);
Channel channelA = new Channel();
channelA.setId(1L);
channelA.setName("FACEBOOK");
deploymentChannelA.setChannel(channelA);
List<DeploymentChannelParamValue> parameters = new ArrayList<>();
ChannelParam channelParamA = new ChannelParam();
channelParamA.setId(1L);
channelParamA.setName("token");
DeploymentChannelParamValue parameterA = new DeploymentChannelParamValue();
parameterA.setId(1L);
parameterA.setValue("facebook-abc");
parameterA.setParameter(channelParamA);
DeploymentChannelParamValue parameterB = new DeploymentChannelParamValue();
parameterB.setId(2L);
parameterB.setValue("https://facebook....");
parameters.add(parameterA);
parameters.add(parameterB);
deploymentChannelA.setParameters(parameters);
DeploymentChannel deploymentChannelB = new DeploymentChannel();
deploymentChannelB.setId(2L);
deploymentChannelB.setName("WHATSAPP");
deploymentChannelB.setStatus(StatusEnum.INACTIVE);
deploymentChannelB.setParameters(new ArrayList<>());
deploymentChannels.add(deploymentChannelA);
deploymentChannels.add(deploymentChannelB);
agentBD.setDeploymentChannels(deploymentChannels);
// Agent Data Bean
AgentBean agentBeanA = new AgentBean();
agentBeanA.setId(idAgente);
agentBeanA.setName("BOT-AGENT");
agentBeanA.setDescription("BOT AVANZADO DE PREGUNTAS");
agentBeanA.setVersion("2.0.0");
agentBeanA.setLanguage(LanguageEnum.SPANISH.getName());
agentBeanA.setTimezone("GMT-5");
agentBeanA.setType(AgentTypeEnum.FREQUENT_QUESTION.getName());
agentBeanA.setStatus(AgentStatusEnum.CREATED.getName());
agentBeanA.setAvatar("avatar-BOT.png");
agentBeanA.setCountryId(countryA.getId());
agentBeanA.setCountryName(countryA.getName());
agentBeanA.setFrequentQuestions(new ArrayList<>());
FrequentQuestionBean frequentQuestionBeanA = new FrequentQuestionBean();
frequentQuestionBeanA.setId(idFrequentQuestion);
frequentQuestionBeanA.setUuid("");
frequentQuestionBeanA.setDescription("Database Principal");
frequentQuestionBeanA.setUser("lortiz");
frequentQuestionBeanA.setFilename("preguntas-advanced.xls");
frequentQuestionBeanA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
agentBeanA.getFrequentQuestions().add(frequentQuestionBeanA);
FrequentQuestionBean frequentQuestionBeanB = new FrequentQuestionBean();
//frequentQuestionBeanB.setId(12L);
frequentQuestionBeanB.setUuid("");
frequentQuestionBeanB.setDescription("Database Secundaria");
frequentQuestionBeanB.setUser("lortiz");
frequentQuestionBeanB.setFilename("preguntas-advanced-TIGO.xls");
frequentQuestionBeanB.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED.getName());
agentBeanA.getFrequentQuestions().add(frequentQuestionBeanB);
agentBeanA.setDeploymentChannels(new ArrayList<>());
DeploymentChannelBean deploymentChannelBeanA = new DeploymentChannelBean();
deploymentChannelBeanA.setId(1L);
deploymentChannelBeanA.setName("FACEBOOK");
deploymentChannelBeanA.setStatus(StatusEnum.ACTIVE.getName());
deploymentChannelBeanA.setChannelId(channelA.getId());
deploymentChannelBeanA.setChannelName(channelA.getName());
deploymentChannelBeanA.setParameters(new ArrayList<>());
DeploymentChannelParamValueBean deploymentChannelParamValueBeanA = new DeploymentChannelParamValueBean();
deploymentChannelParamValueBeanA.setId(1L);
deploymentChannelParamValueBeanA.setValue("facebook-botbyte");
deploymentChannelParamValueBeanA.setChannelParamName(channelParamA.getName());
deploymentChannelBeanA.getParameters().add(deploymentChannelParamValueBeanA);
agentBeanA.getDeploymentChannels().add(deploymentChannelBeanA);
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(agentBD));
Mockito.when(countryRepository.findById(idCountry))
.thenReturn(Optional.ofNullable(countryA));
Mockito.when(frequentQuestionRepository.findById(idFrequentQuestion))
.thenReturn(Optional.ofNullable(frequentQuestionA));
Mockito.when(agentRepository.save(any(Agent.class)))
.thenReturn(agentBD);
Mockito.when(deploymentChannelRepository.findById(1L))
.thenReturn(Optional.ofNullable(deploymentChannelA));
Mockito.when(channelRepository.findById(1L))
.thenReturn(Optional.ofNullable(channelA));
Mockito.when(deploymentChannelParamValueRepository.findById(1L))
.thenReturn(Optional.ofNullable(parameterA));
Mockito.when(channelParamRepository.findByNameAndChannelId(channelParamA.getName(), channelA.getId()))
.thenReturn(Optional.ofNullable(channelParamA));
agentService.save(agentBeanA);
}
@Test
public void getAgent_whenAgentNotExists_OK() {
Long idAgente = 1L;
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(null));
AgentBean agentBean = agentService.getAgent(idAgente);
assertThat(agentBean).isNull();
}
@Test
public void getAgent_whenAgentExists_OK() {
Long idAgente = 1L;
Long idCountry = 1L;
Long idFrequentQuestion = 1L;
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setName("BOT-1");
agentA.setDescription("BOT BASICO DE PREGUNTAS");
agentA.setVersion("0.0.1");
agentA.setLanguage(LanguageEnum.SPANISH);
agentA.setTimezone("GMT-5");
agentA.setType(AgentTypeEnum.FREQUENT_QUESTION);
agentA.setStatus(AgentStatusEnum.CREATED);
agentA.setAvatar("avatar-png");
Country countryA = new Country();
countryA.setId(idCountry);
countryA.setName("Perú");
agentA.setCountry(countryA);
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idFrequentQuestion);
frequentQuestionA.setDescription("Preguntas de entrenamiento");
frequentQuestionA.setUser("lortiz");
frequentQuestionA.setFilename("preguntas-base-old.xls");
frequentQuestionA.setUploadDate(LocalDateTime.now());
frequentQuestionA.setStatus(FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED);
frequentQuestions.add(frequentQuestionA);
agentA.setFrequentQuestions(frequentQuestions);
List<DeploymentChannel> deploymentChannels = new ArrayList<>();
DeploymentChannel deploymentChannelA = new DeploymentChannel();
deploymentChannelA.setId(1L);
deploymentChannelA.setName("FACEBOOK");
deploymentChannelA.setStatus(StatusEnum.ACTIVE);
Channel channelA = new Channel();
channelA.setId(1L);
channelA.setName("FACEBOOK");
deploymentChannelA.setChannel(channelA);
List<DeploymentChannelParamValue> parameters = new ArrayList<>();
ChannelParam channelParamA = new ChannelParam();
channelParamA.setName("token");
DeploymentChannelParamValue parameterA = new DeploymentChannelParamValue();
parameterA.setId(1L);
parameterA.setValue("facebook-abc");
parameterA.setParameter(channelParamA);
DeploymentChannelParamValue parameterB = new DeploymentChannelParamValue();
parameterB.setId(2L);
parameterB.setValue("https://facebook....");
parameters.add(parameterA);
parameters.add(parameterB);
deploymentChannelA.setParameters(parameters);
DeploymentChannel deploymentChannelB = new DeploymentChannel();
deploymentChannelB.setId(2L);
deploymentChannelB.setName("WHATSAPP");
deploymentChannelB.setStatus(StatusEnum.INACTIVE);
deploymentChannelB.setParameters(new ArrayList<>());
deploymentChannels.add(deploymentChannelA);
deploymentChannels.add(deploymentChannelB);
agentA.setDeploymentChannels(deploymentChannels);
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
AgentBean agentBean = agentService.getAgent(idAgente);
assertThat(agentBean.getId()).isEqualTo(idAgente);
}
@Test
public void delete_whenAgentExists_OK() {
Long idAgente = 1L;
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
Mockito.when(agentRepository.save(any(Agent.class))).thenReturn(agentA);
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void delete_whenAgentNotExists_OK() {
Long idAgente = null;
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void delete_whenAgentNotExistsById_OK() {
Long idAgente = 1L;
Agent agentA = null;
Mockito.when(agentRepository.findById(idAgente)).thenReturn(Optional.ofNullable(agentA));
boolean isValid = agentService.delete(idAgente);
assertThat(isValid).isEqualTo(Boolean.TRUE);
}
@Test
public void getCountries_whenCountries_areOK() {
List<Country> countries = new ArrayList<>();
Country countryA = new Country();
Country countryB = new Country();
countries.add(countryA);
countries.add(countryB);
Mockito.when(countryRepository.findAll()).thenReturn(countries);
List<CountryBean> countriesBeanList = agentService.getCountries();
assertThat(countriesBeanList.size()).isEqualTo(2);
}
@Test
public void getChannels_whenChannels_areOK() {
List<Channel> channels = new ArrayList<>();
Channel channelA = new Channel();
Channel channelB = new Channel();
channels.add(channelA);
channels.add(channelB);
Mockito.when(channelRepository.findAll()).thenReturn(channels);
List<ChannelBean> channelsBeanList = agentService.getChannels();
assertThat(channelsBeanList.size()).isEqualTo(2);
}
@Test
public void synchronizeFiles_whenQuestionFileIsNotPresent_OK() {
Long idAgente = 1L;
String user = "lortiz";
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idAgente);
frequentQuestionA.setUuid(uuid);
frequentQuestions.add(frequentQuestionA);
Agent agentA = new Agent();
agentA.setId(idAgente);
agentA.setStatus(AgentStatusEnum.PENDING_SYNCHRONIZED);
Mockito.when(frequentQuestionRepository.findAllByAgentIdAndStatus(idAgente, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED))
.thenReturn(frequentQuestions);
Mockito.when(questionFileRepository.findByUuid(uuid))
.thenReturn(Optional.ofNullable(null));
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(agentA));
agentService.synchronizeFiles(idAgente, user);
//@HU como validar un void method
}
@Test
public void synchronizeFiles_whenQuestionFileIsPresentButNotAgent_OK() {
Long idAgente = 1L;
String user = "lortiz";
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
List<FrequentQuestion> frequentQuestions = new ArrayList<>();
FrequentQuestion frequentQuestionA = new FrequentQuestion();
frequentQuestionA.setId(idAgente);
frequentQuestionA.setUuid(uuid);
frequentQuestions.add(frequentQuestionA);
QuestionFile questionFileA = new QuestionFile();
questionFileA.setName("preguntas-basicas-old");
Mockito.when(frequentQuestionRepository.findAllByAgentIdAndStatus(idAgente, FrequentQuestionStatusEnum.PENDING_SYNCHRONIZED))
.thenReturn(frequentQuestions);
Mockito.when(questionFileRepository.findByUuid(uuid))
.thenReturn(Optional.ofNullable(questionFileA));
Mockito.when(agentRepository.findById(idAgente))
.thenReturn(Optional.ofNullable(null));
agentService.synchronizeFiles(idAgente, user);
//@HU como validar un void method
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bytesw.bytebot.service;
import com.bytesw.bytebot.http.FileValidationResponse;
import com.bytesw.bytebot.http.enums.ValidationStatusEnum;
import com.bytesw.bytebot.model.QuestionFile;
import com.bytesw.bytebot.repository.QuestionFileRepository;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import static org.assertj.core.api.Java6Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.ArgumentMatchers.any;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Hernán Uriarte Melchor
* @version 14/09/18.
* <p>
* <p>
* Copyright (c) 2018 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.
*/
@RunWith(SpringRunner.class)
public class FileManagementServiceTest {
@TestConfiguration
static class UserServiceTestContextConfiguration {
@MockBean
private QuestionFileRepository questionFileRepository;
@Bean
public FileManagementService fileManagementService() {
return new FileManagementService();
}
}
@Autowired
private FileManagementService fileManagementService;
@Autowired
private QuestionFileRepository questionFileRepository;
@Before
public void setUp() {
}
@Test
public void validateAndSaveFile_whenFileHasInvalidExtension_SimpleError() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-columna-doble-columna.xls");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileHeadersRepetead = new MockMultipartFile(
"preguntas-ejemplo-sin-columna-doble-columna.xml",
"preguntas-ejemplo-sin-columna-doble-columna.xml",
MediaType.APPLICATION_XML_VALUE,
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileHeadersRepetead);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.INCOMPATIBLE_EXTENSION);
}
@Test
public void validateAndSaveFile_whenFileHasHeaderRepetead_ErrorWithDetails() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-columna-doble-columna.xls");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileHeadersRepetead = new MockMultipartFile(
"preguntas-ejemplo-sin-columna-doble-columna.xls",
"preguntas-ejemplo-sin-columna-doble-columna.xls",
"application/vnd.ms-excel",
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileHeadersRepetead);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.HEADER_ERROR);
}
@Test
public void validateAndSaveFile_whenFileHasBadContent_ErrorWithDetails() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFileBadContent = new MockMultipartFile(
"preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx",
"preguntas-ejemplo-sin-contenido-espacios-blanco.xlsx",
"application/vnd.ms-excel",
inputData);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFileBadContent);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.CONTENT_ERROR);
}
@Test
public void validateAndSaveFile_whenFileIsCorrect_thenIsSaved() throws IOException {
InputStream inputData = new FileInputStream("src/test/resources/data/preguntas-ejemplo-base.xlsx");
String uuid = "1f59cb41-778a-46f6-acfc-3625108275bb";
MultipartFile xlsFile = new MockMultipartFile(
"preguntas-ejemplo-base.xlsx",
"preguntas-ejemplo-base.xlsx",
"application/vnd.ms-excel",
inputData);
QuestionFile questionFileBD = new QuestionFile();
questionFileBD.setUuid(uuid);
questionFileBD.setName(xlsFile.getOriginalFilename());
questionFileBD.setSize(xlsFile.getSize());
questionFileBD.setUploadDate(LocalDateTime.now());
questionFileBD.setData(xlsFile.getBytes());
Mockito.when(questionFileRepository.save(any(QuestionFile.class)))
.thenReturn(questionFileBD);
FileValidationResponse response = fileManagementService.validateAndSaveFile(uuid, xlsFile);
assertThat(response.getFileValidationResult().getStatus())
.isEqualTo(ValidationStatusEnum.OK);
}
}
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