feat: chat-rct

feature/issue-14/chatrct
Frédérik Benoist 2024-02-20 00:14:11 +01:00
parent 851a927265
commit ea076d2383
7 changed files with 444 additions and 13 deletions

View File

@ -0,0 +1,16 @@
meta {
name: PromptActions
type: http
seq: 5
}
get {
url: {{host}}/hdpos/api/chatrct/actions?itemId=XY10000-08-3A&produitId=3700824
body: none
auth: none
}
query {
itemId: XY10000-08-3A
produitId: 3700824
}

View File

@ -5,7 +5,11 @@ meta {
}
get {
url: {{host}}/hdpos/api/chatrct/rct/XY10000-08-3A
url: {{host}}/hdpos/api/chatrct/rct?itemId=XY10000-08-3A
body: none
auth: none
}
query {
itemId: XY10000-08-3A
}

View File

@ -0,0 +1,18 @@
meta {
name: PromptStore
type: http
seq: 4
}
get {
url: {{host}}/hdpos/api/chatrct/store/4?storeId=4&distributorId=1&itemId=XY10000-08-3A&produitId=3700824
body: none
auth: none
}
query {
storeId: 4
distributorId: 1
itemId: XY10000-08-3A
produitId: 3700824
}

View File

@ -0,0 +1,24 @@
meta {
name: RctForceCache
type: http
seq: 6
}
put {
url: {{host}}/hdpos/api/chatrct/rct/forceCache
body: json
auth: none
}
body:json {
{
"itemId": "XY10000",
"comment": "Test FRED"
}
}
body:form-urlencoded {
itemId: 9999999
comment: test
}

View File

@ -0,0 +1,27 @@
meta {
name: RctForceException
type: http
seq: 7
}
put {
url: {{host}}/hdpos/api/chatrct/rct/forceException
body: json
auth: none
}
body:json {
{
"id_produit":3700821,
"id_distrib":1,
"fdate":"20241220",
"forcer_cache":1,
"modul_trait":"HDPOS"
}
}
body:form-urlencoded {
itemId: 9999999
comment: test
}

View File

@ -3,10 +3,20 @@ package com.example.services;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@ -32,9 +42,9 @@ public class ChatRctService {
}
@GET
@Path("/rct/{itemId}")
@Path("/rct")
@Produces(MediaType.APPLICATION_JSON)
public Response getRctById(@PathParam("itemId") String itemId) {
public Response getRctById(@QueryParam("itemId") String itemId) {
if (itemId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"itemId parameter is required\"}").build();
@ -61,8 +71,11 @@ public class ChatRctService {
Clob resultClob = callableStatement.getClob(2);
String result = resultClob.getSubString(1, (int) resultClob.length());
// Convert Unicode representations to emojis
String resultWithEmojis = convertUnicodeStrsToEmojis(result);
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(result);
String jsonResponse = objectMapper.writeValueAsString(resultWithEmojis);
return Response.ok(jsonResponse).build();
}
@ -80,9 +93,9 @@ public class ChatRctService {
@Path("/distributor/{distributorId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getDistributorById(
@PathParam("distributorId") String distributorId,
@PathParam("distributorId") Integer distributorId,
@QueryParam("itemId") String itemId,
@QueryParam("produitId") String produitId) {
@QueryParam("produitId") Integer produitId) {
if (distributorId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"distributorId parameter is required\"}").build();
@ -101,9 +114,9 @@ public class ChatRctService {
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(call)) {
// Set input parameters
callableStatement.setString(1, distributorId);
callableStatement.setInt(1, distributorId);
callableStatement.setString(2, itemId);
callableStatement.setString(3, produitId);
callableStatement.setInt(3, produitId);
// Set output parameters
callableStatement.registerOutParameter(4, Types.CLOB);
@ -115,8 +128,11 @@ public class ChatRctService {
Clob resultClob = callableStatement.getClob(4);
String result = resultClob.getSubString(1, (int) resultClob.length());
// Convert Unicode representations to emojis
String resultWithEmojis = convertUnicodeStrsToEmojis(result);
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(result);
String jsonResponse = objectMapper.writeValueAsString(resultWithEmojis);
return Response.ok(jsonResponse).build();
}
@ -128,5 +144,331 @@ public class ChatRctService {
e.printStackTrace(); // Gérer les exceptions correctement dans un environnement de production
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("{\"error\":\"Error processing JSON\"}").build();
}
}
}
@GET
@Path("/store/{storeId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getStoreById(
@PathParam("storeId") Integer storeId,
@QueryParam("distributorId") Integer distributorId,
@QueryParam("itemId") String itemId,
@QueryParam("produitId") Integer produitId) {
if (storeId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"storeId parameter is required\"}").build();
}
if (distributorId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"distributorId parameter is required\"}").build();
}
if (itemId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"itemId parameter is required\"}").build();
}
String ip = "";
String enseigne = "";
int vendable = -1; // error by default
int gerable = -1; // error by default
DriverManager.setLoginTimeout(5); // Set timeout to 5 seconds
try (DatabaseConnectDOTSOFT databaseConnection = new DatabaseConnectDOTSOFT("com02")) {
String ipQuery = "SELECT hsc.ip FROM com02.HOTLINE_STRUCTURE_CAISSE hsc WHERE hsc.ID_STRUCTURE = ? AND hsc.ID_CAISSE = 20";
logger.info(ipQuery);
PreparedStatement ipStatement = databaseConnection.getConnection().prepareStatement(ipQuery);
ipStatement.setInt(1, storeId);
ResultSet ipResultSet = ipStatement.executeQuery();
if (ipResultSet.next()) {
ip = ipResultSet.getString("ip");
}
String enseigneQuery = "SELECT xs.enseigne FROM omni.xst_structure xs WHERE xs.ID_STRUCTURE = ?";
logger.info(enseigneQuery);
PreparedStatement enseigneStatement = databaseConnection.getConnection().prepareStatement(enseigneQuery);
enseigneStatement.setInt(1, storeId);
ResultSet enseigneResultSet = enseigneStatement.executeQuery();
if (enseigneResultSet.next()) {
enseigne = enseigneResultSet.getString("enseigne");
}
} catch (SQLException e) {
e.printStackTrace();
}
logger.info("Try to connect on IP :" + ip);
// if Ip address is not null and enseigne is not null
if (ip.length() > 0 && enseigne.length() > 0) {
try (DatabaseConnectXSTORE databaseConnection = new DatabaseConnectXSTORE(ip,"dtv")) {
String itemQuery = "SELECT COUNT(*) as gerable " +
"FROM dtv.ITM_ITEM " +
"WHERE ORGANIZATION_ID = 1 AND ITEM_ID = ?";
logger.info(itemQuery);
try (PreparedStatement itemStatement = databaseConnection.getConnection().prepareStatement(itemQuery)) {
itemStatement.setString(1, itemId);
ResultSet itemResultSet = itemStatement.executeQuery();
if (itemResultSet.next()) {
if (itemResultSet.getInt("gerable") > 0)
gerable = 1;
else
gerable = 0;
}
}
String optionsQuery = "SELECT COUNT(*) as vendable " +
"FROM dtv.ITM_ITEM_OPTIONS " +
"WHERE ORGANIZATION_ID = 1 AND ITEM_ID = ? AND LEVEL_CODE = 'ENSEIGNE' AND LEVEL_VALUE = ? AND ITEM_AVAILABILITY_CODE = 'AVAILABLE'";
logger.info(optionsQuery);
try (PreparedStatement optionsStatement = databaseConnection.getConnection().prepareStatement(optionsQuery)) {
optionsStatement.setString(1, itemId);
optionsStatement.setString(2, enseigne);
ResultSet optionsResultSet = optionsStatement.executeQuery();
if (optionsResultSet.next()) {
if (optionsResultSet.getInt("vendable") > 0)
vendable = 1;
else
vendable = 0;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (vendable == -1) {
logger.info("Unable to determine vendable status for store " + storeId);
}
try (DatabaseConnectDOTSOFT databaseConnection = new DatabaseConnectDOTSOFT("omni")) {
String call = "{ call fbe_hdpos.chatrct_prompt_store(?,?,?,?,?,?,?,?) }";
logger.info(call);
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(call)) {
// Set input parameters
callableStatement.setInt(1, storeId);
callableStatement.setInt(2, distributorId);
callableStatement.setString(3, itemId);
callableStatement.setInt(4, produitId);
callableStatement.setString(5, enseigne);
callableStatement.setInt(6, gerable);
callableStatement.setInt(7, vendable);
// Set output parameters
callableStatement.registerOutParameter(8, Types.CLOB);
// Execute the stored procedure
callableStatement.execute();
// Retrieve results
Clob resultClob = callableStatement.getClob(8);
String result = resultClob.getSubString(1, (int) resultClob.length());
// Convert Unicode representations to emojis
String resultWithEmojis = convertUnicodeStrsToEmojis(result);
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(resultWithEmojis);
return Response.ok(jsonResponse).build();
}
} catch (SQLException e) {
e.printStackTrace();
String errorResponse = "{\"error\":\"" + e.getMessage() + "\"}";
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse).build();
} catch (JsonProcessingException e) {
e.printStackTrace(); // Gérer les exceptions correctement dans un environnement de production
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("{\"error\":\"Error processing JSON\"}").build();
}
}
@PUT
@Path("/rct/forceCache")
@Consumes(MediaType.APPLICATION_JSON)
public Response putRctForceCache(Map<String, String> request) {
String itemId = request.get("itemId");
String comment = request.get("comment");
if (itemId == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"itemId parameter is required\"}").build();
}
if (comment == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"comment parameter is required\"}").build();
}
try (DatabaseConnectDOTSOFT databaseConnection = new DatabaseConnectDOTSOFT("omni")) {
String enableOutput = "begin dbms_output.enable; end;";
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(enableOutput)) {
callableStatement.execute();
}
String call = "{ call p_xsto_itm_force_cache(?,?) }";
logger.info(call);
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(call)) {
// Set input parameters
callableStatement.setString(1, itemId);
callableStatement.setString(2, comment);
// Execute the stored procedure
callableStatement.execute();
Map<String, String> result = new HashMap<>();
// Retrieve DBMS_OUTPUT
String getOutput = "begin dbms_output.get_line(?, ?); end;";
try (CallableStatement outputCallableStatement = databaseConnection.getConnection().prepareCall(getOutput)) {
outputCallableStatement.registerOutParameter(1, Types.VARCHAR);
outputCallableStatement.registerOutParameter(2, Types.INTEGER);
StringBuilder output = new StringBuilder();
int status = 0;
do {
outputCallableStatement.execute();
status = outputCallableStatement.getInt(2);
if (status == 0) {
output.append(outputCallableStatement.getString(1));
}
} while (status == 0);
// Add DBMS_OUTPUT to your result
result.put("output", output.toString());
}
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(result);
return Response.ok(jsonResponse).build();
}
} catch (SQLException e) {
e.printStackTrace();
String errorResponse = "{\"error\":\"" + e.getMessage() + "\"}";
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse).build();
} catch (JsonProcessingException e) {
e.printStackTrace(); // Gérer les exceptions correctement dans un environnement de production
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("{\"error\":\"Error processing JSON\"}").build();
}
}
@PUT
@Path("/rct/forceException")
@Consumes(MediaType.APPLICATION_JSON)
public Response putRctForceException(Map<String, String> request) {
String id_produit_str = request.get("id_produit");
String id_distrib_str = request.get("id_distrib");
String fdate = request.get("fdate");
String forcer_cache_str = request.get("forcer_cache");
String modul_trait = request.get("modul_trait");
Long id_produit = Optional.ofNullable(id_produit_str)
.map(Long::parseLong)
.orElseThrow(() -> new BadRequestException("id_produit parameter is required"));
Integer id_distrib = Optional.ofNullable(id_distrib_str)
.map(Integer::parseInt)
.orElseThrow(() -> new BadRequestException("id_distrib parameter is required"));
Integer forcer_cache = Optional.ofNullable(forcer_cache_str)
.map(Integer::parseInt)
.orElseThrow(() -> new BadRequestException("forcer_cache parameter is required"));
if (fdate == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"fdate parameter is required\"}").build();
}
if (modul_trait == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"modul_trait parameter is required\"}").build();
}
try (DatabaseConnectDOTSOFT databaseConnection = new DatabaseConnectDOTSOFT("omni")) {
String enableOutput = "begin dbms_output.enable; end;";
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(enableOutput)) {
callableStatement.execute();
}
String call = "{ call p_xsto_itm_force_exception(?,?,?,?,?) }";
logger.info(call);
try (CallableStatement callableStatement = databaseConnection.getConnection().prepareCall(call)) {
// Set input parameters
callableStatement.setLong(1, id_produit);
callableStatement.setInt(2, id_distrib);
callableStatement.setString(3, fdate);
callableStatement.setInt(4, forcer_cache);
callableStatement.setString(5, modul_trait);
// Execute the stored procedure
callableStatement.execute();
Map<String, String> result = new HashMap<>();
// Retrieve DBMS_OUTPUT
String getOutput = "begin dbms_output.get_line(?, ?); end;";
try (CallableStatement outputCallableStatement = databaseConnection.getConnection().prepareCall(getOutput)) {
outputCallableStatement.registerOutParameter(1, Types.VARCHAR);
outputCallableStatement.registerOutParameter(2, Types.INTEGER);
StringBuilder output = new StringBuilder();
int status = 0;
do {
outputCallableStatement.execute();
status = outputCallableStatement.getInt(2);
if (status == 0) {
output.append(outputCallableStatement.getString(1));
}
} while (status == 0);
// Add DBMS_OUTPUT to your result
result.put("output", output.toString());
}
ObjectMapper objectMapper = new ObjectMapper();
String jsonResponse = objectMapper.writeValueAsString(result);
return Response.ok(jsonResponse).build();
}
} catch (SQLException e) {
e.printStackTrace();
String errorResponse = "{\"error\":\"" + e.getMessage() + "\"}";
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponse).build();
} catch (JsonProcessingException e) {
e.printStackTrace(); // Gérer les exceptions correctement dans un environnement de production
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("{\"error\":\"Error processing JSON\"}").build();
}
}
public static String convertUnicodeStrsToEmojis(String str) {
Pattern pattern = Pattern.compile("U\\+[0-9A-Fa-f]+");
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String unicodeStr = matcher.group();
String emoji = convertUnicodeStrToEmoji(unicodeStr);
matcher.appendReplacement(sb, emoji);
}
matcher.appendTail(sb);
return sb.toString();
}
public static String convertUnicodeStrToEmoji(String unicodeStr) {
String[] parts = unicodeStr.split("\\+");
int unicodeInt = Integer.parseInt(parts[1], 16);
return new String(Character.toChars(unicodeInt));
}
}

View File

@ -179,12 +179,12 @@ public class StoreService {
" AND hsc2.id_caisse BETWEEN 20 AND 39) AS caisses," +
" REPLACE(REPLACE(TRIM(st.adresse1), chr(10), ''), chr(13), '') AS adresse," +
" axs.date_stock as date_migration" +
" FROM COM02.structure st" +
" FROM com02.STRUCTURE st" +
" JOIN omni.ASPD_XSTO_STRUCTURE axs ON st.ID_STRUCTURE = axs.ID_STRUCTURE" +
" JOIN com02.PARAM_PAYS pp ON pp.id_pays = st.id_pays" +
" LEFT OUTER JOIN mobretail.mp_etab_param metabp ON metabp.id_etab = st.id_structure" +
" LEFT OUTER JOIN mobretail.mr_photo mpprinc ON mpprinc.id_photo = metabp.id_photo_principale" +
" LEFT OUTER JOIN omni.ASPD_XSTO_STRUCTURE axs ON st.ID_STRUCTURE = axs.ID_STRUCTURE" +
" WHERE axs.date_stock is not null AND st.ID_NIVEAU=4 AND st.STATUT=2 AND st.id_canal_distribution = 1 and st.magasin_demo = 0" +
" WHERE axs.date_stock is not null AND st.id_niveau=4 AND st.statut=2 AND st.id_canal_distribution = 1" +
" ORDER BY st.id_structure";
logger.info(query);