Commit d87369f6 authored by Roberto Loayza's avatar Roberto Loayza

Requerimiento GoalForAction

 - Create
 - Update
 - Delete
parent f337d2c1
package com.bytesw.bytebot.controller;
import com.bytesw.bytebot.bean.AgentBean;
import com.bytesw.bytebot.etl.beans.GoalBean;
import com.bytesw.bytebot.service.GoalService;
import com.bytesw.xdf.annotation.ProgramSecurity;
import com.bytesw.xdf.controller.XDFController;
import com.bytesw.xdf.sql.beans.Pagination;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController()
@RequestMapping("/service/settings/goal")
@ProgramSecurity("GOAL")
@Log4j2
public class GoalController extends XDFController<GoalBean, String> {
@Autowired
private GoalService goalService;
public GoalController(GoalService service) {
super(service);
}
@PostMapping(value = "/goalForAction")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> createGoalForAction(@RequestBody Map<String, Object> body) {
GoalBean info = goalService.save(body);
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
}
@DeleteMapping(value = "/goalForAction/{id}")
@PreAuthorize("hasPermission(this, 'view')")
public ResponseEntity<String> GoalForAction(@ApiParam(value = "id", required = true) @PathVariable("id") Long id) {
String info = "";
try{
goalService.delete(id);
info = id.toString();
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
} catch (Exception e) {
info = e.getMessage();
}
return new ResponseEntity(gson.toJson(info), HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping(value = "/goalForAction/{id}")
@PreAuthorize("hasPermission(this, 'edit')")
public ResponseEntity<String> updateConversationalAgent(@PathVariable("id") Long id,
@RequestBody Map<String, Object> body) {
String info = "";
try{
goalService.updateGoalForActions(body, id);
return new ResponseEntity(gson.toJson(info), HttpStatus.OK);
} catch (Exception e) {
info = e.getMessage();
}
return new ResponseEntity(gson.toJson(info), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
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);
}
}
...@@ -45,7 +45,6 @@ import org.springframework.scheduling.support.CronTrigger; ...@@ -45,7 +45,6 @@ import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.Duration; import java.time.Duration;
import java.sql.Timestamp;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.*; import java.util.*;
......
...@@ -58,26 +58,19 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio ...@@ -58,26 +58,19 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio
@Override @Override
@Transactional @Transactional
public void write(List<? extends DynaBean> list) throws Exception { public void write(List<? extends DynaBean> list) throws Exception {
/* JSON de prueba */
//String jsonPrueba = "{\"telefonos_desplegados\":[{\"CodigoInternacional\": \"1415\",\"numero\": \"5238886\"},{\"CodigoInternacional\": \"51\",\"numero\": \"456789\"},{\"CodigoInternacional\": \"51\", \"numero\": \"456789\"}]}";
//agent.setChannelValue(jsonPrueba);
//-------
Object numeros = JsonUtils.getFieldFromJson(agent.getChannelValue(), "$.telefonos_desplegados"); Object numeros = JsonUtils.getFieldFromJson(agent.getChannelValue(), "$.telefonos_desplegados");
List<String> numerosAgentes = numbersAgent((List<Map>) numeros); List<String> numerosAgentes = numbersAgent((List<Map>) numeros);
//*------
for (DynaBean dynaBean : list) { for (DynaBean dynaBean : list) {
Long id = Long.parseLong(dynaBean.get("id").toString()); Long id = Long.parseLong(dynaBean.get("id").toString());
String json = (String) dynaBean.get("data"); String json = (String) dynaBean.get("data");
String event = (String) JsonUtils.getFieldFromJson(json, "$.event"); String event = (String) JsonUtils.getFieldFromJson(json, "$.event");
String sender_id; String sender_id;
boolean update_control = false; boolean update_control = false;
// Transform present Date
String presentDate = OffsetDateTime.now().toString().replace('T', ' '); String presentDate = OffsetDateTime.now().toString().replace('T', ' ');
String timeZone = presentDate.substring(presentDate.length() - 6); String timeZone = presentDate.substring(presentDate.length() - 6);
presentDate = presentDate.replace(timeZone, ""); presentDate = presentDate.replace(timeZone, "");
if (EventTypeEnum.USER.getName().equals(event)) { if (EventTypeEnum.USER.getName().equals(event)) {
String toAgent = (String) JsonUtils.getFieldFromJson(json, "$.metadata.To"); String toAgent = (String) JsonUtils.getFieldFromJson(json, "$.metadata.To");
//*------------
String agentNumber = new String(); String agentNumber = new String();
if (toAgent == null) { if (toAgent == null) {
continue; continue;
...@@ -85,9 +78,7 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio ...@@ -85,9 +78,7 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio
if (toAgent.isEmpty()) { if (toAgent.isEmpty()) {
agentNumber = toAgent.split(":")[1]; agentNumber = toAgent.split(":")[1];
} }
//*------------
if (numerosAgentes.contains(agentNumber)) { if (numerosAgentes.contains(agentNumber)) {
// if (agent.getChannelValue().equals(toAgent)) {
String intent = (String) JsonUtils.getFieldFromJson(json, "$.parse_data.intent.name"); String intent = (String) JsonUtils.getFieldFromJson(json, "$.parse_data.intent.name");
if (intentByAgent.contains(intent)) { if (intentByAgent.contains(intent)) {
String SmSMessageSid = (String) JsonUtils.getFieldFromJson(json, "$.metadata.SmsMessageSid"); String SmSMessageSid = (String) JsonUtils.getFieldFromJson(json, "$.metadata.SmsMessageSid");
...@@ -148,7 +139,6 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio ...@@ -148,7 +139,6 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio
} }
} }
//-------
private List<String> numbersAgent(List<Map> listNumber){ private List<String> numbersAgent(List<Map> listNumber){
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
for (Map map : listNumber){ for (Map map : listNumber){
...@@ -159,7 +149,6 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio ...@@ -159,7 +149,6 @@ public class DataSensibleJPAWriter implements ItemWriter<DynaBean>, StepExecutio
} }
return result; return result;
} }
//-------
@Override @Override
public void beforeStep(StepExecution stepExecution) { public void beforeStep(StepExecution stepExecution) {
......
...@@ -14,7 +14,7 @@ public class GoalBean { ...@@ -14,7 +14,7 @@ public class GoalBean {
private Long id; private Long id;
@Expose @Expose
private String ident; private String identifier;
@Expose @Expose
private Long agenId; private Long agenId;
......
package com.bytesw.bytebot.etl.beans;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class GoalForActionsBean {
@Expose
private Long id;
@Expose
private Long goalId;
@Expose
private Long actionId;
}
package com.bytesw.bytebot.etl.dao; package com.bytesw.bytebot.etl.dao;
import com.bytesw.bytebot.etl.model.Action; import com.bytesw.bytebot.etl.model.Action;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional; import java.util.Optional;
......
package com.bytesw.bytebot.etl.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
@Cacheable(false)
@Entity
@Getter
@Setter
@ToString
@Table(name = "avb_GoalForActions")
@NamedQuery(name = "GoalForActions.findByPK", query = "Select p from GoalForActions p where p.id = ?1")
public class GoalForActions {
@Id
@Column(name = "gfac_id")
@TableGenerator(name = "AVB_GOALFORACTIONS_GENERATOR", table = "SEQUENCE_TABLE", pkColumnName = "SEQ_NAME",
valueColumnName = "SEQ_COUNT", pkColumnValue = "AVB_GOALFORACTIONS_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "AVB_GOALFORACTIONS_GENERATOR")
private Long id;
@Column(name = "goal_id")
private Long goalId;
@Column(name = "action_id")
private Long actionId;
}
package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.Action;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
public interface ActionRepository extends CrudRepository<Action, Long>, JpaSpecificationExecutor<Action> {
}
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);
}
...@@ -2,7 +2,15 @@ package com.bytesw.bytebot.repository; ...@@ -2,7 +2,15 @@ package com.bytesw.bytebot.repository;
import com.bytesw.bytebot.etl.model.Goal; import com.bytesw.bytebot.etl.model.Goal;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 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.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface GoalRepository extends CrudRepository<Goal, Long>, JpaSpecificationExecutor<Goal> { 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.service;
import com.bytesw.bytebot.etl.beans.GoalForActionsBean;
import com.bytesw.bytebot.etl.dao.ActionRepository;
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 save(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 delete(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 update(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);
}
}
}
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.List;
import java.util.Map;
import java.util.Optional;
@Service
@Transactional
@Log4j2
public class GoalService extends XDFService<Goal, GoalBean, Long> {
@Autowired
private GoalRepository goalRepository;
@Autowired
private GoalForActionsRepository goalForActionsRepository;
@Autowired
private AgentRepository agentRepository;
@Autowired
private GoalForActionService goalForActionService;
protected GoalService(GoalRepository repository) {
super(repository);
}
@Override
protected Goal toModel(Goal model, GoalBean bean) {
if (model == null) {
model = new Goal();
}
BeanUtils.copyProperties(bean, model);
return model;
}
@Override
protected GoalBean toBean(Goal model) {
GoalBean bean = new GoalBean();
BeanUtils.copyProperties(model, bean);
return bean;
}
@Transactional(propagation = Propagation.REQUIRED)
public GoalBean save(Map<String, Object> body) {
Goal goal = new Goal();
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
Long agenId = Long.valueOf(body.get("AgentId").toString());
String ident = body.get("Ident").toString();
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
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.save(goal.getId(), (List) body.get("actionList"));
return toBean(goal);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void delete(Long goalId) {
if (!goalRepository.existsById(goalId)){
throw new NotFoundException("Goal no registrado.");
}
goalForActionService.delete(goalId);
goalRepository.deleteById(goalId);
}
@Transactional(propagation = Propagation.REQUIRED)
public void updateGoalForActions(Map<String, Object> body, Long goalId) {
if (body.isEmpty()) {
throw new NotFoundException("No se encuentran parametros.");
}
if (!goalRepository.existsById(goalId)) {
throw new NotFoundException("Goal no se encuenta registrado");
}
Long agenId = Long.valueOf(body.get("AgentId").toString());
String ident = body.get("Ident").toString();
if (!agentRepository.existsById(agenId)) {
throw new NotFoundException("Agente no registrado.");
}
Goal goal = new Goal();
goal.setId(goalId);
goal.setAgenId(agenId);
goal.setIdentifier(ident);
goal = goalRepository.save(goal);
goalForActionService.update(goal.getId(), (List) body.get("actionList"));
}
}
\ No newline at end of file
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